| 1 | import torch |
| 2 | from _common import load_kospi |
| 3 | from rnn import VanillaRNN |
| 4 | from torch import nn |
| 5 | |
| 6 | torch.manual_seed(0) |
| 7 | |
| 8 | data = load_kospi() |
| 9 | x = data.x_train[:3] # 학습 샘플 3개: [배치 3, 길이 5, 특징 4] |
| 10 | |
| 11 | |
| 12 | def n_params(module): |
| 13 | return sum(p.numel() for p in module.parameters()) |
| 14 | |
| 15 | |
| 16 | print("1) model(x): 윈도 3개를 한 번에 넣는다") |
| 17 | model = VanillaRNN(input_size=4, hidden_size=8, num_layers=1) |
| 18 | with torch.no_grad(): |
| 19 | out = model(x) |
| 20 | print(f" 입력 x {tuple(x.shape)} ← [배치, 시퀀스 길이, 특징 수]") |
| 21 | print(f" 출력 {tuple(out.shape)} ← [배치, 시퀀스 길이, 은닉 크기]") |
| 22 | print(" → 날마다 은닉 상태 8칸이 하나씩 나온다. 5일이므로 5개다") |
| 23 | print() |
| 24 | |
| 25 | print("2) 5단계의 한 칸 계산을 5번 되풀이한 것과 같은가") |
| 26 | W, U, b_w, b_u = (p.detach() for p in model.rnn.parameters()) |
| 27 | h = torch.zeros(3, 8) # 샘플 3개의 은닉 상태. 0에서 시작 |
| 28 | steps = [] |
| 29 | for t in range(5): |
| 30 | x_t = x[:, t] # t번째 날: [배치 3, 특징 4] |
| 31 | h = torch.tanh(x_t @ W.T + b_w + h @ U.T + b_u) # 같은 W, U 를 매번 다시 쓴다 |
| 32 | steps.append(h) |
| 33 | print(f" t={t + 1}: x_t {tuple(x_t.shape)} + 이전 h {tuple(h.shape)} → 새 h {tuple(h.shape)}") |
| 34 | by_hand = torch.stack(steps, dim=1) # [배치, 시퀀스 길이, 은닉 크기] |
| 35 | print( |
| 36 | f" 손으로 펼친 결과 {tuple(by_hand.shape)} 와 model(x) 의 차이: {(by_hand - out).abs().max():.1e}" |
| 37 | ) |
| 38 | print() |
| 39 | |
| 40 | print("3) 길이가 달라져도 파라미터는 그대로다") |
| 41 | with torch.no_grad(): |
| 42 | long_out = model(torch.randn(3, 50, 4)) |
| 43 | print(f" 길이 5 → 출력 {tuple(out.shape)}, 파라미터 {n_params(model)}개") |
| 44 | print(f" 길이 50 → 출력 {tuple(long_out.shape)}, 파라미터 {n_params(model)}개") |
| 45 | print(" → 모든 시점이 같은 W, U 를 쓴다. 그래서 길이가 얼마든 같은 모델에 넣을 수 있다") |
| 46 | print() |
| 47 | |
| 48 | print("4) nn.RNN 이 돌려주는 두 가지: out 과 hn") |
| 49 | with torch.no_grad(): |
| 50 | out, hn = model.rnn(x) |
| 51 | print(f" out {tuple(out.shape)} ← [배치, 시퀀스 길이, 은닉 크기] 모든 시점의 은닉 상태") |
| 52 | print(f" hn {tuple(hn.shape)} ← [층 수, 배치, 은닉 크기] 마지막 시점의 은닉 상태") |
| 53 | print(f" out[:, -1] 과 hn[0] 의 차이: {(out[:, -1] - hn[0]).abs().max():.1e}") |
| 54 | print(" → 층이 하나면 hn 은 out 의 마지막 시점을 따로 꺼낸 것이다") |
| 55 | print(" → 축의 순서가 다르다. out 은 배치가 맨 앞이고, hn 은 층 수가 맨 앞이다") |
| 56 | print() |
| 57 | |
| 58 | print("5) 층을 2개 쌓으면: VanillaRNN(4, 8, num_layers=2)") |
| 59 | model2 = VanillaRNN(input_size=4, hidden_size=8, num_layers=2) |
| 60 | for name, p in model2.rnn.named_parameters(): |
| 61 | print(f" {name:<13} {tuple(p.shape)}") |
| 62 | print(f" 파라미터 수: {n_params(model2)} = 1층 112 + 2층 (8×8 + 8×8 + 8 + 8)") |
| 63 | print( |
| 64 | " → 2층의 weight_ih_l1 은 (8, 8) 이다. 2층의 입력은 특징 4개가 아니라 1층의 은닉 상태 8칸이다" |
| 65 | ) |
| 66 | with torch.no_grad(): |
| 67 | out2, hn2 = model2.rnn(x) |
| 68 | print(f" out {tuple(out2.shape)} ← 층을 쌓아도 그대로다. 맨 위(2층)의 출력만 나온다") |
| 69 | print(f" hn {tuple(hn2.shape)} ← 층마다 하나씩이라 맨 앞이 2가 됐다") |
| 70 | print(f" out[:, -1] 과 hn[-1](2층) 의 차이: {(out2[:, -1] - hn2[-1]).abs().max():.1e}") |
| 71 | print( |
| 72 | f" out[:, -1] 과 hn[0](1층) 의 차이: {(out2[:, -1] - hn2[0]).abs().max():.3f} ← 1층의 것은 out 에 없다" |
| 73 | ) |
| 74 | print() |
| 75 | |
| 76 | print("6) batch_first=True 를 빼먹으면") |
| 77 | torch.manual_seed(1) |
| 78 | right = nn.RNN(4, 8, batch_first=True) |
| 79 | wrong = nn.RNN(4, 8) # 기본값 batch_first=False: [시퀀스 길이, 배치, 특징 수] 로 읽는다 |
| 80 | wrong.load_state_dict(right.state_dict()) # 가중치는 똑같이 |
| 81 | with torch.no_grad(): |
| 82 | out_right, hn_right = right(x) |
| 83 | out_wrong, hn_wrong = wrong(x) |
| 84 | out_fixed, _ = wrong(x.transpose(0, 1)) # 축을 [길이, 배치, 특징] 으로 바꿔서 넣기 |
| 85 | print(f" 같은 x {tuple(x.shape)} 를 넣었을 때") |
| 86 | print( |
| 87 | f" batch_first=True : out {tuple(out_right.shape)}, hn {tuple(hn_right.shape)} ← 샘플 3개, 5일씩" |
| 88 | ) |
| 89 | print( |
| 90 | f" batch_first=False: out {tuple(out_wrong.shape)}, hn {tuple(hn_wrong.shape)} ← 샘플 5개, 3일씩으로 읽었다" |
| 91 | ) |
| 92 | print(f" 두 out 의 차이의 최댓값: {(out_right - out_wrong).abs().max():.3f}") |
| 93 | print(" → 오류가 나지 않고 out 의 모양도 같다. 값만 다르다. hn 의 모양을 봐야 알 수 있다") |
| 94 | print( |
| 95 | f" x.transpose(0, 1) {tuple(x.transpose(0, 1).shape)} 로 넣으면 out {tuple(out_fixed.shape)}, " |
| 96 | f"다시 돌려놓고 비교한 차이: {(out_fixed.transpose(0, 1) - out_right).abs().max():.1e}" |
| 97 | ) |
| 98 | print() |
| 99 | |
| 100 | print("7) h0 의 모양은 batch_first 와 상관없이 [층 수, 배치, 은닉 크기] 다") |
| 101 | with torch.no_grad(): |
| 102 | out_default, _ = model2.rnn(x) # h0 생략 |
| 103 | out_zeros, _ = model2.rnn(x, torch.zeros(2, 3, 8)) # [층 수 2, 배치 3, 은닉 8] |
| 104 | print( |
| 105 | f" h0 를 생략한 결과와 torch.zeros(2, 3, 8) 을 넣은 결과의 차이: {(out_default - out_zeros).abs().max():.1e}" |
| 106 | ) |
| 107 | try: |
| 108 | model2.rnn(x, torch.zeros(3, 2, 8)) # 배치를 앞에 둔 잘못된 모양 |
| 109 | except RuntimeError as e: |
| 110 | print(f" torch.zeros(3, 2, 8) 을 넣으면 오류: {e}") |
| 111 | print( |
| 112 | f" forward 안의 h0: torch.zeros(self.num_layers, x.size(0), self.hidden_size) = (2, {x.size(0)}, 8)" |
| 113 | ) |