amer224 commited on
Commit
fee301d
Β·
verified Β·
1 Parent(s): 8022f91

Add brains/sovereign-nano/model_nano.py

Browse files
Files changed (1) hide show
  1. brains/sovereign-nano/model_nano.py +36 -25
brains/sovereign-nano/model_nano.py CHANGED
@@ -854,12 +854,15 @@ def make_nano(cfg: Optional[NanoConfig] = None,
854
  return Nano(cfg)
855
 
856
 
857
- def load_real_shard():
858
- """Try the REAL shard first (via $HF_TOKEN), then a local copy."""
 
 
 
859
  for candidate in ("shard_v2_1786707781_27_23.npz",
860
  "rl/shards_v2/shard_v2_1786707781_27_23.npz"):
861
  if os.path.exists(candidate):
862
- return np.load(candidate)
863
  try:
864
  from huggingface_hub import hf_hub_download
865
  token = os.environ.get("HF_TOKEN")
@@ -867,7 +870,7 @@ def load_real_shard():
867
  return None
868
  path = hf_hub_download(HF_DATASET, HF_SHARD, repo_type="dataset",
869
  token=token, local_dir="/tmp/nano_real")
870
- return np.load(path)
871
  except Exception as e:
872
  print(f"real shard fetch failed ({str(e)[:100]}) β€” using replica")
873
  return None
@@ -926,7 +929,7 @@ if __name__ == "__main__":
926
  f"[spine {bd['spine']:,} | decoder {bd['decoder']:,} | "
927
  f"heads {bd['heads']:,} | mem {bd['mem']:,}]")
928
 
929
- d = load_real_shard()
930
  if d is not None:
931
  print("REAL shard loaded β€” schema asserts below:")
932
  print(f" keys: {sorted(k for k in d.keys())}")
@@ -943,23 +946,28 @@ if __name__ == "__main__":
943
  print(f"prep: {B} frames from {prep['real_episodes']} episodes "
944
  f"({prep['real_frames']} total frames in shard)")
945
 
946
- # forward (contract)
947
- click, kind_logits, pct, value = net(prep["rgb"], prep["nums"],
948
- rtg=prep["rtg"])
949
- assert click.shape == (B, 1024), click.shape
950
- assert kind_logits.shape == (B, 3), kind_logits.shape
951
- assert pct.shape == (B,), pct.shape
952
- assert value.shape == (B,), value.shape
953
- print(f"forward: {tuple(click.shape)} {tuple(kind_logits.shape)} "
954
- f"{tuple(pct.shape)} {tuple(value.shape)} β€” PASS")
955
-
956
- # act at B=4 β€” logprob/entropy MUST be (B,)
957
- a = net.act(prep["rgb"][:4], prep["nums"][:4], rtg=prep["rtg"][:4])
958
- assert a["logprob"].shape == (4,), a["logprob"].shape
959
- assert a["entropy"].shape == (4,), a["entropy"].shape
960
- print(f"act(B=4): logprob {tuple(a['logprob'].shape)} | entropy "
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)
@@ -975,10 +983,13 @@ if __name__ == "__main__":
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")
 
854
  return Nano(cfg)
855
 
856
 
857
+ def load_real_shard(mmap: bool = False):
858
+ """Try the REAL shard first (via $HF_TOKEN), then a local copy.
859
+ mmap=True memory-maps the npz (tiny mode on a 2GB box: the full
860
+ arrays never sit in RAM; prep slices before any float32 conversion)."""
861
+ mode = "r" if mmap else None
862
  for candidate in ("shard_v2_1786707781_27_23.npz",
863
  "rl/shards_v2/shard_v2_1786707781_27_23.npz"):
864
  if os.path.exists(candidate):
865
+ return np.load(candidate, mmap_mode=mode)
866
  try:
867
  from huggingface_hub import hf_hub_download
868
  token = os.environ.get("HF_TOKEN")
 
870
  return None
871
  path = hf_hub_download(HF_DATASET, HF_SHARD, repo_type="dataset",
872
  token=token, local_dir="/tmp/nano_real")
873
+ return np.load(path, mmap_mode=mode)
874
  except Exception as e:
875
  print(f"real shard fetch failed ({str(e)[:100]}) β€” using replica")
876
  return None
 
929
  f"[spine {bd['spine']:,} | decoder {bd['decoder']:,} | "
930
  f"heads {bd['heads']:,} | mem {bd['mem']:,}]")
931
 
932
+ d = load_real_shard(mmap=tiny)
933
  if d is not None:
934
  print("REAL shard loaded β€” schema asserts below:")
935
  print(f" keys: {sorted(k for k in d.keys())}")
 
946
  print(f"prep: {B} frames from {prep['real_episodes']} episodes "
947
  f"({prep['real_frames']} total frames in shard)")
948
 
949
+ # forward + act probes β€” no_grad (B's 17-Aug note: the probes were
950
+ # grad-enabled and never freed, holding full-graph activations at
951
+ # B=8/16 β€” that was the ~1.5GB tiny-mode peak. no_grad + del keeps
952
+ # the only grad graph as the L=4 loss below.)
953
+ with torch.no_grad():
954
+ click, kind_logits, pct, value = net(prep["rgb"], prep["nums"],
955
+ rtg=prep["rtg"])
956
+ assert click.shape == (B, 1024), click.shape
957
+ assert kind_logits.shape == (B, 3), kind_logits.shape
958
+ assert pct.shape == (B,), pct.shape
959
+ assert value.shape == (B,), value.shape
960
+ print(f"forward: {tuple(click.shape)} {tuple(kind_logits.shape)} "
961
+ f"{tuple(pct.shape)} {tuple(value.shape)} β€” PASS")
962
+
963
+ # act at B=4 β€” logprob/entropy MUST be (B,)
964
+ a = net.act(prep["rgb"][:4], prep["nums"][:4], rtg=prep["rtg"][:4])
965
+ assert a["logprob"].shape == (4,), a["logprob"].shape
966
+ assert a["entropy"].shape == (4,), a["entropy"].shape
967
+ print(f"act(B=4): logprob {tuple(a['logprob'].shape)} | entropy "
968
+ f"{tuple(a['entropy'].shape)} | state "
969
+ f"{tuple(a['state'].shape)} β€” PASS")
970
+ del click, kind_logits, pct, value, a
971
 
972
  # stage-a loss + backward (tiny mode: 4-sample slice keeps one small
973
  # grad graph instead of two bs16 graphs)
 
983
  nums_next=prep["econ_t"][:L], w=prep["w"][:L])
984
  assert torch.isfinite(loss), "non-finite loss"
985
  # pipeline review finding 1 (asserted): with the 0.1x heat-tower init,
986
+ # the cell CE must NOT be over-confident. NOTE (B, 17 Aug): on the
987
+ # real shard 1786707781 the init cell CE measures 8.81/9.19 β€” the
988
+ # ideal uniform floor ln(1024)β‰ˆ6.93 is unreachable because the
989
+ # mixer's nonzero features survive the 0.1x tower conv. Threshold
990
+ # <9.5 (B's calibrated value) still catches the 16+ disease class.
991
  init_cell = float(terms["cell_nll"])
992
+ assert init_cell < 9.5, \
993
  f"init cell CE {init_cell:.2f} β€” heat init over-confident (regressed?)"
994
  loss.backward()
995
  print(f"loss: {loss.item():.4f} β€” backward OK β€” PASS")