Merged
[fix] Fix test case failures related to `anticipatory_routing` that occurred after the 0.4.0 migration. #1467
[fix] Fix test case failures related to `anticipatory_routing` that occurred after the 0.4.0 migration. #1467
Merged
zhangguoguangAdd on 2 days ago
Total: 4 files changed+192-102
@@ -90,13 +90,26 @@ def _worker(folder):
90 local_rank = int(os.environ["LOCAL_RANK"])90 local_rank = int(os.environ["LOCAL_RANK"])
91 91 
92 from torchtitan.components.checkpointer import DATALOADER, LR_SCHEDULER, MODEL, OPTIMIZER, TRAIN_STATE92 from torchtitan.components.checkpointer import DATALOADER, LR_SCHEDULER, MODEL, OPTIMIZER, TRAIN_STATE
93+ from torchtitan.components.data.types import TrainingMicrobatch
94+ from torchtitan.components.optim import Optim
95+ from torchtitan.models.common.activation import Sigmoid
96+ from torchtitan.models.common.linear.hi_mid_lo_linear import HiMidLoLinear
93 from torchtitan.models.common.moe import TokenChoiceTopKRouter97 from torchtitan.models.common.moe import TokenChoiceTopKRouter
94 98 
95 from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode99 from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode
96 from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig100 from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig
97 from torchtitan_npu.extensions.experiment.anticipatory_routing.detector import LossSpikeDetector101 from torchtitan_npu.extensions.experiment.anticipatory_routing.detector import LossSpikeDetector
98 from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase102 from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase
99- from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx103+ from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx, TrainingEngineEx
104+ 
105+ class Microbatch(TrainingMicrobatch):
106+ def __init__(self, inputs, labels):
107+ self.inputs, self.labels = inputs, labels
108+ self.loss_token_counts = torch.tensor(1)
109+ self.routing_token_counts = torch.tensor([1])
110+ 
111+ def as_input_dict(self):
112+ return {"input": self.inputs, "labels": self.labels}
100 113 
101 class Loader:114 class Loader:
102 def __init__(self):115 def __init__(self):
@@ -112,7 +125,7 @@ def _worker(folder):
112 if rank == 0 and index in (10, 11) and index not in self.injected:125 if rank == 0 and index in (10, 11) and index not in self.injected:
113 target = 1126 target = 1
114 self.injected.add(index)127 self.injected.add(index)
115- yield {"input": inputs, "num_valid_tokens": 1}, torch.tensor([[target]])128+ yield Microbatch(inputs, torch.tensor([[target]]))
116 129 
117 def state_dict(self):130 def state_dict(self):
118 return {"position": self.position}131 return {"position": self.position}
@@ -126,13 +139,15 @@ def _worker(folder):
126 super().__init__()139 super().__init__()
127 self.routers = torch.nn.ModuleList()140 self.routers = torch.nn.ModuleList()
128 for _ in range(2):141 for _ in range(2):
129- router = TokenChoiceTopKRouter.__new__(TokenChoiceTopKRouter)142+ router = TokenChoiceTopKRouter.Config(
130- torch.nn.Module.__init__(router)143+ num_experts=2,
144+ top_k=1,
145+ gate=HiMidLoLinear.Config(in_features=2, out_features=2),
146+ score_func=Sigmoid.Config(),
147+ route_norm=False,
148+ route_scale=1.0,
149+ ).build()
131 router.gate = torch.nn.Identity()150 router.gate = torch.nn.Identity()
132- router.score_func = "sigmoid"
133- router.num_experts, router.top_k = 2, 1
134- router.num_expert_groups = None
135- router.route_norm, router.route_scale = False, 1.0
136 self.routers.append(router)151 self.routers.append(router)
137 self.experts = torch.nn.Parameter(torch.tensor([[4.0, -4.0], [3.0, -3.0]]))152 self.experts = torch.nn.Parameter(torch.tensor([[4.0, -4.0], [3.0, -3.0]]))
138 self.register_buffer("counter", torch.zeros(()))153 self.register_buffer("counter", torch.zeros(()))
@@ -141,19 +156,19 @@ def _worker(folder):
141 self.trained = []156 self.trained = []
142 157 
143 def preprocess_inputs(self, batch, **kwargs):158 def preprocess_inputs(self, batch, **kwargs):
144- return batch["input"], batch["labels"], {}159+ return batch["input"], batch["labels"], {}, {}
145 160 
146 def forward(self, x):161 def forward(self, x):
147 self.counter.add_(1)162 self.counter.add_(1)
148 index = int(x[0, 0, 0].item()) - 1163 index = int(x[0, 0, 0].item()) - 1
149 output = 0164 output = 0
150 for layer, router in enumerate(self.routers):165 for layer, router in enumerate(self.routers):
151- cache = router._anticipatory_cache166+ cache = schedule.cache
152 choice = (index + layer + rank) % 2167 choice = (index + layer + rank) % 2
153 if cache.mode is RoutingMode.REPLAY:168 if cache.mode is RoutingMode.REPLAY:
154 choice = 1 - choice # Force live top-k to disagree with captured IDs.169 choice = 1 - choice # Force live top-k to disagree with captured IDs.
155 logits = torch.tensor([[[5.0, 0.0] if choice == 0 else [0.0, 5.0]]], device=x.device)170 logits = torch.tensor([[[5.0, 0.0] if choice == 0 else [0.0, 5.0]]], device=x.device)
156- scores, ids, _ = router(logits)171+ scores, ids, _ = router(logits.reshape(-1, 2))
157 key = (index, layer)172 key = (index, layer)
158 if cache.mode is RoutingMode.CAPTURE:173 if cache.mode is RoutingMode.CAPTURE:
159 self.recorded[key] = (x.detach().cpu().clone(), ids.detach().cpu().clone())174 self.recorded[key] = (x.detach().cpu().clone(), ids.detach().cpu().clone())
@@ -166,59 +181,79 @@ def _worker(folder):
166 output = output + (self.experts[ids] * scores.unsqueeze(-1)).sum(-2)181 output = output + (self.experts[ids] * scores.unsqueeze(-1)).sum(-2)
167 if torch.is_grad_enabled():182 if torch.is_grad_enabled():
168 self.trained.append((index, cache.mode))183 self.trained.append((index, cache.mode))
169- return output / 2184+ return (output / 2).unsqueeze(0)
170 185 
171 class Scheduler(torch.optim.lr_scheduler.StepLR):186 class Scheduler(torch.optim.lr_scheduler.StepLR):
172 def get_metrics(self):187 def get_metrics(self):
173 return {"lr": self.get_last_lr()[0]}188 return {"lr": self.get_last_lr()[0]}
174 189 
175 trainer = object.__new__(TrainerEx)190 trainer = object.__new__(TrainerEx)
176- trainer.device = torch.device(f"npu:{local_rank}")191+ runtime = trainer.engine = object.__new__(TrainingEngineEx)
177- trainer.step = trainer.ntokens_seen = 0192+ runtime.device = torch.device(f"npu:{local_rank}")
178- model = Model().to(trainer.device)193+ runtime.num_completed_steps = runtime.ntokens_seen = 0
179- trainer.model_parts = [model]194+ model = Model().to(runtime.device)
195+ runtime.model_parts = [model]
180 trainer.dataloader = Loader()196 trainer.dataloader = Loader()
181- trainer.gradient_accumulation_steps = 2197+ trainer.gradient_accumulation_steps = runtime.num_accumulation_steps = 2
182 trainer.num_pp_microbatches = 1198 trainer.num_pp_microbatches = 1
183- trainer.config = SimpleNamespace(199+ trainer.config = runtime.config = SimpleNamespace(
184 anticipatory=AnticipatoryRoutingConfig(200 anticipatory=AnticipatoryRoutingConfig(
185 enable=True,201 enable=True,
186 delay_steps=2,202 delay_steps=2,
187 active_steps=2,203 active_steps=2,
188 detector=LossSpikeDetector.Config(warmup_steps=4),204 detector=LossSpikeDetector.Config(warmup_steps=4),
189 ),205 ),
190- training=SimpleNamespace(steps=10, disable_cuda_graphs=True, max_norm=100.0),206+ training=SimpleNamespace(
191- checkpoint=SimpleNamespace(interval=2, keep_latest_k=0),207+ steps=10,
208+ disable_cuda_graphs=True,
209+ max_context_length=1,
210+ num_tokens_per_microbatch_per_dp_rank=1,
211+ preprocess_microbatch_groups_lazily=False,
212+ ),
213+ checkpointer=SimpleNamespace(interval=2, keep_latest_k=0),
192 parallelism=SimpleNamespace(),214 parallelism=SimpleNamespace(),
215+ debug=SimpleNamespace(spmd_typechecking=False),
216+ optim=Optim.Config(max_norm=100.0),
193 )217 )
194- trainer.parallel_dims = SimpleNamespace(218+ runtime.parallelism_context = SimpleNamespace(
195 pp_enabled=False,219 pp_enabled=False,
196 dp_enabled=False,220 dp_enabled=False,
197 ep_enabled=False,221 ep_enabled=False,
198 dp_cp_enabled=False,222 dp_cp_enabled=False,
223+ dp_replicate_enabled=False,
224+ cp=1,
199 get_optional_mesh=lambda name: None,225 get_optional_mesh=lambda name: None,
226+ activate_spmd=lambda **kwargs: nullcontext(),
200 )227 )
201 trainer.metrics_processor = SimpleNamespace(228 trainer.metrics_processor = SimpleNamespace(
229+ step_last_log=-1,
202 ntokens_since_last_log=0,230 ntokens_since_last_log=0,
203 data_loading_times=[],231 data_loading_times=[],
204 should_log=lambda step: False,232 should_log=lambda step: False,
205 )233 )
206- trainer.train_context = nullcontext234+ runtime.sdc_replayer = runtime._sdc = None
207- trainer.sdc_replayer = None235+ runtime.garbage_collector = SimpleNamespace(run=lambda step: None)
208- trainer._sdc = SimpleNamespace(finalize_sdc_step=lambda: None)236+ runtime._cuda_graph_per_microbatch_group_enabled = False
209- trainer.optimizers = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)237+ runtime.max_num_documents = None
210- trainer.lr_schedulers = Scheduler(trainer.optimizers, step_size=1, gamma=0.99)238+ runtime.preprocess_inputs_kwargs = {}
211- 239+ runtime._run_forward_backward = lambda groups, tokens: runtime._forward_backward_body(
212- def process(inputs, labels):240+ groups, tokens, defer_fsdp_gradient_reduction=False
213- trainer.ntokens_seen += labels.numel()241+ )
214- return inputs["input"], labels, {}242+ optim = runtime.optim = object.__new__(Optim)
215- 243+ optim.config = trainer.config.optim
216- trainer.post_dataloading_process = process244+ optim.parallelism_context = runtime.parallelism_context
217- trainer.loss_fn = lambda pred, labels, count, **kwargs: (245+ optim.parameters = list(model.parameters())
218- F.cross_entropy(pred.flatten(0, 1), labels.flatten(), reduction="sum") / count,246+ optim.pp_has_last_stage = True
219- None,247+ optim.optimizers = torch.optim.SGD(optim.parameters, lr=1e-4, momentum=0.9)
248+ optim.lr_schedulers = Scheduler(optim.optimizers, step_size=1, gamma=0.99)
249+ optim.ema = None
250+ optim._is_first_step_call = True
251+ optim.gradient_clipper = optim.config.gradient_clipper.build()
252+ optim._run_update = optim._update
253+ runtime.loss_fn = lambda pred, labels, *, global_loss_token_counts: (
254+ F.cross_entropy(pred.flatten(0, 1), labels.flatten(), reduction="sum") / global_loss_token_counts,
255+ {},
220 )256 )
221- trainer.fwd_bwd_fn = trainer._forward_backward_body
222 257 
223 class DiskCheckpoint:258 class DiskCheckpoint:
224 """DCP adapter with upstream flat model keys and resumable training state."""259 """DCP adapter with upstream flat model keys and resumable training state."""
@@ -239,10 +274,10 @@ def _worker(folder):
239 state = dict(model.state_dict())274 state = dict(model.state_dict())
240 state.update(275 state.update(
241 {276 {
242- OPTIMIZER: trainer.optimizers.state_dict(),277+ OPTIMIZER: runtime.optim.optimizers.state_dict(),
243- LR_SCHEDULER: trainer.lr_schedulers.state_dict(),278+ LR_SCHEDULER: runtime.optim.lr_schedulers.state_dict(),
244 DATALOADER: trainer.dataloader.state_dict(),279 DATALOADER: trainer.dataloader.state_dict(),
245- TRAIN_STATE: trainer.state_dict(),280+ TRAIN_STATE: {"step": runtime.num_completed_steps, "ntokens_seen": runtime.ntokens_seen},
246 }281 }
247 )282 )
248 return state283 return state
@@ -256,43 +291,44 @@ def _worker(folder):
256 state = deepcopy(self.payload())291 state = deepcopy(self.payload())
257 dcp.load(state, checkpoint_id=str(Path(folder) / f"step-{step}"))292 dcp.load(state, checkpoint_id=str(Path(folder) / f"step-{step}"))
258 model.load_state_dict({key: state[key] for key in model.state_dict()})293 model.load_state_dict({key: state[key] for key in model.state_dict()})
259- trainer.optimizers.load_state_dict(state[OPTIMIZER])294+ runtime.optim.optimizers.load_state_dict(state[OPTIMIZER])
260- trainer.lr_schedulers.load_state_dict(state[LR_SCHEDULER])295+ runtime.optim.lr_schedulers.load_state_dict(state[LR_SCHEDULER])
261 trainer.dataloader.load_state_dict(state[DATALOADER])296 trainer.dataloader.load_state_dict(state[DATALOADER])
262- trainer.load_state_dict(state[TRAIN_STATE])297+ runtime.num_completed_steps = state[TRAIN_STATE]["step"]
298+ runtime.ntokens_seen = state[TRAIN_STATE]["ntokens_seen"]
263 torch.testing.assert_close(self.payload(), state, rtol=0, atol=0)299 torch.testing.assert_close(self.payload(), state, rtol=0, atol=0)
264 self.loaded.append(step)300 self.loaded.append(step)
265 return True301 return True
266 302 
267- trainer.checkpointer = DiskCheckpoint()303+ runtime.checkpointer = DiskCheckpoint()
268 trainer.anticipatory_schedule = AnticipatorySchedule(trainer)304 trainer.anticipatory_schedule = AnticipatorySchedule(trainer)
305+ runtime.anticipatory_schedule = trainer.anticipatory_schedule
269 engine, schedule = trainer.anticipatory_schedule.engine, trainer.anticipatory_schedule306 engine, schedule = trainer.anticipatory_schedule.engine, trainer.anticipatory_schedule
270- stream = trainer.batch_generator(trainer.dataloader)307+ stream = trainer.microbatch_generator(trainer.dataloader)
271 transitions, blocked = [], []308 transitions, blocked = [], []
272 for _ in range(14): # Bounded even if rollback regresses into a loop.309 for _ in range(14): # Bounded even if rollback regresses into a loop.
273- if trainer.step >= 10:310+ if runtime.num_completed_steps >= 10:
274 break311 break
275- trainer.step += 1
276 trainer.train_step(stream)312 trainer.train_step(stream)
277- transitions.append((trainer.step, schedule.phase, len(schedule._queue)))313+ transitions.append((runtime.num_completed_steps, schedule.phase, len(schedule._queue)))
278- if trainer.step == 4 and trainer.checkpointer.loaded:314+ if runtime.num_completed_steps == 4 and runtime.checkpointer.loaded:
279 assert model.counter.item() == 8 # WARMUP buffer changes were restored.315 assert model.counter.item() == 8 # WARMUP buffer changes were restored.
280- assert trainer.ntokens_seen == 8316+ assert runtime.ntokens_seen == 8
281- assert trainer.lr_schedulers.last_epoch == 4317+ assert runtime.optim.lr_schedulers.last_epoch == 4
282 assert trainer.dataloader.position == 12318 assert trainer.dataloader.position == 12
283 for entry in schedule._queue:319 for entry in schedule._queue:
284- assert all(labels.device.type == "cpu" for _, labels in entry.microbatches)320+ assert all(batch.labels.device.type == "cpu" for batch in entry.microbatches)
285 assert all(ids.device.type == "npu" for slot in entry.slots for ids in slot.values())321 assert all(ids.device.type == "npu" for slot in entry.slots for ids in slot.values())
286 if engine.suppress_checkpoint_saves:322 if engine.suppress_checkpoint_saves:
287- assert not trainer.checkpointer.save(trainer.step)323+ assert not runtime.checkpointer.save(runtime.num_completed_steps)
288- blocked.append(trainer.step)324+ blocked.append(runtime.num_completed_steps)
289- elif trainer.step % 2 == 0:325+ elif runtime.num_completed_steps % 2 == 0:
290- assert trainer.checkpointer.save(trainer.step, last_step=trainer.step == 10)326+ assert runtime.checkpointer.save(runtime.num_completed_steps, last_step=runtime.num_completed_steps == 10)
291 327 
292 torch.npu.synchronize()328 torch.npu.synchronize()
293- assert trainer.step == 10329+ assert runtime.num_completed_steps == 10
294- assert trainer.checkpointer.loaded == [4]330+ assert runtime.checkpointer.loaded == [4]
295- assert trainer.checkpointer.saved == [2, 4, 8, 10]331+ assert runtime.checkpointer.saved == [2, 4, 8, 10]
296 assert blocked == [4, 5, 6, 7]332 assert blocked == [4, 5, 6, 7]
297 assert transitions[5:10] == [333 assert transitions[5:10] == [
298 (4, Phase.ACTIVE, 2),334 (4, Phase.ACTIVE, 2),
@@ -305,8 +341,8 @@ def _worker(folder):
305 assert [mode for _, mode in model.trained[12:]] == [RoutingMode.REPLAY] * 8 + [RoutingMode.OFF] * 4341 assert [mode for _, mode in model.trained[12:]] == [RoutingMode.REPLAY] * 8 + [RoutingMode.OFF] * 4
306 assert model.replayed == [(i, layer) for i in range(8, 16) for layer in range(2)]342 assert model.replayed == [(i, layer) for i in range(8, 16) for layer in range(2)]
307 assert len(model.recorded) == len(model.replayed)343 assert len(model.recorded) == len(model.replayed)
308- assert model.counter.item() == trainer.ntokens_seen == 20344+ assert model.counter.item() == runtime.ntokens_seen == 20
309- assert trainer.lr_schedulers.last_epoch == 10345+ assert runtime.optim.lr_schedulers.last_epoch == 10
310 assert schedule._num_rollbacks == 1 and not schedule._queue346 assert schedule._num_rollbacks == 1 and not schedule._queue
311 assert schedule.cache.mode is RoutingMode.OFF347 assert schedule.cache.mode is RoutingMode.OFF
312 assert not engine.failed and not engine.suppress_checkpoint_saves348 assert not engine.failed and not engine.suppress_checkpoint_saves
@@ -15,7 +15,6 @@ _CPP17_TRITON_RELEASES = frozenset({"3.2.1", "3.2.2", "3.2.2.post2", "3.6.0", "3
15_SMOKE_ROOT = Path(__file__).resolve().parent15_SMOKE_ROOT = Path(__file__).resolve().parent
16_DEFERRED_SMOKE_TESTS = frozenset(16_DEFERRED_SMOKE_TESTS = frozenset(
17 {17 {
18- "anticipatory_routing/test_anticipatory_routing_smoke.py::test_loss_spike_rollback_and_route_replay",
19 "sdc/test_sdc_smoke.py::test_compiled_controls_are_typed_without_installing_the_eager_wrapper",18 "sdc/test_sdc_smoke.py::test_compiled_controls_are_typed_without_installing_the_eager_wrapper",
20 "sdc/test_sdc_smoke.py::test_invalid_compiled_sdc_business_config_is_rejected",19 "sdc/test_sdc_smoke.py::test_invalid_compiled_sdc_business_config_is_rejected",
21 "sdc/test_sdc_smoke.py::test_compiled_gradient_checks_real_bf16_gradients",20 "sdc/test_sdc_smoke.py::test_compiled_gradient_checks_real_bf16_gradients",
@@ -57,20 +57,6 @@ collect_ignore = [
57]57]
58 58 
59 59 
60-_DEFERRED_ROUTING_TESTS = {
61- "test_forward_only_preserves_batch_and_forwards_model_metadata",
62- "test_rollback_restores_training_state_and_restarts_iterator",
63- "test_spike_recovery_warmup_active_drain_and_normal",
64- "test_replay_failure_cleans_state_and_blocks_checkpoint",
65- "test_recording_failure_resets_routing_before_next_forward",
66- "test_compiled_routes_share_graphs_across_layers_modes_and_microbatches",
67- "test_capture_compile_failure_preserves_upstream_entry_and_state",
68- "test_compiled_capture_preserves_hooks_and_rng",
69- "test_compiled_spike_recovery_runs_capture_and_replay_without_recompiling",
70- "test_compiled_capture_keeps_disabled_hooks_outside_graph",
71-}
72- 
73- 
74# Mixed modules retain their text cases; entries may name a whole vision class.60# Mixed modules retain their text cases; entries may name a whole vision class.
75_DEFERRED_VISION_TESTS = {61_DEFERRED_VISION_TESTS = {
76 "models/qwen3_5/test_qwen3_5_torchvision_dependency.py": {62 "models/qwen3_5/test_qwen3_5_torchvision_dependency.py": {
@@ -116,11 +102,6 @@ def pytest_collection_modifyitems(items):
116 if not item.path.is_relative_to(_REPO / "tests/unit_tests"):102 if not item.path.is_relative_to(_REPO / "tests/unit_tests"):
117 continue103 continue
118 relative_path = item.path.relative_to(_REPO / "tests/unit_tests").as_posix()104 relative_path = item.path.relative_to(_REPO / "tests/unit_tests").as_posix()
119- if (
120- relative_path == "extensions/experiment/anticipatory_routing/test_anticipatory_routing.py"
121- and getattr(item, "originalname", item.name) in _DEFERRED_ROUTING_TESTS
122- ):
123- item.add_marker(pytest.mark.skip(reason="Anticipatory routing CPU fixture migration is deferred to #238"))
124 vision_names = _DEFERRED_VISION_TESTS.get(relative_path, ())105 vision_names = _DEFERRED_VISION_TESTS.get(relative_path, ())
125 is_vision = any(getattr(node, "originalname", node.name) in vision_names for node in item.listchain())106 is_vision = any(getattr(node, "originalname", node.name) in vision_names for node in item.listchain())
126 if relative_path.startswith("models/deepseek_v4_1/"):107 if relative_path.startswith("models/deepseek_v4_1/"):
@@ -24,7 +24,7 @@ from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import Rout
24from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig24from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig
25from torchtitan_npu.extensions.experiment.anticipatory_routing.router import build_routing_cache25from torchtitan_npu.extensions.experiment.anticipatory_routing.router import build_routing_cache
26from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase26from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase
27-from torchtitan_npu.extensions.torchtitan.trainer import TrainingEngineEx, TrainerEx27+from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx, TrainingEngineEx
28 28 
29 29 
30class Scheduler(torch.optim.lr_scheduler.StepLR):30class Scheduler(torch.optim.lr_scheduler.StepLR):
@@ -36,7 +36,8 @@ class Microbatch(TrainingMicrobatch):
36 def __init__(self, inputs, labels, num_valid_tokens=1):36 def __init__(self, inputs, labels, num_valid_tokens=1):
37 self.inputs = inputs37 self.inputs = inputs
38 self.labels = labels38 self.labels = labels
39- self.num_valid_tokens = num_valid_tokens39+ self.loss_token_counts = torch.tensor(num_valid_tokens)
40+ self.routing_token_counts = torch.tensor([num_valid_tokens])
40 41 
41 def as_input_dict(self):42 def as_input_dict(self):
42 return {**self.inputs, "labels": self.labels}43 return {**self.inputs, "labels": self.labels}
@@ -89,7 +90,7 @@ class Model(nn.Module):
89 self.register_buffer("counter", torch.tensor(0.0))90 self.register_buffer("counter", torch.tensor(0.0))
90 91 
91 def preprocess_inputs(self, batch, **kwargs):92 def preprocess_inputs(self, batch, **kwargs):
92- return batch["input"], batch["labels"], {}93+ return batch["input"], batch["labels"], {}, {}
93 94 
94 def forward(self, x):95 def forward(self, x):
95 self.counter.add_(1)96 self.counter.add_(1)
@@ -102,7 +103,7 @@ def test_forward_only_preserves_batch_and_forwards_model_metadata():
102 103 
103 class ForwardModel(nn.Module):104 class ForwardModel(nn.Module):
104 def preprocess_inputs(self, batch, **kwargs):105 def preprocess_inputs(self, batch, **kwargs):
105- return batch.pop("input"), batch.pop("labels"), batch106+ return batch.pop("input"), batch.pop("labels"), batch, {}
106 107 
107 def forward(self, inputs, *, positions):108 def forward(self, inputs, *, positions):
108 self.seen = (inputs, positions)109 self.seen = (inputs, positions)
@@ -112,7 +113,7 @@ def test_forward_only_preserves_batch_and_forwards_model_metadata():
112 engine.runtime = make_runtime(model)113 engine.runtime = make_runtime(model)
113 inputs, positions, labels = torch.tensor([1]), torch.tensor([2]), torch.tensor([3])114 inputs, positions, labels = torch.tensor([1]), torch.tensor([2]), torch.tensor([3])
114 batch = Microbatch({"input": inputs, "positions": positions, "num_valid_tokens": 1}, labels)115 batch = Microbatch({"input": inputs, "positions": positions, "num_valid_tokens": 1}, labels)
115- engine.forward_only_microbatch(batch)116+ engine.forward_only_microbatch(batch, global_routing_token_counts=torch.tensor([1]))
116 torch.testing.assert_close(model.seen, (inputs, positions))117 torch.testing.assert_close(model.seen, (inputs, positions))
117 assert batch.inputs["num_valid_tokens"] == 1118 assert batch.inputs["num_valid_tokens"] == 1
118 assert set(batch.inputs) == {"input", "positions", "num_valid_tokens"}119 assert set(batch.inputs) == {"input", "positions", "num_valid_tokens"}
@@ -132,6 +133,7 @@ def make_trainer(monkeypatch, *, delay=2, active=3, size=40, steps=10, device="c
132 training=SimpleNamespace(133 training=SimpleNamespace(
133 steps=steps,134 steps=steps,
134 disable_cuda_graphs=True,135 disable_cuda_graphs=True,
136+ preprocess_microbatch_groups_lazily=False,
135 max_context_length=1,137 max_context_length=1,
136 num_tokens_per_microbatch_per_dp_rank=1,138 num_tokens_per_microbatch_per_dp_rank=1,
137 ),139 ),
@@ -153,11 +155,16 @@ def make_trainer(monkeypatch, *, delay=2, active=3, size=40, steps=10, device="c
153 activate_spmd=lambda **kwargs: nullcontext(),155 activate_spmd=lambda **kwargs: nullcontext(),
154 )156 )
155 trainer.metrics_processor = SimpleNamespace(157 trainer.metrics_processor = SimpleNamespace(
156- ntokens_since_last_log=0, data_loading_times=[], should_log=lambda step: False158+ ntokens_since_last_log=0,
159+ data_loading_times=[],
160+ should_log=lambda step: False,
161+ step_last_log=-1,
162+ reset=lambda: None,
157 )163 )
158 runtime.sdc_replayer = None164 runtime.sdc_replayer = None
159 runtime._sdc = None165 runtime._sdc = None
160- runtime.gc_handler = SimpleNamespace(run=lambda step: None)166+ runtime._cuda_graph_per_microbatch_group_enabled = False
167+ runtime.garbage_collector = SimpleNamespace(run=lambda step: None)
161 runtime.max_num_documents = None168 runtime.max_num_documents = None
162 runtime.preprocess_inputs_kwargs = {}169 runtime.preprocess_inputs_kwargs = {}
163 runtime._run_forward_backward = lambda groups, tokens: runtime._forward_backward_body(170 runtime._run_forward_backward = lambda groups, tokens: runtime._forward_backward_body(
@@ -172,6 +179,9 @@ def make_trainer(monkeypatch, *, delay=2, active=3, size=40, steps=10, device="c
172 optim.optimizers = torch.optim.SGD(optim.parameters, lr=0.001, momentum=0.9, foreach=False, fused=False)179 optim.optimizers = torch.optim.SGD(optim.parameters, lr=0.001, momentum=0.9, foreach=False, fused=False)
173 optim.lr_schedulers = Scheduler(optim.optimizers, step_size=1, gamma=0.9)180 optim.lr_schedulers = Scheduler(optim.optimizers, step_size=1, gamma=0.9)
174 optim.ema = None181 optim.ema = None
182+ # CPU fixture bypasses the accelerator cache warmup but retains real updates.
183+ optim._is_first_step_call = False
184+ optim.gradient_clipper = optim.config.gradient_clipper.build()
175 optim._run_update = optim._update185 optim._run_update = optim._update
176 saves = []186 saves = []
177 187 
@@ -188,9 +198,9 @@ def make_trainer(monkeypatch, *, delay=2, active=3, size=40, steps=10, device="c
188 cache = trainer.anticipatory_schedule.cache198 cache = trainer.anticipatory_schedule.cache
189 trained = []199 trained = []
190 200 
191- def loss_fn(prediction, labels, *, global_valid_tokens):201+ def loss_fn(prediction, labels, *, global_loss_token_counts):
192 trained.append((runtime.num_completed_steps + 1, int(labels.item()), cache.mode))202 trained.append((runtime.num_completed_steps + 1, int(labels.item()), cache.mode))
193- return prediction.square().sum() / global_valid_tokens, {}203+ return prediction.square().sum() / global_loss_token_counts, {}
194 204 
195 runtime.loss_fn = loss_fn205 runtime.loss_fn = loss_fn
196 return trainer, trained206 return trainer, trained
@@ -481,7 +491,7 @@ def test_recording_failure_resets_routing_before_next_forward(monkeypatch, stage
481 model = trainer.engine.model_parts[0]491 model = trainer.engine.model_parts[0]
482 batch = Microbatch({"input": torch.ones(1, 1, 2)}, torch.zeros(1))492 batch = Microbatch({"input": torch.ones(1, 1, 2)}, torch.zeros(1))
483 if stage != "initialization":493 if stage != "initialization":
484- engine.initialize_routing(cache, batch)494+ engine.initialize_routing(cache, batch, global_routing_token_counts=torch.tensor([1]))
485 before = deepcopy(model.state_dict())495 before = deepcopy(model.state_dict())
486 failure = RuntimeError("injected recording failure")496 failure = RuntimeError("injected recording failure")
487 497 
@@ -496,7 +506,7 @@ def test_recording_failure_resets_routing_before_next_forward(monkeypatch, stage
496 try:506 try:
497 with pytest.raises(RuntimeError) as caught:507 with pytest.raises(RuntimeError) as caught:
498 if stage == "initialization":508 if stage == "initialization":
499- engine.initialize_routing(cache, batch)509+ engine.initialize_routing(cache, batch, global_routing_token_counts=torch.tensor([1]))
500 else:510 else:
501 schedule._prefetch_and_capture(schedule.data)511 schedule._prefetch_and_capture(schedule.data)
502 finally:512 finally:
@@ -663,7 +673,7 @@ def test_compiled_routes_share_graphs_across_layers_modes_and_microbatches(
663 self.layers = nn.ModuleList([checkpoint_wrapper(Block()) if full_ac else Block() for _ in range(40)])673 self.layers = nn.ModuleList([checkpoint_wrapper(Block()) if full_ac else Block() for _ in range(40)])
664 674 
665 def preprocess_inputs(self, batch, **kwargs):675 def preprocess_inputs(self, batch, **kwargs):
666- return batch["input"], batch["labels"], {}676+ return batch["input"], batch["labels"], {}, {}
667 677 
668 def forward(self, x):678 def forward(self, x):
669 for layer in self.layers:679 for layer in self.layers:
@@ -695,7 +705,9 @@ def test_compiled_routes_share_graphs_across_layers_modes_and_microbatches(
695 def update(module, routing, inputs, slots=None, index=0):705 def update(module, routing, inputs, slots=None, index=0):
696 module.zero_grad(set_to_none=True)706 module.zero_grad(set_to_none=True)
697 inputs = inputs.detach().clone().requires_grad_()707 inputs = inputs.detach().clone().requires_grad_()
698- make_engine(module).initialize_routing(routing, Microbatch({"input": inputs}, torch.zeros(1)))708+ make_engine(module).initialize_routing(
709+ routing, Microbatch({"input": inputs}, torch.zeros(1)), global_routing_token_counts=torch.tensor([1])
710+ )
699 try:711 try:
700 routing.begin_training(slots)712 routing.begin_training(slots)
701 routing.select(index)713 routing.select(index)
@@ -723,7 +735,9 @@ def test_compiled_routes_share_graphs_across_layers_modes_and_microbatches(
723 slot = {}735 slot = {}
724 try:736 try:
725 cache.begin_capture(slot)737 cache.begin_capture(slot)
726- engine.forward_only_microbatch(Microbatch({"input": inputs}, torch.zeros(1)))738+ engine.forward_only_microbatch(
739+ Microbatch({"input": inputs}, torch.zeros(1)), global_routing_token_counts=torch.tensor([1])
740+ )
727 cache.save_captured_routes()741 cache.save_captured_routes()
728 finally:742 finally:
729 cache.reset()743 cache.reset()
@@ -732,7 +746,9 @@ def test_compiled_routes_share_graphs_across_layers_modes_and_microbatches(
732 expected = {}746 expected = {}
733 try:747 try:
734 reference_cache.begin_capture(expected)748 reference_cache.begin_capture(expected)
735- make_engine(reference).forward_only_microbatch(Microbatch({"input": inputs}, torch.zeros(1)))749+ make_engine(reference).forward_only_microbatch(
750+ Microbatch({"input": inputs}, torch.zeros(1)), global_routing_token_counts=torch.tensor([1])
751+ )
736 reference_cache.save_captured_routes()752 reference_cache.save_captured_routes()
737 finally:753 finally:
738 reference_cache.reset()754 reference_cache.reset()
@@ -748,7 +764,9 @@ def test_compiled_routes_share_graphs_across_layers_modes_and_microbatches(
748 first = torch.tensor([[[2.0, -2.0]]], device=device)764 first = torch.tensor([[[2.0, -2.0]]], device=device)
749 second = first.flip(-1)765 second = first.flip(-1)
750 before = deepcopy(model.state_dict())766 before = deepcopy(model.state_dict())
751- make_engine(model).initialize_routing(cache, Microbatch({"input": first}, torch.zeros(1)))767+ make_engine(model).initialize_routing(
768+ cache, Microbatch({"input": first}, torch.zeros(1)), global_routing_token_counts=torch.tensor([1])
769+ )
752 torch.testing.assert_close(model.state_dict(), before, rtol=0, atol=0)770 torch.testing.assert_close(model.state_dict(), before, rtol=0, atol=0)
753 assert not graphs # Shape initialization is isolated, eager and runs only once.771 assert not graphs # Shape initialization is isolated, eager and runs only once.
754 compare_update(first)772 compare_update(first)
@@ -844,11 +862,11 @@ def test_capture_compile_failure_preserves_upstream_entry_and_state():
844 rng = torch.get_rng_state().clone()862 rng = torch.get_rng_state().clone()
845 slot = {}863 slot = {}
846 try:864 try:
847- engine.initialize_routing(cache, batch)865+ engine.initialize_routing(cache, batch, global_routing_token_counts=torch.tensor([1]))
848 with pytest.raises(RuntimeError, match="capture compiler failed"):866 with pytest.raises(RuntimeError, match="capture compiler failed"):
849 try:867 try:
850 cache.begin_capture(slot)868 cache.begin_capture(slot)
851- engine.forward_only_microbatch(batch)869+ engine.forward_only_microbatch(batch, global_routing_token_counts=torch.tensor([1]))
852 cache.save_captured_routes()870 cache.save_captured_routes()
853 finally:871 finally:
854 cache.reset()872 cache.reset()
@@ -885,11 +903,11 @@ def test_compiled_capture_preserves_hooks_and_rng():
885 rng = torch.get_rng_state().clone()903 rng = torch.get_rng_state().clone()
886 before = deepcopy(model.state_dict())904 before = deepcopy(model.state_dict())
887 try:905 try:
888- engine.initialize_routing(cache, batch)906+ engine.initialize_routing(cache, batch, global_routing_token_counts=torch.tensor([1]))
889 slot = {}907 slot = {}
890 try:908 try:
891 cache.begin_capture(slot)909 cache.begin_capture(slot)
892- engine.forward_only_microbatch(batch)910+ engine.forward_only_microbatch(batch, global_routing_token_counts=torch.tensor([1]))
893 cache.save_captured_routes()911 cache.save_captured_routes()
894 finally:912 finally:
895 cache.reset()913 cache.reset()
@@ -993,13 +1011,13 @@ def test_compiled_capture_keeps_disabled_hooks_outside_graph(monkeypatch, full_a
993 batch = Microbatch({"input": torch.tensor([[[2.0, -2.0]]])}, torch.zeros(1))1011 batch = Microbatch({"input": torch.tensor([[[2.0, -2.0]]])}, torch.zeros(1))
994 before = deepcopy(model.state_dict())1012 before = deepcopy(model.state_dict())
995 try:1013 try:
996- engine.initialize_routing(cache, batch)1014+ engine.initialize_routing(cache, batch, global_routing_token_counts=torch.tensor([1]))
997 events.clear()1015 events.clear()
998 for _ in range(2):1016 for _ in range(2):
999 slot = {}1017 slot = {}
1000 try:1018 try:
1001 cache.begin_capture(slot)1019 cache.begin_capture(slot)
1002- engine.forward_only_microbatch(batch)1020+ engine.forward_only_microbatch(batch, global_routing_token_counts=torch.tensor([1]))
1003 cache.save_captured_routes()1021 cache.save_captured_routes()
1004 finally:1022 finally:
1005 cache.reset()1023 cache.reset()
@@ -1016,3 +1034,59 @@ def test_compiled_capture_keeps_disabled_hooks_outside_graph(monkeypatch, full_a
1016 assert all(parameter.grad is not None for parameter in model.parameters())1034 assert all(parameter.grad is not None for parameter in model.parameters())
1017 finally:1035 finally:
1018 torch._dynamo.reset()1036 torch._dynamo.reset()
1037+ 
1038+ 
1039+@pytest.mark.parametrize("dp_enabled", [False, True], ids=["local", "dp-reduced"])
1040+def test_step_routing_counts_reach_recording_and_replay(monkeypatch, dp_enabled):
1041+ from torchtitan_npu.extensions.experiment.anticipatory_routing import engine as engine_module
1042+ 
1043+ trainer, _ = make_trainer(monkeypatch)
1044+ schedule = trainer.anticipatory_schedule
1045+ runtime = trainer.engine
1046+ batches = [
1047+ Microbatch({"input": torch.tensor([[[1.0, 0.0]]])}, torch.tensor([[0]]), 2),
1048+ Microbatch({"input": torch.tensor([[[2.0, 0.0]]])}, torch.tensor([[1]]), 3),
1049+ ]
1050+ batches[0].routing_token_counts = torch.tensor([2, 1])
1051+ batches[1].routing_token_counts = torch.tensor([3, 2])
1052+ original_counts = [batch.routing_token_counts.clone() for batch in batches]
1053+ expected = torch.tensor([12, 7] if dp_enabled else [5, 3])
1054+ reductions = []
1055+ mesh = object()
1056+ runtime.parallelism_context.dp_enabled = dp_enabled
1057+ runtime.parallelism_context.get_mesh = lambda name: mesh if name == "dp" else None
1058+ 
1059+ def sum_counts(value, actual_mesh):
1060+ # Isolate the distributed transport, checking local counts at its boundary.
1061+ assert actual_mesh is mesh
1062+ reductions.append(value.clone())
1063+ if value.numel() == 2:
1064+ torch.testing.assert_close(value, torch.tensor([5, 3]))
1065+ return value + torch.tensor([7, 4])
1066+ torch.testing.assert_close(value, torch.tensor([5, 5, 3]))
1067+ return value + torch.tensor([7, 7, 4])
1068+ 
1069+ monkeypatch.setattr(engine_module.dist_utils, "dist_sum_tensor", sum_counts)
1070+ model = runtime.model_parts[0]
1071+ original_preprocess = model.preprocess_inputs
1072+ received = []
1073+ 
1074+ def preprocess(batch, **kwargs):
1075+ received.append(kwargs["global_routing_token_counts"].clone())
1076+ return original_preprocess(batch, **kwargs)
1077+ 
1078+ monkeypatch.setattr(model, "preprocess_inputs", preprocess)
1079+ monkeypatch.setattr(Loader, "__iter__", lambda self: iter(batches))
1080+ assert schedule._prefetch_and_capture(schedule.data)
1081+ capture_calls = len(received)
1082+ assert capture_calls == 3 # Initialization and two recorded microbatches.
1083+ run_step(trainer)
1084+ assert len(received) == capture_calls + 2
1085+ for counts in received:
1086+ torch.testing.assert_close(counts, expected)
1087+ for batch, original in zip(batches, original_counts, strict=True):
1088+ torch.testing.assert_close(batch.routing_token_counts, original)
1089+ assert len(reductions) == (2 if dp_enabled else 0)
1090+ # Both losses use the step denominator, not each microbatch's count.
1091+ assert schedule.engine.last_global_loss == pytest.approx(5 / (12 if dp_enabled else 5))
1092+ assert not schedule._queue and schedule.phase is Phase.NORMAL