| 1 | import torch |
| 2 | from torch import nn |
| 3 | from utils import PINN, gradients |
| 4 | |
| 5 | torch.manual_seed(0) |
| 6 | |
| 7 | print("1) 답을 아는 함수로 확인: f(t, x, y) = 3t + sin(x)·y²") |
| 8 | txy = torch.rand(5, 3, dtype=torch.float64).requires_grad_(True) # 점 5개. 열 순서 (t, x, y) |
| 9 | t, x, y = txy.unbind(dim=1) |
| 10 | f = 3 * t + torch.sin(x) * y**2 |
| 11 | df = gradients(f, txy) |
| 12 | print( |
| 13 | f" f {tuple(f.shape)}, txy {tuple(txy.shape)} → gradients(f, txy) {tuple(df.shape)} ← 열 순서 (∂f/∂t, ∂f/∂x, ∂f/∂y)" |
| 14 | ) |
| 15 | exact = torch.stack([torch.full_like(t, 3.0), torch.cos(x) * y**2, 2 * torch.sin(x) * y], dim=1) |
| 16 | print(" 자동 미분 (∂t, ∂x, ∂y) 손으로 미분한 식 (3, cos(x)·y², 2·sin(x)·y)") |
| 17 | for a, b in zip(df.tolist(), exact.tolist()): |
| 18 | print(f" {a[0]:8.5f} {a[1]:8.5f} {a[2]:8.5f} {b[0]:8.5f} {b[1]:8.5f} {b[2]:8.5f}") |
| 19 | print(f" 가장 큰 차이: {(df - exact).abs().max().item():.1e}") |
| 20 | print() |
| 21 | |
| 22 | print("2) 합을 미분해도 행별 미분이 되는 이유: 한 행의 출력은 그 행의 입력만 본다") |
| 23 | row0 = torch.autograd.grad(f[0], txy, retain_graph=True)[0] |
| 24 | print( |
| 25 | f" f[0] 하나만 미분한 결과에서 0 이 아닌 행: {row0.abs().sum(dim=1).nonzero().flatten().tolist()} ← 0번 행뿐" |
| 26 | ) |
| 27 | print(f" 그 0번 행이 gradients(f, txy)[0] 과 같은가: {torch.equal(row0[0], df[0])}") |
| 28 | print() |
| 29 | |
| 30 | print("3) 한 번 더 미분하기: ∂²f/∂x² = −sin(x)·y²") |
| 31 | f_x = df[:, 1] |
| 32 | f_xx = gradients(f_x, txy)[:, 1] |
| 33 | print( |
| 34 | f" df.requires_grad = {df.requires_grad}, grad_fn = {type(df.grad_fn).__name__} ← create_graph=True 라서 미분 결과에도 그래프가 붙는다" |
| 35 | ) |
| 36 | print(f" 자동 미분 : {[round(v, 5) for v in f_xx.tolist()]}") |
| 37 | print(f" 손으로 : {[round(v, 5) for v in (-torch.sin(x) * y**2).tolist()]}") |
| 38 | plain = torch.autograd.grad(f.sum(), txy, retain_graph=True)[0] # create_graph 를 주지 않으면 |
| 39 | print(f" create_graph 없이 구한 미분: requires_grad = {plain.requires_grad} ← 그래프가 없다") |
| 40 | try: |
| 41 | torch.autograd.grad(plain[:, 1].sum(), txy) |
| 42 | except RuntimeError as e: |
| 43 | print(f" 그것을 다시 미분하면: RuntimeError: {str(e)[:60]}...") |
| 44 | print() |
| 45 | |
| 46 | print("4) 신경망에 적용: 출력 c 를 입력 좌표로 미분한다") |
| 47 | model = PINN().double() |
| 48 | txy = torch.tensor([[1.0, 3.0, 0.5], [2.0, 4.0, -1.0]], dtype=torch.float64, requires_grad=True) |
| 49 | c = model(txy)[:, 0] |
| 50 | c_t, c_x, c_y = gradients(c, txy).unbind(dim=1) |
| 51 | print( |
| 52 | f" c {tuple(c.shape)} → c_t {tuple(c_t.shape)}, c_x {tuple(c_x.shape)}, c_y {tuple(c_y.shape)}" |
| 53 | ) |
| 54 | h = 1e-5 |
| 55 | step = torch.tensor([0.0, h, 0.0], dtype=torch.float64) |
| 56 | with torch.no_grad(): |
| 57 | numeric = (model(txy + step)[:, 0] - model(txy - step)[:, 0]) / (2 * h) # 중앙 차분 |
| 58 | print(f" 자동 미분 c_x : {[f'{v:.8f}' for v in c_x.tolist()]}") |
| 59 | print(f" x 를 ±{h} 흔들어 잰 값 : {[f'{v:.8f}' for v in numeric.tolist()]}") |
| 60 | print(" → 'x 를 조금 옮기면 c 가 얼마나 변하나'를 그 점에서 정확히 계산한 값이다") |
| 61 | print() |
| 62 | |
| 63 | print("5) 가중치로 미분하는 것과 무엇이 다른가") |
| 64 | weight = model.net[0].parametrizations.weight.original1 |
| 65 | print( |
| 66 | f" 입력으로 미분 : gradients(c, txy) {tuple(gradients(c, txy).shape)} ← 점마다 3개. 손실을 '만드는' 재료" |
| 67 | ) |
| 68 | print(f" 가중치로 미분 : weight.grad 는 아직 {weight.grad} ← backward() 를 부른 적이 없다") |
| 69 | loss = (c_x**2).mean() # c_x 로 만든 아무 손실 |
| 70 | loss.backward() |
| 71 | print( |
| 72 | f" c_x 로 손실을 만들어 backward() 하면 weight.grad {tuple(weight.grad.shape)}, 크기 {weight.grad.norm().item():.2e}" |
| 73 | ) |
| 74 | print( |
| 75 | " → c_x 에 그래프가 남아 있어서, 'c_x 를 줄이려면 가중치를 어느 쪽으로'까지 계산된다. 이것이 미분의 미분이다" |
| 76 | ) |
| 77 | print() |
| 78 | |
| 79 | print("6) 활성 함수가 ReLU 였다면: 두 번 미분하면 0 이 된다") |
| 80 | for name, act in (("ReLU", nn.ReLU()), ("SiLU", nn.SiLU())): |
| 81 | torch.manual_seed(0) |
| 82 | mlp = nn.Sequential(nn.Linear(3, 50), act, nn.Linear(50, 50), act, nn.Linear(50, 1)).double() |
| 83 | pts = torch.rand(1000, 3, dtype=torch.float64).requires_grad_(True) |
| 84 | out = mlp(pts)[:, 0] |
| 85 | d1 = gradients(out, pts)[:, 1] |
| 86 | d2 = gradients(d1, pts)[:, 1] |
| 87 | print( |
| 88 | f" {name}: 1차 미분 크기 평균 {d1.abs().mean().item():.4f}, 2차 미분 크기 평균 {d2.abs().mean().item():.4f}" |
| 89 | ) |
| 90 | print(" → ReLU 는 꺾인 직선이라 구간마다 기울기가 상수다. 확산 항(2차 미분)이 통째로 사라진다") |