| 1 | import torch |
| 2 | from maml import K, Regressor, loss_with_params, sample_points, sample_task |
| 3 | from torch.func import functional_call |
| 4 | |
| 5 | torch.manual_seed(0) |
| 6 | torch.set_num_threads(1) # 스레드 수에 따라 소수점 끝자리가 달라지지 않게 고정한다 |
| 7 | |
| 8 | model = Regressor() |
| 9 | a, b = sample_task() |
| 10 | x, y = sample_points(a, b, K) |
| 11 | |
| 12 | |
| 13 | def snapshot(model): |
| 14 | return [p.detach().clone() for p in model.parameters()] |
| 15 | |
| 16 | |
| 17 | def max_change(model, before): |
| 18 | return max((p - q).abs().max().item() for p, q in zip(model.parameters(), before)) |
| 19 | |
| 20 | |
| 21 | print("1) 모델의 파라미터를 {이름: 텐서} 딕셔너리로 꺼내기") |
| 22 | theta = dict(model.named_parameters()) |
| 23 | for name, p in theta.items(): |
| 24 | print(f" {name:<13} {tuple(p.shape)}") |
| 25 | print( |
| 26 | " → 복사본이 아니다. 모델 안에 있는 바로 그 텐서를 이름으로 가리킬 뿐이다:", |
| 27 | theta["net.0.weight"] is model.net[0].weight, |
| 28 | ) |
| 29 | print() |
| 30 | |
| 31 | print("2) functional_call(model, 딕셔너리, (x,)): 딕셔너리의 값으로 순전파") |
| 32 | out_model = model(x) |
| 33 | out_func = functional_call(model, theta, (x,)) |
| 34 | print( |
| 35 | f" 모델 자신의 파라미터를 넘기면 model(x) 와 같다. 최대 차이: {(out_model - out_func).abs().max().item():.1e}" |
| 36 | ) |
| 37 | print() |
| 38 | |
| 39 | print("3) 다른 값을 넘기면 그 값으로 계산한다. 모델은 구조(층의 순서)만 빌려준다") |
| 40 | other = Regressor() # 초깃값이 다른 두 번째 모델 |
| 41 | theta_other = dict(other.named_parameters()) |
| 42 | before = snapshot(model) |
| 43 | out_swapped = functional_call(model, theta_other, (x,)) |
| 44 | print( |
| 45 | " model(x) :", |
| 46 | " ".join(f"{v:7.4f}" for v in out_model.flatten().tolist()), |
| 47 | ) |
| 48 | print( |
| 49 | " other(x) :", |
| 50 | " ".join(f"{v:7.4f}" for v in other(x).flatten().tolist()), |
| 51 | ) |
| 52 | print( |
| 53 | " functional_call(model, other의 값, x) :", |
| 54 | " ".join(f"{v:7.4f}" for v in out_swapped.flatten().tolist()), |
| 55 | ) |
| 56 | print(f" 그 뒤 model 의 가중치가 바뀐 정도: {max_change(model, before):.1e} ← 그대로다") |
| 57 | print() |
| 58 | |
| 59 | print("4) 이번 단계의 함수: loss_with_params(model, params, x, y)") |
| 60 | print(f" model 의 값으로 잰 MSE: {loss_with_params(model, theta, x, y).item():.4f}") |
| 61 | print(f" other 의 값으로 잰 MSE: {loss_with_params(model, theta_other, x, y).item():.4f}") |
| 62 | print() |
| 63 | |
| 64 | print("5) 경사하강 한 걸음을 두 가지 방법으로 (학습률 0.01)") |
| 65 | loss = loss_with_params(model, theta, x, y) |
| 66 | grads = torch.autograd.grad(loss, list(theta.values())) |
| 67 | # (가) 새 딕셔너리를 만든다. 모델은 건드리지 않는다 |
| 68 | theta_new = {name: p - 0.01 * g for (name, p), g in zip(theta.items(), grads)} |
| 69 | out_dict = functional_call(model, theta_new, (x,)) |
| 70 | changed_a = max_change(model, before) |
| 71 | # (나) 옵티마이저로 모델을 직접 고친다 |
| 72 | optimizer = torch.optim.SGD(model.parameters(), lr=0.01) |
| 73 | optimizer.zero_grad() |
| 74 | loss_with_params(model, theta, x, y).backward() |
| 75 | optimizer.step() |
| 76 | changed_b = max_change(model, before) |
| 77 | w_new, w_model = theta_new["net.0.weight"], model.net[0].weight |
| 78 | print(" (가) 새 딕셔너리 (나) optimizer.step()") |
| 79 | print(f" 모델 가중치가 바뀐 정도 {changed_a:<24.6f}{changed_b:.6f}") |
| 80 | print(" 한 걸음 뒤의 값이 있는 곳 theta_new model 안 (원래 값을 덮어씀)") |
| 81 | print(f" 그 값의 is_leaf {w_new.is_leaf!s:<24}{w_model.is_leaf}") |
| 82 | print(f" 그 값의 grad_fn {type(w_new.grad_fn).__name__:<24}{w_model.grad_fn}") |
| 83 | print( |
| 84 | f" 두 방법의 출력 차이(최대): {(out_dict - model(x)).abs().max().item():.1e} ← 계산 결과는 같다" |
| 85 | ) |
| 86 | print( |
| 87 | " → (나)는 출발점이 사라지고, 새 값이 출발점에서 어떻게 만들어졌는지(grad_fn)도 남지 않는다" |
| 88 | ) |
| 89 | print( |
| 90 | " → (가)는 출발점이 모델에 그대로 있고, 새 값은 '출발점 - 0.01 × 기울기' 라는 뺄셈(SubBackward0)으로 이어져 있다" |
| 91 | ) |