thefinalboss commited on
Commit
f29b6ae
·
verified ·
1 Parent(s): de10ad1

opt: cumsum/chunked attention kernels, memory-flat CE, block checkpointing, v2 trainer (proven equivalent, 46 tests)

Browse files
Files changed (1) hide show
  1. tests/test_block_ckpt.py +81 -0
tests/test_block_ckpt.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Equivalence proof: block-level activation checkpointing (opt 6).
2
+
3
+ block_ckpt=True wraps each block's PURE core in torch.utils.checkpoint.
4
+ Danger zone: tick_chunk_core READS the carry (attn_S/attn_z) then OVERWRITES
5
+ it. A naive whole-block checkpoint would make backward's recompute read the
6
+ NEW carry — wrong gradients. The refactor keeps the read-mutate cycle
7
+ outside the checkpointed region; these tests prove loss, gradients AND the
8
+ carry evolution across consecutive chunks are identical with and without.
9
+ """
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import pytest
14
+ import torch
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
17
+
18
+ from fractus.continuous_engine import ContinuousThoughtEngine
19
+
20
+ CFG = dict(vocab_size=1000, d_model=64, n_heads=1, d_head=64,
21
+ n_levels=2, n_oscillators=8, coupling_rank=4,
22
+ n_experts=8, top_k=2, expert_d_ff=64, siren_rank=16,
23
+ n_layers=3) # 3 blocks: carry chain matters
24
+
25
+
26
+ def _run(block_ckpt, n_chunks=3):
27
+ torch.manual_seed(42)
28
+ eng = ContinuousThoughtEngine(**CFG)
29
+ eng.reset_thought(batch_size=2)
30
+ opt = torch.optim.SGD(eng.parameters(), lr=7e-4, momentum=0.9)
31
+ g = torch.Generator().manual_seed(7)
32
+ out = []
33
+ for _ in range(n_chunks):
34
+ toks = torch.randint(0, 1000, (2, 17), generator=g)
35
+ chunk, target = toks[:, :-1], toks[:, 1:]
36
+ ce, lb = eng.tick_chunk_train_ce(chunk, target, ce_chunk=64,
37
+ block_ckpt=block_ckpt)
38
+ loss = ce + 0.02 * lb
39
+ opt.zero_grad(set_to_none=True)
40
+ loss.backward()
41
+ opt.step()
42
+ snap = [(b.attn_S.clone(), b.attn_z.clone()) for b in eng.blocks]
43
+ out.append((ce.detach().clone(), lb.detach().clone(), snap))
44
+ grads = {n: p.grad.clone() for n, p in eng.named_parameters()
45
+ if p.grad is not None}
46
+ return out, grads
47
+
48
+
49
+ def test_block_ckpt_matches_unchecked():
50
+ """Losses, per-block carries after EACH chunk, and all param grads equal."""
51
+ ref, grads_ref = _run(False)
52
+ ck, grads_ck = _run(True)
53
+ for i, ((ce_r, lb_r, snap_r), (ce_c, lb_c, snap_c)) in enumerate(zip(ref, ck)):
54
+ assert torch.allclose(ce_r, ce_c, atol=1e-5, rtol=1e-5), \
55
+ f"chunk {i}: ce {ce_r.item():.6f} vs {ce_c.item():.6f}"
56
+ assert torch.allclose(lb_r, lb_c, atol=1e-6), f"chunk {i}: lb differs"
57
+ # THE point: carry evolution identical across the chunk sequence,
58
+ # for every block in the chain
59
+ for j, ((S_r, z_r), (S_c, z_c)) in enumerate(zip(snap_r, snap_c)):
60
+ assert torch.allclose(S_r, S_c, atol=1e-4, rtol=1e-4), \
61
+ f"chunk {i} block {j}: attn_S diverged (max {(S_r - S_c).abs().max():.2e})"
62
+ assert torch.allclose(z_r, z_c, atol=1e-5, rtol=1e-4), \
63
+ f"chunk {i} block {j}: attn_z diverged"
64
+ assert set(grads_ref) == set(grads_ck)
65
+ for name in grads_ref:
66
+ gr, gc_ = grads_ref[name], grads_ck[name]
67
+ assert torch.allclose(gr, gc_, atol=1e-4, rtol=1e-3), \
68
+ f"grad mismatch on {name}: max {(gr - gc_).abs().max():.3e}"
69
+
70
+
71
+ def test_block_ckpt_off_is_default_behavior():
72
+ """block_ckpt=False must hit exactly the legacy path."""
73
+ from fractus.continuous_engine import ContinuousThoughtEngine as E
74
+ import inspect
75
+ src = inspect.getsource(E.tick_chunk_train_ce)
76
+ assert "use_reentrant" in src # checkpointed branch exists
77
+ assert "block_ckpt and torch.is_grad_enabled()" in src
78
+
79
+
80
+ if __name__ == "__main__":
81
+ sys.exit(pytest.main([__file__, "-v"]))