amer224 commited on
Commit
fc3acb3
·
verified ·
1 Parent(s): dc1d0bc

Add brains/sovereign-nano/opt.py

Browse files
Files changed (1) hide show
  1. brains/sovereign-nano/opt.py +200 -0
brains/sovereign-nano/opt.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ opt.py — inference optimizations for SOVEREIGN-nano (torch-native, no
3
+ exotic deps). Each lever states honestly what it can and cannot do.
4
+
5
+ 1. fold_bn(model) — folds BatchNorm into the preceding convs for
6
+ EVALUATION / rollout mode. Verified numerically in the smoke: at init
7
+ (running stats mu=0, sigma=1) the folded net is EXACTLY equivalent;
8
+ after training it is the standard inference approximation.
9
+ KEEP the unfolded state for training.
10
+ 2. to_channels_last(x) — NHWC input helper (encoder + heat convs get
11
+ cuDNN's fast NHWC path; the model auto-converts to NCHW before
12
+ interpolate/grid_sample internally).
13
+ 3. compile_if_available(model) — torch.compile (torch>=2.0), 1.3-2x on
14
+ 256px CNNs; first call pays a one-time compile cost.
15
+ 4. count_flops(model, rgb, nums) — hook-based MAC/GFLOP counter for the
16
+ exact input (so speed claims are measured, not vibes).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections import defaultdict
22
+ from typing import Dict, Optional, Tuple
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+
27
+
28
+ # --------------------------------------------------------------------------
29
+ # 1. BatchNorm folding (inference-only)
30
+ # --------------------------------------------------------------------------
31
+
32
+ def _fold(conv: nn.Conv2d, bn: nn.BatchNorm2d) -> nn.Conv2d:
33
+ w = conv.weight.detach().clone()
34
+ gamma = bn.weight.detach().clone()
35
+ beta = bn.bias.detach().clone()
36
+ var = bn.running_var.detach().clone()
37
+ mean = bn.running_mean.detach().clone()
38
+ scale = gamma / torch.sqrt(var + bn.eps)
39
+ wf = w * scale.view(-1, 1, 1, 1)
40
+ b_prev = (conv.bias.detach().clone()
41
+ if conv.bias is not None
42
+ else torch.zeros(w.shape[0], device=w.device))
43
+ bf = (b_prev - mean) * scale + beta
44
+ new = nn.Conv2d(conv.in_channels, conv.out_channels, conv.kernel_size,
45
+ stride=conv.stride, padding=conv.padding,
46
+ dilation=conv.dilation, groups=conv.groups, bias=True)
47
+ with torch.no_grad():
48
+ new.weight.copy_(wf)
49
+ new.bias.copy_(bf)
50
+ return new
51
+
52
+
53
+ def fold_bn(module: nn.Module) -> nn.Module:
54
+ """Fold every Conv->BN pair into a single Conv (in place). Only call
55
+ this on a model you are about to RUN in eval mode (rollouts/eval)."""
56
+ # adjacent pairs inside nn.Sequential (stem, _ConvBn, mixer, tower)
57
+ if isinstance(module, nn.Sequential):
58
+ keys = list(module._modules.keys())
59
+ i = 0
60
+ while i < len(keys):
61
+ m = module._modules[keys[i]]
62
+ if (isinstance(m, nn.Conv2d) and i + 1 < len(keys)
63
+ and isinstance(module._modules[keys[i + 1]],
64
+ nn.BatchNorm2d)):
65
+ module._modules[keys[i]] = _fold(
66
+ m, module._modules[keys[i + 1]])
67
+ module._modules[keys[i + 1]] = nn.Identity()
68
+ i += 2
69
+ else:
70
+ i += 1
71
+ for m in module._modules.values():
72
+ fold_bn(m)
73
+ return module
74
+
75
+ # attribute pairs (ResBlock: conv1/bn1 conv2/bn2; UpStage: up/bn)
76
+ for cname, bname in (("conv1", "bn1"), ("conv2", "bn2"), ("up", "bn"),
77
+ ("conv", "bn")):
78
+ c = getattr(module, cname, None)
79
+ b = getattr(module, bname, None)
80
+ if isinstance(c, nn.Conv2d) and isinstance(b, nn.BatchNorm2d):
81
+ setattr(module, cname, _fold(c, b))
82
+ setattr(module, bname, nn.Identity())
83
+ for m in module._modules.values():
84
+ fold_bn(m)
85
+ return module
86
+
87
+
88
+ # --------------------------------------------------------------------------
89
+ # 2. channels_last helper
90
+ # --------------------------------------------------------------------------
91
+
92
+ def to_channels_last(x: torch.Tensor) -> torch.Tensor:
93
+ """NHWC input for the conv-bound paths. The model converts back to
94
+ NCHW internally before interpolate/grid_sample (see model_nano)."""
95
+ return x.contiguous(memory_format=torch.channels_last)
96
+
97
+
98
+ # --------------------------------------------------------------------------
99
+ # 3. torch.compile helper
100
+ # --------------------------------------------------------------------------
101
+
102
+ def compile_if_available(model: nn.Module,
103
+ mode: str = "reduce-overhead") -> nn.Module:
104
+ """Compile if torch>=2.0; returns the (possibly wrapped) model."""
105
+ try:
106
+ if not hasattr(torch, "compile"):
107
+ raise RuntimeError("torch < 2.0")
108
+ return torch.compile(model, mode=mode)
109
+ except Exception as e:
110
+ print(f"[opt] torch.compile unavailable ({str(e)[:80]}) — "
111
+ f"returning eager model")
112
+ return model
113
+
114
+
115
+ # --------------------------------------------------------------------------
116
+ # 4. FLOP counter (hook-based, exact for the given input)
117
+ # --------------------------------------------------------------------------
118
+
119
+ def count_flops(model: nn.Module, rgb: torch.Tensor,
120
+ nums: Optional[torch.Tensor] = None,
121
+ rtg: Optional[torch.Tensor] = None
122
+ ) -> Tuple[int, Dict[str, int]]:
123
+ """MACs and per-module breakdown for one forward at this input size.
124
+ GRU and grid_sample are omitted (negligible — stated)."""
125
+ macs: Dict[str, int] = defaultdict(int)
126
+ handles = []
127
+
128
+ def hook(name: str):
129
+ def f(m, inp, out):
130
+ x = inp[0]
131
+ o = out[0] if isinstance(out, tuple) else out
132
+ if isinstance(m, nn.Conv2d):
133
+ macs[name] = int(
134
+ o.shape[0] * o.shape[2] * o.shape[3] * m.kernel_size[0]
135
+ * m.kernel_size[1] * m.in_channels * m.out_channels
136
+ / max(m.groups, 1))
137
+ elif isinstance(m, nn.Linear):
138
+ macs[name] = int(x.shape[0] * m.in_features * m.out_features)
139
+ return f
140
+
141
+ for name, m in model.named_modules():
142
+ if isinstance(m, (nn.Conv2d, nn.Linear)):
143
+ handles.append(m.register_forward_hook(hook(name)))
144
+ was_training = model.training
145
+ model.eval()
146
+ with torch.no_grad():
147
+ model(rgb, nums, rtg=rtg)
148
+ model.train(was_training)
149
+ for h in handles:
150
+ h.remove()
151
+ return sum(macs.values()), dict(macs)
152
+
153
+
154
+ def gflops(total_macs: int) -> float:
155
+ return total_macs * 2 / 1e9
156
+
157
+
158
+ # --------------------------------------------------------------------------
159
+ # Smoke
160
+ # --------------------------------------------------------------------------
161
+
162
+ if __name__ == "__main__":
163
+ from model_nano import NanoConfig, make_nano
164
+
165
+ print("== opt.py smoke ==")
166
+ cfg = NanoConfig(map_size=64)
167
+ net = make_nano(cfg, seed=0).eval()
168
+ x = torch.rand(1, 3, 64, 64)
169
+ nums = torch.rand(1, 8)
170
+
171
+ # FLOP count
172
+ total_macs, per_mod = count_flops(net, x, nums)
173
+ print(f"FLOPs @64px: {gflops(total_macs):.2f} GFLOPs "
174
+ f"({total_macs/1e6:.0f}M MACs)")
175
+ top = sorted(per_mod.items(), key=lambda kv: -kv[1])[:4]
176
+ print(" top modules: " + ", ".join(
177
+ f"{n.split('.')[-1]}={v/1e6:.0f}M" for n, v in top))
178
+
179
+ # BN folding exactness at init
180
+ ref = net(x, nums, return_all=True)
181
+ fold_bn(net)
182
+ out = net(x, nums, return_all=True)
183
+ diffs = [float((ref[k] - out[k]).abs().max().item())
184
+ for k in ("heat", "kind_logits", "value", "pct", "win_logits")
185
+ if ref[k] is not None]
186
+ print(f"fold max-diff (must be ~0 at init): {max(diffs):.2e}")
187
+ assert max(diffs) < 1e-5, "BN fold is not numerically exact!"
188
+
189
+ # channels_last path
190
+ net_cl = make_nano(cfg, seed=0).eval()
191
+ x_cl = to_channels_last(x)
192
+ out_cl = net_cl(x_cl, nums, return_all=True)
193
+ d_cl = float((out["heat"] - out_cl["heat"]).abs().max().item())
194
+ print(f"channels_last max-diff: {d_cl:.2e}")
195
+ assert d_cl < 1e-5
196
+
197
+ # torch.compile availability
198
+ cnet = compile_if_available(net)
199
+ print("compile:", "active" if cnet is not net else "unavailable")
200
+ print("opt.py smoke OK")