enhancesd-v6-model / model.py
matthewcodes's picture
Remove unrelated references from architecture docstrings
31b7a0f verified
Raw History Blame Contribute Delete
18 kB
"""The student: a one-step pixel-space image-to-image network.
A convolutional U-Net with attention at the deep levels, trained adversarially.
NOT a diffusion model -- no noise schedule, no sampling.
Every op here must be implementable as a ReShade FX compute pass, because that
is where it runs at inference. The allowed set, enforced by `assert_shader_safe`:
3x3 / 1x1 conv, stride-2 down, nearest up, concat, LeakyReLU,
per-channel scale+bias (which is also how FiLM conditioning is applied).
Banned: attention, normalisation layers at inference (BatchNorm is folded at
export), dynamic shapes, channel counts not divisible by 4.
Size is LOCKED at width 32, depth 4 (~4.9 M params) by the M0 compute budget at
20 ms/frame -- see DECISIONS.md. Do not grow it without re-checking the budget.
Multi-style: a small learned per-style embedding drives FiLM (feature-wise
linear modulation) scale/bias at each block, so one network serves several
styles, switching is instant, and styles interpolate. Style is SELECTED at
runtime (an index), never computed from text -- there is no text encoder in the
frame path, by architecture.
"""
from __future__ import annotations
import torch
import torch.nn as nn
from torch.nn.utils import parametrize
from torch.nn.utils.parametrizations import spectral_norm
import torch.nn.functional as F
# Network input channels: color 3 + depth 1 + normals 3 + warped_prev 3 + validity 1
IN_CHANNELS = 11
def _clamp_st(x: torch.Tensor, lo: float, hi: float) -> torch.Tensor:
"""Straight-through clamp: value is clamped, gradient passes as identity."""
return x + (x.clamp(lo, hi) - x).detach()
class FiLM(nn.Module):
"""Per-channel scale and bias from a style embedding.
At inference this is two numbers per channel, applied as y = x * s + b --
already in the shader op set. The MLP that produces them runs only when the
style changes (host-side, at style-switch), never per frame, so it costs
nothing in the frame budget and need not be shader-implementable.
"""
def __init__(self, style_dim: int, channels: int,
scale_range: float = 0.5, bias_range: float = 0.5):
super().__init__()
self.to_scale_bias = nn.Linear(style_dim, channels * 2)
# Bounds on the modulation. See forward() for why these exist.
self.scale_range = scale_range
self.bias_range = bias_range
# Start as identity (scale 1, bias 0) so an untrained/one-style network
# is unaffected by conditioning.
nn.init.zeros_(self.to_scale_bias.weight)
with torch.no_grad():
self.to_scale_bias.bias[:channels] = 1.0
self.to_scale_bias.bias[channels:] = 0.0
self.channels = channels
def forward(self, x: torch.Tensor, style: torch.Tensor) -> torch.Tensor:
"""y = x * scale + bias, with scale and bias BOUNDED.
Why bounded: with the convolutions spectral-normalised, this per-channel
multiply was the only unbounded multiplicative path left in the network,
and optimisation pressure moved straight to it. Measured in
tools/m3/diagnose_divergence.py: over 960 steps the projection weights
grew from 0.0084 to 0.155 (about 20x) while the convolutions stayed
bounded, and every activation then exploded (enc3 2.5e7, dec3 3.9e16).
Compounding a scale over the network's 9 blocks is what makes an
unbounded multiply dangerous here.
scale lands in [1 - scale_range, 1 + scale_range] and bias in
[-bias_range, +bias_range], via a straight-through clamp so the value is
bounded while the gradient still flows (a hard clamp would recreate the
dead-gradient failure this project already hit). Both are plain clamps
at inference, already in the shader op set.
"""
sb = self.to_scale_bias(style) # [N, 2C]
s, b = sb[:, :self.channels], sb[:, self.channels:]
s = _clamp_st(s, 1.0 - self.scale_range, 1.0 + self.scale_range)
b = _clamp_st(b, -self.bias_range, self.bias_range)
return x * s[:, :, None, None] + b[:, :, None, None]
class ConvBlock(nn.Module):
"""Two 3x3 convs with LeakyReLU, FiLM after the first."""
def __init__(self, in_ch: int, out_ch: int, style_dim: int):
super().__init__()
self.c1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
self.film = FiLM(style_dim, out_ch)
self.c2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
self.act = nn.LeakyReLU(0.2, inplace=True)
def forward(self, x: torch.Tensor, style: torch.Tensor) -> torch.Tensor:
x = self.act(self.film(self.c1(x), style))
return self.act(self.c2(x))
class SelfAttention2d(nn.Module):
"""Global self-attention over a feature map. **NOT shader-safe.**
The FX compute-shader op set has no attention and no normalisation, which is
why `assert_shader_safe` bans both. The owner dropped that constraint on
2026-09-05, committing to a native runtime. Attention is the thing a stack of
3x3 convolutions structurally cannot do: relate distant parts of the frame,
which is what "relight this room" actually requires.
Only affordable at low resolution. At 512x288 input the token counts are
L0 147,456 / L1 36,864 / L2 9,216 / L3 2,304 / L4 576 -- so this belongs at
the deep levels, exactly as Stable Diffusion's U-Net places it.
The output projection is ZERO-INITIALISED, so the block starts as an exact
identity and the network's passthrough property at init is preserved.
"""
def __init__(self, ch: int, heads: int = 4):
super().__init__()
assert ch % heads == 0, f"channels {ch} not divisible by heads {heads}"
self.heads = heads
self.norm = nn.GroupNorm(8, ch)
self.qkv = nn.Conv2d(ch, ch * 3, 1)
self.proj = nn.Conv2d(ch, ch, 1)
nn.init.zeros_(self.proj.weight)
nn.init.zeros_(self.proj.bias)
def forward(self, x: torch.Tensor) -> torch.Tensor:
n, c, h, w = x.shape
q, k, v = self.qkv(self.norm(x)).chunk(3, dim=1)
def sh(t):
return t.reshape(n, self.heads, c // self.heads, h * w).transpose(-2, -1)
o = F.scaled_dot_product_attention(sh(q), sh(k), sh(v))
o = o.transpose(-2, -1).reshape(n, c, h, w)
return x + self.proj(o)
class Student(nn.Module):
"""U-Net with a zero-initialised residual head.
Untrained -> exact passthrough (the identity baseline v4 requires, and a
GAN-stabilising starting point). Style is an index into a learned embedding
table, so a photoreal<->bodycam slider is a lerp between two embeddings.
"""
def __init__(self, width: int = 32, depth: int = 4, style_dim: int = 32,
num_styles: int = 2, in_ch: int = IN_CHANNELS, # photoreal(0), digital-camera(1)
residual_limit: float = 1.0, spectral: bool = True,
width0: int = 0, attn_levels: tuple = (), attn_heads: int = 4):
"""`width0` overrides the channel count of LEVEL 0 only (0 = use `width`).
Why level 0 is worth decoupling. A conv level costs Cin*Cout*H*W, and the
default schedule doubles channels while quartering pixels, so every level
costs about the same in FLOPs -- but NOT in wall clock: measured on an
RTX 3060 at 512x288, level 0 is 45.5% of a width-32 block's time, because
it is memory-bandwidth bound at full resolution while the deep levels are
compute bound.
That matters because the measured quality deficit is EDGE detail, which
lives at full resolution. Widening everything (w64 d4) costs +8.86 ms;
widening level 0 alone buys capacity where the deficit actually is for
+2.35 ms. Measured, 512x288, bf16, spectral norm folded:
w32 d4 (5.76M) 7.28 ms w64 d4 (22.88M) 17.62 ms
w32 d5 (22.96M) 8.76 ms w32 d5 + L0=64 (23.11M) 11.11 ms
"""
super().__init__()
assert width % 4 == 0, "channel counts must be multiples of 4"
w0 = width0 or width
assert w0 % 4 == 0, "channel counts must be multiples of 4"
self.width, self.depth, self.style_dim = width, depth, style_dim
self.width0 = w0
self.residual_limit = residual_limit
self.spectral = spectral
self.style_embedding = nn.Embedding(num_styles, style_dim)
# Level 0 may be overridden; deeper levels keep the width*2^i schedule.
chans = [w0] + [width * (2 ** i) for i in range(1, depth)]
self.attn_levels = tuple(sorted(set(attn_levels)))
for i in self.attn_levels:
if not 0 <= i < depth:
raise ValueError(f"attn level {i} outside 0..{depth - 1}")
self.enc = nn.ModuleList()
self.down = nn.ModuleList()
self.enc_attn = nn.ModuleList()
c = in_ch
for i in range(depth):
w = chans[i]
self.enc.append(ConvBlock(c, w, style_dim))
self.enc_attn.append(SelfAttention2d(w, attn_heads)
if i in self.attn_levels else nn.Identity())
self.down.append(nn.Conv2d(w, w, 3, stride=2, padding=1))
c = w
self.mid = ConvBlock(c, c, style_dim)
# The bottleneck is the cheapest place to attend and the widest receptive
# field, so it gets attention whenever any level does.
self.mid_attn = SelfAttention2d(c, attn_heads) if self.attn_levels else nn.Identity()
self.dec = nn.ModuleList()
self.dec_attn = nn.ModuleList()
for i in reversed(range(depth)):
w = chans[i]
self.dec.append(ConvBlock(c + w, w, style_dim))
self.dec_attn.append(SelfAttention2d(w, attn_heads)
if i in self.attn_levels else nn.Identity())
c = w
self.head = nn.Conv2d(c, 3, 1)
nn.init.zeros_(self.head.weight)
nn.init.zeros_(self.head.bias)
self.act = nn.LeakyReLU(0.2, inplace=True)
if spectral:
apply_spectral_norm(self)
def _style_vec(self, style, batch: int, device) -> torch.Tensor:
"""Accept a style index, a batch of indices, or an explicit embedding.
An explicit embedding lets training/inference interpolate between styles
(the blend slider) rather than pick one.
"""
if style is None:
return self.style_embedding(torch.zeros(batch, dtype=torch.long, device=device))
if isinstance(style, int):
return self.style_embedding(torch.full((batch,), style, dtype=torch.long, device=device))
if style.dtype in (torch.long, torch.int):
return self.style_embedding(style)
return style # already an embedding
def forward(self, x: torch.Tensor, style=None, return_raw: bool = False) -> torch.Tensor:
rgb = x[:, :3]
s = self._style_vec(style, x.shape[0], x.device)
skips = []
h = x
for enc, attn, down in zip(self.enc, self.enc_attn, self.down):
h = attn(enc(h, s))
skips.append(h)
h = self.act(down(h))
h = self.mid_attn(self.mid(h, s))
for dec, attn, skip in zip(self.dec, self.dec_attn, reversed(skips)):
h = F.interpolate(h, size=skip.shape[-2:], mode="nearest")
h = attn(dec(torch.cat([h, skip], dim=1), s))
h = F.interpolate(h, size=rgb.shape[-2:], mode="nearest")
res = self.head(h)
if return_raw:
return rgb + res # unbounded, for the range penalty
# BOUND THE RESIDUAL, straight-through. An appearance transform has no
# business moving a pixel by more than `residual_limit`, and without this
# the run realism_v3 drove the raw output to ~1e9 by step 1120: the range
# penalty then reached 1.5e9 and the gradient became inf. Value is
# clamped (shader: two clamps, both basic intrinsics), gradient passes.
res = _clamp_st(res, -self.residual_limit, self.residual_limit)
raw = rgb + res
# STRAIGHT-THROUGH CLAMP. The forward value is exactly saturate(raw), so
# this matches the shader bit for bit, but the gradient passes as
# identity instead of being zeroed outside [0,1].
#
# Why: with a hard .clamp(0,1) the run realism_v2 died at step 2120 --
# adversarial pressure pushed the residual past the range, every pixel
# saturated, grad_norm_G became exactly 0.0 and STAYED there for the
# remaining 3900 steps. A hard clamp is an absorbing state: once out of
# range there is no gradient to come back with. See DECISIONS.md.
return _clamp_st(raw, 0.0, 1.0)
def apply_spectral_norm(model: nn.Module) -> None:
"""Spectral-normalise every conv in the generator.
Why: runs realism_v3/v4 diverged because nothing bounds the decoder. The
instrumented reproduction (tools/m3/diagnose_divergence.py) showed encoder
activations steady around 2-30 while decoder activations climbed to 3.9e3,
with FiLM weights flat at 0.035 -- so the growth is in the decoder conv
weights, not the conditioning, and the shader op set forbids normalisation
layers that would otherwise damp it.
Spectral norm is a training-time REPARAMETERISATION: at export the weight is
materialised as W / sigma(W), a plain tensor. Nothing is added to the frame
budget and the shader op set is untouched. `strip_spectral_norm` performs
that materialisation and must be called before export.
"""
# The output head is EXCLUDED: it is zero-initialised on purpose (untrained
# network == exact passthrough), and sigma(0) == 0, so spectral norm would
# divide by zero and make every weight NaN. Caught by the export-equivalence
# check, which returned nan before this exclusion.
skip = {id(model.head)} if hasattr(model, "head") else set()
# Every attention output projection is zero-initialised for the same reason
# (the block starts as an exact identity), so it hits the same sigma(0)==0
# divide-by-zero. Observed 2026-09-05: without this the model's passthrough
# output was nan from level 3 onward.
for m in model.modules():
if isinstance(m, SelfAttention2d):
skip.add(id(m.proj))
for mod in model.modules():
if isinstance(mod, nn.Conv2d) and id(mod) not in skip \
and not parametrize.is_parametrized(mod, "weight"):
spectral_norm(mod)
def strip_spectral_norm(model: nn.Module) -> nn.Module:
"""Bake the spectral-norm reparameterisation into the weights, for export.
MUTATES `model` IN PLACE, and note that `copy.deepcopy` does NOT give you a
safe scratch copy: PyTorch parametrisation replaces the module class and the
copy still shares that state, so stripping a deepcopy leaves the ORIGINAL
model unusable (its `weight` attribute disappears). Observed in test. Strip
the model you intend to export, at the end of training, and do not keep
training it afterwards.
"""
for mod in model.modules():
if isinstance(mod, nn.Conv2d) and parametrize.is_parametrized(mod, "weight"):
parametrize.remove_parametrizations(mod, "weight", leave_parametrized=True)
return model
def assert_shader_safe(model: nn.Module) -> None:
"""Fail loudly if the model uses an op the shader engine cannot run.
Called in tests and before export. The whole point of the architecture is
that it maps to FX compute passes; a stray LayerNorm or attention here would
silently make the model unexportable.
"""
allowed = (Student, ConvBlock, FiLM, nn.ModuleList, nn.Conv2d, nn.LeakyReLU,
nn.Embedding, nn.Linear) # Linear only inside FiLM (host-side)
# Spectral norm is a reparameterisation, not a runtime op: it is folded into
# the weights by strip_spectral_norm() before export, so it is allowed here.
banned = (nn.MultiheadAttention, nn.BatchNorm2d, nn.GroupNorm, nn.LayerNorm,
nn.InstanceNorm2d, nn.Softmax)
for name, m in model.named_modules():
if isinstance(m, banned):
raise TypeError(f"shader-unsafe op {type(m).__name__} at '{name}'")
for p_name, _ in m.named_parameters(recurse=False):
pass
# Channel-count check on every conv.
for name, m in model.named_modules():
if isinstance(m, nn.Conv2d):
if m.out_channels % 4 != 0 and m.out_channels != 3:
raise ValueError(f"conv '{name}' out_channels={m.out_channels} not /4 (and not the 3-ch head)")
def assert_native_safe(model: nn.Module) -> None:
"""Invariants that still hold once the FX shader op set is abandoned.
`assert_shader_safe` is deliberately left strict: it describes the ReShade FX
compute path, and a model with attention genuinely is not runnable there.
This is the check for the native runtime -- attention and the norms inside it
are allowed, everything else that matters is still enforced:
- channel counts multiples of 4
- no BatchNorm/InstanceNorm (they would need folding and behave differently
between train and eval); GroupNorm/LayerNorm inside attention are fine
- the residual head is still a 1x1 conv to 3 channels
"""
banned = (nn.BatchNorm2d, nn.InstanceNorm2d)
for name, m in model.named_modules():
if isinstance(m, banned):
raise TypeError(f"unsupported op {type(m).__name__} at '{name}'")
for name, m in model.named_modules():
if isinstance(m, nn.Conv2d):
if m.out_channels % 4 != 0 and m.out_channels != 3:
raise ValueError(f"conv '{name}' out_channels={m.out_channels} not /4 (and not the 3-ch head)")
def count_params(m: nn.Module) -> int:
return sum(p.numel() for p in m.parameters())