amer224 commited on
Commit
ac83639
Β·
verified Β·
1 Parent(s): e005d5e

Add brains/sovereign-nano/model_nano.py

Browse files
Files changed (1) hide show
  1. brains/sovereign-nano/model_nano.py +40 -11
brains/sovereign-nano/model_nano.py CHANGED
@@ -45,6 +45,7 @@ torch + numpy only. Run: python model_nano.py
45
  from __future__ import annotations
46
 
47
  import os
 
48
  from dataclasses import dataclass
49
  from typing import Optional, Tuple
50
 
@@ -318,6 +319,19 @@ class Nano(nn.Module):
318
 
319
  self.apply(_init_weights)
320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
  # -- helpers ------------------------------------------------------------
322
 
323
  @staticmethod
@@ -567,9 +581,11 @@ def stage_a_loss(out: dict, kind: torch.Tensor, cell: torch.Tensor,
567
  kind_nll = F.cross_entropy(out["kind_logits"], kind, reduction="none",
568
  label_smoothing=0.05)
569
  # v3 review bug 2: CE((B,3,g*g),(B,)) crashes β€” select the taken-kind row
 
 
570
  cell_nll = F.cross_entropy(
571
  out["cell_logits"][torch.arange(B, device=kind.device), kind.long()],
572
- cell.long(), reduction="none")
573
  pct_nll = -(Beta(out["pct_params"][0], out["pct_params"][1])
574
  .log_prob(pct_t.clamp(EPS, 1 - EPS)))
575
  pct_nll = pct_nll * (kind != 2).float() # bank: pct undefined
@@ -895,6 +911,11 @@ def synthetic_shard() -> dict:
895
 
896
  if __name__ == "__main__":
897
  print("== SOVEREIGN-nano smoke ==")
 
 
 
 
 
898
  torch.manual_seed(0)
899
 
900
  net = make_nano()
@@ -917,7 +938,7 @@ if __name__ == "__main__":
917
  "building a schema-EXACT synthetic replica")
918
  d = synthetic_shard()
919
 
920
- prep = prep_shard(d, max_frames=16)
921
  B = prep["n_sel"]
922
  print(f"prep: {B} frames from {prep['real_episodes']} episodes "
923
  f"({prep['real_frames']} total frames in shard)")
@@ -940,17 +961,25 @@ if __name__ == "__main__":
940
  f"{tuple(a['entropy'].shape)} | state "
941
  f"{tuple(a['state'].shape)} β€” PASS")
942
 
943
- # stage-a loss + backward
944
- out = net(prep["rgb"], prep["nums"], rtg=prep["rtg"],
945
- cell=prep["cell"], return_all=True)
 
 
946
  loss, terms = stage_a_loss(
947
- out, prep["kind"], prep["cell"], prep["pct"],
948
- ret=prep["ret"], win_lab=prep["win_lab"],
949
- lab64=prep["lab64"], lab64_next=prep["lab64_next"],
950
- gate_mask=prep["gate_mask"], gate_valid=prep["gate_valid"],
951
- threat=prep["threat"], expand=prep["expand"],
952
- nums_next=prep["econ_t"], w=prep["w"])
953
  assert torch.isfinite(loss), "non-finite loss"
 
 
 
 
 
 
954
  loss.backward()
955
  print(f"loss: {loss.item():.4f} β€” backward OK β€” PASS")
956
  print("terms: " + " ".join(f"{k}={float(v):.3f}" for k, v in
 
45
  from __future__ import annotations
46
 
47
  import os
48
+ import sys
49
  from dataclasses import dataclass
50
  from typing import Optional, Tuple
51
 
 
319
 
320
  self.apply(_init_weights)
321
 
322
+ # ANTI-OVER-CONFIDENCE INIT (pipeline review finding 1, 15 Aug):
323
+ # at default init the cell CE started at ~16.05 instead of the
324
+ # uniform-floor ln(gΒ²)β‰ˆ6.93 β€” the tower's final conv + 1x1 made
325
+ # peaked logits. Scale the final conv by 0.1x and zero its bias
326
+ # so the heat starts near-uniform. The gate head's sigmoid(0)=0.5
327
+ # adds only a constant -0.693 logit, which does not shift the
328
+ # softmax. The smoke ASSERTS the resulting init cell CE < 8.5.
329
+ with torch.no_grad():
330
+ w = self.heat_tower[-1].weight
331
+ w.mul_(0.1)
332
+ if self.heat_tower[-1].bias is not None:
333
+ self.heat_tower[-1].bias.zero_()
334
+
335
  # -- helpers ------------------------------------------------------------
336
 
337
  @staticmethod
 
581
  kind_nll = F.cross_entropy(out["kind_logits"], kind, reduction="none",
582
  label_smoothing=0.05)
583
  # v3 review bug 2: CE((B,3,g*g),(B,)) crashes β€” select the taken-kind row
584
+ # + label smoothing 0.02 (pipeline review finding 1: keeps cell peaks
585
+ # soft during Stage-A; complements the 0.1x heat init)
586
  cell_nll = F.cross_entropy(
587
  out["cell_logits"][torch.arange(B, device=kind.device), kind.long()],
588
+ cell.long(), reduction="none", label_smoothing=0.02)
589
  pct_nll = -(Beta(out["pct_params"][0], out["pct_params"][1])
590
  .log_prob(pct_t.clamp(EPS, 1 - EPS)))
591
  pct_nll = pct_nll * (kind != 2).float() # bank: pct undefined
 
911
 
912
  if __name__ == "__main__":
913
  print("== SOVEREIGN-nano smoke ==")
914
+ tiny = "--tiny" in sys.argv # pipeline review finding 2:
915
+ # small boxes get a low-memory path
916
+ if tiny:
917
+ print("tiny mode: 8 frames, loss on a 4-sample slice "
918
+ "(peak ~0.5GB vs ~1.5-2GB full)")
919
  torch.manual_seed(0)
920
 
921
  net = make_nano()
 
938
  "building a schema-EXACT synthetic replica")
939
  d = synthetic_shard()
940
 
941
+ prep = prep_shard(d, max_frames=8 if tiny else 16)
942
  B = prep["n_sel"]
943
  print(f"prep: {B} frames from {prep['real_episodes']} episodes "
944
  f"({prep['real_frames']} total frames in shard)")
 
961
  f"{tuple(a['entropy'].shape)} | state "
962
  f"{tuple(a['state'].shape)} β€” PASS")
963
 
964
+ # stage-a loss + backward (tiny mode: 4-sample slice keeps one small
965
+ # grad graph instead of two bs16 graphs)
966
+ L = min(B, 4) if tiny else B
967
+ loss_out = net(prep["rgb"][:L], prep["nums"][:L], rtg=prep["rtg"][:L],
968
+ cell=prep["cell"][:L], return_all=True)
969
  loss, terms = stage_a_loss(
970
+ loss_out, prep["kind"][:L], prep["cell"][:L], prep["pct"][:L],
971
+ ret=prep["ret"][:L], win_lab=prep["win_lab"][:L],
972
+ lab64=prep["lab64"][:L], lab64_next=prep["lab64_next"][:L],
973
+ gate_mask=prep["gate_mask"][:L], gate_valid=prep["gate_valid"][:L],
974
+ threat=prep["threat"][:L], expand=prep["expand"][:L],
975
+ nums_next=prep["econ_t"][:L], w=prep["w"][:L])
976
  assert torch.isfinite(loss), "non-finite loss"
977
+ # pipeline review finding 1 (asserted): with the 0.1x heat-tower init,
978
+ # the cell CE must start at the uniform floor ln(1024)β‰ˆ6.93 β€” NOT the
979
+ # over-confident 16+ of the default init
980
+ init_cell = float(terms["cell_nll"])
981
+ assert init_cell < 8.5, \
982
+ f"init cell CE {init_cell:.2f} β€” heat init over-confident (regressed?)"
983
  loss.backward()
984
  print(f"loss: {loss.item():.4f} β€” backward OK β€” PASS")
985
  print("terms: " + " ".join(f"{k}={float(v):.3f}" for k, v in