thefinalboss commited on
Commit
1838baa
·
verified ·
1 Parent(s): a140a7f

Body growth lock: vocab 266 fixed, expert phases copied, train hit counter.

Browse files
README.md CHANGED
@@ -36,6 +36,8 @@ Three properties, and they are the product, not a slogan.
36
 
37
  What was accepted for this fork: Atomizer spans adapted to Fractus integer ticks, vocab 266, train from scratch, x8 left untouched. Packet features (320-d) stay off the id stream. The boundary marker is the Atomizer decision the head can see.
38
 
 
 
39
  ## What this fork is
40
 
41
  Fractus CTE is not a transformer. It keeps a residual thought state `h`, advances it tick by tick through a stack of blocks (linear attention carry `(S, z)`, Kuramoto phase clock, phase-routed MoE), and emits a next-id distribution from a head tied to the input embedding.
 
36
 
37
  What was accepted for this fork: Atomizer spans adapted to Fractus integer ticks, vocab 266, train from scratch, x8 left untouched. Packet features (320-d) stay off the id stream. The boundary marker is the Atomizer decision the head can see.
38
 
39
+ **It grows without bound, in the body only.** `grow_atom` zero-pads a trained engine into a larger one: `d_model`, depth, experts, oscillator count, coupling rank. Old rows are copied, new rows start neutral, expert phases of the copied experts are kept so the router does not forget who was who. The vocab stays 266. Growing the head would orphan the Atomizer. Runtime self-mod (`maybe_grow` / `add_expert`) still adds one zero-init expert near the dominant phase; `tick_chunk_train` now feeds the same hit counter as `tick`, so that path can fire during training, not only during single-tick generation. A CPU lock checks this: 32→48 width, 1→2 blocks, 2→4 experts, phase copy, tied head, backward, then one live `add_expert`. That is the mechanic. It is not a trained 1B.
40
+
41
  ## What this fork is
42
 
43
  Fractus CTE is not a transformer. It keeps a residual thought state `h`, advances it tick by tick through a stack of blocks (linear attention carry `(S, z)`, Kuramoto phase clock, phase-routed MoE), and emits a next-id distribution from a head tied to the input embedding.
fractus/continuous_engine.py CHANGED
@@ -518,6 +518,20 @@ class ContinuousThoughtEngine(nn.Module):
518
 
519
  self.thought_state = h[:, -1:, :].detach()
520
  logits = self.output_head(h) # (B, C, vocab)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521
  return logits, total_lb
522
 
523
  def tick_chunk_train_ce(self, observations: torch.Tensor,
 
518
 
519
  self.thought_state = h[:, -1:, :].detach()
520
  logits = self.output_head(h) # (B, C, vocab)
521
+
522
+ # Same hit counter as tick(), so maybe_grow can fire on the train path.
523
+ self._tick_count = getattr(self, "_tick_count", 0) + int(C)
524
+ n_exp = self.blocks[0].moe.n_experts
525
+ if not hasattr(self, "_expert_hits") or self._expert_hits.numel() != n_exp:
526
+ self._expert_hits = torch.zeros(n_exp)
527
+ with torch.no_grad():
528
+ gates = self.blocks[0].moe._compute_gates(
529
+ self.blocks[0].kuramoto_phases[:, 0:1, :]
530
+ )
531
+ topk_idx = gates.topk(self.blocks[0].moe.top_k, dim=-1).indices
532
+ for e in range(n_exp):
533
+ self._expert_hits[e] += (topk_idx == e).sum().item()
534
+
535
  return logits, total_lb
536
 
537
  def tick_chunk_train_ce(self, observations: torch.Tensor,
fractus/grow.py CHANGED
@@ -126,6 +126,14 @@ def _transfer_block_weights(old_blk, new_blk, old_d: int, new_d: int):
126
  moe_new = new_blk.moe
127
  e_copy = min(moe_old.n_experts, moe_new.n_experts)
128
 
 
 
 
 
 
 
 
 
129
  if moe_old.expert_rank is not None and moe_new.expert_rank is not None:
130
  for param_name in ["U1", "V1", "U2", "V2", "scale1", "scale2", "b1", "b2"]:
131
  old_p = getattr(moe_old, param_name).data
@@ -222,6 +230,29 @@ def grow_cte(old_engine, new_config: Dict[str, Any]):
222
  return new_engine
223
 
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  def grow_summary(old_engine, new_engine) -> dict:
226
  """Report what changed between old and new engine."""
227
  return {
 
126
  moe_new = new_blk.moe
127
  e_copy = min(moe_old.n_experts, moe_new.n_experts)
128
 
129
+ # Expert phases are the routing identity. A fresh Farey table on the new
130
+ # block would send old experts to different gates. Keep the copied rows.
131
+ if hasattr(moe_old, "expert_phases") and hasattr(moe_new, "expert_phases"):
132
+ old_ph = moe_old.expert_phases.data
133
+ new_ph = moe_new.expert_phases.data
134
+ n_copy = min(old_ph.shape[0], new_ph.shape[0], e_copy)
135
+ new_ph[:n_copy] = old_ph[:n_copy]
136
+
137
  if moe_old.expert_rank is not None and moe_new.expert_rank is not None:
138
  for param_name in ["U1", "V1", "U2", "V2", "scale1", "scale2", "b1", "b2"]:
139
  old_p = getattr(moe_old, param_name).data
 
230
  return new_engine
231
 
232
 
233
+ def grow_atom(old_engine, new_config: Dict[str, Any]):
234
+ """Grow width, depth, experts, oscillators. Never the Atom vocab.
235
+
236
+ The id stream is closed at 266 (bytes + specials + boundary markers).
237
+ Growing the head would orphan the tokenizer. Infinite growth is the
238
+ body: d_model, n_layers, n_experts, rank, oscillators. The head stays.
239
+ """
240
+ from .atom_tokenizer import VOCAB_SIZE
241
+
242
+ if old_engine.vocab_size != VOCAB_SIZE:
243
+ raise ValueError(
244
+ f"grow_atom requires vocab {VOCAB_SIZE}, got {old_engine.vocab_size}"
245
+ )
246
+ cfg = dict(new_config)
247
+ cfg["vocab_size"] = VOCAB_SIZE
248
+ grown = grow_cte(old_engine, cfg)
249
+ if grown.vocab_size != VOCAB_SIZE:
250
+ raise RuntimeError("grow_atom changed vocab")
251
+ if grown.output_head.weight.data_ptr() != grown.observe.weight.data_ptr():
252
+ grown.output_head.weight = grown.observe.weight
253
+ return grown
254
+
255
+
256
  def grow_summary(old_engine, new_engine) -> dict:
257
  """Report what changed between old and new engine."""
258
  return {
tests/test_atom_grow.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grow lock for the Atom fork: body grows, vocab 266 does not."""
2
+
3
+ import os
4
+ import sys
5
+
6
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+
11
+ from fractus.atom_tokenizer import VOCAB_SIZE, AtomFractusTokenizer
12
+ from fractus.continuous_engine import ContinuousThoughtEngine
13
+ from fractus.grow import grow_atom, grow_summary
14
+
15
+
16
+ def test_grow_body_keeps_vocab_and_trains():
17
+ tok = AtomFractusTokenizer()
18
+ ids = torch.tensor(tok.encode("Fractus grandit. Le vocabulaire ne grandit pas."), dtype=torch.long)
19
+ assert int(ids.max()) < VOCAB_SIZE
20
+
21
+ eng = ContinuousThoughtEngine(
22
+ vocab_size=VOCAB_SIZE, d_model=32, n_heads=4, d_head=8, n_levels=1,
23
+ n_oscillators=4, coupling_rank=2, n_experts=2, top_k=1,
24
+ expert_d_ff=32, siren_rank=4, n_layers=1,
25
+ )
26
+ before = sum(p.numel() for p in eng.parameters())
27
+ grown = grow_atom(eng, dict(
28
+ d_model=48, n_layers=2, n_experts=4, n_oscillators=6, coupling_rank=2,
29
+ n_heads=4, d_head=12, siren_rank=4, expert_d_ff=32, top_k=2,
30
+ ))
31
+ after = sum(p.numel() for p in grown.parameters())
32
+ assert grown.vocab_size == VOCAB_SIZE
33
+ assert grown.output_head.weight.data_ptr() == grown.observe.weight.data_ptr()
34
+ assert len(grown.blocks) == 2
35
+ assert grown.blocks[0].moe.n_experts == 4
36
+ assert after > before
37
+ # Old expert phase survived the copy.
38
+ assert torch.allclose(grown.blocks[0].moe.expert_phases[:2], eng.blocks[0].moe.expert_phases[:2])
39
+
40
+ chunk = ids[:16].unsqueeze(0)
41
+ target = ids[1:17]
42
+ grown.train()
43
+ logits, lb = grown.tick_chunk_train(chunk)
44
+ loss = F.cross_entropy(logits.reshape(-1, VOCAB_SIZE), target) + 0.01 * lb
45
+ loss.backward()
46
+ assert logits.shape[-1] == VOCAB_SIZE
47
+
48
+ new_idx = grown.blocks[0].moe.add_expert(dominant_idx=0)
49
+ assert new_idx == 4
50
+ assert grown.blocks[0].moe.n_experts == 5
51
+ grown.reset_thought(1)
52
+ logits2, _ = grown.tick_chunk_train(chunk)
53
+ assert logits2.shape[-1] == VOCAB_SIZE
54
+ print(grow_summary(eng, grown))
55
+
56
+
57
+ if __name__ == "__main__":
58
+ test_grow_body_keeps_vocab_and_trains()
59
+ print("grow ok")