| 1 | """12.2 은닉 유체 메카니즘(HFM, Hidden Fluid Mechanics) - 학습 |
| 2 | |
| 3 | 원기둥 뒤로 흐르는 유동에서 "농도 c 만 관측"하고, 나비에-스토크스 방정식을 손실에 넣어 |
| 4 | 관측하지 않은 속도 (u, v) 와 압력 p 까지 추정하는 물리 정보 신경망(PINN)을 학습한다. |
| 5 | 손실 = 농도 데이터 오차 + 지배 방정식 잔차. u, v, p 의 정답은 학습에 쓰지 않는다. |
| 6 | |
| 7 | 실행: uv run python ch12_scientific/hfm/train.py |
| 8 | uv run python ch12_scientific/hfm/train.py --iterations 5000 --resume (이어서 학습) |
| 9 | """ |
| 10 | |
| 11 | # %% |
| 12 | import time |
| 13 | |
| 14 | import matplotlib.pyplot as plt |
| 15 | import torch |
| 16 | from mat_to_numpy import snapshot |
| 17 | from utils import PINN, field_errors, navier_stokes_2d |
| 18 | |
| 19 | from ptintro import save_fig |
| 20 | |
| 21 | |
| 22 | # %% |
| 23 | def build_model(txy_data, device, resume_path=None): |
| 24 | """PINN 을 만든다. 입력 정규화 통계는 학습 데이터에서 구해 모델 안(buffer)에 넣어 둔다.""" |
| 25 | model = PINN(mean=txy_data.mean(dim=0), std=txy_data.std(dim=0)).to(device) |
| 26 | if resume_path is not None: |
| 27 | model.load_state_dict(torch.load(resume_path, map_location=device, weights_only=True)) |
| 28 | print(f"가중치를 불러왔다: {resume_path}") |
| 29 | return model |
| 30 | |
| 31 | |
| 32 | def random_batch(*tensors, batch_size): |
| 33 | """같은 길이의 텐서들에서 같은 무작위 행을 batch_size 개 뽑는다.""" |
| 34 | idx = torch.randint(len(tensors[0]), (batch_size,), device=tensors[0].device) |
| 35 | return [t[idx] for t in tensors] |
| 36 | |
| 37 | |
| 38 | # %% |
| 39 | def data_loss(model, txy, c_true): |
| 40 | """데이터 손실: 관측한 농도와 예측한 농도(출력의 첫 열)의 평균제곱오차.""" |
| 41 | c_pred = model(txy)[:, 0:1] |
| 42 | return torch.mean((c_pred - c_true) ** 2) |
| 43 | |
| 44 | |
| 45 | def equation_loss(model, txy): |
| 46 | """방정식 손실: 나비에-스토크스 잔차 4개의 제곱 평균을 더한 값. 정답이 필요 없다.""" |
| 47 | txy = txy.requires_grad_(True) # 출력을 입력으로 미분해야 하므로 입력에 기울기 추적을 켠다 |
| 48 | residuals = navier_stokes_2d(model(txy), txy) |
| 49 | return sum(torch.mean(e**2) for e in residuals) |
| 50 | |
| 51 | |
| 52 | def train_step(model, optimizer, txy_data, c_data, txy_eqns, batch_size): |
| 53 | """학습 한 스텝: 두 손실을 더해 역전파한다.""" |
| 54 | model.train() |
| 55 | txy_d, c_d = random_batch(txy_data, c_data, batch_size=batch_size) |
| 56 | (txy_e,) = random_batch(txy_eqns, batch_size=batch_size) |
| 57 | |
| 58 | loss_d = data_loss(model, txy_d, c_d) |
| 59 | loss_e = equation_loss(model, txy_e) |
| 60 | loss = loss_d + loss_e |
| 61 | |
| 62 | optimizer.zero_grad() |
| 63 | loss.backward() # 입력에 대한 미분(2차까지)을 다시 가중치로 미분한다 |
| 64 | optimizer.step() |
| 65 | return loss_d.item(), loss_e.item() |
| 66 | |
| 67 | |
| 68 | # %% |
| 69 | def last_snapshot_errors(model, fields): |
| 70 | """마지막 시각 스냅숏에서 c, u, v, p 의 상대 오차를 잰다(u, v, p 는 학습에 쓰지 않은 값).""" |
| 71 | inputs, targets = snapshot(fields, -1) |
| 72 | errors, _ = field_errors(model, inputs, targets) |
| 73 | return " ".join(f"{name}: {value:.3f}" for name, value in errors.items()) |
| 74 | |
| 75 | |
| 76 | def train(model, txy_data, c_data, txy_eqns, iterations, batch_size, lr): |
| 77 | """학습 루프. 손실 기록 {"data": [...], "eqns": [...]} 을 돌려준다.""" |
| 78 | optimizer = torch.optim.Adam(model.parameters(), lr=lr) |
| 79 | history = {"data": [], "eqns": []} |
| 80 | log_every = max(1, iterations // 10) |
| 81 | start = time.time() |
| 82 | |
| 83 | for it in range(1, iterations + 1): |
| 84 | loss_d, loss_e = train_step(model, optimizer, txy_data, c_data, txy_eqns, batch_size) |
| 85 | history["data"].append(loss_d) |
| 86 | history["eqns"].append(loss_e) |
| 87 | if it % log_every == 0 or it == 1: |
| 88 | print( |
| 89 | f"[{it:5d}/{iterations}] 손실 {loss_d + loss_e:.3e} " |
| 90 | f"(데이터 {loss_d:.3e}, 방정식 {loss_e:.3e}) {time.time() - start:.0f}초" |
| 91 | ) |
| 92 | return history |
| 93 | |
| 94 | |
| 95 | def plot_history(history): |
| 96 | plt.figure(figsize=(7, 4)) |
| 97 | plt.semilogy(history["data"], label="data loss (concentration)") |
| 98 | plt.semilogy(history["eqns"], label="equation loss (Navier-Stokes residual)") |
| 99 | plt.xlabel("iteration") |
| 100 | plt.legend() |
| 101 | save_fig("ch12", "hfm_train_loss") |