FloorIsAwake's picture
Clean worktree path in provenance metadata and note K=4 depth for non-looped row
3c98ec5 verified
Raw History Blame Contribute Delete
23.6 kB
"""Column-aligned recurrent discrete diffusion model (`LoopedCarryDiffusion`) and matched
direct sum-bit cross-entropy training objective.
Provenance: Architecture and state-dict keys are preserved bit-for-bit from the baseline
snapshot `54ae69f6597e47c746beab677618de7b84293531` (`ec_looped_diffusion/model.py`,
SHA-256: 22d8a75f68199c6445c30b2facadda8a2289a7a8fe37e544567932156bf7ab6b) so all frozen
Stage 1-2 checkpoints load with `strict=True`. Additions for this paper study:
- `compute_direct_sum_loss`: matched direct sum-bit CE control (always all-MASK input,
identical architecture, identical loop deep supervision, supervising all W target bits).
- `denoise_predict_with_stats`: returns exact forward-call (NFE) and core-iteration counts
to separate recurrent depth K, iterative unmasking steps S, and T2T refinement passes R.
- `parameter_digest`: deterministic SHA-256 digest of parameter tensors for controlled-arm
initialization verification.
"""
from __future__ import annotations
import hashlib
import math
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor, nn
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: Tensor) -> Tensor:
norm = torch.rsqrt(x.float().pow(2).mean(dim=-1, keepdim=True) + self.eps)
return (x.float() * norm).to(x.dtype) * self.weight
class SwiGLU(nn.Module):
def __init__(self, d_model: int, d_ff: int):
super().__init__()
self.w_gate_up = nn.Linear(d_model, 2 * d_ff, bias=False)
self.w_down = nn.Linear(d_ff, d_model, bias=False)
def forward(self, x: Tensor) -> Tensor:
gate, up = self.w_gate_up(x).chunk(2, dim=-1)
return self.w_down(F.silu(gate) * up)
class GatedShortConvBlock(nn.Module):
"""Bidirectional gated depthwise ShortConv block (translation-invariant local carry wire)."""
def __init__(self, d_model: int, d_ff: int, kernel_size: int = 5):
super().__init__()
assert kernel_size % 2 == 1
self.norm1 = RMSNorm(d_model)
self.in_proj = nn.Linear(d_model, 2 * d_model, bias=False)
self.dw_conv = nn.Conv1d(
d_model,
d_model,
kernel_size=kernel_size,
padding=kernel_size // 2,
groups=d_model,
bias=True,
)
self.out_proj = nn.Linear(d_model, d_model, bias=False)
self.norm2 = RMSNorm(d_model)
self.mlp = SwiGLU(d_model, d_ff)
def forward(self, x: Tensor, valid_mask: Optional[Tensor] = None) -> Tensor:
h = self.norm1(x)
v, gate = self.in_proj(h).chunk(2, dim=-1)
if valid_mask is not None:
v = v * valid_mask.unsqueeze(-1).to(v.dtype)
conv_out = self.dw_conv(v.transpose(1, 2)).transpose(1, 2)
x = x + self.out_proj(conv_out * F.silu(gate))
x = x + self.mlp(self.norm2(x))
return x
def _build_directional_alibi_slopes(n_heads: int) -> tuple[Tensor, Tensor]:
"""Directional ALiBi slopes: LSB-biased, MSB-biased, and symmetric/global heads."""
slopes = []
directions = []
n_lsb = n_heads // 3
n_msb = n_heads // 3
n_sym = n_heads - n_lsb - n_msb
for i in range(n_lsb):
slopes.append(0.5 ** (i + 1))
directions.append(-1)
for i in range(n_msb):
slopes.append(0.5 ** (i + 1))
directions.append(1)
for i in range(n_sym):
slopes.append(0.0 if i == 0 else 0.25 ** i)
directions.append(0)
return torch.tensor(slopes, dtype=torch.float32), torch.tensor(directions, dtype=torch.int64)
class ALiBiAttentionBlock(nn.Module):
"""Pre-RMSNorm + QK-Norm Multi-Head Attention with width-invariant directional ALiBi."""
def __init__(
self,
d_model: int,
n_heads: int,
d_ff: int,
log_len_scale_mode: str = "none",
log_len_ref_width: int = 16,
):
super().__init__()
assert d_model % n_heads == 0
if log_len_scale_mode not in {"none", "fixed_log", "learned_log"}:
raise ValueError(f"Unknown log length scaling mode: {log_len_scale_mode!r}")
if log_len_ref_width < 2:
raise ValueError("log_len_ref_width must be at least 2")
self.log_len_scale_mode = log_len_scale_mode
self.log_len_ref_width = log_len_ref_width
if log_len_scale_mode == "learned_log":
self.log_scale_alpha = nn.Parameter(torch.ones(n_heads))
self.n_heads = n_heads
self.head_dim = d_model // n_heads
self.norm1 = RMSNorm(d_model)
self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
self.q_norm = RMSNorm(self.head_dim)
self.k_norm = RMSNorm(self.head_dim)
self.o_proj = nn.Linear(d_model, d_model, bias=False)
self.norm2 = RMSNorm(d_model)
self.mlp = SwiGLU(d_model, d_ff)
slopes, dirs = _build_directional_alibi_slopes(n_heads)
self.register_buffer("alibi_slopes", slopes, persistent=False)
self.register_buffer("alibi_dirs", dirs, persistent=False)
def _alibi_bias(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> Tensor:
pos = torch.arange(seq_len, device=device, dtype=torch.float32)
diff = pos.unsqueeze(0) - pos.unsqueeze(1)
abs_dist = diff.abs()
biases = []
for h in range(self.n_heads):
s = self.alibi_slopes[h]
d = int(self.alibi_dirs[h].item())
if d == -1:
b = -s * torch.where(diff <= 0, -diff, 4.0 * diff)
elif d == 1:
b = -s * torch.where(diff >= 0, diff, 4.0 * (-diff))
else:
b = -s * abs_dist
biases.append(b)
return torch.stack(biases, dim=0).unsqueeze(0).to(dtype)
def forward(self, x: Tensor, valid_mask: Optional[Tensor] = None) -> Tensor:
B, W, D = x.shape
h = self.norm1(x)
q, k, v = self.qkv(h).chunk(3, dim=-1)
q = self.q_norm(q.view(B, W, self.n_heads, self.head_dim)).transpose(1, 2)
k = self.k_norm(k.view(B, W, self.n_heads, self.head_dim)).transpose(1, 2)
v = v.view(B, W, self.n_heads, self.head_dim).transpose(1, 2)
attn_bias = self._alibi_bias(W, x.device, q.dtype)
if self.log_len_scale_mode != "none" and W > self.log_len_ref_width:
ref_width = self.log_len_ref_width
if self.log_len_scale_mode == "fixed_log":
scale = math.log(W) / math.log(ref_width)
else:
excess = math.log(W / ref_width) / math.log(ref_width)
alpha = self.log_scale_alpha.clamp_min(0).view(1, self.n_heads, 1, 1)
scale = (1.0 + alpha * excess).to(q.dtype)
q = q * scale
attn_bias = attn_bias * scale
if valid_mask is not None:
key_invalid = (~valid_mask).view(B, 1, 1, W)
attn_bias = attn_bias.expand(B, -1, -1, -1).masked_fill(key_invalid, -1e4)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_bias)
out = out.transpose(1, 2).contiguous().view(B, W, D)
x = x + self.o_proj(out)
x = x + self.mlp(self.norm2(x))
return x
def mask_frac_features(mask_frac: Tensor, dtype: torch.dtype) -> Tensor:
m = mask_frac
return torch.stack((m, 1.0 - m, torch.sin(math.pi * m), torch.cos(math.pi * m)), dim=-1).to(dtype)
@dataclass
class LoopedCarryConfig:
cond_dim: int
num_ops: int = 8
target_vocab: int = 2
d_model: int = 256
n_heads: int = 8
d_ff: int = 640
prelude_layers: int = 1
core_layers: int = 2
coda_layers: int = 1
default_loops: int = 4
conv_kernel_size: int = 5
use_short_conv: bool = True
prelude_use_short_conv: bool = True
use_loop_sharing: bool = True
loop_use_step_emb: bool = False
loop_noise_std: float = 0.02
self_correct_prob: float = 0.25
log_len_scale_mode: str = "none"
log_len_ref_width: int = 16
class LoopedCarryDiffusion(nn.Module):
"""Column-aligned recurrent discrete diffusion model."""
def __init__(self, cfg: LoopedCarryConfig):
super().__init__()
self.cfg = cfg
self.mask_token_id = cfg.target_vocab
self.cond_proj = nn.Linear(cfg.cond_dim, cfg.d_model, bias=True)
self.op_emb = nn.Embedding(cfg.num_ops, cfg.d_model)
self.clean_prelude = (
GatedShortConvBlock(cfg.d_model, cfg.d_ff, cfg.conv_kernel_size)
if (cfg.use_short_conv and cfg.prelude_use_short_conv)
else self._make_attention_block()
)
self.target_emb = nn.Embedding(cfg.target_vocab + 1, cfg.d_model)
self.mask_cond_proj = nn.Linear(4, cfg.d_model, bias=False)
nn.init.zeros_(self.mask_cond_proj.weight)
self.prelude = nn.ModuleList([self._make_block(i) for i in range(cfg.prelude_layers)])
if cfg.use_loop_sharing:
self.core = nn.ModuleList([self._make_core_block(i) for i in range(cfg.core_layers)])
self.unshared_cores = None
else:
self.core = None
self.unshared_cores = nn.ModuleList([
nn.ModuleList([self._make_core_block(i) for i in range(cfg.core_layers)])
for _ in range(cfg.default_loops)
])
self.loop_norm = RMSNorm(cfg.d_model)
self.loop_adapter = nn.Linear(cfg.d_model, cfg.d_model, bias=False)
self.step_emb = nn.Embedding(4, cfg.d_model)
if not cfg.loop_use_step_emb:
with torch.no_grad():
self.step_emb.weight.zero_()
self.step_emb.weight.requires_grad_(False)
self.coda = nn.ModuleList([self._make_attention_block() for _ in range(cfg.coda_layers)])
self.final_norm = RMSNorm(cfg.d_model)
self.lm_head = nn.Linear(cfg.d_model, cfg.target_vocab, bias=False)
self.apply(self._init_weights)
nn.init.zeros_(self.mask_cond_proj.weight)
if not cfg.loop_use_step_emb:
with torch.no_grad():
self.step_emb.weight.zero_()
def _make_attention_block(self) -> ALiBiAttentionBlock:
return ALiBiAttentionBlock(
self.cfg.d_model,
self.cfg.n_heads,
self.cfg.d_ff,
self.cfg.log_len_scale_mode,
self.cfg.log_len_ref_width,
)
def _make_block(self, idx: int) -> nn.Module:
if self.cfg.use_short_conv and self.cfg.prelude_use_short_conv and idx % 2 == 0:
return GatedShortConvBlock(self.cfg.d_model, self.cfg.d_ff, self.cfg.conv_kernel_size)
return self._make_attention_block()
def _make_core_block(self, idx: int) -> nn.Module:
if self.cfg.use_short_conv and idx % 2 == 0:
return GatedShortConvBlock(self.cfg.d_model, self.cfg.d_ff, self.cfg.conv_kernel_size)
return self._make_attention_block()
@staticmethod
def _init_weights(m: nn.Module) -> None:
if isinstance(m, (nn.Linear, nn.Conv1d)):
nn.init.normal_(m.weight, mean=0.0, std=0.02)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Embedding):
nn.init.normal_(m.weight, mean=0.0, std=0.02)
def num_parameters(self) -> int:
return sum(p.numel() for p in self.parameters() if p.requires_grad)
def _loop_input(self, state: Tensor, anchor: Tensor, step: int, mask_frac: Tensor) -> Tensor:
out = state + self.loop_adapter(self.loop_norm(state + anchor))
out = out + self.mask_cond_proj(mask_frac_features(mask_frac, out.dtype))
if self.cfg.loop_use_step_emb:
out = out + self.step_emb.weight[min(step, self.step_emb.num_embeddings - 1)]
if self.training and self.cfg.loop_noise_std > 0.0:
out = out + torch.randn_like(out) * self.cfg.loop_noise_std
return out
def _decode_coda(self, state: Tensor, valid_mask: Optional[Tensor]) -> Tensor:
h = state
for blk in self.coda:
h = blk(h, valid_mask)
return self.lm_head(self.final_norm(h))
def forward_with_exits(
self,
cond_feat: Tensor,
op_ids: Tensor,
noisy_ids: Tensor,
*,
num_loops: Optional[int] = None,
valid_mask: Optional[Tensor] = None,
return_hidden: bool = False,
) -> tuple[list[Tensor], Optional[Tensor]]:
B, W, _ = cond_feat.shape
loops = self.cfg.default_loops if num_loops is None else num_loops
if not self.cfg.use_loop_sharing:
loops = min(loops, len(self.unshared_cores))
clean = self.cond_proj(cond_feat) + self.op_emb(op_ids).unsqueeze(1)
clean = self.clean_prelude(clean, valid_mask)
is_masked = noisy_ids.eq(self.mask_token_id)
if valid_mask is not None:
denom = valid_mask.float().sum(dim=1, keepdim=True).clamp_min(1.0)
m_frac = (is_masked & valid_mask).float().sum(dim=1, keepdim=True) / denom
else:
m_frac = is_masked.float().mean(dim=1, keepdim=True)
m_frac = m_frac.expand(B, W)
x = clean + self.target_emb(noisy_ids)
for blk in self.prelude:
x = blk(x, valid_mask)
anchor = x
state = x
exit_logits: list[Tensor] = []
if self.training and loops >= 2:
exit_steps = sorted({max(0, loops // 2 - 1), loops - 1})
else:
exit_steps = [loops - 1]
for step in range(loops):
state = self._loop_input(state, anchor, step, m_frac)
blocks = self.core if self.cfg.use_loop_sharing else self.unshared_cores[step]
for blk in blocks:
state = blk(state, valid_mask)
if step in exit_steps:
exit_logits.append(self._decode_coda(state, valid_mask))
return exit_logits, (state if return_hidden else None)
def forward(
self,
cond_feat: Tensor,
op_ids: Tensor,
noisy_ids: Tensor,
*,
num_loops: Optional[int] = None,
valid_mask: Optional[Tensor] = None,
) -> Tensor:
exits, _ = self.forward_with_exits(
cond_feat, op_ids, noisy_ids, num_loops=num_loops, valid_mask=valid_mask
)
return exits[-1]
def corrupt_targets(
self,
targets: Tensor,
valid_mask: Optional[Tensor] = None,
*,
min_mask_prob: float = 0.05,
self_correct_prob: Optional[float] = None,
) -> tuple[Tensor, Tensor]:
B, W = targets.shape
device = targets.device
sc_p = self.cfg.self_correct_prob if self_correct_prob is None else self_correct_prob
t = torch.rand(B, 1, device=device) * (1.0 - min_mask_prob) + min_mask_prob
all_mask_rows = torch.rand(B, 1, device=device) < 0.25
t = torch.where(all_mask_rows, torch.ones_like(t), t)
masked = torch.rand(B, W, device=device) < t
if valid_mask is not None:
masked = masked & valid_mask
noisy = targets.masked_fill(masked, self.mask_token_id)
if sc_p > 0.0:
visible = ~masked if valid_mask is None else (valid_mask & ~masked)
draws = torch.rand(B, W, device=device)
corrupt = visible & (draws < sc_p)
anchors = visible & (draws >= sc_p) & (draws < 2.0 * sc_p)
prev = F.pad(targets[:, :-1], (1, 0), value=0)
rand_wrong = (targets + torch.randint(1, self.cfg.target_vocab, (B, W), device=device)) % self.cfg.target_vocab
use_prev = (draws < sc_p * 0.5) & (prev != targets)
corrupted_val = torch.where(use_prev, prev, rand_wrong)
noisy = torch.where(corrupt, corrupted_val, noisy)
supervised = masked | corrupt | anchors
else:
supervised = masked
if valid_mask is not None:
supervised = supervised & valid_mask
noisy = noisy.masked_fill(~valid_mask, self.mask_token_id)
return noisy, supervised
def _deep_supervision_ce(
self,
exit_logits: list[Tensor],
targets: Tensor,
supervised: Tensor,
) -> Tensor:
total_loss = torch.zeros((), device=targets.device, dtype=torch.float32)
if len(exit_logits) == 1:
weights = [1.0]
else:
weights = [0.3 / (len(exit_logits) - 1)] * (len(exit_logits) - 1) + [0.7]
sup_flat = supervised.reshape(-1)
tgt_flat = targets.reshape(-1)
if not sup_flat.any():
return total_loss
for w, logits in zip(weights, exit_logits):
ce = F.cross_entropy(logits.float().reshape(-1, self.cfg.target_vocab)[sup_flat], tgt_flat[sup_flat])
total_loss = total_loss + w * ce
return total_loss
def compute_diffusion_loss(
self,
cond_feat: Tensor,
op_ids: Tensor,
targets: Tensor,
*,
num_loops: Optional[int] = None,
valid_mask: Optional[Tensor] = None,
) -> Tensor:
noisy_ids, supervised = self.corrupt_targets(targets, valid_mask=valid_mask)
exit_logits, _ = self.forward_with_exits(
cond_feat, op_ids, noisy_ids, num_loops=num_loops, valid_mask=valid_mask
)
return self._deep_supervision_ce(exit_logits, targets, supervised)
def compute_direct_sum_loss(
self,
cond_feat: Tensor,
op_ids: Tensor,
targets: Tensor,
*,
num_loops: Optional[int] = None,
valid_mask: Optional[Tensor] = None,
) -> Tensor:
"""Matched direct sum-bit CE control: always feeds all-MASK tokens and supervises all valid bits."""
B, W = targets.shape
noisy_ids = torch.full((B, W), self.mask_token_id, dtype=torch.long, device=targets.device)
supervised = (
torch.ones((B, W), dtype=torch.bool, device=targets.device)
if valid_mask is None
else valid_mask.bool()
)
exit_logits, _ = self.forward_with_exits(
cond_feat, op_ids, noisy_ids, num_loops=num_loops, valid_mask=valid_mask
)
return self._deep_supervision_ce(exit_logits, targets, supervised)
@torch.no_grad()
def denoise_predict_with_stats(
self,
cond_feat: Tensor,
op_ids: Tensor,
*,
num_loops: int,
valid_mask: Optional[Tensor] = None,
refine_steps: int = 0,
iterative_steps: int = 1,
conf_threshold: float = 0.95,
) -> tuple[Tensor, Tensor, dict[str, int]]:
"""Run inference separating recurrent depth K, iterative unmasking steps S, and T2T passes R."""
B, W, _ = cond_feat.shape
device = cond_feat.device
noisy = torch.full((B, W), self.mask_token_id, dtype=torch.long, device=device)
effective_loops = num_loops if self.cfg.use_loop_sharing else min(num_loops, len(self.unshared_cores))
unmask_nfes = 0
refine_nfes = 0
if iterative_steps <= 1:
logits = self.forward(cond_feat, op_ids, noisy, num_loops=num_loops, valid_mask=valid_mask)
unmask_nfes = 1
preds = logits.argmax(dim=-1)
else:
remaining = torch.ones((B, W), dtype=torch.bool, device=device)
if valid_mask is not None:
remaining = remaining & valid_mask
logits = None
for step in range(iterative_steps):
logits = self.forward(cond_feat, op_ids, noisy, num_loops=num_loops, valid_mask=valid_mask)
unmask_nfes += 1
probs = logits.float().softmax(dim=-1)
max_p, argmax = probs.max(dim=-1)
if step == iterative_steps - 1:
noisy = torch.where(remaining, argmax, noisy)
remaining = torch.zeros_like(remaining)
break
steps_left = iterative_steps - step
quota = ((remaining.sum(dim=-1, keepdim=True) + steps_left - 1) // steps_left).clamp_min(1)
conf_sel = remaining & (max_p >= conf_threshold)
order = max_p.masked_fill(~remaining, -1.0).argsort(dim=-1, descending=True, stable=True)
topk_sel = remaining & (order.argsort(dim=-1) < quota)
reveal = conf_sel | topk_sel
noisy = torch.where(reveal, argmax, noisy)
remaining = remaining & ~reveal
if not remaining.any():
break
preds = noisy
cur = preds.clone()
for _ in range(refine_steps):
cur_in = cur.masked_fill(~valid_mask, self.mask_token_id) if valid_mask is not None else cur
logits = self.forward(cond_feat, op_ids, cur_in, num_loops=num_loops, valid_mask=valid_mask)
refine_nfes += 1
nxt = logits.argmax(dim=-1)
same = ((nxt == cur) | ~valid_mask).all() if valid_mask is not None else (nxt == cur).all()
cur = nxt
if same:
break
total_nfes = unmask_nfes + refine_nfes
stats = {
"effective_loops": int(effective_loops),
"unmask_nfes": int(unmask_nfes),
"refine_nfes": int(refine_nfes),
"total_nfes": int(total_nfes),
"total_core_evals": int(total_nfes * effective_loops),
}
return cur, logits, stats
@torch.no_grad()
def denoise_predict(
self,
cond_feat: Tensor,
op_ids: Tensor,
*,
num_loops: int,
valid_mask: Optional[Tensor] = None,
refine_steps: int = 0,
iterative_steps: int = 1,
conf_threshold: float = 0.95,
) -> tuple[Tensor, Tensor]:
preds, logits, _ = self.denoise_predict_with_stats(
cond_feat,
op_ids,
num_loops=num_loops,
valid_mask=valid_mask,
refine_steps=refine_steps,
iterative_steps=iterative_steps,
conf_threshold=conf_threshold,
)
return preds, logits
def parameter_digest(model: nn.Module) -> str:
"""Deterministic SHA-256 digest of all state-dict tensors (CPU float32/raw bytes)."""
h = hashlib.sha256()
for name, tensor in sorted(model.state_dict().items()):
h.update(name.encode("utf-8"))
h.update(tensor.detach().cpu().contiguous().numpy().tobytes())
return h.hexdigest()
def audit_zero_leakage(model: LoopedCarryDiffusion, device: torch.device) -> float:
"""Verify exact zero leakage: perturbing targets behind MASK tokens gives max_delta == 0.0."""
model.eval()
B, W = 4, 16
cond = torch.randn(B, W, model.cfg.cond_dim, device=device)
ops = torch.zeros(B, dtype=torch.long, device=device)
y1 = torch.zeros(B, W, dtype=torch.long, device=device)
y2 = torch.ones(B, W, dtype=torch.long, device=device) % model.cfg.target_vocab
mask = torch.zeros(B, W, dtype=torch.bool, device=device)
mask[:, ::2] = True
y2 = torch.where(mask, y2, y1)
n1 = y1.masked_fill(mask, model.mask_token_id)
n2 = y2.masked_fill(mask, model.mask_token_id)
with torch.no_grad():
l1 = model(cond, ops, n1, num_loops=model.cfg.default_loops)
l2 = model(cond, ops, n2, num_loops=model.cfg.default_loops)
return float((l1 - l2).abs().max().item())