| 1 | import os |
| 2 | import re |
| 3 | import shutil |
| 4 | from pathlib import Path |
| 5 | |
| 6 | import torch |
| 7 | from resnet import ConvNet, PlainBlock, ResidualBlock, fit, make_loaders |
| 8 | from torch import nn |
| 9 | from torch.utils.data import DataLoader, TensorDataset |
| 10 | |
| 11 | torch.set_num_threads(1) # 스레드 수에 따라 소수점 끝자리가 달라지지 않게 고정한다 |
| 12 | device = torch.device("cpu") |
| 13 | here = Path(__file__).resolve().parent |
| 14 | |
| 15 | |
| 16 | def take(dataset, n): |
| 17 | xs, ys = zip(*[dataset[i] for i in range(n)]) |
| 18 | return TensorDataset(torch.stack(xs), torch.tensor(ys)) |
| 19 | |
| 20 | |
| 21 | def count(module): |
| 22 | return sum(p.numel() for p in module.parameters()) |
| 23 | |
| 24 | |
| 25 | torch.manual_seed(0) |
| 26 | x = torch.randn(4, 16, 16, 16) |
| 27 | |
| 28 | print("1) 모양이 바뀌는 블록: ResidualBlock(16, 32, stride=2)") |
| 29 | block = ResidualBlock(16, 32, stride=2) |
| 30 | print(f" 지름길: {block.shortcut}".replace("\n", "\n ")) |
| 31 | with torch.no_grad(): |
| 32 | f, s, out = block.conv_block(x), block.shortcut(x), block(x) |
| 33 | print(f" 입력 x {tuple(x.shape)}") |
| 34 | print(f" F(x) {tuple(f.shape)} ← 첫 합성곱의 stride 2가 크기를 절반으로, 채널을 32로") |
| 35 | print( |
| 36 | f" shortcut(x) {tuple(s.shape)} ← 1×1 합성곱도 stride 2, 출력 채널 32. F(x)와 같은 모양이 됐다" |
| 37 | ) |
| 38 | print(f" 출력 {tuple(out.shape)} ← 9단계에서 오류가 나던 덧셈이 된다") |
| 39 | same = ResidualBlock(16, 16) |
| 40 | print(f" 모양이 안 바뀌는 ResidualBlock(16, 16)의 지름길: {same.shortcut} ← 9단계 그대로") |
| 41 | print() |
| 42 | |
| 43 | print("2) 1×1 합성곱, stride 2가 하는 계산") |
| 44 | conv1x1 = block.shortcut[0] |
| 45 | with torch.no_grad(): |
| 46 | y = conv1x1(x) |
| 47 | manual = ( |
| 48 | conv1x1.weight[:, :, 0, 0] @ x[0, :, 6, 10] |
| 49 | ) # 가중치 (32, 16) × 입력의 (6, 10) 칸에 있는 채널 16개 |
| 50 | print( |
| 51 | f" 가중치 모양 {tuple(conv1x1.weight.shape)}: 이웃을 보지 않는다. 같은 자리의 채널 16개를 섞어 32개로 만든다" |
| 52 | ) |
| 53 | print(f" 출력 (3, 5) 칸의 앞 3채널: {' '.join(f'{v:+.4f}' for v in y[0, :3, 3, 5].tolist())}") |
| 54 | print( |
| 55 | f" 입력 (6, 10) 칸으로 직접 계산: {' '.join(f'{v:+.4f}' for v in manual[:3].tolist())} ← stride 2라 두 칸에 하나씩만 쓴다" |
| 56 | ) |
| 57 | print( |
| 58 | f" 파라미터: 1×1 합성곱 16 × 32 = {conv1x1.weight.numel()}, 배치 정규화 {count(block.shortcut[1])} → 지름길 {count(block.shortcut)}개" |
| 59 | ) |
| 60 | print(f" 블록 전체 {count(block):,}개 가운데 지름길이 {count(block.shortcut) / count(block):.1%}") |
| 61 | print() |
| 62 | |
| 63 | print("3) ConvNet에 넣으면: ConvNet(ResidualBlock, [2, 2, 2, 2], width=8)") |
| 64 | model = ConvNet(ResidualBlock, [2, 2, 2, 2], width=8) |
| 65 | print(" 블록 입력 채널 → 출력 채널 stride 지름길") |
| 66 | for name in ("layer1", "layer2", "layer3", "layer4"): |
| 67 | for i, blk in enumerate(getattr(model, name)): |
| 68 | conv = blk.conv_block[0] |
| 69 | kind = "x 그대로" if isinstance(blk.shortcut, nn.Identity) else "1×1 합성곱 + BN" |
| 70 | print( |
| 71 | f" {name}[{i}] {conv.in_channels:>3} → {conv.out_channels:<3} {conv.stride[0]} {kind}" |
| 72 | ) |
| 73 | plain = ConvNet(PlainBlock, [2, 2, 2, 2], width=8) |
| 74 | print( |
| 75 | f" 9단계에서 오류가 나던 순전파: 입력 (2, 3, 32, 32) → 출력 {tuple(model(torch.randn(2, 3, 32, 32)).shape)}" |
| 76 | ) |
| 77 | print( |
| 78 | f" 파라미터: PlainBlock으로 쌓으면 {count(plain):,}, ResidualBlock으로 쌓으면 {count(model):,} ← 차이 {count(model) - count(plain):,}개가 1×1 지름길 3개" |
| 79 | ) |
| 80 | print(" → 블록 8개 가운데 5개는 x를 그대로 더하고, 묶음이 바뀌는 3곳만 1×1 합성곱을 쓴다") |
| 81 | print() |
| 82 | |
| 83 | N_TRAIN, N_TEST, BATCH, EPOCHS = 1000, 500, 50, 4 |
| 84 | print( |
| 85 | f"4) 8단계의 실험을 블록만 바꿔 다시: 학습용 {N_TRAIN:,}장, 배치 {BATCH}, {EPOCHS}에폭({N_TRAIN // BATCH * EPOCHS}번 갱신), width 8, 같은 시드" |
| 86 | ) |
| 87 | full_train, full_test = make_loaders() |
| 88 | trainset, testset = take(full_train.dataset, N_TRAIN), take(full_test.dataset, N_TEST) |
| 89 | testloader = DataLoader(testset, batch_size=500) |
| 90 | results = {} |
| 91 | for num_blocks in ([1, 1, 1, 1], [4, 4, 4, 4]): |
| 92 | layers = 2 * sum(num_blocks) + 2 |
| 93 | torch.manual_seed(0) |
| 94 | model = ConvNet(ResidualBlock, num_blocks, width=8) |
| 95 | order = torch.Generator().manual_seed(0) |
| 96 | trainloader = DataLoader(trainset, batch_size=BATCH, shuffle=True, generator=order) |
| 97 | print( |
| 98 | f" {layers}층: fit(ConvNet(ResidualBlock, {num_blocks}, width=8), ...) 파라미터 {count(model):,}개" |
| 99 | ) |
| 100 | losses, accuracies = fit(model, trainloader, testloader, EPOCHS, device) |
| 101 | results[layers] = (losses[-1], accuracies[-1]) |
| 102 | # 8단계 demo가 찍은 표에서 PlainBlock의 결과를 읽어 온다 |
| 103 | step8 = (here.parent / "08-deeper-is-worse" / "output.txt").read_text() |
| 104 | plain_results = { |
| 105 | int(m[1]): (float(m[2]), float(m[3])) |
| 106 | for m in re.finditer(r"^\s+(10|34)\s+[\d,]+\s+([\d.]+)\s+([\d.]+)%$", step8, re.MULTILINE) |
| 107 | } |
| 108 | print() |
| 109 | print(" 마지막 에폭의 학습 손실 (괄호 안은 평가 정확도)") |
| 110 | print(" 층 수 PlainBlock (8단계) ResidualBlock") |
| 111 | for layers in (10, 34): |
| 112 | (pl, pa), (rl, ra) = plain_results[layers], results[layers] |
| 113 | print(f" {layers} {pl:.3f} ({pa:5.2f}%) {rl:.3f} ({ra:5.2f}%)") |
| 114 | print( |
| 115 | f" → PlainBlock은 깊게 쌓자 학습 손실이 올랐다 ({plain_results[10][0]:.3f} → {plain_results[34][0]:.3f}). ResidualBlock은 내려간다 ({results[10][0]:.3f} → {results[34][0]:.3f})" |
| 116 | ) |
| 117 | print( |
| 118 | " → 평가 정확도는 평가용 500장으로 잰 값이고 갱신도 80번뿐이라 들쭉날쭉하다. 여기서는 학습 손실을 본다" |
| 119 | ) |
| 120 | print() |
| 121 | |
| 122 | print("5) 학습 전 기울기의 크기: 맨 앞 합성곱 / 맨 뒤 Linear") |
| 123 | images, labels = next(iter(DataLoader(trainset, batch_size=128))) |
| 124 | print(" 층 수 PlainBlock ResidualBlock") |
| 125 | for num_blocks in ([1, 1, 1, 1], [4, 4, 4, 4], [7, 7, 7, 7]): |
| 126 | ratios = [] |
| 127 | for blk in (PlainBlock, ResidualBlock): |
| 128 | torch.manual_seed(0) |
| 129 | model = ConvNet(blk, num_blocks, width=8) |
| 130 | nn.functional.cross_entropy(model(images), labels).backward() |
| 131 | ratios.append((model.base[0].weight.grad.norm() / model.head[2].weight.grad.norm()).item()) |
| 132 | print(f" {2 * sum(num_blocks) + 2} {ratios[0]:8.1f} {ratios[1]:8.1f}") |
| 133 | print(" → 8단계에서 58층의 앞쪽 기울기는 뒤쪽의 2,000배였다. 지름길이 있으면 한 자릿수다") |
| 134 | print() |
| 135 | |
| 136 | print("6) 더 길게 돌린 비교 (미리 돌려 저장해 둔 것)") |
| 137 | print( |
| 138 | " 학습용 5,000장, 평가용 2,000장, width 8, 배치 128, 8에폭(320번 갱신). 깊이는 10, 34, 58층" |
| 139 | ) |
| 140 | full_run = here.parent / "full_run" |
| 141 | log = (full_run / "depth_log.txt").read_text() |
| 142 | runs = re.findall(r"^(\w+), .* = (\d+)층 \((\d+)초\)\n((?: \[.*\n)+)", log, re.MULTILINE) |
| 143 | table = {} |
| 144 | print( |
| 145 | " 블록 층 수 1에폭 손실 4에폭 손실 8에폭 손실 8에폭 평가 정확도 걸린 시간" |
| 146 | ) |
| 147 | for block, layers, seconds, body in runs: |
| 148 | rows = re.findall(r"학습 손실 ([\d.]+) \| 평가 정확도\s+([\d.]+)%", body) |
| 149 | table[block, int(layers)] = float(rows[-1][0]) |
| 150 | print( |
| 151 | f" {block:<14} {layers:>3} {rows[0][0]} {rows[3][0]} {rows[-1][0]}" |
| 152 | f" {float(rows[-1][1]):5.2f}% {int(seconds):>3}초" |
| 153 | ) |
| 154 | image_dir = Path(os.environ["IMAGE_DIR"]) |
| 155 | image_dir.mkdir(parents=True, exist_ok=True) |
| 156 | shutil.copy(full_run / "depth.png", image_dir / "depth.png") |
| 157 | print(" 에폭별 학습 손실 (왼쪽 PlainBlock, 오른쪽 ResidualBlock)") |
| 158 | print("[[image:depth]]") |
| 159 | p10, p34, p58 = (table["PlainBlock", n] for n in (10, 34, 58)) |
| 160 | r10, r34, r58 = (table["ResidualBlock", n] for n in (10, 34, 58)) |
| 161 | print(f" → PlainBlock은 깊을수록 곡선이 통째로 위로 올라간다: {p10:.3f} → {p34:.3f} → {p58:.3f}") |
| 162 | print( |
| 163 | f" → ResidualBlock은 10층과 34층의 곡선이 거의 겹친다 ({r10:.3f}, {r34:.3f}). 같은 34층끼리 비교하면 {p34:.3f} 대 {r34:.3f}다" |
| 164 | ) |
| 165 | print( |
| 166 | f" → 58층은 지름길이 있어도 10층보다 느리다 ({r58:.3f}). 그래도 지름길 없는 58층({p58:.3f})보다는 훨씬 낮다" |
| 167 | ) |
| 168 | print( |
| 169 | " → 지름길은 '깊어서 학습이 안 되는 문제'를 크게 줄였다. 320번 갱신으로는 깊은 쪽이 얕은 쪽을 앞서지는 못했다" |
| 170 | ) |