Repository navigation
Expand file tree
/
Copy pathtest_smoke.py
More file actions
2699 lines (2302 loc) · 105 KB
/
Copy pathtest_smoke.py
File metadata and controls
2699 lines (2302 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
tests/test_smoke.py — Project Chronos smoke tests for CI
"""
import sys
import os
# When running pytest from repo root, ensure chronos package is importable
_repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _repo_root not in sys.path:
sys.path.insert(0, _repo_root)
import torch
from torch.utils.data import DataLoader, TensorDataset
from unittest import mock
def _mlx_available() -> bool:
try:
import mlx.core as mx
return bool(mx.metal.is_available())
except Exception:
return False
class _TinyPickleTokenizer:
bos_token_id = 1
eos_token_id = 2
pad_token_id = 0
def __call__(self, text, add_special_tokens=False, max_length=None, truncation=False):
ids = [3 + (ord(c) % 16) for c in text][:max_length or 32]
return type("Encoded", (), {"input_ids": ids})()
def make_model(window=16):
from chronos.model.config import ChronosConfig
from chronos.model.model_chronos import ChronosForCausalLM
cfg = ChronosConfig(
hidden_size=128, num_hidden_layers=4, num_experts=4,
use_moe=True, use_hybrid_attention=True,
kv_latent_dim=16, rope_dim=8, sliding_window_size=window,
vram_budget_gb=0.5,
)
return ChronosForCausalLM(cfg), cfg
def test_forward():
model, cfg = make_model()
x = torch.randint(0, cfg.vocab_size, (2, 16))
out, lp = model(x, labels=x)
assert out.loss.item() > 0
assert lp.shape == (2, 16, cfg.lookahead_steps + 1, cfg.num_experts)
def test_kv_cache_bounded():
model, cfg = make_model(window=8)
model.eval()
x = torch.randint(0, cfg.vocab_size, (1, 8))
with torch.no_grad():
out, _ = model(x, use_cache=True)
past_kv = out.past_key_values
for _ in range(30):
xn = torch.randint(0, cfg.vocab_size, (1, 1))
out2, _ = model(xn, past_key_values=past_kv, use_cache=True)
past_kv = out2.past_key_values
from chronos.model.hybrid_attention import SlidingWindowAttention
for i, layer in enumerate(model.model.layers):
if isinstance(layer.self_attn, SlidingWindowAttention):
assert past_kv[i][0].shape[1] <= 8, f"Layer {i} KV not bounded"
def test_temporal_loss():
from chronos.model.temporal_loss import temporal_locality_loss, total_loss
probs = torch.rand(2, 16, 4)
tl = temporal_locality_loss(probs)
assert tl.item() >= 0
ce = torch.tensor(2.0)
bal = torch.tensor(0.01)
loss = total_loss(ce, bal, probs, 5e-4, 1e-3)
assert loss.item() > ce.item()
def test_offload_training_losses_and_metrics_are_finite():
from chronos.model.temporal_loss import (
lookahead_union_loss,
router_locality_loss,
router_offload_metrics,
)
torch.manual_seed(3)
router_logits = torch.randn(2, 6, 5, requires_grad=True)
router_probs = torch.softmax(router_logits, dim=-1)
lookahead_logits = torch.randn(2, 6, 3, 5, requires_grad=True)
lookahead_probs = torch.softmax(lookahead_logits, dim=-1)
locality = router_locality_loss(router_probs, num_experts_per_tok=2)
union = lookahead_union_loss(
lookahead_probs,
router_probs.detach(),
lookahead_steps=2,
num_experts_per_tok=2,
)
loss = locality + union
assert torch.isfinite(loss)
loss.backward()
assert router_logits.grad is not None
assert lookahead_logits.grad is not None
assert torch.isfinite(router_logits.grad).all()
assert torch.isfinite(lookahead_logits.grad).all()
metrics = router_offload_metrics(
router_probs.detach(),
lookahead_probs.detach(),
lookahead_steps=2,
num_experts_per_tok=2,
)
assert metrics["expert_working_set"] >= 1
assert 0.0 <= metrics["router_adjacent_jaccard"] <= 1.0
assert 0.0 <= metrics["lookahead_topk_recall"] <= 1.0
assert 0.0 <= metrics["lookahead_union_recall"] <= 1.0
def test_lru_cache():
from chronos.io.expert_store import LRUCache
lru = LRUCache(capacity=3)
lru.put(0); lru.put(1); lru.put(2)
evicted = lru.put(3)
assert evicted == 0
assert lru.contains(3)
assert not lru.contains(0)
def test_expert_store_init():
from chronos.io.expert_store import ExpertStore
model, cfg = make_model()
store = ExpertStore(model, cfg, ssd_dir='/tmp/chronos_ci_test')
s = store.stats()
assert s['vram_capacity'] >= 1
assert s['ram_capacity_dynamic'] >= 1
assert 'available_ram_gb' in s
def test_lazy_expert_placeholder_uses_shared_fallback():
from chronos.model.config import ChronosConfig
from chronos.model.model_chronos import ChronosForCausalLM
from chronos.model.moe_chronos import LazyExpertPlaceholder
cfg = ChronosConfig(
hidden_size=32, num_hidden_layers=1, num_experts=2,
num_experts_per_tok=1, num_shared_experts=1,
num_attention_heads=2, num_key_value_heads=2,
kv_latent_dim=8, rope_dim=4, max_seq_len=16,
vocab_size=128, use_moe=True,
)
model = ChronosForCausalLM(cfg).eval()
moe = model.model.layers[0].mlp
moe.experts[0] = LazyExpertPlaceholder(cfg.hidden_size, cfg.moe_intermediate_size, torch.float32)
x = torch.randn(1, 4, cfg.hidden_size)
mask = torch.tensor([0.0, 1.0])
with torch.no_grad():
y = moe(x, available_expert_mask=mask)
assert y.shape == x.shape
def test_async_prefetcher():
import time
from chronos.io.expert_store import ExpertStore
from chronos.io.async_prefetcher import AsyncPrefetcher
model, cfg = make_model()
store = ExpertStore(model, cfg, ssd_dir='/tmp/chronos_ci_test')
pf = AsyncPrefetcher(store)
pf.start()
pf.submit([0, 1])
time.sleep(0.05)
pf.stop()
assert pf.stats['total_requests'] == 2
def test_hybrid_attention_layers():
from chronos.model.hybrid_attention import MLAAttention, SlidingWindowAttention
model, cfg = make_model()
for i, layer in enumerate(model.model.layers):
if i % 2 == 0:
assert isinstance(layer.self_attn, MLAAttention), f"Layer {i} should be MLA"
else:
assert isinstance(layer.self_attn, SlidingWindowAttention), f"Layer {i} should be SW"
def test_benchmark_functions():
from chronos.eval.benchmark import compute_perplexity, measure_throughput
model, cfg = make_model()
ids = torch.randint(0, cfg.vocab_size, (4, 16))
ds = TensorDataset(ids, ids.clone())
loader = DataLoader(ds, batch_size=2)
ppl = compute_perplexity(model, loader, 'cpu', max_batches=2)
assert ppl > 1.0
tps = measure_throughput(model, ids[:1, :8], 'cpu', max_new_tokens=5)
assert tps > 0
# ── M1: cluster-aware safetensors storage ─────────────────────────
def test_cluster_storage_roundtrip(tmp_path=None):
"""Write every expert to .ctsr, read them back, confirm bit-identity."""
import tempfile, os as _os
from chronos.io.storage import ClusterStorage
from chronos.model.moe_chronos import ChronosMOEFeedForward
model, cfg = make_model()
moe_layers = [l.mlp for l in model.model.layers
if isinstance(l.mlp, ChronosMOEFeedForward)]
# Two clusters — exercise the manifest mapping.
clusters = [[0, 2], [1, 3]]
out_dir = tempfile.mkdtemp(prefix="chronos_ctsr_")
ClusterStorage.write_clusters(
moe_layers=moe_layers, clusters=clusters,
output_dir=out_dir, num_layers=len(moe_layers),
num_experts=cfg.num_experts, dtype=torch.float16,
)
cs = ClusterStorage(out_dir)
for cid, expected_experts in [(0, [0, 2]), (1, [1, 3])]:
nested = cs.load_cluster(cid, dtype=torch.float16)
# All expected experts present
assert sorted(nested.keys()) == sorted(expected_experts), \
f"cluster {cid} keys mismatch: {nested.keys()}"
# All layers present per expert
for eid in expected_experts:
assert sorted(nested[eid].keys()) == list(range(len(moe_layers))), \
f"layer set mismatch for expert {eid}"
# bit-identity vs source
for li in range(len(moe_layers)):
src_state = moe_layers[li].experts[eid].state_dict()
for pname, src_t in src_state.items():
loaded = nested[eid][li][pname]
src_fp16 = src_t.detach().to(torch.float16).cpu()
assert torch.equal(loaded, src_fp16), \
f"mismatch at expert={eid} layer={li} param={pname}"
def test_expert_store_clustered_prefetch(tmp_path=None):
"""Requesting one expert pulls in its whole Louvain cluster."""
import tempfile, os as _os
from chronos.io.expert_store import ExpertStore
model, cfg = make_model()
ssd = tempfile.mkdtemp(prefix="chronos_es_")
store = ExpertStore(model, cfg, ssd_dir=ssd)
# Force a 2-expert cluster containing experts 0 and 2.
clusters = [[0, 2], [1, 3]]
store.offload_all_to_ssd(clusters=clusters)
assert store.stats()["cluster_aware"] is True
assert store.stats()["num_clusters"] == 2
# Prefetch only expert 0 — expert 2 must come along for the ride.
store.prefetch_to_ram([0])
assert store.ram_lru.contains(0), "requested expert not in RAM"
assert store.ram_lru.contains(2), "co-cluster expert not pulled"
# Expert from a different cluster must NOT be loaded.
assert not store.ram_lru.contains(1), "wrong-cluster expert leaked"
# ── M2: lookahead supervision loss ────────────────────────────────
def test_lookahead_supervision_grad():
"""One backward step must produce non-zero grad on the LookaheadRouter."""
from chronos.model.temporal_loss import lookahead_supervision_loss
model, cfg = make_model()
model.train()
x = torch.randint(0, cfg.vocab_size, (2, 12))
out, lookahead_probs = model(x, labels=x)
# Build a teacher: layer-averaged real router probs (stop-grad).
from chronos.model.moe_chronos import ChronosMOEFeedForward
probs = [l.mlp.last_router_probs for l in model.model.layers
if isinstance(l.mlp, ChronosMOEFeedForward) and l.mlp.last_router_probs is not None]
teacher = torch.stack(probs, dim=2).mean(dim=2).detach() # [B, S, E]
la_loss = lookahead_supervision_loss(lookahead_probs, teacher, cfg.lookahead_steps)
assert la_loss.item() > 0, "lookahead loss should be strictly positive"
la_loss.backward()
last_layer = model.model.lookahead_router.proj[-1]
assert last_layer.weight.grad is not None, "no grad on lookahead head"
assert last_layer.weight.grad.abs().sum().item() > 0, "zero grad on lookahead head"
# ── M3: double-stream pipeline ────────────────────────────────────
def test_pipeline_overlap_simulated():
"""Measure the structural overlap benefit directly:
The M3 pipeline promises `prefetch_for_next_step` is *non-blocking*
(work happens in the async daemon) while the legacy `step(...)` path
blocks the caller on promote_to_vram (which in turn calls the
synchronous prefetch_to_ram → SSD sim sleep).
Rather than chase wall-clock speedup through 8 forwards (tiny
toy-model forward pass is ~0.5ms, drowned by thread jitter), we
measure the two primitives under CHRONOS_SIM_SSD_MS=30:
(a) prefetch_for_next_step(lp) should return in <<30ms.
(b) step(lp, [fresh_expert_id]) must block for ≥25ms.
That is the structural invariant that makes the decode loop overlap
possible on real GPU/SSD hardware. If it holds on CPU it holds
everywhere.
"""
import os as _os, tempfile, time as _time
from chronos.runtime.cache_manager import CacheManager
from chronos.model.config import ChronosConfig
from chronos.model.model_chronos import ChronosForCausalLM
cfg = ChronosConfig(
hidden_size=64, num_hidden_layers=2, num_experts=9,
use_moe=True, use_hybrid_attention=True,
kv_latent_dim=8, rope_dim=4, sliding_window_size=16,
vram_budget_gb=0.01,
num_shared_experts=1,
)
model = ChronosForCausalLM(cfg)
model.eval()
ssd = tempfile.mkdtemp(prefix="chronos_overlap_")
mgr = CacheManager(model, cfg, ssd_dir=ssd)
# Three distinct clusters so we can use one for async prefetch, another
# for the legacy-blocking test, with no overlap between them.
mgr.expert_store.offload_all_to_ssd(
clusters=[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
)
mgr.expert_store.attach_cluster_manifest()
mgr.warm_up(initial_expert_ids=[0])
mgr.start()
# Synthesize a lookahead tensor predicting expert 5 at t+1 (cluster 1).
E = cfg.num_experts
lp = torch.zeros(1, 1, cfg.lookahead_steps + 1, E)
lp[..., 0] = 1.0 / E
lp[0, 0, 1, 5] = 1.0 # t+1 → expert 5 → loads cluster [3,4,5]
_os.environ["CHRONOS_SIM_SSD_MS"] = "30"
try:
# Case A: async prefetch must return fast
t0 = _time.monotonic()
mgr.prefetch_for_next_step(lp)
async_ret_ms = (_time.monotonic() - t0) * 1000
# Let the daemon finish
_time.sleep(0.1)
# Case B: legacy step() promoting an expert from a DIFFERENT
# cluster (7 → cluster [6,7,8]) must block on SSD sim.
lp2 = torch.zeros(1, 1, cfg.lookahead_steps + 1, E)
lp2[..., 0] = 1.0 / E
t0 = _time.monotonic()
mgr.step(lp2, [7])
legacy_blocked_ms = (_time.monotonic() - t0) * 1000
finally:
_os.environ.pop("CHRONOS_SIM_SSD_MS", None)
mgr.stop()
print(f"\n [overlap] prefetch_for_next_step: {async_ret_ms:.1f}ms (want <<30)")
print(f" [overlap] legacy step() w/ miss: {legacy_blocked_ms:.1f}ms (want ≥25)")
assert async_ret_ms < 15, f"prefetch_for_next_step blocked {async_ret_ms:.1f}ms (expected <<30ms)"
assert legacy_blocked_ms >= 25, f"legacy step() did not block on SSD (got {legacy_blocked_ms:.1f}ms)"
def test_setup_from_state_dict_replaces_live_experts_with_placeholders():
import tempfile
from chronos.model.config import ChronosConfig
from chronos.model.model_chronos import ChronosForCausalLM
from chronos.model.moe_chronos import LazyExpertPlaceholder
from chronos.runtime.inference_engine import ChronosInferenceEngine
cfg = ChronosConfig(
hidden_size=32, num_hidden_layers=1, num_experts=4,
use_moe=True, use_hybrid_attention=True,
kv_latent_dim=8, rope_dim=4, sliding_window_size=16,
vram_budget_gb=0.01, num_shared_experts=1,
num_attention_heads=2, num_key_value_heads=2,
max_seq_len=16, vocab_size=128,
storage_format="pt",
)
model = ChronosForCausalLM(cfg).eval()
state = model.state_dict()
engine = ChronosInferenceEngine(model, cfg, ssd_dir=tempfile.mkdtemp(prefix="chronos_lazy_setup_"))
engine.setup_from_state_dict(state, warm_expert_ids=[])
expert0 = model.model.layers[0].mlp.experts[0]
assert isinstance(expert0, LazyExpertPlaceholder)
engine.teardown()
def test_inference_route_stats_cover_all_moe_layers():
from chronos.model.config import ChronosConfig
from chronos.model.model_chronos import ChronosForCausalLM
from chronos.runtime.inference_engine import ChronosInferenceEngine
cfg = ChronosConfig(
hidden_size=32, num_hidden_layers=2, num_experts=4,
num_experts_per_tok=1, num_shared_experts=1,
num_attention_heads=2, num_key_value_heads=2,
kv_latent_dim=8, rope_dim=4, max_seq_len=16,
vocab_size=128, use_moe=True, storage_format="pt",
)
model = ChronosForCausalLM(cfg).eval()
engine = ChronosInferenceEngine(model, cfg, ssd_dir="/tmp/chronos_ci_route_stats")
ids = torch.randint(0, cfg.vocab_size, (1, 4))
with torch.no_grad():
model(ids, use_cache=False)
first_layer_id = engine._get_current_expert_ids(capacity=1)[0]
masks = []
for li, layer in enumerate(model.model.layers):
moe = layer.mlp
probs = moe.last_router_probs[:, -1, :]
eid = int(torch.topk(probs, k=1, dim=-1).indices.reshape(-1)[0].item())
mask = torch.zeros(cfg.num_experts, dtype=torch.bool)
if li == 0:
mask[eid] = True
masks.append(mask)
stats = engine._route_cache_stats(masks, include_all_tokens=False)
assert first_layer_id in stats["activated_expert_ids"]
assert len(stats["per_layer"]) == 2
assert stats["cache_hits"] == 1
assert stats["cache_misses"] == 1
assert stats["fallback_weight_mass"] > 0
def test_on_demand_offload_loads_only_missing_expert_and_preserves_logits(tmp_path):
from chronos.model.config import ChronosConfig
from chronos.model.model_chronos import ChronosForCausalLM
from chronos.runtime.inference_engine import ChronosInferenceEngine
torch.manual_seed(7)
cfg = ChronosConfig(
hidden_size=32, num_hidden_layers=1, num_experts=3,
num_experts_per_tok=1, num_shared_experts=1,
num_attention_heads=2, num_key_value_heads=2,
kv_latent_dim=8, rope_dim=4, max_seq_len=16,
vocab_size=128, use_moe=True, storage_format="pt",
)
source = ChronosForCausalLM(cfg).eval()
half_state = {k: v.detach().half().cpu() for k, v in source.state_dict().items()}
full_ref = ChronosForCausalLM(cfg).eval()
full_ref.load_state_dict(half_state, strict=True)
ids = torch.randint(0, cfg.vocab_size, (1, 6))
with torch.no_grad():
full, _ = full_ref(ids, use_cache=False)
full_ref(ids, use_cache=False)
needed = []
for layer in full_ref.model.layers:
probs = layer.mlp.last_router_probs.reshape(-1, cfg.num_experts)
needed.extend(torch.topk(probs, k=cfg.num_experts_per_tok, dim=-1).indices.reshape(-1).tolist())
needed = sorted(set(int(eid) for eid in needed))
lazy = ChronosForCausalLM(cfg).eval()
lazy.load_state_dict(half_state, strict=True)
engine = ChronosInferenceEngine(lazy, cfg, ssd_dir=str(tmp_path / "lazy"))
store = engine.cache_manager.expert_store
store.vram_capacity = 1
store.ram_capacity = 1
store.vram_lru.capacity = 1
store.ram_lru.capacity = 1
engine.setup_from_state_dict(half_state, warm_expert_ids=[])
try:
engine._runtime_stats = {
"on_demand_loads": 0,
"on_demand_load_time_s": 0.0,
"sync_ssd_loads": 0,
"async_cold_miss_prefetches": 0,
"resident_vram_hits": 0,
"resident_ram_hits": 0,
"on_demand_loaded_experts": [],
"on_demand_promoted_experts": [],
}
engine._install_moe_runtime_hooks("sync_on_demand")
cold_mask = torch.zeros(cfg.num_experts, dtype=torch.bool)
with torch.no_grad():
lazy_out, _ = lazy(ids, use_cache=False, available_expert_masks=[cold_mask])
assert torch.allclose(full.logits, lazy_out.logits, atol=1e-5, rtol=1e-5)
assert set(engine._runtime_stats["on_demand_loaded_experts"]).issubset(set(needed))
assert set(engine._runtime_stats["on_demand_loaded_experts"]) == set(needed)
assert len(store.vram_lru) <= 1
assert len(store.ram_lru) <= 1
assert len(store._ram_buffers) <= 1
finally:
engine._clear_moe_runtime_hooks()
engine.teardown()
def test_predictive_on_demand_cold_miss_queues_async_prefetch(tmp_path):
from chronos.model.config import ChronosConfig
from chronos.model.model_chronos import ChronosForCausalLM
from chronos.runtime.inference_engine import ChronosInferenceEngine
cfg = ChronosConfig(
hidden_size=32, num_hidden_layers=1, num_experts=2,
num_experts_per_tok=1, num_shared_experts=1,
num_attention_heads=2, num_key_value_heads=2,
kv_latent_dim=8, rope_dim=4, max_seq_len=16,
vocab_size=128, use_moe=True, storage_format="pt",
)
engine = ChronosInferenceEngine(ChronosForCausalLM(cfg).eval(), cfg, ssd_dir=str(tmp_path))
submitted = []
ensure_calls = []
engine.cache_manager.prefetch_experts_to_ram = lambda ids: submitted.extend(ids) or list(ids)
engine.cache_manager.ensure_resident = lambda ids: ensure_calls.extend(ids) or list(ids)
engine.cache_manager.expert_store.vram_lru.contains = lambda _eid: False
engine.cache_manager.expert_store.ram_lru.contains = lambda _eid: False
engine._runtime_stats = {
"on_demand_loads": 0,
"on_demand_load_time_s": 0.0,
"sync_ssd_loads": 0,
"async_cold_miss_prefetches": 0,
"resident_vram_hits": 0,
"resident_ram_hits": 0,
"on_demand_loaded_experts": [],
"on_demand_promoted_experts": [],
}
engine._install_moe_runtime_hooks("on_demand")
try:
loader = engine._moe_layers()[0].runtime_on_demand_loader
result = loader(1)
assert result["ok"] is False
assert submitted == [1]
assert ensure_calls == []
assert engine._runtime_stats["async_cold_miss_prefetches"] == 1
assert engine._runtime_stats["sync_ssd_loads"] == 0
finally:
engine._clear_moe_runtime_hooks()
engine.teardown()
# ── M5/M6 tests ───────────────────────────────────────────────────
def test_backend_dispatcher():
from chronos.backend import BackendDispatcher
d = BackendDispatcher()
avail = d.available()
assert "cpu" in avail, f"cpu must be available, got {avail}"
assert d.device_str("cpu") == "cpu"
assert d.supports_training("cpu") is True
if "mlx" in avail:
assert d.supports_training("mlx") is True
assert d.supports_training("vulkan") is False # no upstream autograd
assert d.info("opencl").available is False # stub
sel = d.select()
assert sel in avail
def test_training_backend_resolver():
from chronos.backend import BackendDispatcher
d = BackendDispatcher()
fake_infos = {
"cuda": mock.Mock(available=False, supports_training=False, torch_device=None),
"xpu": mock.Mock(available=False, supports_training=False, torch_device=None),
"mps": mock.Mock(available=True, supports_training=True, torch_device="mps"),
"cpu": mock.Mock(available=True, supports_training=True, torch_device="cpu"),
"mlx": mock.Mock(available=True, supports_training=True, torch_device=None),
}
with mock.patch.object(d, "info", side_effect=lambda name: fake_infos.get(name, mock.Mock(available=False, supports_training=False, torch_device=None))):
assert d.training_available() == ["mlx", "mps", "cpu"]
assert d.select_training() == "mlx"
assert d.select_training("auto") == "mlx"
assert d.select_training("cpu") == "cpu"
assert d.select_training("mlx") == "mlx"
assert d.training_device_str("mlx") == "mlx"
assert d.training_device_str("mps") == "mps"
assert d.resolve_training_device("auto") == ("mlx", "mlx")
assert d.resolve_training_device("mlx") == ("mlx", "mlx")
assert d.resolve_training_device("cpu") == ("cpu", "cpu")
def test_training_backend_resolver_falls_back_when_mlx_not_trainable():
from chronos.backend import BackendDispatcher
d = BackendDispatcher()
fake_infos = {
"cuda": mock.Mock(available=False, supports_training=False, torch_device=None),
"xpu": mock.Mock(available=False, supports_training=False, torch_device=None),
"mps": mock.Mock(available=True, supports_training=True, torch_device="mps"),
"cpu": mock.Mock(available=True, supports_training=True, torch_device="cpu"),
"mlx": mock.Mock(available=True, supports_training=False, torch_device=None),
}
with mock.patch.object(d, "info", side_effect=lambda name: fake_infos.get(name, mock.Mock(available=False, supports_training=False, torch_device=None))):
assert d.training_available() == ["mps", "cpu"]
assert d.select_training("mlx") == "mps"
assert d.resolve_training_device("mlx") == ("mps", "mps")
def test_train_backend_choice_helpers():
from ui.tabs.train_tab import (
_available_train_backend_choices,
_train_backend_dropdown_choices,
)
with mock.patch("chronos.workbench.training.training_available", return_value=["mlx", "mps", "cpu"]):
assert _available_train_backend_choices() == ["auto", "mlx", "mps", "cpu"]
choices = _train_backend_dropdown_choices("en")
assert choices[0][1] == "auto"
assert [value for _, value in choices] == ["auto", "mlx", "mps", "cpu"]
def test_inference_resolves_mlx_without_pytorch_checkpoint_fallback():
from ui.tabs import inference_tab as mod
assert mod.TORCH_INFERENCE_PRIORITY[0] == "cuda"
with mock.patch("chronos.backend.select", return_value="mlx"):
backend, note = mod._resolve_inference_backend("auto", "./out/foo.pth", {"hidden_size": 384})
assert backend == "mlx"
assert note == ""
with mock.patch("chronos.backend.select", return_value="mlx"):
backend, note = mod._resolve_inference_backend("auto", "./out/foo.pth", {})
assert backend == "mlx"
assert note == ""
with mock.patch("chronos.backend.select", return_value="cuda"):
backend, note = mod._resolve_inference_backend("auto", "./out/foo.pth", {"hidden_size": 384})
assert backend == "cuda"
assert note == ""
with mock.patch("chronos.backend.select", return_value="cpu"):
backend, note = mod._resolve_inference_backend("cuda", "./out/foo.pth", {})
assert backend == "cpu"
assert "Requested cuda" in note
def test_device_utils_mps_is_not_cpu_path():
from chronos.trainer.device_utils import (
configure_cpu_threads,
dataloader_kwargs,
grad_scaler,
resolve_dtype_name,
runtime_summary,
torch_device_type,
)
assert torch_device_type("mps") == "mps"
assert torch_device_type("mlx") == "mlx"
assert torch_device_type("cuda:0") == "cuda"
assert resolve_dtype_name("cpu", "auto") == "float32"
assert resolve_dtype_name("mps", "auto") == "float32" # = chronos.precision.resolve_torch
assert resolve_dtype_name("mlx", "auto") == "bfloat16"
assert grad_scaler("mps", "float16").is_enabled() is False
assert grad_scaler("cuda", "float16").is_enabled() in {True, False}
summary = runtime_summary("mps", "bfloat16")
assert summary.device_type == "mps"
assert summary.autocast is True
assert summary.scaler is False
mlx_summary = runtime_summary("mlx", "auto")
assert mlx_summary.device_type == "mlx"
assert mlx_summary.dtype == "bfloat16"
assert mlx_summary.autocast is False
assert dataloader_kwargs("mps", num_workers="auto")["num_workers"] == 0
assert dataloader_kwargs("mlx", num_workers="auto")["num_workers"] == 0
assert dataloader_kwargs("mps", num_workers=4)["num_workers"] == 0
assert dataloader_kwargs("mlx", num_workers=4)["num_workers"] == 0
assert dataloader_kwargs("mps", num_workers=0)["pin_memory"] is False
assert dataloader_kwargs("cuda", num_workers=0)["pin_memory"] is True
threads = configure_cpu_threads("auto", budget_percent=75)
assert threads >= 1
def test_configure_cpu_threads_overrides_single_thread_env(monkeypatch):
from chronos.trainer.device_utils import configure_cpu_threads, cpu_thread_snapshot
monkeypatch.setenv("OMP_NUM_THREADS", "1")
monkeypatch.delenv("CHRONOS_CPU_THREADS", raising=False)
threads = configure_cpu_threads("auto", budget_percent=100)
snap = cpu_thread_snapshot()
assert threads >= 1
assert snap["torch_num_threads"] == threads
assert snap["OMP_NUM_THREADS"] == str(threads)
assert snap["MKL_NUM_THREADS"] == str(threads)
assert snap["VECLIB_MAXIMUM_THREADS"] == str(threads)
assert snap["NUMEXPR_NUM_THREADS"] == str(threads)
def test_configure_cpu_threads_ignores_stale_chronos_env_by_default(monkeypatch):
from chronos.trainer.device_utils import configure_cpu_threads, cpu_thread_snapshot
monkeypatch.setenv("CHRONOS_CPU_THREADS", "1")
monkeypatch.setenv("OMP_NUM_THREADS", "1")
try:
import psutil
physical = int(psutil.cpu_count(logical=False) or os.cpu_count() or 1)
except Exception:
physical = int(os.cpu_count() or 1)
threads = configure_cpu_threads("auto", budget_percent=100)
snap = cpu_thread_snapshot()
assert threads == physical
assert snap["OMP_NUM_THREADS"] == str(physical)
assert snap["last_source"] == "budget_percent"
def test_configure_cpu_threads_can_prefer_env_for_diagnostics(monkeypatch):
from chronos.trainer.device_utils import configure_cpu_threads, cpu_thread_snapshot
monkeypatch.setenv("CHRONOS_CPU_THREADS", "2")
threads = configure_cpu_threads("auto", budget_percent=100, prefer_env=True)
snap = cpu_thread_snapshot()
assert threads == 2
assert snap["OMP_NUM_THREADS"] == "2"
assert snap["last_source"] == "CHRONOS_CPU_THREADS"
def test_mac_backend_diagnostics_shape():
from chronos.backend.mac_diagnostics import mac_backend_diagnostics
diag = mac_backend_diagnostics(configure_threads=False)
assert "torch_num_threads" in diag
assert "mps_available" in diag
assert "mlx_available" in diag
def test_mac_backend_diagnostics_overrides_single_thread_env(monkeypatch):
from chronos.backend.mac_diagnostics import mac_backend_diagnostics
monkeypatch.setenv("OMP_NUM_THREADS", "1")
monkeypatch.setenv("MKL_NUM_THREADS", "1")
monkeypatch.setenv("VECLIB_MAXIMUM_THREADS", "1")
monkeypatch.setenv("NUMEXPR_NUM_THREADS", "1")
monkeypatch.delenv("CHRONOS_CPU_THREADS", raising=False)
diag = mac_backend_diagnostics(configure_threads=True)
threads = int(diag["torch_num_threads"])
assert threads >= 1
assert diag["env"]["OMP_NUM_THREADS"] == str(threads)
assert diag["env"]["MKL_NUM_THREADS"] == str(threads)
assert diag["env"]["VECLIB_MAXIMUM_THREADS"] == str(threads)
assert diag["env"]["NUMEXPR_NUM_THREADS"] == str(threads)
def test_inference_cpu_thread_helper_overrides_single_thread_env(monkeypatch):
from ui.tabs.inference_tab import _configure_inference_cpu_threads_if_needed
monkeypatch.setenv("OMP_NUM_THREADS", "1")
monkeypatch.setenv("MKL_NUM_THREADS", "1")
monkeypatch.setenv("VECLIB_MAXIMUM_THREADS", "1")
monkeypatch.setenv("NUMEXPR_NUM_THREADS", "1")
monkeypatch.delenv("CHRONOS_CPU_THREADS", raising=False)
stats = _configure_inference_cpu_threads_if_needed("cpu")
threads = int(stats["cpu_threads"])
assert threads >= 1
assert stats["cpu_thread_env"]["OMP_NUM_THREADS"] == str(threads)
assert stats["cpu_thread_env"]["MKL_NUM_THREADS"] == str(threads)
assert stats["cpu_thread_env"]["VECLIB_MAXIMUM_THREADS"] == str(threads)
assert stats["cpu_thread_env"]["NUMEXPR_NUM_THREADS"] == str(threads)
def test_inference_backend_choice_helpers():
from ui.tabs.inference_tab import (
_available_inference_backend_choices,
_default_inference_backend_value,
)
with mock.patch("chronos.backend.available", return_value=["mlx", "mps", "cpu"]):
assert _available_inference_backend_choices() == ["auto", "mlx", "mps", "cpu"]
assert _default_inference_backend_value() == "auto"
def test_cuda_inference_path_uses_cuda_device_map():
from ui.tabs import inference_tab as mod
class _FakeTensor:
def __init__(self, item_value=7):
self.devices = []
self.item_value = item_value
def to(self, device):
self.devices.append(device)
return self
@property
def shape(self):
return (1, 3)
def tolist(self):
return [[1, 2, 3, self.item_value]]
def __getitem__(self, _key):
return mock.Mock(tolist=mock.Mock(return_value=[self.item_value]))
class _FakeModel:
def __init__(self):
self.devices = []
self.eval_called = False
def load_state_dict(self, _weights, strict=False):
return None
def to(self, device=None, dtype=None):
# place_torch_model() moves device and compute dtype in one call.
self.devices.append(device)
return self
def modules(self):
return []
def eval(self):
self.eval_called = True
return self
class _FakeEngine:
def __init__(self, _model, _cfg, ssd_dir=None):
self.setup_called = False
def setup(self, warm_expert_ids=None):
self.setup_called = True
def setup_from_state_dict(self, _state, warm_expert_ids=None):
self.setup_called = True
def generate(self, input_ids, **_kwargs):
return input_ids
def teardown(self):
return None
fake_model = _FakeModel()
fake_input = _FakeTensor(item_value=11)
fake_torch = mock.Mock()
fake_torch.tensor = mock.Mock(return_value=fake_input)
fake_torch.load = mock.Mock(return_value={})
import chronos.runtime.inference_engine # ensure module is loaded before torch is mocked
with mock.patch.dict(sys.modules, {"torch": fake_torch}):
with mock.patch("chronos.model.model_chronos.ChronosForCausalLM", return_value=fake_model):
with mock.patch("chronos.runtime.inference_engine.ChronosInferenceEngine", _FakeEngine):
generated = mod._run_torch_inference(
"cuda",
model_cfg=object(),
model_path_val="",
token_ids=[1, 2, 3],
attention_mask=[1, 1, 1],
max_tok=1,
temp=0.8,
eos_token_id=99,
)
generated_tokens, stats = generated
assert generated_tokens == [11]
assert stats["effective_expert_budget"] == 1
assert "setup_rss_delta_gb" in stats
assert fake_model.devices == ["cuda"]
assert fake_model.eval_called is True
assert fake_input.devices == ["cuda", "cuda"]
assert fake_torch.tensor.call_count == 2
def test_torch_inference_loads_base_only_before_lazy_setup():
from ui.tabs import inference_tab as mod
captured = {}
class _FakeTensor:
def to(self, _device):
return self
@property
def shape(self):
return (1, 3)
def tolist(self):
return [[1, 2, 3]]
def __getitem__(self, _key):
return mock.Mock(tolist=mock.Mock(return_value=[]))
class _FakeModel:
def load_state_dict(self, weights, strict=False):
captured["loaded_keys"] = sorted(weights.keys())
captured["strict"] = strict
def to(self, device=None, dtype=None):
return self
def modules(self):
return []
def eval(self):
return self
class _FakeEngine:
def __init__(self, _model, _cfg, ssd_dir=None):
pass
def setup_from_state_dict(self, state, warm_expert_ids=None, clusters=None):
captured["setup_keys"] = sorted(state.keys())
captured["clusters"] = clusters
def setup(self, warm_expert_ids=None):
captured["setup_called"] = True
def generate(self, input_ids, **_kwargs):
return input_ids
def teardown(self):
captured["teardown"] = True
fake_state = {
"model.embed_tokens.weight": torch.zeros(4, 4),
"model.layers.0.mlp.experts.0.gate_proj.weight": torch.zeros(4, 4),
"model.layers.0.mlp.experts.0.up_proj.weight": torch.zeros(4, 4),
}
with mock.patch("torch.load", return_value=fake_state):
with mock.patch("os.path.exists", return_value=True):
with mock.patch("chronos.model.model_chronos.ChronosForCausalLM", return_value=_FakeModel()):
with mock.patch("chronos.runtime.inference_engine.ChronosInferenceEngine", _FakeEngine):
out = mod._run_torch_inference(
"cpu",
model_cfg=object(),
model_path_val="/tmp/fake.pth",
token_ids=[1, 2, 3],
attention_mask=[1, 1, 1],
max_tok=4,
temp=0.8,
eos_token_id=99,
)
generated_tokens, stats = out
assert generated_tokens == []
assert stats["effective_expert_budget"] == 1
assert "setup_rss_delta_gb" in stats
assert captured["strict"] is False
assert captured["loaded_keys"] == ["model.embed_tokens.weight"]
assert any(".mlp.experts." in key for key in captured["setup_keys"])
assert captured["clusters"] is None # trained without cluster locality: per-expert pages
assert stats["paging_resolved"] == "expert"
assert captured["teardown"] is True
def test_param_estimator():
from ui.estimator import ArchConfig, total_params, active_params
cfg = ArchConfig(
hidden_size=64, num_hidden_layers=2, num_experts=4,
num_experts_per_tok=1, num_shared_experts=1,
moe_intermediate_size=128, vocab_size=1000,
num_attention_heads=4, num_key_value_heads=4,
tie_word_embeddings=True,
)
tot = total_params(cfg)
act = active_params(cfg)
assert tot > 0 and act > 0, f"got tot={tot} act={act}"
assert act < tot, "active must be smaller than total for MoE"
# Sanity: embedding dominates; should be > vocab * hidden
assert tot >= cfg.vocab_size * cfg.hidden_size
def test_param_estimator_recurrent_active_is_unique_and_compute_is_separate():
from ui.estimator import ArchConfig, total_params, active_params, compute_params
cfg = ArchConfig(hidden_size=64, num_hidden_layers=4, recurrent_enabled=True,
recurrent_groups=2, recurrent_depth=8, num_experts=4,
num_experts_per_tok=1, num_shared_experts=1,
num_attention_heads=4, num_key_value_heads=4, vocab_size=1000)
assert active_params(cfg) <= total_params(cfg)
assert compute_params(cfg) >= active_params(cfg)
def test_metrics_bus():
from chronos.runtime.metrics import MetricsBus
bus = MetricsBus()
for i in range(5):
bus.record("foo", float(i))
assert bus.latest("foo") == 4.0
ser = bus.series("foo")
assert len(ser) == 5
snap = bus.snapshot()
assert "foo" in snap
bus.reset()
assert bus.snapshot() == {}
def test_vllm_adapter_no_vllm():
from chronos.serving import register_chronos_with_vllm, HAS_VLLM, is_available
# On a host without vLLM, this is a graceful no-op (returns False).
result = register_chronos_with_vllm(verbose=False)
# Accept either True (if a user DID install vllm) or False (no-op).
assert isinstance(result, bool)
assert isinstance(HAS_VLLM, bool)
assert is_available() == HAS_VLLM
def test_hf_save_load_roundtrip():
import tempfile
from chronos.model.hf_io import save_chronos_pretrained, load_chronos_pretrained
torch.manual_seed(0)
model, cfg = make_model()
model.eval()
x = torch.randint(0, cfg.vocab_size, (1, 8))
out1, _ = model(x)
before = out1.logits.detach().clone()
with tempfile.TemporaryDirectory() as d:
save_chronos_pretrained(model, d)
m2, cache = load_chronos_pretrained(d)