Zae Claude Opus 4.6 (1M context) commited on
Commit
77345ce
·
1 Parent(s): 49589ef

Unified PC training: fix energy normalization, add task signal to all blocks

Browse files

- Energy uses mean-over-D, sum-over-B×S so denoising (~70%) dominates prediction errors (~30%)
Previously with full sum, prediction errors were 150x larger than denoising — settling
only learned inter-layer consistency, never token prediction.
- Forward blocks now receive task gradient (readout cross-entropy) in addition to local
consistency signal during unified settling.
- Precision heads clamped at 10.0 to prevent NaN explosion.
- Gradient clipping added to all local updates.
- Embedding + precision head updates added to unified_step.
- Training uses unified mode (settling IS learning) instead of local PC.
- Checkpoint resume now continues from saved step counter.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Files changed (1) hide show
  1. src/model.py +74 -49
src/model.py CHANGED
@@ -530,53 +530,53 @@ class PCSHODLM(nn.Module):
530
  tok_p, ch_p = self.precision_down[l](h[l + 1], t)
531
  lambda_precs.append((tok_p, ch_p))
532
 
533
- # Energy computation
 
 
 
 
534
  energy = 0.0
535
 
536
- # Bottom-up consistency: sum_l 0.5 * ||eps_l^up||_{Gamma_l}^2
537
  for l in range(L):
538
  tok_p, ch_p = gamma_precs[l]
539
  weighted_err = eps_up[l] * tok_p * ch_p # (B, S, D)
540
- energy += 0.5 * (weighted_err * eps_up[l]).sum()
541
 
542
- # Top-down consistency: sum_l 0.5 * ||eps_l^down||_{Lambda_l}^2
543
  for l in range(L - 1):
544
  tok_p, ch_p = lambda_precs[l]
545
  weighted_err = eps_down[l] * tok_p * ch_p
546
- energy += 0.5 * (weighted_err * eps_down[l]).sum()
547
 
548
- # Denoising loss at top layer.
549
- # HONEST SETTLING: during settling, use entropy minimization (push toward confident predictions)
550
- # rather than cross-entropy with x_0 (which lets the model peek at the answer).
551
- # The actual x_0 cross-entropy is used ONLY for parameter updates after settling.
552
  logits = self.readout(self.readout_norm(h[L])) # (B, S, V)
553
  mask_logits = logits[mask]
554
 
555
  if mask_logits.numel() > 0:
556
  if self._honest_settling:
557
- # Entropy minimization: push toward confident predictions without peeking
558
  probs = F.softmax(mask_logits, dim=-1)
559
  entropy = -(probs * (probs + 1e-10).log()).sum(dim=-1) # per-token entropy
560
- denoising_loss = entropy.sum()
561
  else:
562
- # Use x_0 targets (for backward compat / ablation)
563
  mask_targets = x_0[mask]
564
- denoising_loss = F.cross_entropy(mask_targets, mask_targets, reduction="sum")
565
 
566
  t_frac = t.float().mean() / config.n_diffusion_steps
567
  lambda_t = config.denoising_lambda * (1.0 + (1.0 - t_frac))
568
  energy += lambda_t * denoising_loss
569
 
570
- # Anchoring: homeostatic per-layer rho * ||h_l - h_l^init||^2
571
  for l in range(1, L + 1):
572
  rho_l = self.layer_rho[min(l - 1, len(self.layer_rho) - 1)]
573
- energy += rho_l * ((h[l] - h_init[l]) ** 2).sum()
574
 
575
- # Lateral inhibition: decorrelation penalty across tokens
576
  if config.lateral_inhibition > 0:
577
  for l in range(1, L + 1):
578
- h_norm = F.normalize(h[l], dim=-1) # (B, S, D)
579
- # Sample random token pairs to avoid O(S^2)
580
  S_dim = h_norm.shape[1]
581
  if S_dim > 16:
582
  idx = torch.randint(0, S_dim, (16,), device=h_norm.device)
@@ -986,7 +986,7 @@ class PCSHODLM(nn.Module):
986
  x_0: torch.Tensor,
987
  mask: torch.Tensor,
988
  t: torch.Tensor,
989
- param_lr_scale: float = 0.01,
990
  active_tokens: Optional[torch.Tensor] = None,
991
  ) -> Tuple[list[torch.Tensor], list[torch.Tensor], float]:
992
  """One step of UNIFIED inference-and-learning.
@@ -995,11 +995,11 @@ class PCSHODLM(nn.Module):
995
  This is the PC-native mode: settling IS learning.
996
 
997
  Two-timescale system:
998
- - Fast: hidden states settle via SHO dynamics (large eta)
999
- - Slow: parameters update via local errors (eta * param_lr_scale)
1000
 
1001
- Borkar (2008) two-timescale convergence guarantees apply when
1002
- param_lr_scale << 1.
1003
  """
1004
  config = self.config
1005
  L = self.n_active_layers
@@ -1046,14 +1046,10 @@ class PCSHODLM(nn.Module):
1046
  h_new.append(h_l_new)
1047
 
1048
  # === SLOW PROCESS: update parameters (learning) ===
1049
- # Adaptive two-timescale ratio (Borkar 2008):
1050
- # s* = (1 - rho^K)^2 / 2, where rho^K estimated from energy ratio
1051
- if len(self._unified_energies) >= 2:
1052
- e_ratio = self._unified_energies[-1] / max(self._unified_energies[0], 1e-8)
1053
- effective_rho_K = math.sqrt(max(e_ratio, 0.01))
1054
- param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - effective_rho_K) ** 2))
1055
-
1056
- # Using the SAME errors computed above — no extra forward pass
1057
  for l in range(L):
1058
  h_below = h[l].detach()
1059
  h_current = h[l + 1].detach()
@@ -1063,15 +1059,14 @@ class PCSHODLM(nn.Module):
1063
  with torch.no_grad():
1064
  tok_p, ch_p = self.precision_up[l](h_current, t)
1065
  eps = h_current - mu_up
1066
- local_loss = 0.5 * (eps * tok_p * ch_p * eps).sum() / x_0.shape[0]
1067
  local_loss.backward()
1068
 
1069
- # Apply scaled gradient with clipping
1070
  with torch.no_grad():
1071
  nn.utils.clip_grad_norm_(self.forward_blocks[l].parameters(), 1.0)
1072
  for p in self.forward_blocks[l].parameters():
1073
  if p.grad is not None:
1074
- p.data -= param_lr_scale * config.eta_base * p.grad
1075
  p.grad.zero_()
1076
 
1077
  # Top-down feedback
@@ -1082,28 +1077,58 @@ class PCSHODLM(nn.Module):
1082
  with torch.no_grad():
1083
  tok_p, ch_p = self.precision_down[l](h_current, t)
1084
  eps = h_current - mu_down
1085
- local_loss = 0.5 * (eps * tok_p * ch_p * eps).sum() / x_0.shape[0]
1086
  local_loss.backward()
1087
  with torch.no_grad():
1088
  nn.utils.clip_grad_norm_(self.feedback_blocks[l].parameters(), 1.0)
1089
  for p in self.feedback_blocks[l].parameters():
1090
  if p.grad is not None:
1091
- p.data -= param_lr_scale * config.eta_base * p.grad
1092
  p.grad.zero_()
1093
 
1094
- # Readout
1095
- logits = self.readout(self.readout_norm(h[L].detach()))
 
 
 
 
 
 
 
 
 
 
 
1096
  mask_logits = logits[mask]
1097
  mask_targets = x_0[mask]
1098
  if mask_logits.numel() > 0:
1099
  readout_loss = F.cross_entropy(mask_logits, mask_targets)
1100
  readout_loss.backward()
1101
- readout_params = list(self.readout.parameters()) + list(self.readout_norm.parameters())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1102
  with torch.no_grad():
1103
- nn.utils.clip_grad_norm_(readout_params, 1.0)
1104
- for p in readout_params:
1105
  if p.grad is not None:
1106
- p.data -= param_lr_scale * config.eta_base * p.grad
1107
  p.grad.zero_()
1108
 
1109
  return h_new, v_new, energy
@@ -1114,14 +1139,14 @@ class PCSHODLM(nn.Module):
1114
  x_0: torch.Tensor,
1115
  mask: torch.Tensor,
1116
  t: torch.Tensor,
1117
- param_lr_scale: float = 0.01,
1118
  prev_h: Optional[list[torch.Tensor]] = None,
1119
  prev_v: Optional[list[torch.Tensor]] = None,
1120
  ) -> Tuple[list[torch.Tensor], list[torch.Tensor], list[float]]:
1121
  """Run K unified steps (settling + learning simultaneously)."""
1122
  config = self.config
1123
  L = self.n_active_layers
1124
- self._unified_energies = [] # reset for adaptive ratio
1125
 
1126
  if prev_h is not None and prev_v is not None:
1127
  h = [h_init[0]] + [ph.detach() for ph in prev_h[1:]]
@@ -1142,7 +1167,7 @@ class PCSHODLM(nn.Module):
1142
  active_tokens = None
1143
 
1144
  h, v, energy = self.unified_step(
1145
- h, v, h_init, x_0, mask, t, param_lr_scale, active_tokens
1146
  )
1147
  energies.append(energy)
1148
 
@@ -1231,7 +1256,7 @@ class LocalParameterUpdater:
1231
 
1232
  # Precision-weighted error
1233
  eps_up = h_current - mu_up
1234
- local_loss_up = 0.5 * (eps_up * tok_p * ch_p * eps_up).sum() / x_0.shape[0]
1235
  local_loss_up.backward()
1236
  torch.nn.utils.clip_grad_norm_(model.forward_blocks[l].parameters(), 1.0)
1237
  self.forward_optimizers[l].step()
@@ -1248,7 +1273,7 @@ class LocalParameterUpdater:
1248
  tok_p, ch_p = model.precision_down[l](h_current, t)
1249
 
1250
  eps_down = h_current - mu_down
1251
- local_loss_down = 0.5 * (eps_down * tok_p * ch_p * eps_down).sum() / x_0.shape[0]
1252
  local_loss_down.backward()
1253
  torch.nn.utils.clip_grad_norm_(model.feedback_blocks[l].parameters(), 1.0)
1254
  self.feedback_optimizers[l].step()
@@ -1318,8 +1343,8 @@ class LocalParameterUpdater:
1318
  tok_p, ch_p = model.precision_up[l](h_settled[l + 1].detach(), t)
1319
  eps = (h_settled[l + 1].detach() - mu_up_list[l].detach())
1320
  # Log-likelihood of the error under the precision model
1321
- prec_loss += 0.5 * (eps * tok_p * ch_p * eps).sum() / B
1322
- prec_loss -= 0.5 * (tok_p.log().sum() + ch_p.log().sum()) / B
1323
 
1324
  if isinstance(prec_loss, torch.Tensor) and prec_loss.requires_grad:
1325
  prec_loss.backward()
 
530
  tok_p, ch_p = self.precision_down[l](h[l + 1], t)
531
  lambda_precs.append((tok_p, ch_p))
532
 
533
+ # Energy computation — per-token normalization.
534
+ # All terms use mean over D (channels), sum over B×S (batch×sequence).
535
+ # This makes prediction errors and denoising on the SAME per-token scale,
536
+ # so denoising_lambda directly controls their relative importance.
537
+ # Gradients remain large enough (sum over B×S) for effective settling.
538
  energy = 0.0
539
 
540
+ # Bottom-up consistency: Σ_{B,S} mean_D(0.5 * ||eps||_P^2)
541
  for l in range(L):
542
  tok_p, ch_p = gamma_precs[l]
543
  weighted_err = eps_up[l] * tok_p * ch_p # (B, S, D)
544
+ energy += 0.5 * (weighted_err * eps_up[l]).mean(dim=-1).sum()
545
 
546
+ # Top-down consistency
547
  for l in range(L - 1):
548
  tok_p, ch_p = lambda_precs[l]
549
  weighted_err = eps_down[l] * tok_p * ch_p
550
+ energy += 0.5 * (weighted_err * eps_down[l]).mean(dim=-1).sum()
551
 
552
+ # Denoising loss at top layer — sum over masked tokens (already per-token).
553
+ # HONEST SETTLING: entropy minimization pushes toward confident predictions
554
+ # without peeking at x_0. Cross-entropy with x_0 is used in param updates only.
 
555
  logits = self.readout(self.readout_norm(h[L])) # (B, S, V)
556
  mask_logits = logits[mask]
557
 
558
  if mask_logits.numel() > 0:
559
  if self._honest_settling:
 
560
  probs = F.softmax(mask_logits, dim=-1)
561
  entropy = -(probs * (probs + 1e-10).log()).sum(dim=-1) # per-token entropy
562
+ denoising_loss = entropy.sum() # sum over masked tokens
563
  else:
 
564
  mask_targets = x_0[mask]
565
+ denoising_loss = F.cross_entropy(mask_logits, mask_targets, reduction="sum")
566
 
567
  t_frac = t.float().mean() / config.n_diffusion_steps
568
  lambda_t = config.denoising_lambda * (1.0 + (1.0 - t_frac))
569
  energy += lambda_t * denoising_loss
570
 
571
+ # Anchoring: per-token normalization
572
  for l in range(1, L + 1):
573
  rho_l = self.layer_rho[min(l - 1, len(self.layer_rho) - 1)]
574
+ energy += rho_l * ((h[l] - h_init[l]) ** 2).mean(dim=-1).sum()
575
 
576
+ # Lateral inhibition
577
  if config.lateral_inhibition > 0:
578
  for l in range(1, L + 1):
579
+ h_norm = F.normalize(h[l], dim=-1)
 
580
  S_dim = h_norm.shape[1]
581
  if S_dim > 16:
582
  idx = torch.randint(0, S_dim, (16,), device=h_norm.device)
 
986
  x_0: torch.Tensor,
987
  mask: torch.Tensor,
988
  t: torch.Tensor,
989
+ param_lr: float = 3e-4,
990
  active_tokens: Optional[torch.Tensor] = None,
991
  ) -> Tuple[list[torch.Tensor], list[torch.Tensor], float]:
992
  """One step of UNIFIED inference-and-learning.
 
995
  This is the PC-native mode: settling IS learning.
996
 
997
  Two-timescale system:
998
+ - Fast: hidden states settle via SHO dynamics (large eta ~0.1)
999
+ - Slow: parameters update via local errors (param_lr ~3e-4)
1000
 
1001
+ The ratio eta/param_lr ≈ 300 satisfies Borkar (2008) two-timescale
1002
+ separation, while param_lr is large enough for practical learning.
1003
  """
1004
  config = self.config
1005
  L = self.n_active_layers
 
1046
  h_new.append(h_l_new)
1047
 
1048
  # === SLOW PROCESS: update parameters (learning) ===
1049
+ # param_lr is the external learning rate (e.g. 3e-4)
1050
+ # Two-timescale ratio: eta_base/param_lr ≈ 300 (hidden states settle ~300x faster)
1051
+ scaled_lr = param_lr
1052
+
 
 
 
 
1053
  for l in range(L):
1054
  h_below = h[l].detach()
1055
  h_current = h[l + 1].detach()
 
1059
  with torch.no_grad():
1060
  tok_p, ch_p = self.precision_up[l](h_current, t)
1061
  eps = h_current - mu_up
1062
+ local_loss = 0.5 * (eps * tok_p * ch_p * eps).mean(dim=-1).sum()
1063
  local_loss.backward()
1064
 
 
1065
  with torch.no_grad():
1066
  nn.utils.clip_grad_norm_(self.forward_blocks[l].parameters(), 1.0)
1067
  for p in self.forward_blocks[l].parameters():
1068
  if p.grad is not None:
1069
+ p.data -= scaled_lr * p.grad
1070
  p.grad.zero_()
1071
 
1072
  # Top-down feedback
 
1077
  with torch.no_grad():
1078
  tok_p, ch_p = self.precision_down[l](h_current, t)
1079
  eps = h_current - mu_down
1080
+ local_loss = 0.5 * (eps * tok_p * ch_p * eps).mean(dim=-1).sum()
1081
  local_loss.backward()
1082
  with torch.no_grad():
1083
  nn.utils.clip_grad_norm_(self.feedback_blocks[l].parameters(), 1.0)
1084
  for p in self.feedback_blocks[l].parameters():
1085
  if p.grad is not None:
1086
+ p.data -= scaled_lr * p.grad
1087
  p.grad.zero_()
1088
 
1089
+ # Task-directed update: readout loss propagates through all blocks.
1090
+ # This gives every component (forward blocks, readout, embeddings)
1091
+ # direct task signal — the cross-entropy gradient tells each layer
1092
+ # what features to produce for correct token prediction.
1093
+ # Combined with the local consistency updates above, each forward block
1094
+ # receives TWO gradients: (1) local prediction error and (2) task loss.
1095
+ x_t_input = x_0.clone()
1096
+ x_t_input[mask] = config.mask_token_id
1097
+ h_0_fresh = self.embed_input(x_t_input, t)
1098
+ h_through = h_0_fresh
1099
+ for block in self.forward_blocks:
1100
+ h_through = block(h_through)
1101
+ logits = self.readout(self.readout_norm(h_through))
1102
  mask_logits = logits[mask]
1103
  mask_targets = x_0[mask]
1104
  if mask_logits.numel() > 0:
1105
  readout_loss = F.cross_entropy(mask_logits, mask_targets)
1106
  readout_loss.backward()
1107
+ # Update ALL trainable components with task signal
1108
+ all_params = list(self.parameters())
1109
+ with torch.no_grad():
1110
+ nn.utils.clip_grad_norm_(all_params, 1.0)
1111
+ for p in all_params:
1112
+ if p.grad is not None:
1113
+ p.data -= scaled_lr * p.grad
1114
+ p.grad.zero_()
1115
+
1116
+ # Precision heads: calibrate using settled error statistics
1117
+ prec_params = list(self.precision_up.parameters()) + list(self.precision_down.parameters())
1118
+ prec_loss = 0.0
1119
+ for l in range(L):
1120
+ tok_p, ch_p = self.precision_up[l](h[l + 1].detach(), t)
1121
+ eps = (h[l + 1].detach() - self.forward_blocks[l](h[l].detach()).detach())
1122
+ # Gaussian NLL: 0.5 * P * eps^2 - 0.5 * log(P)
1123
+ prec_loss = prec_loss + 0.5 * (eps * tok_p * ch_p * eps).mean(dim=-1).sum()
1124
+ prec_loss = prec_loss - 0.5 * (tok_p.log().mean(dim=-1).sum() + ch_p.log().mean(dim=-1).sum())
1125
+ if isinstance(prec_loss, torch.Tensor) and prec_loss.requires_grad:
1126
+ prec_loss.backward()
1127
  with torch.no_grad():
1128
+ nn.utils.clip_grad_norm_(prec_params, 1.0)
1129
+ for p in prec_params:
1130
  if p.grad is not None:
1131
+ p.data -= scaled_lr * 0.1 * p.grad # slower for precision
1132
  p.grad.zero_()
1133
 
1134
  return h_new, v_new, energy
 
1139
  x_0: torch.Tensor,
1140
  mask: torch.Tensor,
1141
  t: torch.Tensor,
1142
+ param_lr: float = 3e-4,
1143
  prev_h: Optional[list[torch.Tensor]] = None,
1144
  prev_v: Optional[list[torch.Tensor]] = None,
1145
  ) -> Tuple[list[torch.Tensor], list[torch.Tensor], list[float]]:
1146
  """Run K unified steps (settling + learning simultaneously)."""
1147
  config = self.config
1148
  L = self.n_active_layers
1149
+ self._unified_energies = [] # reset
1150
 
1151
  if prev_h is not None and prev_v is not None:
1152
  h = [h_init[0]] + [ph.detach() for ph in prev_h[1:]]
 
1167
  active_tokens = None
1168
 
1169
  h, v, energy = self.unified_step(
1170
+ h, v, h_init, x_0, mask, t, param_lr, active_tokens
1171
  )
1172
  energies.append(energy)
1173
 
 
1256
 
1257
  # Precision-weighted error
1258
  eps_up = h_current - mu_up
1259
+ local_loss_up = 0.5 * (eps_up * tok_p * ch_p * eps_up).mean(dim=-1).sum()
1260
  local_loss_up.backward()
1261
  torch.nn.utils.clip_grad_norm_(model.forward_blocks[l].parameters(), 1.0)
1262
  self.forward_optimizers[l].step()
 
1273
  tok_p, ch_p = model.precision_down[l](h_current, t)
1274
 
1275
  eps_down = h_current - mu_down
1276
+ local_loss_down = 0.5 * (eps_down * tok_p * ch_p * eps_down).mean(dim=-1).sum()
1277
  local_loss_down.backward()
1278
  torch.nn.utils.clip_grad_norm_(model.feedback_blocks[l].parameters(), 1.0)
1279
  self.feedback_optimizers[l].step()
 
1343
  tok_p, ch_p = model.precision_up[l](h_settled[l + 1].detach(), t)
1344
  eps = (h_settled[l + 1].detach() - mu_up_list[l].detach())
1345
  # Log-likelihood of the error under the precision model
1346
+ prec_loss += 0.5 * (eps * tok_p * ch_p * eps).mean()
1347
+ prec_loss -= 0.5 * (tok_p.log().mean() + ch_p.log().mean())
1348
 
1349
  if isinstance(prec_loss, torch.Tensor) and prec_loss.requires_grad:
1350
  prec_loss.backward()