luclima commited on
Commit
2ceca3e
·
verified ·
1 Parent(s): 4e9d621

Upload folder using huggingface_hub (part 49)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/conftest.py +0 -0
  2. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/__init__.py +0 -0
  3. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/conftest.py +0 -0
  4. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_executor.py +334 -0
  5. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_planner.py +336 -0
  6. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/__init__.py +0 -0
  7. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/conftest.py +0 -0
  8. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_executor.py +292 -0
  9. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_planner.py +259 -0
  10. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/test_axis_aligner.py +555 -0
  11. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/__init__.py +0 -0
  12. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/conftest.py +0 -0
  13. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_loader.py +388 -0
  14. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_plugins.py +248 -0
  15. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_concat_steps.py +86 -0
  16. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_executor.py +459 -0
  17. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_planner.py +575 -0
  18. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_thd_seq_lens_loader.py +172 -0
  19. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/__init__.py +0 -0
  20. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/conftest.py +0 -0
  21. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_executor.py +1097 -0
  22. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_parallel_info.py +100 -0
  23. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_planner.py +2067 -0
  24. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/conftest.py +40 -0
  25. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/__init__.py +0 -0
  26. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dim_parser.py +152 -0
  27. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dims_parser.py +295 -0
  28. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_tensor_naming.py +98 -0
  29. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_types.py +28 -0
  30. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/__init__.py +0 -0
  31. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/conftest.py +0 -0
  32. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_comparator.py +380 -0
  33. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_formatter.py +1113 -0
  34. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_types.py +262 -0
  35. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_comparator.py +210 -0
  36. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_matcher.py +341 -0
  37. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_display.py +500 -0
  38. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dp_utils.py +350 -0
  39. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dump_loader.py +62 -0
  40. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_e2e_demo.py +249 -0
  41. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_entrypoint.py +0 -0
  42. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_log_sink.py +118 -0
  43. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_manually_verify.py +295 -0
  44. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_meta_overrider.py +298 -0
  45. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_model_validation.py +471 -0
  46. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_output_types.py +771 -0
  47. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_per_token_visualizer.py +159 -0
  48. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_preset.py +51 -0
  49. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_utils.py +485 -0
  50. asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_visualizer.py +96 -0
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/conftest.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/__init__.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/conftest.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_executor.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.executor import (
7
+ AlignerResult,
8
+ StepPlansResult,
9
+ SubPlansResult,
10
+ _execute_step_plans,
11
+ execute_aligner_plan,
12
+ execute_sub_plan,
13
+ execute_sub_plans,
14
+ )
15
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import (
16
+ AlignerPerStepPlan,
17
+ AlignerPlan,
18
+ )
19
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import (
20
+ TokenAlignerPlan,
21
+ TokenLocator,
22
+ )
23
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import (
24
+ ConcatParams,
25
+ UnsharderPlan,
26
+ )
27
+ from sglang.srt.debug_utils.comparator.dims_spec import (
28
+ ParallelAxis,
29
+ TokenLayout,
30
+ apply_dim_names,
31
+ without_dim_names,
32
+ )
33
+ from sglang.srt.debug_utils.comparator.utils import Pair
34
+ from sglang.test.ci.ci_register import register_cpu_ci
35
+
36
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
37
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
38
+
39
+
40
+ class TestExecuteSubPlans:
41
+ def test_empty_tensors_returns_none(self) -> None:
42
+ r: SubPlansResult = execute_sub_plans(tensors=[], plans=[])
43
+ assert r.tensor is None
44
+ assert r.checks == []
45
+ assert r.snapshots == []
46
+
47
+ def test_no_plans_single_tensor_passthrough(self) -> None:
48
+ tensor: torch.Tensor = torch.tensor([1.0, 2.0, 3.0])
49
+ r: SubPlansResult = execute_sub_plans(tensors=[tensor], plans=[])
50
+ assert r.tensor is not None
51
+ assert torch.equal(r.tensor, tensor)
52
+ assert r.checks == []
53
+ assert r.snapshots == []
54
+
55
+ def test_no_plans_multiple_tensors_returns_none(self) -> None:
56
+ tensors: list[torch.Tensor] = [
57
+ torch.tensor([1.0]),
58
+ torch.tensor([2.0]),
59
+ ]
60
+ r: SubPlansResult = execute_sub_plans(tensors=tensors, plans=[])
61
+ assert r.tensor is None
62
+ assert r.checks == []
63
+ assert r.snapshots == []
64
+
65
+ def test_with_unsharder_plan(self) -> None:
66
+ t0: torch.Tensor = apply_dim_names(torch.tensor([[1.0, 2.0]]), ["b", "h"])
67
+ t1: torch.Tensor = apply_dim_names(torch.tensor([[3.0, 4.0]]), ["b", "h"])
68
+
69
+ plan = UnsharderPlan(
70
+ axis=ParallelAxis.TP,
71
+ params=ConcatParams(dim_name="h"),
72
+ groups=[[0, 1]],
73
+ )
74
+
75
+ r: SubPlansResult = execute_sub_plans(tensors=[t0, t1], plans=[plan])
76
+
77
+ assert r.tensor is not None
78
+ expected: torch.Tensor = torch.tensor([[1.0, 2.0, 3.0, 4.0]])
79
+ assert torch.equal(without_dim_names(r.tensor), expected)
80
+ assert r.checks == []
81
+ assert len(r.snapshots) == 1
82
+
83
+
84
+ class TestExecuteSubPlan:
85
+ def test_unknown_plan_type_raises(self) -> None:
86
+ class _FakePlan:
87
+ pass
88
+
89
+ with pytest.raises(NotImplementedError, match="Unknown"):
90
+ execute_sub_plan(tensors=[torch.tensor([1.0])], plan=_FakePlan())
91
+
92
+
93
+ class TestExecuteStepPlans:
94
+ def test_step_with_none_result_omitted(self) -> None:
95
+ tensors: list[torch.Tensor] = [
96
+ torch.tensor([1.0]),
97
+ torch.tensor([2.0]),
98
+ ]
99
+
100
+ step_plan = AlignerPerStepPlan(
101
+ step=0,
102
+ input_object_indices=[0, 1],
103
+ sub_plans=[],
104
+ )
105
+
106
+ r: StepPlansResult = _execute_step_plans(
107
+ tensors=tensors, step_plans=[step_plan]
108
+ )
109
+
110
+ assert r.tensors == {}
111
+ assert r.checks == []
112
+ assert len(r.traced_side.step_plans) == 1
113
+
114
+ def test_single_step_passthrough(self) -> None:
115
+ tensor: torch.Tensor = torch.tensor([1.0, 2.0])
116
+
117
+ step_plan = AlignerPerStepPlan(
118
+ step=5,
119
+ input_object_indices=[0],
120
+ sub_plans=[],
121
+ )
122
+
123
+ r: StepPlansResult = _execute_step_plans(
124
+ tensors=[tensor], step_plans=[step_plan]
125
+ )
126
+
127
+ assert 5 in r.tensors
128
+ assert torch.equal(r.tensors[5], tensor)
129
+ assert r.checks == []
130
+ assert len(r.traced_side.step_plans) == 1
131
+ assert r.traced_side.step_plans[0].step == 5
132
+
133
+
134
+ class TestExecuteAlignerPlan:
135
+ def _make_step_plan(self, *, step: int, indices: list[int]) -> AlignerPerStepPlan:
136
+ return AlignerPerStepPlan(step=step, input_object_indices=indices, sub_plans=[])
137
+
138
+ def test_x_side_empty_returns_failed_x(self) -> None:
139
+ plan = AlignerPlan(
140
+ per_step_plans=Pair(
141
+ x=[self._make_step_plan(step=0, indices=[0, 1])],
142
+ y=[self._make_step_plan(step=0, indices=[0])],
143
+ ),
144
+ token_aligner_plan=None,
145
+ )
146
+
147
+ tensors_pair: Pair[list[torch.Tensor]] = Pair(
148
+ x=[torch.tensor([1.0]), torch.tensor([2.0])],
149
+ y=[torch.tensor([3.0])],
150
+ )
151
+
152
+ result: AlignerResult = execute_aligner_plan(
153
+ tensors_pair=tensors_pair, plan=plan
154
+ )
155
+
156
+ assert result.tensors is None
157
+ assert result.failed_side_xy == "x"
158
+
159
+ def test_y_side_empty_returns_failed_y(self) -> None:
160
+ plan = AlignerPlan(
161
+ per_step_plans=Pair(
162
+ x=[self._make_step_plan(step=0, indices=[0])],
163
+ y=[self._make_step_plan(step=0, indices=[0, 1])],
164
+ ),
165
+ token_aligner_plan=None,
166
+ )
167
+
168
+ tensors_pair: Pair[list[torch.Tensor]] = Pair(
169
+ x=[torch.tensor([1.0])],
170
+ y=[torch.tensor([2.0]), torch.tensor([3.0])],
171
+ )
172
+
173
+ result: AlignerResult = execute_aligner_plan(
174
+ tensors_pair=tensors_pair, plan=plan
175
+ )
176
+
177
+ assert result.tensors is None
178
+ assert result.failed_side_xy == "y"
179
+
180
+ def test_no_token_aligner_single_step(self) -> None:
181
+ plan = AlignerPlan(
182
+ per_step_plans=Pair(
183
+ x=[self._make_step_plan(step=0, indices=[0])],
184
+ y=[self._make_step_plan(step=0, indices=[0])],
185
+ ),
186
+ token_aligner_plan=None,
187
+ )
188
+
189
+ t_x: torch.Tensor = torch.tensor([1.0, 2.0])
190
+ t_y: torch.Tensor = torch.tensor([3.0, 4.0])
191
+ tensors_pair: Pair[list[torch.Tensor]] = Pair(x=[t_x], y=[t_y])
192
+
193
+ result: AlignerResult = execute_aligner_plan(
194
+ tensors_pair=tensors_pair, plan=plan
195
+ )
196
+
197
+ assert result.tensors is not None
198
+ assert result.failed_side_xy is None
199
+ assert torch.equal(result.tensors.x, t_x)
200
+ assert torch.equal(result.tensors.y, t_y)
201
+
202
+ def test_success_returns_none_failed_side(self) -> None:
203
+ plan = AlignerPlan(
204
+ per_step_plans=Pair(
205
+ x=[self._make_step_plan(step=0, indices=[0])],
206
+ y=[self._make_step_plan(step=0, indices=[0])],
207
+ ),
208
+ token_aligner_plan=None,
209
+ )
210
+
211
+ tensors_pair: Pair[list[torch.Tensor]] = Pair(
212
+ x=[torch.tensor([10.0])],
213
+ y=[torch.tensor([20.0])],
214
+ )
215
+
216
+ result: AlignerResult = execute_aligner_plan(
217
+ tensors_pair=tensors_pair, plan=plan
218
+ )
219
+
220
+ assert result.failed_side_xy is None
221
+ assert result.tensors is not None
222
+
223
+
224
+ class TestExecuteAlignerPlanWithTokenDim:
225
+ """End-to-end tests for AlignerPlan with non-zero token_dim."""
226
+
227
+ def _make_step_plan(self, *, step: int, indices: list[int]) -> AlignerPerStepPlan:
228
+ return AlignerPerStepPlan(step=step, input_object_indices=indices, sub_plans=[])
229
+
230
+ def test_token_dim_nonzero_e2e(self) -> None:
231
+ """AlignerPlan with token at dim 1 passes through to token aligner correctly."""
232
+ torch.manual_seed(42)
233
+
234
+ # shape [3, 4, 8]: dim0=a, dim1=token(4 tokens), dim2=hidden
235
+ tensor_x: torch.Tensor = apply_dim_names(torch.randn(3, 4, 8), ["a", "t", "h"])
236
+ tensor_y: torch.Tensor = apply_dim_names(torch.randn(3, 4, 8), ["a", "t", "h"])
237
+
238
+ locator_x = TokenLocator(
239
+ steps=[0, 0, 0],
240
+ token_index_in_step=[0, 1, 2],
241
+ )
242
+ locator_y = TokenLocator(
243
+ steps=[0, 0, 0],
244
+ token_index_in_step=[0, 1, 2],
245
+ )
246
+ token_plan = TokenAlignerPlan(
247
+ locators=Pair(x=locator_x, y=locator_y),
248
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.T),
249
+ )
250
+
251
+ plan = AlignerPlan(
252
+ per_step_plans=Pair(
253
+ x=[self._make_step_plan(step=0, indices=[0])],
254
+ y=[self._make_step_plan(step=0, indices=[0])],
255
+ ),
256
+ token_aligner_mode="smart",
257
+ token_aligner_plan=token_plan,
258
+ )
259
+
260
+ tensors_pair: Pair[list[torch.Tensor]] = Pair(x=[tensor_x], y=[tensor_y])
261
+ result: AlignerResult = execute_aligner_plan(
262
+ tensors_pair=tensors_pair, plan=plan
263
+ )
264
+
265
+ assert result.tensors is not None
266
+ assert result.failed_side_xy is None
267
+ # token dim stays at dim 1 -> shape [3, 3, 8] (3 tokens selected from 4)
268
+ assert result.tensors.x.shape == (3, 3, 8)
269
+ assert result.tensors.y.shape == (3, 3, 8)
270
+
271
+ plain_x: torch.Tensor = without_dim_names(tensor_x)
272
+ plain_y: torch.Tensor = without_dim_names(tensor_y)
273
+ for i in range(3):
274
+ assert torch.equal(
275
+ result.tensors.x.select(dim=1, index=i),
276
+ plain_x.select(dim=1, index=i),
277
+ )
278
+ assert torch.equal(
279
+ result.tensors.y.select(dim=1, index=i),
280
+ plain_y.select(dim=1, index=i),
281
+ )
282
+
283
+ def test_bshd_cross_layout_e2e(self) -> None:
284
+ """x=SGLang THD, y=Megatron BSHD: planner->executor full flow."""
285
+ torch.manual_seed(42)
286
+
287
+ # x side: THD layout, shape [6, 8] (6 tokens, hidden=8), pre-named
288
+ tensor_x: torch.Tensor = apply_dim_names(torch.randn(6, 8), ["t", "h"])
289
+
290
+ # y side: BSHD layout, shape [2, 3, 8] (B=2, S=3, H=8), pre-named
291
+ tensor_y: torch.Tensor = apply_dim_names(torch.randn(2, 3, 8), ["b", "s", "h"])
292
+ flat_y: torch.Tensor = tensor_y.reshape(6, 8)
293
+
294
+ locator = TokenLocator(
295
+ steps=[0, 0, 0],
296
+ token_index_in_step=[0, 2, 5],
297
+ )
298
+ token_plan = TokenAlignerPlan(
299
+ locators=Pair(x=locator, y=locator),
300
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.BS),
301
+ )
302
+
303
+ plan = AlignerPlan(
304
+ per_step_plans=Pair(
305
+ x=[self._make_step_plan(step=0, indices=[0])],
306
+ y=[self._make_step_plan(step=0, indices=[0])],
307
+ ),
308
+ token_aligner_mode="smart",
309
+ token_aligner_plan=token_plan,
310
+ )
311
+
312
+ tensors_pair: Pair[list[torch.Tensor]] = Pair(x=[tensor_x], y=[tensor_y])
313
+ result: AlignerResult = execute_aligner_plan(
314
+ tensors_pair=tensors_pair, plan=plan
315
+ )
316
+
317
+ assert result.tensors is not None
318
+ assert result.failed_side_xy is None
319
+
320
+ assert result.tensors.x.shape == (3, 8)
321
+ assert result.tensors.y.shape == (3, 8)
322
+
323
+ plain_x: torch.Tensor = without_dim_names(tensor_x)
324
+ assert torch.equal(result.tensors.x[0], plain_x[0])
325
+ assert torch.equal(result.tensors.x[1], plain_x[2])
326
+ assert torch.equal(result.tensors.x[2], plain_x[5])
327
+
328
+ assert torch.equal(result.tensors.y[0], flat_y[0])
329
+ assert torch.equal(result.tensors.y[1], flat_y[2])
330
+ assert torch.equal(result.tensors.y[2], flat_y[5])
331
+
332
+
333
+ if __name__ == "__main__":
334
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_planner.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Any, Optional
3
+
4
+ import pytest
5
+
6
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.planner import (
7
+ _compute_per_step_plans,
8
+ compute_aligner_plan,
9
+ compute_per_step_sub_plans,
10
+ )
11
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import (
12
+ AlignerPerStepPlan,
13
+ AlignerPerStepSubPlan,
14
+ AlignerPlan,
15
+ )
16
+ from sglang.srt.debug_utils.comparator.aligner.reorderer.types import (
17
+ ReordererPlan,
18
+ ZigzagToNaturalThdParams,
19
+ )
20
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import (
21
+ CpThdConcatParams,
22
+ UnsharderPlan,
23
+ )
24
+ from sglang.srt.debug_utils.comparator.dims_spec import TokenLayout
25
+ from sglang.srt.debug_utils.comparator.utils import Pair
26
+ from sglang.test.ci.ci_register import register_cpu_ci
27
+
28
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
29
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
30
+
31
+
32
+ def _make_meta(
33
+ *,
34
+ step: int = 0,
35
+ dims: Optional[str] = None,
36
+ tp_rank: int = 0,
37
+ tp_size: int = 1,
38
+ cp_rank: int = 0,
39
+ cp_size: int = 1,
40
+ extra_parallel_info: Optional[dict[str, int]] = None,
41
+ ) -> dict[str, Any]:
42
+ meta: dict[str, Any] = {"step": step}
43
+ if dims is not None:
44
+ meta["dims"] = dims
45
+ parallel_info: dict[str, int] = {
46
+ "tp_rank": tp_rank,
47
+ "tp_size": tp_size,
48
+ "cp_rank": cp_rank,
49
+ "cp_size": cp_size,
50
+ }
51
+ if extra_parallel_info is not None:
52
+ parallel_info.update(extra_parallel_info)
53
+ meta["sglang_parallel_info"] = parallel_info
54
+ return meta
55
+
56
+
57
+ class TestComputePerStepSubPlans:
58
+ def test_empty_metas(self) -> None:
59
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(metas=[])
60
+ assert result == []
61
+
62
+ def test_single_meta(self) -> None:
63
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(
64
+ metas=[_make_meta(dims="b h[tp]", tp_size=2)]
65
+ )
66
+ assert result == []
67
+
68
+ def test_dims_none(self) -> None:
69
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(
70
+ metas=[
71
+ _make_meta(tp_rank=0, tp_size=2),
72
+ _make_meta(tp_rank=1, tp_size=2),
73
+ ]
74
+ )
75
+ assert result == []
76
+
77
+ def test_tp_sharded_returns_unsharder_plan(self) -> None:
78
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(
79
+ metas=[
80
+ _make_meta(dims="b h[tp]", tp_rank=0, tp_size=2),
81
+ _make_meta(dims="b h[tp]", tp_rank=1, tp_size=2),
82
+ ]
83
+ )
84
+ assert len(result) >= 1
85
+ unsharder_plans: list[UnsharderPlan] = [
86
+ p for p in result if isinstance(p, UnsharderPlan)
87
+ ]
88
+ assert len(unsharder_plans) >= 1
89
+
90
+ def test_zigzag_returns_both_plans(self) -> None:
91
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(
92
+ metas=[
93
+ _make_meta(dims="b s[cp:zigzag] h", cp_rank=0, cp_size=2),
94
+ _make_meta(dims="b s[cp:zigzag] h", cp_rank=1, cp_size=2),
95
+ ]
96
+ )
97
+ unsharder_plans: list[UnsharderPlan] = [
98
+ p for p in result if isinstance(p, UnsharderPlan)
99
+ ]
100
+ reorderer_plans: list[ReordererPlan] = [
101
+ p for p in result if isinstance(p, ReordererPlan)
102
+ ]
103
+ assert len(unsharder_plans) >= 1
104
+ assert len(reorderer_plans) >= 1
105
+
106
+
107
+ class TestComputePerStepPlans:
108
+ def test_groups_by_step(self) -> None:
109
+ metas: list[dict[str, Any]] = [
110
+ _make_meta(step=0, tp_rank=0, tp_size=2),
111
+ _make_meta(step=0, tp_rank=1, tp_size=2),
112
+ _make_meta(step=1, tp_rank=0, tp_size=1),
113
+ ]
114
+ result: list[AlignerPerStepPlan] = _compute_per_step_plans(metas=metas)
115
+
116
+ assert len(result) == 2
117
+ assert result[0].step == 0
118
+ assert result[0].input_object_indices == [0, 1]
119
+ assert result[1].step == 1
120
+ assert result[1].input_object_indices == [2]
121
+
122
+ def test_sorted_by_step(self) -> None:
123
+ metas: list[dict[str, Any]] = [
124
+ _make_meta(step=2),
125
+ _make_meta(step=0),
126
+ _make_meta(step=1),
127
+ ]
128
+ result: list[AlignerPerStepPlan] = _compute_per_step_plans(metas=metas)
129
+
130
+ steps: list[int] = [p.step for p in result]
131
+ assert steps == [0, 1, 2]
132
+
133
+ def test_single_meta_per_step_empty_sub_plans(self) -> None:
134
+ metas: list[dict[str, Any]] = [
135
+ _make_meta(step=0),
136
+ _make_meta(step=1),
137
+ ]
138
+ result: list[AlignerPerStepPlan] = _compute_per_step_plans(metas=metas)
139
+
140
+ assert len(result) == 2
141
+ assert all(plan.sub_plans == [] for plan in result)
142
+
143
+
144
+ class TestComputeAlignerPlan:
145
+ def test_wraps_both_sides(self) -> None:
146
+ metas_x: list[dict[str, Any]] = [_make_meta(step=0)]
147
+ metas_y: list[dict[str, Any]] = [_make_meta(step=0)]
148
+
149
+ plan: AlignerPlan = compute_aligner_plan(
150
+ metas_pair=Pair(x=metas_x, y=metas_y),
151
+ token_aligner_mode=None,
152
+ token_aligner_plan=None,
153
+ )
154
+
155
+ assert len(plan.per_step_plans.x) == 1
156
+ assert len(plan.per_step_plans.y) == 1
157
+ assert plan.token_aligner_plan is None
158
+
159
+ def test_preserves_token_aligner_plan(self) -> None:
160
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import (
161
+ TokenAlignerPlan,
162
+ TokenLocator,
163
+ )
164
+
165
+ ta_plan = TokenAlignerPlan(
166
+ locators=Pair(
167
+ x=TokenLocator(steps=[0], token_index_in_step=[0]),
168
+ y=TokenLocator(steps=[0], token_index_in_step=[0]),
169
+ ),
170
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.T),
171
+ )
172
+
173
+ plan: AlignerPlan = compute_aligner_plan(
174
+ metas_pair=Pair(x=[_make_meta()], y=[_make_meta()]),
175
+ token_aligner_mode="smart",
176
+ token_aligner_plan=ta_plan,
177
+ )
178
+
179
+ assert plan.token_aligner_plan is ta_plan
180
+ assert plan.token_aligner_mode == "smart"
181
+
182
+
183
+ class TestComputePerStepSubPlansThd:
184
+ def test_thd_zigzag_returns_thd_plans(self) -> None:
185
+ """t[cp:zigzag] h[tp] generates THD-typed unsharder + reorderer plans."""
186
+ thd_global_seq_lens: list[int] = [100, 64, 92]
187
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(
188
+ metas=[
189
+ _make_meta(
190
+ dims="t[cp:zigzag] h[tp]",
191
+ cp_rank=0,
192
+ cp_size=2,
193
+ tp_rank=0,
194
+ tp_size=2,
195
+ ),
196
+ _make_meta(
197
+ dims="t[cp:zigzag] h[tp]",
198
+ cp_rank=0,
199
+ cp_size=2,
200
+ tp_rank=1,
201
+ tp_size=2,
202
+ ),
203
+ _make_meta(
204
+ dims="t[cp:zigzag] h[tp]",
205
+ cp_rank=1,
206
+ cp_size=2,
207
+ tp_rank=0,
208
+ tp_size=2,
209
+ ),
210
+ _make_meta(
211
+ dims="t[cp:zigzag] h[tp]",
212
+ cp_rank=1,
213
+ cp_size=2,
214
+ tp_rank=1,
215
+ tp_size=2,
216
+ ),
217
+ ],
218
+ thd_global_seq_lens=thd_global_seq_lens,
219
+ )
220
+
221
+ unsharder_plans: list[UnsharderPlan] = [
222
+ p for p in result if isinstance(p, UnsharderPlan)
223
+ ]
224
+ reorderer_plans: list[ReordererPlan] = [
225
+ p for p in result if isinstance(p, ReordererPlan)
226
+ ]
227
+
228
+ # Should have at least one THD concat plan for CP axis
229
+ thd_concat_plans: list[UnsharderPlan] = [
230
+ p for p in unsharder_plans if isinstance(p.params, CpThdConcatParams)
231
+ ]
232
+ assert len(thd_concat_plans) == 1
233
+ assert thd_concat_plans[0].params.seq_lens_per_rank == [50, 32, 46]
234
+
235
+ # Should have exactly one THD reorder plan
236
+ assert len(reorderer_plans) == 1
237
+ assert isinstance(reorderer_plans[0].params, ZigzagToNaturalThdParams)
238
+ assert reorderer_plans[0].params.cp_size == 2
239
+ # Reorder seq_lens = global seq_lens (reorder happens after unshard)
240
+ assert reorderer_plans[0].params.seq_lens == [100, 64, 92]
241
+
242
+
243
+ class TestComputePerStepSubPlansDpFiltered:
244
+ """Tests that compute_per_step_sub_plans passes dp_filtered_axis to unsharder,
245
+ so DP axes already handled by the upstream DP filter don't cause validation errors.
246
+ """
247
+
248
+ def test_dp2_tp2_does_not_raise(self) -> None:
249
+ """DP2 + TP2, dims='t h[tp]' → should not raise despite DP being active."""
250
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(
251
+ metas=[
252
+ _make_meta(
253
+ dims="t h[tp]",
254
+ tp_rank=0,
255
+ tp_size=2,
256
+ extra_parallel_info={"dp_rank": 0, "dp_size": 2},
257
+ ),
258
+ _make_meta(
259
+ dims="t h[tp]",
260
+ tp_rank=1,
261
+ tp_size=2,
262
+ extra_parallel_info={"dp_rank": 0, "dp_size": 2},
263
+ ),
264
+ ]
265
+ )
266
+ unsharder_plans: list[UnsharderPlan] = [
267
+ p for p in result if isinstance(p, UnsharderPlan)
268
+ ]
269
+ assert len(unsharder_plans) == 1
270
+ assert unsharder_plans[0].axis.value == "tp"
271
+
272
+ def test_dp2_only_no_sharding_does_not_raise(self) -> None:
273
+ """DP2 only, dims='t h' → should not raise, no plans produced."""
274
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(
275
+ metas=[
276
+ _make_meta(
277
+ dims="t h",
278
+ extra_parallel_info={"dp_rank": 0, "dp_size": 2},
279
+ ),
280
+ _make_meta(
281
+ dims="t h",
282
+ extra_parallel_info={"dp_rank": 0, "dp_size": 2},
283
+ ),
284
+ ]
285
+ )
286
+ assert result == []
287
+
288
+ def test_dp_alias_passes_correct_filtered_axis(self) -> None:
289
+ """dims with '# dp:=moe_dp', metas have moe_dp → should not raise."""
290
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(
291
+ metas=[
292
+ _make_meta(
293
+ dims="t h[tp] # dp:=moe_dp",
294
+ tp_rank=0,
295
+ tp_size=2,
296
+ extra_parallel_info={"moe_dp_rank": 0, "moe_dp_size": 2},
297
+ ),
298
+ _make_meta(
299
+ dims="t h[tp] # dp:=moe_dp",
300
+ tp_rank=1,
301
+ tp_size=2,
302
+ extra_parallel_info={"moe_dp_rank": 0, "moe_dp_size": 2},
303
+ ),
304
+ ]
305
+ )
306
+ unsharder_plans: list[UnsharderPlan] = [
307
+ p for p in result if isinstance(p, UnsharderPlan)
308
+ ]
309
+ assert len(unsharder_plans) == 1
310
+ assert unsharder_plans[0].axis.value == "tp"
311
+
312
+ def test_dp2_tp2_cp2_does_not_raise(self) -> None:
313
+ """DP2 + TP2 + CP2, dims='s[cp] h[tp]' → should not raise."""
314
+ metas = []
315
+ for cp_rank in range(2):
316
+ for tp_rank in range(2):
317
+ metas.append(
318
+ _make_meta(
319
+ dims="s[cp] h[tp]",
320
+ tp_rank=tp_rank,
321
+ tp_size=2,
322
+ cp_rank=cp_rank,
323
+ cp_size=2,
324
+ extra_parallel_info={"dp_rank": 0, "dp_size": 2},
325
+ )
326
+ )
327
+ result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(metas=metas)
328
+ unsharder_plans: list[UnsharderPlan] = [
329
+ p for p in result if isinstance(p, UnsharderPlan)
330
+ ]
331
+ axes = {p.axis.value for p in unsharder_plans}
332
+ assert axes == {"cp", "tp"}
333
+
334
+
335
+ if __name__ == "__main__":
336
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/__init__.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/conftest.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_executor.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from sglang.srt.debug_utils.comparator.aligner.reorderer.executor import (
7
+ _reorder_zigzag_to_natural,
8
+ _reorder_zigzag_to_natural_thd,
9
+ execute_reorderer_plan,
10
+ )
11
+ from sglang.srt.debug_utils.comparator.aligner.reorderer.types import (
12
+ ReordererPlan,
13
+ ZigzagToNaturalThdParams,
14
+ )
15
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.executor import (
16
+ execute_unsharder_plan,
17
+ )
18
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import (
19
+ CpThdConcatParams,
20
+ UnsharderPlan,
21
+ )
22
+ from sglang.srt.debug_utils.comparator.dims_spec import (
23
+ ParallelAxis,
24
+ apply_dim_names,
25
+ without_dim_names,
26
+ )
27
+ from sglang.test.ci.ci_register import register_cpu_ci
28
+
29
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
30
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
31
+
32
+
33
+ def _zigzag_order(cp_size: int) -> list[int]:
34
+ """Build zigzag interleaving order for 2*cp_size chunks."""
35
+ order: list[int] = []
36
+ num_chunks: int = cp_size * 2
37
+ for i in range(cp_size):
38
+ order.append(i)
39
+ order.append(num_chunks - 1 - i)
40
+ return order
41
+
42
+
43
+ def _zigzag_split_seq(seq_natural: torch.Tensor, *, cp_size: int) -> list[torch.Tensor]:
44
+ """Split a natural-order seq into per-rank zigzag segments.
45
+
46
+ Returns: list of per-rank tensors, where rank_i holds chunks assigned by zigzag.
47
+ """
48
+ num_chunks: int = cp_size * 2
49
+ chunks: list[torch.Tensor] = list(seq_natural.chunk(num_chunks, dim=0))
50
+ order: list[int] = _zigzag_order(cp_size)
51
+ zigzagged: torch.Tensor = torch.cat([chunks[i] for i in order], dim=0)
52
+ return list(zigzagged.chunk(cp_size, dim=0))
53
+
54
+
55
+ class TestZigzagToNatural:
56
+ def test_zigzag_to_natural_cp2(self) -> None:
57
+ """cp_size=2: zigzag order [0,3,1,2] -> natural [0,1,2,3]."""
58
+ natural = torch.arange(24).reshape(4, 6)
59
+ chunks = list(natural.chunk(4, dim=0))
60
+
61
+ zigzag_order: list[int] = [0, 3, 1, 2]
62
+ zigzagged = torch.cat([chunks[i] for i in zigzag_order], dim=0)
63
+
64
+ result = _reorder_zigzag_to_natural(zigzagged, dim=0, cp_size=2)
65
+ assert torch.equal(result, natural)
66
+
67
+ def test_zigzag_to_natural_cp3(self) -> None:
68
+ """cp_size=3: zigzag 162534 -> natural 123456 (1-indexed)."""
69
+ natural = torch.arange(60).reshape(6, 10)
70
+ chunks = list(natural.chunk(6, dim=0))
71
+
72
+ zigzag_order: list[int] = [0, 5, 1, 4, 2, 3]
73
+ zigzagged = torch.cat([chunks[i] for i in zigzag_order], dim=0)
74
+
75
+ result = _reorder_zigzag_to_natural(zigzagged, dim=0, cp_size=3)
76
+ assert torch.equal(result, natural)
77
+
78
+ def test_zigzag_to_natural_arbitrary_dim(self) -> None:
79
+ """Reorder along dim=1 instead of dim=0."""
80
+ natural = torch.arange(48).reshape(3, 4, 4)
81
+ chunks = list(natural.chunk(4, dim=1))
82
+
83
+ zigzag_order: list[int] = [0, 3, 1, 2]
84
+ zigzagged = torch.cat([chunks[i] for i in zigzag_order], dim=1)
85
+
86
+ result = _reorder_zigzag_to_natural(zigzagged, dim=1, cp_size=2)
87
+ assert torch.equal(result, natural)
88
+
89
+
90
+ class TestZigzagToNaturalThd:
91
+ def test_single_seq(self) -> None:
92
+ """Single seq THD reorder: equivalent to whole-tensor reorder."""
93
+ natural = torch.arange(100)
94
+ zigzag_ranks: list[torch.Tensor] = _zigzag_split_seq(natural, cp_size=2)
95
+ zigzagged: torch.Tensor = torch.cat(zigzag_ranks, dim=0)
96
+
97
+ result = _reorder_zigzag_to_natural_thd(
98
+ zigzagged, dim=0, cp_size=2, seq_lens=[100]
99
+ )
100
+ assert torch.equal(result, natural)
101
+
102
+ def test_multi_seq(self) -> None:
103
+ """Two seqs of different lengths, each independently reordered."""
104
+ seq_a_natural = torch.arange(100)
105
+ seq_b_natural = torch.arange(100, 164)
106
+
107
+ seq_a_zigzag: torch.Tensor = torch.cat(
108
+ _zigzag_split_seq(seq_a_natural, cp_size=2), dim=0
109
+ )
110
+ seq_b_zigzag: torch.Tensor = torch.cat(
111
+ _zigzag_split_seq(seq_b_natural, cp_size=2), dim=0
112
+ )
113
+
114
+ combined_zigzag: torch.Tensor = torch.cat([seq_a_zigzag, seq_b_zigzag], dim=0)
115
+ result = _reorder_zigzag_to_natural_thd(
116
+ combined_zigzag, dim=0, cp_size=2, seq_lens=[100, 64]
117
+ )
118
+
119
+ expected: torch.Tensor = torch.cat([seq_a_natural, seq_b_natural], dim=0)
120
+ assert torch.equal(result, expected)
121
+
122
+ def test_with_tail_pad(self) -> None:
123
+ """THD reorder with trailing global padding preserved unchanged."""
124
+ seq_natural = torch.arange(100)
125
+ pad: torch.Tensor = torch.full((56,), fill_value=-1)
126
+
127
+ seq_zigzag: torch.Tensor = torch.cat(
128
+ _zigzag_split_seq(seq_natural, cp_size=2), dim=0
129
+ )
130
+ combined: torch.Tensor = torch.cat([seq_zigzag, pad], dim=0)
131
+
132
+ result = _reorder_zigzag_to_natural_thd(
133
+ combined, dim=0, cp_size=2, seq_lens=[100]
134
+ )
135
+
136
+ assert torch.equal(result[:100], seq_natural)
137
+ assert torch.equal(result[100:], pad)
138
+
139
+ def test_with_hidden_dim(self) -> None:
140
+ """THD reorder with trailing hidden dimension (shape [T, H])."""
141
+ torch.manual_seed(42)
142
+ hidden: int = 8
143
+ seq_natural = torch.randn(100, hidden)
144
+
145
+ seq_zigzag: torch.Tensor = torch.cat(
146
+ _zigzag_split_seq(seq_natural, cp_size=2), dim=0
147
+ )
148
+
149
+ result = _reorder_zigzag_to_natural_thd(
150
+ seq_zigzag, dim=0, cp_size=2, seq_lens=[100]
151
+ )
152
+ assert torch.equal(result, seq_natural)
153
+
154
+ def test_with_leading_batch_dim(self) -> None:
155
+ """THD reorder with leading batch dim: shape [B, T, H], t is dim=1."""
156
+ torch.manual_seed(42)
157
+ batch: int = 2
158
+ hidden: int = 4
159
+ seq_a_natural = torch.randn(batch, 100, hidden)
160
+ seq_b_natural = torch.randn(batch, 64, hidden)
161
+ full_natural: torch.Tensor = torch.cat([seq_a_natural, seq_b_natural], dim=1)
162
+
163
+ # Zigzag each seq along dim=1
164
+ def zigzag_along_dim1(t: torch.Tensor) -> torch.Tensor:
165
+ num_chunks: int = 2 * 2 # cp_size=2
166
+ chunks: list[torch.Tensor] = list(t.chunk(num_chunks, dim=1))
167
+ order: list[int] = [0, 3, 1, 2] # zigzag for cp_size=2
168
+ return torch.cat([chunks[i] for i in order], dim=1)
169
+
170
+ seq_a_zigzag: torch.Tensor = zigzag_along_dim1(seq_a_natural)
171
+ seq_b_zigzag: torch.Tensor = zigzag_along_dim1(seq_b_natural)
172
+ combined_zigzag: torch.Tensor = torch.cat([seq_a_zigzag, seq_b_zigzag], dim=1)
173
+
174
+ result = _reorder_zigzag_to_natural_thd(
175
+ combined_zigzag, dim=1, cp_size=2, seq_lens=[100, 64]
176
+ )
177
+ assert torch.equal(result, full_natural)
178
+
179
+
180
+ class TestThdCpZigzagE2E:
181
+ """End-to-end unshard + reorder tests for THD CP zigzag format.
182
+
183
+ Simulates Miles/Megatron forward data splitting:
184
+
185
+ cp_size=2, batch with 2 seqs: seqA(100 tokens), seqB(61→pad to 64)
186
+
187
+ Forward:
188
+ seqA(100): chunk_size=25, 4 chunks → rank0=[chunk0+chunk3](50), rank1=[chunk1+chunk2](50)
189
+ seqB(64): chunk_size=16, 4 chunks → rank0=[chunk0+chunk3](32), rank1=[chunk1+chunk2](32)
190
+ global pad → align to 128
191
+ rank0: [seqA_r0(50) | seqB_r0(32) | pad(46)] = 128 tokens
192
+ rank1: [seqA_r1(50) | seqB_r1(32) | pad(46)] = 128 tokens
193
+ global cu_seqlens: [0, 100, 164, 256]
194
+
195
+ Comparator undo:
196
+ Step 1 THD unshard: per-seq cross-rank concat → [seqA_zigzag(100) | seqB_zigzag(64) | pad(92)]
197
+ Step 2 THD reorder: per-seq zigzag→natural → [seqA_natural(100) | seqB_natural(64) | pad(92)]
198
+ """
199
+
200
+ def test_thd_cp2_two_seqs(self) -> None:
201
+ """cp_size=2, 2 seqs (100, 61→64) + global pad."""
202
+ torch.manual_seed(42)
203
+ cp_size: int = 2
204
+ total_per_rank: int = 128
205
+
206
+ seq_a_natural = torch.randn(100)
207
+ seq_b_natural_raw = torch.randn(61)
208
+ seq_b_padded = torch.cat([seq_b_natural_raw, torch.zeros(3)]) # pad 61→64
209
+
210
+ seq_a_ranks: list[torch.Tensor] = _zigzag_split_seq(
211
+ seq_a_natural, cp_size=cp_size
212
+ )
213
+ seq_b_ranks: list[torch.Tensor] = _zigzag_split_seq(
214
+ seq_b_padded, cp_size=cp_size
215
+ )
216
+
217
+ # Build per-rank tensors: [seqA_r | seqB_r | pad_r]
218
+ rank_tensors: list[torch.Tensor] = []
219
+ for rank in range(cp_size):
220
+ used: int = seq_a_ranks[rank].shape[0] + seq_b_ranks[rank].shape[0]
221
+ pad_len: int = total_per_rank - used
222
+ rank_tensor: torch.Tensor = apply_dim_names(
223
+ torch.cat([seq_a_ranks[rank], seq_b_ranks[rank], torch.zeros(pad_len)]),
224
+ ["t"],
225
+ )
226
+ rank_tensors.append(rank_tensor)
227
+
228
+ # Step 1: THD unshard
229
+ seq_lens_per_rank: list[int] = [50, 32, 46]
230
+ unshard_plan = UnsharderPlan(
231
+ axis=ParallelAxis.CP,
232
+ params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=seq_lens_per_rank),
233
+ groups=[[0, 1]],
234
+ )
235
+ unsharder_result = execute_unsharder_plan(unshard_plan, rank_tensors)
236
+ unsharded: list[torch.Tensor] = unsharder_result.tensors
237
+ assert len(unsharded) == 1
238
+
239
+ # Step 2: THD reorder
240
+ reorder_seq_lens: list[int] = [s * cp_size for s in seq_lens_per_rank]
241
+ reorder_plan = ReordererPlan(
242
+ params=ZigzagToNaturalThdParams(
243
+ dim_name="t", cp_size=cp_size, seq_lens=reorder_seq_lens
244
+ )
245
+ )
246
+ reordered: list[torch.Tensor] = execute_reorderer_plan(reorder_plan, unsharded)
247
+ assert len(reordered) == 1
248
+
249
+ result: torch.Tensor = without_dim_names(reordered[0])
250
+ assert torch.equal(result[:100], seq_a_natural)
251
+ assert torch.equal(result[100:164], seq_b_padded)
252
+
253
+ def test_thd_cp3_single_seq(self) -> None:
254
+ """cp_size=3, single seq (120 tokens)."""
255
+ torch.manual_seed(42)
256
+ cp_size: int = 3
257
+ seq_natural = torch.randn(120)
258
+
259
+ seq_ranks: list[torch.Tensor] = _zigzag_split_seq(seq_natural, cp_size=cp_size)
260
+
261
+ rank_tensors: list[torch.Tensor] = [
262
+ apply_dim_names(t, ["t"]) for t in seq_ranks
263
+ ]
264
+
265
+ # Step 1: THD unshard
266
+ seq_len_per_rank: int = 120 // cp_size # 40
267
+ unshard_plan = UnsharderPlan(
268
+ axis=ParallelAxis.CP,
269
+ params=CpThdConcatParams(
270
+ dim_name="t", seq_lens_per_rank=[seq_len_per_rank]
271
+ ),
272
+ groups=[list(range(cp_size))],
273
+ )
274
+ unsharder_result = execute_unsharder_plan(unshard_plan, rank_tensors)
275
+ unsharded: list[torch.Tensor] = unsharder_result.tensors
276
+ assert len(unsharded) == 1
277
+
278
+ # Step 2: THD reorder
279
+ reorder_plan = ReordererPlan(
280
+ params=ZigzagToNaturalThdParams(
281
+ dim_name="t", cp_size=cp_size, seq_lens=[120]
282
+ )
283
+ )
284
+ reordered: list[torch.Tensor] = execute_reorderer_plan(reorder_plan, unsharded)
285
+ assert len(reordered) == 1
286
+
287
+ result: torch.Tensor = without_dim_names(reordered[0])
288
+ assert torch.equal(result, seq_natural)
289
+
290
+
291
+ if __name__ == "__main__":
292
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_planner.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from sglang.srt.debug_utils.comparator.aligner.reorderer.executor import (
7
+ execute_reorderer_plan,
8
+ )
9
+ from sglang.srt.debug_utils.comparator.aligner.reorderer.planner import (
10
+ compute_reorderer_plans,
11
+ )
12
+ from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ReordererPlan
13
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.executor import (
14
+ execute_unsharder_plan,
15
+ )
16
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.planner import (
17
+ compute_unsharder_plan,
18
+ )
19
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import AxisInfo
20
+ from sglang.srt.debug_utils.comparator.dims_spec import (
21
+ DimSpec,
22
+ ParallelAxis,
23
+ apply_dim_names,
24
+ parse_dims,
25
+ without_dim_names,
26
+ )
27
+ from sglang.test.ci.ci_register import register_cpu_ci
28
+
29
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
30
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
31
+
32
+
33
+ class TestComputeReordererPlans:
34
+ def test_compute_reorderer_plans_zigzag(self) -> None:
35
+ """s[cp:zigzag] produces a ReordererPlan."""
36
+ dim_specs = parse_dims("b s[cp:zigzag] h[tp]").dims
37
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
38
+ {
39
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
40
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
41
+ },
42
+ ]
43
+ plans = compute_reorderer_plans(
44
+ dim_specs=dim_specs, parallel_infos=parallel_infos
45
+ )
46
+
47
+ assert len(plans) == 1
48
+ assert plans[0].params.op == "zigzag_to_natural"
49
+ assert plans[0].params.dim_name == "s"
50
+ assert plans[0].params.cp_size == 2
51
+
52
+ def test_compute_reorderer_plans_thd_zigzag(self) -> None:
53
+ """t[cp:zigzag] produces a ZigzagToNaturalThdParams plan."""
54
+ dim_specs = parse_dims("t[cp:zigzag] h[tp]").dims
55
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
56
+ {
57
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
58
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
59
+ },
60
+ ]
61
+ thd_global_seq_lens: list[int] = [100, 64, 92]
62
+ plans = compute_reorderer_plans(
63
+ dim_specs=dim_specs,
64
+ parallel_infos=parallel_infos,
65
+ thd_global_seq_lens=thd_global_seq_lens,
66
+ )
67
+
68
+ assert len(plans) == 1
69
+ assert plans[0].params.op == "zigzag_to_natural_thd"
70
+ assert plans[0].params.cp_size == 2
71
+ assert plans[0].params.seq_lens == [100, 64, 92]
72
+
73
+ def test_non_seq_dim_still_raises(self) -> None:
74
+ """Zigzag on non-sequence/non-token dim (e.g. h[cp:zigzag]) raises ValueError."""
75
+ dim_specs = parse_dims("h[cp:zigzag] d").dims
76
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
77
+ {ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2)},
78
+ ]
79
+ with pytest.raises(ValueError, match="only supported on sequence dims"):
80
+ compute_reorderer_plans(dim_specs=dim_specs, parallel_infos=parallel_infos)
81
+
82
+ def test_thd_zigzag_without_seq_lens_raises(self) -> None:
83
+ """t[cp:zigzag] without thd_global_seq_lens raises ValueError."""
84
+ dim_specs = parse_dims("t[cp:zigzag] h[tp]").dims
85
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
86
+ {
87
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
88
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
89
+ },
90
+ ]
91
+ with pytest.raises(ValueError, match="thd_global_seq_lens is required"):
92
+ compute_reorderer_plans(dim_specs=dim_specs, parallel_infos=parallel_infos)
93
+
94
+ def test_thd_natural_no_reorder(self) -> None:
95
+ """t[cp:natural] and t[cp] produce no reorder plans."""
96
+ for dims_str in ["t[cp:natural] h[tp]", "t[cp] h[tp]"]:
97
+ dim_specs = parse_dims(dims_str).dims
98
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
99
+ {
100
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
101
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
102
+ },
103
+ ]
104
+ plans = compute_reorderer_plans(
105
+ dim_specs=dim_specs, parallel_infos=parallel_infos
106
+ )
107
+ assert plans == []
108
+
109
+ def test_compute_reorderer_plans_natural(self) -> None:
110
+ """s[cp] and s[cp:natural] produce no reorder plans."""
111
+ for dims_str in ["b s[cp] h[tp]", "b s[cp:natural] h[tp]"]:
112
+ dim_specs = parse_dims(dims_str).dims
113
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
114
+ {
115
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
116
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
117
+ },
118
+ ]
119
+ plans = compute_reorderer_plans(
120
+ dim_specs=dim_specs, parallel_infos=parallel_infos
121
+ )
122
+ assert plans == []
123
+
124
+
125
+ class TestCpZigzagTpE2E:
126
+ def test_cp_zigzag_tp_e2e(self) -> None:
127
+ """CP=2 zigzag + TP=2: full pipeline round-trip."""
128
+ torch.manual_seed(42)
129
+ full_tensor = torch.randn(4, 8, 16)
130
+
131
+ # Shard: first split seq dim (dim=1) into CP=2 with zigzag ordering,
132
+ # then split hidden dim (dim=2) into TP=2.
133
+ natural_cp_chunks = list(full_tensor.chunk(4, dim=1))
134
+ zigzag_order: list[int] = [0, 3, 1, 2]
135
+ zigzagged = torch.cat([natural_cp_chunks[i] for i in zigzag_order], dim=1)
136
+
137
+ cp_chunks = list(zigzagged.chunk(2, dim=1))
138
+ tensors: list[torch.Tensor] = []
139
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
140
+ for cp_rank in range(2):
141
+ tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=2))
142
+ for tp_rank in range(2):
143
+ tensors.append(tp_chunks[tp_rank])
144
+ parallel_infos.append(
145
+ {
146
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
147
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
148
+ }
149
+ )
150
+
151
+ dim_specs: list[DimSpec] = parse_dims("b s[cp:zigzag] h[tp]").dims
152
+ dim_names: list[str] = [s.name for s in dim_specs]
153
+
154
+ unsharder_plans = compute_unsharder_plan(
155
+ dim_specs=dim_specs, parallel_infos=parallel_infos
156
+ )
157
+ reorderer_plans = compute_reorderer_plans(
158
+ dim_specs=dim_specs, parallel_infos=parallel_infos
159
+ )
160
+ all_plans = [*unsharder_plans, *reorderer_plans]
161
+
162
+ assert len(unsharder_plans) == 2
163
+ assert len(reorderer_plans) == 1
164
+
165
+ current: list[torch.Tensor] = [
166
+ apply_dim_names(t, list(dim_names)) for t in tensors
167
+ ]
168
+ for plan in all_plans:
169
+ if isinstance(plan, ReordererPlan):
170
+ current = execute_reorderer_plan(plan, current)
171
+ else:
172
+ current = execute_unsharder_plan(plan, current).tensors
173
+
174
+ assert len(current) == 1
175
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
176
+
177
+
178
+ class TestCpZigzagSpSameDimE2E:
179
+ """E2E test for t[cp:zigzag,sp] — two axes sharding the same token dim."""
180
+
181
+ def test_cp2_sp2_zigzag_e2e(self) -> None:
182
+ """CP=2 zigzag + SP=2 on same token dim: full unshard + reorder round-trip.
183
+
184
+ Shard order (outer to inner, matching left-to-right in dims annotation):
185
+ 1. CP zigzag splits token dim into 2 CP chunks (zigzag order)
186
+ 2. SP splits each CP chunk into 2 SP chunks
187
+
188
+ Unshard order (inner to outer, right-to-left):
189
+ 1. SP concat (inner): merge SP chunks back
190
+ 2. CP concat (outer): merge CP chunks back
191
+ 3. Zigzag reorder: restore natural token order
192
+ """
193
+ torch.manual_seed(42)
194
+ total_tokens: int = 16
195
+ hidden: int = 8
196
+ full_tensor: torch.Tensor = torch.randn(total_tokens, hidden)
197
+
198
+ # Step 1: CP zigzag split — split into 2*cp_size=4 natural chunks, reorder by zigzag
199
+ cp_size: int = 2
200
+ sp_size: int = 2
201
+ n_natural_chunks: int = cp_size * 2
202
+ natural_chunks: list[torch.Tensor] = list(
203
+ full_tensor.chunk(n_natural_chunks, dim=0)
204
+ )
205
+ zigzag_order: list[int] = [0, 3, 1, 2]
206
+ zigzagged: torch.Tensor = torch.cat(
207
+ [natural_chunks[i] for i in zigzag_order], dim=0
208
+ )
209
+ cp_chunks: list[torch.Tensor] = list(zigzagged.chunk(cp_size, dim=0))
210
+
211
+ # Step 2: SP split within each CP chunk
212
+ tensors: list[torch.Tensor] = []
213
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
214
+ for cp_rank in range(cp_size):
215
+ sp_chunks: list[torch.Tensor] = list(
216
+ cp_chunks[cp_rank].chunk(sp_size, dim=0)
217
+ )
218
+ for sp_rank in range(sp_size):
219
+ tensors.append(sp_chunks[sp_rank])
220
+ parallel_infos.append(
221
+ {
222
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=cp_size),
223
+ ParallelAxis.SP: AxisInfo(axis_rank=sp_rank, axis_size=sp_size),
224
+ }
225
+ )
226
+
227
+ dim_specs: list[DimSpec] = parse_dims("t[cp:zigzag,sp] h").dims
228
+ dim_names: list[str] = [s.name for s in dim_specs]
229
+
230
+ unsharder_plans = compute_unsharder_plan(
231
+ dim_specs=dim_specs, parallel_infos=parallel_infos
232
+ )
233
+ reorderer_plans = compute_reorderer_plans(
234
+ dim_specs=dim_specs,
235
+ parallel_infos=parallel_infos,
236
+ thd_global_seq_lens=[total_tokens],
237
+ )
238
+ all_plans = [*unsharder_plans, *reorderer_plans]
239
+
240
+ assert len(unsharder_plans) == 2 # SP concat, CP concat
241
+ assert unsharder_plans[0].axis == ParallelAxis.SP
242
+ assert unsharder_plans[1].axis == ParallelAxis.CP
243
+ assert len(reorderer_plans) == 1 # zigzag reorder
244
+
245
+ current: list[torch.Tensor] = [
246
+ apply_dim_names(t, list(dim_names)) for t in tensors
247
+ ]
248
+ for plan in all_plans:
249
+ if isinstance(plan, ReordererPlan):
250
+ current = execute_reorderer_plan(plan, current)
251
+ else:
252
+ current = execute_unsharder_plan(plan, current).tensors
253
+
254
+ assert len(current) == 1
255
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
256
+
257
+
258
+ if __name__ == "__main__":
259
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/test_axis_aligner.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Optional
3
+
4
+ import pytest
5
+ import torch
6
+
7
+ from sglang.srt.debug_utils.comparator.aligner.axis_aligner import (
8
+ AxisAlignerPlan,
9
+ compute_axis_aligner_plan,
10
+ execute_axis_aligner_plan,
11
+ )
12
+ from sglang.srt.debug_utils.comparator.dims_spec import (
13
+ apply_dim_names,
14
+ without_dim_names,
15
+ )
16
+ from sglang.srt.debug_utils.comparator.log_sink import log_sink
17
+ from sglang.srt.debug_utils.comparator.utils import Pair
18
+ from sglang.test.ci.ci_register import register_cpu_ci
19
+
20
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
21
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
22
+
23
+
24
+ class TestComputeAxisAlignerPlan:
25
+ def test_no_dims_returns_none(self) -> None:
26
+ assert compute_axis_aligner_plan(Pair(x=None, y=None)) is None
27
+ assert compute_axis_aligner_plan(Pair(x="t h d", y=None)) is None
28
+ assert compute_axis_aligner_plan(Pair(x=None, y="t h d")) is None
29
+
30
+ def test_same_order_returns_none(self) -> None:
31
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
32
+ Pair(x="t h d", y="t h d")
33
+ )
34
+ assert result is None
35
+
36
+ def test_different_order(self) -> None:
37
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
38
+ Pair(x="t h d", y="t d h")
39
+ )
40
+ assert result is not None
41
+ assert result.pattern.x == "t h d -> t d h"
42
+ assert result.pattern.y is None
43
+
44
+ def test_name_mismatch_returns_none_with_warning(self) -> None:
45
+ with log_sink.context() as warnings:
46
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
47
+ Pair(x="t h d", y="t h e")
48
+ )
49
+
50
+ assert result is None
51
+ assert len(warnings) == 1
52
+ assert warnings[0].category == "axis_aligner_dim_mismatch"
53
+ assert "dim name sets differ" in warnings[0].message
54
+
55
+ def test_modifiers_ignored_for_name_extraction(self) -> None:
56
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
57
+ Pair(x="t h[tp] d", y="t d h[tp]")
58
+ )
59
+ assert result is not None
60
+ assert result.pattern.x == "t h d -> t d h"
61
+
62
+ def test_squeeze_only_no_swap(self) -> None:
63
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
64
+ Pair(x="t 1 h", y="t h")
65
+ )
66
+ assert result is not None
67
+ assert result.pattern.x == "t 1 h -> t h"
68
+ assert result.pattern.y is None
69
+
70
+ def test_squeeze_both_sides(self) -> None:
71
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
72
+ Pair(x="t 1 h", y="1 t h")
73
+ )
74
+ assert result is not None
75
+ assert result.pattern.x == "t 1 h -> t h"
76
+ assert result.pattern.y == "1 t h -> t h"
77
+
78
+ def test_squeeze_plus_swap(self) -> None:
79
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
80
+ Pair(x="t 1 h d", y="t d h")
81
+ )
82
+ assert result is not None
83
+ assert result.pattern.x == "t 1 h d -> t d h"
84
+ assert result.pattern.y is None
85
+
86
+ def test_squeeze_y_only(self) -> None:
87
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
88
+ Pair(x="t h", y="t 1 h")
89
+ )
90
+ assert result is not None
91
+ assert result.pattern.x is None
92
+ assert result.pattern.y == "t 1 h -> t h"
93
+
94
+ def test_multiple_squeeze_one_side(self) -> None:
95
+ """Two squeeze dims on x, none on y."""
96
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
97
+ Pair(x="1 t 1 h", y="t h")
98
+ )
99
+ assert result is not None
100
+ assert result.pattern.x == "1 t 1 h -> t h"
101
+ assert result.pattern.y is None
102
+
103
+ def test_multiple_squeeze_asymmetric(self) -> None:
104
+ """Different numbers of squeeze dims on each side."""
105
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
106
+ Pair(x="1 t 1 h", y="1 t h")
107
+ )
108
+ assert result is not None
109
+ assert result.pattern.x == "1 t 1 h -> t h"
110
+ assert result.pattern.y == "1 t h -> t h"
111
+
112
+ def test_four_dim_full_reversal(self) -> None:
113
+ """4-dim permutation: full reversal."""
114
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
115
+ Pair(x="a b c d", y="d c b a")
116
+ )
117
+ assert result is not None
118
+ assert result.pattern.x == "a b c d -> d c b a"
119
+ assert result.pattern.y is None
120
+
121
+
122
+ class TestComputeAxisAlignerPlanFused:
123
+ def test_fused_vs_separate(self) -> None:
124
+ """x=fused 2D, y=separate 3D: y flattens to match x's fused form."""
125
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
126
+ Pair(x="t (num_heads*head_dim)[tp]", y="t num_heads[tp] head_dim")
127
+ )
128
+ assert result is not None
129
+ assert result.pattern.x is None
130
+ assert result.pattern.y == "t num_heads head_dim -> t (num_heads head_dim)"
131
+
132
+ def test_separate_vs_fused(self) -> None:
133
+ """x=separate 3D, y=fused 2D: x flattens to match y's fused form."""
134
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
135
+ Pair(x="t num_heads[tp] head_dim", y="t (num_heads*head_dim)[tp]")
136
+ )
137
+ assert result is not None
138
+ assert result.pattern.x == "t num_heads head_dim -> t (num_heads head_dim)"
139
+ assert result.pattern.y is None
140
+
141
+ def test_both_fused_same_no_plan(self) -> None:
142
+ """Both sides fused, same order → None (no-op)."""
143
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
144
+ Pair(x="t (a*b)", y="t (a*b)")
145
+ )
146
+ assert result is None
147
+
148
+ def test_fused_name_mismatch_returns_none(self) -> None:
149
+ """Fused vs separate with mismatched names → None."""
150
+ with log_sink.context() as warnings:
151
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
152
+ Pair(x="t (a*b)", y="t c d")
153
+ )
154
+ assert result is None
155
+ assert len(warnings) == 1
156
+
157
+ def test_partial_fused_and_regular(self) -> None:
158
+ """x has "(a*b) c", y has "a b c": y flattens a,b to match x's fused form."""
159
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
160
+ Pair(x="(a*b) c", y="a b c")
161
+ )
162
+ assert result is not None
163
+ assert result.pattern.x is None
164
+ assert result.pattern.y == "a b c -> (a b) c"
165
+
166
+ def test_fused_vs_reordered_separate(self) -> None:
167
+ """x=fused "(a*b) c", y=reordered separate "b a c": y flattens+reorders."""
168
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
169
+ Pair(x="(a*b) c", y="b a c")
170
+ )
171
+ assert result is not None
172
+ assert result.pattern.x is None
173
+ assert result.pattern.y == "b a c -> (a b) c"
174
+
175
+ def test_fused_reorder_both_sides(self) -> None:
176
+ """x=fused "c (a*b)", y=separate "a b c": x reorders fused, y flattens."""
177
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
178
+ Pair(x="c (a*b)", y="a b c")
179
+ )
180
+ assert result is not None
181
+ assert result.pattern.x == "c a___b -> a___b c"
182
+ assert result.pattern.y == "a b c -> (a b) c"
183
+
184
+ def test_fused_with_squeeze(self) -> None:
185
+ """Fused + squeeze on one side, separate on other."""
186
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
187
+ Pair(x="t 1 (a*b)", y="t a b")
188
+ )
189
+ assert result is not None
190
+ assert result.pattern.x == "t 1 a___b -> t a___b"
191
+ assert result.pattern.y == "t a b -> t (a b)"
192
+
193
+ def test_three_way_fused_vs_separate(self) -> None:
194
+ """3-way fused on x, separate on y."""
195
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
196
+ Pair(x="t (a*b*c)", y="t a b c")
197
+ )
198
+ assert result is not None
199
+ assert result.pattern.x is None
200
+ assert result.pattern.y == "t a b c -> t (a b c)"
201
+
202
+ def test_separate_vs_three_way_fused(self) -> None:
203
+ """Separate on x, 3-way fused on y."""
204
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
205
+ Pair(x="t a b c", y="t (a*b*c)")
206
+ )
207
+ assert result is not None
208
+ assert result.pattern.x == "t a b c -> t (a b c)"
209
+ assert result.pattern.y is None
210
+
211
+ def test_both_fused_different_order(self) -> None:
212
+ """Both sides fused same group but dims in different order."""
213
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
214
+ Pair(x="c (a*b)", y="(a*b) c")
215
+ )
216
+ assert result is not None
217
+ assert result.pattern.x == "c a___b -> a___b c"
218
+ assert result.pattern.y is None
219
+
220
+ def test_overlapping_fused_groups_returns_none(self) -> None:
221
+ """x fuses (a*b), y fuses (b*c): incompatible overlap → None with warning."""
222
+ with log_sink.context() as warnings:
223
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
224
+ Pair(x="(a*b) c", y="a (b*c)")
225
+ )
226
+ assert result is None
227
+ assert len(warnings) == 1
228
+ assert warnings[0].category == "axis_aligner_fused_conflict"
229
+ assert "overlapping fused groups" in warnings[0].message
230
+
231
+
232
+ class TestExecuteAxisAlignerPlan:
233
+ def test_rearrange(self) -> None:
234
+ torch.manual_seed(42)
235
+ tensor: torch.Tensor = apply_dim_names(torch.randn(4, 8, 16), ["t", "h", "d"])
236
+ plan = AxisAlignerPlan(pattern=Pair(x="t h d -> t d h", y=None))
237
+
238
+ result: torch.Tensor = execute_axis_aligner_plan(
239
+ tensor=tensor, plan=plan, side="x"
240
+ )
241
+
242
+ assert result.shape == (4, 16, 8)
243
+ for i in range(4):
244
+ assert torch.equal(result[i], without_dim_names(tensor)[i].T)
245
+
246
+ def test_execute_squeeze(self) -> None:
247
+ torch.manual_seed(42)
248
+ tensor: torch.Tensor = apply_dim_names(
249
+ torch.randn(4, 1, 8), ["t", "singleton0", "h"]
250
+ )
251
+ plan = AxisAlignerPlan(pattern=Pair(x="t 1 h -> t h", y=None))
252
+
253
+ result: torch.Tensor = execute_axis_aligner_plan(
254
+ tensor=tensor, plan=plan, side="x"
255
+ )
256
+
257
+ assert result.shape == (4, 8)
258
+
259
+ def test_execute_squeeze_then_swap(self) -> None:
260
+ torch.manual_seed(42)
261
+ tensor: torch.Tensor = apply_dim_names(
262
+ torch.randn(4, 1, 8, 16), ["t", "singleton0", "h", "d"]
263
+ )
264
+ plan = AxisAlignerPlan(pattern=Pair(x="t 1 h d -> t d h", y=None))
265
+
266
+ result: torch.Tensor = execute_axis_aligner_plan(
267
+ tensor=tensor, plan=plan, side="x"
268
+ )
269
+
270
+ assert result.shape == (4, 16, 8)
271
+
272
+ def test_execute_y_side(self) -> None:
273
+ torch.manual_seed(42)
274
+ tensor: torch.Tensor = apply_dim_names(
275
+ torch.randn(4, 1, 8), ["t", "singleton0", "h"]
276
+ )
277
+ plan = AxisAlignerPlan(pattern=Pair(x=None, y="t 1 h -> t h"))
278
+
279
+ result: torch.Tensor = execute_axis_aligner_plan(
280
+ tensor=tensor, plan=plan, side="y"
281
+ )
282
+
283
+ assert result.shape == (4, 8)
284
+
285
+ def test_noop_side(self) -> None:
286
+ torch.manual_seed(42)
287
+ tensor: torch.Tensor = apply_dim_names(torch.randn(4, 8, 16), ["t", "h", "d"])
288
+ plan = AxisAlignerPlan(pattern=Pair(x="t h d -> t d h", y=None))
289
+
290
+ result: torch.Tensor = execute_axis_aligner_plan(
291
+ tensor=tensor, plan=plan, side="y"
292
+ )
293
+
294
+ assert result.shape == (4, 8, 16)
295
+
296
+ def test_invalid_side_raises(self) -> None:
297
+ """Invalid side value should raise ValueError."""
298
+ torch.manual_seed(42)
299
+ tensor: torch.Tensor = torch.randn(4, 8, 16)
300
+ plan = AxisAlignerPlan(pattern=Pair(x="t h d -> t d h", y=None))
301
+
302
+ with pytest.raises(ValueError, match="side must be"):
303
+ execute_axis_aligner_plan(tensor=tensor, plan=plan, side="z")
304
+
305
+
306
+ class TestExecuteAxisAlignerPlanFlatten:
307
+ def test_flatten_separate_to_match_fused(self) -> None:
308
+ """3D (t=4, nh=8, hd=16) → 2D (t=4, nh*hd=128) via einops flatten."""
309
+ torch.manual_seed(42)
310
+ tensor_3d: torch.Tensor = torch.randn(4, 8, 16)
311
+ plan = AxisAlignerPlan(
312
+ pattern=Pair(x=None, y="t nh hd -> t (nh hd)"),
313
+ )
314
+
315
+ result: torch.Tensor = execute_axis_aligner_plan(
316
+ tensor=tensor_3d, plan=plan, side="y"
317
+ )
318
+
319
+ assert result.shape == (4, 128)
320
+ assert torch.equal(result, tensor_3d.reshape(4, 128))
321
+
322
+ def test_flatten_preserves_data(self) -> None:
323
+ """Flatten should be equivalent to reshape — verify element equality."""
324
+ torch.manual_seed(42)
325
+ tensor: torch.Tensor = torch.randn(2, 3, 4, 5)
326
+ plan = AxisAlignerPlan(
327
+ pattern=Pair(x="a b c d -> a (b c) d", y=None),
328
+ )
329
+
330
+ result: torch.Tensor = execute_axis_aligner_plan(
331
+ tensor=tensor, plan=plan, side="x"
332
+ )
333
+
334
+ assert result.shape == (2, 12, 5)
335
+ assert torch.equal(result, tensor.reshape(2, 12, 5))
336
+
337
+ def test_flatten_then_rearrange(self) -> None:
338
+ """Flatten + reorder in a single einops pattern."""
339
+ torch.manual_seed(42)
340
+ tensor: torch.Tensor = torch.randn(4, 8, 16, 32)
341
+ plan = AxisAlignerPlan(
342
+ pattern=Pair(x="t a b d -> t d (a b)", y=None),
343
+ )
344
+
345
+ result: torch.Tensor = execute_axis_aligner_plan(
346
+ tensor=tensor, plan=plan, side="x"
347
+ )
348
+
349
+ assert result.shape == (4, 32, 128)
350
+
351
+
352
+ class TestEndToEndFusedAlignment:
353
+ def test_fused_vs_separate_full_pipeline(self) -> None:
354
+ """Full pipeline: x=fused 2D "t nh*hd", y=separate 3D "t nh hd"."""
355
+ torch.manual_seed(42)
356
+ num_heads: int = 8
357
+ head_dim: int = 16
358
+
359
+ x_tensor: torch.Tensor = torch.randn(4, num_heads * head_dim)
360
+ y_tensor: torch.Tensor = x_tensor.reshape(4, num_heads, head_dim)
361
+
362
+ plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
363
+ Pair(x="t (num_heads*head_dim)", y="t num_heads head_dim")
364
+ )
365
+ assert plan is not None
366
+
367
+ y_aligned: torch.Tensor = execute_axis_aligner_plan(
368
+ tensor=y_tensor, plan=plan, side="y"
369
+ )
370
+
371
+ assert y_aligned.shape == x_tensor.shape
372
+ assert torch.equal(y_aligned, x_tensor)
373
+
374
+ def test_separate_vs_fused_full_pipeline(self) -> None:
375
+ """Full pipeline: x=separate 3D "t nh hd", y=fused 2D "t nh*hd"."""
376
+ torch.manual_seed(42)
377
+ num_heads: int = 8
378
+ head_dim: int = 16
379
+
380
+ x_tensor: torch.Tensor = torch.randn(4, num_heads, head_dim)
381
+ y_tensor: torch.Tensor = x_tensor.reshape(4, num_heads * head_dim)
382
+
383
+ plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
384
+ Pair(x="t num_heads head_dim", y="t (num_heads*head_dim)")
385
+ )
386
+ assert plan is not None
387
+
388
+ x_aligned: torch.Tensor = execute_axis_aligner_plan(
389
+ tensor=x_tensor, plan=plan, side="x"
390
+ )
391
+
392
+ assert x_aligned.shape == y_tensor.shape
393
+ assert torch.equal(x_aligned, y_tensor)
394
+
395
+ def test_fused_with_reorder(self) -> None:
396
+ """Fused x + reordered separate y: both need alignment."""
397
+ torch.manual_seed(42)
398
+ a_size: int = 3
399
+ b_size: int = 5
400
+
401
+ # x: fused "c a*b" shape (7, 15)
402
+ x_tensor: torch.Tensor = torch.randn(7, a_size * b_size)
403
+ # y: separate "a b c" shape (3, 5, 7)
404
+ y_tensor: torch.Tensor = x_tensor.reshape(7, a_size, b_size).permute(1, 2, 0)
405
+
406
+ plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
407
+ Pair(x="c (a*b)", y="a b c")
408
+ )
409
+ assert plan is not None
410
+
411
+ x_aligned: torch.Tensor = execute_axis_aligner_plan(
412
+ tensor=x_tensor, plan=plan, side="x"
413
+ )
414
+ y_aligned: torch.Tensor = execute_axis_aligner_plan(
415
+ tensor=y_tensor, plan=plan, side="y"
416
+ )
417
+
418
+ assert x_aligned.shape == y_aligned.shape
419
+ assert torch.allclose(x_aligned, y_aligned)
420
+
421
+
422
+ class TestEndToEndThreeWayFused:
423
+ def test_three_way_fused_vs_separate(self) -> None:
424
+ """Full pipeline: x=3-way fused "t (a*b*c)", y=separate "t a b c"."""
425
+ torch.manual_seed(42)
426
+ a_size, b_size, c_size = 2, 3, 4
427
+
428
+ x_tensor: torch.Tensor = torch.randn(5, a_size * b_size * c_size)
429
+ y_tensor: torch.Tensor = x_tensor.reshape(5, a_size, b_size, c_size)
430
+
431
+ plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
432
+ Pair(x="t (a*b*c)", y="t a b c")
433
+ )
434
+ assert plan is not None
435
+
436
+ y_aligned: torch.Tensor = execute_axis_aligner_plan(
437
+ tensor=y_tensor, plan=plan, side="y"
438
+ )
439
+
440
+ assert y_aligned.shape == x_tensor.shape
441
+ assert torch.equal(y_aligned, x_tensor)
442
+
443
+
444
+ class TestSeqTokenEquivalencePlan:
445
+ """Tests for s≡t dimension name equivalence in compute_axis_aligner_plan."""
446
+
447
+ def test_s_t_equivalence_squeeze(self) -> None:
448
+ """sglang 't h' vs megatron 's 1 h': plan squeezes y-side singleton, x-side no-op."""
449
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
450
+ Pair(x="t h", y="s 1 h")
451
+ )
452
+ assert result is not None
453
+ assert result.pattern.x is None
454
+ assert result.pattern.y == "s 1 h -> s h"
455
+
456
+ def test_s_t_equivalence_same_shape(self) -> None:
457
+ """'t h d' vs 's h d': same order after normalization → no plan needed."""
458
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
459
+ Pair(x="t h d", y="s h d")
460
+ )
461
+ assert result is None
462
+
463
+ def test_s_t_equivalence_with_swap(self) -> None:
464
+ """'t d h' vs 's h d': plan not None, x-pattern reorders."""
465
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
466
+ Pair(x="t d h", y="s h d")
467
+ )
468
+ assert result is not None
469
+ assert result.pattern.x is not None
470
+
471
+ def test_s_t_equivalence_with_fused(self) -> None:
472
+ """'t (a*b)' vs 's a b': plan not None, y-pattern flattens."""
473
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
474
+ Pair(x="t (a*b)", y="s a b")
475
+ )
476
+ assert result is not None
477
+ assert result.pattern.y is not None
478
+
479
+ def test_s_t_equivalence_with_squeeze_and_fused(self) -> None:
480
+ """'t (num_heads*head_dim)' vs 's 1 num_heads head_dim': plan squeezes + flattens."""
481
+ result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
482
+ Pair(x="t (num_heads*head_dim)", y="s 1 num_heads head_dim")
483
+ )
484
+ assert result is not None
485
+
486
+
487
+ class TestSeqTokenEquivalenceExecute:
488
+ """Tests for s≡t dimension name equivalence in execute_axis_aligner_plan."""
489
+
490
+ def test_execute_s_t_squeeze(self) -> None:
491
+ """Tensor [4,1,8] with pattern 's 1 h -> s h' → shape [4,8]."""
492
+ torch.manual_seed(42)
493
+ tensor: torch.Tensor = torch.randn(4, 1, 8)
494
+ plan = AxisAlignerPlan(pattern=Pair(x=None, y="s 1 h -> s h"))
495
+
496
+ result: torch.Tensor = execute_axis_aligner_plan(
497
+ tensor=tensor, plan=plan, side="y"
498
+ )
499
+
500
+ assert result.shape == (4, 8)
501
+ assert torch.equal(result, tensor.squeeze(1))
502
+
503
+
504
+ class TestEndToEndSeqTokenEquivalence:
505
+ """End-to-end tests for s≡t equivalence through compute + execute pipeline."""
506
+
507
+ def test_s_t_squeeze_full_pipeline(self) -> None:
508
+ """x=tensor(4,8) dims='t h', y=tensor(4,1,8) dims='s 1 h' → both aligned to (4,8)."""
509
+ torch.manual_seed(42)
510
+ data: torch.Tensor = torch.randn(4, 8)
511
+ x_tensor: torch.Tensor = data.clone()
512
+ y_tensor: torch.Tensor = data.unsqueeze(1)
513
+
514
+ plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
515
+ Pair(x="t h", y="s 1 h")
516
+ )
517
+ assert plan is not None
518
+
519
+ x_aligned: torch.Tensor = execute_axis_aligner_plan(
520
+ tensor=x_tensor, plan=plan, side="x"
521
+ )
522
+ y_aligned: torch.Tensor = execute_axis_aligner_plan(
523
+ tensor=y_tensor, plan=plan, side="y"
524
+ )
525
+
526
+ assert x_aligned.shape == y_aligned.shape == (4, 8)
527
+ assert torch.equal(x_aligned, y_aligned)
528
+
529
+ def test_s_t_fused_full_pipeline(self) -> None:
530
+ """x=tensor(4,128) dims='t (nh*hd)', y=tensor(4,1,8,16) dims='s 1 nh hd' → both (4,128)."""
531
+ torch.manual_seed(42)
532
+ num_heads: int = 8
533
+ head_dim: int = 16
534
+ data: torch.Tensor = torch.randn(4, num_heads * head_dim)
535
+ x_tensor: torch.Tensor = data.clone()
536
+ y_tensor: torch.Tensor = data.reshape(4, num_heads, head_dim).unsqueeze(1)
537
+
538
+ plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan(
539
+ Pair(x="t (nh*hd)", y="s 1 nh hd")
540
+ )
541
+ assert plan is not None
542
+
543
+ x_aligned: torch.Tensor = execute_axis_aligner_plan(
544
+ tensor=x_tensor, plan=plan, side="x"
545
+ )
546
+ y_aligned: torch.Tensor = execute_axis_aligner_plan(
547
+ tensor=y_tensor, plan=plan, side="y"
548
+ )
549
+
550
+ assert x_aligned.shape == y_aligned.shape == (4, num_heads * head_dim)
551
+ assert torch.equal(x_aligned, y_aligned)
552
+
553
+
554
+ if __name__ == "__main__":
555
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/__init__.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/conftest.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_loader.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import polars as pl
5
+ import pytest
6
+ import torch
7
+
8
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_loader import (
9
+ _detect_plugin,
10
+ _ensure_dims_in_metas,
11
+ _load_and_align_aux_tensor,
12
+ _load_non_tensor_aux,
13
+ )
14
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_plugins import (
15
+ _MegatronPlugin,
16
+ _SGLangPlugin,
17
+ )
18
+ from sglang.srt.debug_utils.comparator.log_sink import LogSink
19
+ from sglang.srt.debug_utils.comparator.output_types import ErrorLog, InfoLog
20
+ from sglang.test.ci.ci_register import register_cpu_ci
21
+
22
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
23
+
24
+ _sglang_plugin = _SGLangPlugin()
25
+ _megatron_plugin = _MegatronPlugin()
26
+
27
+
28
+ def _save_pt(
29
+ dump_path: Path,
30
+ *,
31
+ name: str,
32
+ step: int,
33
+ rank: int,
34
+ value: object,
35
+ meta: dict | None = None,
36
+ ) -> str:
37
+ filename: str = f"name={name}___step={step}___rank={rank}.pt"
38
+ payload: dict = {"value": value, "meta": meta or {}}
39
+ torch.save(payload, dump_path / filename)
40
+ return filename
41
+
42
+
43
+ def _make_df_from_filenames(filenames: list[str]) -> pl.DataFrame:
44
+ rows: list[dict] = []
45
+ for fn in filenames:
46
+ parts: dict = {}
47
+ stem: str = fn.removesuffix(".pt")
48
+ for kv in stem.split("___"):
49
+ if "=" in kv:
50
+ k, v = kv.split("=", 1)
51
+ parts[k] = v
52
+ rows.append(
53
+ {
54
+ "filename": fn,
55
+ "name": parts["name"],
56
+ "step": int(parts["step"]),
57
+ "rank": int(parts["rank"]),
58
+ }
59
+ )
60
+ return pl.DataFrame(rows)
61
+
62
+
63
+ class TestEnsureDimsInMetas:
64
+ """Tests for _ensure_dims_in_metas."""
65
+
66
+ def _make_meta(self, *, cp_size: int = 1, cp_rank: int = 0) -> dict:
67
+ return {
68
+ "sglang_parallel_info": {
69
+ "tp_rank": 0,
70
+ "tp_size": 1,
71
+ "cp_rank": cp_rank,
72
+ "cp_size": cp_size,
73
+ }
74
+ }
75
+
76
+ def test_no_cp_returns_metas_unchanged(self):
77
+ """Without CP parallelism, metas are returned as-is."""
78
+ metas: list[dict] = [self._make_meta(cp_size=1)]
79
+ result = _ensure_dims_in_metas(
80
+ name="input_ids", plugin=_sglang_plugin, metas=metas, ndim=1
81
+ )
82
+ assert result is metas
83
+
84
+ def test_dims_already_present_returns_metas_unchanged(self):
85
+ """If dims is already in meta, metas are returned as-is."""
86
+ metas: list[dict] = [{**self._make_meta(cp_size=2, cp_rank=0), "dims": "t"}]
87
+ result = _ensure_dims_in_metas(
88
+ name="input_ids", plugin=_sglang_plugin, metas=metas, ndim=1
89
+ )
90
+ assert result is metas
91
+
92
+ def test_cp_sharded_sglang_input_ids_infers_dims(self):
93
+ """CP + input_ids in sglang infers dims 't[cp:zigzag]'."""
94
+ metas: list[dict] = [
95
+ self._make_meta(cp_size=2, cp_rank=0),
96
+ self._make_meta(cp_size=2, cp_rank=1),
97
+ ]
98
+ result = _ensure_dims_in_metas(
99
+ name="input_ids", plugin=_sglang_plugin, metas=metas, ndim=1
100
+ )
101
+ assert result is not metas
102
+ assert result[0]["dims"] == "t[cp:zigzag]"
103
+ assert result[1]["dims"] == "t[cp:zigzag]"
104
+
105
+ def test_cp_sharded_sglang_positions_infers_dims(self):
106
+ """CP + positions in sglang infers dims 't[cp:zigzag]'."""
107
+ metas: list[dict] = [
108
+ self._make_meta(cp_size=2, cp_rank=0),
109
+ self._make_meta(cp_size=2, cp_rank=1),
110
+ ]
111
+ result = _ensure_dims_in_metas(
112
+ name="positions", plugin=_sglang_plugin, metas=metas, ndim=1
113
+ )
114
+ assert result[0]["dims"] == "t[cp:zigzag]"
115
+
116
+ def test_cp_sharded_megatron_input_ids_infers_dims_1d(self):
117
+ """CP + input_ids in megatron (1D) infers dims 't[cp:zigzag]'."""
118
+ metas: list[dict] = [
119
+ {"megatron_parallel_info": {"cp_rank": 0, "cp_size": 2}},
120
+ {"megatron_parallel_info": {"cp_rank": 1, "cp_size": 2}},
121
+ ]
122
+ result = _ensure_dims_in_metas(
123
+ name="input_ids", plugin=_megatron_plugin, metas=metas, ndim=1
124
+ )
125
+ assert result[0]["dims"] == "t[cp:zigzag]"
126
+
127
+ def test_cp_sharded_megatron_input_ids_infers_dims_2d(self):
128
+ """CP + input_ids in megatron (2D) infers dims 'b s[cp:zigzag]'."""
129
+ metas: list[dict] = [
130
+ {"megatron_parallel_info": {"cp_rank": 0, "cp_size": 2}},
131
+ {"megatron_parallel_info": {"cp_rank": 1, "cp_size": 2}},
132
+ ]
133
+ result = _ensure_dims_in_metas(
134
+ name="input_ids", plugin=_megatron_plugin, metas=metas, ndim=2
135
+ )
136
+ assert result[0]["dims"] == "b s[cp:zigzag]"
137
+
138
+ def test_cp_non_sharded_name_returns_metas_unchanged(self):
139
+ """CP + non-sharded tensor name (seq_lens) returns metas as-is."""
140
+ metas: list[dict] = [
141
+ self._make_meta(cp_size=2, cp_rank=0),
142
+ self._make_meta(cp_size=2, cp_rank=1),
143
+ ]
144
+ result = _ensure_dims_in_metas(
145
+ name="seq_lens", plugin=_sglang_plugin, metas=metas, ndim=1
146
+ )
147
+ assert result is metas
148
+
149
+ def test_unknown_plugin_returns_metas_unchanged(self):
150
+ """CP + plugin with empty cp_sharded_names returns metas as-is."""
151
+
152
+ class _DummyPlugin(_SGLangPlugin):
153
+ @property
154
+ def cp_sharded_names(self) -> frozenset[str]:
155
+ return frozenset()
156
+
157
+ metas: list[dict] = [
158
+ self._make_meta(cp_size=2, cp_rank=0),
159
+ self._make_meta(cp_size=2, cp_rank=1),
160
+ ]
161
+ result = _ensure_dims_in_metas(
162
+ name="input_ids", plugin=_DummyPlugin(), metas=metas, ndim=1
163
+ )
164
+ assert result is metas
165
+
166
+
167
+ class TestDetectPlugin:
168
+ def test_discriminating_names_sglang(self, tmp_path: Path) -> None:
169
+ fn: str = _save_pt(
170
+ tmp_path, name="seq_lens", step=0, rank=0, value=torch.tensor([3])
171
+ )
172
+ df: pl.DataFrame = _make_df_from_filenames([fn])
173
+
174
+ result = _detect_plugin(df, dump_path=tmp_path)
175
+
176
+ assert result is not None
177
+ assert result.name == "sglang"
178
+
179
+ def test_fallback_to_meta_based_detection(self, tmp_path: Path) -> None:
180
+ fn: str = _save_pt(
181
+ tmp_path,
182
+ name="input_ids",
183
+ step=0,
184
+ rank=0,
185
+ value=torch.tensor([1, 2, 3]),
186
+ meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}},
187
+ )
188
+ df: pl.DataFrame = _make_df_from_filenames([fn])
189
+
190
+ result = _detect_plugin(df, dump_path=tmp_path)
191
+
192
+ assert result is not None
193
+ assert result.name == "sglang"
194
+
195
+ def test_returns_none_no_match(self, tmp_path: Path) -> None:
196
+ fn: str = _save_pt(
197
+ tmp_path, name="unrelated_tensor", step=0, rank=0, value=torch.tensor([1])
198
+ )
199
+ df: pl.DataFrame = _make_df_from_filenames([fn])
200
+
201
+ result = _detect_plugin(df, dump_path=tmp_path)
202
+
203
+ assert result is None
204
+
205
+
206
+ class TestLoadNonTensorAux:
207
+ def test_multi_rank_mismatch_warning(self, tmp_path: Path) -> None:
208
+ fn0: str = _save_pt(tmp_path, name="rids", step=0, rank=0, value=["req_A"])
209
+ fn1: str = _save_pt(tmp_path, name="rids", step=0, rank=1, value=["req_B"])
210
+ df: pl.DataFrame = _make_df_from_filenames([fn0, fn1])
211
+
212
+ sink = LogSink()
213
+ with sink.context() as warnings:
214
+ from unittest.mock import patch
215
+
216
+ with patch(
217
+ "sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_loader.log_sink",
218
+ sink,
219
+ ):
220
+ result = _load_non_tensor_aux(
221
+ name="rids", step=0, df=df, dump_path=tmp_path
222
+ )
223
+
224
+ assert result == ["req_A"]
225
+ assert len(warnings) == 1
226
+ assert isinstance(warnings[0], ErrorLog)
227
+ assert "rids_mismatch" in warnings[0].category
228
+
229
+ def test_no_rows_returns_none(self, tmp_path: Path) -> None:
230
+ df: pl.DataFrame = _make_df_from_filenames([])
231
+
232
+ result = _load_non_tensor_aux(name="rids", step=0, df=df, dump_path=tmp_path)
233
+
234
+ assert result is None
235
+
236
+
237
+ class TestLoadAndAlignAuxTensor:
238
+ def test_multi_rank_no_dims_emits_warning(self, tmp_path: Path) -> None:
239
+ fn0: str = _save_pt(
240
+ tmp_path,
241
+ name="input_ids",
242
+ step=0,
243
+ rank=0,
244
+ value=torch.tensor([1, 2, 3]),
245
+ meta={
246
+ "sglang_parallel_info": {
247
+ "tp_rank": 0,
248
+ "tp_size": 2,
249
+ "cp_rank": 0,
250
+ "cp_size": 1,
251
+ }
252
+ },
253
+ )
254
+ fn1: str = _save_pt(
255
+ tmp_path,
256
+ name="input_ids",
257
+ step=0,
258
+ rank=1,
259
+ value=torch.tensor([4, 5, 6]),
260
+ meta={
261
+ "sglang_parallel_info": {
262
+ "tp_rank": 1,
263
+ "tp_size": 2,
264
+ "cp_rank": 0,
265
+ "cp_size": 1,
266
+ }
267
+ },
268
+ )
269
+ df: pl.DataFrame = _make_df_from_filenames([fn0, fn1])
270
+
271
+ sink = LogSink()
272
+ with sink.context() as warnings:
273
+ from unittest.mock import patch
274
+
275
+ with patch(
276
+ "sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_loader.log_sink",
277
+ sink,
278
+ ):
279
+ result = _load_and_align_aux_tensor(
280
+ name="input_ids",
281
+ step=0,
282
+ df=df,
283
+ dump_path=tmp_path,
284
+ plugin=_sglang_plugin,
285
+ )
286
+
287
+ assert result is not None
288
+ assert torch.equal(result, torch.tensor([1, 2, 3]))
289
+ assert len(warnings) == 1
290
+ assert isinstance(warnings[0], InfoLog)
291
+ assert "aux_no_dims" in warnings[0].category
292
+
293
+
294
+ class TestLoadNonTensorAuxDp:
295
+ """DP filtering in _load_non_tensor_aux."""
296
+
297
+ def test_dp2_non_tensor_returns_value(self, tmp_path: Path) -> None:
298
+ """DP=2 non-tensor aux: both ranks have same value, filter keeps all (non-tensor)."""
299
+ fn0: str = _save_pt(
300
+ tmp_path,
301
+ name="rids",
302
+ step=0,
303
+ rank=0,
304
+ value=["req_A"],
305
+ meta={
306
+ "sglang_parallel_info": {
307
+ "dp_rank": 0,
308
+ "dp_size": 2,
309
+ }
310
+ },
311
+ )
312
+ fn1: str = _save_pt(
313
+ tmp_path,
314
+ name="rids",
315
+ step=0,
316
+ rank=1,
317
+ value=["req_A"],
318
+ meta={
319
+ "sglang_parallel_info": {
320
+ "dp_rank": 1,
321
+ "dp_size": 2,
322
+ }
323
+ },
324
+ )
325
+ df: pl.DataFrame = _make_df_from_filenames([fn0, fn1])
326
+
327
+ sink = LogSink()
328
+ with sink.context():
329
+ from unittest.mock import patch
330
+
331
+ with patch(
332
+ "sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_loader.log_sink",
333
+ sink,
334
+ ):
335
+ result = _load_non_tensor_aux(
336
+ name="rids", step=0, df=df, dump_path=tmp_path
337
+ )
338
+
339
+ assert result == ["req_A"]
340
+
341
+
342
+ class TestLoadAndAlignAuxTensorDp:
343
+ """DP filtering in _load_and_align_aux_tensor."""
344
+
345
+ def test_dp2_tensor_one_empty(self, tmp_path: Path) -> None:
346
+ """DP=2 tensor aux: rank 0 has data, rank 1 empty -> returns rank 0 tensor."""
347
+ fn0: str = _save_pt(
348
+ tmp_path,
349
+ name="input_ids",
350
+ step=0,
351
+ rank=0,
352
+ value=torch.tensor([10, 20, 30]),
353
+ meta={
354
+ "sglang_parallel_info": {
355
+ "dp_rank": 0,
356
+ "dp_size": 2,
357
+ }
358
+ },
359
+ )
360
+ fn1: str = _save_pt(
361
+ tmp_path,
362
+ name="input_ids",
363
+ step=0,
364
+ rank=1,
365
+ value=torch.tensor([]),
366
+ meta={
367
+ "sglang_parallel_info": {
368
+ "dp_rank": 1,
369
+ "dp_size": 2,
370
+ }
371
+ },
372
+ )
373
+ df: pl.DataFrame = _make_df_from_filenames([fn0, fn1])
374
+
375
+ result = _load_and_align_aux_tensor(
376
+ name="input_ids",
377
+ step=0,
378
+ df=df,
379
+ dump_path=tmp_path,
380
+ plugin=_sglang_plugin,
381
+ )
382
+
383
+ assert result is not None
384
+ assert torch.equal(result, torch.tensor([10, 20, 30]))
385
+
386
+
387
+ if __name__ == "__main__":
388
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_plugins.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_plugins import (
7
+ _infer_positions,
8
+ _MegatronPlugin,
9
+ _SGLangPlugin,
10
+ )
11
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import (
12
+ PositionalSeqId,
13
+ SGLangSeqId,
14
+ TokenAlignerStepAux,
15
+ )
16
+ from sglang.srt.debug_utils.comparator.dims_spec import TokenLayout
17
+ from sglang.test.ci.ci_register import register_cpu_ci
18
+
19
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
20
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
21
+
22
+ _sglang_plugin = _SGLangPlugin()
23
+ _megatron_plugin = _MegatronPlugin()
24
+
25
+
26
+ class TestNormalizeSGLang:
27
+ """Tests for SGLang aux tensor normalization."""
28
+
29
+ def test_with_rids(self):
30
+ """SGLang tensors with rids produce string seq_ids."""
31
+ step_data: dict = {
32
+ "input_ids": torch.tensor([10, 20, 30]),
33
+ "positions": torch.tensor([0, 1, 2]),
34
+ "seq_lens": torch.tensor([3]),
35
+ "rids": ["A"],
36
+ }
37
+
38
+ result: TokenAlignerStepAux = _sglang_plugin.compute_step_aux(
39
+ step_data, layout=TokenLayout.T, step=0
40
+ )
41
+
42
+ assert result.input_ids == [10, 20, 30]
43
+ assert result.positions == [0, 1, 2]
44
+ assert result.seq_lens == [3]
45
+ assert result.seq_ids == [SGLangSeqId(rid="A")]
46
+
47
+ def test_rids_none_fallback(self):
48
+ """Missing rids results in (step, index) fallback seq_ids."""
49
+ step_data: dict = {
50
+ "input_ids": torch.tensor([10, 20]),
51
+ "positions": torch.tensor([0, 1]),
52
+ "seq_lens": torch.tensor([2]),
53
+ }
54
+
55
+ result: TokenAlignerStepAux = _sglang_plugin.compute_step_aux(
56
+ step_data, layout=TokenLayout.T, step=3
57
+ )
58
+ assert result.seq_ids == [PositionalSeqId(step=3, seq_index=0)]
59
+
60
+ def test_multiple_seqs_with_rids(self):
61
+ """Multiple sequences with rids."""
62
+ step_data: dict = {
63
+ "input_ids": torch.tensor([10, 20, 30, 40, 50]),
64
+ "positions": torch.tensor([0, 1, 2, 0, 1]),
65
+ "seq_lens": torch.tensor([3, 2]),
66
+ "rids": ["A", "B"],
67
+ }
68
+
69
+ result: TokenAlignerStepAux = _sglang_plugin.compute_step_aux(
70
+ step_data, layout=TokenLayout.T, step=0
71
+ )
72
+ assert result.seq_ids == [SGLangSeqId(rid="A"), SGLangSeqId(rid="B")]
73
+
74
+
75
+ class TestNormalizeMegatron:
76
+ """Tests for Megatron aux tensor normalization."""
77
+
78
+ def test_cu_seqlens_to_seq_lens(self):
79
+ """cu_seqlens_q is converted to seq_lens via differencing."""
80
+ step_data: dict = {
81
+ "input_ids": torch.tensor([10, 20, 30, 40, 50]),
82
+ "cu_seqlens_q": torch.tensor([0, 3, 5]),
83
+ }
84
+
85
+ result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux(
86
+ step_data, layout=TokenLayout.T, step=0
87
+ )
88
+
89
+ assert result.seq_lens == [3, 2]
90
+
91
+ def test_positions_inferred_thd(self):
92
+ """Positions inferred from seq_lens in thd layout."""
93
+ step_data: dict = {
94
+ "input_ids": torch.tensor([10, 20, 30, 40, 50]),
95
+ "cu_seqlens_q": torch.tensor([0, 3, 5]),
96
+ }
97
+
98
+ result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux(
99
+ step_data, layout=TokenLayout.T, step=0
100
+ )
101
+
102
+ assert result.positions == [0, 1, 2, 0, 1]
103
+
104
+ def test_position_ids_passthrough(self):
105
+ """Explicit position_ids used directly instead of inference."""
106
+ step_data: dict = {
107
+ "input_ids": torch.tensor([10, 20, 30, 40, 50]),
108
+ "position_ids": torch.tensor([5, 6, 7, 8, 9]),
109
+ "cu_seqlens_q": torch.tensor([0, 5]),
110
+ }
111
+
112
+ result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux(
113
+ step_data, layout=TokenLayout.T, step=0
114
+ )
115
+
116
+ assert result.positions == [5, 6, 7, 8, 9]
117
+
118
+ def test_seq_ids_are_step_index_tuples(self):
119
+ """Megatron seq_ids are (step, seq_index) tuples."""
120
+ step_data: dict = {
121
+ "input_ids": torch.tensor([10, 20, 30, 40, 50]),
122
+ "cu_seqlens_q": torch.tensor([0, 3, 5]),
123
+ }
124
+
125
+ result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux(
126
+ step_data, layout=TokenLayout.T, step=5
127
+ )
128
+ assert result.seq_ids == [
129
+ PositionalSeqId(step=5, seq_index=0),
130
+ PositionalSeqId(step=5, seq_index=1),
131
+ ]
132
+
133
+
134
+ class TestDetectLayoutMegatron:
135
+ """Tests for Megatron layout detection."""
136
+
137
+ def test_detect_layout_bshd_via_qkv_format(self):
138
+ """qkv_format containing 'bshd' → layout 'bshd'."""
139
+ raw: dict[int, dict[str, object]] = {
140
+ 0: {"qkv_format": "bshd", "input_ids": torch.tensor([1, 2, 3])}
141
+ }
142
+ assert _megatron_plugin.detect_layout(raw) == TokenLayout.BS
143
+
144
+ def test_detect_layout_bshd_via_ndim(self):
145
+ """2D input_ids → layout BS."""
146
+ raw: dict[int, dict[str, object]] = {
147
+ 0: {"input_ids": torch.tensor([[1, 2], [3, 4]])}
148
+ }
149
+ assert _megatron_plugin.detect_layout(raw) == TokenLayout.BS
150
+
151
+ def test_detect_layout_thd_via_qkv_format(self):
152
+ """qkv_format 'thd' → layout T."""
153
+ raw: dict[int, dict[str, object]] = {
154
+ 0: {"qkv_format": "thd", "input_ids": torch.tensor([1, 2, 3])}
155
+ }
156
+ assert _megatron_plugin.detect_layout(raw) == TokenLayout.T
157
+
158
+
159
+ class TestNormalizeMegatronBSHD:
160
+ """Tests for Megatron BSHD normalization."""
161
+
162
+ def test_basic_bshd(self):
163
+ """2D input_ids [2,4] → flat [8], seq_lens=[4,4], positions=[0,1,2,3,0,1,2,3]."""
164
+ step_data: dict = {
165
+ "input_ids": torch.tensor([[10, 20, 30, 40], [50, 60, 70, 80]]),
166
+ }
167
+
168
+ result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux(
169
+ step_data, layout=TokenLayout.BS, step=0
170
+ )
171
+
172
+ assert result.input_ids == [10, 20, 30, 40, 50, 60, 70, 80]
173
+ assert result.seq_lens == [4, 4]
174
+ assert result.positions == [0, 1, 2, 3, 0, 1, 2, 3]
175
+ assert result.seq_ids == [
176
+ PositionalSeqId(step=0, seq_index=0),
177
+ PositionalSeqId(step=0, seq_index=1),
178
+ ]
179
+
180
+ def test_bshd_with_cu_seqlens(self):
181
+ """BSHD with cu_seqlens_q → uses cu_seqlens for seq_lens."""
182
+ step_data: dict = {
183
+ "input_ids": torch.tensor([[10, 20, 30, 40], [50, 60, 70, 80]]),
184
+ "cu_seqlens_q": torch.tensor([0, 3, 8]),
185
+ }
186
+
187
+ result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux(
188
+ step_data, layout=TokenLayout.BS, step=0
189
+ )
190
+
191
+ assert result.seq_lens == [3, 5]
192
+
193
+ def test_bshd_with_position_ids(self):
194
+ """BSHD with 2D position_ids → flattened positions."""
195
+ step_data: dict = {
196
+ "input_ids": torch.tensor([[10, 20], [30, 40]]),
197
+ "position_ids": torch.tensor([[5, 6], [10, 11]]),
198
+ }
199
+
200
+ result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux(
201
+ step_data, layout=TokenLayout.BS, step=0
202
+ )
203
+
204
+ assert result.positions == [5, 6, 10, 11]
205
+
206
+
207
+ class TestInferPositions:
208
+ """Tests for position inference helper."""
209
+
210
+ def test_thd_multiple_sequences(self):
211
+ """thd: positions reset to 0 for each sequence."""
212
+ result = _infer_positions(
213
+ seq_lens=torch.tensor([2, 3]),
214
+ )
215
+ assert torch.equal(result, torch.tensor([0, 1, 0, 1, 2]))
216
+
217
+
218
+ class TestInferCpShardedDims:
219
+ """Tests for infer_cp_sharded_dims on each plugin."""
220
+
221
+ def test_megatron_infer_1d(self) -> None:
222
+ """Megatron 1D → 't[cp:zigzag]'."""
223
+ result: str = _megatron_plugin.infer_cp_sharded_dims(name="input_ids", ndim=1)
224
+ assert result == "t[cp:zigzag]"
225
+
226
+ def test_megatron_infer_2d(self) -> None:
227
+ """Megatron 2D → 'b s[cp:zigzag]'."""
228
+ result: str = _megatron_plugin.infer_cp_sharded_dims(name="input_ids", ndim=2)
229
+ assert result == "b s[cp:zigzag]"
230
+
231
+ def test_sglang_infer_1d(self) -> None:
232
+ """SGLang 1D → 't[cp:zigzag]'."""
233
+ result: str = _sglang_plugin.infer_cp_sharded_dims(name="input_ids", ndim=1)
234
+ assert result == "t[cp:zigzag]"
235
+
236
+ def test_megatron_infer_3d_raises(self) -> None:
237
+ """Megatron 3D raises ValueError."""
238
+ with pytest.raises(ValueError, match="cannot infer dims"):
239
+ _megatron_plugin.infer_cp_sharded_dims(name="input_ids", ndim=3)
240
+
241
+ def test_sglang_infer_2d_raises(self) -> None:
242
+ """SGLang 2D raises ValueError."""
243
+ with pytest.raises(ValueError, match="cannot infer dims"):
244
+ _sglang_plugin.infer_cp_sharded_dims(name="input_ids", ndim=2)
245
+
246
+
247
+ if __name__ == "__main__":
248
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_concat_steps.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.concat_steps import (
7
+ execute_token_aligner_concat_steps,
8
+ )
9
+ from sglang.srt.debug_utils.comparator.dims_spec import apply_dim_names
10
+ from sglang.srt.debug_utils.comparator.utils import Pair
11
+ from sglang.test.ci.ci_register import register_cpu_ci
12
+
13
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
14
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
15
+
16
+
17
+ class TestExecuteConcat:
18
+ def test_single_step_equal_length(self) -> None:
19
+ x = torch.tensor([1.0, 2.0, 3.0])
20
+ y = torch.tensor([4.0, 5.0, 6.0])
21
+ result: Pair[torch.Tensor] = execute_token_aligner_concat_steps(
22
+ tensor_of_step_pair=Pair(x={0: x}, y={0: y}),
23
+ )
24
+ assert torch.equal(result.x, x)
25
+ assert torch.equal(result.y, y)
26
+
27
+ def test_truncates_to_min(self) -> None:
28
+ x = torch.tensor([1.0, 2.0, 3.0, 4.0])
29
+ y = torch.tensor([5.0, 6.0])
30
+ result: Pair[torch.Tensor] = execute_token_aligner_concat_steps(
31
+ tensor_of_step_pair=Pair(x={0: x}, y={0: y}),
32
+ )
33
+ assert torch.equal(result.x, torch.tensor([1.0, 2.0]))
34
+ assert torch.equal(result.y, y)
35
+
36
+ def test_multi_step_sorted_concat(self) -> None:
37
+ result: Pair[torch.Tensor] = execute_token_aligner_concat_steps(
38
+ tensor_of_step_pair=Pair(
39
+ x={1: torch.tensor([3.0, 4.0]), 0: torch.tensor([1.0, 2.0])},
40
+ y={0: torch.tensor([5.0, 6.0, 7.0, 8.0])},
41
+ ),
42
+ )
43
+ assert torch.equal(result.x, torch.tensor([1.0, 2.0, 3.0, 4.0]))
44
+ assert torch.equal(result.y, torch.tensor([5.0, 6.0, 7.0, 8.0]))
45
+
46
+ def test_named_token_dim_nonzero(self) -> None:
47
+ """Token dim at dim=1 (not dim=0) — concat and truncate along correct dim."""
48
+ # shape [2, 3, 4]: dim0=batch, dim1=token, dim2=hidden
49
+ x_step0 = apply_dim_names(torch.randn(2, 3, 4), ["b", "t", "h"])
50
+ x_step1 = apply_dim_names(torch.randn(2, 5, 4), ["b", "t", "h"])
51
+ y_step0 = apply_dim_names(torch.randn(2, 6, 4), ["b", "t", "h"])
52
+
53
+ result: Pair[torch.Tensor] = execute_token_aligner_concat_steps(
54
+ tensor_of_step_pair=Pair(
55
+ x={0: x_step0, 1: x_step1},
56
+ y={0: y_step0},
57
+ ),
58
+ )
59
+
60
+ # x: 3+5=8 tokens; y: 6 tokens → truncate to 6
61
+ assert result.x.shape == (2, 6, 4)
62
+ assert result.y.shape == (2, 6, 4)
63
+
64
+ def test_named_dims_no_token_dim_fallback(self) -> None:
65
+ """Named dims without t or s → fallback to dim 0."""
66
+ x = apply_dim_names(torch.randn(4, 8), ["b", "h"])
67
+ y = apply_dim_names(torch.randn(3, 8), ["b", "h"])
68
+ result: Pair[torch.Tensor] = execute_token_aligner_concat_steps(
69
+ tensor_of_step_pair=Pair(x={0: x}, y={0: y}),
70
+ )
71
+ assert result.x.shape == (3, 8)
72
+ assert result.y.shape == (3, 8)
73
+
74
+ def test_seq_dim_fallback(self) -> None:
75
+ """Named dims with s but no t → uses s as token dim."""
76
+ x = apply_dim_names(torch.randn(2, 5, 4), ["b", "s", "h"])
77
+ y = apply_dim_names(torch.randn(2, 3, 4), ["b", "s", "h"])
78
+ result: Pair[torch.Tensor] = execute_token_aligner_concat_steps(
79
+ tensor_of_step_pair=Pair(x={0: x}, y={0: y}),
80
+ )
81
+ assert result.x.shape == (2, 3, 4)
82
+ assert result.y.shape == (2, 3, 4)
83
+
84
+
85
+ if __name__ == "__main__":
86
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_executor.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ import pytest
6
+ import torch
7
+
8
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.executor import (
9
+ execute_token_aligner,
10
+ )
11
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.planner import (
12
+ compute_token_aligner_plan,
13
+ )
14
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.seq_info_builder import (
15
+ build_seqs_info,
16
+ )
17
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import (
18
+ SGLangSeqId,
19
+ TokenAlignerGlobalAux,
20
+ TokenAlignerPlan,
21
+ TokenAlignerStepAux,
22
+ TokenLocator,
23
+ )
24
+ from sglang.srt.debug_utils.comparator.dims_spec import (
25
+ TokenLayout,
26
+ apply_dim_names,
27
+ without_dim_names,
28
+ )
29
+ from sglang.srt.debug_utils.comparator.utils import Pair
30
+ from sglang.test.ci.ci_register import register_cpu_ci
31
+
32
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
33
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
34
+
35
+
36
+ def _named(tensor: torch.Tensor, names: list[str]) -> torch.Tensor:
37
+ return apply_dim_names(tensor, names)
38
+
39
+
40
+ class TestExecuteAlignment:
41
+ """Tests for token alignment execution."""
42
+
43
+ def test_thd_vs_thd_identity(self):
44
+ """Two identical thd sides produce element-wise equal aligned tensors."""
45
+ torch.manual_seed(42)
46
+ hidden_step0 = apply_dim_names(torch.randn(5, 8), ["t", "h"])
47
+ hidden_step1 = apply_dim_names(torch.randn(2, 8), ["t", "h"])
48
+
49
+ aux = TokenAlignerStepAux(
50
+ input_ids=[10, 20, 30, 40, 50],
51
+ positions=[0, 1, 2, 0, 1],
52
+ seq_lens=[3, 2],
53
+ seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")],
54
+ )
55
+ aux_step1 = TokenAlignerStepAux(
56
+ input_ids=[31, 51],
57
+ positions=[3, 2],
58
+ seq_lens=[1, 1],
59
+ seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")],
60
+ )
61
+
62
+ side_aux = TokenAlignerGlobalAux(
63
+ step_auxs={0: aux, 1: aux_step1},
64
+ framework="sglang",
65
+ layout=TokenLayout.T,
66
+ )
67
+
68
+ index = build_seqs_info(side_aux)
69
+ plan = compute_token_aligner_plan(seqs_info_pair=Pair(x=index, y=index))
70
+
71
+ tensors = {0: hidden_step0, 1: hidden_step1}
72
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
73
+ plan=plan, tensor_of_step_pair=Pair(x=tensors, y=tensors)
74
+ )
75
+
76
+ assert torch.equal(aligned.x, aligned.y)
77
+ assert aligned.x.shape[0] == len(plan.locators.x.steps)
78
+
79
+ def test_zero_matched_tokens(self):
80
+ """Empty TokenAlignerPlan (no matched tokens) returns shape[0]==0 without crash."""
81
+ torch.manual_seed(42)
82
+
83
+ plan = TokenAlignerPlan(
84
+ locators=Pair(
85
+ x=TokenLocator(steps=[], token_index_in_step=[]),
86
+ y=TokenLocator(steps=[], token_index_in_step=[]),
87
+ ),
88
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.T),
89
+ )
90
+
91
+ tensors = {0: apply_dim_names(torch.randn(5, 8), ["t", "h"])}
92
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
93
+ plan=plan, tensor_of_step_pair=Pair(x=tensors, y=tensors)
94
+ )
95
+
96
+ assert aligned.x.shape[0] == 0
97
+ assert aligned.y.shape[0] == 0
98
+ assert aligned.x.shape[1:] == (8,)
99
+ assert aligned.y.shape[1:] == (8,)
100
+
101
+
102
+ class TestTokenDim:
103
+ """Tests for non-zero token_dim support."""
104
+
105
+ def _make_simple_plan(self, *, num_tokens: int) -> TokenAlignerPlan:
106
+ locator = TokenLocator(
107
+ steps=[0] * num_tokens,
108
+ token_index_in_step=list(range(num_tokens)),
109
+ )
110
+ return TokenAlignerPlan(
111
+ locators=Pair(x=locator, y=locator),
112
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.T),
113
+ )
114
+
115
+ def test_token_dim_nonzero(self) -> None:
116
+ """tensor shape [3, 5, 8], token_dim=1 -> token dim stays at dim 1."""
117
+ torch.manual_seed(42)
118
+ tensor: torch.Tensor = _named(torch.randn(3, 5, 8), ["a", "t", "h"])
119
+ plan: TokenAlignerPlan = self._make_simple_plan(num_tokens=5)
120
+
121
+ tensors: dict[int, torch.Tensor] = {0: tensor}
122
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
123
+ plan=plan,
124
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
125
+ )
126
+
127
+ assert aligned.x.shape == (3, 5, 8)
128
+ assert torch.equal(aligned.x, aligned.y)
129
+ plain: torch.Tensor = without_dim_names(tensor)
130
+ for i in range(5):
131
+ assert torch.equal(
132
+ aligned.x.select(dim=1, index=i), plain.select(dim=1, index=i)
133
+ )
134
+
135
+ def test_token_dim_last(self) -> None:
136
+ """tensor shape [3, 8, 5], token_dim=2 -> token dim stays at dim 2."""
137
+ torch.manual_seed(42)
138
+ tensor: torch.Tensor = _named(torch.randn(3, 8, 5), ["a", "h", "t"])
139
+ plan: TokenAlignerPlan = self._make_simple_plan(num_tokens=5)
140
+
141
+ tensors: dict[int, torch.Tensor] = {0: tensor}
142
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
143
+ plan=plan,
144
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
145
+ )
146
+
147
+ assert aligned.x.shape == (3, 8, 5)
148
+ plain: torch.Tensor = without_dim_names(tensor)
149
+ for i in range(5):
150
+ assert torch.equal(
151
+ aligned.x.select(dim=2, index=i), plain.select(dim=2, index=i)
152
+ )
153
+
154
+ def test_token_dim_zero(self) -> None:
155
+ """token_dim=0 selects along first dimension (standard t-h-d layout)."""
156
+ torch.manual_seed(42)
157
+ tensor: torch.Tensor = _named(torch.randn(5, 8), ["t", "h"])
158
+ plan: TokenAlignerPlan = self._make_simple_plan(num_tokens=5)
159
+
160
+ tensors: dict[int, torch.Tensor] = {0: tensor}
161
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
162
+ plan=plan,
163
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
164
+ )
165
+
166
+ assert aligned.x.shape == (5, 8)
167
+ plain: torch.Tensor = without_dim_names(tensor)
168
+ for i in range(5):
169
+ assert torch.equal(aligned.x[i], plain.select(dim=0, index=i))
170
+
171
+ def test_zero_matched_tokens_nonzero_token_dim(self) -> None:
172
+ """Empty plan with token_dim=1 produces correct empty shape."""
173
+ torch.manual_seed(42)
174
+
175
+ plan = TokenAlignerPlan(
176
+ locators=Pair(
177
+ x=TokenLocator(steps=[], token_index_in_step=[]),
178
+ y=TokenLocator(steps=[], token_index_in_step=[]),
179
+ ),
180
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.T),
181
+ )
182
+
183
+ tensors: dict[int, torch.Tensor] = {
184
+ 0: _named(torch.randn(3, 5, 8), ["a", "t", "h"])
185
+ }
186
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
187
+ plan=plan,
188
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
189
+ )
190
+
191
+ # token dim (dim 1) set to 0, other dims preserved -> [3, 0, 8]
192
+ assert aligned.x.shape == (3, 0, 8)
193
+ assert aligned.y.shape == (3, 0, 8)
194
+
195
+ def test_high_rank_tensor(self) -> None:
196
+ """tensor shape [2, 3, 5, 4, 8] (a b t c d), token_dim=2 -> stays at dim 2."""
197
+ torch.manual_seed(42)
198
+ tensor: torch.Tensor = _named(
199
+ torch.randn(2, 3, 5, 4, 8), ["a", "x", "t", "c", "h"]
200
+ )
201
+ plan: TokenAlignerPlan = self._make_simple_plan(num_tokens=5)
202
+
203
+ tensors: dict[int, torch.Tensor] = {0: tensor}
204
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
205
+ plan=plan,
206
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
207
+ )
208
+
209
+ assert aligned.x.shape == (2, 3, 5, 4, 8)
210
+ plain: torch.Tensor = without_dim_names(tensor)
211
+ for i in range(5):
212
+ assert torch.equal(
213
+ aligned.x.select(dim=2, index=i), plain.select(dim=2, index=i)
214
+ )
215
+
216
+
217
+ class TestBSHDExecutor:
218
+ """BSHD tensor collapse: B+S dims -> flat token dim for alignment."""
219
+
220
+ def test_bshd_standard_bs_at_front(self):
221
+ """Standard "b s h d": B=dim0, S=dim1. [2, 3, 4, 5] -> collapse -> [6, 4, 5]."""
222
+ torch.manual_seed(42)
223
+ tensor: torch.Tensor = _named(torch.randn(2, 3, 4, 5), ["b", "s", "h", "d"])
224
+ flat: torch.Tensor = tensor.reshape(6, 4, 5)
225
+
226
+ locator = TokenLocator(
227
+ steps=[0, 0, 0],
228
+ token_index_in_step=[0, 3, 5],
229
+ )
230
+ plan = TokenAlignerPlan(
231
+ locators=Pair(x=locator, y=locator),
232
+ layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS),
233
+ )
234
+
235
+ tensors: dict[int, torch.Tensor] = {0: tensor}
236
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
237
+ plan=plan,
238
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
239
+ )
240
+
241
+ assert aligned.x.shape == (3, 4, 5)
242
+ assert torch.equal(aligned.x[0], flat[0])
243
+ assert torch.equal(aligned.x[1], flat[3])
244
+ assert torch.equal(aligned.x[2], flat[5])
245
+
246
+ def test_bshd_3d_bs_at_front(self):
247
+ """Minimal 3D "b s h": B=dim0, S=dim1. [2, 3, 4] -> collapse -> [6, 4]."""
248
+ torch.manual_seed(42)
249
+ tensor: torch.Tensor = _named(torch.randn(2, 3, 4), ["b", "s", "h"])
250
+ flat: torch.Tensor = tensor.reshape(6, 4)
251
+
252
+ locator = TokenLocator(
253
+ steps=[0, 0, 0, 0],
254
+ token_index_in_step=[0, 2, 3, 5],
255
+ )
256
+ plan = TokenAlignerPlan(
257
+ locators=Pair(x=locator, y=locator),
258
+ layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS),
259
+ )
260
+
261
+ tensors: dict[int, torch.Tensor] = {0: tensor}
262
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
263
+ plan=plan,
264
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
265
+ )
266
+
267
+ assert aligned.x.shape == (4, 4)
268
+ assert torch.equal(aligned.x[0], flat[0])
269
+ assert torch.equal(aligned.x[1], flat[2])
270
+ assert torch.equal(aligned.x[2], flat[3])
271
+ assert torch.equal(aligned.x[3], flat[5])
272
+
273
+ def test_bshd_bs_not_at_front(self):
274
+ """Non-leading "h b s d": B=dim1, S=dim2. [4, 2, 3, 5] -> collapse -> [4, 6, 5]."""
275
+ torch.manual_seed(42)
276
+ tensor: torch.Tensor = _named(torch.randn(4, 2, 3, 5), ["h", "b", "s", "d"])
277
+ flat: torch.Tensor = tensor.reshape(4, 6, 5)
278
+
279
+ locator = TokenLocator(
280
+ steps=[0, 0, 0],
281
+ token_index_in_step=[0, 3, 5],
282
+ )
283
+ plan = TokenAlignerPlan(
284
+ locators=Pair(x=locator, y=locator),
285
+ layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS),
286
+ )
287
+
288
+ tensors: dict[int, torch.Tensor] = {0: tensor}
289
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
290
+ plan=plan,
291
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
292
+ )
293
+
294
+ assert aligned.x.shape == (4, 3, 5)
295
+ for idx, flat_idx in enumerate([0, 3, 5]):
296
+ assert torch.equal(
297
+ aligned.x.select(dim=1, index=idx),
298
+ flat.select(dim=1, index=flat_idx),
299
+ )
300
+
301
+ def test_bshd_expert_before_bs(self):
302
+ """Expert dim before B: "e b s h d". [2, 3, 4, 5, 6] -> collapse -> [2, 12, 5, 6]."""
303
+ torch.manual_seed(42)
304
+ tensor: torch.Tensor = _named(
305
+ torch.randn(2, 3, 4, 5, 6), ["e", "b", "s", "h", "d"]
306
+ )
307
+ flat: torch.Tensor = tensor.reshape(2, 12, 5, 6)
308
+
309
+ locator = TokenLocator(
310
+ steps=[0, 0, 0],
311
+ token_index_in_step=[0, 5, 11],
312
+ )
313
+ plan = TokenAlignerPlan(
314
+ locators=Pair(x=locator, y=locator),
315
+ layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS),
316
+ )
317
+
318
+ tensors: dict[int, torch.Tensor] = {0: tensor}
319
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
320
+ plan=plan,
321
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
322
+ )
323
+
324
+ assert aligned.x.shape == (2, 3, 5, 6)
325
+ for idx, flat_idx in enumerate([0, 5, 11]):
326
+ assert torch.equal(
327
+ aligned.x.select(dim=1, index=idx),
328
+ flat.select(dim=1, index=flat_idx),
329
+ )
330
+
331
+ def test_bshd_bs_at_end(self):
332
+ """B and S at end: "h d b s". [4, 5, 2, 3] -> collapse -> [4, 5, 6]."""
333
+ torch.manual_seed(42)
334
+ tensor: torch.Tensor = _named(torch.randn(4, 5, 2, 3), ["h", "d", "b", "s"])
335
+ flat: torch.Tensor = tensor.reshape(4, 5, 6)
336
+
337
+ locator = TokenLocator(
338
+ steps=[0, 0, 0],
339
+ token_index_in_step=[1, 3, 5],
340
+ )
341
+ plan = TokenAlignerPlan(
342
+ locators=Pair(x=locator, y=locator),
343
+ layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS),
344
+ )
345
+
346
+ tensors: dict[int, torch.Tensor] = {0: tensor}
347
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
348
+ plan=plan,
349
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
350
+ )
351
+
352
+ assert aligned.x.shape == (4, 5, 3)
353
+ for idx, flat_idx in enumerate([1, 3, 5]):
354
+ assert torch.equal(
355
+ aligned.x.select(dim=2, index=idx),
356
+ flat.select(dim=2, index=flat_idx),
357
+ )
358
+
359
+ def test_cross_layout_thd_vs_bshd(self):
360
+ """Cross-layout: x=THD [6, 8], y=BSHD [2, 3, 8] -> y collapse -> [6, 8]."""
361
+ torch.manual_seed(42)
362
+ tensor_thd: torch.Tensor = _named(torch.randn(6, 8), ["t", "h"])
363
+ tensor_bshd: torch.Tensor = _named(torch.randn(2, 3, 8), ["b", "s", "h"])
364
+ flat_bshd: torch.Tensor = tensor_bshd.reshape(6, 8)
365
+
366
+ locator = TokenLocator(
367
+ steps=[0, 0, 0],
368
+ token_index_in_step=[0, 2, 5],
369
+ )
370
+ plan = TokenAlignerPlan(
371
+ locators=Pair(x=locator, y=locator),
372
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.BS),
373
+ )
374
+
375
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
376
+ plan=plan,
377
+ tensor_of_step_pair=Pair(x={0: tensor_thd}, y={0: tensor_bshd}),
378
+ )
379
+
380
+ assert aligned.x.shape == (3, 8)
381
+ assert aligned.y.shape == (3, 8)
382
+ assert torch.equal(aligned.x[0], tensor_thd[0])
383
+ assert torch.equal(aligned.y[0], flat_bshd[0])
384
+ assert torch.equal(aligned.y[2], flat_bshd[5])
385
+
386
+ def test_bshd_reversed_sb_order(self):
387
+ """Reversed "s b h": S=dim0, B=dim1. Collapse is batch-major: (b s)."""
388
+ torch.manual_seed(42)
389
+ tensor: torch.Tensor = _named(torch.randn(3, 2, 4), ["s", "b", "h"])
390
+ # batch-major flatten: rearrange("s b h -> (b s) h")
391
+ from einops import rearrange
392
+
393
+ flat: torch.Tensor = rearrange(tensor, "s b h -> (b s) h")
394
+
395
+ locator = TokenLocator(
396
+ steps=[0, 0, 0],
397
+ token_index_in_step=[0, 2, 5],
398
+ )
399
+ plan = TokenAlignerPlan(
400
+ locators=Pair(x=locator, y=locator),
401
+ layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS),
402
+ )
403
+
404
+ tensors: dict[int, torch.Tensor] = {0: tensor}
405
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
406
+ plan=plan,
407
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
408
+ )
409
+
410
+ assert aligned.x.shape == (3, 4)
411
+ assert torch.equal(aligned.x[0], flat[0])
412
+ assert torch.equal(aligned.x[1], flat[2])
413
+ assert torch.equal(aligned.x[2], flat[5])
414
+
415
+ def test_bshd_empty_plan_bs_not_at_front(self):
416
+ """Empty plan with non-leading B,S: "h b s d". [4, 2, 3, 5] -> collapse -> [4, 0, 5]."""
417
+ plan = TokenAlignerPlan(
418
+ locators=Pair(
419
+ x=TokenLocator(steps=[], token_index_in_step=[]),
420
+ y=TokenLocator(steps=[], token_index_in_step=[]),
421
+ ),
422
+ layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS),
423
+ )
424
+
425
+ tensors: dict[int, torch.Tensor] = {
426
+ 0: _named(torch.randn(4, 2, 3, 5), ["h", "b", "s", "d"])
427
+ }
428
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
429
+ plan=plan,
430
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
431
+ )
432
+
433
+ assert aligned.x.shape == (4, 0, 5)
434
+ assert aligned.y.shape == (4, 0, 5)
435
+
436
+ def test_bshd_empty_plan_bs_at_front(self):
437
+ """Empty plan with standard BSHD: "b s h". [2, 3, 4] -> collapse -> [0, 4]."""
438
+ plan = TokenAlignerPlan(
439
+ locators=Pair(
440
+ x=TokenLocator(steps=[], token_index_in_step=[]),
441
+ y=TokenLocator(steps=[], token_index_in_step=[]),
442
+ ),
443
+ layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS),
444
+ )
445
+
446
+ tensors: dict[int, torch.Tensor] = {
447
+ 0: _named(torch.randn(2, 3, 4), ["b", "s", "h"])
448
+ }
449
+ aligned: Pair[torch.Tensor] = execute_token_aligner(
450
+ plan=plan,
451
+ tensor_of_step_pair=Pair(x=tensors, y=tensors),
452
+ )
453
+
454
+ assert aligned.x.shape == (0, 4)
455
+ assert aligned.y.shape == (0, 4)
456
+
457
+
458
+ if __name__ == "__main__":
459
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_planner.py ADDED
@@ -0,0 +1,575 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.planner import (
6
+ _match_sequences,
7
+ compute_token_aligner_plan,
8
+ )
9
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.seq_info_builder import (
10
+ build_seqs_info,
11
+ )
12
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import (
13
+ PositionalSeqId,
14
+ SeqId,
15
+ SGLangSeqId,
16
+ TokenAlignerGlobalAux,
17
+ TokenAlignerSeqInfo,
18
+ TokenAlignerSeqsInfo,
19
+ TokenAlignerStepAux,
20
+ TokenLocator,
21
+ )
22
+ from sglang.srt.debug_utils.comparator.dims_spec import TokenLayout
23
+ from sglang.srt.debug_utils.comparator.utils import Pair
24
+ from sglang.test.ci.ci_register import register_cpu_ci
25
+
26
+ register_cpu_ci(est_time=30, suite="base-a-test-cpu", nightly=True)
27
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
28
+
29
+
30
+ class TestBuildTokenIndexSGLangThd:
31
+ """Tests for SGLang thd token index building."""
32
+
33
+ def test_single_step_prefill(self):
34
+ """Single prefill step with two sequences."""
35
+ side_aux = TokenAlignerGlobalAux(
36
+ step_auxs={
37
+ 0: TokenAlignerStepAux(
38
+ input_ids=[10, 20, 30, 40, 50],
39
+ positions=[0, 1, 2, 0, 1],
40
+ seq_lens=[3, 2],
41
+ seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")],
42
+ ),
43
+ },
44
+ framework="sglang",
45
+ layout=TokenLayout.T,
46
+ )
47
+
48
+ index = build_seqs_info(side_aux)
49
+ assert len(index.sequences) == 2
50
+
51
+ seq_a = index.sequences[SGLangSeqId(rid="A")]
52
+ assert seq_a.input_ids == [10, 20, 30]
53
+ assert seq_a.positions == [0, 1, 2]
54
+ assert seq_a.locator.steps == [0, 0, 0]
55
+ assert seq_a.locator.token_index_in_step == [0, 1, 2]
56
+
57
+ seq_b = index.sequences[SGLangSeqId(rid="B")]
58
+ assert seq_b.input_ids == [40, 50]
59
+ assert seq_b.positions == [0, 1]
60
+ assert seq_b.locator.token_index_in_step == [3, 4]
61
+
62
+ def test_multi_step_prefill_decode(self):
63
+ """Prefill step followed by decode steps, sequences accumulate tokens."""
64
+ side_aux = TokenAlignerGlobalAux(
65
+ step_auxs={
66
+ 0: TokenAlignerStepAux(
67
+ input_ids=[10, 20, 30, 40, 50],
68
+ positions=[0, 1, 2, 0, 1],
69
+ seq_lens=[3, 2],
70
+ seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")],
71
+ ),
72
+ 1: TokenAlignerStepAux(
73
+ input_ids=[31, 51],
74
+ positions=[3, 2],
75
+ seq_lens=[1, 1],
76
+ seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")],
77
+ ),
78
+ },
79
+ framework="sglang",
80
+ layout=TokenLayout.T,
81
+ )
82
+
83
+ index = build_seqs_info(side_aux)
84
+ assert len(index.sequences) == 2
85
+
86
+ seq_a = index.sequences[SGLangSeqId(rid="A")]
87
+ assert seq_a.input_ids == [10, 20, 30, 31]
88
+ assert seq_a.positions == [0, 1, 2, 3]
89
+ assert seq_a.locator.steps == [0, 0, 0, 1]
90
+
91
+ seq_b = index.sequences[SGLangSeqId(rid="B")]
92
+ assert seq_b.input_ids == [40, 50, 51]
93
+ assert seq_b.positions == [0, 1, 2]
94
+
95
+ def test_sequence_exit_and_join(self):
96
+ """Sequence A exits, new sequence D joins with different seq_id."""
97
+ side_aux = TokenAlignerGlobalAux(
98
+ step_auxs={
99
+ 0: TokenAlignerStepAux(
100
+ input_ids=[10, 20, 30],
101
+ positions=[0, 1, 2],
102
+ seq_lens=[3],
103
+ seq_ids=[SGLangSeqId(rid="A")],
104
+ ),
105
+ 1: TokenAlignerStepAux(
106
+ input_ids=[100, 200],
107
+ positions=[0, 1],
108
+ seq_lens=[2],
109
+ seq_ids=[SGLangSeqId(rid="D")],
110
+ ),
111
+ },
112
+ framework="sglang",
113
+ layout=TokenLayout.T,
114
+ )
115
+
116
+ index = build_seqs_info(side_aux)
117
+ assert len(index.sequences) == 2
118
+
119
+ def test_different_seq_ids_produce_separate_sequences(self):
120
+ """Different seq_ids at different steps → separate sequences."""
121
+ side_aux = TokenAlignerGlobalAux(
122
+ step_auxs={
123
+ 0: TokenAlignerStepAux(
124
+ input_ids=[10, 20],
125
+ positions=[0, 1],
126
+ seq_lens=[2],
127
+ seq_ids=[SGLangSeqId(rid="A")],
128
+ ),
129
+ 1: TokenAlignerStepAux(
130
+ input_ids=[100, 200, 300],
131
+ positions=[0, 1, 2],
132
+ seq_lens=[3],
133
+ seq_ids=[SGLangSeqId(rid="D")],
134
+ ),
135
+ },
136
+ framework="sglang",
137
+ layout=TokenLayout.T,
138
+ )
139
+
140
+ index = build_seqs_info(side_aux)
141
+ assert len(index.sequences) == 2
142
+
143
+ all_input_ids = {
144
+ seq_id: rec.input_ids for seq_id, rec in index.sequences.items()
145
+ }
146
+ assert [10, 20] in all_input_ids.values()
147
+ assert [100, 200, 300] in all_input_ids.values()
148
+
149
+
150
+ class TestBuildTokenIndexMegatronThd:
151
+ """Tests for Megatron thd token index building."""
152
+
153
+ def test_single_step_two_sequences(self):
154
+ """Single step with two sequences in thd layout."""
155
+ side_aux = TokenAlignerGlobalAux(
156
+ step_auxs={
157
+ 0: TokenAlignerStepAux(
158
+ input_ids=[10, 20, 30, 40, 50],
159
+ positions=[0, 1, 2, 0, 1],
160
+ seq_lens=[3, 2],
161
+ seq_ids=[
162
+ PositionalSeqId(step=0, seq_index=0),
163
+ PositionalSeqId(step=0, seq_index=1),
164
+ ],
165
+ ),
166
+ },
167
+ framework="megatron",
168
+ layout=TokenLayout.T,
169
+ )
170
+
171
+ index = build_seqs_info(side_aux)
172
+ assert len(index.sequences) == 2
173
+
174
+ seq0 = index.sequences[PositionalSeqId(step=0, seq_index=0)]
175
+ assert seq0.input_ids == [10, 20, 30]
176
+ assert seq0.positions == [0, 1, 2]
177
+ assert seq0.locator.steps == [0, 0, 0]
178
+ assert seq0.locator.token_index_in_step == [0, 1, 2]
179
+
180
+ seq1 = index.sequences[PositionalSeqId(step=0, seq_index=1)]
181
+ assert seq1.input_ids == [40, 50]
182
+ assert seq1.positions == [0, 1]
183
+ assert seq1.locator.token_index_in_step == [3, 4]
184
+
185
+ def test_multi_step_accumulation(self):
186
+ """Two steps with different seq_ids produce separate sequences."""
187
+ side_aux = TokenAlignerGlobalAux(
188
+ step_auxs={
189
+ 0: TokenAlignerStepAux(
190
+ input_ids=[10, 20, 30, 40],
191
+ positions=[0, 1, 0, 1],
192
+ seq_lens=[2, 2],
193
+ seq_ids=[
194
+ PositionalSeqId(step=0, seq_index=0),
195
+ PositionalSeqId(step=0, seq_index=1),
196
+ ],
197
+ ),
198
+ 1: TokenAlignerStepAux(
199
+ input_ids=[50, 60, 70, 80],
200
+ positions=[0, 1, 0, 1],
201
+ seq_lens=[2, 2],
202
+ seq_ids=[
203
+ PositionalSeqId(step=1, seq_index=0),
204
+ PositionalSeqId(step=1, seq_index=1),
205
+ ],
206
+ ),
207
+ },
208
+ framework="megatron",
209
+ layout=TokenLayout.T,
210
+ )
211
+
212
+ index = build_seqs_info(side_aux)
213
+ assert len(index.sequences) == 4
214
+
215
+ seq0 = index.sequences[PositionalSeqId(step=0, seq_index=0)]
216
+ assert seq0.input_ids == [10, 20]
217
+ assert seq0.locator.steps == [0, 0]
218
+
219
+ seq2 = index.sequences[PositionalSeqId(step=1, seq_index=0)]
220
+ assert seq2.input_ids == [50, 60]
221
+ assert seq2.locator.steps == [1, 1]
222
+
223
+
224
+ class TestMatchSequences:
225
+ """Tests for _match_sequences: for each y, find matching x."""
226
+
227
+ def test_exact_match_simple(self):
228
+ """Identical input_ids on both sides → all matched."""
229
+ matched = _match_seqs(
230
+ x={0: (10, 20, 30), 1: (40, 50)},
231
+ y={0: (10, 20, 30), 1: (40, 50)},
232
+ )
233
+ S = _int_to_seq_id
234
+ assert _matched_ids(matched) == {(S(0), S(0)), (S(1), S(1))}
235
+
236
+ def test_exact_match_different_order(self):
237
+ """Sequences in different order still match by content."""
238
+ matched = _match_seqs(
239
+ x={0: (10, 20), 1: (40, 50)},
240
+ y={0: (40, 50), 1: (10, 20)},
241
+ )
242
+ S = _int_to_seq_id
243
+ assert _matched_ids(matched) == {(S(1), S(0)), (S(0), S(1))}
244
+
245
+ def test_exact_match_different_seq_ids(self):
246
+ """Seq IDs don't need to correspond — matching is by content."""
247
+ matched = _match_seqs(
248
+ x={5: (10, 20), 9: (30, 40)},
249
+ y={2: (30, 40), 7: (10, 20)},
250
+ )
251
+ S = _int_to_seq_id
252
+ assert _matched_ids(matched) == {(S(9), S(2)), (S(5), S(7))}
253
+
254
+ def test_no_match(self):
255
+ """Completely different input_ids → no matches."""
256
+ matched = _match_seqs(
257
+ x={0: (10, 20)},
258
+ y={0: (99, 88)},
259
+ )
260
+ assert matched == []
261
+
262
+ def test_empty_sides(self):
263
+ """Empty x or y → no matches."""
264
+ assert _match_seqs(x={}, y={0: (10,)}) == []
265
+ assert _match_seqs(x={0: (10,)}, y={}) == []
266
+ assert _match_seqs(x={}, y={}) == []
267
+
268
+ def test_x_has_more_sequences(self):
269
+ """Extra x sequences are ignored (no y needs them)."""
270
+ matched = _match_seqs(
271
+ x={0: (10, 20), 1: (30, 40), 2: (50, 60)},
272
+ y={0: (30, 40)},
273
+ )
274
+ S = _int_to_seq_id
275
+ assert _matched_ids(matched) == {(S(1), S(0))}
276
+
277
+ def test_y_has_more_sequences(self):
278
+ """Extra y sequences remain unmatched."""
279
+ matched = _match_seqs(
280
+ x={0: (10, 20)},
281
+ y={0: (10, 20), 1: (30, 40), 2: (50, 60)},
282
+ )
283
+ S = _int_to_seq_id
284
+ assert _matched_ids(matched) == {(S(0), S(0))}
285
+
286
+ def test_one_x_not_reused(self):
287
+ """Each x can only be claimed once, even if multiple y want it."""
288
+ matched = _match_seqs(
289
+ x={0: (10, 20)},
290
+ y={0: (10, 20), 1: (10, 20)},
291
+ )
292
+ assert len(matched) == 1
293
+
294
+ def test_ambiguous_all_matched(self):
295
+ """Multiple identical sequences on both sides → all paired (greedy 1:1)."""
296
+ matched = _match_seqs(
297
+ x={0: (10, 20), 1: (10, 20), 2: (10, 20)},
298
+ y={0: (10, 20), 1: (10, 20), 2: (10, 20)},
299
+ )
300
+ S = _int_to_seq_id
301
+ assert len(matched) == 3
302
+ x_ids = {m[0] for m in matched}
303
+ y_ids = {m[1] for m in matched}
304
+ assert x_ids == {S(0), S(1), S(2)}
305
+ assert y_ids == {S(0), S(1), S(2)}
306
+
307
+ def test_prefix_x_shorter(self):
308
+ """x has fewer tokens (prefix of y) → prefix match."""
309
+ matched = _match_seqs(
310
+ x={0: (10, 20)},
311
+ y={0: (10, 20, 30)},
312
+ )
313
+ S = _int_to_seq_id
314
+ assert _matched_ids(matched) == {(S(0), S(0))}
315
+
316
+ def test_prefix_y_shorter(self):
317
+ """y has fewer tokens (prefix of x) → prefix match."""
318
+ matched = _match_seqs(
319
+ x={0: (10, 20, 30)},
320
+ y={0: (10, 20)},
321
+ )
322
+ S = _int_to_seq_id
323
+ assert _matched_ids(matched) == {(S(0), S(0))}
324
+
325
+ def test_prefix_picks_longest(self):
326
+ """Among multiple prefix candidates, picks the one with longest overlap."""
327
+ matched = _match_seqs(
328
+ x={0: (10,), 1: (10, 20, 30)},
329
+ y={0: (10, 20, 30, 40)},
330
+ )
331
+ S = _int_to_seq_id
332
+ assert _matched_ids(matched) == {(S(1), S(0))}
333
+
334
+ def test_exact_preferred_over_prefix(self):
335
+ """Exact match is tried first, even if a longer prefix candidate exists."""
336
+ matched = _match_seqs(
337
+ x={0: (10, 20), 1: (10, 20, 30)},
338
+ y={0: (10, 20)},
339
+ )
340
+ S = _int_to_seq_id
341
+ assert _matched_ids(matched) == {(S(0), S(0))}
342
+
343
+ def test_prefix_fallback_after_exact(self):
344
+ """Exact matches consume sequences, remaining use prefix match."""
345
+ matched = _match_seqs(
346
+ x={0: (10, 20, 30), 1: (40, 50)},
347
+ y={0: (10, 20, 30), 1: (40, 50, 60)},
348
+ )
349
+ S = _int_to_seq_id
350
+ assert len(matched) == 2
351
+ matched_set = _matched_ids(matched)
352
+ assert (S(0), S(0)) in matched_set
353
+ assert (S(1), S(1)) in matched_set
354
+
355
+ def test_single_token_sequences(self):
356
+ """Single-token sequences can match."""
357
+ matched = _match_seqs(
358
+ x={0: (42,)},
359
+ y={0: (42,)},
360
+ )
361
+ S = _int_to_seq_id
362
+ assert _matched_ids(matched) == {(S(0), S(0))}
363
+
364
+ def test_no_partial_overlap_without_prefix(self):
365
+ """Overlapping content that isn't a prefix → no match."""
366
+ matched = _match_seqs(
367
+ x={0: (10, 20, 30)},
368
+ y={0: (20, 30, 40)},
369
+ )
370
+ assert matched == []
371
+
372
+
373
+ class TestComputeAlignmentPlanCrossFramework:
374
+ """Tests for alignment plan across different frameworks and layouts."""
375
+
376
+ def test_thd_vs_thd_different_step_splits(self):
377
+ """Two thd sides with same tokens but different step distributions."""
378
+ side_aux_a = TokenAlignerGlobalAux(
379
+ step_auxs={
380
+ 0: TokenAlignerStepAux(
381
+ input_ids=[10, 20],
382
+ positions=[0, 1],
383
+ seq_lens=[2],
384
+ seq_ids=[SGLangSeqId(rid="X")],
385
+ ),
386
+ 1: TokenAlignerStepAux(
387
+ input_ids=[30],
388
+ positions=[2],
389
+ seq_lens=[1],
390
+ seq_ids=[SGLangSeqId(rid="X")],
391
+ ),
392
+ },
393
+ framework="sglang",
394
+ layout=TokenLayout.T,
395
+ )
396
+ side_aux_b = TokenAlignerGlobalAux(
397
+ step_auxs={
398
+ 0: TokenAlignerStepAux(
399
+ input_ids=[10, 20, 30],
400
+ positions=[0, 1, 2],
401
+ seq_lens=[3],
402
+ seq_ids=[SGLangSeqId(rid="X")],
403
+ ),
404
+ },
405
+ framework="sglang",
406
+ layout=TokenLayout.T,
407
+ )
408
+
409
+ index_a = build_seqs_info(side_aux_a)
410
+ index_b = build_seqs_info(side_aux_b)
411
+
412
+ plan = compute_token_aligner_plan(seqs_info_pair=Pair(x=index_a, y=index_b))
413
+ assert len(plan.locators.x.steps) == 3
414
+
415
+ def test_sglang_vs_megatron_thd(self):
416
+ """SGLang multi-step thd aligned with Megatron single-step thd."""
417
+ side_aux_a = TokenAlignerGlobalAux(
418
+ step_auxs={
419
+ 0: TokenAlignerStepAux(
420
+ input_ids=[10, 20, 30, 40, 50],
421
+ positions=[0, 1, 2, 0, 1],
422
+ seq_lens=[3, 2],
423
+ seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")],
424
+ ),
425
+ 1: TokenAlignerStepAux(
426
+ input_ids=[31, 51],
427
+ positions=[3, 2],
428
+ seq_lens=[1, 1],
429
+ seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")],
430
+ ),
431
+ },
432
+ framework="sglang",
433
+ layout=TokenLayout.T,
434
+ )
435
+ side_aux_b = TokenAlignerGlobalAux(
436
+ step_auxs={
437
+ 0: TokenAlignerStepAux(
438
+ input_ids=[10, 20, 30, 31, 40, 50, 51],
439
+ positions=[0, 1, 2, 3, 0, 1, 2],
440
+ seq_lens=[4, 3],
441
+ seq_ids=[
442
+ PositionalSeqId(step=0, seq_index=0),
443
+ PositionalSeqId(step=0, seq_index=1),
444
+ ],
445
+ ),
446
+ },
447
+ framework="megatron",
448
+ layout=TokenLayout.T,
449
+ )
450
+
451
+ index_a = build_seqs_info(side_aux_a)
452
+ index_b = build_seqs_info(side_aux_b)
453
+
454
+ plan = compute_token_aligner_plan(seqs_info_pair=Pair(x=index_a, y=index_b))
455
+
456
+ assert len(plan.locators.x.steps) == 7
457
+
458
+ def test_cross_layout_sglang_thd_vs_megatron_bshd(self):
459
+ """SGLang THD vs Megatron BSHD end-to-end alignment via planner.
460
+
461
+ SGLang side: two sequences [10,20,30] and [40,50] across 2 steps.
462
+ Megatron BSHD side: same tokens as 2 batch slots [10,20,30,PAD] and [40,50,PAD,PAD],
463
+ where PAD tokens (99) are included because BSHD treats whole padded row as one seq.
464
+ Planner should match by prefix and align the common 5 tokens.
465
+ """
466
+ side_sglang = TokenAlignerGlobalAux(
467
+ step_auxs={
468
+ 0: TokenAlignerStepAux(
469
+ input_ids=[10, 20, 30, 40, 50],
470
+ positions=[0, 1, 2, 0, 1],
471
+ seq_lens=[3, 2],
472
+ seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")],
473
+ ),
474
+ },
475
+ framework="sglang",
476
+ layout=TokenLayout.T,
477
+ )
478
+
479
+ side_megatron_bshd = TokenAlignerGlobalAux(
480
+ step_auxs={
481
+ # BSHD normalized: flat [B*S] with each batch slot as one seq
482
+ 0: TokenAlignerStepAux(
483
+ input_ids=[10, 20, 30, 99, 40, 50, 99, 99],
484
+ positions=[0, 1, 2, 3, 0, 1, 2, 3],
485
+ seq_lens=[4, 4],
486
+ seq_ids=[
487
+ PositionalSeqId(step=0, seq_index=0),
488
+ PositionalSeqId(step=0, seq_index=1),
489
+ ],
490
+ ),
491
+ },
492
+ framework="megatron",
493
+ layout=TokenLayout.BS,
494
+ )
495
+
496
+ index_sglang = build_seqs_info(side_sglang)
497
+ index_megatron = build_seqs_info(side_megatron_bshd)
498
+
499
+ plan = compute_token_aligner_plan(
500
+ seqs_info_pair=Pair(x=index_sglang, y=index_megatron)
501
+ )
502
+
503
+ # Seq A: [10,20,30] matches prefix of [10,20,30,99] → 3 tokens
504
+ # Seq B: [40,50] matches prefix of [40,50,99,99] → 2 tokens
505
+ assert len(plan.locators.x.steps) == 5
506
+ assert plan.layouts.x == TokenLayout.T
507
+ assert plan.layouts.y == TokenLayout.BS
508
+
509
+
510
+ # ---------------------------------------------------------------------------
511
+ # Helpers
512
+ # ---------------------------------------------------------------------------
513
+
514
+
515
+ def _int_to_seq_id(k: int) -> SeqId:
516
+ """Convert an int key to a SeqId for test convenience."""
517
+ return SGLangSeqId(rid=str(k))
518
+
519
+
520
+ def _make_index(
521
+ *,
522
+ sequences: dict[int, tuple[int, ...]],
523
+ layout: TokenLayout = TokenLayout.T,
524
+ ) -> TokenAlignerSeqsInfo:
525
+ """Create a TokenAlignerSeqsInfo from simplified input_ids-only specification."""
526
+ records: dict[SeqId, TokenAlignerSeqInfo] = {}
527
+ for k, input_ids in sequences.items():
528
+ num_tokens = len(input_ids)
529
+ records[_int_to_seq_id(k)] = TokenAlignerSeqInfo(
530
+ input_ids=list(input_ids),
531
+ positions=list(range(num_tokens)),
532
+ locator=TokenLocator(
533
+ steps=[0] * num_tokens,
534
+ token_index_in_step=list(range(num_tokens)),
535
+ ),
536
+ )
537
+ return TokenAlignerSeqsInfo(sequences=records, layout=layout)
538
+
539
+
540
+ def _make_seq_info_dict(
541
+ sequences: dict[int, tuple[int, ...]],
542
+ ) -> dict[SeqId, TokenAlignerSeqInfo]:
543
+ """Create a dict of TokenAlignerSeqInfo from {int_key: input_ids_tuple}."""
544
+ result: dict[SeqId, TokenAlignerSeqInfo] = {}
545
+ for k, input_ids in sequences.items():
546
+ num_tokens = len(input_ids)
547
+ result[_int_to_seq_id(k)] = TokenAlignerSeqInfo(
548
+ input_ids=list(input_ids),
549
+ positions=list(range(num_tokens)),
550
+ locator=TokenLocator(
551
+ steps=[0] * num_tokens,
552
+ token_index_in_step=list(range(num_tokens)),
553
+ ),
554
+ )
555
+ return result
556
+
557
+
558
+ def _match_seqs(
559
+ *,
560
+ x: dict[int, tuple[int, ...]],
561
+ y: dict[int, tuple[int, ...]],
562
+ ) -> list[tuple[SeqId, SeqId]]:
563
+ """Shorthand: build SeqInfo dicts and call _match_sequences."""
564
+ return _match_sequences(
565
+ seqs=Pair(x=_make_seq_info_dict(x), y=_make_seq_info_dict(y))
566
+ )
567
+
568
+
569
+ def _matched_ids(matched: list[tuple[SeqId, SeqId]]) -> set[tuple[SeqId, SeqId]]:
570
+ """Convert matched pairs list to set for order-independent comparison."""
571
+ return set(matched)
572
+
573
+
574
+ if __name__ == "__main__":
575
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_thd_seq_lens_loader.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+ from unittest.mock import patch
4
+
5
+ import polars as pl
6
+ import pytest
7
+ import torch
8
+
9
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.concat_steps.thd_seq_lens_loader import (
10
+ load_thd_seq_lens_only,
11
+ )
12
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_plugins import (
13
+ _SGLangPlugin,
14
+ )
15
+ from sglang.test.ci.ci_register import register_cpu_ci
16
+
17
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
18
+
19
+
20
+ def _save_pt(
21
+ dump_path: Path,
22
+ *,
23
+ name: str,
24
+ step: int,
25
+ rank: int,
26
+ value: object,
27
+ meta: dict | None = None,
28
+ ) -> str:
29
+ filename: str = f"name={name}___step={step}___rank={rank}.pt"
30
+ payload: dict = {"value": value, "meta": meta or {}}
31
+ torch.save(payload, dump_path / filename)
32
+ return filename
33
+
34
+
35
+ def _make_df_from_filenames(filenames: list[str]) -> pl.DataFrame:
36
+ rows: list[dict] = []
37
+ for fn in filenames:
38
+ parts: dict = {}
39
+ stem: str = fn.removesuffix(".pt")
40
+ for kv in stem.split("___"):
41
+ if "=" in kv:
42
+ k, v = kv.split("=", 1)
43
+ parts[k] = v
44
+ rows.append(
45
+ {
46
+ "filename": fn,
47
+ "name": parts["name"],
48
+ "step": int(parts["step"]),
49
+ "rank": int(parts["rank"]),
50
+ }
51
+ )
52
+ return pl.DataFrame(rows)
53
+
54
+
55
+ class TestLoadThdSeqLensOnly:
56
+ """Tests for load_thd_seq_lens_only."""
57
+
58
+ def test_returns_none_when_no_plugin(self, tmp_path: Path) -> None:
59
+ """No recognized plugin → returns None."""
60
+ fn: str = _save_pt(
61
+ tmp_path, name="unrelated_tensor", step=0, rank=0, value=torch.tensor([1])
62
+ )
63
+ df: pl.DataFrame = _make_df_from_filenames([fn])
64
+
65
+ result = load_thd_seq_lens_only(dump_path=tmp_path, df=df)
66
+
67
+ assert result is None
68
+
69
+ def test_returns_none_when_no_cp_sharded_names(self, tmp_path: Path) -> None:
70
+ """Plugin detected but cp_sharded_names is empty → returns None."""
71
+
72
+ class _NoCpPlugin(_SGLangPlugin):
73
+ @property
74
+ def cp_sharded_names(self) -> frozenset[str]:
75
+ return frozenset()
76
+
77
+ fn: str = _save_pt(
78
+ tmp_path,
79
+ name="seq_lens",
80
+ step=0,
81
+ rank=0,
82
+ value=torch.tensor([3, 5]),
83
+ meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}},
84
+ )
85
+ df: pl.DataFrame = _make_df_from_filenames([fn])
86
+
87
+ with patch(
88
+ "sglang.srt.debug_utils.comparator.aligner.token_aligner.concat_steps.thd_seq_lens_loader._detect_plugin",
89
+ return_value=_NoCpPlugin(),
90
+ ):
91
+ result = load_thd_seq_lens_only(dump_path=tmp_path, df=df)
92
+
93
+ assert result is None
94
+
95
+ def test_sglang_extracts_seq_lens(self, tmp_path: Path) -> None:
96
+ """SGLang format: seq_lens tensor present → extracts per-seq lengths."""
97
+ fn: str = _save_pt(
98
+ tmp_path,
99
+ name="seq_lens",
100
+ step=0,
101
+ rank=0,
102
+ value=torch.tensor([3, 5]),
103
+ meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}},
104
+ )
105
+ df: pl.DataFrame = _make_df_from_filenames([fn])
106
+
107
+ result = load_thd_seq_lens_only(dump_path=tmp_path, df=df)
108
+
109
+ assert result is not None
110
+ assert result == {0: [3, 5]}
111
+
112
+ def test_megatron_extracts_from_cu_seqlens(self, tmp_path: Path) -> None:
113
+ """Megatron format: cu_seqlens_q tensor → derives seq_lens via diff."""
114
+ fn: str = _save_pt(
115
+ tmp_path,
116
+ name="cu_seqlens_q",
117
+ step=0,
118
+ rank=0,
119
+ value=torch.tensor([0, 3, 8], dtype=torch.int64),
120
+ meta={"megatron_parallel_info": {"cp_rank": 0, "cp_size": 2}},
121
+ )
122
+ df: pl.DataFrame = _make_df_from_filenames([fn])
123
+
124
+ result = load_thd_seq_lens_only(dump_path=tmp_path, df=df)
125
+
126
+ assert result is not None
127
+ assert result == {0: [3, 5]}
128
+
129
+ def test_multi_step(self, tmp_path: Path) -> None:
130
+ """Two steps with different seq_lens → returns both in result dict."""
131
+ fn0: str = _save_pt(
132
+ tmp_path,
133
+ name="seq_lens",
134
+ step=0,
135
+ rank=0,
136
+ value=torch.tensor([3, 5]),
137
+ meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}},
138
+ )
139
+ fn1: str = _save_pt(
140
+ tmp_path,
141
+ name="seq_lens",
142
+ step=1,
143
+ rank=0,
144
+ value=torch.tensor([10, 20, 30]),
145
+ meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}},
146
+ )
147
+ df: pl.DataFrame = _make_df_from_filenames([fn0, fn1])
148
+
149
+ result = load_thd_seq_lens_only(dump_path=tmp_path, df=df)
150
+
151
+ assert result is not None
152
+ assert result == {0: [3, 5], 1: [10, 20, 30]}
153
+
154
+ def test_returns_none_when_seq_lens_missing(self, tmp_path: Path) -> None:
155
+ """Plugin with cp_sharded_names but no seq_lens/cu_seqlens_q tensor → None."""
156
+ fn: str = _save_pt(
157
+ tmp_path,
158
+ name="cu_seqlens_kv",
159
+ step=0,
160
+ rank=0,
161
+ value=torch.tensor([0, 4], dtype=torch.int64),
162
+ meta={"megatron_parallel_info": {"cp_rank": 0, "cp_size": 2}},
163
+ )
164
+ df: pl.DataFrame = _make_df_from_filenames([fn])
165
+
166
+ result = load_thd_seq_lens_only(dump_path=tmp_path, df=df)
167
+
168
+ assert result is None
169
+
170
+
171
+ if __name__ == "__main__":
172
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/__init__.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/conftest.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_executor.py ADDED
@@ -0,0 +1,1097 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.executor import (
7
+ UnsharderResult,
8
+ _apply_unshard,
9
+ _verify_replicated_group,
10
+ execute_unsharder_plan,
11
+ )
12
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.planner import (
13
+ compute_unsharder_plan,
14
+ )
15
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import (
16
+ AxisInfo,
17
+ CpThdConcatParams,
18
+ PickParams,
19
+ ReduceSumParams,
20
+ UnsharderPlan,
21
+ )
22
+ from sglang.srt.debug_utils.comparator.dims_spec import (
23
+ DimSpec,
24
+ ParallelAxis,
25
+ apply_dim_names,
26
+ get_dim_names,
27
+ parse_dims,
28
+ without_dim_names,
29
+ )
30
+ from sglang.srt.debug_utils.comparator.output_types import ReplicatedCheckResult
31
+ from sglang.test.ci.ci_register import register_cpu_ci
32
+
33
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
34
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
35
+
36
+
37
+ def _name_tensors(
38
+ tensors: list[torch.Tensor], dim_specs: list[DimSpec]
39
+ ) -> list[torch.Tensor]:
40
+ names: list[str] = [s.sanitized_name for s in dim_specs]
41
+ return [apply_dim_names(t, names) for t in tensors]
42
+
43
+
44
+ class TestExecuteUnsharderPlan:
45
+ def test_tp4_concat(self) -> None:
46
+ full_tensor = torch.randn(2, 8, 16)
47
+ shards = list(full_tensor.chunk(4, dim=1))
48
+
49
+ dim_specs = parse_dims("b h[tp] d").dims
50
+ parallel_infos = [
51
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4)
52
+ ]
53
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
54
+ assert len(plans) == 1
55
+
56
+ named_shards: list[torch.Tensor] = _name_tensors(shards, dim_specs)
57
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
58
+ plans[0], named_shards
59
+ )
60
+ assert len(unsharder_result.tensors) == 1
61
+ assert torch.allclose(
62
+ without_dim_names(unsharder_result.tensors[0]), full_tensor
63
+ )
64
+ assert unsharder_result.replicated_checks == []
65
+
66
+ def test_scrambled_world_ranks_correct_result(self) -> None:
67
+ full_tensor = torch.randn(4, 8)
68
+ shards = list(full_tensor.chunk(4, dim=0))
69
+
70
+ parallel_infos = [
71
+ {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)},
72
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)},
73
+ {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)},
74
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)},
75
+ ]
76
+ dim_specs = parse_dims("h[tp] d").dims
77
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
78
+ assert len(plans) == 1
79
+
80
+ tensors_ordered_by_world_rank = _name_tensors(
81
+ [
82
+ shards[2], # world_rank=0, axis_rank=2
83
+ shards[0], # world_rank=1, axis_rank=0
84
+ shards[3], # world_rank=2, axis_rank=3
85
+ shards[1], # world_rank=3, axis_rank=1
86
+ ],
87
+ dim_specs,
88
+ )
89
+
90
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
91
+ plans[0], tensors_ordered_by_world_rank
92
+ )
93
+ assert len(unsharder_result.tensors) == 1
94
+ assert torch.allclose(
95
+ without_dim_names(unsharder_result.tensors[0]), full_tensor
96
+ )
97
+ assert unsharder_result.replicated_checks == []
98
+
99
+ def test_single_step_reduces_tensor_count(self) -> None:
100
+ """8 tensors with 2 groups of 4 produce 2 output tensors."""
101
+ full_a = torch.randn(4, 8)
102
+ full_b = torch.randn(4, 8)
103
+ shards_a = list(full_a.chunk(4, dim=0))
104
+ shards_b = list(full_b.chunk(4, dim=0))
105
+
106
+ dim_specs = parse_dims("s[cp] h[tp]").dims
107
+ parallel_infos = []
108
+ for cp_rank in range(2):
109
+ for tp_rank in range(4):
110
+ parallel_infos.append(
111
+ {
112
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
113
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=4),
114
+ }
115
+ )
116
+
117
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
118
+ assert len(plans) == 2
119
+
120
+ tensors: list[torch.Tensor] = []
121
+ for cp_rank in range(2):
122
+ source = shards_a if cp_rank == 0 else shards_b
123
+ for tp_rank in range(4):
124
+ tensors.append(source[tp_rank])
125
+
126
+ named_tensors: list[torch.Tensor] = _name_tensors(tensors, dim_specs)
127
+ intermediate_result: UnsharderResult = execute_unsharder_plan(
128
+ plans[0], named_tensors
129
+ )
130
+ assert len(intermediate_result.tensors) == 4
131
+
132
+ final_result: UnsharderResult = execute_unsharder_plan(
133
+ plans[1], intermediate_result.tensors
134
+ )
135
+ assert len(final_result.tensors) == 1
136
+
137
+ def test_cp_tp_concat(self) -> None:
138
+ """CP=2 + TP=2: multi-step unshard reconstructs original tensor."""
139
+ torch.manual_seed(42)
140
+ full_tensor = torch.randn(4, 8, 16)
141
+
142
+ cp_chunks = list(full_tensor.chunk(2, dim=1))
143
+ tensors: list[torch.Tensor] = []
144
+ parallel_infos = []
145
+ for cp_rank in range(2):
146
+ tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=2))
147
+ for tp_rank in range(2):
148
+ tensors.append(tp_chunks[tp_rank])
149
+ parallel_infos.append(
150
+ {
151
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
152
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
153
+ }
154
+ )
155
+
156
+ dim_specs = parse_dims("b s[cp] h[tp]").dims
157
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
158
+ assert len(plans) == 2
159
+
160
+ current: list[torch.Tensor] = _name_tensors(tensors, dim_specs)
161
+ for plan in plans:
162
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current)
163
+ current = unsharder_result.tensors
164
+
165
+ assert len(current) == 1
166
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
167
+
168
+ def test_cp_tp_scrambled(self) -> None:
169
+ """Scrambled world_ranks for CP=2 + TP=2 still reconstruct correctly."""
170
+ torch.manual_seed(42)
171
+ full_tensor = torch.randn(4, 8, 16)
172
+
173
+ cp_chunks = list(full_tensor.chunk(2, dim=1))
174
+ shard_map: dict[tuple[int, int], torch.Tensor] = {}
175
+ for cp_rank in range(2):
176
+ tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=2))
177
+ for tp_rank in range(2):
178
+ shard_map[(cp_rank, tp_rank)] = tp_chunks[tp_rank]
179
+
180
+ scrambled_assignment = [
181
+ (1, 1), # world_rank=0
182
+ (0, 0), # world_rank=1
183
+ (1, 0), # world_rank=2
184
+ (0, 1), # world_rank=3
185
+ ]
186
+
187
+ tensors: list[torch.Tensor] = []
188
+ parallel_infos = []
189
+ for cp_rank, tp_rank in scrambled_assignment:
190
+ tensors.append(shard_map[(cp_rank, tp_rank)])
191
+ parallel_infos.append(
192
+ {
193
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
194
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
195
+ }
196
+ )
197
+
198
+ dim_specs = parse_dims("b s[cp] h[tp]").dims
199
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
200
+ assert len(plans) == 2
201
+
202
+ current: list[torch.Tensor] = _name_tensors(tensors, dim_specs)
203
+ for plan in plans:
204
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current)
205
+ current = unsharder_result.tensors
206
+
207
+ assert len(current) == 1
208
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
209
+
210
+ def test_unsupported_params_type_raises(self) -> None:
211
+ """_apply_unshard raises ValueError for unknown params type."""
212
+
213
+ class _FakeParams:
214
+ pass
215
+
216
+ with pytest.raises(ValueError, match="Unsupported unshard"):
217
+ _apply_unshard(
218
+ _FakeParams(),
219
+ [torch.randn(2, 2)],
220
+ axis=ParallelAxis.TP,
221
+ group_index=0,
222
+ )
223
+
224
+ def test_cp_tp_ep_three_axis_concat(self) -> None:
225
+ """CP=2 + TP=2 + EP=2: three-step unshard reconstructs original tensor."""
226
+ torch.manual_seed(42)
227
+ full_tensor = torch.randn(4, 8, 16, 32)
228
+
229
+ ep_chunks = list(full_tensor.chunk(2, dim=1))
230
+ shard_map: dict[tuple[int, int, int], torch.Tensor] = {}
231
+ for ep_rank in range(2):
232
+ cp_chunks = list(ep_chunks[ep_rank].chunk(2, dim=2))
233
+ for cp_rank in range(2):
234
+ tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=3))
235
+ for tp_rank in range(2):
236
+ shard_map[(ep_rank, cp_rank, tp_rank)] = tp_chunks[tp_rank]
237
+
238
+ tensors: list[torch.Tensor] = []
239
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
240
+ for ep_rank in range(2):
241
+ for cp_rank in range(2):
242
+ for tp_rank in range(2):
243
+ tensors.append(shard_map[(ep_rank, cp_rank, tp_rank)])
244
+ parallel_infos.append(
245
+ {
246
+ ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2),
247
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
248
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
249
+ }
250
+ )
251
+
252
+ dim_specs = parse_dims("b e[ep] s[cp] h[tp]").dims
253
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
254
+ assert len(plans) == 3
255
+
256
+ current: list[torch.Tensor] = _name_tensors(tensors, dim_specs)
257
+ for plan in plans:
258
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current)
259
+ current = unsharder_result.tensors
260
+
261
+ assert len(current) == 1
262
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
263
+
264
+ def test_cp_tp_ep_scrambled_three_axis(self) -> None:
265
+ """Scrambled ranks for CP=2 + TP=2 + EP=2 still reconstruct correctly."""
266
+ torch.manual_seed(42)
267
+ full_tensor = torch.randn(4, 8, 16, 32)
268
+
269
+ ep_chunks = list(full_tensor.chunk(2, dim=1))
270
+ shard_map: dict[tuple[int, int, int], torch.Tensor] = {}
271
+ for ep_rank in range(2):
272
+ cp_chunks = list(ep_chunks[ep_rank].chunk(2, dim=2))
273
+ for cp_rank in range(2):
274
+ tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=3))
275
+ for tp_rank in range(2):
276
+ shard_map[(ep_rank, cp_rank, tp_rank)] = tp_chunks[tp_rank]
277
+
278
+ scrambled_assignment = [
279
+ (1, 0, 1), # world_rank=0
280
+ (0, 1, 0), # world_rank=1
281
+ (1, 1, 0), # world_rank=2
282
+ (0, 0, 0), # world_rank=3
283
+ (0, 1, 1), # world_rank=4
284
+ (1, 0, 0), # world_rank=5
285
+ (0, 0, 1), # world_rank=6
286
+ (1, 1, 1), # world_rank=7
287
+ ]
288
+
289
+ tensors: list[torch.Tensor] = []
290
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
291
+ for ep_rank, cp_rank, tp_rank in scrambled_assignment:
292
+ tensors.append(shard_map[(ep_rank, cp_rank, tp_rank)])
293
+ parallel_infos.append(
294
+ {
295
+ ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2),
296
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
297
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
298
+ }
299
+ )
300
+
301
+ dim_specs = parse_dims("b e[ep] s[cp] h[tp]").dims
302
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
303
+ assert len(plans) == 3
304
+
305
+ current: list[torch.Tensor] = _name_tensors(tensors, dim_specs)
306
+ for plan in plans:
307
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current)
308
+ current = unsharder_result.tensors
309
+
310
+ assert len(current) == 1
311
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
312
+
313
+
314
+ class TestPickOperation:
315
+ def test_pick_single_group(self) -> None:
316
+ """PickParams picks the first tensor from a single group."""
317
+ tensor = torch.randn(4, 8)
318
+ dim_specs = parse_dims("h d # tp:replicated").dims
319
+ replicated = frozenset({ParallelAxis.TP})
320
+ parallel_infos = [
321
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)},
322
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)},
323
+ ]
324
+
325
+ plans = compute_unsharder_plan(
326
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
327
+ )
328
+ assert len(plans) == 1
329
+ assert isinstance(plans[0].params, PickParams)
330
+
331
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
332
+ plans[0], [tensor, tensor.clone()]
333
+ )
334
+ assert len(unsharder_result.tensors) == 1
335
+ assert torch.allclose(without_dim_names(unsharder_result.tensors[0]), tensor)
336
+ assert all(c.passed for c in unsharder_result.replicated_checks)
337
+
338
+ def test_pick_multiple_groups(self) -> None:
339
+ """PickParams with multiple groups picks one from each."""
340
+ dim_specs = parse_dims("h[tp] # cp:replicated").dims
341
+ replicated = frozenset({ParallelAxis.CP})
342
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
343
+ {
344
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
345
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
346
+ },
347
+ {
348
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
349
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
350
+ },
351
+ {
352
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
353
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
354
+ },
355
+ {
356
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
357
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
358
+ },
359
+ ]
360
+
361
+ plans = compute_unsharder_plan(
362
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
363
+ )
364
+ pick_plans = [p for p in plans if isinstance(p.params, PickParams)]
365
+ assert len(pick_plans) == 1
366
+ assert pick_plans[0].axis == ParallelAxis.CP
367
+
368
+ tensor = torch.randn(4)
369
+ tensors = [tensor.clone() for _ in range(4)]
370
+
371
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
372
+ pick_plans[0], tensors
373
+ )
374
+ assert len(unsharder_result.tensors) == 2
375
+ assert all(c.passed for c in unsharder_result.replicated_checks)
376
+
377
+ def test_replicated_tp_sharded_cp_e2e(self) -> None:
378
+ """CP2 TP2, dims='b s[cp] d # tp:replicated': replicated TP pick + sharded CP concat round-trip."""
379
+ torch.manual_seed(42)
380
+ full_tensor = torch.randn(4, 8, 16)
381
+ cp_chunks = list(full_tensor.chunk(2, dim=1))
382
+
383
+ tensors: list[torch.Tensor] = []
384
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
385
+ for cp_rank in range(2):
386
+ for tp_rank in range(2):
387
+ tensors.append(cp_chunks[cp_rank].clone())
388
+ parallel_infos.append(
389
+ {
390
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
391
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
392
+ }
393
+ )
394
+
395
+ dim_specs = parse_dims("b s[cp] d # tp:replicated").dims
396
+ replicated = frozenset({ParallelAxis.TP})
397
+ plans = compute_unsharder_plan(
398
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
399
+ )
400
+ assert len(plans) == 2
401
+
402
+ current: list[torch.Tensor] = _name_tensors(tensors, dim_specs)
403
+ for plan in plans:
404
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current)
405
+ current = unsharder_result.tensors
406
+
407
+ assert len(current) == 1
408
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
409
+
410
+ def test_fully_replicated_e2e(self) -> None:
411
+ """CP2 TP2, dims='b h d # cp:replicated tp:replicated': fully replicated -> 2 pick steps -> 1 tensor."""
412
+ torch.manual_seed(42)
413
+ full_tensor = torch.randn(4, 8, 16)
414
+
415
+ tensors: list[torch.Tensor] = []
416
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
417
+ for cp_rank in range(2):
418
+ for tp_rank in range(2):
419
+ tensors.append(full_tensor.clone())
420
+ parallel_infos.append(
421
+ {
422
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
423
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
424
+ }
425
+ )
426
+
427
+ dim_specs = parse_dims("b h d # cp:replicated tp:replicated").dims
428
+ replicated = frozenset({ParallelAxis.CP, ParallelAxis.TP})
429
+ plans = compute_unsharder_plan(
430
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
431
+ )
432
+ assert len(plans) == 2
433
+ assert all(isinstance(p.params, PickParams) for p in plans)
434
+
435
+ current: list[torch.Tensor] = _name_tensors(tensors, dim_specs)
436
+ for plan in plans:
437
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current)
438
+ current = unsharder_result.tensors
439
+
440
+ assert len(current) == 1
441
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
442
+
443
+
444
+ class TestVerifyReplicatedGroup:
445
+ def test_fails_on_mismatch(self) -> None:
446
+ """_verify_replicated_group returns failed check when replicas differ."""
447
+ tensor_a = torch.ones(4)
448
+ tensor_b = torch.ones(4) + 0.1
449
+
450
+ checks: list[ReplicatedCheckResult] = _verify_replicated_group(
451
+ [tensor_a, tensor_b],
452
+ axis=ParallelAxis.TP,
453
+ group_index=0,
454
+ )
455
+ assert len(checks) == 1
456
+ assert checks[0].axis == "tp"
457
+ assert checks[0].group_index == 0
458
+ assert checks[0].compared_index == 1
459
+ assert checks[0].baseline_index == 0
460
+ assert not checks[0].passed
461
+ assert checks[0].diff.max_abs_diff == pytest.approx(0.1, abs=1e-5)
462
+
463
+ def test_passes_when_identical(self) -> None:
464
+ """_verify_replicated_group returns passed check for identical replicas."""
465
+ tensor = torch.randn(4, 8)
466
+
467
+ checks: list[ReplicatedCheckResult] = _verify_replicated_group(
468
+ [tensor, tensor.clone()],
469
+ axis=ParallelAxis.TP,
470
+ group_index=0,
471
+ )
472
+ assert len(checks) == 1
473
+ assert checks[0].passed
474
+
475
+ def test_multiple_mismatches(self) -> None:
476
+ """_verify_replicated_group reports each differing replica."""
477
+ baseline = torch.zeros(4)
478
+ other_a = torch.ones(4)
479
+ other_b = torch.ones(4) * 2
480
+
481
+ checks: list[ReplicatedCheckResult] = _verify_replicated_group(
482
+ [baseline, other_a, other_b],
483
+ axis=ParallelAxis.CP,
484
+ group_index=1,
485
+ )
486
+ assert len(checks) == 2
487
+ assert checks[0].compared_index == 1
488
+ assert not checks[0].passed
489
+ assert checks[1].compared_index == 2
490
+ assert not checks[1].passed
491
+ assert checks[1].diff.max_abs_diff == pytest.approx(2.0, abs=1e-5)
492
+
493
+ def test_execute_returns_replicated_checks(self) -> None:
494
+ """execute_unsharder_plan returns replicated checks for mismatch."""
495
+ dim_specs = parse_dims("h d # tp:replicated").dims
496
+ replicated = frozenset({ParallelAxis.TP})
497
+ parallel_infos = [
498
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)},
499
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)},
500
+ ]
501
+ plans = compute_unsharder_plan(
502
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
503
+ )
504
+
505
+ tensor_a = torch.zeros(4)
506
+ tensor_b = torch.ones(4)
507
+
508
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
509
+ plans[0], [tensor_a, tensor_b]
510
+ )
511
+ assert len(unsharder_result.tensors) == 1
512
+ assert len(unsharder_result.replicated_checks) == 1
513
+ assert not unsharder_result.replicated_checks[0].passed
514
+ assert torch.allclose(without_dim_names(unsharder_result.tensors[0]), tensor_a)
515
+
516
+ def test_atol_boundary_within(self) -> None:
517
+ """Difference exactly at atol (1e-6) -> passed."""
518
+ baseline = torch.zeros(4)
519
+ other = torch.full((4,), 1e-6)
520
+
521
+ checks: list[ReplicatedCheckResult] = _verify_replicated_group(
522
+ [baseline, other],
523
+ axis=ParallelAxis.TP,
524
+ group_index=0,
525
+ )
526
+ assert len(checks) == 1
527
+ assert checks[0].passed
528
+
529
+ def test_atol_boundary_exceeded(self) -> None:
530
+ """Difference just above atol (1e-6 + 1e-9) -> failed."""
531
+ baseline = torch.zeros(4)
532
+ other = torch.full((4,), 1e-6 + 1e-9)
533
+
534
+ checks: list[ReplicatedCheckResult] = _verify_replicated_group(
535
+ [baseline, other],
536
+ axis=ParallelAxis.TP,
537
+ group_index=0,
538
+ )
539
+ assert len(checks) == 1
540
+ assert not checks[0].passed
541
+ assert checks[0].compared_index == 1
542
+
543
+ def test_recompute_pseudo_mismatch(self) -> None:
544
+ """_verify_replicated_group returns failed check for RECOMPUTE_PSEUDO axis mismatch."""
545
+ tensor_a = torch.ones(4)
546
+ tensor_b = torch.ones(4) + 0.1
547
+
548
+ checks: list[ReplicatedCheckResult] = _verify_replicated_group(
549
+ [tensor_a, tensor_b],
550
+ axis=ParallelAxis.RECOMPUTE_PSEUDO,
551
+ group_index=0,
552
+ )
553
+ assert len(checks) == 1
554
+ assert checks[0].axis == "recompute_pseudo"
555
+ assert checks[0].group_index == 0
556
+ assert checks[0].compared_index == 1
557
+ assert checks[0].baseline_index == 0
558
+ assert not checks[0].passed
559
+ assert checks[0].diff.max_abs_diff == pytest.approx(0.1, abs=1e-5)
560
+
561
+
562
+ class TestThdCpConcat:
563
+ def test_single_seq(self) -> None:
564
+ """Single seq THD unshard: 2 ranks → per-seq concat."""
565
+ rank0 = apply_dim_names(torch.tensor([1, 2, 3]), ["t"])
566
+ rank1 = apply_dim_names(torch.tensor([4, 5, 6]), ["t"])
567
+
568
+ plan = UnsharderPlan(
569
+ axis=ParallelAxis.CP,
570
+ params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3]),
571
+ groups=[[0, 1]],
572
+ )
573
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1])
574
+
575
+ assert len(unsharder_result.tensors) == 1
576
+ expected = torch.tensor([1, 2, 3, 4, 5, 6])
577
+ assert torch.equal(without_dim_names(unsharder_result.tensors[0]), expected)
578
+
579
+ def test_multi_seq(self) -> None:
580
+ """Multi-seq THD unshard: 2 ranks, seq_lens=[50, 32, 46]."""
581
+ # rank0: [seqA_r0(50) | seqB_r0(32) | pad_r0(46)]
582
+ # rank1: [seqA_r1(50) | seqB_r1(32) | pad_r1(46)]
583
+ seq_a_r0 = torch.arange(0, 50)
584
+ seq_b_r0 = torch.arange(100, 132)
585
+ pad_r0 = torch.full((46,), -1)
586
+ rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0, pad_r0]), ["t"])
587
+
588
+ seq_a_r1 = torch.arange(50, 100)
589
+ seq_b_r1 = torch.arange(132, 164)
590
+ pad_r1 = torch.full((46,), -2)
591
+ rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1, pad_r1]), ["t"])
592
+
593
+ plan = UnsharderPlan(
594
+ axis=ParallelAxis.CP,
595
+ params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[50, 32, 46]),
596
+ groups=[[0, 1]],
597
+ )
598
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1])
599
+
600
+ assert len(unsharder_result.tensors) == 1
601
+ unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0])
602
+
603
+ # seqA: r0(50) + r1(50) = 100 tokens, values 0..99
604
+ assert torch.equal(unsharded[:100], torch.cat([seq_a_r0, seq_a_r1]))
605
+ # seqB: r0(32) + r1(32) = 64 tokens
606
+ assert torch.equal(unsharded[100:164], torch.cat([seq_b_r0, seq_b_r1]))
607
+ # pad: r0(46) + r1(46) = 92 tokens
608
+ assert torch.equal(unsharded[164:256], torch.cat([pad_r0, pad_r1]))
609
+
610
+ def test_with_hidden_dim(self) -> None:
611
+ """THD unshard with trailing hidden dim: shape [T, H]."""
612
+ torch.manual_seed(42)
613
+ hidden: int = 4
614
+ # rank0: [seqA_r0(3, 4) | seqB_r0(2, 4)]
615
+ # rank1: [seqA_r1(3, 4) | seqB_r1(2, 4)]
616
+ seq_a_r0 = torch.randn(3, hidden)
617
+ seq_b_r0 = torch.randn(2, hidden)
618
+ rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0]), ["t", "h"])
619
+
620
+ seq_a_r1 = torch.randn(3, hidden)
621
+ seq_b_r1 = torch.randn(2, hidden)
622
+ rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1]), ["t", "h"])
623
+
624
+ plan = UnsharderPlan(
625
+ axis=ParallelAxis.CP,
626
+ params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3, 2]),
627
+ groups=[[0, 1]],
628
+ )
629
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1])
630
+
631
+ assert len(unsharder_result.tensors) == 1
632
+ unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0])
633
+
634
+ assert unsharded.shape == (10, hidden)
635
+ assert torch.equal(unsharded[:6], torch.cat([seq_a_r0, seq_a_r1]))
636
+ assert torch.equal(unsharded[6:10], torch.cat([seq_b_r0, seq_b_r1]))
637
+
638
+ def test_with_leading_batch_dim(self) -> None:
639
+ """THD unshard with leading batch dim: shape [B, T, H], t is dim=1."""
640
+ torch.manual_seed(42)
641
+ batch: int = 2
642
+ hidden: int = 4
643
+ # rank0: [seqA_r0(3) | seqB_r0(2)] per batch item
644
+ # rank1: [seqA_r1(3) | seqB_r1(2)] per batch item
645
+ seq_a_r0 = torch.randn(batch, 3, hidden)
646
+ seq_b_r0 = torch.randn(batch, 2, hidden)
647
+ rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0], dim=1), ["b", "t", "h"])
648
+
649
+ seq_a_r1 = torch.randn(batch, 3, hidden)
650
+ seq_b_r1 = torch.randn(batch, 2, hidden)
651
+ rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1], dim=1), ["b", "t", "h"])
652
+
653
+ plan = UnsharderPlan(
654
+ axis=ParallelAxis.CP,
655
+ params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3, 2]),
656
+ groups=[[0, 1]],
657
+ )
658
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1])
659
+
660
+ assert len(unsharder_result.tensors) == 1
661
+ unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0])
662
+
663
+ assert unsharded.shape == (batch, 10, hidden)
664
+ # seqA: r0(3) + r1(3) = 6 tokens per batch
665
+ assert torch.equal(unsharded[:, :6, :], torch.cat([seq_a_r0, seq_a_r1], dim=1))
666
+ # seqB: r0(2) + r1(2) = 4 tokens per batch
667
+ assert torch.equal(
668
+ unsharded[:, 6:10, :], torch.cat([seq_b_r0, seq_b_r1], dim=1)
669
+ )
670
+
671
+
672
+ class TestReduceSum:
673
+ def test_basic_tp2_reduce(self) -> None:
674
+ """2 partial tensors sum to full tensor."""
675
+ torch.manual_seed(42)
676
+ full_tensor = torch.randn(4, 8)
677
+ part_a = full_tensor * 0.6
678
+ part_b = full_tensor * 0.4
679
+
680
+ dim_specs = parse_dims("h[tp:partial] d").dims
681
+ parallel_infos = [
682
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
683
+ ]
684
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
685
+ assert len(plans) == 1
686
+ assert isinstance(plans[0].params, ReduceSumParams)
687
+
688
+ named_parts: list[torch.Tensor] = _name_tensors([part_a, part_b], dim_specs)
689
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
690
+ plans[0], named_parts
691
+ )
692
+
693
+ assert len(unsharder_result.tensors) == 1
694
+ assert torch.allclose(
695
+ without_dim_names(unsharder_result.tensors[0]), full_tensor
696
+ )
697
+
698
+ def test_tp4_reduce(self) -> None:
699
+ """4 partial tensors sum to full tensor."""
700
+ torch.manual_seed(42)
701
+ full_tensor = torch.randn(4, 8)
702
+ parts: list[torch.Tensor] = [full_tensor * 0.25 for _ in range(4)]
703
+
704
+ dim_specs = parse_dims("h[tp:partial] d").dims
705
+ parallel_infos = [
706
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4)
707
+ ]
708
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
709
+ assert len(plans) == 1
710
+
711
+ named_parts: list[torch.Tensor] = _name_tensors(parts, dim_specs)
712
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
713
+ plans[0], named_parts
714
+ )
715
+
716
+ assert len(unsharder_result.tensors) == 1
717
+ assert torch.allclose(
718
+ without_dim_names(unsharder_result.tensors[0]), full_tensor
719
+ )
720
+
721
+ def test_multi_axis_concat_then_reduce(self) -> None:
722
+ """CP concat + TP reduce end-to-end."""
723
+ torch.manual_seed(42)
724
+ full_tensor = torch.randn(4, 8, 16)
725
+
726
+ cp_chunks = list(full_tensor.chunk(2, dim=1))
727
+ # Each CP chunk is held as partial sums across TP ranks
728
+ tensors: list[torch.Tensor] = []
729
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
730
+ for cp_rank in range(2):
731
+ for tp_rank in range(2):
732
+ tensors.append(cp_chunks[cp_rank] * 0.5)
733
+ parallel_infos.append(
734
+ {
735
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
736
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
737
+ }
738
+ )
739
+
740
+ dim_specs = parse_dims("b s[cp] h[tp:partial]").dims
741
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
742
+ assert len(plans) == 2
743
+
744
+ current: list[torch.Tensor] = _name_tensors(tensors, dim_specs)
745
+ for plan in plans:
746
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current)
747
+ current = unsharder_result.tensors
748
+
749
+ assert len(current) == 1
750
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
751
+
752
+ def test_reduce_scrambled_ranks(self) -> None:
753
+ """Scrambled rank order — sum is commutative so result is the same."""
754
+ torch.manual_seed(42)
755
+ full_tensor = torch.randn(4, 8)
756
+ parts: list[torch.Tensor] = [
757
+ full_tensor * 0.1,
758
+ full_tensor * 0.2,
759
+ full_tensor * 0.3,
760
+ full_tensor * 0.4,
761
+ ]
762
+
763
+ parallel_infos = [
764
+ {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)},
765
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)},
766
+ {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)},
767
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)},
768
+ ]
769
+ dim_specs = parse_dims("h[tp:partial] d").dims
770
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
771
+
772
+ named_parts: list[torch.Tensor] = _name_tensors(parts, dim_specs)
773
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
774
+ plans[0], named_parts
775
+ )
776
+
777
+ assert len(unsharder_result.tensors) == 1
778
+ assert torch.allclose(
779
+ without_dim_names(unsharder_result.tensors[0]), full_tensor
780
+ )
781
+
782
+ def test_reduce_preserves_named_dims(self) -> None:
783
+ """Named tensor dimensions are preserved through reduce_sum."""
784
+ dim_specs = parse_dims("h[tp:partial] d").dims
785
+ part_a = apply_dim_names(torch.randn(4, 8), ["h", "d"])
786
+ part_b = apply_dim_names(torch.randn(4, 8), ["h", "d"])
787
+
788
+ plan = UnsharderPlan(
789
+ axis=ParallelAxis.TP,
790
+ params=ReduceSumParams(),
791
+ groups=[[0, 1]],
792
+ )
793
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
794
+ plan, [part_a, part_b]
795
+ )
796
+
797
+ assert len(unsharder_result.tensors) == 1
798
+ assert get_dim_names(unsharder_result.tensors[0]) == ("h", "d")
799
+ expected = apply_dim_names(
800
+ without_dim_names(part_a) + without_dim_names(part_b), ["h", "d"]
801
+ )
802
+ assert torch.allclose(
803
+ without_dim_names(unsharder_result.tensors[0]), without_dim_names(expected)
804
+ )
805
+
806
+ def test_recompute_pseudo_mismatch(self) -> None:
807
+ """_verify_replicated_group returns failed check for RECOMPUTE_PSEUDO axis mismatch."""
808
+ tensor_a = torch.ones(4)
809
+ tensor_b = torch.ones(4) + 0.1
810
+
811
+ checks: list[ReplicatedCheckResult] = _verify_replicated_group(
812
+ [tensor_a, tensor_b],
813
+ axis=ParallelAxis.RECOMPUTE_PSEUDO,
814
+ group_index=0,
815
+ )
816
+ assert len(checks) == 1
817
+ assert checks[0].axis == "recompute_pseudo"
818
+ assert checks[0].group_index == 0
819
+ assert checks[0].compared_index == 1
820
+ assert checks[0].baseline_index == 0
821
+ assert not checks[0].passed
822
+ assert checks[0].diff.max_abs_diff == pytest.approx(0.1, abs=1e-5)
823
+
824
+
825
+ class TestThdCpConcat:
826
+ def test_single_seq(self) -> None:
827
+ """Single seq THD unshard: 2 ranks → per-seq concat."""
828
+ rank0 = apply_dim_names(torch.tensor([1, 2, 3]), ["t"])
829
+ rank1 = apply_dim_names(torch.tensor([4, 5, 6]), ["t"])
830
+
831
+ plan = UnsharderPlan(
832
+ axis=ParallelAxis.CP,
833
+ params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3]),
834
+ groups=[[0, 1]],
835
+ )
836
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1])
837
+
838
+ assert len(unsharder_result.tensors) == 1
839
+ expected = torch.tensor([1, 2, 3, 4, 5, 6])
840
+ assert torch.equal(without_dim_names(unsharder_result.tensors[0]), expected)
841
+
842
+ def test_multi_seq(self) -> None:
843
+ """Multi-seq THD unshard: 2 ranks, seq_lens=[50, 32, 46]."""
844
+ # rank0: [seqA_r0(50) | seqB_r0(32) | pad_r0(46)]
845
+ # rank1: [seqA_r1(50) | seqB_r1(32) | pad_r1(46)]
846
+ seq_a_r0 = torch.arange(0, 50)
847
+ seq_b_r0 = torch.arange(100, 132)
848
+ pad_r0 = torch.full((46,), -1)
849
+ rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0, pad_r0]), ["t"])
850
+
851
+ seq_a_r1 = torch.arange(50, 100)
852
+ seq_b_r1 = torch.arange(132, 164)
853
+ pad_r1 = torch.full((46,), -2)
854
+ rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1, pad_r1]), ["t"])
855
+
856
+ plan = UnsharderPlan(
857
+ axis=ParallelAxis.CP,
858
+ params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[50, 32, 46]),
859
+ groups=[[0, 1]],
860
+ )
861
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1])
862
+
863
+ assert len(unsharder_result.tensors) == 1
864
+ unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0])
865
+
866
+ # seqA: r0(50) + r1(50) = 100 tokens, values 0..99
867
+ assert torch.equal(unsharded[:100], torch.cat([seq_a_r0, seq_a_r1]))
868
+ # seqB: r0(32) + r1(32) = 64 tokens
869
+ assert torch.equal(unsharded[100:164], torch.cat([seq_b_r0, seq_b_r1]))
870
+ # pad: r0(46) + r1(46) = 92 tokens
871
+ assert torch.equal(unsharded[164:256], torch.cat([pad_r0, pad_r1]))
872
+
873
+ def test_with_hidden_dim(self) -> None:
874
+ """THD unshard with trailing hidden dim: shape [T, H]."""
875
+ torch.manual_seed(42)
876
+ hidden: int = 4
877
+ # rank0: [seqA_r0(3, 4) | seqB_r0(2, 4)]
878
+ # rank1: [seqA_r1(3, 4) | seqB_r1(2, 4)]
879
+ seq_a_r0 = torch.randn(3, hidden)
880
+ seq_b_r0 = torch.randn(2, hidden)
881
+ rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0]), ["t", "h"])
882
+
883
+ seq_a_r1 = torch.randn(3, hidden)
884
+ seq_b_r1 = torch.randn(2, hidden)
885
+ rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1]), ["t", "h"])
886
+
887
+ plan = UnsharderPlan(
888
+ axis=ParallelAxis.CP,
889
+ params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3, 2]),
890
+ groups=[[0, 1]],
891
+ )
892
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1])
893
+
894
+ assert len(unsharder_result.tensors) == 1
895
+ unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0])
896
+
897
+ assert unsharded.shape == (10, hidden)
898
+ assert torch.equal(unsharded[:6], torch.cat([seq_a_r0, seq_a_r1]))
899
+ assert torch.equal(unsharded[6:10], torch.cat([seq_b_r0, seq_b_r1]))
900
+
901
+ def test_with_leading_batch_dim(self) -> None:
902
+ """THD unshard with leading batch dim: shape [B, T, H], t is dim=1."""
903
+ torch.manual_seed(42)
904
+ batch: int = 2
905
+ hidden: int = 4
906
+ # rank0: [seqA_r0(3) | seqB_r0(2)] per batch item
907
+ # rank1: [seqA_r1(3) | seqB_r1(2)] per batch item
908
+ seq_a_r0 = torch.randn(batch, 3, hidden)
909
+ seq_b_r0 = torch.randn(batch, 2, hidden)
910
+ rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0], dim=1), ["b", "t", "h"])
911
+
912
+ seq_a_r1 = torch.randn(batch, 3, hidden)
913
+ seq_b_r1 = torch.randn(batch, 2, hidden)
914
+ rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1], dim=1), ["b", "t", "h"])
915
+
916
+ plan = UnsharderPlan(
917
+ axis=ParallelAxis.CP,
918
+ params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3, 2]),
919
+ groups=[[0, 1]],
920
+ )
921
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1])
922
+
923
+ assert len(unsharder_result.tensors) == 1
924
+ unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0])
925
+
926
+ assert unsharded.shape == (batch, 10, hidden)
927
+ # seqA: r0(3) + r1(3) = 6 tokens per batch
928
+ assert torch.equal(unsharded[:, :6, :], torch.cat([seq_a_r0, seq_a_r1], dim=1))
929
+ # seqB: r0(2) + r1(2) = 4 tokens per batch
930
+ assert torch.equal(
931
+ unsharded[:, 6:10, :], torch.cat([seq_b_r0, seq_b_r1], dim=1)
932
+ )
933
+
934
+
935
+ class TestReduceSum:
936
+ def test_basic_tp2_reduce(self) -> None:
937
+ """2 partial tensors sum to full tensor."""
938
+ torch.manual_seed(42)
939
+ full_tensor = torch.randn(4, 8)
940
+ part_a = full_tensor * 0.6
941
+ part_b = full_tensor * 0.4
942
+
943
+ dim_specs = parse_dims("h[tp:partial] d").dims
944
+ parallel_infos = [
945
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
946
+ ]
947
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
948
+ assert len(plans) == 1
949
+ assert isinstance(plans[0].params, ReduceSumParams)
950
+
951
+ named_parts: list[torch.Tensor] = _name_tensors([part_a, part_b], dim_specs)
952
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
953
+ plans[0], named_parts
954
+ )
955
+
956
+ assert len(unsharder_result.tensors) == 1
957
+ assert torch.allclose(
958
+ without_dim_names(unsharder_result.tensors[0]), full_tensor
959
+ )
960
+
961
+ def test_tp4_reduce(self) -> None:
962
+ """4 partial tensors sum to full tensor."""
963
+ torch.manual_seed(42)
964
+ full_tensor = torch.randn(4, 8)
965
+ parts: list[torch.Tensor] = [full_tensor * 0.25 for _ in range(4)]
966
+
967
+ dim_specs = parse_dims("h[tp:partial] d").dims
968
+ parallel_infos = [
969
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4)
970
+ ]
971
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
972
+ assert len(plans) == 1
973
+
974
+ named_parts: list[torch.Tensor] = _name_tensors(parts, dim_specs)
975
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
976
+ plans[0], named_parts
977
+ )
978
+
979
+ assert len(unsharder_result.tensors) == 1
980
+ assert torch.allclose(
981
+ without_dim_names(unsharder_result.tensors[0]), full_tensor
982
+ )
983
+
984
+ def test_multi_axis_concat_then_reduce(self) -> None:
985
+ """CP concat + TP reduce end-to-end."""
986
+ torch.manual_seed(42)
987
+ full_tensor = torch.randn(4, 8, 16)
988
+
989
+ cp_chunks = list(full_tensor.chunk(2, dim=1))
990
+ # Each CP chunk is held as partial sums across TP ranks
991
+ tensors: list[torch.Tensor] = []
992
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
993
+ for cp_rank in range(2):
994
+ for tp_rank in range(2):
995
+ tensors.append(cp_chunks[cp_rank] * 0.5)
996
+ parallel_infos.append(
997
+ {
998
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
999
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
1000
+ }
1001
+ )
1002
+
1003
+ dim_specs = parse_dims("b s[cp] h[tp:partial]").dims
1004
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
1005
+ assert len(plans) == 2
1006
+
1007
+ current: list[torch.Tensor] = _name_tensors(tensors, dim_specs)
1008
+ for plan in plans:
1009
+ unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current)
1010
+ current = unsharder_result.tensors
1011
+
1012
+ assert len(current) == 1
1013
+ assert torch.allclose(without_dim_names(current[0]), full_tensor)
1014
+
1015
+ def test_reduce_scrambled_ranks(self) -> None:
1016
+ """Scrambled rank order — sum is commutative so result is the same."""
1017
+ torch.manual_seed(42)
1018
+ full_tensor = torch.randn(4, 8)
1019
+ parts: list[torch.Tensor] = [
1020
+ full_tensor * 0.1,
1021
+ full_tensor * 0.2,
1022
+ full_tensor * 0.3,
1023
+ full_tensor * 0.4,
1024
+ ]
1025
+
1026
+ parallel_infos = [
1027
+ {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)},
1028
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)},
1029
+ {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)},
1030
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)},
1031
+ ]
1032
+ dim_specs = parse_dims("h[tp:partial] d").dims
1033
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
1034
+
1035
+ named_parts: list[torch.Tensor] = _name_tensors(parts, dim_specs)
1036
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
1037
+ plans[0], named_parts
1038
+ )
1039
+
1040
+ assert len(unsharder_result.tensors) == 1
1041
+ assert torch.allclose(
1042
+ without_dim_names(unsharder_result.tensors[0]), full_tensor
1043
+ )
1044
+
1045
+ def test_reduce_preserves_named_dims(self) -> None:
1046
+ """Named tensor dimensions are preserved through reduce_sum."""
1047
+ dim_specs = parse_dims("h[tp:partial] d").dims
1048
+ part_a = apply_dim_names(torch.randn(4, 8), ["h", "d"])
1049
+ part_b = apply_dim_names(torch.randn(4, 8), ["h", "d"])
1050
+
1051
+ plan = UnsharderPlan(
1052
+ axis=ParallelAxis.TP,
1053
+ params=ReduceSumParams(),
1054
+ groups=[[0, 1]],
1055
+ )
1056
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
1057
+ plan, [part_a, part_b]
1058
+ )
1059
+
1060
+ assert len(unsharder_result.tensors) == 1
1061
+ assert get_dim_names(unsharder_result.tensors[0]) == ("h", "d")
1062
+ expected = apply_dim_names(
1063
+ without_dim_names(part_a) + without_dim_names(part_b), ["h", "d"]
1064
+ )
1065
+ assert torch.allclose(
1066
+ without_dim_names(unsharder_result.tensors[0]), without_dim_names(expected)
1067
+ )
1068
+
1069
+
1070
+ class TestFusedDimExecutor:
1071
+ def test_fused_tp2_concat(self) -> None:
1072
+ """Fused dim "t (num_heads*head_dim)[tp]": TP=2 concat on fused axis."""
1073
+ torch.manual_seed(42)
1074
+ full_tensor = torch.randn(4, 128) # t=4, nh*hd=128
1075
+
1076
+ shards = list(full_tensor.chunk(2, dim=1))
1077
+
1078
+ dim_specs = parse_dims("t (num_heads*head_dim)[tp]").dims
1079
+ parallel_infos = [
1080
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
1081
+ ]
1082
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
1083
+ assert len(plans) == 1
1084
+
1085
+ named_shards: list[torch.Tensor] = _name_tensors(shards, dim_specs)
1086
+ unsharder_result: UnsharderResult = execute_unsharder_plan(
1087
+ plans[0], named_shards
1088
+ )
1089
+
1090
+ assert len(unsharder_result.tensors) == 1
1091
+ assert torch.allclose(
1092
+ without_dim_names(unsharder_result.tensors[0]), full_tensor
1093
+ )
1094
+
1095
+
1096
+ if __name__ == "__main__":
1097
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_parallel_info.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.parallel_info import (
6
+ normalize_parallel_info,
7
+ )
8
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import AxisInfo
9
+ from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis
10
+ from sglang.test.ci.ci_register import register_cpu_ci
11
+
12
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
13
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
14
+
15
+
16
+ class TestNormalizeParallelInfo:
17
+ def test_sglang_info(self) -> None:
18
+ meta = {
19
+ "sglang_parallel_info": {
20
+ "tp_rank": 2,
21
+ "tp_size": 4,
22
+ "pp_rank": 0,
23
+ "pp_size": 1,
24
+ }
25
+ }
26
+ result = normalize_parallel_info(meta)
27
+ assert result == {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)}
28
+
29
+ def test_megatron_info(self) -> None:
30
+ meta = {
31
+ "megatron_parallel_info": {
32
+ "tp_rank": 1,
33
+ "tp_size": 2,
34
+ "cp_rank": 0,
35
+ "cp_size": 4,
36
+ "dp_rank": 0,
37
+ "dp_size": 1,
38
+ }
39
+ }
40
+ result = normalize_parallel_info(meta)
41
+ assert result == {
42
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
43
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=4),
44
+ }
45
+
46
+ def test_no_parallel_info(self) -> None:
47
+ assert normalize_parallel_info({}) == {}
48
+ assert normalize_parallel_info({"other_key": 42}) == {}
49
+
50
+ def test_both_present_raises(self) -> None:
51
+ meta = {
52
+ "sglang_parallel_info": {"tp_rank": 0, "tp_size": 2},
53
+ "megatron_parallel_info": {"tp_rank": 0, "tp_size": 2},
54
+ }
55
+ with pytest.raises(ValueError, match="multiple parallel_info"):
56
+ normalize_parallel_info(meta)
57
+
58
+ def test_megatron_with_sp(self) -> None:
59
+ """Megatron SP reuses TP group: sp_rank==tp_rank, sp_size==tp_size."""
60
+ meta = {
61
+ "megatron_parallel_info": {
62
+ "tp_rank": 1,
63
+ "tp_size": 4,
64
+ "sp_rank": 1,
65
+ "sp_size": 4,
66
+ }
67
+ }
68
+ result = normalize_parallel_info(meta)
69
+ assert result == {
70
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4),
71
+ ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=4),
72
+ }
73
+
74
+ def test_size_1_filtered(self) -> None:
75
+ meta = {
76
+ "sglang_parallel_info": {
77
+ "tp_rank": 0,
78
+ "tp_size": 1,
79
+ "cp_rank": 0,
80
+ "cp_size": 1,
81
+ }
82
+ }
83
+ assert normalize_parallel_info(meta) == {}
84
+
85
+ def test_recompute_pseudo_from_top_level_meta(self) -> None:
86
+ """recompute_pseudo_rank/size at top-level meta is extracted alongside TP."""
87
+ meta = {
88
+ "recompute_pseudo_rank": 1,
89
+ "recompute_pseudo_size": 2,
90
+ "sglang_parallel_info": {"tp_rank": 0, "tp_size": 2},
91
+ }
92
+ result = normalize_parallel_info(meta)
93
+ assert result == {
94
+ ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=1, axis_size=2),
95
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
96
+ }
97
+
98
+
99
+ if __name__ == "__main__":
100
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_planner.py ADDED
@@ -0,0 +1,2067 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.planner import (
6
+ _compute_dependent_axes,
7
+ _is_dependent_axis,
8
+ _is_jointly_determined,
9
+ _validate_explicit_replicated,
10
+ _validate_replicated_axes_orthogonal,
11
+ compute_unsharder_plan,
12
+ )
13
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import (
14
+ AxisInfo,
15
+ ConcatParams,
16
+ PickParams,
17
+ ReduceSumParams,
18
+ )
19
+ from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis, parse_dims
20
+ from sglang.test.ci.ci_register import register_cpu_ci
21
+
22
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
23
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
24
+
25
+
26
+ class TestComputeUnsharderPlan:
27
+ def test_tp4_plan(self) -> None:
28
+ dim_specs = parse_dims("b s h[tp] d").dims
29
+ parallel_infos = [
30
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4)
31
+ ]
32
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
33
+
34
+ assert len(plans) == 1
35
+ assert plans[0].axis == ParallelAxis.TP
36
+ assert plans[0].params.dim_name == "h"
37
+ assert plans[0].groups == [[0, 1, 2, 3]]
38
+
39
+ def test_inconsistent_axis_size_raises(self) -> None:
40
+ dim_specs = parse_dims("h[tp]").dims
41
+ parallel_infos = [
42
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)},
43
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)},
44
+ ]
45
+ with pytest.raises(ValueError, match="Inconsistent axis_size"):
46
+ compute_unsharder_plan(dim_specs, parallel_infos)
47
+
48
+ def test_missing_axis_in_all_parallel_infos_skipped(self) -> None:
49
+ """Axis in dims but absent from all parallel_infos -> axis_size=1, auto-skip.
50
+ But CP is active and undeclared → raises undeclared error."""
51
+ dim_specs = parse_dims("h[tp]").dims
52
+ parallel_infos = [{ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2)}]
53
+ with pytest.raises(ValueError, match="not declared"):
54
+ compute_unsharder_plan(dim_specs, parallel_infos)
55
+
56
+ def test_empty_parallel_infos_raises(self) -> None:
57
+ dim_specs = parse_dims("h[tp]").dims
58
+ with pytest.raises(ValueError, match="must not be empty"):
59
+ compute_unsharder_plan(dim_specs, [])
60
+
61
+ def test_scrambled_world_ranks(self) -> None:
62
+ """world_rank order != axis_rank order."""
63
+ dim_specs = parse_dims("h[tp]").dims
64
+ parallel_infos = [
65
+ {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)},
66
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)},
67
+ {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)},
68
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)},
69
+ ]
70
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
71
+ assert len(plans) == 1
72
+ assert plans[0].groups == [[1, 3, 0, 2]]
73
+
74
+ def test_no_sharded_axes_returns_empty(self) -> None:
75
+ dim_specs = parse_dims("b s d").dims
76
+ parallel_infos = [{}]
77
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
78
+ assert plans == []
79
+
80
+ def test_multi_axis_plan(self) -> None:
81
+ """Multi-axis (TP + CP) produces a 2-step plan."""
82
+ dim_specs = parse_dims("s[cp] h[tp]").dims
83
+ parallel_infos = [
84
+ {
85
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
86
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
87
+ },
88
+ {
89
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
90
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
91
+ },
92
+ {
93
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
94
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
95
+ },
96
+ {
97
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
98
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
99
+ },
100
+ ]
101
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
102
+
103
+ assert len(plans) == 2
104
+ assert plans[0].axis == ParallelAxis.CP
105
+ assert plans[1].axis == ParallelAxis.TP
106
+
107
+ def test_cp_tp_plan(self) -> None:
108
+ """CP=2 + TP=4 produces correct 2-step plan with correct groups."""
109
+ dim_specs = parse_dims("s[cp] h[tp]").dims
110
+ parallel_infos = []
111
+ for cp_rank in range(2):
112
+ for tp_rank in range(4):
113
+ parallel_infos.append(
114
+ {
115
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
116
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=4),
117
+ }
118
+ )
119
+
120
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
121
+
122
+ assert len(plans) == 2
123
+
124
+ cp_plan = plans[0]
125
+ assert cp_plan.axis == ParallelAxis.CP
126
+ assert len(cp_plan.groups) == 4
127
+ for group in cp_plan.groups:
128
+ assert len(group) == 2
129
+
130
+ tp_plan = plans[1]
131
+ assert tp_plan.axis == ParallelAxis.TP
132
+ assert len(tp_plan.groups) == 1
133
+ assert len(tp_plan.groups[0]) == 4
134
+
135
+ def test_cp_tp_scrambled_ranks(self) -> None:
136
+ """Scrambled rank assignment still produces correct plan."""
137
+ dim_specs = parse_dims("s[cp] h[tp]").dims
138
+ parallel_infos = [
139
+ {
140
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
141
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
142
+ },
143
+ {
144
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
145
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
146
+ },
147
+ {
148
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
149
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
150
+ },
151
+ {
152
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
153
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
154
+ },
155
+ ]
156
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
157
+
158
+ assert len(plans) == 2
159
+
160
+ cp_plan = plans[0]
161
+ assert cp_plan.axis == ParallelAxis.CP
162
+ assert len(cp_plan.groups) == 2
163
+ for group in cp_plan.groups:
164
+ assert len(group) == 2
165
+
166
+ tp_plan = plans[1]
167
+ assert tp_plan.axis == ParallelAxis.TP
168
+ assert len(tp_plan.groups) == 1
169
+ assert len(tp_plan.groups[0]) == 2
170
+
171
+ def test_axis_rank_coverage_incomplete_raises(self) -> None:
172
+ """TP size=4 but only ranks 0,1,3 provided (missing rank 2)."""
173
+ dim_specs = parse_dims("h[tp]").dims
174
+ parallel_infos = [
175
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)},
176
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)},
177
+ {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)},
178
+ ]
179
+ with pytest.raises(ValueError, match="axis_rank coverage.*incomplete"):
180
+ compute_unsharder_plan(dim_specs, parallel_infos)
181
+
182
+ def test_reduction_partial_returns_reduce_sum(self) -> None:
183
+ dim_specs = parse_dims("h[tp:partial]").dims
184
+ parallel_infos = [
185
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
186
+ ]
187
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
188
+
189
+ assert len(plans) == 1
190
+ assert plans[0].axis == ParallelAxis.TP
191
+ assert isinstance(plans[0].params, ReduceSumParams)
192
+ assert plans[0].groups == [[0, 1]]
193
+
194
+ def test_reduction_partial_tp4(self) -> None:
195
+ """TP=4 with partial reduction produces a single ReduceSumParams step."""
196
+ dim_specs = parse_dims("h[tp:partial]").dims
197
+ parallel_infos = [
198
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4)
199
+ ]
200
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
201
+
202
+ assert len(plans) == 1
203
+ assert isinstance(plans[0].params, ReduceSumParams)
204
+ assert plans[0].groups == [[0, 1, 2, 3]]
205
+
206
+ def test_multi_axis_with_reduction_on_one(self) -> None:
207
+ """CP concat + TP reduce produces a 2-step plan."""
208
+ dim_specs = parse_dims("s[cp] h[tp:partial]").dims
209
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
210
+ for cp_rank in range(2):
211
+ for tp_rank in range(2):
212
+ parallel_infos.append(
213
+ {
214
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
215
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
216
+ }
217
+ )
218
+
219
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
220
+
221
+ assert len(plans) == 2
222
+ assert plans[0].axis == ParallelAxis.CP
223
+ assert isinstance(plans[0].params, ConcatParams)
224
+ assert plans[1].axis == ParallelAxis.TP
225
+ assert isinstance(plans[1].params, ReduceSumParams)
226
+
227
+ def test_reduction_scrambled_ranks(self) -> None:
228
+ """Scrambled world_rank order with partial reduction."""
229
+ dim_specs = parse_dims("h[tp:partial]").dims
230
+ parallel_infos = [
231
+ {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)},
232
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)},
233
+ {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)},
234
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)},
235
+ ]
236
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
237
+
238
+ assert len(plans) == 1
239
+ assert isinstance(plans[0].params, ReduceSumParams)
240
+ assert plans[0].groups == [[1, 3, 0, 2]]
241
+
242
+ def test_ordering_zigzag_accepted(self) -> None:
243
+ dim_specs = parse_dims("s[cp:zigzag]").dims
244
+ parallel_infos = [
245
+ {ParallelAxis.CP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
246
+ ]
247
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
248
+ assert len(plans) == 1
249
+ assert plans[0].axis == ParallelAxis.CP
250
+
251
+ def test_ordering_natural_accepted(self) -> None:
252
+ dim_specs = parse_dims("s[cp:natural]").dims
253
+ parallel_infos = [
254
+ {ParallelAxis.CP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
255
+ ]
256
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
257
+ assert len(plans) == 1
258
+ assert plans[0].axis == ParallelAxis.CP
259
+
260
+ def test_three_axis_plan(self) -> None:
261
+ """EP=2 + CP=2 + TP=2 produces a 3-step plan."""
262
+ dim_specs = parse_dims("b e[ep] s[cp] h[tp]").dims
263
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
264
+ for ep_rank in range(2):
265
+ for cp_rank in range(2):
266
+ for tp_rank in range(2):
267
+ parallel_infos.append(
268
+ {
269
+ ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2),
270
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
271
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
272
+ }
273
+ )
274
+
275
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
276
+
277
+ assert len(plans) == 3
278
+ assert plans[0].axis == ParallelAxis.EP
279
+ assert plans[1].axis == ParallelAxis.CP
280
+ assert plans[2].axis == ParallelAxis.TP
281
+
282
+ # Step 0 (EP): 8 tensors → 4 (groups of 2)
283
+ assert len(plans[0].groups) == 4
284
+ for group in plans[0].groups:
285
+ assert len(group) == 2
286
+
287
+ # Step 1 (CP): 4 tensors → 2 (groups of 2)
288
+ assert len(plans[1].groups) == 2
289
+ for group in plans[1].groups:
290
+ assert len(group) == 2
291
+
292
+ # Step 2 (TP): 2 tensors → 1 (single group of 2)
293
+ assert len(plans[2].groups) == 1
294
+ assert len(plans[2].groups[0]) == 2
295
+
296
+ def test_same_dim_cp_sp_plan(self) -> None:
297
+ """t[cp:zigzag,sp] with CP=2 SP=2: SP unshards first (inner), then CP."""
298
+ dim_specs = parse_dims("t[cp:zigzag,sp] 1 h").dims
299
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
300
+ for cp_rank in range(2):
301
+ for sp_rank in range(2):
302
+ parallel_infos.append(
303
+ {
304
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
305
+ ParallelAxis.SP: AxisInfo(axis_rank=sp_rank, axis_size=2),
306
+ }
307
+ )
308
+
309
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
310
+
311
+ assert len(plans) == 2
312
+
313
+ # SP unshards first (rightmost modifier = innermost shard)
314
+ sp_plan = plans[0]
315
+ assert sp_plan.axis == ParallelAxis.SP
316
+ assert isinstance(sp_plan.params, ConcatParams)
317
+ assert sp_plan.params.dim_name == "t"
318
+ assert len(sp_plan.groups) == 2
319
+ for group in sp_plan.groups:
320
+ assert len(group) == 2
321
+
322
+ # CP unshards second (leftmost modifier = outermost shard)
323
+ cp_plan = plans[1]
324
+ assert cp_plan.axis == ParallelAxis.CP
325
+ assert isinstance(cp_plan.params, ConcatParams)
326
+ assert cp_plan.params.dim_name == "t"
327
+ assert len(cp_plan.groups) == 1
328
+ assert len(cp_plan.groups[0]) == 2
329
+
330
+ def test_same_dim_cp_sp_with_thd(self) -> None:
331
+ """t[cp:zigzag,sp] with THD: SP → ConcatParams, CP → CpThdConcatParams."""
332
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import (
333
+ CpThdConcatParams,
334
+ )
335
+
336
+ dim_specs = parse_dims("t[cp:zigzag,sp] h").dims
337
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
338
+ for cp_rank in range(2):
339
+ for sp_rank in range(2):
340
+ parallel_infos.append(
341
+ {
342
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
343
+ ParallelAxis.SP: AxisInfo(axis_rank=sp_rank, axis_size=2),
344
+ }
345
+ )
346
+
347
+ thd_global_seq_lens: list[int] = [100, 64]
348
+ plans = compute_unsharder_plan(
349
+ dim_specs, parallel_infos, thd_global_seq_lens=thd_global_seq_lens
350
+ )
351
+
352
+ assert len(plans) == 2
353
+
354
+ # SP unshards first: plain concat (SP is not CP, no THD special handling)
355
+ sp_plan = plans[0]
356
+ assert sp_plan.axis == ParallelAxis.SP
357
+ assert isinstance(sp_plan.params, ConcatParams)
358
+ assert sp_plan.params.dim_name == "t"
359
+
360
+ # CP unshards second: THD concat because dim is 't' + axis is CP + thd_global_seq_lens provided
361
+ cp_plan = plans[1]
362
+ assert cp_plan.axis == ParallelAxis.CP
363
+ assert isinstance(cp_plan.params, CpThdConcatParams)
364
+ assert cp_plan.params.dim_name == "t"
365
+ assert cp_plan.params.seq_lens_per_rank == [50, 32]
366
+
367
+ def test_sp_in_dims_but_not_in_parallel_info(self) -> None:
368
+ """s[sp] in dims but SP absent from parallel_info (SP disabled), should auto-skip."""
369
+ dim_specs = parse_dims("s[sp] b h[tp]").dims
370
+ parallel_infos = [
371
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)},
372
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)},
373
+ ]
374
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
375
+ assert len(plans) == 1
376
+ assert plans[0].axis == ParallelAxis.TP
377
+
378
+ def test_all_dims_sharded_but_single_gpu(self) -> None:
379
+ """Single GPU (TP=1, CP=1), dims has s[cp] h[tp] but parallel_info is empty."""
380
+ dim_specs = parse_dims("b s[cp] h[tp] d").dims
381
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [{}]
382
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
383
+ assert plans == []
384
+
385
+ def test_sharded_axis_missing_from_rank_raises(self) -> None:
386
+ """A world_rank missing a sharded axis raises ValueError."""
387
+ dim_specs = parse_dims("s[cp] h[tp]").dims
388
+ parallel_infos = [
389
+ {
390
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
391
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
392
+ },
393
+ {
394
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
395
+ # missing TP — sharded axis absent from rank
396
+ },
397
+ ]
398
+ with pytest.raises(ValueError, match="missing parallel_info"):
399
+ compute_unsharder_plan(dim_specs, parallel_infos)
400
+
401
+ def test_tp_sharded_etp_dependent_auto_resolved(self) -> None:
402
+ """dims=h[tp], active={TP, ETP, EP}, EP replicated, etp depends on tp → plan succeeds."""
403
+ dim_specs = parse_dims("b h[tp] d # ep:replicated").dims
404
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
405
+ for tp_rank in range(2):
406
+ for ep_rank in range(2):
407
+ parallel_infos.append(
408
+ {
409
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
410
+ ParallelAxis.ETP: AxisInfo(axis_rank=tp_rank, axis_size=2),
411
+ ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2),
412
+ }
413
+ )
414
+
415
+ plans = compute_unsharder_plan(
416
+ dim_specs,
417
+ parallel_infos,
418
+ explicit_replicated_axes=frozenset({ParallelAxis.EP}),
419
+ )
420
+
421
+ axes_in_plan = [p.axis for p in plans]
422
+ assert ParallelAxis.TP in axes_in_plan
423
+ assert ParallelAxis.EP in axes_in_plan
424
+ assert ParallelAxis.ETP not in axes_in_plan
425
+
426
+ def test_edp_jointly_determined_by_tp_and_cp(self) -> None:
427
+ """dims=t[cp:zigzag,sp] h # tp:replicated, EDP determined by (TP,CP) jointly → plan succeeds.
428
+
429
+ Simulates tp=2, cp=2, ep=1, etp=1 on 4 GPUs.
430
+ """
431
+ dim_specs = parse_dims("t[cp:zigzag,sp] h # tp:replicated").dims
432
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
433
+ {
434
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
435
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
436
+ ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2),
437
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4),
438
+ },
439
+ {
440
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
441
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
442
+ ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2),
443
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4),
444
+ },
445
+ {
446
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
447
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
448
+ ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2),
449
+ ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=4),
450
+ },
451
+ {
452
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
453
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
454
+ ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2),
455
+ ParallelAxis.EDP: AxisInfo(axis_rank=3, axis_size=4),
456
+ },
457
+ ]
458
+ plans = compute_unsharder_plan(
459
+ dim_specs,
460
+ parallel_infos,
461
+ explicit_replicated_axes=frozenset({ParallelAxis.TP}),
462
+ )
463
+ axes_in_plan = [p.axis for p in plans]
464
+ assert ParallelAxis.CP in axes_in_plan
465
+ assert ParallelAxis.TP in axes_in_plan
466
+ assert ParallelAxis.EDP not in axes_in_plan
467
+
468
+
469
+ class TestExplicitReplicatedAxes:
470
+ def test_replicated_tp_with_sharded_cp(self) -> None:
471
+ """CP2 TP2, dims='b s[cp] d # tp:replicated' → PickPlan(TP) + ConcatPlan(CP)."""
472
+ dim_specs = parse_dims("b s[cp] d # tp:replicated").dims
473
+ replicated = frozenset({ParallelAxis.TP})
474
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
475
+ {
476
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
477
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
478
+ },
479
+ {
480
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
481
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
482
+ },
483
+ {
484
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
485
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
486
+ },
487
+ {
488
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
489
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
490
+ },
491
+ ]
492
+ plans = compute_unsharder_plan(
493
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
494
+ )
495
+
496
+ assert len(plans) == 2
497
+ assert plans[0].axis == ParallelAxis.TP
498
+ assert isinstance(plans[0].params, PickParams)
499
+ assert len(plans[0].groups) == 2
500
+ for group in plans[0].groups:
501
+ assert len(group) == 2
502
+
503
+ assert plans[1].axis == ParallelAxis.CP
504
+ assert isinstance(plans[1].params, ConcatParams)
505
+ assert plans[1].params.dim_name == "s"
506
+
507
+ def test_fully_replicated(self) -> None:
508
+ """CP2 TP2, dims='b h d # cp:replicated tp:replicated' → PickPlan(CP) + PickPlan(TP)."""
509
+ dim_specs = parse_dims("b h d # cp:replicated tp:replicated").dims
510
+ replicated = frozenset({ParallelAxis.CP, ParallelAxis.TP})
511
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
512
+ {
513
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
514
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
515
+ },
516
+ {
517
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
518
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
519
+ },
520
+ {
521
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
522
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
523
+ },
524
+ {
525
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
526
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
527
+ },
528
+ ]
529
+ plans = compute_unsharder_plan(
530
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
531
+ )
532
+
533
+ assert len(plans) == 2
534
+ assert all(isinstance(p.params, PickParams) for p in plans)
535
+ axes = {p.axis for p in plans}
536
+ assert axes == {ParallelAxis.CP, ParallelAxis.TP}
537
+
538
+ def test_multiple_replicated_one_sharded(self) -> None:
539
+ """CP2 TP2 EP2, dims='h[tp] # cp:replicated ep:replicated'."""
540
+ dim_specs = parse_dims("h[tp] # cp:replicated ep:replicated").dims
541
+ replicated = frozenset({ParallelAxis.CP, ParallelAxis.EP})
542
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
543
+ for cp_rank in range(2):
544
+ for ep_rank in range(2):
545
+ for tp_rank in range(2):
546
+ parallel_infos.append(
547
+ {
548
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
549
+ ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2),
550
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
551
+ }
552
+ )
553
+
554
+ plans = compute_unsharder_plan(
555
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
556
+ )
557
+
558
+ assert len(plans) == 3
559
+ pick_plans = [p for p in plans if isinstance(p.params, PickParams)]
560
+ concat_plans = [p for p in plans if isinstance(p.params, ConcatParams)]
561
+ assert len(pick_plans) == 2
562
+ assert len(concat_plans) == 1
563
+ assert concat_plans[0].axis == ParallelAxis.TP
564
+
565
+ replicated_axes_in_plan = {p.axis for p in pick_plans}
566
+ assert replicated_axes_in_plan == {ParallelAxis.CP, ParallelAxis.EP}
567
+
568
+ def test_replicated_scrambled_ranks(self) -> None:
569
+ """Scrambled world_rank order with explicit replicated axis."""
570
+ dim_specs = parse_dims("h[tp] # cp:replicated").dims
571
+ replicated = frozenset({ParallelAxis.CP})
572
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
573
+ {
574
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
575
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
576
+ },
577
+ {
578
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
579
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
580
+ },
581
+ {
582
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
583
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
584
+ },
585
+ {
586
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
587
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
588
+ },
589
+ ]
590
+ plans = compute_unsharder_plan(
591
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
592
+ )
593
+
594
+ assert len(plans) == 2
595
+ assert plans[0].axis == ParallelAxis.CP
596
+ assert isinstance(plans[0].params, PickParams)
597
+ assert plans[1].axis == ParallelAxis.TP
598
+ assert isinstance(plans[1].params, ConcatParams)
599
+
600
+ def test_replicated_axis_inconsistent_size_raises(self) -> None:
601
+ """Replicated axis with inconsistent sizes raises ValueError."""
602
+ dim_specs = parse_dims("h[tp] # cp:replicated").dims
603
+ replicated = frozenset({ParallelAxis.CP})
604
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
605
+ {
606
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
607
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
608
+ },
609
+ {
610
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=4),
611
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
612
+ },
613
+ ]
614
+ with pytest.raises(ValueError, match="Inconsistent axis_size"):
615
+ compute_unsharder_plan(
616
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
617
+ )
618
+
619
+ def test_replicated_axis_missing_from_rank_raises(self) -> None:
620
+ """A rank missing a replicated axis that other ranks have raises ValueError."""
621
+ dim_specs = parse_dims("h[tp] # cp:replicated").dims
622
+ replicated = frozenset({ParallelAxis.CP})
623
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
624
+ {
625
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
626
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
627
+ },
628
+ {
629
+ # missing CP — replicated axis absent from this rank
630
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
631
+ },
632
+ ]
633
+ with pytest.raises(ValueError, match="missing parallel_info"):
634
+ compute_unsharder_plan(
635
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
636
+ )
637
+
638
+ def test_recompute_pseudo_auto_replicated(self) -> None:
639
+ """RECOMPUTE_PSEUDO is auto-replicated without explicit declaration."""
640
+ dim_specs = parse_dims("h d").dims
641
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
642
+ {ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=0, axis_size=2)},
643
+ {ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=1, axis_size=2)},
644
+ ]
645
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
646
+
647
+ assert len(plans) == 1
648
+ assert plans[0].axis == ParallelAxis.RECOMPUTE_PSEUDO
649
+ assert isinstance(plans[0].params, PickParams)
650
+ assert plans[0].groups == [[0, 1]]
651
+
652
+ def test_recompute_pseudo_explicit_replicated_also_works(self) -> None:
653
+ """RECOMPUTE_PSEUDO with explicit # recompute_pseudo:replicated also works."""
654
+ dim_specs = parse_dims("h d # recompute_pseudo:replicated").dims
655
+ replicated = frozenset({ParallelAxis.RECOMPUTE_PSEUDO})
656
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
657
+ {ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=0, axis_size=2)},
658
+ {ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=1, axis_size=2)},
659
+ ]
660
+ plans = compute_unsharder_plan(
661
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
662
+ )
663
+
664
+ assert len(plans) == 1
665
+ assert plans[0].axis == ParallelAxis.RECOMPUTE_PSEUDO
666
+ assert isinstance(plans[0].params, PickParams)
667
+ assert plans[0].groups == [[0, 1]]
668
+
669
+ def test_undeclared_active_axis_raises(self) -> None:
670
+ """Active axis not declared as sharded or replicated raises ValueError."""
671
+ dim_specs = parse_dims("b s[cp] d").dims
672
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
673
+ {
674
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
675
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
676
+ },
677
+ {
678
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
679
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
680
+ },
681
+ {
682
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
683
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
684
+ },
685
+ {
686
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
687
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
688
+ },
689
+ ]
690
+ with pytest.raises(ValueError, match="tp.*not declared"):
691
+ compute_unsharder_plan(dim_specs, parallel_infos)
692
+
693
+ def test_replicated_not_in_parallel_infos_raises(self) -> None:
694
+ """Declaring replicated axis not in parallel_infos raises ValueError."""
695
+ dim_specs = parse_dims("h[tp] # ep:replicated").dims
696
+ replicated = frozenset({ParallelAxis.EP})
697
+ parallel_infos = [
698
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
699
+ ]
700
+ with pytest.raises(ValueError, match="not found in parallel_infos"):
701
+ compute_unsharder_plan(
702
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
703
+ )
704
+
705
+ def test_explicit_replicated_conflicts_with_sharded_raises(self) -> None:
706
+ """Planner-level defense: replicated overlaps sharded → ValueError."""
707
+ dim_specs = parse_dims("h[tp]").dims
708
+ replicated = frozenset({ParallelAxis.TP})
709
+ parallel_infos = [
710
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
711
+ ]
712
+ with pytest.raises(ValueError, match="both sharded and replicated"):
713
+ compute_unsharder_plan(
714
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
715
+ )
716
+
717
+
718
+ class TestComputeUnsharderPlanFusedDims:
719
+ def test_fused_dim_tp2(self) -> None:
720
+ """Fused dim "(num_heads*head_dim)[tp]" should unshard on the fused tensor name."""
721
+ dim_specs = parse_dims("t (num_heads*head_dim)[tp]").dims
722
+ parallel_infos = [
723
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
724
+ ]
725
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
726
+
727
+ assert len(plans) == 1
728
+ assert plans[0].axis == ParallelAxis.TP
729
+ assert isinstance(plans[0].params, ConcatParams)
730
+ assert plans[0].params.dim_name == "num_heads___head_dim"
731
+ assert plans[0].groups == [[0, 1]]
732
+
733
+ def test_fused_dim_modifier_on_second_sub(self) -> None:
734
+ """Modifier on fused dim: "(a*b)[tp]" should produce concat plan."""
735
+ dim_specs = parse_dims("t (a*b)[tp]").dims
736
+ parallel_infos = [
737
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
738
+ ]
739
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
740
+
741
+ assert len(plans) == 1
742
+ assert plans[0].axis == ParallelAxis.TP
743
+ assert isinstance(plans[0].params, ConcatParams)
744
+ assert plans[0].params.dim_name == "a___b"
745
+
746
+ def test_fused_dim_no_modifier(self) -> None:
747
+ """Fused dim without modifier + explicit replicated TP → PickParams."""
748
+ dim_specs = parse_dims("t (a*b) # tp:replicated").dims
749
+ replicated = frozenset({ParallelAxis.TP})
750
+ parallel_infos = [
751
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
752
+ ]
753
+ plans = compute_unsharder_plan(
754
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
755
+ )
756
+
757
+ assert len(plans) == 1
758
+ assert isinstance(plans[0].params, PickParams)
759
+
760
+ def test_fused_dim_with_reduction(self) -> None:
761
+ """Fused dim with partial reduction: "(a*b)[tp:partial]"."""
762
+ dim_specs = parse_dims("t (a*b)[tp:partial]").dims
763
+ parallel_infos = [
764
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
765
+ ]
766
+ plans = compute_unsharder_plan(dim_specs, parallel_infos)
767
+
768
+ assert len(plans) == 1
769
+ assert plans[0].axis == ParallelAxis.TP
770
+ assert isinstance(plans[0].params, ReduceSumParams)
771
+
772
+
773
+ class TestAxisContainment:
774
+ def test_tp_replicated_auto_resolves_dependent_axes(self) -> None:
775
+ """tp:replicated + attn_tp/moe_tp active but undeclared → no error, correct pick."""
776
+ dim_specs = parse_dims("t h # tp:replicated").dims
777
+ replicated = frozenset({ParallelAxis.TP})
778
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
779
+ {
780
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4),
781
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
782
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
783
+ },
784
+ {
785
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4),
786
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
787
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
788
+ },
789
+ {
790
+ ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4),
791
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
792
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
793
+ },
794
+ {
795
+ ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4),
796
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
797
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
798
+ },
799
+ ]
800
+ plans = compute_unsharder_plan(
801
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
802
+ )
803
+
804
+ assert len(plans) == 1
805
+ assert plans[0].axis == ParallelAxis.TP
806
+ assert isinstance(plans[0].params, PickParams)
807
+ assert plans[0].groups == [[0, 1, 2, 3]]
808
+
809
+ def test_independent_axis_still_requires_declaration(self) -> None:
810
+ """cp independent of tp → cp undeclared still raises."""
811
+ dim_specs = parse_dims("t h # tp:replicated").dims
812
+ replicated = frozenset({ParallelAxis.TP})
813
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
814
+ {
815
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
816
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
817
+ },
818
+ {
819
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
820
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
821
+ },
822
+ {
823
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
824
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
825
+ },
826
+ {
827
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
828
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
829
+ },
830
+ ]
831
+ with pytest.raises(ValueError, match="cp.*not declared"):
832
+ compute_unsharder_plan(
833
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
834
+ )
835
+
836
+ def test_backward_compat_explicit_children(self) -> None:
837
+ """Both tp:replicated and attn_tp:replicated → ValueError (not orthogonal)."""
838
+ dim_specs = parse_dims(
839
+ "t h # tp:replicated attn_tp:replicated moe_tp:replicated"
840
+ ).dims
841
+ replicated = frozenset(
842
+ {ParallelAxis.TP, ParallelAxis.ATTN_TP, ParallelAxis.MOE_TP}
843
+ )
844
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
845
+ {
846
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4),
847
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
848
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
849
+ },
850
+ {
851
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4),
852
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
853
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
854
+ },
855
+ {
856
+ ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4),
857
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
858
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
859
+ },
860
+ {
861
+ ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4),
862
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
863
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
864
+ },
865
+ ]
866
+ with pytest.raises(ValueError, match="not orthogonal"):
867
+ compute_unsharder_plan(
868
+ dim_specs, parallel_infos, explicit_replicated_axes=replicated
869
+ )
870
+
871
+
872
+ class TestDpFilteredAxis:
873
+ """Tests for dp_filtered_axis parameter: DP axis handled by upstream DP filter
874
+ should be excluded from unsharder validation."""
875
+
876
+ def test_dp_filtered_skips_undeclared_error(self) -> None:
877
+ """DP active but dp_filtered_axis=DP → no error, no DP plan produced."""
878
+ dim_specs = parse_dims("b h d").dims
879
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
880
+ {ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2)},
881
+ ]
882
+ plans = compute_unsharder_plan(
883
+ dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP
884
+ )
885
+ assert plans == []
886
+
887
+ def test_dp_filtered_with_sharded_tp(self) -> None:
888
+ """DP2 + TP2, dims='t h[tp]', dp_filtered_axis=DP → only TP concat plan."""
889
+ dim_specs = parse_dims("t h[tp]").dims
890
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
891
+ {
892
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
893
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
894
+ },
895
+ {
896
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
897
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
898
+ },
899
+ ]
900
+ plans = compute_unsharder_plan(
901
+ dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP
902
+ )
903
+
904
+ assert len(plans) == 1
905
+ assert plans[0].axis == ParallelAxis.TP
906
+ assert isinstance(plans[0].params, ConcatParams)
907
+
908
+ def test_dp_filtered_with_replicated_tp(self) -> None:
909
+ """DP2 + TP2, dims='b h # tp:replicated', dp_filtered_axis=DP → only TP pick plan."""
910
+ dim_specs = parse_dims("b h # tp:replicated").dims
911
+ replicated = frozenset({ParallelAxis.TP})
912
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
913
+ {
914
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
915
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
916
+ },
917
+ {
918
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
919
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
920
+ },
921
+ ]
922
+ plans = compute_unsharder_plan(
923
+ dim_specs,
924
+ parallel_infos,
925
+ explicit_replicated_axes=replicated,
926
+ dp_filtered_axis=ParallelAxis.DP,
927
+ )
928
+
929
+ assert len(plans) == 1
930
+ assert plans[0].axis == ParallelAxis.TP
931
+ assert isinstance(plans[0].params, PickParams)
932
+
933
+ def test_dp_filtered_does_not_affect_other_undeclared(self) -> None:
934
+ """DP filtered + EP active but undeclared (independent of TP) → still raises for EP."""
935
+ dim_specs = parse_dims("t h[tp]").dims
936
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
937
+ {
938
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
939
+ ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2),
940
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
941
+ }
942
+ for tp_rank in range(2)
943
+ for ep_rank in range(2)
944
+ ]
945
+ with pytest.raises(ValueError, match="ep.*not declared"):
946
+ compute_unsharder_plan(
947
+ dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP
948
+ )
949
+
950
+ def test_dp_filtered_none_still_raises_for_undeclared_dp(self) -> None:
951
+ """Default dp_filtered_axis=None, DP active but undeclared (independent of TP) → raises."""
952
+ dim_specs = parse_dims("t h[tp]").dims
953
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
954
+ {
955
+ ParallelAxis.DP: AxisInfo(axis_rank=dp_rank, axis_size=2),
956
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
957
+ }
958
+ for tp_rank in range(2)
959
+ for dp_rank in range(2)
960
+ ]
961
+ with pytest.raises(ValueError, match="dp.*not declared"):
962
+ compute_unsharder_plan(dim_specs, parallel_infos)
963
+
964
+ def test_dp_filtered_custom_alias(self) -> None:
965
+ """dp_filtered_axis=MOE_DP (custom alias) skips undeclared error for moe_dp."""
966
+ dim_specs = parse_dims("t h[tp]").dims
967
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
968
+ {
969
+ ParallelAxis.MOE_DP: AxisInfo(axis_rank=0, axis_size=2),
970
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
971
+ },
972
+ {
973
+ ParallelAxis.MOE_DP: AxisInfo(axis_rank=0, axis_size=2),
974
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
975
+ },
976
+ ]
977
+ plans = compute_unsharder_plan(
978
+ dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.MOE_DP
979
+ )
980
+
981
+ assert len(plans) == 1
982
+ assert plans[0].axis == ParallelAxis.TP
983
+
984
+ def test_dp_filtered_not_in_parallel_infos_is_harmless(self) -> None:
985
+ """dp_filtered_axis=DP but DP not in parallel_infos → no error, no effect."""
986
+ dim_specs = parse_dims("t h[tp]").dims
987
+ parallel_infos = [
988
+ {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2)
989
+ ]
990
+ plans = compute_unsharder_plan(
991
+ dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP
992
+ )
993
+
994
+ assert len(plans) == 1
995
+ assert plans[0].axis == ParallelAxis.TP
996
+
997
+ def test_dp_filtered_with_multi_axis_sharding(self) -> None:
998
+ """DP2 + TP2 + CP2, dims='s[cp] h[tp]', dp_filtered_axis=DP → CP+TP plans only."""
999
+ dim_specs = parse_dims("s[cp] h[tp]").dims
1000
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
1001
+ for cp_rank in range(2):
1002
+ for tp_rank in range(2):
1003
+ parallel_infos.append(
1004
+ {
1005
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1006
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
1007
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
1008
+ }
1009
+ )
1010
+ plans = compute_unsharder_plan(
1011
+ dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP
1012
+ )
1013
+
1014
+ assert len(plans) == 2
1015
+ assert plans[0].axis == ParallelAxis.CP
1016
+ assert plans[1].axis == ParallelAxis.TP
1017
+
1018
+
1019
+ class TestIsDependentAxis:
1020
+ def test_child_determined_by_parent(self) -> None:
1021
+ """attn_tp uniquely determined by tp → dependent."""
1022
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1023
+ {
1024
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4),
1025
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
1026
+ },
1027
+ {
1028
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4),
1029
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
1030
+ },
1031
+ {
1032
+ ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4),
1033
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
1034
+ },
1035
+ {
1036
+ ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4),
1037
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
1038
+ },
1039
+ ]
1040
+ assert _is_dependent_axis(
1041
+ parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.ATTN_TP
1042
+ )
1043
+
1044
+ def test_child_not_determined_by_parent(self) -> None:
1045
+ """dp varies independently of tp → not dependent."""
1046
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1047
+ {
1048
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1049
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1050
+ },
1051
+ {
1052
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1053
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1054
+ },
1055
+ {
1056
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1057
+ ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2),
1058
+ },
1059
+ {
1060
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1061
+ ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2),
1062
+ },
1063
+ ]
1064
+ assert not _is_dependent_axis(
1065
+ parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.DP
1066
+ )
1067
+
1068
+ def test_parent_absent_from_all_infos(self) -> None:
1069
+ """Parent axis not in any info → vacuously True."""
1070
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1071
+ {ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2)},
1072
+ {ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2)},
1073
+ ]
1074
+ assert _is_dependent_axis(
1075
+ parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.DP
1076
+ )
1077
+
1078
+ def test_child_absent_from_all_infos(self) -> None:
1079
+ """Child axis not in any info → vacuously True."""
1080
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1081
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)},
1082
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)},
1083
+ ]
1084
+ assert _is_dependent_axis(
1085
+ parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.DP
1086
+ )
1087
+
1088
+ def test_single_info_always_dependent(self) -> None:
1089
+ """With one info entry, any pair is trivially dependent."""
1090
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1091
+ {
1092
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1093
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1094
+ },
1095
+ ]
1096
+ assert _is_dependent_axis(
1097
+ parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.DP
1098
+ )
1099
+
1100
+ def test_child_missing_from_some_infos_but_consistent(self) -> None:
1101
+ """Child absent from some infos but consistent where present → dependent."""
1102
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1103
+ {
1104
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1105
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
1106
+ },
1107
+ {
1108
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1109
+ # ATTN_TP absent here
1110
+ },
1111
+ {
1112
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1113
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
1114
+ },
1115
+ ]
1116
+ assert _is_dependent_axis(
1117
+ parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.ATTN_TP
1118
+ )
1119
+
1120
+ def test_empty_parallel_infos(self) -> None:
1121
+ """No infos → vacuously True."""
1122
+ assert _is_dependent_axis(
1123
+ [], parent=ParallelAxis.TP, child=ParallelAxis.ATTN_TP
1124
+ )
1125
+
1126
+ def test_same_parent_rank_different_child_ranks(self) -> None:
1127
+ """Explicit conflict: parent_rank=0 maps to child_rank=0 and child_rank=1."""
1128
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1129
+ {
1130
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1131
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
1132
+ },
1133
+ {
1134
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1135
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
1136
+ },
1137
+ ]
1138
+ assert not _is_dependent_axis(
1139
+ parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.ATTN_TP
1140
+ )
1141
+
1142
+
1143
+ class TestComputeDependentAxes:
1144
+ def test_dependent_child_found(self) -> None:
1145
+ """parent={TP}, candidate={ETP}, etp depends on tp → returns {ETP}."""
1146
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1147
+ {
1148
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1149
+ ParallelAxis.ETP: AxisInfo(axis_rank=0, axis_size=2),
1150
+ },
1151
+ {
1152
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1153
+ ParallelAxis.ETP: AxisInfo(axis_rank=1, axis_size=2),
1154
+ },
1155
+ ]
1156
+ result = _compute_dependent_axes(
1157
+ parent_axes={ParallelAxis.TP},
1158
+ candidate_axes={ParallelAxis.ETP},
1159
+ parallel_infos=parallel_infos,
1160
+ )
1161
+ assert result == frozenset({ParallelAxis.ETP})
1162
+
1163
+ def test_independent_child_not_found(self) -> None:
1164
+ """parent={TP}, candidate={CP}, cp independent → returns empty."""
1165
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1166
+ {
1167
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1168
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1169
+ },
1170
+ {
1171
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1172
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1173
+ },
1174
+ {
1175
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1176
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1177
+ },
1178
+ {
1179
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1180
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1181
+ },
1182
+ ]
1183
+ result = _compute_dependent_axes(
1184
+ parent_axes={ParallelAxis.TP},
1185
+ candidate_axes={ParallelAxis.CP},
1186
+ parallel_infos=parallel_infos,
1187
+ )
1188
+ assert result == frozenset()
1189
+
1190
+ def test_multiple_parents(self) -> None:
1191
+ """parent={TP, EP}, candidate={ETP, MOE_EP}, both dependent → returns both."""
1192
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1193
+ {
1194
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1195
+ ParallelAxis.EP: AxisInfo(axis_rank=0, axis_size=2),
1196
+ ParallelAxis.ETP: AxisInfo(axis_rank=0, axis_size=2),
1197
+ ParallelAxis.MOE_EP: AxisInfo(axis_rank=0, axis_size=2),
1198
+ },
1199
+ {
1200
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1201
+ ParallelAxis.EP: AxisInfo(axis_rank=0, axis_size=2),
1202
+ ParallelAxis.ETP: AxisInfo(axis_rank=1, axis_size=2),
1203
+ ParallelAxis.MOE_EP: AxisInfo(axis_rank=0, axis_size=2),
1204
+ },
1205
+ {
1206
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1207
+ ParallelAxis.EP: AxisInfo(axis_rank=1, axis_size=2),
1208
+ ParallelAxis.ETP: AxisInfo(axis_rank=0, axis_size=2),
1209
+ ParallelAxis.MOE_EP: AxisInfo(axis_rank=1, axis_size=2),
1210
+ },
1211
+ {
1212
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1213
+ ParallelAxis.EP: AxisInfo(axis_rank=1, axis_size=2),
1214
+ ParallelAxis.ETP: AxisInfo(axis_rank=1, axis_size=2),
1215
+ ParallelAxis.MOE_EP: AxisInfo(axis_rank=1, axis_size=2),
1216
+ },
1217
+ ]
1218
+ result = _compute_dependent_axes(
1219
+ parent_axes={ParallelAxis.TP, ParallelAxis.EP},
1220
+ candidate_axes={ParallelAxis.ETP, ParallelAxis.MOE_EP},
1221
+ parallel_infos=parallel_infos,
1222
+ )
1223
+ assert result == frozenset({ParallelAxis.ETP, ParallelAxis.MOE_EP})
1224
+
1225
+
1226
+ class TestValidateExplicitReplicated:
1227
+ def test_valid_all_axes_declared(self) -> None:
1228
+ """All axes declared as sharded or replicated → no error."""
1229
+ _validate_explicit_replicated(
1230
+ explicit_replicated_axes=frozenset({ParallelAxis.CP}),
1231
+ sharded_axes={ParallelAxis.TP},
1232
+ all_axes={ParallelAxis.TP, ParallelAxis.CP},
1233
+ parallel_infos=[
1234
+ {
1235
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1236
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1237
+ },
1238
+ ],
1239
+ )
1240
+
1241
+ def test_replicated_not_in_all_axes_raises(self) -> None:
1242
+ """Declaring replicated axis absent from all_axes → ValueError."""
1243
+ with pytest.raises(ValueError, match="not found in parallel_infos"):
1244
+ _validate_explicit_replicated(
1245
+ explicit_replicated_axes=frozenset({ParallelAxis.EP}),
1246
+ sharded_axes={ParallelAxis.TP},
1247
+ all_axes={ParallelAxis.TP},
1248
+ parallel_infos=[
1249
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)},
1250
+ ],
1251
+ )
1252
+
1253
+ def test_replicated_conflicts_with_sharded_raises(self) -> None:
1254
+ """Same axis declared sharded and replicated → ValueError."""
1255
+ with pytest.raises(ValueError, match="both sharded and replicated"):
1256
+ _validate_explicit_replicated(
1257
+ explicit_replicated_axes=frozenset({ParallelAxis.TP}),
1258
+ sharded_axes={ParallelAxis.TP},
1259
+ all_axes={ParallelAxis.TP},
1260
+ parallel_infos=[
1261
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)},
1262
+ ],
1263
+ )
1264
+
1265
+ def test_undeclared_active_axis_raises(self) -> None:
1266
+ """Active axis not sharded/replicated/implicitly_replicated → ValueError."""
1267
+ with pytest.raises(ValueError, match="dp.*not declared"):
1268
+ _validate_explicit_replicated(
1269
+ explicit_replicated_axes=frozenset({ParallelAxis.TP}),
1270
+ sharded_axes=set(),
1271
+ all_axes={ParallelAxis.TP, ParallelAxis.DP},
1272
+ parallel_infos=[
1273
+ {
1274
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1275
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1276
+ },
1277
+ {
1278
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1279
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1280
+ },
1281
+ {
1282
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1283
+ ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2),
1284
+ },
1285
+ {
1286
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1287
+ ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2),
1288
+ },
1289
+ ],
1290
+ )
1291
+
1292
+ def test_dependent_child_implicitly_replicated(self) -> None:
1293
+ """Child axis dependent on replicated parent → no error (implicitly replicated)."""
1294
+ _validate_explicit_replicated(
1295
+ explicit_replicated_axes=frozenset({ParallelAxis.TP}),
1296
+ sharded_axes=set(),
1297
+ all_axes={ParallelAxis.TP, ParallelAxis.ATTN_TP, ParallelAxis.MOE_TP},
1298
+ parallel_infos=[
1299
+ {
1300
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4),
1301
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
1302
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
1303
+ },
1304
+ {
1305
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4),
1306
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
1307
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
1308
+ },
1309
+ {
1310
+ ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4),
1311
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
1312
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
1313
+ },
1314
+ {
1315
+ ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4),
1316
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
1317
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
1318
+ },
1319
+ ],
1320
+ )
1321
+
1322
+ def test_dp_filtered_axis_excluded_from_undeclared(self) -> None:
1323
+ """dp_filtered_axis is exempt from undeclared check."""
1324
+ _validate_explicit_replicated(
1325
+ explicit_replicated_axes=frozenset(),
1326
+ sharded_axes={ParallelAxis.TP},
1327
+ all_axes={ParallelAxis.TP, ParallelAxis.DP},
1328
+ parallel_infos=[
1329
+ {
1330
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1331
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1332
+ },
1333
+ ],
1334
+ dp_filtered_axis=ParallelAxis.DP,
1335
+ )
1336
+
1337
+ def test_dp_filtered_does_not_exempt_other_axes(self) -> None:
1338
+ """dp_filtered_axis=DP, but EP still undeclared (independent of TP) → raises."""
1339
+ with pytest.raises(ValueError, match="ep.*not declared"):
1340
+ _validate_explicit_replicated(
1341
+ explicit_replicated_axes=frozenset(),
1342
+ sharded_axes={ParallelAxis.TP},
1343
+ all_axes={ParallelAxis.TP, ParallelAxis.DP, ParallelAxis.EP},
1344
+ parallel_infos=[
1345
+ {
1346
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
1347
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1348
+ ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2),
1349
+ }
1350
+ for tp_rank in range(2)
1351
+ for ep_rank in range(2)
1352
+ ],
1353
+ dp_filtered_axis=ParallelAxis.DP,
1354
+ )
1355
+
1356
+ def test_independent_child_not_implicitly_replicated(self) -> None:
1357
+ """Child axis independent of replicated parent → still raises."""
1358
+ with pytest.raises(ValueError, match="dp.*not declared"):
1359
+ _validate_explicit_replicated(
1360
+ explicit_replicated_axes=frozenset({ParallelAxis.TP}),
1361
+ sharded_axes=set(),
1362
+ all_axes={ParallelAxis.TP, ParallelAxis.DP},
1363
+ parallel_infos=[
1364
+ {
1365
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1366
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1367
+ },
1368
+ {
1369
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1370
+ ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2),
1371
+ },
1372
+ {
1373
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1374
+ ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2),
1375
+ },
1376
+ {
1377
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1378
+ ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2),
1379
+ },
1380
+ ],
1381
+ )
1382
+
1383
+ def test_sharded_axis_determines_undeclared_implicitly_sharded(self) -> None:
1384
+ """TP sharded, ETP dependent on TP → no error (implicitly sharded)."""
1385
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
1386
+ for tp_rank in range(2):
1387
+ for ep_rank in range(2):
1388
+ parallel_infos.append(
1389
+ {
1390
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
1391
+ ParallelAxis.ETP: AxisInfo(axis_rank=tp_rank, axis_size=2),
1392
+ ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2),
1393
+ }
1394
+ )
1395
+ _validate_explicit_replicated(
1396
+ explicit_replicated_axes=frozenset({ParallelAxis.EP}),
1397
+ sharded_axes={ParallelAxis.TP},
1398
+ all_axes={ParallelAxis.TP, ParallelAxis.ETP, ParallelAxis.EP},
1399
+ parallel_infos=parallel_infos,
1400
+ )
1401
+
1402
+ def test_sharded_axis_does_not_resolve_independent_child(self) -> None:
1403
+ """TP sharded, CP active but independent of TP → still raises."""
1404
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1405
+ {
1406
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1407
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1408
+ },
1409
+ {
1410
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1411
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1412
+ },
1413
+ {
1414
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1415
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1416
+ },
1417
+ {
1418
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1419
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1420
+ },
1421
+ ]
1422
+ with pytest.raises(ValueError, match="cp.*not declared"):
1423
+ _validate_explicit_replicated(
1424
+ explicit_replicated_axes=frozenset(),
1425
+ sharded_axes={ParallelAxis.TP},
1426
+ all_axes={ParallelAxis.TP, ParallelAxis.CP},
1427
+ parallel_infos=parallel_infos,
1428
+ )
1429
+
1430
+ def test_no_axes_at_all(self) -> None:
1431
+ """Empty axes sets → no error."""
1432
+ _validate_explicit_replicated(
1433
+ explicit_replicated_axes=frozenset(),
1434
+ sharded_axes=set(),
1435
+ all_axes=set(),
1436
+ parallel_infos=[{}],
1437
+ )
1438
+
1439
+ def test_jointly_determined_axis_passes(self) -> None:
1440
+ """EDP determined by (TP, CP) jointly but not by either alone → no error.
1441
+
1442
+ Simulates tp=2, cp=2, ep=1, etp=1 on 4 GPUs where edp_size=4
1443
+ and edp_rank = unique per (tp_rank, cp_rank) combination.
1444
+ """
1445
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1446
+ {
1447
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1448
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1449
+ ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2),
1450
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4),
1451
+ },
1452
+ {
1453
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1454
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1455
+ ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2),
1456
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4),
1457
+ },
1458
+ {
1459
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1460
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1461
+ ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2),
1462
+ ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=4),
1463
+ },
1464
+ {
1465
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1466
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1467
+ ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2),
1468
+ ParallelAxis.EDP: AxisInfo(axis_rank=3, axis_size=4),
1469
+ },
1470
+ ]
1471
+ _validate_explicit_replicated(
1472
+ explicit_replicated_axes=frozenset({ParallelAxis.TP}),
1473
+ sharded_axes={ParallelAxis.CP, ParallelAxis.SP},
1474
+ all_axes={
1475
+ ParallelAxis.TP,
1476
+ ParallelAxis.CP,
1477
+ ParallelAxis.SP,
1478
+ ParallelAxis.EDP,
1479
+ },
1480
+ parallel_infos=parallel_infos,
1481
+ )
1482
+
1483
+ def test_jointly_undetermined_axis_still_raises(self) -> None:
1484
+ """Axis not determined even by the combination of all declared axes → raises.
1485
+
1486
+ DP is orthogonal to TP (each TP rank pairs with both DP ranks),
1487
+ so (TP,) cannot determine DP.
1488
+ """
1489
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1490
+ {
1491
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
1492
+ ParallelAxis.DP: AxisInfo(axis_rank=dp_rank, axis_size=2),
1493
+ }
1494
+ for tp_rank in range(2)
1495
+ for dp_rank in range(2)
1496
+ ]
1497
+ with pytest.raises(ValueError, match="dp.*not declared"):
1498
+ _validate_explicit_replicated(
1499
+ explicit_replicated_axes=frozenset(),
1500
+ sharded_axes={ParallelAxis.TP},
1501
+ all_axes={ParallelAxis.TP, ParallelAxis.DP},
1502
+ parallel_infos=parallel_infos,
1503
+ )
1504
+
1505
+
1506
+ class TestIsJointlyDetermined:
1507
+ def test_edp_determined_by_tp_and_cp(self) -> None:
1508
+ """EDP rank = unique per (TP, CP) combination → True."""
1509
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1510
+ {
1511
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1512
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1513
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4),
1514
+ },
1515
+ {
1516
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1517
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1518
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4),
1519
+ },
1520
+ {
1521
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1522
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1523
+ ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=4),
1524
+ },
1525
+ {
1526
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1527
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1528
+ ParallelAxis.EDP: AxisInfo(axis_rank=3, axis_size=4),
1529
+ },
1530
+ ]
1531
+ assert _is_jointly_determined(
1532
+ parallel_infos,
1533
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1534
+ child=ParallelAxis.EDP,
1535
+ )
1536
+
1537
+ def test_dp_not_determined_by_tp_alone(self) -> None:
1538
+ """DP is orthogonal to TP → False."""
1539
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1540
+ {
1541
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2),
1542
+ ParallelAxis.DP: AxisInfo(axis_rank=dp_rank, axis_size=2),
1543
+ }
1544
+ for tp_rank in range(2)
1545
+ for dp_rank in range(2)
1546
+ ]
1547
+ assert not _is_jointly_determined(
1548
+ parallel_infos,
1549
+ parent_axes=frozenset({ParallelAxis.TP}),
1550
+ child=ParallelAxis.DP,
1551
+ )
1552
+
1553
+ def test_empty_parallel_infos_returns_false(self) -> None:
1554
+ """No parallel_info entries → False (no evidence)."""
1555
+ assert not _is_jointly_determined(
1556
+ [],
1557
+ parent_axes=frozenset({ParallelAxis.TP}),
1558
+ child=ParallelAxis.EDP,
1559
+ )
1560
+
1561
+ def test_child_absent_from_infos_returns_false(self) -> None:
1562
+ """Child axis not present in any info → False."""
1563
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1564
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)},
1565
+ ]
1566
+ assert not _is_jointly_determined(
1567
+ parallel_infos,
1568
+ parent_axes=frozenset({ParallelAxis.TP}),
1569
+ child=ParallelAxis.EDP,
1570
+ )
1571
+
1572
+ def test_empty_parent_axes_returns_false(self) -> None:
1573
+ """Empty parent_axes → False (no parents to determine child)."""
1574
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1575
+ {
1576
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1577
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1578
+ },
1579
+ ]
1580
+ assert not _is_jointly_determined(
1581
+ parallel_infos,
1582
+ parent_axes=frozenset(),
1583
+ child=ParallelAxis.EDP,
1584
+ )
1585
+
1586
+ def test_single_parent_determines_child(self) -> None:
1587
+ """Single parent tp_rank uniquely maps to edp_rank → True (degenerate joint case)."""
1588
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1589
+ {
1590
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1591
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1592
+ },
1593
+ {
1594
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1595
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2),
1596
+ },
1597
+ ]
1598
+ assert _is_jointly_determined(
1599
+ parallel_infos,
1600
+ parent_axes=frozenset({ParallelAxis.TP}),
1601
+ child=ParallelAxis.EDP,
1602
+ )
1603
+
1604
+ def test_conflict_returns_false(self) -> None:
1605
+ """Same (tp_rank, cp_rank) maps to different edp_rank → False."""
1606
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1607
+ {
1608
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1609
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1610
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4),
1611
+ },
1612
+ {
1613
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1614
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1615
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4),
1616
+ },
1617
+ ]
1618
+ assert not _is_jointly_determined(
1619
+ parallel_infos,
1620
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1621
+ child=ParallelAxis.EDP,
1622
+ )
1623
+
1624
+ def test_two_parents_jointly_determine_child(self) -> None:
1625
+ """(tp_rank, cp_rank) tuple uniquely determines edp_rank → True."""
1626
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1627
+ {
1628
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1629
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1630
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4),
1631
+ },
1632
+ {
1633
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1634
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1635
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4),
1636
+ },
1637
+ {
1638
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1639
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1640
+ ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=4),
1641
+ },
1642
+ {
1643
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1644
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1645
+ ParallelAxis.EDP: AxisInfo(axis_rank=3, axis_size=4),
1646
+ },
1647
+ ]
1648
+ assert _is_jointly_determined(
1649
+ parallel_infos,
1650
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1651
+ child=ParallelAxis.EDP,
1652
+ )
1653
+
1654
+ def test_three_parents_jointly_determine_child(self) -> None:
1655
+ """(tp, cp, ep) triple uniquely determines edp → True."""
1656
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1657
+ {
1658
+ ParallelAxis.TP: AxisInfo(axis_rank=tp, axis_size=2),
1659
+ ParallelAxis.CP: AxisInfo(axis_rank=cp, axis_size=2),
1660
+ ParallelAxis.EP: AxisInfo(axis_rank=ep, axis_size=2),
1661
+ ParallelAxis.EDP: AxisInfo(axis_rank=tp * 4 + cp * 2 + ep, axis_size=8),
1662
+ }
1663
+ for tp in range(2)
1664
+ for cp in range(2)
1665
+ for ep in range(2)
1666
+ ]
1667
+ assert _is_jointly_determined(
1668
+ parallel_infos,
1669
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP, ParallelAxis.EP}),
1670
+ child=ParallelAxis.EDP,
1671
+ )
1672
+
1673
+ def test_parent_partially_absent_causes_ambiguity(self) -> None:
1674
+ """Some infos lack a parent axis → False, even if child values differ.
1675
+
1676
+ When cp is missing from some infos, the joint determination is
1677
+ incomplete because we cannot construct a full parent key.
1678
+ """
1679
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1680
+ {
1681
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1682
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1683
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4),
1684
+ },
1685
+ {
1686
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1687
+ # cp absent — parent key is incomplete
1688
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4),
1689
+ },
1690
+ ]
1691
+ assert not _is_jointly_determined(
1692
+ parallel_infos,
1693
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1694
+ child=ParallelAxis.EDP,
1695
+ )
1696
+
1697
+ def test_partial_parent_first_info_missing_returns_false(self) -> None:
1698
+ """First info lacks a parent axis; second info has all parents → False."""
1699
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1700
+ {
1701
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1702
+ # cp absent
1703
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1704
+ },
1705
+ {
1706
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1707
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1708
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2),
1709
+ },
1710
+ ]
1711
+ assert not _is_jointly_determined(
1712
+ parallel_infos,
1713
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1714
+ child=ParallelAxis.EDP,
1715
+ )
1716
+
1717
+ def test_universally_absent_parent_ignored_remaining_determines(self) -> None:
1718
+ """Parent axis absent from ALL infos is ignored; remaining parent determines child → True.
1719
+
1720
+ Models the real scenario where DP (size 1) is in declared_axes but
1721
+ filtered out of all parallel_infos by normalize_parallel_info.
1722
+ """
1723
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1724
+ {
1725
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1726
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1727
+ },
1728
+ {
1729
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1730
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2),
1731
+ },
1732
+ ]
1733
+ assert _is_jointly_determined(
1734
+ parallel_infos,
1735
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1736
+ child=ParallelAxis.EDP,
1737
+ )
1738
+
1739
+ def test_all_parents_universally_absent_returns_false(self) -> None:
1740
+ """Every parent axis absent from ALL infos → no active parents → False."""
1741
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1742
+ {
1743
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1744
+ },
1745
+ {
1746
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2),
1747
+ },
1748
+ ]
1749
+ assert not _is_jointly_determined(
1750
+ parallel_infos,
1751
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1752
+ child=ParallelAxis.EDP,
1753
+ )
1754
+
1755
+ def test_universally_absent_parent_remaining_conflict_returns_false(self) -> None:
1756
+ """Parent axis absent from ALL infos ignored, but remaining parent has conflict → False."""
1757
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1758
+ {
1759
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1760
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1761
+ },
1762
+ {
1763
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1764
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2),
1765
+ },
1766
+ ]
1767
+ assert not _is_jointly_determined(
1768
+ parallel_infos,
1769
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1770
+ child=ParallelAxis.EDP,
1771
+ )
1772
+
1773
+ def test_partial_parent_matching_child_still_returns_false(self) -> None:
1774
+ """Even when child values match across infos, incomplete parent → False.
1775
+
1776
+ Ensures the check is about parent completeness, not child conflict.
1777
+ """
1778
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1779
+ {
1780
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1781
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1782
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1783
+ },
1784
+ {
1785
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1786
+ # cp absent — but edp_rank is SAME as first info
1787
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1788
+ },
1789
+ ]
1790
+ assert not _is_jointly_determined(
1791
+ parallel_infos,
1792
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1793
+ child=ParallelAxis.EDP,
1794
+ )
1795
+
1796
+ def test_many_infos_consistent_joint_mapping(self) -> None:
1797
+ """8 ranks with (tp, cp) consistently mapping to edp → True."""
1798
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1799
+ {
1800
+ ParallelAxis.TP: AxisInfo(axis_rank=tp, axis_size=2),
1801
+ ParallelAxis.CP: AxisInfo(axis_rank=cp, axis_size=2),
1802
+ ParallelAxis.EP: AxisInfo(axis_rank=ep, axis_size=2),
1803
+ ParallelAxis.EDP: AxisInfo(axis_rank=tp * 2 + cp, axis_size=4),
1804
+ }
1805
+ for tp in range(2)
1806
+ for cp in range(2)
1807
+ for ep in range(2)
1808
+ ]
1809
+ assert _is_jointly_determined(
1810
+ parallel_infos,
1811
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1812
+ child=ParallelAxis.EDP,
1813
+ )
1814
+
1815
+ def test_partial_parent_middle_info_missing_returns_false(self) -> None:
1816
+ """Middle info in a 3-info list lacks a parent → False."""
1817
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1818
+ {
1819
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1820
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1821
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=3),
1822
+ },
1823
+ {
1824
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1825
+ # cp absent
1826
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=3),
1827
+ },
1828
+ {
1829
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1830
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1831
+ ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=3),
1832
+ },
1833
+ ]
1834
+ assert not _is_jointly_determined(
1835
+ parallel_infos,
1836
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1837
+ child=ParallelAxis.EDP,
1838
+ )
1839
+
1840
+ def test_child_absent_from_some_infos_still_true(self) -> None:
1841
+ """Child absent from some infos but consistent where present → True.
1842
+
1843
+ Infos without the child are skipped; no parent completeness issue.
1844
+ """
1845
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1846
+ {
1847
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1848
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1849
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1850
+ },
1851
+ {
1852
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1853
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1854
+ # edp absent — this info is skipped
1855
+ },
1856
+ {
1857
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1858
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1859
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2),
1860
+ },
1861
+ ]
1862
+ assert _is_jointly_determined(
1863
+ parallel_infos,
1864
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1865
+ child=ParallelAxis.EDP,
1866
+ )
1867
+
1868
+ def test_child_absent_from_all_infos_returns_false(self) -> None:
1869
+ """Child not present in any info → mapping is empty → False."""
1870
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1871
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)},
1872
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)},
1873
+ ]
1874
+ assert not _is_jointly_determined(
1875
+ parallel_infos,
1876
+ parent_axes=frozenset({ParallelAxis.TP}),
1877
+ child=ParallelAxis.CP,
1878
+ )
1879
+
1880
+ def test_parent_present_in_some_but_missing_with_child_returns_false(self) -> None:
1881
+ """Parent present in some infos but absent in an info that has child.
1882
+
1883
+ This is the potential false-positive scenario: an info has child but
1884
+ not all active parents, so the parent key cannot be fully constructed.
1885
+ """
1886
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1887
+ {
1888
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1889
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
1890
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2),
1891
+ },
1892
+ {
1893
+ # TP present in first info so it's active, but absent here
1894
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
1895
+ ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2),
1896
+ },
1897
+ ]
1898
+ assert not _is_jointly_determined(
1899
+ parallel_infos,
1900
+ parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
1901
+ child=ParallelAxis.EDP,
1902
+ )
1903
+
1904
+ def test_single_info_with_all_axes_returns_true(self) -> None:
1905
+ """Single info entry with parent and child → trivially determined → True."""
1906
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1907
+ {
1908
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=1),
1909
+ ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=1),
1910
+ },
1911
+ ]
1912
+ assert _is_jointly_determined(
1913
+ parallel_infos,
1914
+ parent_axes=frozenset({ParallelAxis.TP}),
1915
+ child=ParallelAxis.EDP,
1916
+ )
1917
+
1918
+
1919
+ class TestReplicatedAxesOrthogonality:
1920
+ """Tests for _validate_replicated_axes_orthogonal: every pair of explicitly
1921
+ replicated axes must be fully orthogonal (no dependency relationship)."""
1922
+
1923
+ def test_tp_determines_moe_tp_raises(self) -> None:
1924
+ """TP4 + MOE_TP2 where tp_rank determines moe_tp_rank → ValueError."""
1925
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1926
+ {
1927
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4),
1928
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
1929
+ },
1930
+ {
1931
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4),
1932
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
1933
+ },
1934
+ {
1935
+ ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4),
1936
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
1937
+ },
1938
+ {
1939
+ ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4),
1940
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
1941
+ },
1942
+ ]
1943
+ with pytest.raises(ValueError, match="not orthogonal"):
1944
+ _validate_replicated_axes_orthogonal(
1945
+ explicit_replicated_axes=frozenset(
1946
+ {ParallelAxis.TP, ParallelAxis.MOE_TP}
1947
+ ),
1948
+ parallel_infos=parallel_infos,
1949
+ )
1950
+
1951
+ def test_tp_determines_sp_identical_group_raises(self) -> None:
1952
+ """TP2 + SP2 where sp_rank == tp_rank → ValueError."""
1953
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1954
+ {
1955
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
1956
+ ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2),
1957
+ },
1958
+ {
1959
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
1960
+ ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2),
1961
+ },
1962
+ ]
1963
+ with pytest.raises(ValueError, match="not orthogonal"):
1964
+ _validate_replicated_axes_orthogonal(
1965
+ explicit_replicated_axes=frozenset({ParallelAxis.TP, ParallelAxis.SP}),
1966
+ parallel_infos=parallel_infos,
1967
+ )
1968
+
1969
+ def test_three_axes_two_overlapping_pairs_raises(self) -> None:
1970
+ """TP4 + ATTN_TP2 + MOE_TP2, TP determines both → error mentions two pairs."""
1971
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
1972
+ {
1973
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4),
1974
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
1975
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
1976
+ },
1977
+ {
1978
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4),
1979
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
1980
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2),
1981
+ },
1982
+ {
1983
+ ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4),
1984
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2),
1985
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
1986
+ },
1987
+ {
1988
+ ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4),
1989
+ ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2),
1990
+ ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2),
1991
+ },
1992
+ ]
1993
+ with pytest.raises(ValueError, match="not orthogonal") as exc_info:
1994
+ _validate_replicated_axes_orthogonal(
1995
+ explicit_replicated_axes=frozenset(
1996
+ {ParallelAxis.TP, ParallelAxis.ATTN_TP, ParallelAxis.MOE_TP}
1997
+ ),
1998
+ parallel_infos=parallel_infos,
1999
+ )
2000
+ msg = str(exc_info.value)
2001
+ assert "attn_tp" in msg
2002
+ assert "moe_tp" in msg
2003
+
2004
+ def test_three_axes_one_overlap_one_orthogonal_raises(self) -> None:
2005
+ """TP4 + MOE_TP2 (dependent) + CP2 (independent) → only tp/moe_tp pair errors."""
2006
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = []
2007
+ for cp_rank in range(2):
2008
+ for tp_rank in range(4):
2009
+ parallel_infos.append(
2010
+ {
2011
+ ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=4),
2012
+ ParallelAxis.MOE_TP: AxisInfo(
2013
+ axis_rank=tp_rank % 2, axis_size=2
2014
+ ),
2015
+ ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2),
2016
+ }
2017
+ )
2018
+ with pytest.raises(ValueError, match="not orthogonal") as exc_info:
2019
+ _validate_replicated_axes_orthogonal(
2020
+ explicit_replicated_axes=frozenset(
2021
+ {ParallelAxis.TP, ParallelAxis.MOE_TP, ParallelAxis.CP}
2022
+ ),
2023
+ parallel_infos=parallel_infos,
2024
+ )
2025
+ msg = str(exc_info.value)
2026
+ assert "moe_tp" in msg
2027
+ assert "cp" not in msg
2028
+
2029
+ def test_single_replicated_axis_no_check(self) -> None:
2030
+ """Only one replicated axis → no orthogonality check needed, passes."""
2031
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
2032
+ {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)},
2033
+ {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)},
2034
+ ]
2035
+ _validate_replicated_axes_orthogonal(
2036
+ explicit_replicated_axes=frozenset({ParallelAxis.TP}),
2037
+ parallel_infos=parallel_infos,
2038
+ )
2039
+
2040
+ def test_two_independent_axes_ok(self) -> None:
2041
+ """TP2 + CP2 fully orthogonal → no error."""
2042
+ parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [
2043
+ {
2044
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
2045
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
2046
+ },
2047
+ {
2048
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
2049
+ ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2),
2050
+ },
2051
+ {
2052
+ ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2),
2053
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
2054
+ },
2055
+ {
2056
+ ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2),
2057
+ ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2),
2058
+ },
2059
+ ]
2060
+ _validate_replicated_axes_orthogonal(
2061
+ explicit_replicated_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}),
2062
+ parallel_infos=parallel_infos,
2063
+ )
2064
+
2065
+
2066
+ if __name__ == "__main__":
2067
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/conftest.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import warnings
3
+ from pathlib import Path
4
+
5
+ warnings.filterwarnings(
6
+ "ignore", message="builtin type Swig.*", category=DeprecationWarning
7
+ )
8
+
9
+ # Add the test root to sys.path so `registered.debug_utils.comparator.testing_helpers`
10
+ # can be imported by test modules.
11
+ _TEST_ROOT: Path = Path(__file__).resolve().parents[3]
12
+ if str(_TEST_ROOT) not in sys.path:
13
+ sys.path.insert(0, str(_TEST_ROOT))
14
+
15
+ import pytest
16
+
17
+ from sglang.srt.debug_utils.comparator.report_sink import report_sink
18
+
19
+ collect_ignore_glob: list[str] = []
20
+
21
+
22
+ def pytest_configure(config: pytest.Config) -> None:
23
+ config.addinivalue_line(
24
+ "filterwarnings",
25
+ "ignore:Unknown config option. asyncio_mode:pytest.PytestConfigWarning",
26
+ )
27
+ config.addinivalue_line(
28
+ "filterwarnings",
29
+ "ignore:builtin type Swig.*:DeprecationWarning",
30
+ )
31
+ config.addinivalue_line(
32
+ "filterwarnings",
33
+ "ignore:Named tensors and all their associated APIs:UserWarning",
34
+ )
35
+
36
+
37
+ @pytest.fixture(autouse=True)
38
+ def _reset_report_sink() -> None:
39
+ yield
40
+ report_sink._reset()
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/__init__.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dim_parser.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from sglang.srt.debug_utils.comparator.dims_spec import (
6
+ DimSpec,
7
+ Ordering,
8
+ ParallelAxis,
9
+ ParallelModifier,
10
+ Reduction,
11
+ parse_dim,
12
+ )
13
+ from sglang.test.ci.ci_register import register_cpu_ci
14
+
15
+ register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True)
16
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
17
+
18
+
19
+ class TestParseDim:
20
+ def test_plain_name(self) -> None:
21
+ assert parse_dim("b") == DimSpec(name="b")
22
+
23
+ def test_parallel_axis(self) -> None:
24
+ assert parse_dim("h[tp]") == DimSpec(
25
+ name="h",
26
+ parallel_modifiers=[ParallelModifier(axis=ParallelAxis.TP)],
27
+ )
28
+
29
+ def test_all_parallel_axes(self) -> None:
30
+ assert parse_dim("a[tp]").parallel_modifiers[0].axis == ParallelAxis.TP
31
+ assert parse_dim("a[cp]").parallel_modifiers[0].axis == ParallelAxis.CP
32
+ assert parse_dim("a[ep]").parallel_modifiers[0].axis == ParallelAxis.EP
33
+ assert parse_dim("a[sp]").parallel_modifiers[0].axis == ParallelAxis.SP
34
+
35
+ def test_ordering(self) -> None:
36
+ assert (
37
+ parse_dim("s[cp:zigzag]").parallel_modifiers[0].ordering == Ordering.ZIGZAG
38
+ )
39
+ assert (
40
+ parse_dim("s[cp:natural]").parallel_modifiers[0].ordering
41
+ == Ordering.NATURAL
42
+ )
43
+
44
+ def test_reduction(self) -> None:
45
+ assert (
46
+ parse_dim("h[tp:partial]").parallel_modifiers[0].reduction
47
+ == Reduction.PARTIAL
48
+ )
49
+
50
+ def test_all_qualifiers(self) -> None:
51
+ assert parse_dim("s[cp:zigzag+partial]") == DimSpec(
52
+ name="s",
53
+ parallel_modifiers=[
54
+ ParallelModifier(
55
+ axis=ParallelAxis.CP,
56
+ ordering=Ordering.ZIGZAG,
57
+ reduction=Reduction.PARTIAL,
58
+ ),
59
+ ],
60
+ )
61
+
62
+ def test_multi_axis(self) -> None:
63
+ result: DimSpec = parse_dim("t[cp:zigzag,sp]")
64
+ assert result.name == "t"
65
+ assert len(result.parallel_modifiers) == 2
66
+ assert result.parallel_modifiers[0] == ParallelModifier(
67
+ axis=ParallelAxis.CP, ordering=Ordering.ZIGZAG
68
+ )
69
+ assert result.parallel_modifiers[1] == ParallelModifier(axis=ParallelAxis.SP)
70
+
71
+ def test_invalid_token_raises(self) -> None:
72
+ with pytest.raises(ValueError, match="Invalid dim token"):
73
+ parse_dim("h[]")
74
+ with pytest.raises(ValueError, match="Invalid dim token"):
75
+ parse_dim("h[tp[x]]")
76
+
77
+ def test_unknown_axis_raises(self) -> None:
78
+ with pytest.raises(ValueError, match="Unknown axis"):
79
+ parse_dim("h[xyz]")
80
+
81
+ def test_unknown_qualifier_raises(self) -> None:
82
+ with pytest.raises(ValueError, match="Unknown qualifier"):
83
+ parse_dim("h[tp:foobar]")
84
+
85
+ def test_multiple_ordering_raises(self) -> None:
86
+ with pytest.raises(ValueError, match="Multiple ordering"):
87
+ parse_dim("s[cp:zigzag+natural]")
88
+
89
+ def test_multiple_reduction_raises(self) -> None:
90
+ with pytest.raises(ValueError, match="Multiple reduction"):
91
+ parse_dim("h[tp:partial+partial]")
92
+
93
+ def test_duplicate_axis_raises(self) -> None:
94
+ with pytest.raises(ValueError, match="Duplicate axis"):
95
+ parse_dim("h[tp,tp]")
96
+
97
+ def test_squeeze_dim(self) -> None:
98
+ assert parse_dim("1") == DimSpec(name="1")
99
+
100
+ def test_squeeze_dim_rejects_modifiers(self) -> None:
101
+ with pytest.raises(ValueError, match="Invalid dim token"):
102
+ parse_dim("1[tp]")
103
+
104
+
105
+ class TestParseFusedDim:
106
+ def test_basic_fused(self) -> None:
107
+ result: DimSpec = parse_dim("(num_heads*head_dim)")
108
+ assert result.name == "num_heads*head_dim"
109
+ assert result.parallel_modifiers == []
110
+ assert result.is_fused
111
+ assert result.sub_dims == ["num_heads", "head_dim"]
112
+
113
+ def test_fused_with_modifier(self) -> None:
114
+ result: DimSpec = parse_dim("(num_heads*head_dim)[tp]")
115
+ assert result.name == "num_heads*head_dim"
116
+ assert result.parallel_modifiers == [ParallelModifier(axis=ParallelAxis.TP)]
117
+ assert result.sub_dims == ["num_heads", "head_dim"]
118
+
119
+ def test_three_way_fused(self) -> None:
120
+ result: DimSpec = parse_dim("(a*b*c)")
121
+ assert result.name == "a*b*c"
122
+ assert len(result.sub_dims) == 3
123
+ assert result.sub_dims == ["a", "b", "c"]
124
+
125
+ def test_three_way_fused_with_modifier(self) -> None:
126
+ result: DimSpec = parse_dim("(a*b*c)[tp]")
127
+ assert result.parallel_modifiers == [ParallelModifier(axis=ParallelAxis.TP)]
128
+ assert len(result.sub_dims) == 3
129
+
130
+ def test_fused_with_complex_modifier(self) -> None:
131
+ result: DimSpec = parse_dim("(a*b)[cp:zigzag]")
132
+ assert result.parallel_modifiers == [
133
+ ParallelModifier(axis=ParallelAxis.CP, ordering=Ordering.ZIGZAG)
134
+ ]
135
+ assert result.sub_dims == ["a", "b"]
136
+
137
+ def test_regular_dim_not_fused(self) -> None:
138
+ result: DimSpec = parse_dim("h[tp]")
139
+ assert not result.is_fused
140
+ assert result.sub_dims == ["h"]
141
+
142
+ def test_fused_duplicate_sub_names_raises(self) -> None:
143
+ with pytest.raises(ValueError, match="Duplicate sub-dim"):
144
+ parse_dim("(a*a)")
145
+
146
+ def test_fused_invalid_sub_dim_raises(self) -> None:
147
+ with pytest.raises(ValueError, match="Invalid sub-dim"):
148
+ parse_dim("(a*1)")
149
+
150
+
151
+ if __name__ == "__main__":
152
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dims_parser.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from sglang.srt.debug_utils.comparator.dims_spec import (
6
+ SQUEEZE_DIM_NAME,
7
+ DimSpec,
8
+ DimsSpec,
9
+ Ordering,
10
+ ParallelAxis,
11
+ ParallelModifier,
12
+ _SingletonDimUtil,
13
+ parse_dims,
14
+ resolve_dim_names,
15
+ )
16
+ from sglang.test.ci.ci_register import register_cpu_ci
17
+
18
+ register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True)
19
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
20
+
21
+
22
+ class TestSingletonDimUtilFilterOut:
23
+ def test_no_squeeze(self) -> None:
24
+ specs: list[DimSpec] = parse_dims("t h d").dims
25
+ assert _SingletonDimUtil.filter_out(specs) == specs
26
+
27
+ def test_with_squeeze(self) -> None:
28
+ specs: list[DimSpec] = parse_dims("t 1 h").dims
29
+ filtered: list[DimSpec] = _SingletonDimUtil.filter_out(specs)
30
+ assert len(filtered) == 2
31
+ assert filtered[0].name == "t"
32
+ assert filtered[1].name == "h"
33
+
34
+ def test_all_squeeze(self) -> None:
35
+ specs: list[DimSpec] = parse_dims("1 1").dims
36
+ assert _SingletonDimUtil.filter_out(specs) == []
37
+
38
+
39
+ class TestSingletonDimUtilIsSqueeze:
40
+ def test_squeeze(self) -> None:
41
+ assert _SingletonDimUtil.is_squeeze(DimSpec(name=SQUEEZE_DIM_NAME)) is True
42
+
43
+ def test_non_squeeze(self) -> None:
44
+ assert _SingletonDimUtil.is_squeeze(DimSpec(name="t")) is False
45
+
46
+
47
+ class TestSingletonDimUtilMakeName:
48
+ def test_indices(self) -> None:
49
+ assert _SingletonDimUtil.make_name(0) == "singleton0"
50
+ assert _SingletonDimUtil.make_name(1) == "singleton1"
51
+ assert _SingletonDimUtil.make_name(99) == "singleton99"
52
+
53
+
54
+ class TestSingletonDimUtilSanitizeNames:
55
+ def test_no_squeeze(self) -> None:
56
+ assert _SingletonDimUtil.sanitize_names(["t", "h", "d"]) == ["t", "h", "d"]
57
+
58
+ def test_single_squeeze(self) -> None:
59
+ assert _SingletonDimUtil.sanitize_names(["t", "1", "h"]) == [
60
+ "t",
61
+ "singleton0",
62
+ "h",
63
+ ]
64
+
65
+ def test_multiple_squeeze(self) -> None:
66
+ assert _SingletonDimUtil.sanitize_names(["1", "t", "1", "h"]) == [
67
+ "singleton0",
68
+ "t",
69
+ "singleton1",
70
+ "h",
71
+ ]
72
+
73
+ def test_empty(self) -> None:
74
+ assert _SingletonDimUtil.sanitize_names([]) == []
75
+
76
+
77
+ class TestParseDims:
78
+ def test_multi_dims(self) -> None:
79
+ assert parse_dims("b s h d").dims == [
80
+ DimSpec(name="b"),
81
+ DimSpec(name="s"),
82
+ DimSpec(name="h"),
83
+ DimSpec(name="d"),
84
+ ]
85
+
86
+ def test_single_dim(self) -> None:
87
+ assert parse_dims("t").dims == [DimSpec(name="t")]
88
+
89
+ def test_mixed_annotated(self) -> None:
90
+ assert parse_dims("b s[cp:zigzag] h[tp] d").dims == [
91
+ DimSpec(name="b"),
92
+ DimSpec(
93
+ name="s",
94
+ parallel_modifiers=[
95
+ ParallelModifier(axis=ParallelAxis.CP, ordering=Ordering.ZIGZAG),
96
+ ],
97
+ ),
98
+ DimSpec(
99
+ name="h",
100
+ parallel_modifiers=[ParallelModifier(axis=ParallelAxis.TP)],
101
+ ),
102
+ DimSpec(name="d"),
103
+ ]
104
+
105
+ def test_empty_string_raises(self) -> None:
106
+ with pytest.raises(ValueError, match="empty"):
107
+ parse_dims("")
108
+
109
+ def test_whitespace_only_raises(self) -> None:
110
+ with pytest.raises(ValueError, match="empty"):
111
+ parse_dims(" ")
112
+
113
+ def test_duplicate_name_raises(self) -> None:
114
+ with pytest.raises(ValueError, match="Duplicate"):
115
+ parse_dims("h h")
116
+
117
+ def test_with_squeeze_dims(self) -> None:
118
+ dims: list[DimSpec] = parse_dims("t 1 h").dims
119
+ assert len(dims) == 3
120
+ assert dims[0] == DimSpec(name="t")
121
+ assert dims[1] == DimSpec(name="1")
122
+ assert dims[2] == DimSpec(name="h")
123
+
124
+ def test_multiple_squeeze_dims_no_duplicate_error(self) -> None:
125
+ dims: list[DimSpec] = parse_dims("t 1 h 1 d").dims
126
+ assert len(dims) == 5
127
+ assert dims[1] == DimSpec(name="1")
128
+ assert dims[3] == DimSpec(name="1")
129
+
130
+
131
+ class TestParseDimsWithFused:
132
+ def test_fused_in_dims(self) -> None:
133
+ result: DimsSpec = parse_dims("t (num_heads*head_dim)[tp]")
134
+ assert len(result.dims) == 2
135
+ assert result.dims[0] == DimSpec(name="t")
136
+ assert result.dims[1].is_fused
137
+ assert result.dims[1].name == "num_heads*head_dim"
138
+
139
+ def test_fused_and_regular_mixed(self) -> None:
140
+ result: DimsSpec = parse_dims("t (num_heads*head_dim)[tp] d")
141
+ assert len(result.dims) == 3
142
+ assert not result.dims[0].is_fused
143
+ assert result.dims[1].is_fused
144
+ assert not result.dims[2].is_fused
145
+
146
+ def test_fused_sub_name_conflicts_with_regular_raises(self) -> None:
147
+ with pytest.raises(ValueError, match="Duplicate"):
148
+ parse_dims("t num_heads (num_heads*head_dim)")
149
+
150
+ def test_multiple_fused_dims(self) -> None:
151
+ result: DimsSpec = parse_dims("(a*b) (c*d)")
152
+ assert len(result.dims) == 2
153
+ assert result.dims[0].is_fused
154
+ assert result.dims[1].is_fused
155
+
156
+ def test_cross_fused_duplicate_sub_name_raises(self) -> None:
157
+ with pytest.raises(ValueError, match="Duplicate"):
158
+ parse_dims("(a*b) (c*a)")
159
+
160
+
161
+ class TestParseDimsWithHash:
162
+ """parse_dims strips the ``#`` declaration section from dims."""
163
+
164
+ def test_shape_dims_unchanged(self) -> None:
165
+ assert parse_dims("b s h[tp] # dp:=moe_dp").dims == parse_dims("b s h[tp]").dims
166
+
167
+ def test_dp_group_alias_extracted(self) -> None:
168
+ assert parse_dims("b s h[tp] # dp:=moe_dp").dp_group_alias == "moe_dp"
169
+
170
+ def test_no_hash_no_alias(self) -> None:
171
+ assert parse_dims("b s h[tp]").dp_group_alias is None
172
+
173
+ def test_whitespace_around_hash(self) -> None:
174
+ assert parse_dims("t h # dp:=foo ").dims == parse_dims("t h").dims
175
+ assert parse_dims("t h # dp:=foo ").dp_group_alias == "foo"
176
+
177
+ def test_multiple_declarations_picks_dp(self) -> None:
178
+ result: DimsSpec = parse_dims("t h[tp] # dp:=moe_dp ep:replicated")
179
+ assert result.dims == parse_dims("t h[tp]").dims
180
+ assert result.dp_group_alias == "moe_dp"
181
+ assert result.replicated_axes == frozenset({ParallelAxis.EP})
182
+
183
+ def test_no_dp_alias_token(self) -> None:
184
+ result: DimsSpec = parse_dims("t h[tp] # ep:replicated")
185
+ assert result.dp_group_alias is None
186
+ assert result.replicated_axes == frozenset({ParallelAxis.EP})
187
+
188
+
189
+ class TestDpGroupAlias:
190
+ def test_basic(self) -> None:
191
+ assert parse_dims("b s h[tp] # dp:=moe_dp").dp_group_alias == "moe_dp"
192
+
193
+ def test_no_hash_returns_none(self) -> None:
194
+ assert parse_dims("t h").dp_group_alias is None
195
+
196
+ def test_no_dp_alias_token(self) -> None:
197
+ assert parse_dims("t h[tp] # ep:replicated").dp_group_alias is None
198
+
199
+ def test_multiple_tokens_picks_dp(self) -> None:
200
+ assert (
201
+ parse_dims("b s # ep:replicated dp:=custom_dp").dp_group_alias
202
+ == "custom_dp"
203
+ )
204
+
205
+
206
+ class TestExplicitReplicatedAxes:
207
+ def test_single_replicated(self) -> None:
208
+ result: DimsSpec = parse_dims("b s h[tp] d # ep:replicated")
209
+ assert result.replicated_axes == frozenset({ParallelAxis.EP})
210
+
211
+ def test_explicit_sharded_equivalent(self) -> None:
212
+ assert parse_dims("b s h[tp:sharded] d").dims == parse_dims("b s h[tp] d").dims
213
+
214
+ def test_multiple_replicated(self) -> None:
215
+ result: DimsSpec = parse_dims("b s h[tp] d # ep:replicated cp:replicated")
216
+ assert result.replicated_axes == frozenset({ParallelAxis.EP, ParallelAxis.CP})
217
+
218
+ def test_dp_alias_and_replicated_coexist(self) -> None:
219
+ result: DimsSpec = parse_dims("b s h[tp] d # dp:=moe_dp ep:replicated")
220
+ assert result.dp_group_alias == "moe_dp"
221
+ assert result.replicated_axes == frozenset({ParallelAxis.EP})
222
+
223
+ def test_no_hash_replicated_empty(self) -> None:
224
+ result: DimsSpec = parse_dims("b s h[tp] d")
225
+ assert result.replicated_axes == frozenset()
226
+
227
+ def test_hash_without_replicated(self) -> None:
228
+ result: DimsSpec = parse_dims("b s h[tp] d # dp:=moe_dp")
229
+ assert result.replicated_axes == frozenset()
230
+
231
+ def test_replicated_conflicts_with_sharded_raises(self) -> None:
232
+ with pytest.raises(ValueError, match="both sharded.*and replicated"):
233
+ parse_dims("b s h[tp] d # tp:replicated")
234
+
235
+ def test_unknown_axis_in_replicated_raises(self) -> None:
236
+ with pytest.raises(ValueError, match="Unknown axis"):
237
+ parse_dims("b s h[tp] d # xyz:replicated")
238
+
239
+ def test_duplicate_replicated_declaration_raises(self) -> None:
240
+ with pytest.raises(ValueError, match="Duplicate replicated"):
241
+ parse_dims("b s h d # ep:replicated ep:replicated")
242
+
243
+ def test_unrecognized_token_in_comment_raises(self) -> None:
244
+ with pytest.raises(ValueError, match="Unrecognized token"):
245
+ parse_dims("b s h[tp] d # ep:replicatd")
246
+
247
+ def test_duplicate_dp_alias_raises(self) -> None:
248
+ with pytest.raises(ValueError, match="Duplicate dp alias"):
249
+ parse_dims("b s h d # dp:=foo dp:=bar")
250
+
251
+
252
+ class TestResolveDimNames:
253
+ def test_no_squeeze(self) -> None:
254
+ assert resolve_dim_names("t h d") == ["t", "h", "d"]
255
+
256
+ def test_single_squeeze(self) -> None:
257
+ assert resolve_dim_names("t 1 h") == ["t", "singleton0", "h"]
258
+
259
+ def test_multiple_squeeze(self) -> None:
260
+ assert resolve_dim_names("1 t 1 h") == [
261
+ "singleton0",
262
+ "t",
263
+ "singleton1",
264
+ "h",
265
+ ]
266
+
267
+
268
+ class TestResolveDimNamesWithFused:
269
+ def test_fused_dim_uses_triple_underscore(self) -> None:
270
+ assert resolve_dim_names("t (num_heads*head_dim)") == [
271
+ "t",
272
+ "num_heads___head_dim",
273
+ ]
274
+
275
+ def test_fused_with_regular_dims(self) -> None:
276
+ assert resolve_dim_names("t (num_heads*head_dim)[tp] d") == [
277
+ "t",
278
+ "num_heads___head_dim",
279
+ "d",
280
+ ]
281
+
282
+ def test_three_way_fused(self) -> None:
283
+ assert resolve_dim_names("(a*b*c)") == ["a___b___c"]
284
+
285
+ def test_fused_with_squeeze(self) -> None:
286
+ assert resolve_dim_names("t 1 (a*b)") == ["t", "singleton0", "a___b"]
287
+
288
+
289
+ class TestResolveDimNamesWithHash:
290
+ def test_hash_stripped(self) -> None:
291
+ assert resolve_dim_names("t h # dp:=moe_dp") == ["t", "h"]
292
+
293
+
294
+ if __name__ == "__main__":
295
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_tensor_naming.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from sglang.srt.debug_utils.comparator.dims_spec import (
7
+ DimSpec,
8
+ apply_dim_names,
9
+ find_dim_index,
10
+ get_dim_names,
11
+ parse_dims,
12
+ resolve_dim_by_name,
13
+ without_dim_names,
14
+ )
15
+ from sglang.test.ci.ci_register import register_cpu_ci
16
+
17
+ register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True)
18
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
19
+
20
+
21
+ class TestFindDimIndex:
22
+ def test_found(self) -> None:
23
+ specs: list[DimSpec] = parse_dims("b s h d").dims
24
+ assert find_dim_index(specs, "s") == 1
25
+
26
+ def test_not_found(self) -> None:
27
+ specs: list[DimSpec] = parse_dims("b s h d").dims
28
+ assert find_dim_index(specs, "t") is None
29
+
30
+ def test_first_dim(self) -> None:
31
+ specs: list[DimSpec] = parse_dims("t h d").dims
32
+ assert find_dim_index(specs, "t") == 0
33
+
34
+ def test_last_dim(self) -> None:
35
+ specs: list[DimSpec] = parse_dims("b s h d").dims
36
+ assert find_dim_index(specs, "d") == 3
37
+
38
+ def test_with_modifiers(self) -> None:
39
+ specs: list[DimSpec] = parse_dims("b s[cp:zigzag] h[tp] d").dims
40
+ assert find_dim_index(specs, "h") == 2
41
+
42
+ def test_empty_list(self) -> None:
43
+ assert find_dim_index([], "t") is None
44
+
45
+
46
+ class TestResolveDimByName:
47
+ def test_resolve_found(self) -> None:
48
+ tensor: torch.Tensor = apply_dim_names(torch.randn(2, 3, 4), ["b", "s", "h"])
49
+ assert resolve_dim_by_name(tensor, "b") == 0
50
+ assert resolve_dim_by_name(tensor, "s") == 1
51
+ assert resolve_dim_by_name(tensor, "h") == 2
52
+
53
+ def test_resolve_not_found_raises(self) -> None:
54
+ tensor: torch.Tensor = apply_dim_names(torch.randn(2, 3), ["b", "s"])
55
+ with pytest.raises(ValueError, match="not in tensor names"):
56
+ resolve_dim_by_name(tensor, "h")
57
+
58
+ def test_resolve_unnamed_raises(self) -> None:
59
+ tensor: torch.Tensor = torch.randn(2, 3)
60
+ with pytest.raises(ValueError, match="no names"):
61
+ resolve_dim_by_name(tensor, "b")
62
+
63
+
64
+ class TestApplyDimNames:
65
+ def test_apply(self) -> None:
66
+ tensor: torch.Tensor = torch.randn(2, 3, 4)
67
+ named: torch.Tensor = apply_dim_names(tensor, ["b", "s", "h"])
68
+ assert get_dim_names(named) == ("b", "s", "h")
69
+ assert named.shape == (2, 3, 4)
70
+
71
+ def test_apply_preserves_data(self) -> None:
72
+ tensor: torch.Tensor = torch.randn(2, 3)
73
+ named: torch.Tensor = apply_dim_names(tensor, ["x", "y"])
74
+ assert torch.equal(without_dim_names(named), tensor)
75
+
76
+ def test_ndim_mismatch_gives_clear_error(self) -> None:
77
+ tensor: torch.Tensor = torch.randn(10, 1, 128)
78
+ with pytest.raises(
79
+ ValueError,
80
+ match=r"dims metadata mismatch.*3 dims.*shape \[10, 1, 128\].*2 names \['t', 'num_experts'\].*fix the dims string",
81
+ ):
82
+ apply_dim_names(tensor, ["t", "num_experts"])
83
+
84
+
85
+ class TestStripDimNames:
86
+ def test_strip(self) -> None:
87
+ tensor: torch.Tensor = apply_dim_names(torch.randn(2, 3), ["a", "b"])
88
+ stripped: torch.Tensor = without_dim_names(tensor)
89
+ assert get_dim_names(stripped) == (None, None)
90
+
91
+ def test_strip_already_unnamed(self) -> None:
92
+ tensor: torch.Tensor = torch.randn(2, 3)
93
+ stripped: torch.Tensor = without_dim_names(tensor)
94
+ assert get_dim_names(stripped) == (None, None)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_types.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from sglang.srt.debug_utils.comparator.dims_spec import (
6
+ BATCH_DIM_NAME,
7
+ SEQ_DIM_NAME,
8
+ TOKEN_DIM_NAME,
9
+ )
10
+ from sglang.test.ci.ci_register import register_cpu_ci
11
+
12
+ register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True)
13
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
14
+
15
+
16
+ class TestDimConstants:
17
+ def test_token_dim_name(self) -> None:
18
+ assert TOKEN_DIM_NAME == "t"
19
+
20
+ def test_batch_dim_name(self) -> None:
21
+ assert BATCH_DIM_NAME == "b"
22
+
23
+ def test_seq_dim_name(self) -> None:
24
+ assert SEQ_DIM_NAME == "s"
25
+
26
+
27
+ if __name__ == "__main__":
28
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/__init__.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/conftest.py ADDED
File without changes
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_comparator.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from sglang.srt.debug_utils.comparator.tensor_comparator.comparator import (
7
+ QUANTILE_NUMEL_THRESHOLD,
8
+ SAMPLE_DIFF_THRESHOLD,
9
+ _compute_tensor_stats,
10
+ compare_tensor_pair,
11
+ compute_diff,
12
+ compute_tensor_info,
13
+ )
14
+ from sglang.srt.debug_utils.comparator.tensor_comparator.types import DiffInfo
15
+ from sglang.test.ci.ci_register import register_cpu_ci
16
+
17
+ register_cpu_ci(est_time=20, suite="base-a-test-cpu", nightly=True)
18
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
19
+
20
+
21
+ class TestComputeTensorInfo:
22
+ def test_basic_tensor_returns_correct_shape_and_dtype(self) -> None:
23
+ tensor = torch.randn(2, 3)
24
+ info = compute_tensor_info(tensor)
25
+ assert info.shape == [2, 3]
26
+ assert info.dtype == "torch.float32"
27
+ assert info.stats.mean == pytest.approx(tensor.float().mean().item(), abs=1e-4)
28
+
29
+ def test_include_sample_false_returns_none_sample(self) -> None:
30
+ tensor = torch.randn(2, 3)
31
+ info = compute_tensor_info(tensor, include_sample=False)
32
+ assert info.sample is None
33
+
34
+ def test_include_sample_true_returns_string_sample(self) -> None:
35
+ tensor = torch.randn(2, 3)
36
+ info = compute_tensor_info(tensor, include_sample=True)
37
+ assert info.sample is not None
38
+ assert isinstance(info.sample, str)
39
+
40
+ def test_empty_tensor_stats_are_zero(self) -> None:
41
+ tensor = torch.tensor([])
42
+ info = compute_tensor_info(tensor)
43
+ assert info.stats.mean == 0.0
44
+ assert info.stats.std == 0.0
45
+ assert info.shape == [0]
46
+
47
+ def test_integer_tensor_converted_to_float_for_stats(self) -> None:
48
+ """Integer tensors should be cast to float internally for stats computation."""
49
+ tensor = torch.tensor([1, 2, 3, 4], dtype=torch.int32)
50
+ info = compute_tensor_info(tensor)
51
+ assert info.dtype == "torch.int32"
52
+ assert info.stats.mean == pytest.approx(2.5, abs=1e-4)
53
+ assert info.stats.min == pytest.approx(1.0, abs=1e-4)
54
+ assert info.stats.max == pytest.approx(4.0, abs=1e-4)
55
+
56
+ def test_bfloat16_tensor_shape_and_stats(self) -> None:
57
+ """bfloat16 tensors produce correct shape and dtype string."""
58
+ tensor = torch.ones(3, 4, dtype=torch.bfloat16)
59
+ info = compute_tensor_info(tensor)
60
+ assert info.shape == [3, 4]
61
+ assert info.dtype == "torch.bfloat16"
62
+ assert info.stats.mean == pytest.approx(1.0, abs=1e-2)
63
+
64
+ def test_multidimensional_shape(self) -> None:
65
+ """Shape is preserved for high-rank tensors."""
66
+ tensor = torch.randn(2, 3, 4, 5)
67
+ info = compute_tensor_info(tensor)
68
+ assert info.shape == [2, 3, 4, 5]
69
+
70
+ def test_scalar_tensor(self) -> None:
71
+ """Scalar (0-dim) tensor produces empty shape list."""
72
+ tensor = torch.tensor(3.14)
73
+ info = compute_tensor_info(tensor)
74
+ assert info.shape == []
75
+ assert info.stats.mean == pytest.approx(3.14, abs=1e-4)
76
+ assert info.stats.min == pytest.approx(3.14, abs=1e-4)
77
+ assert info.stats.max == pytest.approx(3.14, abs=1e-4)
78
+
79
+ def test_include_sample_true_contains_tensor_representation(self) -> None:
80
+ """Sample string should contain some recognizable tensor content."""
81
+ tensor = torch.tensor([1.0, 2.0])
82
+ info = compute_tensor_info(tensor, include_sample=True)
83
+ assert info.sample is not None
84
+ assert "1." in info.sample or "2." in info.sample
85
+
86
+ def test_percentiles_present_for_small_tensor(self) -> None:
87
+ """Small tensors (< threshold) should have percentile data."""
88
+ tensor = torch.randn(100)
89
+ info = compute_tensor_info(tensor)
90
+ assert len(info.stats.percentiles) > 0
91
+ assert 50 in info.stats.percentiles
92
+
93
+
94
+ class TestComputeTensorInfo:
95
+ def test_basic_tensor_returns_correct_shape_and_dtype(self) -> None:
96
+ tensor = torch.randn(2, 3)
97
+ info = compute_tensor_info(tensor)
98
+ assert info.shape == [2, 3]
99
+ assert info.dtype == "torch.float32"
100
+ assert info.stats.mean == pytest.approx(tensor.float().mean().item(), abs=1e-4)
101
+
102
+ def test_include_sample_false_returns_none_sample(self) -> None:
103
+ tensor = torch.randn(2, 3)
104
+ info = compute_tensor_info(tensor, include_sample=False)
105
+ assert info.sample is None
106
+
107
+ def test_include_sample_true_returns_string_sample(self) -> None:
108
+ tensor = torch.randn(2, 3)
109
+ info = compute_tensor_info(tensor, include_sample=True)
110
+ assert info.sample is not None
111
+ assert isinstance(info.sample, str)
112
+
113
+ def test_empty_tensor_stats_are_zero(self) -> None:
114
+ tensor = torch.tensor([])
115
+ info = compute_tensor_info(tensor)
116
+ assert info.stats.mean == 0.0
117
+ assert info.stats.std == 0.0
118
+ assert info.shape == [0]
119
+
120
+ def test_integer_tensor_converted_to_float_for_stats(self) -> None:
121
+ """Integer tensors should be cast to float internally for stats computation."""
122
+ tensor = torch.tensor([1, 2, 3, 4], dtype=torch.int32)
123
+ info = compute_tensor_info(tensor)
124
+ assert info.dtype == "torch.int32"
125
+ assert info.stats.mean == pytest.approx(2.5, abs=1e-4)
126
+ assert info.stats.min == pytest.approx(1.0, abs=1e-4)
127
+ assert info.stats.max == pytest.approx(4.0, abs=1e-4)
128
+
129
+ def test_bfloat16_tensor_shape_and_stats(self) -> None:
130
+ """bfloat16 tensors produce correct shape and dtype string."""
131
+ tensor = torch.ones(3, 4, dtype=torch.bfloat16)
132
+ info = compute_tensor_info(tensor)
133
+ assert info.shape == [3, 4]
134
+ assert info.dtype == "torch.bfloat16"
135
+ assert info.stats.mean == pytest.approx(1.0, abs=1e-2)
136
+
137
+ def test_multidimensional_shape(self) -> None:
138
+ """Shape is preserved for high-rank tensors."""
139
+ tensor = torch.randn(2, 3, 4, 5)
140
+ info = compute_tensor_info(tensor)
141
+ assert info.shape == [2, 3, 4, 5]
142
+
143
+ def test_scalar_tensor(self) -> None:
144
+ """Scalar (0-dim) tensor produces empty shape list."""
145
+ tensor = torch.tensor(3.14)
146
+ info = compute_tensor_info(tensor)
147
+ assert info.shape == []
148
+ assert info.stats.mean == pytest.approx(3.14, abs=1e-4)
149
+ assert info.stats.min == pytest.approx(3.14, abs=1e-4)
150
+ assert info.stats.max == pytest.approx(3.14, abs=1e-4)
151
+
152
+ def test_include_sample_true_contains_tensor_representation(self) -> None:
153
+ """Sample string should contain some recognizable tensor content."""
154
+ tensor = torch.tensor([1.0, 2.0])
155
+ info = compute_tensor_info(tensor, include_sample=True)
156
+ assert info.sample is not None
157
+ assert "1." in info.sample or "2." in info.sample
158
+
159
+ def test_percentiles_present_for_small_tensor(self) -> None:
160
+ """Small tensors (< threshold) should have percentile data."""
161
+ tensor = torch.randn(100)
162
+ info = compute_tensor_info(tensor)
163
+ assert len(info.stats.percentiles) > 0
164
+ assert 50 in info.stats.percentiles
165
+
166
+
167
+ class TestComputeTensorStats:
168
+ def test_basic_stats(self):
169
+ x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])
170
+ stats = _compute_tensor_stats(x)
171
+
172
+ assert stats.mean == pytest.approx(3.0, abs=1e-4)
173
+ assert stats.abs_mean == pytest.approx(3.0, abs=1e-4)
174
+ assert stats.std == pytest.approx(1.5811, abs=1e-3)
175
+ assert stats.min == pytest.approx(1.0, abs=1e-4)
176
+ assert stats.max == pytest.approx(5.0, abs=1e-4)
177
+
178
+ def test_abs_mean_with_negative_values(self):
179
+ x = torch.tensor([-3.0, -1.0, 1.0, 3.0])
180
+ stats = _compute_tensor_stats(x)
181
+
182
+ assert stats.mean == pytest.approx(0.0, abs=1e-4)
183
+ assert stats.abs_mean == pytest.approx(2.0, abs=1e-4)
184
+
185
+ def test_quantile_values(self):
186
+ x = torch.linspace(0.0, 100.0, steps=1000)
187
+ stats = _compute_tensor_stats(x)
188
+
189
+ assert stats.percentiles[1] == pytest.approx(1.0, abs=0.5)
190
+ assert stats.percentiles[5] == pytest.approx(5.0, abs=0.5)
191
+ assert stats.percentiles[50] == pytest.approx(50.0, abs=0.5)
192
+ assert stats.percentiles[95] == pytest.approx(95.0, abs=0.5)
193
+ assert stats.percentiles[99] == pytest.approx(99.0, abs=0.5)
194
+
195
+ def test_percentiles_exact_for_uniform_range(self):
196
+ """Percentiles of arange(0, 101) equal the percentile index exactly (linear interp)."""
197
+ x = torch.arange(0, 101, dtype=torch.float32)
198
+ stats = _compute_tensor_stats(x)
199
+
200
+ for p in (1, 5, 50, 95, 99):
201
+ assert stats.percentiles[p] == pytest.approx(float(p), abs=1e-4)
202
+
203
+ def test_percentiles_match_torch_quantile_reference(self):
204
+ """numpy-based percentiles must match torch.quantile on the same data within tight tolerance."""
205
+ torch.manual_seed(0)
206
+ x = torch.randn(5000)
207
+ stats = _compute_tensor_stats(x)
208
+
209
+ for p in (1, 5, 50, 95, 99):
210
+ expected = torch.quantile(x.float(), p / 100.0).item()
211
+ assert stats.percentiles[p] == pytest.approx(expected, abs=1e-4)
212
+
213
+ def test_large_tensor_skips_quantiles(self):
214
+ x = torch.randn(QUANTILE_NUMEL_THRESHOLD + 1)
215
+ stats = _compute_tensor_stats(x)
216
+
217
+ assert stats.mean is not None
218
+ assert stats.percentiles == {}
219
+
220
+
221
+ class TestComputeDiff:
222
+ def test_identical_tensors(self):
223
+ x = torch.ones(10, 10)
224
+ diff = compute_diff(x_baseline=x, x_target=x)
225
+
226
+ assert diff.rel_diff == pytest.approx(0.0, abs=1e-5)
227
+ assert diff.max_abs_diff == pytest.approx(0.0, abs=1e-5)
228
+ assert diff.mean_abs_diff == pytest.approx(0.0, abs=1e-5)
229
+ assert diff.abs_diff_percentiles[50] == pytest.approx(0.0, abs=1e-5)
230
+ assert diff.abs_diff_percentiles[95] == pytest.approx(0.0, abs=1e-5)
231
+ assert diff.abs_diff_percentiles[99] == pytest.approx(0.0, abs=1e-5)
232
+ assert diff.passed is True
233
+
234
+ def test_known_offset(self):
235
+ x = torch.ones(10, 10)
236
+ y = x.clone()
237
+ y[3, 7] = 1.5
238
+
239
+ diff = compute_diff(x_baseline=x, x_target=y)
240
+
241
+ assert diff.max_abs_diff == pytest.approx(0.5, abs=1e-4)
242
+ assert diff.max_diff_coord == [3, 7]
243
+ assert diff.baseline_at_max == pytest.approx(1.0, abs=1e-4)
244
+ assert diff.target_at_max == pytest.approx(1.5, abs=1e-4)
245
+ assert diff.mean_abs_diff == pytest.approx(0.5 / 100, abs=1e-4)
246
+ assert diff.abs_diff_percentiles[1] == pytest.approx(0.0, abs=1e-4)
247
+ assert diff.abs_diff_percentiles[50] == pytest.approx(0.0, abs=1e-4)
248
+ assert diff.abs_diff_percentiles[99] > 0
249
+ assert diff.passed is False
250
+
251
+ def test_large_tensor_skips_diff_quantiles(self):
252
+ x = torch.randn(QUANTILE_NUMEL_THRESHOLD + 1)
253
+ y = x + 0.001
254
+ diff = compute_diff(x_baseline=x, x_target=y)
255
+
256
+ assert diff.abs_diff_percentiles == {}
257
+
258
+ def test_rel_diff_value(self):
259
+ x = torch.tensor([1.0, 0.0])
260
+ y = torch.tensor([0.0, 1.0])
261
+ diff = compute_diff(x_baseline=x, x_target=y)
262
+
263
+ assert diff.rel_diff == pytest.approx(1.0, abs=1e-5)
264
+ assert diff.passed is False
265
+
266
+ def test_per_token_with_seq_dim(self) -> None:
267
+ """seq_dim provided → per_token_rel_diff is list[float]."""
268
+ torch.manual_seed(42)
269
+ x: torch.Tensor = torch.randn(8, 16)
270
+ y: torch.Tensor = x + torch.randn_like(x) * 0.01
271
+
272
+ diff: DiffInfo = compute_diff(
273
+ x_baseline=x, x_target=y, diff_threshold=1e-3, seq_dim=0
274
+ )
275
+
276
+ assert diff.per_token_rel_diff is not None
277
+ assert isinstance(diff.per_token_rel_diff, list)
278
+ assert len(diff.per_token_rel_diff) == 8
279
+ assert all(isinstance(v, float) for v in diff.per_token_rel_diff)
280
+
281
+ def test_per_token_without_seq_dim(self) -> None:
282
+ """No seq_dim → per_token_rel_diff is None."""
283
+ x: torch.Tensor = torch.randn(8, 16)
284
+ y: torch.Tensor = x + torch.randn_like(x) * 0.01
285
+
286
+ diff: DiffInfo = compute_diff(x_baseline=x, x_target=y, diff_threshold=1e-3)
287
+
288
+ assert diff.per_token_rel_diff is None
289
+
290
+ def test_per_token_json_roundtrip(self) -> None:
291
+ """DiffInfo with per_token_rel_diff survives JSON serialization."""
292
+ torch.manual_seed(42)
293
+ x: torch.Tensor = torch.randn(4, 8)
294
+ y: torch.Tensor = x + torch.randn_like(x) * 0.01
295
+
296
+ diff: DiffInfo = compute_diff(
297
+ x_baseline=x, x_target=y, diff_threshold=1e-3, seq_dim=0
298
+ )
299
+
300
+ json_str: str = diff.model_dump_json()
301
+ assert "per_token_rel_diff" in json_str
302
+
303
+ roundtripped: DiffInfo = DiffInfo.model_validate_json(json_str)
304
+ assert roundtripped.per_token_rel_diff is not None
305
+ assert len(roundtripped.per_token_rel_diff) == 4
306
+
307
+
308
+ class TestCompareTensors:
309
+ def test_normal(self):
310
+ x = torch.randn(5, 5)
311
+ y = x + torch.randn(5, 5) * 0.001
312
+
313
+ info = compare_tensor_pair(x_baseline=x, x_target=y, name="test")
314
+
315
+ assert info.name == "test"
316
+ assert info.baseline.shape == [5, 5]
317
+ assert info.target.shape == [5, 5]
318
+ assert info.shape_mismatch is False
319
+ assert info.diff is not None
320
+ assert info.diff_downcast is None
321
+
322
+ def test_shape_mismatch(self):
323
+ x = torch.randn(3, 4)
324
+ y = torch.randn(5, 6)
325
+
326
+ info = compare_tensor_pair(x_baseline=x, x_target=y, name="mismatch")
327
+
328
+ assert info.shape_mismatch is True
329
+ assert info.diff is None
330
+
331
+ def test_dtype_mismatch(self):
332
+ x = torch.randn(5, 5, dtype=torch.float32)
333
+ y = torch.randn(5, 5, dtype=torch.bfloat16)
334
+
335
+ info = compare_tensor_pair(x_baseline=x, x_target=y, name="dtype_test")
336
+
337
+ assert info.shape_mismatch is False
338
+ assert info.diff is not None
339
+ assert info.diff_downcast is not None
340
+ assert info.downcast_dtype == "torch.bfloat16"
341
+
342
+ def test_shape_unification(self):
343
+ torch.manual_seed(0)
344
+ core = torch.randn(4, 8)
345
+ x = core.unsqueeze(0).unsqueeze(0) # [1, 1, 4, 8]
346
+ y = core.clone() # [4, 8]
347
+
348
+ info = compare_tensor_pair(x_baseline=x, x_target=y, name="unify")
349
+
350
+ assert info.baseline.shape == [1, 1, 4, 8]
351
+ assert info.unified_shape == [4, 8]
352
+ assert info.shape_mismatch is False
353
+ assert info.diff is not None
354
+ assert info.diff.max_abs_diff == pytest.approx(0.0, abs=1e-5)
355
+
356
+ def test_sample_generated_when_large_diff(self):
357
+ x = torch.zeros(5, 5)
358
+ y = torch.ones(5, 5)
359
+
360
+ info = compare_tensor_pair(x_baseline=x, x_target=y, name="big_diff")
361
+
362
+ assert info.diff is not None
363
+ assert info.diff.max_abs_diff > SAMPLE_DIFF_THRESHOLD
364
+ assert info.baseline.sample is not None
365
+ assert info.target.sample is not None
366
+
367
+ def test_no_sample_when_small_diff(self):
368
+ x = torch.ones(5, 5)
369
+ y = x + 1e-5
370
+
371
+ info = compare_tensor_pair(x_baseline=x, x_target=y, name="tiny_diff")
372
+
373
+ assert info.diff is not None
374
+ assert info.diff.max_abs_diff < SAMPLE_DIFF_THRESHOLD
375
+ assert info.baseline.sample is None
376
+ assert info.target.sample is None
377
+
378
+
379
+ if __name__ == "__main__":
380
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_formatter.py ADDED
@@ -0,0 +1,1113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ from registered.debug_utils.comparator.testing_helpers import (
5
+ assert_rich_tags_balanced,
6
+ )
7
+ from registered.debug_utils.comparator.testing_helpers import make_diff as _make_diff
8
+ from registered.debug_utils.comparator.testing_helpers import make_stats as _make_stats
9
+ from registered.debug_utils.comparator.testing_helpers import (
10
+ make_tensor_info as _make_tensor_info,
11
+ )
12
+
13
+ from sglang.srt.debug_utils.comparator.aligner.axis_aligner import AxisAlignerPlan
14
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.traced_types import (
15
+ TracedAlignerPlan,
16
+ TracedSidePlan,
17
+ TracedStepPlan,
18
+ TracedSubPlan,
19
+ )
20
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import (
21
+ AlignerPerStepPlan,
22
+ AlignerPlan,
23
+ )
24
+ from sglang.srt.debug_utils.comparator.aligner.reorderer.types import (
25
+ ReordererPlan,
26
+ ZigzagToNaturalParams,
27
+ )
28
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import (
29
+ TokenAlignerPlan,
30
+ TokenLocator,
31
+ )
32
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import (
33
+ ConcatParams,
34
+ UnsharderPlan,
35
+ )
36
+ from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis, TokenLayout
37
+ from sglang.srt.debug_utils.comparator.output_types import (
38
+ BundleFileInfo,
39
+ BundleSideInfo,
40
+ ComparisonTensorRecord,
41
+ ReplicatedCheckResult,
42
+ ShapeSnapshot,
43
+ )
44
+ from sglang.srt.debug_utils.comparator.tensor_comparator.formatter import (
45
+ _format_abs_diff_percentiles_rich,
46
+ _format_bundle_section,
47
+ _format_plan_section_rich,
48
+ _format_stats_rich,
49
+ format_comparison,
50
+ format_comparison_rich,
51
+ format_replicated_checks,
52
+ )
53
+ from sglang.srt.debug_utils.comparator.tensor_comparator.types import (
54
+ DiffInfo,
55
+ TensorComparisonInfo,
56
+ TensorStats,
57
+ )
58
+ from sglang.srt.debug_utils.comparator.utils import Pair
59
+ from sglang.test.ci.ci_register import register_cpu_ci
60
+
61
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
62
+
63
+ _DEFAULT_PERCENTILE_LINES: list[str] = [
64
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]",
65
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]",
66
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]",
67
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]",
68
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]",
69
+ ]
70
+
71
+ _DEFAULT_PERCENTILE_LINES: list[str] = [
72
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]",
73
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]",
74
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]",
75
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]",
76
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]",
77
+ ]
78
+
79
+
80
+ # Snapshot strings below are intentionally spelled out in full per test.
81
+ # The shared skeleton (stats block, diff block) looks duplicated, but keeping
82
+ # each test self-contained makes failures immediately readable without chasing
83
+ # helper functions. Do not extract common fragments.
84
+ class TestFormatComparison:
85
+ def test_normal(self):
86
+ info = TensorComparisonInfo(
87
+ name="test",
88
+ baseline=_make_tensor_info(
89
+ stats=_make_stats(mean=0.1, std=1.0, min=-2.0, max=2.0),
90
+ ),
91
+ target=_make_tensor_info(
92
+ stats=_make_stats(mean=0.1001, std=1.0001, min=-2.0001, max=2.0001),
93
+ ),
94
+ unified_shape=[4, 8],
95
+ shape_mismatch=False,
96
+ diff=_make_diff(),
97
+ )
98
+
99
+ assert format_comparison(info) == (
100
+ "Raw [shape] [4, 8] vs [4, 8]\t"
101
+ "[dtype] torch.float32 vs torch.float32\n"
102
+ "After unify [shape] [4, 8] vs [4, 8]\t"
103
+ "[dtype] torch.float32 vs torch.float32\n"
104
+ "[mean] 0.1000 vs 0.1001 (diff: 0.0001)\n"
105
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
106
+ "[std] 1.0000 vs 1.0001 (diff: 0.0001)\n"
107
+ "[min] -2.0000 vs -2.0001 (diff: -0.0001)\n"
108
+ "[max] 2.0000 vs 2.0001 (diff: 0.0001)\n"
109
+ "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n"
110
+ "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n"
111
+ "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n"
112
+ "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n"
113
+ "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n"
114
+ "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n"
115
+ "max_abs_diff happens at coord=[2, 3] with "
116
+ "baseline=1.0 target=1.0005\n"
117
+ "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005"
118
+ )
119
+
120
+ def test_shape_mismatch(self):
121
+ info = TensorComparisonInfo(
122
+ name="mismatch",
123
+ baseline=_make_tensor_info(shape=[3, 4]),
124
+ target=_make_tensor_info(shape=[5, 6]),
125
+ unified_shape=[3, 4],
126
+ shape_mismatch=True,
127
+ )
128
+
129
+ assert format_comparison(info) == (
130
+ "Raw [shape] [3, 4] vs [5, 6]\t"
131
+ "[dtype] torch.float32 vs torch.float32\n"
132
+ "After unify [shape] [3, 4] vs [5, 6]\t"
133
+ "[dtype] torch.float32 vs torch.float32\n"
134
+ "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n"
135
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
136
+ "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n"
137
+ "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n"
138
+ "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n"
139
+ "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n"
140
+ "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n"
141
+ "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n"
142
+ "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n"
143
+ "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n"
144
+ "⚠️ Shape mismatch"
145
+ )
146
+
147
+ def test_with_downcast(self):
148
+ info = TensorComparisonInfo(
149
+ name="downcast",
150
+ baseline=_make_tensor_info(),
151
+ target=_make_tensor_info(dtype="torch.bfloat16"),
152
+ unified_shape=[4, 8],
153
+ shape_mismatch=False,
154
+ diff=_make_diff(
155
+ rel_diff=0.002, max_abs_diff=0.005, mean_abs_diff=0.001, passed=False
156
+ ),
157
+ diff_downcast=_make_diff(
158
+ rel_diff=0.0001, max_abs_diff=0.0005, mean_abs_diff=0.0002, passed=True
159
+ ),
160
+ downcast_dtype="torch.bfloat16",
161
+ )
162
+
163
+ assert format_comparison(info) == (
164
+ "Raw [shape] [4, 8] vs [4, 8]\t"
165
+ "[🟠dtype] torch.float32 vs torch.bfloat16\n"
166
+ "After unify [shape] [4, 8] vs [4, 8]\t"
167
+ "[dtype] torch.float32 vs torch.bfloat16\n"
168
+ "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n"
169
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
170
+ "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n"
171
+ "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n"
172
+ "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n"
173
+ "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n"
174
+ "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n"
175
+ "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n"
176
+ "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n"
177
+ "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n"
178
+ "❌ rel_diff=0.002\tmax_abs_diff=0.005\tmean_abs_diff=0.001\n"
179
+ "max_abs_diff happens at coord=[2, 3] with "
180
+ "baseline=1.0 target=1.0005\n"
181
+ "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005\n"
182
+ "When downcast to torch.bfloat16: "
183
+ "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n"
184
+ "max_abs_diff happens at coord=[2, 3] with "
185
+ "baseline=1.0 target=1.0005\n"
186
+ "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005"
187
+ )
188
+
189
+ def test_with_shape_unification(self):
190
+ info = TensorComparisonInfo(
191
+ name="unify",
192
+ baseline=_make_tensor_info(shape=[1, 1, 4, 8]),
193
+ target=_make_tensor_info(),
194
+ unified_shape=[4, 8],
195
+ shape_mismatch=False,
196
+ diff=_make_diff(),
197
+ )
198
+
199
+ assert format_comparison(info) == (
200
+ "Raw [shape] [1, 1, 4, 8] vs [4, 8]\t"
201
+ "[dtype] torch.float32 vs torch.float32\n"
202
+ "Unify shape: [1, 1, 4, 8] -> [4, 8] "
203
+ "(to match [4, 8])\n"
204
+ "After unify [shape] [4, 8] vs [4, 8]\t"
205
+ "[dtype] torch.float32 vs torch.float32\n"
206
+ "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n"
207
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
208
+ "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n"
209
+ "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n"
210
+ "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n"
211
+ "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n"
212
+ "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n"
213
+ "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n"
214
+ "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n"
215
+ "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n"
216
+ "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n"
217
+ "max_abs_diff happens at coord=[2, 3] with "
218
+ "baseline=1.0 target=1.0005\n"
219
+ "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005"
220
+ )
221
+
222
+ def test_with_samples(self):
223
+ info = TensorComparisonInfo(
224
+ name="samples",
225
+ baseline=_make_tensor_info(sample="tensor([0.1, 0.2, ...])"),
226
+ target=_make_tensor_info(sample="tensor([0.1, 0.3, ...])"),
227
+ unified_shape=[4, 8],
228
+ shape_mismatch=False,
229
+ diff=_make_diff(),
230
+ )
231
+
232
+ assert format_comparison(info) == (
233
+ "Raw [shape] [4, 8] vs [4, 8]\t"
234
+ "[dtype] torch.float32 vs torch.float32\n"
235
+ "After unify [shape] [4, 8] vs [4, 8]\t"
236
+ "[dtype] torch.float32 vs torch.float32\n"
237
+ "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n"
238
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
239
+ "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n"
240
+ "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n"
241
+ "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n"
242
+ "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n"
243
+ "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n"
244
+ "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n"
245
+ "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n"
246
+ "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n"
247
+ "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n"
248
+ "max_abs_diff happens at coord=[2, 3] with "
249
+ "baseline=1.0 target=1.0005\n"
250
+ "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005\n"
251
+ "x_baseline(sample)=tensor([0.1, 0.2, ...])\n"
252
+ "x_target(sample)=tensor([0.1, 0.3, ...])"
253
+ )
254
+
255
+ def test_empty_percentiles(self):
256
+ stats_no_quantiles = _make_stats(percentiles={})
257
+
258
+ info = TensorComparisonInfo(
259
+ name="no_quantiles",
260
+ baseline=_make_tensor_info(stats=stats_no_quantiles),
261
+ target=_make_tensor_info(stats=stats_no_quantiles),
262
+ unified_shape=[4, 8],
263
+ shape_mismatch=False,
264
+ diff=_make_diff(abs_diff_percentiles={}),
265
+ )
266
+
267
+ assert format_comparison(info) == (
268
+ "Raw [shape] [4, 8] vs [4, 8]\t"
269
+ "[dtype] torch.float32 vs torch.float32\n"
270
+ "After unify [shape] [4, 8] vs [4, 8]\t"
271
+ "[dtype] torch.float32 vs torch.float32\n"
272
+ "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n"
273
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
274
+ "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n"
275
+ "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n"
276
+ "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n"
277
+ "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n"
278
+ "max_abs_diff happens at coord=[2, 3] with "
279
+ "baseline=1.0 target=1.0005"
280
+ )
281
+
282
+
283
+ def _make_comparison_record(
284
+ name: str = "hidden_states",
285
+ shape: list[int] | None = None,
286
+ dtype: str = "torch.float32",
287
+ diff: DiffInfo | None = None,
288
+ shape_mismatch: bool = False,
289
+ sample: str | None = None,
290
+ diff_downcast: DiffInfo | None = None,
291
+ downcast_dtype: str | None = None,
292
+ replicated_checks: list[ReplicatedCheckResult] | None = None,
293
+ raw_bundle_info: Pair[BundleSideInfo] | None = None,
294
+ traced_plan: TracedAlignerPlan | None = None,
295
+ ) -> ComparisonTensorRecord:
296
+ s: list[int] = shape if shape is not None else [4, 8]
297
+ return ComparisonTensorRecord(
298
+ name=name,
299
+ baseline=_make_tensor_info(shape=s, dtype=dtype, sample=sample),
300
+ target=_make_tensor_info(shape=s, dtype=dtype, sample=sample),
301
+ unified_shape=s,
302
+ shape_mismatch=shape_mismatch,
303
+ diff=diff,
304
+ diff_downcast=diff_downcast,
305
+ downcast_dtype=downcast_dtype,
306
+ replicated_checks=replicated_checks or [],
307
+ raw_bundle_info=raw_bundle_info,
308
+ traced_plan=traced_plan,
309
+ )
310
+
311
+
312
+ def _make_bundle_side_info(
313
+ num_files: int = 2,
314
+ shape: list[int] | None = None,
315
+ dtype: str = "torch.float32",
316
+ dims: str | None = None,
317
+ with_parallel_info: bool = False,
318
+ ) -> BundleSideInfo:
319
+ s: list[int] = shape if shape is not None else [2, 4096]
320
+ files: list[BundleFileInfo] = []
321
+ for i in range(num_files):
322
+ par: dict[str, str] | None = (
323
+ {"tp": f"{i}/{num_files}"} if with_parallel_info else None
324
+ )
325
+ files.append(BundleFileInfo(shape=s, dtype=dtype, rank=i, parallel_info=par))
326
+ return BundleSideInfo(num_files=num_files, files=files, dims=dims)
327
+
328
+
329
+ def _make_simple_aligner_plan(
330
+ *,
331
+ with_unsharder: bool = False,
332
+ with_reorderer: bool = False,
333
+ with_token_aligner: bool = False,
334
+ with_axis_aligner: bool = False,
335
+ axis_aligner_noop: bool = False,
336
+ ) -> AlignerPlan:
337
+ baseline_plans: list[AlignerPerStepPlan] = []
338
+ target_plans: list[AlignerPerStepPlan] = []
339
+
340
+ if with_unsharder:
341
+ unsharder: UnsharderPlan = UnsharderPlan(
342
+ axis=ParallelAxis.TP,
343
+ params=ConcatParams(dim_name="h"),
344
+ groups=[[0, 1]],
345
+ )
346
+ target_plans.append(
347
+ AlignerPerStepPlan(
348
+ step=0, input_object_indices=[0, 1], sub_plans=[unsharder]
349
+ )
350
+ )
351
+
352
+ if with_reorderer:
353
+ reorderer: ReordererPlan = ReordererPlan(
354
+ params=ZigzagToNaturalParams(dim_name="s", cp_size=2),
355
+ )
356
+ target_plans.append(
357
+ AlignerPerStepPlan(step=0, input_object_indices=[0], sub_plans=[reorderer])
358
+ )
359
+
360
+ token_aligner_plan: TokenAlignerPlan | None = None
361
+ if with_token_aligner:
362
+ token_aligner_plan = TokenAlignerPlan(
363
+ locators=Pair(
364
+ x=TokenLocator(steps=[0, 0, 0], token_index_in_step=[0, 1, 2]),
365
+ y=TokenLocator(steps=[0, 0, 0], token_index_in_step=[0, 1, 2]),
366
+ ),
367
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.T),
368
+ )
369
+
370
+ axis_aligner_plan: AxisAlignerPlan | None = None
371
+ if with_axis_aligner:
372
+ if axis_aligner_noop:
373
+ axis_aligner_plan = AxisAlignerPlan(pattern=Pair(x=None, y=None))
374
+ else:
375
+ axis_aligner_plan = AxisAlignerPlan(
376
+ pattern=Pair(x="b s d -> s b d", y=None)
377
+ )
378
+
379
+ return AlignerPlan(
380
+ per_step_plans=Pair(x=baseline_plans, y=target_plans),
381
+ token_aligner_plan=token_aligner_plan,
382
+ axis_aligner_plan=axis_aligner_plan,
383
+ )
384
+
385
+
386
+ def _make_traced_plan(
387
+ plan: AlignerPlan,
388
+ *,
389
+ target_input_shapes: list[list[int]] | None = None,
390
+ target_output_shapes: list[list[int]] | None = None,
391
+ ) -> TracedAlignerPlan:
392
+ """Build a TracedAlignerPlan by attaching snapshots to target sub_plans."""
393
+ baseline_traced_steps: list[TracedStepPlan] = [
394
+ TracedStepPlan(
395
+ step=sp.step,
396
+ input_object_indices=sp.input_object_indices,
397
+ sub_plans=[TracedSubPlan(plan=sub) for sub in sp.sub_plans],
398
+ )
399
+ for sp in plan.per_step_plans.x
400
+ ]
401
+
402
+ target_traced_steps: list[TracedStepPlan] = []
403
+ for sp in plan.per_step_plans.y:
404
+ traced_subs: list[TracedSubPlan] = []
405
+ for sub in sp.sub_plans:
406
+ snapshot: ShapeSnapshot | None = None
407
+ if target_input_shapes is not None or target_output_shapes is not None:
408
+ snapshot = ShapeSnapshot(
409
+ input_shapes=target_input_shapes or [[2, 4096], [2, 4096]],
410
+ output_shapes=target_output_shapes or [[4, 4096]],
411
+ )
412
+ traced_subs.append(TracedSubPlan(plan=sub, snapshot=snapshot))
413
+ target_traced_steps.append(
414
+ TracedStepPlan(
415
+ step=sp.step,
416
+ input_object_indices=sp.input_object_indices,
417
+ sub_plans=traced_subs,
418
+ )
419
+ )
420
+
421
+ return TracedAlignerPlan(
422
+ plan=plan,
423
+ per_side=Pair(
424
+ x=TracedSidePlan(step_plans=baseline_traced_steps),
425
+ y=TracedSidePlan(step_plans=target_traced_steps),
426
+ ),
427
+ )
428
+
429
+
430
+ # ---------------------------------------------------------------------------
431
+ # Rich format snapshot tests
432
+ # ---------------------------------------------------------------------------
433
+
434
+
435
+ class TestFormatComparisonRichMinimal:
436
+ """format_comparison_rich() with verbosity='minimal'."""
437
+
438
+ def test_passed(self) -> None:
439
+ record: ComparisonTensorRecord = _make_comparison_record(
440
+ diff=_make_diff(rel_diff=1e-4, passed=True),
441
+ )
442
+ result: str = format_comparison_rich(record, verbosity="minimal")
443
+ assert_rich_tags_balanced(result)
444
+
445
+ assert result == (
446
+ "[green]✅[/] [bold green]hidden_states [/] "
447
+ "rel_diff=1.00e-04"
448
+ )
449
+
450
+ def test_failed(self) -> None:
451
+ record: ComparisonTensorRecord = _make_comparison_record(
452
+ diff=_make_diff(rel_diff=0.5, passed=False),
453
+ )
454
+ result: str = format_comparison_rich(record, verbosity="minimal")
455
+ assert_rich_tags_balanced(result)
456
+
457
+ assert result == (
458
+ "[red]❌[/] [bold red]hidden_states [/] "
459
+ "rel_diff=5.00e-01"
460
+ )
461
+
462
+ def test_shape_mismatch(self) -> None:
463
+ record: ComparisonTensorRecord = _make_comparison_record(
464
+ shape_mismatch=True,
465
+ )
466
+ result: str = format_comparison_rich(record, verbosity="minimal")
467
+ assert_rich_tags_balanced(result)
468
+
469
+ assert result == (
470
+ "[red]❌[/] [bold red]hidden_states [/] "
471
+ "[yellow]shape mismatch[/]"
472
+ )
473
+
474
+ def test_no_diff(self) -> None:
475
+ record: ComparisonTensorRecord = _make_comparison_record()
476
+ result: str = format_comparison_rich(record, verbosity="minimal")
477
+ assert_rich_tags_balanced(result)
478
+
479
+ assert result == ("[red]❌[/] [bold red]hidden_states [/]")
480
+
481
+
482
+ class TestFormatComparisonRichNormal:
483
+ """format_comparison_rich() with verbosity='normal'."""
484
+
485
+ def test_passed(self) -> None:
486
+ record: ComparisonTensorRecord = _make_comparison_record(
487
+ diff=_make_diff(rel_diff=1e-4, passed=True),
488
+ )
489
+ result: str = format_comparison_rich(record, verbosity="normal")
490
+ assert_rich_tags_balanced(result)
491
+
492
+ assert result == (
493
+ "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n"
494
+ " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n"
495
+ " [dim]Aligned[/]\n"
496
+ " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n"
497
+ " [dim]Stats[/]\n"
498
+ " [dim] baseline target Δ[/]\n"
499
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
500
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n"
501
+ " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n"
502
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n"
503
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n"
504
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
505
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n"
506
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]"
507
+ )
508
+
509
+ def test_failed(self) -> None:
510
+ record: ComparisonTensorRecord = _make_comparison_record(
511
+ diff=_make_diff(
512
+ rel_diff=0.5, max_abs_diff=1.0, mean_abs_diff=0.3, passed=False
513
+ ),
514
+ )
515
+ result: str = format_comparison_rich(record, verbosity="normal")
516
+ assert_rich_tags_balanced(result)
517
+
518
+ assert result == (
519
+ "[red]❌[/] [bold red]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n"
520
+ " [bold red]rel_diff=5.00e-01[/] max_abs=1.00e+00 mean_abs=3.00e-01\n"
521
+ " max_abs @ [2, 3]: baseline=1.0 target=1.0005\n"
522
+ " [dim]Aligned[/]\n"
523
+ " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n"
524
+ " [dim]Stats[/]\n"
525
+ " [dim] baseline target Δ[/]\n"
526
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
527
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n"
528
+ " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n"
529
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n"
530
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n"
531
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
532
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n"
533
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n"
534
+ " [dim]Abs Diff Percentiles[/]\n"
535
+ " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04"
536
+ )
537
+
538
+ def test_shape_mismatch(self) -> None:
539
+ record: ComparisonTensorRecord = _make_comparison_record(
540
+ shape_mismatch=True,
541
+ )
542
+ result: str = format_comparison_rich(record, verbosity="normal")
543
+ assert_rich_tags_balanced(result)
544
+
545
+ assert result == (
546
+ "[red]❌[/] [bold red]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n"
547
+ " [yellow]⚠ Shape mismatch[/]\n"
548
+ " [dim]Aligned[/]\n"
549
+ " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n"
550
+ " [dim]Stats[/]\n"
551
+ " [dim] baseline target Δ[/]\n"
552
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
553
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n"
554
+ " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n"
555
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n"
556
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n"
557
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
558
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n"
559
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]"
560
+ )
561
+
562
+ def test_with_downcast(self) -> None:
563
+ record: ComparisonTensorRecord = _make_comparison_record(
564
+ diff=_make_diff(rel_diff=0.01, passed=False),
565
+ diff_downcast=_make_diff(rel_diff=1e-5, passed=True),
566
+ downcast_dtype="torch.bfloat16",
567
+ )
568
+ result: str = format_comparison_rich(record, verbosity="normal")
569
+ assert_rich_tags_balanced(result)
570
+
571
+ assert result == (
572
+ "[red]❌[/] [bold red]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n"
573
+ " [bold red]rel_diff=1.00e-02[/] max_abs=5.00e-04 mean_abs=2.00e-04\n"
574
+ " max_abs @ [2, 3]: baseline=1.0 target=1.0005\n"
575
+ " [green]✅[/] downcast to torch.bfloat16: rel_diff=1.00e-05\n"
576
+ " [dim]Aligned[/]\n"
577
+ " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n"
578
+ " [dim]Stats[/]\n"
579
+ " [dim] baseline target Δ[/]\n"
580
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
581
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n"
582
+ " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n"
583
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n"
584
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n"
585
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
586
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n"
587
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n"
588
+ " [dim]Abs Diff Percentiles[/]\n"
589
+ " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04"
590
+ )
591
+
592
+ def test_with_bundle_info(self) -> None:
593
+ bundle_info: Pair[BundleSideInfo] = Pair(
594
+ x=_make_bundle_side_info(num_files=2, dims="b s h(tp) d"),
595
+ y=_make_bundle_side_info(num_files=2, dims="b s h(tp) d"),
596
+ )
597
+ record: ComparisonTensorRecord = _make_comparison_record(
598
+ diff=_make_diff(passed=True),
599
+ raw_bundle_info=bundle_info,
600
+ )
601
+ result: str = format_comparison_rich(record, verbosity="normal")
602
+ assert_rich_tags_balanced(result)
603
+
604
+ assert result == (
605
+ "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n"
606
+ " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n"
607
+ " [dim]Bundle[/]\n"
608
+ " baseline [cyan]2 files[/] × [2, 4096] float32 [dim]dims: b s h(tp) d[/]\n"
609
+ " target [cyan]2 files[/] × [2, 4096] float32 [dim]dims: b s h(tp) d[/]\n"
610
+ " [dim]Aligned[/]\n"
611
+ " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n"
612
+ " [dim]Stats[/]\n"
613
+ " [dim] baseline target Δ[/]\n"
614
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
615
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n"
616
+ " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n"
617
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n"
618
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n"
619
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
620
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n"
621
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]"
622
+ )
623
+
624
+ def test_with_plan(self) -> None:
625
+ plan: AlignerPlan = _make_simple_aligner_plan(with_unsharder=True)
626
+ record: ComparisonTensorRecord = _make_comparison_record(
627
+ diff=_make_diff(passed=True),
628
+ traced_plan=_make_traced_plan(plan),
629
+ )
630
+ result: str = format_comparison_rich(record, verbosity="normal")
631
+ assert_rich_tags_balanced(result)
632
+
633
+ assert result == (
634
+ "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n"
635
+ " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n"
636
+ " [dim]Plan[/]\n"
637
+ " baseline [dim](passthrough)[/]\n"
638
+ " target [magenta]unsharder(tp)[/]\n"
639
+ " [dim]Aligned[/]\n"
640
+ " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n"
641
+ " [dim]Stats[/]\n"
642
+ " [dim] baseline target Δ[/]\n"
643
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
644
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n"
645
+ " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n"
646
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n"
647
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n"
648
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
649
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n"
650
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]"
651
+ )
652
+
653
+
654
+ class TestFormatComparisonRichVerbose:
655
+ """format_comparison_rich() with verbosity='verbose'."""
656
+
657
+ def test_passed_full_detail(self) -> None:
658
+ record: ComparisonTensorRecord = _make_comparison_record(
659
+ diff=_make_diff(rel_diff=1e-4, passed=True),
660
+ sample="tensor([0.1, 0.2, ...])",
661
+ )
662
+ result: str = format_comparison_rich(record, verbosity="verbose")
663
+ assert_rich_tags_balanced(result)
664
+
665
+ assert result == (
666
+ "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n"
667
+ " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n"
668
+ " [dim]Aligned[/]\n"
669
+ " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n"
670
+ " [dim]Stats[/]\n"
671
+ " [dim] baseline target Δ[/]\n"
672
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
673
+ " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]\n"
674
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n"
675
+ " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]\n"
676
+ " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]\n"
677
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n"
678
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n"
679
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
680
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n"
681
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n"
682
+ " [dim]Abs Diff Percentiles[/]\n"
683
+ " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04\n"
684
+ " [dim]Samples[/]\n"
685
+ " baseline tensor([0.1, 0.2, ...])\n"
686
+ " target tensor([0.1, 0.2, ...])"
687
+ )
688
+
689
+ def test_with_bundle_verbose(self) -> None:
690
+ bundle_info: Pair[BundleSideInfo] = Pair(
691
+ x=_make_bundle_side_info(num_files=2, with_parallel_info=True),
692
+ y=_make_bundle_side_info(num_files=2, with_parallel_info=True),
693
+ )
694
+ record: ComparisonTensorRecord = _make_comparison_record(
695
+ diff=_make_diff(passed=True),
696
+ raw_bundle_info=bundle_info,
697
+ )
698
+ result: str = format_comparison_rich(record, verbosity="verbose")
699
+ assert_rich_tags_balanced(result)
700
+
701
+ assert result == (
702
+ "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n"
703
+ " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n"
704
+ " [dim]Bundle[/]\n"
705
+ " baseline [cyan]2 files[/] float32\n"
706
+ " [0] [2, 4096] rank=0 tp=0/2\n"
707
+ " [1] [2, 4096] rank=1 tp=1/2\n"
708
+ " target [cyan]2 files[/] float32\n"
709
+ " [0] [2, 4096] rank=0 tp=0/2\n"
710
+ " [1] [2, 4096] rank=1 tp=1/2\n"
711
+ " [dim]Aligned[/]\n"
712
+ " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n"
713
+ " [dim]Stats[/]\n"
714
+ " [dim] baseline target Δ[/]\n"
715
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
716
+ " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]\n"
717
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n"
718
+ " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]\n"
719
+ " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]\n"
720
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n"
721
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n"
722
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
723
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n"
724
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n"
725
+ " [dim]Abs Diff Percentiles[/]\n"
726
+ " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04"
727
+ )
728
+
729
+ def test_with_plan_and_traces(self) -> None:
730
+ plan: AlignerPlan = _make_simple_aligner_plan(with_unsharder=True)
731
+ record: ComparisonTensorRecord = _make_comparison_record(
732
+ diff=_make_diff(passed=True),
733
+ traced_plan=_make_traced_plan(
734
+ plan,
735
+ target_input_shapes=[[2, 4096], [2, 4096]],
736
+ target_output_shapes=[[4, 4096]],
737
+ ),
738
+ )
739
+ result: str = format_comparison_rich(record, verbosity="verbose")
740
+ assert_rich_tags_balanced(result)
741
+
742
+ assert result == (
743
+ "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n"
744
+ " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n"
745
+ " [dim]Plan[/]\n"
746
+ " baseline [dim](passthrough)[/]\n"
747
+ " target [magenta]unsharder(tp)[/] (2×[2, 4096] → 1×[4, 4096])\n"
748
+ " [dim]Aligned[/]\n"
749
+ " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n"
750
+ " [dim]Stats[/]\n"
751
+ " [dim] baseline target Δ[/]\n"
752
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
753
+ " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]\n"
754
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n"
755
+ " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]\n"
756
+ " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]\n"
757
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n"
758
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n"
759
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n"
760
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n"
761
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n"
762
+ " [dim]Abs Diff Percentiles[/]\n"
763
+ " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04"
764
+ )
765
+
766
+
767
+ class TestFormatBundleSection:
768
+ """_format_bundle_section() snapshot tests."""
769
+
770
+ def test_single_shape(self) -> None:
771
+ bundle: Pair[BundleSideInfo] = Pair(
772
+ x=_make_bundle_side_info(num_files=2, shape=[2, 4096]),
773
+ y=_make_bundle_side_info(num_files=2, shape=[2, 4096]),
774
+ )
775
+ lines: list[str] = _format_bundle_section(bundle)
776
+
777
+ assert lines == [
778
+ " baseline [cyan]2 files[/] × [2, 4096] float32",
779
+ " target [cyan]2 files[/] × [2, 4096] float32",
780
+ ]
781
+
782
+ def test_mixed_shapes(self) -> None:
783
+ side: BundleSideInfo = BundleSideInfo(
784
+ num_files=2,
785
+ files=[
786
+ BundleFileInfo(shape=[2, 4096], dtype="torch.float32", rank=0),
787
+ BundleFileInfo(shape=[3, 4096], dtype="torch.float32", rank=1),
788
+ ],
789
+ )
790
+ bundle: Pair[BundleSideInfo] = Pair(x=side, y=side)
791
+ lines: list[str] = _format_bundle_section(bundle)
792
+
793
+ assert lines == [
794
+ " baseline [cyan]2 files[/] × mixed shapes float32",
795
+ " target [cyan]2 files[/] × mixed shapes float32",
796
+ ]
797
+
798
+ def test_no_files(self) -> None:
799
+ empty: BundleSideInfo = BundleSideInfo(num_files=0, files=[])
800
+ bundle: Pair[BundleSideInfo] = Pair(x=empty, y=empty)
801
+ lines: list[str] = _format_bundle_section(bundle)
802
+
803
+ assert lines == [
804
+ " baseline [dim](no files)[/]",
805
+ " target [dim](no files)[/]",
806
+ ]
807
+
808
+ def test_with_dims(self) -> None:
809
+ bundle: Pair[BundleSideInfo] = Pair(
810
+ x=_make_bundle_side_info(num_files=1, dims="b s h(tp) d"),
811
+ y=_make_bundle_side_info(num_files=1, dims="b s h(tp) d"),
812
+ )
813
+ lines: list[str] = _format_bundle_section(bundle)
814
+
815
+ assert lines == [
816
+ " baseline [cyan]1 files[/] × [2, 4096] float32 [dim]dims: b s h(tp) d[/]",
817
+ " target [cyan]1 files[/] × [2, 4096] float32 [dim]dims: b s h(tp) d[/]",
818
+ ]
819
+
820
+
821
+ class TestFormatBundleSectionVerbose:
822
+ """_format_bundle_section(verbose=True) snapshot tests."""
823
+
824
+ def test_per_file_listing(self) -> None:
825
+ bundle: Pair[BundleSideInfo] = Pair(
826
+ x=_make_bundle_side_info(num_files=2, with_parallel_info=True),
827
+ y=_make_bundle_side_info(num_files=2, with_parallel_info=True),
828
+ )
829
+ lines: list[str] = _format_bundle_section(bundle, verbose=True)
830
+
831
+ assert lines == [
832
+ " baseline [cyan]2 files[/] float32",
833
+ " [0] [2, 4096] rank=0 tp=0/2",
834
+ " [1] [2, 4096] rank=1 tp=1/2",
835
+ " target [cyan]2 files[/] float32",
836
+ " [0] [2, 4096] rank=0 tp=0/2",
837
+ " [1] [2, 4096] rank=1 tp=1/2",
838
+ ]
839
+
840
+ def test_no_files(self) -> None:
841
+ empty: BundleSideInfo = BundleSideInfo(num_files=0, files=[])
842
+ bundle: Pair[BundleSideInfo] = Pair(x=empty, y=empty)
843
+ lines: list[str] = _format_bundle_section(bundle, verbose=True)
844
+
845
+ assert lines == [
846
+ " baseline [dim](no files)[/]",
847
+ " target [dim](no files)[/]",
848
+ ]
849
+
850
+
851
+ class TestFormatPlanSectionRich:
852
+ """_format_plan_section_rich() snapshot tests."""
853
+
854
+ def test_passthrough(self) -> None:
855
+ plan: AlignerPlan = _make_simple_aligner_plan()
856
+ traced: TracedAlignerPlan = _make_traced_plan(plan)
857
+ lines: list[str] = _format_plan_section_rich(traced_plan=traced)
858
+
859
+ assert lines == [
860
+ " baseline [dim](passthrough)[/]",
861
+ " target [dim](passthrough)[/]",
862
+ ]
863
+
864
+ def test_unsharder_op(self) -> None:
865
+ plan: AlignerPlan = _make_simple_aligner_plan(with_unsharder=True)
866
+ traced: TracedAlignerPlan = _make_traced_plan(plan)
867
+ lines: list[str] = _format_plan_section_rich(traced_plan=traced)
868
+
869
+ assert lines == [
870
+ " baseline [dim](passthrough)[/]",
871
+ " target [magenta]unsharder(tp)[/]",
872
+ ]
873
+
874
+ def test_reorderer_op(self) -> None:
875
+ plan: AlignerPlan = _make_simple_aligner_plan(with_reorderer=True)
876
+ traced: TracedAlignerPlan = _make_traced_plan(plan)
877
+ lines: list[str] = _format_plan_section_rich(traced_plan=traced)
878
+
879
+ assert lines == [
880
+ " baseline [dim](passthrough)[/]",
881
+ " target [magenta]reorderer(zigzag_to_natural)[/]",
882
+ ]
883
+
884
+ def test_with_shape_traces(self) -> None:
885
+ plan: AlignerPlan = _make_simple_aligner_plan(with_unsharder=True)
886
+ traced: TracedAlignerPlan = _make_traced_plan(
887
+ plan,
888
+ target_input_shapes=[[2, 4096], [2, 4096]],
889
+ target_output_shapes=[[4, 4096]],
890
+ )
891
+ lines: list[str] = _format_plan_section_rich(traced_plan=traced)
892
+
893
+ assert lines == [
894
+ " baseline [dim](passthrough)[/]",
895
+ " target [magenta]unsharder(tp)[/] (2×[2, 4096] → 1×[4, 4096])",
896
+ ]
897
+
898
+ def test_with_token_aligner(self) -> None:
899
+ plan: AlignerPlan = _make_simple_aligner_plan(with_token_aligner=True)
900
+ traced: TracedAlignerPlan = _make_traced_plan(plan)
901
+ lines: list[str] = _format_plan_section_rich(traced_plan=traced)
902
+
903
+ assert lines == [
904
+ " baseline [dim](passthrough)[/]",
905
+ " target [dim](passthrough)[/]",
906
+ " token_aligner [dim]3 tokens[/]",
907
+ ]
908
+
909
+ def test_with_axis_aligner(self) -> None:
910
+ plan: AlignerPlan = _make_simple_aligner_plan(with_axis_aligner=True)
911
+ traced: TracedAlignerPlan = _make_traced_plan(plan)
912
+ lines: list[str] = _format_plan_section_rich(traced_plan=traced)
913
+
914
+ assert lines == [
915
+ " baseline [dim](passthrough)[/]",
916
+ " target [dim](passthrough)[/]",
917
+ " axis_aligner [dim]x=b s d -> s b d[/]",
918
+ ]
919
+
920
+ def test_axis_aligner_noop(self) -> None:
921
+ plan: AlignerPlan = _make_simple_aligner_plan(
922
+ with_axis_aligner=True, axis_aligner_noop=True
923
+ )
924
+ traced: TracedAlignerPlan = _make_traced_plan(plan)
925
+ lines: list[str] = _format_plan_section_rich(traced_plan=traced)
926
+
927
+ assert lines == [
928
+ " baseline [dim](passthrough)[/]",
929
+ " target [dim](passthrough)[/]",
930
+ " axis_aligner [dim](no-op)[/]",
931
+ ]
932
+
933
+
934
+ class TestFormatStatsRich:
935
+ """_format_stats_rich() snapshot tests."""
936
+
937
+ def test_basic(self) -> None:
938
+ baseline: TensorStats = _make_stats(mean=0.0, std=1.0, min=-2.0, max=2.0)
939
+ target: TensorStats = _make_stats(
940
+ mean=0.0001, std=1.0001, min=-2.0001, max=2.0001
941
+ )
942
+ lines: list[str] = _format_stats_rich(baseline=baseline, target=target)
943
+ assert_rich_tags_balanced("\n".join(lines))
944
+
945
+ assert lines == [
946
+ " [dim] baseline target Δ[/]",
947
+ " [blue]mean [/] 0.0000 0.0001 [dim]+1.00e-04[/]",
948
+ " [blue]std [/] 1.0000 1.0001 [dim]+1.00e-04[/]",
949
+ " [blue]range [/] [-2.0000, 2.0000] [-2.0001, 2.0001]",
950
+ *_DEFAULT_PERCENTILE_LINES,
951
+ ]
952
+
953
+ def test_large_delta(self) -> None:
954
+ baseline: TensorStats = _make_stats(mean=0.0)
955
+ target: TensorStats = _make_stats(mean=1.0)
956
+ lines: list[str] = _format_stats_rich(baseline=baseline, target=target)
957
+ assert_rich_tags_balanced("\n".join(lines))
958
+
959
+ assert lines == [
960
+ " [dim] baseline target Δ[/]",
961
+ " [blue]mean [/] 0.0000 1.0000 [yellow]+1.00e+00[/]",
962
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]",
963
+ " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]",
964
+ *_DEFAULT_PERCENTILE_LINES,
965
+ ]
966
+
967
+ def test_small_delta(self) -> None:
968
+ baseline: TensorStats = _make_stats(mean=0.0)
969
+ target: TensorStats = _make_stats(mean=0.001)
970
+ lines: list[str] = _format_stats_rich(baseline=baseline, target=target)
971
+ assert_rich_tags_balanced("\n".join(lines))
972
+
973
+ assert lines == [
974
+ " [dim] baseline target Δ[/]",
975
+ " [blue]mean [/] 0.0000 0.0010 [dim]+1.00e-03[/]",
976
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]",
977
+ " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]",
978
+ *_DEFAULT_PERCENTILE_LINES,
979
+ ]
980
+
981
+
982
+ class TestFormatStatsRichVerbose:
983
+ """_format_stats_rich(verbose=True) snapshot tests."""
984
+
985
+ def test_all_stats_with_percentiles(self) -> None:
986
+ baseline: TensorStats = _make_stats()
987
+ target: TensorStats = _make_stats()
988
+ lines: list[str] = _format_stats_rich(
989
+ baseline=baseline, target=target, verbose=True
990
+ )
991
+
992
+ assert lines == [
993
+ " [dim] baseline target Δ[/]",
994
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]",
995
+ " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]",
996
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]",
997
+ " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]",
998
+ " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]",
999
+ " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]",
1000
+ " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]",
1001
+ " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]",
1002
+ " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]",
1003
+ " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]",
1004
+ ]
1005
+
1006
+ def test_no_percentiles(self) -> None:
1007
+ baseline: TensorStats = _make_stats(percentiles={})
1008
+ target: TensorStats = _make_stats(percentiles={})
1009
+ lines: list[str] = _format_stats_rich(
1010
+ baseline=baseline, target=target, verbose=True
1011
+ )
1012
+
1013
+ assert lines == [
1014
+ " [dim] baseline target Δ[/]",
1015
+ " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]",
1016
+ " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]",
1017
+ " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]",
1018
+ " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]",
1019
+ " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]",
1020
+ ]
1021
+
1022
+
1023
+ class TestFormatAbsDiffPercentilesRich:
1024
+ """_format_abs_diff_percentiles_rich() snapshot tests."""
1025
+
1026
+ def test_normal_values(self) -> None:
1027
+ diff: DiffInfo = _make_diff()
1028
+ result: str = _format_abs_diff_percentiles_rich(diff)
1029
+
1030
+ assert result == (
1031
+ "p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 " "p95=4.00e-04 p99=5.00e-04"
1032
+ )
1033
+
1034
+ def test_high_p99_coloring(self) -> None:
1035
+ diff: DiffInfo = _make_diff(
1036
+ abs_diff_percentiles={99: 0.5},
1037
+ )
1038
+ result: str = _format_abs_diff_percentiles_rich(diff)
1039
+
1040
+ assert result == "[yellow]p99=5.00e-01[/]"
1041
+
1042
+ def test_low_p99_no_coloring(self) -> None:
1043
+ diff: DiffInfo = _make_diff(
1044
+ abs_diff_percentiles={99: 0.01},
1045
+ )
1046
+ result: str = _format_abs_diff_percentiles_rich(diff)
1047
+
1048
+ assert result == "p99=1.00e-02"
1049
+
1050
+
1051
+ class TestFormatReplicatedChecks:
1052
+ """format_replicated_checks() snapshot tests."""
1053
+
1054
+ def test_all_passed(self) -> None:
1055
+ checks: list[ReplicatedCheckResult] = [
1056
+ ReplicatedCheckResult(
1057
+ axis="tp",
1058
+ group_index=0,
1059
+ compared_index=1,
1060
+ baseline_index=0,
1061
+ passed=True,
1062
+ atol=1e-3,
1063
+ diff=_make_diff(rel_diff=1e-6, max_abs_diff=1e-5, mean_abs_diff=1e-6),
1064
+ ),
1065
+ ]
1066
+ result: str = format_replicated_checks(checks)
1067
+
1068
+ assert result == (
1069
+ "Replicated checks:\n"
1070
+ " ✅ axis=tp group=0 idx=1 vs 0: "
1071
+ "rel_diff=1.000000e-06 max_abs_diff=1.000000e-05 mean_abs_diff=1.000000e-06"
1072
+ )
1073
+
1074
+ def test_one_failed(self) -> None:
1075
+ checks: list[ReplicatedCheckResult] = [
1076
+ ReplicatedCheckResult(
1077
+ axis="tp",
1078
+ group_index=0,
1079
+ compared_index=1,
1080
+ baseline_index=0,
1081
+ passed=False,
1082
+ atol=1e-3,
1083
+ diff=_make_diff(rel_diff=0.5, max_abs_diff=1.0, mean_abs_diff=0.3),
1084
+ ),
1085
+ ]
1086
+ result: str = format_replicated_checks(checks)
1087
+
1088
+ assert result == (
1089
+ "Replicated checks:\n"
1090
+ " ❌ axis=tp group=0 idx=1 vs 0: "
1091
+ "rel_diff=5.000000e-01 max_abs_diff=1.000000e+00 mean_abs_diff=3.000000e-01"
1092
+ )
1093
+
1094
+ def test_no_diff(self) -> None:
1095
+ checks: list[ReplicatedCheckResult] = [
1096
+ ReplicatedCheckResult(
1097
+ axis="tp",
1098
+ group_index=0,
1099
+ compared_index=1,
1100
+ baseline_index=0,
1101
+ passed=True,
1102
+ atol=1e-3,
1103
+ ),
1104
+ ]
1105
+ result: str = format_replicated_checks(checks)
1106
+
1107
+ assert result == (
1108
+ "Replicated checks:\n" " ✅ axis=tp group=0 idx=1 vs 0: n/a diff"
1109
+ )
1110
+
1111
+
1112
+ if __name__ == "__main__":
1113
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_types.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import sys
3
+
4
+ import pytest
5
+
6
+ from sglang.srt.debug_utils.comparator.output_types import (
7
+ ComparisonSkipRecord,
8
+ ComparisonTensorRecord,
9
+ ConfigRecord,
10
+ ErrorLog,
11
+ InfoLog,
12
+ LogRecord,
13
+ ReplicatedCheckResult,
14
+ SummaryRecord,
15
+ parse_record_json,
16
+ )
17
+ from sglang.srt.debug_utils.comparator.tensor_comparator.types import (
18
+ DiffInfo,
19
+ TensorInfo,
20
+ TensorStats,
21
+ )
22
+ from sglang.test.ci.ci_register import register_cpu_ci
23
+
24
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
25
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
26
+
27
+
28
+ def _make_stats(**overrides) -> TensorStats:
29
+ defaults: dict = dict(
30
+ mean=0.5,
31
+ abs_mean=1.2,
32
+ std=1.0,
33
+ min=-2.0,
34
+ max=3.0,
35
+ percentiles={1: -1.8, 5: -1.5, 50: 0.0, 95: 2.5, 99: 2.8},
36
+ )
37
+ defaults.update(overrides)
38
+ return TensorStats(**defaults)
39
+
40
+
41
+ def _make_diff(**overrides) -> DiffInfo:
42
+ defaults = dict(
43
+ rel_diff=1e-4,
44
+ max_abs_diff=5e-4,
45
+ mean_abs_diff=2e-4,
46
+ max_diff_coord=[2, 3],
47
+ baseline_at_max=1.0,
48
+ target_at_max=1.0005,
49
+ diff_threshold=1e-3,
50
+ passed=True,
51
+ )
52
+ defaults.update(overrides)
53
+ return DiffInfo(**defaults)
54
+
55
+
56
+ def _make_tensor_info(**overrides) -> TensorInfo:
57
+ defaults = dict(
58
+ shape=[4, 8],
59
+ dtype="torch.float32",
60
+ stats=_make_stats(),
61
+ )
62
+ defaults.update(overrides)
63
+ return TensorInfo(**defaults)
64
+
65
+
66
+ class TestStrictBase:
67
+ def test_rejects_extra_fields(self):
68
+ with pytest.raises(Exception):
69
+ TensorStats(mean=0.0, abs_mean=0.5, std=1.0, min=-1.0, max=1.0, bogus=42)
70
+
71
+ def test_rejects_extra_fields_on_diff(self):
72
+ with pytest.raises(Exception):
73
+ DiffInfo(
74
+ rel_diff=0.0,
75
+ max_abs_diff=0.0,
76
+ mean_abs_diff=0.0,
77
+ max_diff_coord=[0],
78
+ baseline_at_max=0.0,
79
+ target_at_max=0.0,
80
+ diff_threshold=1e-3,
81
+ passed=True,
82
+ extra_field=123,
83
+ )
84
+
85
+
86
+ class TestRecordTypes:
87
+ def test_comparison_record_inherits_tensor_fields(self):
88
+ record = ComparisonTensorRecord(
89
+ name="hidden_states",
90
+ baseline=_make_tensor_info(),
91
+ target=_make_tensor_info(),
92
+ unified_shape=[4, 8],
93
+ shape_mismatch=False,
94
+ diff=_make_diff(),
95
+ )
96
+ parsed = json.loads(record.model_dump_json())
97
+ assert parsed["type"] == "comparison_tensor"
98
+ assert parsed["name"] == "hidden_states"
99
+ assert "baseline" in parsed
100
+ assert "diff" in parsed
101
+
102
+ def test_discriminated_union_parsing(self):
103
+ for record in [
104
+ ConfigRecord(
105
+ config={
106
+ "baseline_path": "/a",
107
+ "target_path": "/b",
108
+ "diff_threshold": 1e-3,
109
+ "start_step": 0,
110
+ "end_step": 100,
111
+ }
112
+ ),
113
+ ComparisonSkipRecord(name="attn", reason="no_baseline"),
114
+ ComparisonTensorRecord(
115
+ name="mlp",
116
+ baseline=_make_tensor_info(),
117
+ target=_make_tensor_info(),
118
+ unified_shape=[4, 8],
119
+ shape_mismatch=False,
120
+ ),
121
+ SummaryRecord(total=10, passed=8, failed=1, skipped=1),
122
+ LogRecord(
123
+ errors=[ErrorLog(category="test", message="test warning")],
124
+ ),
125
+ ]:
126
+ restored = parse_record_json(record.model_dump_json())
127
+ assert type(restored) is type(record)
128
+ assert restored == record
129
+
130
+
131
+ def _make_replicated_check(**overrides) -> ReplicatedCheckResult:
132
+ defaults: dict = dict(
133
+ axis="tp",
134
+ group_index=0,
135
+ compared_index=1,
136
+ baseline_index=0,
137
+ passed=False,
138
+ atol=1e-6,
139
+ diff=_make_diff(
140
+ rel_diff=0.1,
141
+ max_abs_diff=0.1,
142
+ mean_abs_diff=0.05,
143
+ diff_threshold=1e-6,
144
+ passed=False,
145
+ ),
146
+ )
147
+ defaults.update(overrides)
148
+ return ReplicatedCheckResult(**defaults)
149
+
150
+
151
+ class TestWarnings:
152
+ def test_comparison_record_failed_when_diff_passed_but_errors(self):
153
+ """ComparisonTensorRecord with diff.passed=True but errors → category=='failed'."""
154
+ record = ComparisonTensorRecord(
155
+ name="hidden",
156
+ baseline=_make_tensor_info(),
157
+ target=_make_tensor_info(),
158
+ unified_shape=[4, 8],
159
+ shape_mismatch=False,
160
+ diff=_make_diff(passed=True),
161
+ errors=[ErrorLog(category="test", message="some warning")],
162
+ )
163
+ assert record.category == "failed"
164
+
165
+ def test_skip_record_failed_when_errors(self):
166
+ """ComparisonSkipRecord with errors → category=='failed' instead of 'skipped'."""
167
+ record = ComparisonSkipRecord(
168
+ name="x",
169
+ reason="no_baseline",
170
+ errors=[ErrorLog(category="test", message="some warning")],
171
+ )
172
+ assert record.category == "failed"
173
+
174
+ def test_replicated_checks_all_passed(self):
175
+ """ComparisonTensorRecord with all replicated_checks passed → category=='passed'."""
176
+ record = ComparisonTensorRecord(
177
+ name="hidden",
178
+ baseline=_make_tensor_info(),
179
+ target=_make_tensor_info(),
180
+ unified_shape=[4, 8],
181
+ shape_mismatch=False,
182
+ diff=_make_diff(passed=True),
183
+ replicated_checks=[_make_replicated_check(passed=True)],
184
+ )
185
+ assert record.category == "passed"
186
+
187
+ def test_replicated_checks_failed_means_record_failed(self):
188
+ """ComparisonTensorRecord with any replicated_check.passed=False → category=='failed'."""
189
+ record = ComparisonTensorRecord(
190
+ name="hidden",
191
+ baseline=_make_tensor_info(),
192
+ target=_make_tensor_info(),
193
+ unified_shape=[4, 8],
194
+ shape_mismatch=False,
195
+ diff=_make_diff(passed=True),
196
+ replicated_checks=[_make_replicated_check(passed=False)],
197
+ )
198
+ assert record.category == "failed"
199
+
200
+ def test_replicated_check_json_round_trip(self):
201
+ """ReplicatedCheckResult survives JSON round-trip via ComparisonTensorRecord."""
202
+ check = _make_replicated_check(
203
+ axis="cp",
204
+ group_index=2,
205
+ compared_index=3,
206
+ baseline_index=0,
207
+ passed=False,
208
+ )
209
+ record = ComparisonTensorRecord(
210
+ name="mlp",
211
+ baseline=_make_tensor_info(),
212
+ target=_make_tensor_info(),
213
+ unified_shape=[4, 8],
214
+ shape_mismatch=False,
215
+ diff=_make_diff(),
216
+ replicated_checks=[check],
217
+ )
218
+
219
+ restored = parse_record_json(record.model_dump_json())
220
+ assert isinstance(restored, ComparisonTensorRecord)
221
+ assert len(restored.replicated_checks) == 1
222
+
223
+ restored_check: ReplicatedCheckResult = restored.replicated_checks[0]
224
+ assert restored_check.axis == "cp"
225
+ assert restored_check.group_index == 2
226
+ assert restored_check.compared_index == 3
227
+ assert restored_check.baseline_index == 0
228
+ assert not restored_check.passed
229
+
230
+ def test_any_log_discriminated_union_round_trip(self):
231
+ """ErrorLog and InfoLog survive JSON round-trip via a LogRecord."""
232
+ all_errors = [
233
+ ErrorLog(
234
+ category="rids_mismatch",
235
+ message="rids mismatch across ranks: rank 0 has [1,2,3], "
236
+ "rank 1 has [4,5,6]",
237
+ ),
238
+ ]
239
+ all_infos = [
240
+ InfoLog(
241
+ category="aux_tensors_missing",
242
+ message="Aux tensors missing, skipping token alignment",
243
+ ),
244
+ ]
245
+
246
+ record = LogRecord(errors=all_errors, infos=all_infos)
247
+ restored = parse_record_json(record.model_dump_json())
248
+ assert isinstance(restored, LogRecord)
249
+ assert len(restored.errors) == len(all_errors)
250
+ assert len(restored.infos) == len(all_infos)
251
+
252
+ for original, parsed in zip(all_errors, restored.errors):
253
+ assert type(parsed) is type(original)
254
+ assert parsed == original
255
+
256
+ for original, parsed in zip(all_infos, restored.infos):
257
+ assert type(parsed) is type(original)
258
+ assert parsed == original
259
+
260
+
261
+ if __name__ == "__main__":
262
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_comparator.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+ from unittest.mock import patch
4
+
5
+ import pytest
6
+ import torch
7
+
8
+ from sglang.srt.debug_utils.comparator.bundle_comparator import (
9
+ _build_skip_from_one_empty_side,
10
+ _load_all_values,
11
+ )
12
+ from sglang.srt.debug_utils.comparator.log_sink import LogSink
13
+ from sglang.srt.debug_utils.comparator.output_types import ErrorLog
14
+ from sglang.srt.debug_utils.comparator.utils import Pair
15
+ from sglang.srt.debug_utils.dump_loader import ValueWithMeta
16
+ from sglang.test.ci.ci_register import register_cpu_ci
17
+
18
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
19
+
20
+
21
+ def _save_tensor(
22
+ dump_path: Path,
23
+ *,
24
+ name: str,
25
+ step: int = 0,
26
+ rank: int = 0,
27
+ ) -> str:
28
+ filename: str = f"step={step}___rank={rank}___dump_index=0___name={name}.pt"
29
+ tensor: torch.Tensor = torch.randn(4)
30
+ torch.save({"value": tensor, "meta": {}}, dump_path / filename)
31
+ return filename
32
+
33
+
34
+ class TestLoadAllValues:
35
+ def test_all_success(self, tmp_path: Path) -> None:
36
+ """All files load successfully — no warnings emitted."""
37
+ fn0: str = _save_tensor(tmp_path, name="a", rank=0)
38
+ fn1: str = _save_tensor(tmp_path, name="a", rank=1)
39
+
40
+ sink = LogSink()
41
+ with sink.context() as warnings:
42
+ with patch(
43
+ "sglang.srt.debug_utils.comparator.bundle_comparator.log_sink",
44
+ sink,
45
+ ):
46
+ result = _load_all_values(filenames=[fn0, fn1], base_path=tmp_path)
47
+
48
+ assert len(result) == 2
49
+ assert len(warnings) == 0
50
+
51
+ def test_one_corrupted_emits_warning(self, tmp_path: Path) -> None:
52
+ """One corrupted file is filtered out and emits a load_failed warning."""
53
+ fn_good: str = _save_tensor(tmp_path, name="a", rank=0)
54
+
55
+ fn_bad: str = "step=0___rank=1___dump_index=0___name=a.pt"
56
+ (tmp_path / fn_bad).write_text("not a valid pt file")
57
+
58
+ sink = LogSink()
59
+ with sink.context() as warnings:
60
+ with patch(
61
+ "sglang.srt.debug_utils.comparator.bundle_comparator.log_sink",
62
+ sink,
63
+ ):
64
+ result = _load_all_values(
65
+ filenames=[fn_good, fn_bad], base_path=tmp_path
66
+ )
67
+
68
+ assert len(result) == 1
69
+ assert len(warnings) == 1
70
+ assert isinstance(warnings[0], ErrorLog)
71
+ assert warnings[0].category == "load_failed"
72
+ assert fn_bad in warnings[0].message
73
+
74
+ def test_all_corrupted_emits_warnings_returns_empty(self, tmp_path: Path) -> None:
75
+ """All files corrupted — returns empty list and emits one warning per file."""
76
+ fn0: str = "step=0___rank=0___dump_index=0___name=a.pt"
77
+ fn1: str = "step=0___rank=1___dump_index=0___name=a.pt"
78
+ (tmp_path / fn0).write_text("corrupt")
79
+ (tmp_path / fn1).write_text("corrupt")
80
+
81
+ sink = LogSink()
82
+ with sink.context() as warnings:
83
+ with patch(
84
+ "sglang.srt.debug_utils.comparator.bundle_comparator.log_sink",
85
+ sink,
86
+ ):
87
+ result = _load_all_values(filenames=[fn0, fn1], base_path=tmp_path)
88
+
89
+ assert len(result) == 0
90
+ assert len(warnings) == 2
91
+ assert all(w.category == "load_failed" for w in warnings)
92
+
93
+
94
+ def _tensor_item(value: torch.Tensor, rank: int = 0) -> ValueWithMeta:
95
+ return ValueWithMeta(
96
+ value=value,
97
+ meta={
98
+ "rank": rank,
99
+ "dims": "b s",
100
+ "sglang_parallel_info": {},
101
+ "megatron_parallel_info": {},
102
+ "filename": f"rank_{rank}.pt",
103
+ },
104
+ )
105
+
106
+
107
+ class TestBuildSkipFromOneEmptySide:
108
+ def test_baseline_empty_sets_reason_and_side(self) -> None:
109
+ """Empty baseline → reason='baseline_load_failed', available_side='target'."""
110
+ item = _tensor_item(torch.randn(2, 3))
111
+ record = _build_skip_from_one_empty_side(
112
+ name="test_tensor",
113
+ pair=Pair(x=[], y=[item]),
114
+ )
115
+ assert record.reason == "baseline_load_failed"
116
+ assert record.available_side == "target"
117
+ assert record.available_tensor_info is not None
118
+
119
+ def test_target_empty_sets_reason_and_side(self) -> None:
120
+ """Empty target → reason='target_load_failed', available_side='baseline'."""
121
+ item = _tensor_item(torch.randn(2, 3))
122
+ record = _build_skip_from_one_empty_side(
123
+ name="test_tensor",
124
+ pair=Pair(x=[item], y=[]),
125
+ )
126
+ assert record.reason == "target_load_failed"
127
+ assert record.available_side == "baseline"
128
+ assert record.available_tensor_info is not None
129
+
130
+ def test_no_tensor_items_returns_minimal_skip(self) -> None:
131
+ """All items are non-tensor → skip record with no tensor info."""
132
+ non_tensor_item = ValueWithMeta(value="not_a_tensor", meta={"rank": 0})
133
+ record = _build_skip_from_one_empty_side(
134
+ name="test_tensor",
135
+ pair=Pair(x=[], y=[non_tensor_item]),
136
+ )
137
+ assert record.reason == "baseline_load_failed"
138
+ assert record.available_tensor_info is None
139
+ assert record.available_bundle_info is None
140
+
141
+ def test_with_tensor_items_populates_info(self) -> None:
142
+ """Tensor items present → tensor_info and bundle_info are populated."""
143
+ item = _tensor_item(torch.randn(2, 3))
144
+ record = _build_skip_from_one_empty_side(
145
+ name="test_tensor",
146
+ pair=Pair(x=[], y=[item]),
147
+ )
148
+ assert record.available_tensor_info is not None
149
+ assert record.available_tensor_info.shape == [2, 3]
150
+ assert record.available_bundle_info is not None
151
+ assert record.available_bundle_info.num_files >= 1
152
+
153
+ def test_multiple_tensor_items_uses_first_for_info(self) -> None:
154
+ """When multiple tensor items exist, tensor_info comes from the first."""
155
+ item1 = _tensor_item(torch.randn(2, 3), rank=0)
156
+ item2 = _tensor_item(torch.randn(4, 5), rank=1)
157
+ record = _build_skip_from_one_empty_side(
158
+ name="multi",
159
+ pair=Pair(x=[], y=[item1, item2]),
160
+ )
161
+ assert record.available_tensor_info is not None
162
+ assert record.available_tensor_info.shape == [2, 3]
163
+ assert record.available_bundle_info is not None
164
+ assert record.available_bundle_info.num_files == 2
165
+
166
+ def test_mixed_tensor_and_non_tensor_filters_non_tensor(self) -> None:
167
+ """Non-tensor items are filtered; tensor_info comes from tensor items only."""
168
+ non_tensor = ValueWithMeta(value="string_value", meta={"rank": 0})
169
+ tensor_item = _tensor_item(torch.randn(5, 6), rank=1)
170
+ record = _build_skip_from_one_empty_side(
171
+ name="mixed",
172
+ pair=Pair(x=[], y=[non_tensor, tensor_item]),
173
+ )
174
+ assert record.available_tensor_info is not None
175
+ assert record.available_tensor_info.shape == [5, 6]
176
+ assert record.available_bundle_info is not None
177
+ assert record.available_bundle_info.num_files == 1
178
+
179
+ def test_tensor_info_includes_sample(self) -> None:
180
+ """Tensor info should include a sample string for skip records."""
181
+ item = _tensor_item(torch.tensor([1.0, 2.0, 3.0]))
182
+ record = _build_skip_from_one_empty_side(
183
+ name="sample_check",
184
+ pair=Pair(x=[item], y=[]),
185
+ )
186
+ assert record.available_tensor_info is not None
187
+ assert record.available_tensor_info.sample is not None
188
+
189
+ def test_name_preserved_in_record(self) -> None:
190
+ """The tensor name is preserved in the skip record."""
191
+ item = _tensor_item(torch.randn(2, 3))
192
+ record = _build_skip_from_one_empty_side(
193
+ name="my_layer.weight",
194
+ pair=Pair(x=[], y=[item]),
195
+ )
196
+ assert record.name == "my_layer.weight"
197
+
198
+ def test_bundle_info_has_dims_from_meta(self) -> None:
199
+ """Bundle info dims field should come from the meta."""
200
+ item = _tensor_item(torch.randn(2, 3))
201
+ record = _build_skip_from_one_empty_side(
202
+ name="dims_check",
203
+ pair=Pair(x=[], y=[item]),
204
+ )
205
+ assert record.available_bundle_info is not None
206
+ assert record.available_bundle_info.dims == "b s"
207
+
208
+
209
+ if __name__ == "__main__":
210
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_matcher.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Any
3
+
4
+ import polars as pl
5
+ import pytest
6
+
7
+ from sglang.srt.debug_utils.comparator.bundle_matcher import (
8
+ TensorBundleInfo,
9
+ TensorFileInfo,
10
+ _rows_to_tensor_infos,
11
+ match_bundles,
12
+ )
13
+ from sglang.srt.debug_utils.comparator.utils import Pair
14
+ from sglang.test.ci.ci_register import register_cpu_ci
15
+
16
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
17
+
18
+
19
+ def _make_row(
20
+ *,
21
+ name: str,
22
+ step: int = 0,
23
+ rank: int = 0,
24
+ layer_id: int | None = None,
25
+ filename: str | None = None,
26
+ ) -> dict[str, Any]:
27
+ if filename is None:
28
+ layer_part: str = f"___layer_id={layer_id}" if layer_id is not None else ""
29
+ filename = f"name={name}___step={step}___rank={rank}{layer_part}.pt"
30
+ row: dict[str, Any] = {
31
+ "name": name,
32
+ "step": step,
33
+ "rank": rank,
34
+ "filename": filename,
35
+ }
36
+ if layer_id is not None:
37
+ row["layer_id"] = layer_id
38
+ return row
39
+
40
+
41
+ def _make_df(rows: list[dict[str, Any]]) -> pl.DataFrame:
42
+ if not rows:
43
+ return pl.DataFrame(rows)
44
+
45
+ all_keys: set[str] = set()
46
+ for row in rows:
47
+ all_keys.update(row.keys())
48
+ normalized: list[dict[str, Any]] = [
49
+ {k: row.get(k, None) for k in all_keys} for row in rows
50
+ ]
51
+ return pl.DataFrame(normalized)
52
+
53
+
54
+ class TestMatchBundles:
55
+ def test_single_tensor_single_step(self) -> None:
56
+ target_df: pl.DataFrame = _make_df([_make_row(name="t_a")])
57
+ baseline_df: pl.DataFrame = _make_df([_make_row(name="t_a")])
58
+
59
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
60
+ dfs=Pair(x=baseline_df, y=target_df),
61
+ skip_keys={"filename"},
62
+ )
63
+
64
+ assert len(results) == 1
65
+ assert len(results[0].x) == 1
66
+ assert len(results[0].y) == 1
67
+ assert results[0].y[0].name == "t_a"
68
+
69
+ def test_multiple_names_separate_bundles(self) -> None:
70
+ target_df: pl.DataFrame = _make_df(
71
+ [
72
+ _make_row(name="t_a"),
73
+ _make_row(name="t_b"),
74
+ ]
75
+ )
76
+ baseline_df: pl.DataFrame = _make_df(
77
+ [
78
+ _make_row(name="t_a"),
79
+ _make_row(name="t_b"),
80
+ ]
81
+ )
82
+
83
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
84
+ dfs=Pair(x=baseline_df, y=target_df),
85
+ skip_keys={"filename"},
86
+ )
87
+
88
+ assert len(results) == 2
89
+ result_names: list[str] = [r.y[0].name for r in results]
90
+ assert "t_a" in result_names
91
+ assert "t_b" in result_names
92
+
93
+ def test_skip_rank_groups_across_ranks(self) -> None:
94
+ target_df: pl.DataFrame = _make_df(
95
+ [
96
+ _make_row(name="t_a", rank=0),
97
+ _make_row(name="t_a", rank=1),
98
+ ]
99
+ )
100
+ baseline_df: pl.DataFrame = _make_df(
101
+ [
102
+ _make_row(name="t_a", rank=0),
103
+ _make_row(name="t_a", rank=1),
104
+ ]
105
+ )
106
+
107
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
108
+ dfs=Pair(x=baseline_df, y=target_df),
109
+ skip_keys={"filename", "rank"},
110
+ )
111
+
112
+ assert len(results) == 1
113
+ assert len(results[0].y) == 2
114
+
115
+ def test_baseline_missing_tensor(self) -> None:
116
+ target_df: pl.DataFrame = _make_df(
117
+ [
118
+ _make_row(name="t_a"),
119
+ _make_row(name="t_extra"),
120
+ ]
121
+ )
122
+ baseline_df: pl.DataFrame = _make_df(
123
+ [
124
+ _make_row(name="t_a"),
125
+ ]
126
+ )
127
+
128
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
129
+ dfs=Pair(x=baseline_df, y=target_df),
130
+ skip_keys={"filename"},
131
+ )
132
+
133
+ assert len(results) == 2
134
+ extra_pair: Pair[TensorBundleInfo] = [
135
+ r for r in results if r.y[0].name == "t_extra"
136
+ ][0]
137
+ assert extra_pair.x == []
138
+
139
+ def test_empty_target_returns_empty(self) -> None:
140
+ target_df: pl.DataFrame = _make_df([])
141
+ baseline_df: pl.DataFrame = _make_df([_make_row(name="t_a")])
142
+
143
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
144
+ dfs=Pair(x=baseline_df, y=target_df),
145
+ skip_keys={"filename"},
146
+ )
147
+
148
+ assert results == []
149
+
150
+ def test_skip_step_groups_across_steps(self) -> None:
151
+ target_df: pl.DataFrame = _make_df(
152
+ [
153
+ _make_row(name="t_a", step=0),
154
+ _make_row(name="t_a", step=1),
155
+ ]
156
+ )
157
+ baseline_df: pl.DataFrame = _make_df(
158
+ [
159
+ _make_row(name="t_a", step=0),
160
+ _make_row(name="t_a", step=1),
161
+ ]
162
+ )
163
+
164
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
165
+ dfs=Pair(x=baseline_df, y=target_df),
166
+ skip_keys={"filename", "step"},
167
+ )
168
+
169
+ assert len(results) == 1
170
+ assert len(results[0].y) == 2
171
+
172
+
173
+ class TestMatchBundlesPipelineParallel:
174
+ """Tests verifying that PP works correctly with the existing matching logic."""
175
+
176
+ LOGICAL_SKIP_KEYS: set[str] = {"filename", "rank", "dump_index", "recompute_status"}
177
+
178
+ def test_same_layer_id_different_ranks_match(self) -> None:
179
+ """SGLang PP=2 rank 0 (layers 0-31) vs Megatron PP=4 rank 2 (layers 16-31):
180
+ layer_id=20 should match regardless of world rank."""
181
+ target_df: pl.DataFrame = _make_df(
182
+ [_make_row(name="hidden", rank=0, layer_id=20)]
183
+ )
184
+ baseline_df: pl.DataFrame = _make_df(
185
+ [_make_row(name="hidden", rank=2, layer_id=20)]
186
+ )
187
+
188
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
189
+ dfs=Pair(x=baseline_df, y=target_df),
190
+ skip_keys=self.LOGICAL_SKIP_KEYS,
191
+ )
192
+
193
+ assert len(results) == 1
194
+ assert len(results[0].x) == 1
195
+ assert len(results[0].y) == 1
196
+
197
+ def test_layer_id_none_non_layer_tensors_match(self) -> None:
198
+ """Non-layer tensors (embedding, lm_head) have no layer_id.
199
+ They should match across different PP ranks."""
200
+ target_df: pl.DataFrame = _make_df([_make_row(name="embed_tokens", rank=0)])
201
+ baseline_df: pl.DataFrame = _make_df([_make_row(name="embed_tokens", rank=0)])
202
+
203
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
204
+ dfs=Pair(x=baseline_df, y=target_df),
205
+ skip_keys=self.LOGICAL_SKIP_KEYS,
206
+ )
207
+
208
+ assert len(results) == 1
209
+ assert len(results[0].x) == 1
210
+ assert len(results[0].y) == 1
211
+
212
+ def test_different_pp_sizes_layer_and_non_layer_bundles(self) -> None:
213
+ """SGLang PP=2 TP=2 (4 ranks) vs Megatron PP=4 TP=2 (8 ranks).
214
+ Layer tensors match by (name, layer_id); non-layer tensors match by name.
215
+ All ranks are grouped into the same bundle when rank is skipped."""
216
+ target_df: pl.DataFrame = _make_df(
217
+ [
218
+ # SGLang: pp_stage=0 has ranks 0,1 (TP=2)
219
+ _make_row(name="hidden", rank=0, layer_id=20),
220
+ _make_row(name="hidden", rank=1, layer_id=20),
221
+ # SGLang: embedding on pp_stage=0
222
+ _make_row(name="embed_tokens", rank=0),
223
+ _make_row(name="embed_tokens", rank=1),
224
+ # SGLang: lm_head on pp_stage=1, ranks 2,3
225
+ _make_row(name="lm_head", rank=2),
226
+ _make_row(name="lm_head", rank=3),
227
+ ]
228
+ )
229
+ baseline_df: pl.DataFrame = _make_df(
230
+ [
231
+ # Megatron: pp_stage=1 has ranks 2,3 for layer 20
232
+ _make_row(name="hidden", rank=2, layer_id=20),
233
+ _make_row(name="hidden", rank=3, layer_id=20),
234
+ # Megatron: embedding on pp_stage=0
235
+ _make_row(name="embed_tokens", rank=0),
236
+ _make_row(name="embed_tokens", rank=1),
237
+ # Megatron: lm_head on pp_stage=3, ranks 6,7
238
+ _make_row(name="lm_head", rank=6),
239
+ _make_row(name="lm_head", rank=7),
240
+ ]
241
+ )
242
+
243
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
244
+ dfs=Pair(x=baseline_df, y=target_df),
245
+ skip_keys=self.LOGICAL_SKIP_KEYS,
246
+ )
247
+
248
+ assert len(results) == 3
249
+ names_to_pairs: dict[str, Pair[TensorBundleInfo]] = {}
250
+ for pair in results:
251
+ key: str = pair.y[0].name
252
+ layer_suffix: str = ""
253
+ if "layer_id" in target_df.columns:
254
+ row_match = [
255
+ r
256
+ for r in target_df.to_dicts()
257
+ if r["filename"] == pair.y[0].filename
258
+ ]
259
+ if row_match and row_match[0].get("layer_id") is not None:
260
+ layer_suffix = f"_{row_match[0]['layer_id']}"
261
+ names_to_pairs[key + layer_suffix] = pair
262
+
263
+ assert len(names_to_pairs["hidden_20"].x) == 2
264
+ assert len(names_to_pairs["hidden_20"].y) == 2
265
+ assert len(names_to_pairs["embed_tokens"].x) == 2
266
+ assert len(names_to_pairs["embed_tokens"].y) == 2
267
+ assert len(names_to_pairs["lm_head"].x) == 2
268
+ assert len(names_to_pairs["lm_head"].y) == 2
269
+
270
+ def test_unmatched_layer_id_creates_empty_baseline(self) -> None:
271
+ """If target has a layer_id that baseline doesn't, the baseline side
272
+ should be empty (not incorrectly matched to a different layer)."""
273
+ target_df: pl.DataFrame = _make_df(
274
+ [
275
+ _make_row(name="hidden", rank=0, layer_id=10),
276
+ _make_row(name="hidden", rank=0, layer_id=20),
277
+ ]
278
+ )
279
+ baseline_df: pl.DataFrame = _make_df(
280
+ [
281
+ _make_row(name="hidden", rank=0, layer_id=10),
282
+ ]
283
+ )
284
+
285
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
286
+ dfs=Pair(x=baseline_df, y=target_df),
287
+ skip_keys=self.LOGICAL_SKIP_KEYS,
288
+ )
289
+
290
+ assert len(results) == 2
291
+ matched: list[Pair[TensorBundleInfo]] = [r for r in results if r.x]
292
+ unmatched: list[Pair[TensorBundleInfo]] = [r for r in results if not r.x]
293
+ assert len(matched) == 1
294
+ assert len(unmatched) == 1
295
+
296
+ def test_pp1_vs_pp_gt1_matches_by_layer_id(self) -> None:
297
+ """PP=1 (all layers on 1 rank) vs PP>1 (layers split across ranks).
298
+ Should match correctly by layer_id regardless of rank."""
299
+ target_df: pl.DataFrame = _make_df(
300
+ [
301
+ # PP=1: all on rank 0
302
+ _make_row(name="hidden", rank=0, layer_id=0),
303
+ _make_row(name="hidden", rank=0, layer_id=1),
304
+ ]
305
+ )
306
+ baseline_df: pl.DataFrame = _make_df(
307
+ [
308
+ # PP=2: layer 0 on rank 0, layer 1 on rank 1
309
+ _make_row(name="hidden", rank=0, layer_id=0),
310
+ _make_row(name="hidden", rank=1, layer_id=1),
311
+ ]
312
+ )
313
+
314
+ results: list[Pair[TensorBundleInfo]] = match_bundles(
315
+ dfs=Pair(x=baseline_df, y=target_df),
316
+ skip_keys=self.LOGICAL_SKIP_KEYS,
317
+ )
318
+
319
+ assert len(results) == 2
320
+ for pair in results:
321
+ assert len(pair.x) == 1
322
+ assert len(pair.y) == 1
323
+
324
+
325
+ class TestRowsToTensorInfos:
326
+ def test_filters_extra_columns(self) -> None:
327
+ rows: list[dict[str, Any]] = [
328
+ {"filename": "a.pt", "name": "t_a", "step": 0, "rank": 7}
329
+ ]
330
+ infos: list[TensorFileInfo] = _rows_to_tensor_infos(rows)
331
+
332
+ assert len(infos) == 1
333
+ assert infos[0] == TensorFileInfo(filename="a.pt", name="t_a", step=0)
334
+
335
+ def test_empty_rows(self) -> None:
336
+ infos: list[TensorFileInfo] = _rows_to_tensor_infos([])
337
+ assert infos == []
338
+
339
+
340
+ if __name__ == "__main__":
341
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_display.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from io import StringIO
3
+ from pathlib import Path
4
+ from typing import Any, Optional
5
+
6
+ import polars as pl
7
+ import pytest
8
+ import torch
9
+ from rich.console import Console
10
+
11
+ from sglang.srt.debug_utils.comparator.display import (
12
+ _collect_input_ids_and_positions,
13
+ _collect_rank_info,
14
+ _extract_parallel_info,
15
+ _render_polars_as_rich_table,
16
+ _render_polars_as_text,
17
+ )
18
+ from sglang.srt.debug_utils.comparator.output_types import (
19
+ InputIdsRecord,
20
+ RankInfoRecord,
21
+ )
22
+ from sglang.test.ci.ci_register import register_cpu_ci
23
+
24
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
25
+
26
+
27
+ def _render_rich(renderable: object) -> str:
28
+ buf: StringIO = StringIO()
29
+ Console(file=buf, force_terminal=False, width=120).print(renderable)
30
+ return buf.getvalue().rstrip("\n")
31
+
32
+
33
+ def _save_dump_file(
34
+ directory: Path,
35
+ *,
36
+ name: str,
37
+ step: int,
38
+ rank: int,
39
+ dump_index: int,
40
+ value: torch.Tensor,
41
+ meta: dict,
42
+ ) -> str:
43
+ filename = f"name={name}___step={step}___rank={rank}___dump_index={dump_index}.pt"
44
+ torch.save({"value": value, "meta": meta}, directory / filename)
45
+ return filename
46
+
47
+
48
+ def _make_df(rows: list[dict]) -> pl.DataFrame:
49
+ df = pl.DataFrame(rows)
50
+ df = df.with_columns(
51
+ pl.col("step").cast(int),
52
+ pl.col("rank").cast(int),
53
+ pl.col("dump_index").cast(int),
54
+ )
55
+ return df
56
+
57
+
58
+ class TestRenderPolarsAsText:
59
+ def test_renders_table(self) -> None:
60
+ df = pl.DataFrame({"col_a": [1, 2], "col_b": ["x", "y"]})
61
+ text: str = _render_polars_as_text(df, title="test table")
62
+
63
+ assert "test table" in text
64
+ assert "col_a" in text
65
+ assert "col_b" in text
66
+
67
+ def test_renders_empty_dataframe(self) -> None:
68
+ df = pl.DataFrame({"a": [], "b": []})
69
+ text: str = _render_polars_as_text(df, title="empty")
70
+ assert "empty" in text
71
+
72
+
73
+ class TestCollectRankInfo:
74
+ def test_collects_rank_info(self, tmp_path: Path) -> None:
75
+ sglang_info = {
76
+ "tp_rank": 0,
77
+ "tp_size": 2,
78
+ "pp_rank": 0,
79
+ "pp_size": 1,
80
+ }
81
+ filename: str = _save_dump_file(
82
+ tmp_path,
83
+ name="input_ids",
84
+ step=0,
85
+ rank=0,
86
+ dump_index=0,
87
+ value=torch.tensor([1, 2, 3]),
88
+ meta={"sglang_parallel_info": sglang_info},
89
+ )
90
+ df = _make_df(
91
+ [
92
+ {
93
+ "filename": filename,
94
+ "name": "input_ids",
95
+ "step": 0,
96
+ "rank": 0,
97
+ "dump_index": 0,
98
+ }
99
+ ]
100
+ )
101
+
102
+ rows: Optional[list[dict[str, Any]]] = _collect_rank_info(df, dump_dir=tmp_path)
103
+
104
+ assert rows is not None
105
+ assert len(rows) == 1
106
+ assert rows[0]["rank"] == 0
107
+ assert rows[0]["tp"] == "0/2"
108
+ assert rows[0]["pp"] == "0/1"
109
+
110
+ def test_returns_none_when_no_input_ids(self, tmp_path: Path) -> None:
111
+ df = _make_df(
112
+ [
113
+ {
114
+ "filename": "f.pt",
115
+ "name": "some_other",
116
+ "step": 0,
117
+ "rank": 0,
118
+ "dump_index": 0,
119
+ }
120
+ ]
121
+ )
122
+ result = _collect_rank_info(df, dump_dir=tmp_path)
123
+ assert result is None
124
+
125
+ def test_deduplicates_ranks(self, tmp_path: Path) -> None:
126
+ meta = {"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}}
127
+ f1: str = _save_dump_file(
128
+ tmp_path,
129
+ name="input_ids",
130
+ step=0,
131
+ rank=0,
132
+ dump_index=0,
133
+ value=torch.tensor([1]),
134
+ meta=meta,
135
+ )
136
+ f2: str = _save_dump_file(
137
+ tmp_path,
138
+ name="input_ids",
139
+ step=1,
140
+ rank=0,
141
+ dump_index=1,
142
+ value=torch.tensor([2]),
143
+ meta=meta,
144
+ )
145
+ df = _make_df(
146
+ [
147
+ {
148
+ "filename": f1,
149
+ "name": "input_ids",
150
+ "step": 0,
151
+ "rank": 0,
152
+ "dump_index": 0,
153
+ },
154
+ {
155
+ "filename": f2,
156
+ "name": "input_ids",
157
+ "step": 1,
158
+ "rank": 0,
159
+ "dump_index": 1,
160
+ },
161
+ ]
162
+ )
163
+
164
+ rows = _collect_rank_info(df, dump_dir=tmp_path)
165
+
166
+ assert rows is not None
167
+ assert len(rows) == 1
168
+
169
+
170
+ class TestCollectInputIdsAndPositions:
171
+ def test_collects_ids_and_positions(self, tmp_path: Path) -> None:
172
+ f_ids: str = _save_dump_file(
173
+ tmp_path,
174
+ name="input_ids",
175
+ step=0,
176
+ rank=0,
177
+ dump_index=0,
178
+ value=torch.tensor([10, 20, 30]),
179
+ meta={},
180
+ )
181
+ f_pos: str = _save_dump_file(
182
+ tmp_path,
183
+ name="positions",
184
+ step=0,
185
+ rank=0,
186
+ dump_index=1,
187
+ value=torch.tensor([0, 1, 2]),
188
+ meta={},
189
+ )
190
+ df = _make_df(
191
+ [
192
+ {
193
+ "filename": f_ids,
194
+ "name": "input_ids",
195
+ "step": 0,
196
+ "rank": 0,
197
+ "dump_index": 0,
198
+ },
199
+ {
200
+ "filename": f_pos,
201
+ "name": "positions",
202
+ "step": 0,
203
+ "rank": 0,
204
+ "dump_index": 1,
205
+ },
206
+ ]
207
+ )
208
+
209
+ rows = _collect_input_ids_and_positions(df, dump_dir=tmp_path)
210
+
211
+ assert rows is not None
212
+ assert len(rows) == 1
213
+ assert rows[0]["step"] == 0
214
+ assert rows[0]["rank"] == 0
215
+ assert rows[0]["num_tokens"] == 3
216
+ assert "10" in rows[0]["input_ids"]
217
+ assert "0" in rows[0]["positions"]
218
+
219
+ def test_returns_none_when_empty(self, tmp_path: Path) -> None:
220
+ df = _make_df(
221
+ [
222
+ {
223
+ "filename": "f.pt",
224
+ "name": "weight",
225
+ "step": 0,
226
+ "rank": 0,
227
+ "dump_index": 0,
228
+ }
229
+ ]
230
+ )
231
+ result = _collect_input_ids_and_positions(df, dump_dir=tmp_path)
232
+ assert result is None
233
+
234
+ def test_with_mock_tokenizer(self, tmp_path: Path) -> None:
235
+ f_ids: str = _save_dump_file(
236
+ tmp_path,
237
+ name="input_ids",
238
+ step=0,
239
+ rank=0,
240
+ dump_index=0,
241
+ value=torch.tensor([1, 2]),
242
+ meta={},
243
+ )
244
+ df = _make_df(
245
+ [
246
+ {
247
+ "filename": f_ids,
248
+ "name": "input_ids",
249
+ "step": 0,
250
+ "rank": 0,
251
+ "dump_index": 0,
252
+ }
253
+ ]
254
+ )
255
+
256
+ class _MockTokenizer:
257
+ def decode(self, ids: list[int], skip_special_tokens: bool = False) -> str:
258
+ return f"decoded:{ids}"
259
+
260
+ rows = _collect_input_ids_and_positions(
261
+ df, dump_dir=tmp_path, tokenizer=_MockTokenizer()
262
+ )
263
+
264
+ assert rows is not None
265
+ assert "decoded_text" in rows[0]
266
+ assert "decoded:" in rows[0]["decoded_text"]
267
+
268
+
269
+ class TestRankInfoRecordSnapshot:
270
+ def test_to_text_snapshot(self) -> None:
271
+ record = RankInfoRecord(
272
+ label="baseline",
273
+ rows=[
274
+ {"rank": 0, "tp": "0/2", "pp": "0/1"},
275
+ {"rank": 1, "tp": "1/2", "pp": "0/1"},
276
+ ],
277
+ )
278
+ text: str = record.to_text()
279
+
280
+ assert "baseline ranks" in text
281
+ assert "rank" in text
282
+ assert "tp" in text
283
+ assert "pp" in text
284
+ assert "0/2" in text
285
+ assert "1/2" in text
286
+ assert "0/1" in text
287
+
288
+ def test_to_rich_snapshot(self) -> None:
289
+ from rich.table import Table
290
+
291
+ record = RankInfoRecord(
292
+ label="baseline",
293
+ rows=[
294
+ {"rank": 0, "tp": "0/2", "pp": "0/1"},
295
+ {"rank": 1, "tp": "1/2", "pp": "0/1"},
296
+ ],
297
+ )
298
+ body = record._format_rich_body()
299
+
300
+ assert isinstance(body, Table)
301
+ rendered: str = _render_rich(body)
302
+ assert "baseline ranks" in rendered
303
+ assert "0/2" in rendered
304
+ assert "1/2" in rendered
305
+
306
+ def test_json_roundtrip(self) -> None:
307
+ record = RankInfoRecord(
308
+ label="target",
309
+ rows=[{"rank": 0, "tp": "0/4"}],
310
+ )
311
+ json_str: str = record.model_dump_json()
312
+
313
+ assert '"type":"rank_info"' in json_str
314
+ assert '"label":"target"' in json_str
315
+ assert '"tp":"0/4"' in json_str
316
+
317
+
318
+ class TestInputIdsRecordSnapshot:
319
+ def test_to_text_snapshot(self) -> None:
320
+ record = InputIdsRecord(
321
+ label="target",
322
+ rows=[
323
+ {
324
+ "step": 0,
325
+ "rank": 0,
326
+ "num_tokens": 3,
327
+ "input_ids": "[10, 20, 30]",
328
+ "positions": "[0, 1, 2]",
329
+ },
330
+ ],
331
+ )
332
+ text: str = record.to_text()
333
+
334
+ assert "target input_ids & positions" in text
335
+ assert "step" in text
336
+ assert "num_tokens" in text
337
+ assert "10, 20, 30" in text
338
+ assert "0, 1, 2" in text
339
+
340
+ def test_to_rich_snapshot(self) -> None:
341
+ from rich.table import Table
342
+
343
+ record = InputIdsRecord(
344
+ label="target",
345
+ rows=[
346
+ {
347
+ "step": 0,
348
+ "rank": 0,
349
+ "num_tokens": 3,
350
+ "input_ids": "[10, 20, 30]",
351
+ "positions": "[0, 1, 2]",
352
+ },
353
+ ],
354
+ )
355
+ body = record._format_rich_body()
356
+
357
+ assert isinstance(body, Table)
358
+ rendered: str = _render_rich(body)
359
+ assert "target input_ids & positions" in rendered
360
+ assert "10, 20, 30" in rendered
361
+ assert "0, 1, 2" in rendered
362
+
363
+ def test_json_roundtrip(self) -> None:
364
+ record = InputIdsRecord(
365
+ label="baseline",
366
+ rows=[
367
+ {
368
+ "step": 0,
369
+ "rank": 0,
370
+ "num_tokens": 2,
371
+ "input_ids": "[1, 2]",
372
+ "positions": "[0, 1]",
373
+ "decoded_text": "'hello'",
374
+ },
375
+ ],
376
+ )
377
+ json_str: str = record.model_dump_json()
378
+
379
+ assert '"type":"input_ids"' in json_str
380
+ assert '"label":"baseline"' in json_str
381
+ assert '"decoded_text"' in json_str
382
+
383
+ def test_to_text_with_decoded(self) -> None:
384
+ record = InputIdsRecord(
385
+ label="test",
386
+ rows=[
387
+ {
388
+ "step": 0,
389
+ "rank": 0,
390
+ "num_tokens": 2,
391
+ "input_ids": "[1, 2]",
392
+ "positions": "[0, 1]",
393
+ "decoded_text": "'hello world'",
394
+ },
395
+ ],
396
+ )
397
+ text: str = record.to_text()
398
+
399
+ assert "decoded_text" in text
400
+ assert "hello world" in text
401
+
402
+
403
+ class TestExtractParallelInfo:
404
+ def test_extracts_rank_size_pairs(self) -> None:
405
+ info: dict = {
406
+ "tp_rank": 1,
407
+ "tp_size": 4,
408
+ "pp_rank": 0,
409
+ "pp_size": 2,
410
+ }
411
+ row_data: dict = {}
412
+ _extract_parallel_info(row_data=row_data, info=info)
413
+
414
+ assert row_data["tp"] == "1/4"
415
+ assert row_data["pp"] == "0/2"
416
+
417
+ def test_skips_error_info(self) -> None:
418
+ row_data: dict = {}
419
+ _extract_parallel_info(
420
+ row_data=row_data, info={"error": True, "tp_rank": 0, "tp_size": 1}
421
+ )
422
+ assert row_data == {}
423
+
424
+ def test_skips_empty_info(self) -> None:
425
+ row_data: dict = {}
426
+ _extract_parallel_info(row_data=row_data, info={})
427
+ assert row_data == {}
428
+
429
+ def test_ignores_rank_without_size(self) -> None:
430
+ row_data: dict = {}
431
+ _extract_parallel_info(row_data=row_data, info={"tp_rank": 0})
432
+ assert "tp" not in row_data
433
+
434
+
435
+ class TestRenderPolarsAsRichTable:
436
+ def test_basic_dataframe_renders_table(self) -> None:
437
+ df = pl.DataFrame({"a": [1, 2], "b": ["x", "y"]})
438
+ table = _render_polars_as_rich_table(df)
439
+ assert len(table.columns) == 2
440
+ assert table.row_count == 2
441
+
442
+ def test_empty_dataframe_returns_table_with_no_rows(self) -> None:
443
+ df = pl.DataFrame(
444
+ {"a": pl.Series([], dtype=pl.Int64), "b": pl.Series([], dtype=pl.Utf8)}
445
+ )
446
+ table = _render_polars_as_rich_table(df)
447
+ assert len(table.columns) == 2
448
+ assert table.row_count == 0
449
+
450
+ def test_title_passed_to_table(self) -> None:
451
+ df = pl.DataFrame({"a": [1]})
452
+ table = _render_polars_as_rich_table(df, title="My Title")
453
+ assert table.title == "My Title"
454
+
455
+ def test_no_title_defaults_to_none(self) -> None:
456
+ df = pl.DataFrame({"x": [1]})
457
+ table = _render_polars_as_rich_table(df)
458
+ assert table.title is None
459
+
460
+ def test_column_names_match_dataframe(self) -> None:
461
+ df = pl.DataFrame({"alpha": [1], "beta": [2], "gamma": [3]})
462
+ table = _render_polars_as_rich_table(df)
463
+ column_headers: list[str] = [col.header for col in table.columns]
464
+ assert column_headers == ["alpha", "beta", "gamma"]
465
+
466
+ def test_values_converted_to_strings(self) -> None:
467
+ """Numeric and None values should be stringified in the rendered output."""
468
+ df = pl.DataFrame({"num": [42], "text": ["hello"]})
469
+ table = _render_polars_as_rich_table(df)
470
+ rendered: str = _render_rich(table)
471
+ assert "42" in rendered
472
+ assert "hello" in rendered
473
+
474
+ def test_single_column_dataframe(self) -> None:
475
+ df = pl.DataFrame({"only_col": [10, 20, 30]})
476
+ table = _render_polars_as_rich_table(df)
477
+ assert len(table.columns) == 1
478
+ assert table.row_count == 3
479
+
480
+ def test_many_rows_all_present(self) -> None:
481
+ """All rows from the dataframe appear in the rich table."""
482
+ df = pl.DataFrame({"val": list(range(50))})
483
+ table = _render_polars_as_rich_table(df)
484
+ assert table.row_count == 50
485
+
486
+ def test_null_values_rendered_as_string(self) -> None:
487
+ """Null values should be converted to their string representation."""
488
+ df = pl.DataFrame({"a": [1, None, 3]})
489
+ table = _render_polars_as_rich_table(df)
490
+ assert table.row_count == 3
491
+ rendered: str = _render_rich(table)
492
+ assert (
493
+ "null" in rendered.lower()
494
+ or "none" in rendered.lower()
495
+ or "None" in rendered
496
+ )
497
+
498
+
499
+ if __name__ == "__main__":
500
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dp_utils.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis
7
+ from sglang.srt.debug_utils.comparator.dp_utils import (
8
+ _extract_dp_info,
9
+ _group_has_data,
10
+ filter_to_non_empty_dp_rank,
11
+ )
12
+ from sglang.srt.debug_utils.dump_loader import ValueWithMeta
13
+ from sglang.test.ci.ci_register import register_cpu_ci
14
+
15
+ register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True)
16
+
17
+
18
+ def _make_sglang_meta(
19
+ *, tp_rank: int = 0, tp_size: int = 1, dp_rank: int = 0, dp_size: int = 1
20
+ ) -> dict:
21
+ return {
22
+ "sglang_parallel_info": {
23
+ "tp_rank": tp_rank,
24
+ "tp_size": tp_size,
25
+ "dp_rank": dp_rank,
26
+ "dp_size": dp_size,
27
+ }
28
+ }
29
+
30
+
31
+ def _make_megatron_meta(
32
+ *, tp_rank: int = 0, tp_size: int = 1, dp_rank: int = 0, dp_size: int = 1
33
+ ) -> dict:
34
+ return {
35
+ "megatron_parallel_info": {
36
+ "tp_rank": tp_rank,
37
+ "tp_size": tp_size,
38
+ "dp_rank": dp_rank,
39
+ "dp_size": dp_size,
40
+ }
41
+ }
42
+
43
+
44
+ def _make_item(value: object, meta: dict) -> ValueWithMeta:
45
+ return ValueWithMeta(value=value, meta=meta)
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # _extract_dp_info
50
+ # ---------------------------------------------------------------------------
51
+
52
+
53
+ class TestExtractDpInfo:
54
+ def test_sglang_dp(self) -> None:
55
+ meta: dict = _make_sglang_meta(dp_rank=1, dp_size=4)
56
+ assert _extract_dp_info(meta, dp_axis=ParallelAxis.DP) == (1, 4)
57
+
58
+ def test_megatron_dp(self) -> None:
59
+ meta: dict = _make_megatron_meta(dp_rank=2, dp_size=8)
60
+ assert _extract_dp_info(meta, dp_axis=ParallelAxis.DP) == (2, 8)
61
+
62
+ def test_no_parallel_info(self) -> None:
63
+ assert _extract_dp_info({}, dp_axis=ParallelAxis.DP) is None
64
+
65
+ def test_no_dp_fields(self) -> None:
66
+ meta: dict = {"sglang_parallel_info": {"tp_rank": 0, "tp_size": 2}}
67
+ assert _extract_dp_info(meta, dp_axis=ParallelAxis.DP) is None
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # _group_has_data
72
+ # ---------------------------------------------------------------------------
73
+
74
+
75
+ class TestGroupHasData:
76
+ def test_non_empty_tensor(self) -> None:
77
+ item: ValueWithMeta = _make_item(value=torch.tensor([1, 2, 3]), meta={})
78
+ assert _group_has_data([item]) is True
79
+
80
+ def test_empty_tensor(self) -> None:
81
+ item: ValueWithMeta = _make_item(value=torch.tensor([]), meta={})
82
+ assert _group_has_data([item]) is False
83
+
84
+ def test_non_tensor_value(self) -> None:
85
+ item: ValueWithMeta = _make_item(value="hello", meta={})
86
+ assert _group_has_data([item]) is False
87
+
88
+ def test_empty_group(self) -> None:
89
+ assert _group_has_data([]) is False
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # filter_to_non_empty_dp_rank
94
+ # ---------------------------------------------------------------------------
95
+
96
+
97
+ class TestFilterToNonEmptyDpRank:
98
+ def test_dp_size_1_returns_unchanged(self) -> None:
99
+ items: list[ValueWithMeta] = [
100
+ _make_item(
101
+ value=torch.tensor([1.0]),
102
+ meta=_make_sglang_meta(dp_size=1),
103
+ ),
104
+ ]
105
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
106
+ items, dp_axis=ParallelAxis.DP
107
+ )
108
+ assert result is items
109
+
110
+ def test_no_parallel_info_returns_unchanged(self) -> None:
111
+ items: list[ValueWithMeta] = [
112
+ _make_item(value=torch.tensor([1.0]), meta={}),
113
+ ]
114
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
115
+ items, dp_axis=ParallelAxis.DP
116
+ )
117
+ assert result is items
118
+
119
+ def test_empty_list_returns_empty(self) -> None:
120
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
121
+ [], dp_axis=ParallelAxis.DP
122
+ )
123
+ assert result == []
124
+
125
+ def test_dp2_all_non_tensor_returns_unchanged(self) -> None:
126
+ """DP=2 with non-tensor values: skip filtering, return unchanged."""
127
+ items: list[ValueWithMeta] = [
128
+ _make_item(
129
+ value=["req_A"],
130
+ meta=_make_sglang_meta(dp_rank=0, dp_size=2),
131
+ ),
132
+ _make_item(
133
+ value=["req_A"],
134
+ meta=_make_sglang_meta(dp_rank=1, dp_size=2),
135
+ ),
136
+ ]
137
+
138
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
139
+ items, dp_axis=ParallelAxis.DP
140
+ )
141
+
142
+ assert result is items
143
+
144
+ def test_dp2_one_empty_one_nonempty_sglang(self) -> None:
145
+ """DP=2, rank 0 has data, rank 1 has empty tensor."""
146
+ items: list[ValueWithMeta] = [
147
+ _make_item(
148
+ value=torch.tensor([1.0, 2.0]),
149
+ meta=_make_sglang_meta(dp_rank=0, dp_size=2),
150
+ ),
151
+ _make_item(
152
+ value=torch.tensor([]),
153
+ meta=_make_sglang_meta(dp_rank=1, dp_size=2),
154
+ ),
155
+ ]
156
+
157
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
158
+ items, dp_axis=ParallelAxis.DP
159
+ )
160
+
161
+ assert len(result) == 1
162
+ assert torch.equal(result[0].value, torch.tensor([1.0, 2.0]))
163
+
164
+ def test_dp2_one_empty_one_nonempty_megatron(self) -> None:
165
+ """DP=2 megatron, rank 1 has data, rank 0 has empty tensor."""
166
+ items: list[ValueWithMeta] = [
167
+ _make_item(
168
+ value=torch.tensor([]),
169
+ meta=_make_megatron_meta(dp_rank=0, dp_size=2),
170
+ ),
171
+ _make_item(
172
+ value=torch.tensor([3.0, 4.0]),
173
+ meta=_make_megatron_meta(dp_rank=1, dp_size=2),
174
+ ),
175
+ ]
176
+
177
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
178
+ items, dp_axis=ParallelAxis.DP
179
+ )
180
+
181
+ assert len(result) == 1
182
+ assert torch.equal(result[0].value, torch.tensor([3.0, 4.0]))
183
+
184
+ def test_dp2_both_nonempty_raises(self) -> None:
185
+ """DP=2, both ranks have data: assertion error."""
186
+ items: list[ValueWithMeta] = [
187
+ _make_item(
188
+ value=torch.tensor([1.0]),
189
+ meta=_make_sglang_meta(dp_rank=0, dp_size=2),
190
+ ),
191
+ _make_item(
192
+ value=torch.tensor([2.0]),
193
+ meta=_make_sglang_meta(dp_rank=1, dp_size=2),
194
+ ),
195
+ ]
196
+
197
+ with pytest.raises(
198
+ AssertionError, match="Expected exactly 1 non-empty dp_rank"
199
+ ):
200
+ filter_to_non_empty_dp_rank(items, dp_axis=ParallelAxis.DP)
201
+
202
+ def test_dp2_with_tp2_filters_correctly(self) -> None:
203
+ """DP=2 x TP=2: 4 items total, 2 non-empty from dp_rank=0."""
204
+ items: list[ValueWithMeta] = [
205
+ _make_item(
206
+ value=torch.tensor([1.0]),
207
+ meta=_make_sglang_meta(tp_rank=0, tp_size=2, dp_rank=0, dp_size=2),
208
+ ),
209
+ _make_item(
210
+ value=torch.tensor([2.0]),
211
+ meta=_make_sglang_meta(tp_rank=1, tp_size=2, dp_rank=0, dp_size=2),
212
+ ),
213
+ _make_item(
214
+ value=torch.tensor([]),
215
+ meta=_make_sglang_meta(tp_rank=0, tp_size=2, dp_rank=1, dp_size=2),
216
+ ),
217
+ _make_item(
218
+ value=torch.tensor([]),
219
+ meta=_make_sglang_meta(tp_rank=1, tp_size=2, dp_rank=1, dp_size=2),
220
+ ),
221
+ ]
222
+
223
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
224
+ items, dp_axis=ParallelAxis.DP
225
+ )
226
+
227
+ assert len(result) == 2
228
+ assert torch.equal(result[0].value, torch.tensor([1.0]))
229
+ assert torch.equal(result[1].value, torch.tensor([2.0]))
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # dp_axis tests (non-default axis)
234
+ # ---------------------------------------------------------------------------
235
+
236
+
237
+ class TestExtractDpInfoWithAxis:
238
+ def test_moe_dp_axis_found(self) -> None:
239
+ meta: dict = {
240
+ "sglang_parallel_info": {
241
+ "dp_rank": 0,
242
+ "dp_size": 2,
243
+ "moe_dp_rank": 1,
244
+ "moe_dp_size": 4,
245
+ }
246
+ }
247
+ assert _extract_dp_info(meta, dp_axis=ParallelAxis.MOE_DP) == (1, 4)
248
+
249
+ def test_moe_dp_axis_not_found_returns_none(self) -> None:
250
+ meta: dict = _make_sglang_meta(dp_rank=0, dp_size=2)
251
+ assert _extract_dp_info(meta, dp_axis=ParallelAxis.MOE_DP) is None
252
+
253
+ def test_dp_axis_uses_default_fields(self) -> None:
254
+ meta: dict = _make_sglang_meta(dp_rank=1, dp_size=4)
255
+ assert _extract_dp_info(meta, dp_axis=ParallelAxis.DP) == (1, 4)
256
+
257
+
258
+ class TestFilterToNonEmptyDpRankWithAxis:
259
+ def test_dp_axis_unchanged_behavior(self) -> None:
260
+ """dp_axis=ParallelAxis.DP → same behavior as default (regression)."""
261
+ items: list[ValueWithMeta] = [
262
+ _make_item(
263
+ value=torch.tensor([1.0, 2.0]),
264
+ meta=_make_sglang_meta(dp_rank=0, dp_size=2),
265
+ ),
266
+ _make_item(
267
+ value=torch.tensor([]),
268
+ meta=_make_sglang_meta(dp_rank=1, dp_size=2),
269
+ ),
270
+ ]
271
+
272
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
273
+ items, dp_axis=ParallelAxis.DP
274
+ )
275
+
276
+ assert len(result) == 1
277
+ assert torch.equal(result[0].value, torch.tensor([1.0, 2.0]))
278
+
279
+ def test_moe_dp_axis_absent_noop(self) -> None:
280
+ """MOE_DP axis fields not in metadata → noop, return items unchanged."""
281
+ items: list[ValueWithMeta] = [
282
+ _make_item(
283
+ value=torch.tensor([1.0]),
284
+ meta=_make_sglang_meta(dp_rank=0, dp_size=2),
285
+ ),
286
+ _make_item(
287
+ value=torch.tensor([2.0]),
288
+ meta=_make_sglang_meta(dp_rank=1, dp_size=2),
289
+ ),
290
+ ]
291
+
292
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
293
+ items, dp_axis=ParallelAxis.MOE_DP
294
+ )
295
+
296
+ assert result is items
297
+
298
+ def test_moe_dp_axis_size_1_noop(self) -> None:
299
+ """MOE_DP axis present but size=1 → noop."""
300
+ meta: dict = {
301
+ "sglang_parallel_info": {
302
+ "dp_rank": 0,
303
+ "dp_size": 2,
304
+ "moe_dp_rank": 0,
305
+ "moe_dp_size": 1,
306
+ }
307
+ }
308
+ items: list[ValueWithMeta] = [
309
+ _make_item(value=torch.tensor([1.0]), meta=meta),
310
+ ]
311
+
312
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
313
+ items, dp_axis=ParallelAxis.MOE_DP
314
+ )
315
+
316
+ assert result is items
317
+
318
+ def test_moe_dp_axis_filters_correctly(self) -> None:
319
+ """MOE_DP axis size=2, one empty rank → correctly filters."""
320
+ meta_rank0: dict = {
321
+ "sglang_parallel_info": {
322
+ "dp_rank": 0,
323
+ "dp_size": 2,
324
+ "moe_dp_rank": 0,
325
+ "moe_dp_size": 2,
326
+ }
327
+ }
328
+ meta_rank1: dict = {
329
+ "sglang_parallel_info": {
330
+ "dp_rank": 0,
331
+ "dp_size": 2,
332
+ "moe_dp_rank": 1,
333
+ "moe_dp_size": 2,
334
+ }
335
+ }
336
+ items: list[ValueWithMeta] = [
337
+ _make_item(value=torch.tensor([1.0, 2.0]), meta=meta_rank0),
338
+ _make_item(value=torch.tensor([]), meta=meta_rank1),
339
+ ]
340
+
341
+ result: list[ValueWithMeta] = filter_to_non_empty_dp_rank(
342
+ items, dp_axis=ParallelAxis.MOE_DP
343
+ )
344
+
345
+ assert len(result) == 1
346
+ assert torch.equal(result[0].value, torch.tensor([1.0, 2.0]))
347
+
348
+
349
+ if __name__ == "__main__":
350
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dump_loader.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+ import torch
6
+
7
+ from sglang.srt.debug_utils.dump_loader import read_tokenizer_path
8
+ from sglang.test.ci.ci_register import register_cpu_ci
9
+
10
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
11
+
12
+
13
+ def _save_pt(
14
+ directory: Path, filename: str, *, value: torch.Tensor, meta: dict
15
+ ) -> None:
16
+ torch.save({"value": value, "meta": meta}, directory / filename)
17
+
18
+
19
+ class TestReadTokenizerPath:
20
+ def test_finds_tokenizer_path(self, tmp_path: Path) -> None:
21
+ _save_pt(
22
+ tmp_path,
23
+ "name=x___step=0___rank=0___dump_index=0.pt",
24
+ value=torch.tensor([1.0]),
25
+ meta={"tokenizer_path": "/models/llama-3"},
26
+ )
27
+ result = read_tokenizer_path(tmp_path)
28
+ assert result == "/models/llama-3"
29
+
30
+ def test_returns_none_when_no_tokenizer_path(self, tmp_path: Path) -> None:
31
+ _save_pt(
32
+ tmp_path,
33
+ "name=x___step=0___rank=0___dump_index=0.pt",
34
+ value=torch.tensor([1.0]),
35
+ meta={},
36
+ )
37
+ result = read_tokenizer_path(tmp_path)
38
+ assert result is None
39
+
40
+ def test_returns_none_for_empty_directory(self, tmp_path: Path) -> None:
41
+ result = read_tokenizer_path(tmp_path)
42
+ assert result is None
43
+
44
+ def test_skips_files_without_tokenizer_path(self, tmp_path: Path) -> None:
45
+ _save_pt(
46
+ tmp_path,
47
+ "name=a___step=0___rank=0___dump_index=0.pt",
48
+ value=torch.tensor([1.0]),
49
+ meta={},
50
+ )
51
+ _save_pt(
52
+ tmp_path,
53
+ "name=b___step=0___rank=0___dump_index=1.pt",
54
+ value=torch.tensor([2.0]),
55
+ meta={"tokenizer_path": "/models/deepseek"},
56
+ )
57
+ result = read_tokenizer_path(tmp_path)
58
+ assert result == "/models/deepseek"
59
+
60
+
61
+ if __name__ == "__main__":
62
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_e2e_demo.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal demo: run the comparator on synthetic data and print its output.
2
+
3
+ This is NOT a correctness test suite.
4
+ The sole purpose is to let a new user run ``pytest -s test_e2e_demo.py``
5
+ and immediately see what comparator text output looks like (passed, failed,
6
+ skipped in one shot). Correctness is verified via the JSONL report file.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ from pathlib import Path
13
+ from typing import Dict, List, Optional
14
+
15
+ import pytest
16
+ import torch
17
+
18
+ import sglang.srt.debug_utils.dumper as _dumper_module
19
+ from sglang.srt.debug_utils.comparator.entrypoint import parse_args, run
20
+ from sglang.srt.debug_utils.comparator.output_types import (
21
+ AnyRecord,
22
+ ComparisonErrorRecord,
23
+ SummaryRecord,
24
+ parse_record_json,
25
+ )
26
+ from sglang.srt.debug_utils.dumper import DumperConfig, _Dumper
27
+ from sglang.test.ci.ci_register import register_cpu_ci
28
+
29
+ register_cpu_ci(est_time=10, suite="default", nightly=True)
30
+
31
+ _EXP_NAME = "demo_exp"
32
+
33
+
34
+ # This file has exactly ONE test. All demo scenarios go here — do not add separate tests.
35
+ def test_demo(tmp_path: Path) -> None:
36
+ """Passed + failed + skipped + sharded + errored in a single demo file."""
37
+ torch.manual_seed(0)
38
+ good_tensor = torch.randn(4, 8)
39
+ sharded_full = torch.randn(2, 8, 16)
40
+
41
+ baseline_dir = tmp_path / "baseline"
42
+ target_dir = tmp_path / "target"
43
+ baseline_dir.mkdir()
44
+ target_dir.mkdir()
45
+
46
+ # Step 1: simple tensors (single rank, no parallelism)
47
+ _dump_single(baseline_dir, name="my_good_tensor", tensor=good_tensor)
48
+ _dump_single(baseline_dir, name="my_bad_tensor", tensor=torch.randn(4, 8))
49
+
50
+ _dump_single(
51
+ target_dir, name="my_good_tensor", tensor=good_tensor + torch.randn(4, 8) * 1e-5
52
+ )
53
+ _dump_single(target_dir, name="my_bad_tensor", tensor=torch.randn(4, 8) * 100)
54
+ _dump_single(target_dir, name="my_orphan_tensor", tensor=torch.randn(4, 8))
55
+
56
+ # Step 2: sharded tensor (BSHD) — baseline: TP=2 on h, target: CP=2 zigzag + SP=2 on s
57
+ sharded_target = sharded_full + torch.randn_like(sharded_full) * 1e-5
58
+ _dump_tp_sharded(
59
+ baseline_dir, name="my_sharded_tensor", full_tensor=sharded_full, tp_size=2
60
+ )
61
+ _dump_cp_zigzag_sp_sharded(
62
+ target_dir,
63
+ name="my_sharded_tensor",
64
+ full_tensor=sharded_target,
65
+ cp_size=2,
66
+ sp_size=2,
67
+ )
68
+
69
+ # Step 3: bad dims — target says h[cp] but parallel_info has tp → undeclared axis error
70
+ bad_dims_tensor = torch.randn(2, 8, 16)
71
+ for tp_rank, shard in enumerate(bad_dims_tensor.chunk(2, dim=-1)):
72
+ _dump_rank(
73
+ baseline_dir,
74
+ rank=tp_rank,
75
+ name="my_bad_dims_tensor",
76
+ tensor=shard,
77
+ dims="b s h[tp]",
78
+ parallel_info={"tp_rank": tp_rank, "tp_size": 2},
79
+ )
80
+ _dump_rank(
81
+ target_dir,
82
+ rank=tp_rank,
83
+ name="my_bad_dims_tensor",
84
+ tensor=shard,
85
+ dims="b s h[cp]",
86
+ parallel_info={"tp_rank": tp_rank, "tp_size": 2},
87
+ )
88
+
89
+ baseline_exp = baseline_dir / _EXP_NAME
90
+ target_exp = target_dir / _EXP_NAME
91
+
92
+ # Step 4: run normal, then verbose
93
+ for verbosity in ("normal", "verbose"):
94
+ report_path = tmp_path / f"report_{verbosity}.jsonl"
95
+ _run(
96
+ baseline_exp,
97
+ target_exp,
98
+ report_path=report_path,
99
+ output_format="text",
100
+ verbosity=verbosity,
101
+ )
102
+ _assert_summary(report_path, passed=2, failed=1, skipped=1, errored=1)
103
+
104
+ # Step 5: verify error record content
105
+ records = _read_report(tmp_path / "report_verbose.jsonl")
106
+ errors = [r for r in records if isinstance(r, ComparisonErrorRecord)]
107
+ assert len(errors) == 1
108
+ assert "tp" in errors[0].exception_message
109
+ assert "--override-dims" in errors[0].traceback_str
110
+
111
+
112
+ # ── Helpers ──────────────────────────────────────────────────────────
113
+
114
+
115
+ def _assert_summary(
116
+ report_path: Path, *, passed: int, failed: int, skipped: int, errored: int = 0
117
+ ) -> None:
118
+ records = _read_report(report_path)
119
+ summary = next(r for r in records if isinstance(r, SummaryRecord))
120
+ assert summary.passed == passed
121
+ assert summary.failed == failed
122
+ assert summary.skipped == skipped
123
+ assert summary.errored == errored
124
+
125
+
126
+ def _dump_single(directory: Path, *, name: str, tensor: torch.Tensor) -> None:
127
+ _dump_rank(directory, rank=0, name=name, tensor=tensor)
128
+
129
+
130
+ def _dump_tp_sharded(
131
+ directory: Path,
132
+ *,
133
+ name: str,
134
+ full_tensor: torch.Tensor,
135
+ tp_size: int,
136
+ ) -> None:
137
+ """Dump TP-sharded tensor: dims="b s h[tp]", shard along last dim."""
138
+ shards = list(full_tensor.chunk(tp_size, dim=-1))
139
+ for tp_rank, shard in enumerate(shards):
140
+ _dump_rank(
141
+ directory,
142
+ rank=tp_rank,
143
+ name=name,
144
+ tensor=shard,
145
+ dims="b s h[tp]",
146
+ parallel_info={"tp_rank": tp_rank, "tp_size": tp_size},
147
+ )
148
+
149
+
150
+ def _dump_cp_zigzag_sp_sharded(
151
+ directory: Path,
152
+ *,
153
+ name: str,
154
+ full_tensor: torch.Tensor,
155
+ cp_size: int,
156
+ sp_size: int,
157
+ ) -> None:
158
+ """Dump CP-zigzag+SP sharded tensor: dims="b s[cp:zigzag,sp] h", shard seq dim."""
159
+ seq_dim = 1
160
+ num_chunks = cp_size * 2
161
+ natural_chunks = list(full_tensor.chunk(num_chunks, dim=seq_dim))
162
+
163
+ zigzag_order: List[int] = []
164
+ for i in range(cp_size):
165
+ zigzag_order.append(i)
166
+ zigzag_order.append(num_chunks - 1 - i)
167
+
168
+ zigzagged = torch.cat([natural_chunks[idx] for idx in zigzag_order], dim=seq_dim)
169
+ cp_chunks = list(zigzagged.chunk(cp_size, dim=seq_dim))
170
+
171
+ rank = 0
172
+ for cp_rank in range(cp_size):
173
+ sp_chunks = list(cp_chunks[cp_rank].chunk(sp_size, dim=seq_dim))
174
+ for sp_rank in range(sp_size):
175
+ _dump_rank(
176
+ directory,
177
+ rank=rank,
178
+ name=name,
179
+ tensor=sp_chunks[sp_rank],
180
+ dims="b s[cp:zigzag,sp] h",
181
+ parallel_info={
182
+ "cp_rank": cp_rank,
183
+ "cp_size": cp_size,
184
+ "sp_rank": sp_rank,
185
+ "sp_size": sp_size,
186
+ },
187
+ )
188
+ rank += 1
189
+
190
+
191
+ def _dump_rank(
192
+ directory: Path,
193
+ *,
194
+ rank: int,
195
+ name: str,
196
+ tensor: torch.Tensor,
197
+ dims: Optional[str] = None,
198
+ parallel_info: Optional[Dict[str, int]] = None,
199
+ ) -> None:
200
+ with pytest.MonkeyPatch.context() as mp:
201
+ mp.setattr(_dumper_module, "_get_rank", lambda: rank)
202
+ dumper = _Dumper(
203
+ config=DumperConfig(enable=True, dir=str(directory), exp_name=_EXP_NAME)
204
+ )
205
+ static_meta: Dict[str, object] = {"world_rank": rank, "world_size": 1}
206
+ if parallel_info is not None:
207
+ static_meta["sglang_parallel_info"] = parallel_info
208
+ dumper.__dict__["_static_meta"] = static_meta
209
+ dumper.dump(name, tensor, dims=dims)
210
+ dumper.step()
211
+
212
+
213
+ def _run(
214
+ baseline_path: Path,
215
+ target_path: Path,
216
+ *,
217
+ report_path: Path,
218
+ output_format: str = "text",
219
+ verbosity: str = "normal",
220
+ ) -> int:
221
+ argv = [
222
+ "--baseline-path",
223
+ str(baseline_path),
224
+ "--target-path",
225
+ str(target_path),
226
+ "--output-format",
227
+ output_format,
228
+ "--verbosity",
229
+ verbosity,
230
+ "--preset",
231
+ "sglang_dev",
232
+ "--report-path",
233
+ str(report_path),
234
+ ]
235
+ print(
236
+ f"\n $ python -m sglang.srt.debug_utils.comparator {' '.join(argv)}\n",
237
+ flush=True,
238
+ )
239
+ return run(parse_args(argv))
240
+
241
+
242
+ def _read_report(report_path: Path) -> List[AnyRecord]:
243
+ return [
244
+ parse_record_json(line) for line in report_path.read_text().strip().splitlines()
245
+ ]
246
+
247
+
248
+ if __name__ == "__main__":
249
+ sys.exit(pytest.main([__file__, "-s", "-v"]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_entrypoint.py ADDED
The diff for this file is too large to render. See raw diff
 
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_log_sink.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import sys
3
+
4
+ import pytest
5
+
6
+ from sglang.srt.debug_utils.comparator.log_sink import LogSink
7
+ from sglang.srt.debug_utils.comparator.output_types import (
8
+ ErrorLog,
9
+ InfoLog,
10
+ )
11
+ from sglang.srt.debug_utils.comparator.report_sink import report_sink
12
+ from sglang.test.ci.ci_register import register_cpu_ci
13
+
14
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
15
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
16
+
17
+
18
+ def _make_error_log(**overrides) -> ErrorLog:
19
+ defaults: dict = dict(
20
+ category="test",
21
+ message="test warning",
22
+ )
23
+ defaults.update(overrides)
24
+ return ErrorLog(**defaults)
25
+
26
+
27
+ class TestLogSink:
28
+ def test_basic_collection(self) -> None:
29
+ sink = LogSink()
30
+ log = _make_error_log()
31
+
32
+ with sink.context() as collected:
33
+ sink.add(log)
34
+
35
+ assert len(collected) == 1
36
+ assert collected[0] is log
37
+
38
+ def test_nested_contexts(self) -> None:
39
+ sink = LogSink()
40
+ outer_log = _make_error_log(message="outer")
41
+ inner_log = _make_error_log(message="inner")
42
+
43
+ with sink.context() as outer:
44
+ sink.add(outer_log)
45
+ with sink.context() as inner:
46
+ sink.add(inner_log)
47
+ assert len(inner) == 1
48
+ assert inner[0] is inner_log
49
+
50
+ assert len(outer) == 1
51
+ assert outer[0] is outer_log
52
+
53
+ def test_empty_context(self) -> None:
54
+ sink = LogSink()
55
+ with sink.context() as collected:
56
+ pass
57
+ assert collected == []
58
+
59
+ def test_add_outside_context_prints(self, capsys) -> None:
60
+ sink = LogSink()
61
+ report_sink.configure(output_format="text")
62
+
63
+ sink.add(_make_error_log())
64
+
65
+ captured = capsys.readouterr()
66
+ assert "test warning" in captured.out
67
+
68
+ def test_context_captures_instead_of_printing(self, capsys) -> None:
69
+ sink = LogSink()
70
+ report_sink.configure(output_format="text")
71
+
72
+ with sink.context() as collected:
73
+ sink.add(_make_error_log())
74
+
75
+ assert len(collected) == 1
76
+ captured = capsys.readouterr()
77
+ assert captured.out == ""
78
+
79
+ def test_json_output_outside_context(self, capsys) -> None:
80
+ sink = LogSink()
81
+ report_sink.configure(output_format="json")
82
+
83
+ sink.add(_make_error_log())
84
+
85
+ captured = capsys.readouterr()
86
+ parsed: dict = json.loads(captured.out.strip())
87
+ assert "errors" in parsed
88
+ assert len(parsed["errors"]) == 1
89
+
90
+ def test_info_log_outside_context_routes_to_infos(self, capsys) -> None:
91
+ """InfoLog added outside context populates LogRecord.infos, not errors."""
92
+ sink = LogSink()
93
+ report_sink.configure(output_format="json")
94
+
95
+ sink.add(InfoLog(category="test", message="info msg"))
96
+
97
+ parsed: dict = json.loads(capsys.readouterr().out.strip())
98
+ assert len(parsed["infos"]) == 1
99
+ assert len(parsed["errors"]) == 0
100
+
101
+ def test_exception_in_context_cleans_stack(self, capsys) -> None:
102
+ sink = LogSink()
103
+ report_sink.configure(output_format="text")
104
+
105
+ with pytest.raises(RuntimeError):
106
+ with sink.context() as collected:
107
+ sink.add(_make_error_log())
108
+ raise RuntimeError("boom")
109
+
110
+ assert len(collected) == 1
111
+
112
+ sink.add(_make_error_log(message="after exception"))
113
+ captured = capsys.readouterr()
114
+ assert "after exception" in captured.out
115
+
116
+
117
+ if __name__ == "__main__":
118
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_manually_verify.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Visual comparison figure tests — CI sanity check + human verification.
2
+
3
+ This file serves two purposes:
4
+ 1. CI sanity check: ensures generate_comparison_figure() runs without errors
5
+ across various tensor scenarios (registered via register_cpu_ci).
6
+ 2. Human verification: all generated PNGs are copied to /tmp/comparator_manual_verify/
7
+ so they can be pulled back to a local machine for visual inspection.
8
+
9
+ Run:
10
+ python -m pytest test/registered/debug_utils/comparator/test_manually_verify.py -x -v
11
+
12
+ Human verification:
13
+ After running, images are at /tmp/comparator_manual_verify/.
14
+ Each test's docstring describes the expected visual appearance.
15
+ """
16
+
17
+ import shutil
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import pytest
22
+ import torch
23
+
24
+ from sglang.test.ci.ci_register import register_cpu_ci
25
+
26
+ register_cpu_ci(est_time=60, suite="base-a-test-cpu", nightly=True)
27
+
28
+ _PUBLISH_DIR: Path = Path("/tmp/comparator_manual_verify")
29
+ _PNG_MAGIC: bytes = b"\x89PNG"
30
+
31
+
32
+ @pytest.fixture(scope="session")
33
+ def publish_dir() -> Path:
34
+ """Fixed output dir for human inspection — files are copied here after generation."""
35
+ if _PUBLISH_DIR.exists():
36
+ shutil.rmtree(_PUBLISH_DIR)
37
+ _PUBLISH_DIR.mkdir(parents=True)
38
+ return _PUBLISH_DIR
39
+
40
+
41
+ def _assert_valid_png(path: Path) -> None:
42
+ assert path.exists(), f"PNG not created: {path}"
43
+ assert path.stat().st_size > 0, f"PNG is empty: {path}"
44
+ with open(path, "rb") as f:
45
+ magic: bytes = f.read(4)
46
+ assert magic == _PNG_MAGIC, f"Not a valid PNG: {path}"
47
+
48
+
49
+ def _generate_and_publish(
50
+ *,
51
+ baseline: torch.Tensor,
52
+ target: torch.Tensor,
53
+ name: str,
54
+ tmp_path: Path,
55
+ publish_dir: Path,
56
+ ) -> Path:
57
+ from sglang.srt.debug_utils.comparator.visualizer import (
58
+ generate_comparison_figure,
59
+ )
60
+
61
+ output_path: Path = tmp_path / f"{name}.png"
62
+ generate_comparison_figure(
63
+ baseline=baseline,
64
+ target=target,
65
+ name=name,
66
+ output_path=output_path,
67
+ )
68
+
69
+ _assert_valid_png(output_path)
70
+ shutil.copy2(src=output_path, dst=publish_dir / output_path.name)
71
+ return output_path
72
+
73
+
74
+ @pytest.fixture(autouse=True)
75
+ def _skip_if_no_matplotlib() -> None:
76
+ pytest.importorskip("matplotlib")
77
+
78
+
79
+ class TestBundleDetailsManualVerify:
80
+ def test_normal_small_diff(self, tmp_path: Path, publish_dir: Path) -> None:
81
+ """Two nearly-identical tensors (randn + 0.01 noise).
82
+
83
+ Expected: All 6 panel rows visible. Diff heatmap nearly uniform light color.
84
+ Hist2d tightly clustered along the red diagonal line.
85
+ """
86
+ baseline: torch.Tensor = torch.randn(32, 64)
87
+ target: torch.Tensor = baseline + torch.randn(32, 64) * 0.01
88
+
89
+ _generate_and_publish(
90
+ baseline=baseline,
91
+ target=target,
92
+ name="normal_small_diff",
93
+ tmp_path=tmp_path,
94
+ publish_dir=publish_dir,
95
+ )
96
+
97
+ def test_significant_diff(self, tmp_path: Path, publish_dir: Path) -> None:
98
+ """Two tensors with larger differences (randn + 0.5 noise).
99
+
100
+ Expected: All 6 panel rows visible. Diff heatmap shows noticeable structure.
101
+ Hist2d scatter is broader, spread away from the diagonal.
102
+ """
103
+ baseline: torch.Tensor = torch.randn(32, 64)
104
+ target: torch.Tensor = baseline + torch.randn(32, 64) * 0.5
105
+
106
+ _generate_and_publish(
107
+ baseline=baseline,
108
+ target=target,
109
+ name="significant_diff",
110
+ tmp_path=tmp_path,
111
+ publish_dir=publish_dir,
112
+ )
113
+
114
+ def test_shape_mismatch(self, tmp_path: Path, publish_dir: Path) -> None:
115
+ """Baseline 32x64, target 16x32 — shapes do not match.
116
+
117
+ Expected: Only 2 panel rows (baseline heatmap, target heatmap).
118
+ No diff/histogram/hist2d/sampled panels since diff cannot be computed.
119
+ """
120
+ baseline: torch.Tensor = torch.randn(32, 64)
121
+ target: torch.Tensor = torch.randn(16, 32)
122
+
123
+ _generate_and_publish(
124
+ baseline=baseline,
125
+ target=target,
126
+ name="shape_mismatch",
127
+ tmp_path=tmp_path,
128
+ publish_dir=publish_dir,
129
+ )
130
+
131
+ def test_large_tensor(self, tmp_path: Path, publish_dir: Path) -> None:
132
+ """4000x4000 tensor — triggers internal downsampling.
133
+
134
+ Expected: Figure renders normally without OOM. Downsampled panels
135
+ should still look reasonable.
136
+ """
137
+ baseline: torch.Tensor = torch.randn(4000, 4000)
138
+ target: torch.Tensor = baseline + torch.randn(4000, 4000) * 0.001
139
+
140
+ _generate_and_publish(
141
+ baseline=baseline,
142
+ target=target,
143
+ name="large_tensor",
144
+ tmp_path=tmp_path,
145
+ publish_dir=publish_dir,
146
+ )
147
+
148
+ def test_1d_tensor(self, tmp_path: Path, publish_dir: Path) -> None:
149
+ """1D tensor (256,) — internally reshaped to 2D before plotting.
150
+
151
+ Expected: All 6 panel rows visible. The heatmap shape reflects the
152
+ reshaped 2D form, not the original 1D.
153
+ """
154
+ baseline: torch.Tensor = torch.randn(256)
155
+ target: torch.Tensor = baseline + 0.01
156
+
157
+ _generate_and_publish(
158
+ baseline=baseline,
159
+ target=target,
160
+ name="1d_tensor",
161
+ tmp_path=tmp_path,
162
+ publish_dir=publish_dir,
163
+ )
164
+
165
+ def test_constant_tensor(self, tmp_path: Path, publish_dir: Path) -> None:
166
+ """All-zero baseline, tiny-valued target.
167
+
168
+ Expected: Colorbar range is extremely small. Histogram concentrates in
169
+ a single bin. No rendering errors from near-zero variance.
170
+ """
171
+ baseline: torch.Tensor = torch.zeros(32, 64)
172
+ target: torch.Tensor = torch.ones(32, 64) * 1e-8
173
+
174
+ _generate_and_publish(
175
+ baseline=baseline,
176
+ target=target,
177
+ name="constant_tensor",
178
+ tmp_path=tmp_path,
179
+ publish_dir=publish_dir,
180
+ )
181
+
182
+ def test_extreme_values(self, tmp_path: Path, publish_dir: Path) -> None:
183
+ """Tensor containing values spanning 1e-10 to 1e10.
184
+
185
+ Expected: Log10 panels handle the wide range gracefully. No inf/nan
186
+ artifacts in the rendered figure.
187
+ """
188
+ baseline: torch.Tensor = torch.randn(32, 64).abs()
189
+ baseline[0, 0] = 1e-10
190
+ baseline[0, 1] = 1e10
191
+ target: torch.Tensor = baseline + torch.randn(32, 64) * 0.01
192
+
193
+ _generate_and_publish(
194
+ baseline=baseline,
195
+ target=target,
196
+ name="extreme_values",
197
+ tmp_path=tmp_path,
198
+ publish_dir=publish_dir,
199
+ )
200
+
201
+
202
+ class TestPerTokenHeatmapManualVerify:
203
+ def test_increasing_diff(self, tmp_path: Path, publish_dir: Path) -> None:
204
+ """Per-token heatmap with linearly increasing diff across token positions.
205
+
206
+ Expected: Heatmap shows a clear left-to-right gradient — dark/cold on
207
+ the left (small diff), bright/hot on the right (large diff). Multiple
208
+ rows for different tensor names. Colorbar shows log10 scale.
209
+ """
210
+ from sglang.srt.debug_utils.comparator.output_types import (
211
+ ComparisonTensorRecord,
212
+ )
213
+ from sglang.srt.debug_utils.comparator.per_token_visualizer import (
214
+ generate_per_token_heatmap,
215
+ )
216
+ from sglang.srt.debug_utils.comparator.tensor_comparator.comparator import (
217
+ compare_tensor_pair,
218
+ )
219
+
220
+ torch.manual_seed(42)
221
+ seq_len: int = 64
222
+ hidden_dim: int = 128
223
+ num_tensors: int = 5
224
+
225
+ records: list[ComparisonTensorRecord] = []
226
+ for i in range(num_tensors):
227
+ baseline: torch.Tensor = torch.randn(seq_len, hidden_dim)
228
+ noise_scale: torch.Tensor = torch.linspace(
229
+ 1e-6, 0.5, steps=seq_len
230
+ ).unsqueeze(1)
231
+ target: torch.Tensor = baseline + torch.randn_like(baseline) * noise_scale
232
+
233
+ info = compare_tensor_pair(
234
+ x_baseline=baseline,
235
+ x_target=target,
236
+ name=f"layer_{i}_hidden_states",
237
+ diff_threshold=1e-3,
238
+ seq_dim=0,
239
+ )
240
+ records.append(ComparisonTensorRecord(**info.model_dump()))
241
+
242
+ output_path: Path = tmp_path / "per_token_increasing_diff.png"
243
+ result = generate_per_token_heatmap(records=records, output_path=output_path)
244
+
245
+ assert result is not None
246
+ _assert_valid_png(output_path)
247
+ shutil.copy2(src=output_path, dst=publish_dir / output_path.name)
248
+
249
+ def test_single_spike(self, tmp_path: Path, publish_dir: Path) -> None:
250
+ """Per-token heatmap where only one token position has large diff.
251
+
252
+ Expected: Heatmap shows one bright vertical stripe at the spike position,
253
+ rest is dark/cold.
254
+ """
255
+ from sglang.srt.debug_utils.comparator.output_types import (
256
+ ComparisonTensorRecord,
257
+ )
258
+ from sglang.srt.debug_utils.comparator.per_token_visualizer import (
259
+ generate_per_token_heatmap,
260
+ )
261
+ from sglang.srt.debug_utils.comparator.tensor_comparator.comparator import (
262
+ compare_tensor_pair,
263
+ )
264
+
265
+ torch.manual_seed(42)
266
+ seq_len: int = 64
267
+ hidden_dim: int = 128
268
+ spike_pos: int = 32
269
+ num_tensors: int = 4
270
+
271
+ records: list[ComparisonTensorRecord] = []
272
+ for i in range(num_tensors):
273
+ baseline: torch.Tensor = torch.randn(seq_len, hidden_dim)
274
+ target: torch.Tensor = baseline.clone()
275
+ target[spike_pos, :] += torch.randn(hidden_dim) * 5.0
276
+
277
+ info = compare_tensor_pair(
278
+ x_baseline=baseline,
279
+ x_target=target,
280
+ name=f"layer_{i}_attn_output",
281
+ diff_threshold=1e-3,
282
+ seq_dim=0,
283
+ )
284
+ records.append(ComparisonTensorRecord(**info.model_dump()))
285
+
286
+ output_path: Path = tmp_path / "per_token_single_spike.png"
287
+ result = generate_per_token_heatmap(records=records, output_path=output_path)
288
+
289
+ assert result is not None
290
+ _assert_valid_png(output_path)
291
+ shutil.copy2(src=output_path, dst=publish_dir / output_path.name)
292
+
293
+
294
+ if __name__ == "__main__":
295
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_meta_overrider.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for meta_overrider — unit tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import textwrap
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+
11
+ from sglang.srt.debug_utils.comparator.meta_overrider import (
12
+ MetaOverrider,
13
+ MetaOverrideRule,
14
+ _load_yaml_rules,
15
+ _parse_cli_override_arg,
16
+ )
17
+ from sglang.test.ci.ci_register import register_cpu_ci
18
+
19
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
20
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
21
+
22
+
23
+ # ───────────────────── Unit: MetaOverrideRule ─────────────────────
24
+
25
+
26
+ class TestMetaOverrideRule:
27
+ """Pydantic validation for MetaOverrideRule."""
28
+
29
+ def test_shared_dims_both(self) -> None:
30
+ """Default side='both' applies dims to both sides."""
31
+ rule = MetaOverrideRule(match="hidden", dims="b s h d")
32
+ assert rule.dims == "b s h d"
33
+ assert rule.side == "both"
34
+
35
+ def test_side_baseline(self) -> None:
36
+ """side='baseline' is accepted."""
37
+ rule = MetaOverrideRule(match="logits", dims="b s v[tp]", side="baseline")
38
+ assert rule.dims == "b s v[tp]"
39
+ assert rule.side == "baseline"
40
+
41
+ def test_side_target(self) -> None:
42
+ """side='target' is accepted."""
43
+ rule = MetaOverrideRule(match="logits", dims="b s v[ep]", side="target")
44
+ assert rule.dims == "b s v[ep]"
45
+ assert rule.side == "target"
46
+
47
+ def test_invalid_side_rejected(self) -> None:
48
+ """Invalid side value is rejected."""
49
+ with pytest.raises(Exception):
50
+ MetaOverrideRule(match="x", dims="b s", side="invalid")
51
+
52
+ def test_dims_required(self) -> None:
53
+ """Must specify dims."""
54
+ with pytest.raises(Exception):
55
+ MetaOverrideRule(match="x")
56
+
57
+ def test_extra_field_rejected(self) -> None:
58
+ """Extra fields are rejected by _StrictBase."""
59
+ with pytest.raises(Exception):
60
+ MetaOverrideRule(match="x", dims="b s", bogus="y")
61
+
62
+
63
+ # ──────────────────── Unit: _parse_cli_override_arg ────────────────────
64
+
65
+
66
+ class TestParseCLIOverrideArg:
67
+ """CLI arg parsing for 'name:dims_string' format."""
68
+
69
+ def test_basic(self) -> None:
70
+ """Standard 'name:dims' parsing."""
71
+ name, dims_str = _parse_cli_override_arg("hidden_states:b s h d")
72
+ assert name == "hidden_states"
73
+ assert dims_str == "b s h d"
74
+
75
+ def test_colon_in_dims(self) -> None:
76
+ """Extra colons in dims are kept (maxsplit=1)."""
77
+ name, dims_str = _parse_cli_override_arg("x:a:b")
78
+ assert name == "x"
79
+ assert dims_str == "a:b"
80
+
81
+ def test_whitespace_trimmed(self) -> None:
82
+ """Leading/trailing whitespace around name and dims is stripped."""
83
+ name, dims_str = _parse_cli_override_arg(" foo : b s ")
84
+ assert name == "foo"
85
+ assert dims_str == "b s"
86
+
87
+ def test_missing_colon(self) -> None:
88
+ """No colon raises ValueError."""
89
+ with pytest.raises(ValueError, match="Invalid override format"):
90
+ _parse_cli_override_arg("no_colon_here")
91
+
92
+ def test_empty_name(self) -> None:
93
+ """Empty name raises ValueError."""
94
+ with pytest.raises(ValueError, match="Invalid override format"):
95
+ _parse_cli_override_arg(":b s h")
96
+
97
+ def test_empty_dims(self) -> None:
98
+ """Empty dims raises ValueError."""
99
+ with pytest.raises(ValueError, match="Invalid override format"):
100
+ _parse_cli_override_arg("foo:")
101
+
102
+
103
+ # ──────────────────── Unit: MetaOverrider ────────────────────
104
+
105
+
106
+ class TestMetaOverrider:
107
+ """MetaOverrider logic: matching, priority, apply_to_meta."""
108
+
109
+ def test_first_match_wins(self) -> None:
110
+ """First matching rule takes effect; later rules ignored."""
111
+ overrider = MetaOverrider(
112
+ rules=[
113
+ MetaOverrideRule(match="hidden", dims="FIRST"),
114
+ MetaOverrideRule(match="hidden", dims="SECOND"),
115
+ ]
116
+ )
117
+ result: dict = overrider.apply_to_meta(
118
+ name="hidden_states",
119
+ meta={"dims": "old"},
120
+ side="baseline",
121
+ )
122
+ assert result["dims"] == "FIRST"
123
+
124
+ def test_regex_contains_match(self) -> None:
125
+ """match is a regex contains search, not exact match."""
126
+ overrider = MetaOverrider(
127
+ rules=[MetaOverrideRule(match=r"\.q_proj\.", dims="h d")]
128
+ )
129
+ result: dict = overrider.apply_to_meta(
130
+ name="layers.0.q_proj.weight",
131
+ meta={"dims": "old"},
132
+ side="baseline",
133
+ )
134
+ assert result["dims"] == "h d"
135
+
136
+ def test_no_match_preserves_original(self) -> None:
137
+ """No matching rule leaves meta untouched."""
138
+ overrider = MetaOverrider(
139
+ rules=[MetaOverrideRule(match="logits", dims="b s v")]
140
+ )
141
+ result: dict = overrider.apply_to_meta(
142
+ name="hidden_states",
143
+ meta={"dims": "original"},
144
+ side="baseline",
145
+ )
146
+ assert result["dims"] == "original"
147
+
148
+ @pytest.mark.parametrize(
149
+ "rule_side,apply_side,should_match",
150
+ [
151
+ ("baseline", "baseline", True),
152
+ ("baseline", "target", False),
153
+ ("target", "target", True),
154
+ ("target", "baseline", False),
155
+ ("both", "baseline", True),
156
+ ("both", "target", True),
157
+ ],
158
+ )
159
+ def test_side_filtering(
160
+ self, rule_side: str, apply_side: str, should_match: bool
161
+ ) -> None:
162
+ """Rule only applies when its side matches the apply side."""
163
+ overrider = MetaOverrider(
164
+ rules=[MetaOverrideRule(match="logits", dims="NEW", side=rule_side)]
165
+ )
166
+ result: dict = overrider.apply_to_meta(
167
+ name="logits",
168
+ meta={"dims": "old"},
169
+ side=apply_side,
170
+ )
171
+ assert result["dims"] == ("NEW" if should_match else "old")
172
+
173
+ def test_is_empty(self) -> None:
174
+ """Empty overrider reports is_empty=True."""
175
+ assert MetaOverrider(rules=[]).is_empty
176
+ assert not MetaOverrider(rules=[MetaOverrideRule(match="x", dims="d")]).is_empty
177
+
178
+ def test_meta_without_dims_key(self) -> None:
179
+ """Override adds 'dims' even if original meta lacks it."""
180
+ overrider = MetaOverrider(rules=[MetaOverrideRule(match="hidden", dims="NEW")])
181
+ result: dict = overrider.apply_to_meta(
182
+ name="hidden",
183
+ meta={"other": "val"},
184
+ side="baseline",
185
+ )
186
+ assert result["dims"] == "NEW"
187
+
188
+
189
+ # ──────────────────── Unit: from_args_and_config ────────────────────
190
+
191
+
192
+ class TestFromArgsAndConfig:
193
+ """MetaOverrider.from_args_and_config merges CLI + YAML rules."""
194
+
195
+ def test_cli_before_yaml(self, tmp_path: Path) -> None:
196
+ """CLI rules are ordered before YAML rules (CLI wins on conflict)."""
197
+ yaml_path = tmp_path / "override.yaml"
198
+ yaml_path.write_text(textwrap.dedent("""\
199
+ overrides:
200
+ - match: "hidden"
201
+ dims: "FROM_YAML"
202
+ """))
203
+
204
+ overrider = MetaOverrider.from_args_and_config(
205
+ override_dims=["hidden:FROM_CLI"],
206
+ override_baseline_dims=[],
207
+ override_target_dims=[],
208
+ override_config=yaml_path,
209
+ )
210
+
211
+ result: dict = overrider.apply_to_meta(
212
+ name="hidden",
213
+ meta={"dims": "old"},
214
+ side="baseline",
215
+ )
216
+ assert result["dims"] == "FROM_CLI"
217
+
218
+ def test_no_config_no_cli(self) -> None:
219
+ """Empty CLI + no YAML yields empty overrider."""
220
+ overrider = MetaOverrider.from_args_and_config(
221
+ override_dims=[],
222
+ override_baseline_dims=[],
223
+ override_target_dims=[],
224
+ override_config=None,
225
+ )
226
+ assert overrider.is_empty
227
+
228
+ def test_per_side_cli_produces_separate_rules(self) -> None:
229
+ """--override-baseline-dims and --override-target-dims produce separate rules with side field."""
230
+ overrider = MetaOverrider.from_args_and_config(
231
+ override_dims=[],
232
+ override_baseline_dims=["hidden:b s h[tp]"],
233
+ override_target_dims=["hidden:b s h[ep]"],
234
+ override_config=None,
235
+ )
236
+
237
+ baseline: dict = overrider.apply_to_meta(
238
+ name="hidden",
239
+ meta={"dims": "old"},
240
+ side="baseline",
241
+ )
242
+ target: dict = overrider.apply_to_meta(
243
+ name="hidden",
244
+ meta={"dims": "old"},
245
+ side="target",
246
+ )
247
+ assert baseline["dims"] == "b s h[tp]"
248
+ assert target["dims"] == "b s h[ep]"
249
+
250
+
251
+ # ──────────────────── Unit: _load_yaml_rules ────────────────────
252
+
253
+
254
+ class TestLoadYamlRules:
255
+ """YAML loading and validation."""
256
+
257
+ def test_valid_yaml(self, tmp_path: Path) -> None:
258
+ """Valid YAML with override rules loads correctly."""
259
+ yaml_path = tmp_path / "override.yaml"
260
+ yaml_path.write_text(textwrap.dedent("""\
261
+ overrides:
262
+ - match: "hidden"
263
+ dims: "b s h d"
264
+ - match: "logits"
265
+ dims: "b s v[tp]"
266
+ side: baseline
267
+ """))
268
+ rules = _load_yaml_rules(yaml_path)
269
+ assert len(rules) == 2
270
+ assert rules[0].dims == "b s h d"
271
+ assert rules[0].side == "both"
272
+ assert rules[1].dims == "b s v[tp]"
273
+ assert rules[1].side == "baseline"
274
+
275
+ def test_empty_yaml(self, tmp_path: Path) -> None:
276
+ """Empty YAML file returns no rules."""
277
+ yaml_path = tmp_path / "empty.yaml"
278
+ yaml_path.write_text("")
279
+ rules = _load_yaml_rules(yaml_path)
280
+ assert rules == []
281
+
282
+ def test_unknown_top_key_rejected(self, tmp_path: Path) -> None:
283
+ """Unknown top-level key is rejected by OverrideConfig."""
284
+ yaml_path = tmp_path / "bad.yaml"
285
+ yaml_path.write_text("unknown_key: 42\n")
286
+ with pytest.raises(Exception):
287
+ _load_yaml_rules(yaml_path)
288
+
289
+ def test_overrides_empty_list(self, tmp_path: Path) -> None:
290
+ """Only 'overrides' key with no entries returns empty list."""
291
+ yaml_path = tmp_path / "minimal.yaml"
292
+ yaml_path.write_text("overrides: []\n")
293
+ rules = _load_yaml_rules(yaml_path)
294
+ assert rules == []
295
+
296
+
297
+ if __name__ == "__main__":
298
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_model_validation.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import sys
3
+
4
+ import pytest
5
+ from pydantic import ValidationError
6
+
7
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.traced_types import (
8
+ TracedAlignerPlan,
9
+ TracedSidePlan,
10
+ TracedStepPlan,
11
+ TracedSubPlan,
12
+ )
13
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import (
14
+ AlignerPerStepPlan,
15
+ AlignerPlan,
16
+ )
17
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import (
18
+ PositionalSeqId,
19
+ TokenAlignerPlan,
20
+ TokenAlignerSeqInfo,
21
+ TokenAlignerStepAux,
22
+ TokenLocator,
23
+ )
24
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import (
25
+ AxisInfo,
26
+ ConcatParams,
27
+ UnsharderPlan,
28
+ )
29
+ from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis, TokenLayout
30
+ from sglang.srt.debug_utils.comparator.output_types import (
31
+ ComparisonErrorRecord,
32
+ ComparisonNonTensorRecord,
33
+ ComparisonSkipRecord,
34
+ ComparisonTensorRecord,
35
+ ErrorLog,
36
+ SummaryRecord,
37
+ parse_record_json,
38
+ )
39
+ from sglang.srt.debug_utils.comparator.tensor_comparator.types import (
40
+ DiffInfo,
41
+ TensorInfo,
42
+ TensorStats,
43
+ )
44
+ from sglang.srt.debug_utils.comparator.utils import Pair, _check_equal_lengths
45
+ from sglang.test.ci.ci_register import register_cpu_ci
46
+
47
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
48
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
49
+
50
+
51
+ class TestCheckEqualLengths:
52
+ def test_all_equal(self):
53
+ _check_equal_lengths(a=[1, 2], b=[3, 4])
54
+
55
+ def test_empty_lists(self):
56
+ _check_equal_lengths(a=[], b=[])
57
+
58
+ def test_mismatch_raises(self):
59
+ with pytest.raises(ValueError, match="Length mismatch"):
60
+ _check_equal_lengths(a=[1, 2], b=[3])
61
+
62
+
63
+ class TestTokenAlignerStepAux:
64
+ def test_valid(self):
65
+ aux = TokenAlignerStepAux(
66
+ input_ids=[10, 20, 30],
67
+ positions=[0, 1, 2],
68
+ seq_lens=[2, 1],
69
+ seq_ids=[
70
+ PositionalSeqId(step=0, seq_index=0),
71
+ PositionalSeqId(step=0, seq_index=1),
72
+ ],
73
+ )
74
+ assert len(aux.input_ids) == 3
75
+
76
+ def test_token_length_mismatch(self):
77
+ with pytest.raises(ValueError, match="Length mismatch"):
78
+ TokenAlignerStepAux(
79
+ input_ids=[10, 20, 30],
80
+ positions=[0, 1],
81
+ seq_lens=[2, 1],
82
+ seq_ids=[
83
+ PositionalSeqId(step=0, seq_index=0),
84
+ PositionalSeqId(step=0, seq_index=1),
85
+ ],
86
+ )
87
+
88
+ def test_seq_length_mismatch(self):
89
+ with pytest.raises(ValueError, match="Length mismatch"):
90
+ TokenAlignerStepAux(
91
+ input_ids=[10, 20, 30],
92
+ positions=[0, 1, 2],
93
+ seq_lens=[2, 1],
94
+ seq_ids=[PositionalSeqId(step=0, seq_index=0)],
95
+ )
96
+
97
+ def test_sum_seq_lens_mismatch(self):
98
+ with pytest.raises(ValueError, match="sum\\(seq_lens\\)"):
99
+ TokenAlignerStepAux(
100
+ input_ids=[10, 20, 30],
101
+ positions=[0, 1, 2],
102
+ seq_lens=[1, 1],
103
+ seq_ids=[
104
+ PositionalSeqId(step=0, seq_index=0),
105
+ PositionalSeqId(step=0, seq_index=1),
106
+ ],
107
+ )
108
+
109
+
110
+ class TestTokenAlignerSeqInfo:
111
+ def test_valid(self):
112
+ info = TokenAlignerSeqInfo(
113
+ input_ids=[10, 20, 30],
114
+ positions=[0, 1, 2],
115
+ locator=TokenLocator(steps=[0, 0, 1], token_index_in_step=[0, 1, 0]),
116
+ )
117
+ assert len(info.input_ids) == 3
118
+
119
+ def test_length_mismatch(self):
120
+ with pytest.raises(ValidationError):
121
+ TokenAlignerSeqInfo(
122
+ input_ids=[10, 20, 30],
123
+ positions=[0, 1, 2],
124
+ locator=TokenLocator(steps=[0, 0], token_index_in_step=[0, 1, 0]),
125
+ )
126
+
127
+ def test_positions_not_sequential(self):
128
+ with pytest.raises(ValidationError, match="positions must be"):
129
+ TokenAlignerSeqInfo(
130
+ input_ids=[10, 20, 30],
131
+ positions=[0, 2, 1],
132
+ locator=TokenLocator(steps=[0, 0, 1], token_index_in_step=[0, 1, 0]),
133
+ )
134
+
135
+
136
+ class TestTokenAlignerPlan:
137
+ def test_valid(self):
138
+ plan = TokenAlignerPlan(
139
+ locators=Pair(
140
+ x=TokenLocator(steps=[0, 0, 1], token_index_in_step=[0, 1, 0]),
141
+ y=TokenLocator(steps=[0, 1, 1], token_index_in_step=[0, 0, 1]),
142
+ ),
143
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.T),
144
+ )
145
+ assert len(plan.locators.x.steps) == 3
146
+
147
+ def test_length_mismatch(self):
148
+ with pytest.raises(ValidationError, match="Length mismatch"):
149
+ TokenAlignerPlan(
150
+ locators=Pair(
151
+ x=TokenLocator(steps=[0, 0], token_index_in_step=[0, 1]),
152
+ y=TokenLocator(steps=[0, 1, 1], token_index_in_step=[0, 0, 1]),
153
+ ),
154
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.T),
155
+ )
156
+
157
+
158
+ class TestSummaryRecord:
159
+ def test_valid(self):
160
+ record = SummaryRecord(total=10, passed=7, failed=2, skipped=1)
161
+ assert record.total == 10
162
+
163
+ def test_total_mismatch(self):
164
+ with pytest.raises(ValidationError, match="total=10"):
165
+ SummaryRecord(total=10, passed=5, failed=2, skipped=1)
166
+
167
+ def test_valid_with_errored(self):
168
+ record = SummaryRecord(total=10, passed=6, failed=2, skipped=1, errored=1)
169
+ assert record.errored == 1
170
+
171
+ def test_total_mismatch_with_errored(self):
172
+ with pytest.raises(ValidationError, match="total=10"):
173
+ SummaryRecord(total=10, passed=6, failed=2, skipped=1, errored=0)
174
+
175
+
176
+ class TestAxisInfo:
177
+ def test_valid(self):
178
+ info = AxisInfo(axis_rank=0, axis_size=4)
179
+ assert info.axis_rank == 0
180
+
181
+ def test_axis_size_zero(self):
182
+ with pytest.raises(ValidationError, match="axis_size must be > 0"):
183
+ AxisInfo(axis_rank=0, axis_size=0)
184
+
185
+ def test_axis_size_negative(self):
186
+ with pytest.raises(ValidationError, match="axis_size must be > 0"):
187
+ AxisInfo(axis_rank=0, axis_size=-1)
188
+
189
+ def test_axis_rank_negative(self):
190
+ with pytest.raises(ValidationError, match="axis_rank must be in"):
191
+ AxisInfo(axis_rank=-1, axis_size=4)
192
+
193
+ def test_axis_rank_too_large(self):
194
+ with pytest.raises(ValidationError, match="axis_rank must be in"):
195
+ AxisInfo(axis_rank=4, axis_size=4)
196
+
197
+ def test_axis_rank_equals_size_minus_one(self):
198
+ info = AxisInfo(axis_rank=3, axis_size=4)
199
+ assert info.axis_rank == 3
200
+
201
+
202
+ def _make_tensor_info() -> TensorInfo:
203
+ return TensorInfo(
204
+ shape=[4, 4],
205
+ dtype="float32",
206
+ stats=TensorStats(mean=0.0, abs_mean=0.8, std=1.0, min=-2.0, max=2.0),
207
+ )
208
+
209
+
210
+ def _make_diff_info(*, passed: bool) -> DiffInfo:
211
+ return DiffInfo(
212
+ rel_diff=0.001,
213
+ max_abs_diff=0.01,
214
+ mean_abs_diff=0.005,
215
+ max_diff_coord=[0, 0],
216
+ baseline_at_max=1.0,
217
+ target_at_max=1.01,
218
+ diff_threshold=1e-3,
219
+ passed=passed,
220
+ )
221
+
222
+
223
+ def _make_comparison_record(
224
+ *,
225
+ diff: DiffInfo | None,
226
+ errors: list | None = None,
227
+ ) -> ComparisonTensorRecord:
228
+ ti: TensorInfo = _make_tensor_info()
229
+ return ComparisonTensorRecord(
230
+ name="t",
231
+ baseline=ti,
232
+ target=ti,
233
+ unified_shape=[4, 4],
234
+ shape_mismatch=False,
235
+ diff=diff,
236
+ errors=errors or [],
237
+ )
238
+
239
+
240
+ class TestOutputRecordCategories:
241
+ def test_skip_record_with_errors_is_failed(self) -> None:
242
+ record = ComparisonSkipRecord(
243
+ name="t",
244
+ reason="test",
245
+ errors=[ErrorLog(category="c", message="m")],
246
+ )
247
+ assert record.category == "failed"
248
+
249
+ def test_skip_record_no_warnings_is_skipped(self) -> None:
250
+ record = ComparisonSkipRecord(name="t", reason="test")
251
+ assert record.category == "skipped"
252
+
253
+ def test_comparison_record_diff_none_is_failed(self) -> None:
254
+ record: ComparisonTensorRecord = _make_comparison_record(diff=None)
255
+ assert record.category == "failed"
256
+
257
+ def test_comparison_record_passed_with_errors_is_failed(self) -> None:
258
+ record: ComparisonTensorRecord = _make_comparison_record(
259
+ diff=_make_diff_info(passed=True),
260
+ errors=[ErrorLog(category="c", message="m")],
261
+ )
262
+ assert record.category == "failed"
263
+
264
+ def test_comparison_record_passed_no_warnings_is_passed(self) -> None:
265
+ record: ComparisonTensorRecord = _make_comparison_record(
266
+ diff=_make_diff_info(passed=True),
267
+ )
268
+ assert record.category == "passed"
269
+
270
+ def test_non_tensor_record_equal_is_passed(self) -> None:
271
+ record = ComparisonNonTensorRecord(
272
+ name="sm_scale",
273
+ baseline_value="0.125",
274
+ target_value="0.125",
275
+ baseline_type="float",
276
+ target_type="float",
277
+ values_equal=True,
278
+ )
279
+ assert record.category == "passed"
280
+
281
+ def test_non_tensor_record_different_is_failed(self) -> None:
282
+ record = ComparisonNonTensorRecord(
283
+ name="sm_scale",
284
+ baseline_value="0.125",
285
+ target_value="0.25",
286
+ baseline_type="float",
287
+ target_type="float",
288
+ values_equal=False,
289
+ )
290
+ assert record.category == "failed"
291
+
292
+ def test_non_tensor_record_with_errors_is_failed(self) -> None:
293
+ record = ComparisonNonTensorRecord(
294
+ name="sm_scale",
295
+ baseline_value="0.125",
296
+ target_value="0.125",
297
+ baseline_type="float",
298
+ target_type="float",
299
+ values_equal=True,
300
+ errors=[ErrorLog(category="c", message="m")],
301
+ )
302
+ assert record.category == "failed"
303
+
304
+ def test_non_tensor_record_json_roundtrip(self) -> None:
305
+ record = ComparisonNonTensorRecord(
306
+ name="sm_scale",
307
+ baseline_value="0.125",
308
+ target_value="0.25",
309
+ baseline_type="float",
310
+ target_type="float",
311
+ values_equal=False,
312
+ )
313
+ json_str: str = record.model_dump_json()
314
+ roundtripped = parse_record_json(json_str)
315
+ assert isinstance(roundtripped, ComparisonNonTensorRecord)
316
+ assert roundtripped.name == "sm_scale"
317
+ assert roundtripped.values_equal is False
318
+ assert roundtripped.baseline_value == "0.125"
319
+ assert roundtripped.target_value == "0.25"
320
+
321
+ def test_non_tensor_record_text_format_equal(self) -> None:
322
+ record = ComparisonNonTensorRecord(
323
+ name="sm_scale",
324
+ baseline_value="0.125",
325
+ target_value="0.125",
326
+ baseline_type="float",
327
+ target_type="float",
328
+ values_equal=True,
329
+ )
330
+ text: str = record.to_text()
331
+ assert "sm_scale" in text
332
+ assert "[equal]" in text
333
+
334
+ def test_non_tensor_record_text_format_different(self) -> None:
335
+ record = ComparisonNonTensorRecord(
336
+ name="sm_scale",
337
+ baseline_value="0.125",
338
+ target_value="0.25",
339
+ baseline_type="float",
340
+ target_type="float",
341
+ values_equal=False,
342
+ )
343
+ text: str = record.to_text()
344
+ assert "baseline" in text
345
+ assert "target" in text
346
+
347
+ def test_error_record_category_is_errored(self) -> None:
348
+ record = ComparisonErrorRecord(
349
+ name="t",
350
+ exception_type="ValueError",
351
+ exception_message="bad",
352
+ traceback_str="...",
353
+ )
354
+ assert record.category == "errored"
355
+
356
+ def test_error_record_json_roundtrip(self) -> None:
357
+ record = ComparisonErrorRecord(
358
+ name="t",
359
+ exception_type="ValueError",
360
+ exception_message="bad",
361
+ traceback_str="traceback...",
362
+ )
363
+ json_str: str = record.model_dump_json()
364
+ roundtripped = parse_record_json(json_str)
365
+ assert isinstance(roundtripped, ComparisonErrorRecord)
366
+ assert roundtripped.name == "t"
367
+ assert roundtripped.exception_type == "ValueError"
368
+ assert roundtripped.exception_message == "bad"
369
+
370
+ def test_error_record_text_format(self) -> None:
371
+ record = ComparisonErrorRecord(
372
+ name="t",
373
+ exception_type="RuntimeError",
374
+ exception_message="oops",
375
+ traceback_str="Traceback...",
376
+ )
377
+ text: str = record.to_text()
378
+ assert "RuntimeError" in text
379
+ assert "oops" in text
380
+ assert "Traceback" in text
381
+
382
+
383
+ def _make_traced_aligner_plan() -> TracedAlignerPlan:
384
+ unsharder = UnsharderPlan(
385
+ axis=ParallelAxis.TP,
386
+ params=ConcatParams(dim_name="h"),
387
+ groups=[[0, 1]],
388
+ )
389
+ plan = AlignerPlan(
390
+ per_step_plans=Pair(
391
+ x=[
392
+ AlignerPerStepPlan(
393
+ step=0, input_object_indices=[0, 1], sub_plans=[unsharder]
394
+ )
395
+ ],
396
+ y=[
397
+ AlignerPerStepPlan(
398
+ step=0, input_object_indices=[0, 1], sub_plans=[unsharder]
399
+ )
400
+ ],
401
+ ),
402
+ )
403
+ traced_sub = TracedSubPlan(plan=unsharder, snapshot=None)
404
+ traced_step = TracedStepPlan(
405
+ step=0, input_object_indices=[0, 1], sub_plans=[traced_sub]
406
+ )
407
+ return TracedAlignerPlan(
408
+ plan=plan,
409
+ per_side=Pair(
410
+ x=TracedSidePlan(step_plans=[traced_step]),
411
+ y=TracedSidePlan(step_plans=[traced_step]),
412
+ ),
413
+ )
414
+
415
+
416
+ class TestAlignerPlanInComparisonTensorRecord:
417
+ def test_comparison_record_with_traced_plan(self) -> None:
418
+ traced_plan: TracedAlignerPlan = _make_traced_aligner_plan()
419
+ record: ComparisonTensorRecord = _make_comparison_record(
420
+ diff=_make_diff_info(passed=True),
421
+ )
422
+ record_with_plan = record.model_copy(update={"traced_plan": traced_plan})
423
+ assert record_with_plan.traced_plan is not None
424
+ assert record_with_plan.traced_plan.per_side.x.step_plans[0].step == 0
425
+
426
+ def test_traced_plan_json_roundtrip(self) -> None:
427
+ traced_plan: TracedAlignerPlan = _make_traced_aligner_plan()
428
+ record: ComparisonTensorRecord = _make_comparison_record(
429
+ diff=_make_diff_info(passed=True),
430
+ )
431
+ record_with_plan = record.model_copy(update={"traced_plan": traced_plan})
432
+
433
+ json_str: str = record_with_plan.model_dump_json()
434
+ parsed = json.loads(json_str)
435
+ assert "traced_plan" in parsed
436
+ assert (
437
+ parsed["traced_plan"]["per_side"]["x"]["step_plans"][0]["sub_plans"][0][
438
+ "plan"
439
+ ]["type"]
440
+ == "unsharder"
441
+ )
442
+
443
+ roundtripped: ComparisonTensorRecord = parse_record_json(json_str)
444
+ assert roundtripped.traced_plan is not None
445
+ assert (
446
+ roundtripped.traced_plan.per_side.x.step_plans[0].sub_plans[0].plan.type
447
+ == "unsharder"
448
+ )
449
+
450
+ def test_comparison_record_without_traced_plan(self) -> None:
451
+ record: ComparisonTensorRecord = _make_comparison_record(
452
+ diff=_make_diff_info(passed=True),
453
+ )
454
+ json_str: str = record.model_dump_json()
455
+ roundtripped: ComparisonTensorRecord = parse_record_json(json_str)
456
+ assert roundtripped.traced_plan is None
457
+
458
+ def test_traced_plan_text_format(self) -> None:
459
+ traced_plan: TracedAlignerPlan = _make_traced_aligner_plan()
460
+ record: ComparisonTensorRecord = _make_comparison_record(
461
+ diff=_make_diff_info(passed=True),
462
+ )
463
+ record_with_plan = record.model_copy(update={"traced_plan": traced_plan})
464
+
465
+ text: str = record_with_plan.to_text()
466
+ assert "Aligner Plan:" in text
467
+ assert "unsharder" in text
468
+
469
+
470
+ if __name__ == "__main__":
471
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_output_types.py ADDED
@@ -0,0 +1,771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from io import StringIO
3
+
4
+ import pytest
5
+ from registered.debug_utils.comparator.testing_helpers import (
6
+ assert_rich_tags_balanced,
7
+ )
8
+ from registered.debug_utils.comparator.testing_helpers import make_diff as _make_diff
9
+ from registered.debug_utils.comparator.testing_helpers import make_stats as _make_stats
10
+ from registered.debug_utils.comparator.testing_helpers import (
11
+ make_tensor_info as _make_tensor_info,
12
+ )
13
+ from rich.console import Console, Group
14
+ from rich.panel import Panel
15
+
16
+ from sglang.srt.debug_utils.comparator.aligner.axis_aligner import AxisAlignerPlan
17
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.traced_types import (
18
+ TracedAlignerPlan,
19
+ TracedSidePlan,
20
+ TracedStepPlan,
21
+ TracedSubPlan,
22
+ )
23
+ from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import (
24
+ AlignerPerStepPlan,
25
+ AlignerPlan,
26
+ )
27
+ from sglang.srt.debug_utils.comparator.aligner.reorderer.types import (
28
+ ReordererPlan,
29
+ ZigzagToNaturalParams,
30
+ )
31
+ from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import (
32
+ TokenAlignerPlan,
33
+ TokenLocator,
34
+ )
35
+ from sglang.srt.debug_utils.comparator.aligner.unsharder.types import (
36
+ ConcatParams,
37
+ UnsharderPlan,
38
+ )
39
+ from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis, TokenLayout
40
+ from sglang.srt.debug_utils.comparator.output_types import (
41
+ BundleFileInfo,
42
+ BundleSideInfo,
43
+ ComparisonNonTensorRecord,
44
+ ComparisonSkipRecord,
45
+ ComparisonTensorRecord,
46
+ ConfigRecord,
47
+ ErrorLog,
48
+ InfoLog,
49
+ LogRecord,
50
+ RecordLocation,
51
+ SummaryRecord,
52
+ _format_aligner_plan,
53
+ _split_logs,
54
+ )
55
+ from sglang.srt.debug_utils.comparator.utils import Pair
56
+ from sglang.test.ci.ci_register import register_cpu_ci
57
+
58
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
59
+
60
+
61
+ def _render_rich(renderable: object) -> str:
62
+ buf: StringIO = StringIO()
63
+ Console(file=buf, force_terminal=False, width=120).print(renderable)
64
+ return buf.getvalue().rstrip("\n")
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Existing tests (preserved)
69
+ # ---------------------------------------------------------------------------
70
+
71
+
72
+ def test_split_logs_mixed_list() -> None:
73
+ """_split_logs correctly partitions a mixed list of ErrorLog and InfoLog."""
74
+ errors, infos = _split_logs(
75
+ [
76
+ ErrorLog(category="a", message="err"),
77
+ InfoLog(category="b", message="info"),
78
+ ErrorLog(category="c", message="err2"),
79
+ ]
80
+ )
81
+ assert len(errors) == 2
82
+ assert len(infos) == 1
83
+ assert errors[0].message == "err"
84
+ assert errors[1].message == "err2"
85
+ assert infos[0].message == "info"
86
+
87
+
88
+ def test_log_record_to_text_format() -> None:
89
+ """LogRecord.to_text() renders errors with ✗ and infos with ℹ markers."""
90
+ record = LogRecord(
91
+ errors=[ErrorLog(category="a", message="bad thing")],
92
+ infos=[InfoLog(category="b", message="fyi")],
93
+ )
94
+ text: str = record.to_text()
95
+ assert "✗ bad thing" in text
96
+ assert "ℹ fyi" in text
97
+
98
+
99
+ class TestLogRecord:
100
+ def test_format_body_returns_empty(self) -> None:
101
+ record: LogRecord = LogRecord()
102
+ assert record._format_body() == ""
103
+
104
+ def test_format_rich_body_returns_empty(self) -> None:
105
+ record: LogRecord = LogRecord()
106
+ assert record._format_rich_body() == ""
107
+
108
+ def test_to_text_empty_no_logs(self) -> None:
109
+ record: LogRecord = LogRecord()
110
+ assert record.to_text() == ""
111
+
112
+ def test_to_text_with_errors_and_infos(self) -> None:
113
+ record: LogRecord = LogRecord(
114
+ errors=[ErrorLog(category="a", message="bad thing")],
115
+ infos=[InfoLog(category="b", message="fyi")],
116
+ )
117
+ text: str = record.to_text()
118
+ assert text == "\n ✗ bad thing\n ℹ fyi"
119
+
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # ConfigRecord
123
+ # ---------------------------------------------------------------------------
124
+
125
+
126
+ class TestConfigRecord:
127
+ def test_format_body(self) -> None:
128
+ record: ConfigRecord = ConfigRecord(config={"a": 1, "b": "two"})
129
+ assert record._format_body() == "Config: {'a': 1, 'b': 'two'}"
130
+
131
+ def test_format_rich_body(self) -> None:
132
+ record: ConfigRecord = ConfigRecord(config={"threshold": 0.001, "mode": "fast"})
133
+ body = record._format_rich_body()
134
+
135
+ assert isinstance(body, Panel)
136
+ rendered: str = _render_rich(body)
137
+ assert rendered == (
138
+ "╭───────────────────────────────────────────────── Comparator Config "
139
+ "──────────────────────────────────────────���───────╮\n"
140
+ "│ threshold : 0.001"
141
+ " │\n"
142
+ "│ mode : fast"
143
+ " │\n"
144
+ "╰──────────────────────────────────────────────────────────────────────"
145
+ "────────────────────────────────────────────────╯"
146
+ )
147
+
148
+ def test_to_text_with_errors(self) -> None:
149
+ record: ConfigRecord = ConfigRecord(
150
+ config={"x": 1},
151
+ errors=[ErrorLog(category="cfg", message="bad config")],
152
+ )
153
+ text: str = record.to_text()
154
+ assert text.startswith("Config: {'x': 1}")
155
+ assert "✗ bad config" in text
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # ComparisonSkipRecord
160
+ # ---------------------------------------------------------------------------
161
+
162
+
163
+ class TestComparisonSkipRecord:
164
+ def test_format_body_no_step(self) -> None:
165
+ record: ComparisonSkipRecord = ComparisonSkipRecord(
166
+ name="layer.weight",
167
+ reason="zero-dim tensor",
168
+ )
169
+ assert record._format_body() == "Skip: layer.weight (zero-dim tensor)"
170
+
171
+ def test_format_body_with_step(self) -> None:
172
+ record: ComparisonSkipRecord = ComparisonSkipRecord(
173
+ name="layer.weight",
174
+ reason="scalar",
175
+ location=RecordLocation(step=3),
176
+ )
177
+ assert record._format_body() == "Skip: layer.weight (step=3) (scalar)"
178
+
179
+ def test_format_rich_body(self) -> None:
180
+ record: ComparisonSkipRecord = ComparisonSkipRecord(
181
+ name="attn.qkv",
182
+ reason="no baseline",
183
+ )
184
+ body: str = record._format_rich_body()
185
+ assert body == "[dim]⊘ attn.qkv ── skipped (no baseline)[/]"
186
+
187
+ def test_category_skipped(self) -> None:
188
+ record: ComparisonSkipRecord = ComparisonSkipRecord(
189
+ name="x",
190
+ reason="r",
191
+ )
192
+ assert record.category == "skipped"
193
+
194
+ def test_category_failed(self) -> None:
195
+ record: ComparisonSkipRecord = ComparisonSkipRecord(
196
+ name="x",
197
+ reason="r",
198
+ errors=[ErrorLog(category="e", message="boom")],
199
+ )
200
+ assert record.category == "failed"
201
+
202
+ def test_format_body_with_available_side(self) -> None:
203
+ record: ComparisonSkipRecord = ComparisonSkipRecord(
204
+ name="layer.weight",
205
+ reason="baseline_load_failed",
206
+ available_side="target",
207
+ available_tensor_info=_make_tensor_info(
208
+ shape=[4, 8],
209
+ dtype="torch.float32",
210
+ stats=_make_stats(mean=0.5, std=1.2, min=-2.0, max=3.0),
211
+ sample="tensor([0.1, 0.2, ...])",
212
+ ),
213
+ )
214
+ body: str = record._format_body()
215
+ assert "baseline_load_failed" in body
216
+ assert "target: shape=[4, 8]" in body
217
+ assert "mean=0.5000" in body
218
+ assert "sample: tensor([0.1, 0.2, ...])" in body
219
+
220
+ def test_format_rich_body_with_available_side(self) -> None:
221
+ record: ComparisonSkipRecord = ComparisonSkipRecord(
222
+ name="attn.qkv",
223
+ reason="baseline_load_failed",
224
+ available_side="target",
225
+ available_tensor_info=_make_tensor_info(
226
+ shape=[4, 8],
227
+ dtype="torch.float32",
228
+ stats=_make_stats(mean=0.5, std=1.2, min=-2.0, max=3.0),
229
+ sample="tensor([0.1, 0.2, ...])",
230
+ ),
231
+ available_bundle_info=BundleSideInfo(
232
+ num_files=2,
233
+ files=[
234
+ BundleFileInfo(shape=[4, 8], dtype="torch.float32"),
235
+ BundleFileInfo(shape=[4, 8], dtype="torch.float32"),
236
+ ],
237
+ ),
238
+ )
239
+ body: str = record._format_rich_body()
240
+ assert "skipped (baseline_load_failed)" in body
241
+ assert "target" in body
242
+ assert "2 files" in body
243
+ assert "mean=0.5000" in body
244
+ assert "tensor(" in body
245
+ assert_rich_tags_balanced(body)
246
+
247
+ def test_format_rich_body_minimal_hides_available_side(self) -> None:
248
+ record: ComparisonSkipRecord = ComparisonSkipRecord(
249
+ name="x",
250
+ reason="target_load_failed",
251
+ available_side="baseline",
252
+ available_tensor_info=_make_tensor_info(),
253
+ )
254
+ body: str = record._format_rich_body(verbosity="minimal")
255
+ assert "skipped" in body
256
+ assert "stats" not in body
257
+ assert_rich_tags_balanced(body)
258
+
259
+
260
+ # ---------------------------------------------------------------------------
261
+ # ComparisonNonTensorRecord
262
+ # ---------------------------------------------------------------------------
263
+
264
+
265
+ class TestComparisonNonTensorRecord:
266
+ def test_format_body_equal(self) -> None:
267
+ record: ComparisonNonTensorRecord = ComparisonNonTensorRecord(
268
+ name="config.lr",
269
+ baseline_value="0.001",
270
+ target_value="0.001",
271
+ baseline_type="float",
272
+ target_type="float",
273
+ values_equal=True,
274
+ )
275
+ assert record._format_body() == "NonTensor: config.lr = 0.001 (float) [equal]"
276
+
277
+ def test_format_body_not_equal(self) -> None:
278
+ record: ComparisonNonTensorRecord = ComparisonNonTensorRecord(
279
+ name="config.lr",
280
+ baseline_value="0.001",
281
+ target_value="0.01",
282
+ baseline_type="float",
283
+ target_type="float",
284
+ values_equal=False,
285
+ )
286
+ assert record._format_body() == (
287
+ "NonTensor: config.lr\n"
288
+ " baseline = 0.001 (float)\n"
289
+ " target = 0.01 (float)"
290
+ )
291
+
292
+ def test_format_rich_body_equal(self) -> None:
293
+ record: ComparisonNonTensorRecord = ComparisonNonTensorRecord(
294
+ name="config.lr",
295
+ baseline_value="0.001",
296
+ target_value="0.001",
297
+ baseline_type="float",
298
+ target_type="float",
299
+ values_equal=True,
300
+ )
301
+ assert record._format_rich_body() == ("═ config.lr = 0.001 (float) [green]✓[/]")
302
+
303
+ def test_format_rich_body_not_equal(self) -> None:
304
+ record: ComparisonNonTensorRecord = ComparisonNonTensorRecord(
305
+ name="config.lr",
306
+ baseline_value="0.001",
307
+ target_value="0.01",
308
+ baseline_type="float",
309
+ target_type="float",
310
+ values_equal=False,
311
+ )
312
+ assert record._format_rich_body() == (
313
+ "═ [bold red]config.lr[/]\n"
314
+ " baseline = 0.001 (float)\n"
315
+ " target = 0.01 (float)"
316
+ )
317
+
318
+ def test_with_step(self) -> None:
319
+ record: ComparisonNonTensorRecord = ComparisonNonTensorRecord(
320
+ name="bias",
321
+ baseline_value="True",
322
+ target_value="True",
323
+ baseline_type="bool",
324
+ target_type="bool",
325
+ values_equal=True,
326
+ location=RecordLocation(step=5),
327
+ )
328
+ assert "(step=5)" in record._format_body()
329
+
330
+ def test_category(self) -> None:
331
+ passed: ComparisonNonTensorRecord = ComparisonNonTensorRecord(
332
+ name="x",
333
+ baseline_value="1",
334
+ target_value="1",
335
+ baseline_type="int",
336
+ target_type="int",
337
+ values_equal=True,
338
+ )
339
+ failed: ComparisonNonTensorRecord = ComparisonNonTensorRecord(
340
+ name="x",
341
+ baseline_value="1",
342
+ target_value="2",
343
+ baseline_type="int",
344
+ target_type="int",
345
+ values_equal=False,
346
+ )
347
+ assert passed.category == "passed"
348
+ assert failed.category == "failed"
349
+
350
+
351
+ # ---------------------------------------------------------------------------
352
+ # SummaryRecord
353
+ # ---------------------------------------------------------------------------
354
+
355
+
356
+ class TestSummaryRecord:
357
+ def test_format_body(self) -> None:
358
+ record: SummaryRecord = SummaryRecord(
359
+ total=10,
360
+ passed=7,
361
+ failed=2,
362
+ skipped=1,
363
+ )
364
+ assert record._format_body() == (
365
+ "Summary: 7 passed, 2 failed, 1 skipped (total 10)"
366
+ )
367
+
368
+ def test_format_rich_body(self) -> None:
369
+ record: SummaryRecord = SummaryRecord(
370
+ total=10,
371
+ passed=7,
372
+ failed=2,
373
+ skipped=1,
374
+ )
375
+ body = record._format_rich_body()
376
+ assert isinstance(body, Panel)
377
+
378
+ rendered: str = _render_rich(body)
379
+ assert rendered == (
380
+ "╭────────────────────────────────────────────────────── SUMMARY "
381
+ "───────────────────────────────────────────────────────╮\n"
382
+ "│ 7 passed │ 2 failed │ 1 skipped │ 10 total"
383
+ " │\n"
384
+ "╰──────────────────────────────────────────────────────────────────────"
385
+ "───────────────────────���────────────────────────╯"
386
+ )
387
+
388
+ def test_validation_error(self) -> None:
389
+ with pytest.raises(ValueError, match="total=5 !="):
390
+ SummaryRecord(total=5, passed=1, failed=1, skipped=1)
391
+
392
+
393
+ # ---------------------------------------------------------------------------
394
+ # ComparisonTensorRecord._format_body
395
+ # ---------------------------------------------------------------------------
396
+
397
+
398
+ class TestComparisonTensorRecordFormatBody:
399
+ def test_basic(self) -> None:
400
+ record: ComparisonTensorRecord = ComparisonTensorRecord(
401
+ name="hidden",
402
+ baseline=_make_tensor_info(),
403
+ target=_make_tensor_info(),
404
+ unified_shape=[4, 8],
405
+ shape_mismatch=False,
406
+ diff=_make_diff(),
407
+ )
408
+ body: str = record._format_body()
409
+
410
+ assert body == (
411
+ "Raw [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n"
412
+ "After unify [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n"
413
+ "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n"
414
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
415
+ "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n"
416
+ "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n"
417
+ "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n"
418
+ "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n"
419
+ "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n"
420
+ "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n"
421
+ "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n"
422
+ "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n"
423
+ "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n"
424
+ "max_abs_diff happens at coord=[2, 3] with baseline=1.0 target=1.0005\n"
425
+ "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005"
426
+ )
427
+
428
+ def test_with_replicated_checks(self) -> None:
429
+ from sglang.srt.debug_utils.comparator.output_types import ReplicatedCheckResult
430
+
431
+ record: ComparisonTensorRecord = ComparisonTensorRecord(
432
+ name="hidden",
433
+ baseline=_make_tensor_info(),
434
+ target=_make_tensor_info(),
435
+ unified_shape=[4, 8],
436
+ shape_mismatch=False,
437
+ diff=_make_diff(),
438
+ replicated_checks=[
439
+ ReplicatedCheckResult(
440
+ axis="tp",
441
+ group_index=0,
442
+ compared_index=1,
443
+ baseline_index=0,
444
+ passed=True,
445
+ atol=1e-3,
446
+ diff=_make_diff(
447
+ rel_diff=1e-6, max_abs_diff=1e-5, mean_abs_diff=1e-6
448
+ ),
449
+ ),
450
+ ],
451
+ )
452
+ body: str = record._format_body()
453
+
454
+ assert body == (
455
+ "Raw [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n"
456
+ "After unify [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n"
457
+ "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n"
458
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
459
+ "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n"
460
+ "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n"
461
+ "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n"
462
+ "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n"
463
+ "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n"
464
+ "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n"
465
+ "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n"
466
+ "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n"
467
+ "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n"
468
+ "max_abs_diff happens at coord=[2, 3] with baseline=1.0 target=1.0005\n"
469
+ "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005\n"
470
+ "Replicated checks:\n"
471
+ " ✅ axis=tp group=0 idx=1 vs 0: "
472
+ "rel_diff=1.000000e-06 max_abs_diff=1.000000e-05 mean_abs_diff=1.000000e-06"
473
+ )
474
+
475
+ def test_with_aligner_plan(self) -> None:
476
+ plan: AlignerPlan = AlignerPlan(
477
+ per_step_plans=Pair(x=[], y=[]),
478
+ )
479
+ traced: TracedAlignerPlan = TracedAlignerPlan(
480
+ plan=plan,
481
+ per_side=Pair(
482
+ x=TracedSidePlan(step_plans=[]),
483
+ y=TracedSidePlan(step_plans=[]),
484
+ ),
485
+ )
486
+ record: ComparisonTensorRecord = ComparisonTensorRecord(
487
+ name="hidden",
488
+ baseline=_make_tensor_info(),
489
+ target=_make_tensor_info(),
490
+ unified_shape=[4, 8],
491
+ shape_mismatch=False,
492
+ diff=_make_diff(),
493
+ traced_plan=traced,
494
+ )
495
+ body: str = record._format_body()
496
+
497
+ assert body == (
498
+ "Raw [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n"
499
+ "After unify [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n"
500
+ "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n"
501
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
502
+ "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n"
503
+ "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n"
504
+ "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n"
505
+ "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n"
506
+ "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n"
507
+ "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n"
508
+ "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n"
509
+ "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n"
510
+ "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n"
511
+ "max_abs_diff happens at coord=[2, 3] with baseline=1.0 target=1.0005\n"
512
+ "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005\n"
513
+ "Aligner Plan:\n"
514
+ " baseline: (no steps)\n"
515
+ " target: (no steps)"
516
+ )
517
+
518
+ def test_with_step(self) -> None:
519
+ record: ComparisonTensorRecord = ComparisonTensorRecord(
520
+ name="hidden",
521
+ baseline=_make_tensor_info(),
522
+ target=_make_tensor_info(),
523
+ unified_shape=[4, 8],
524
+ shape_mismatch=False,
525
+ diff=_make_diff(),
526
+ location=RecordLocation(step=2),
527
+ )
528
+ body: str = record._format_body()
529
+
530
+ assert body == (
531
+ "[step=2] "
532
+ "Raw [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n"
533
+ "After unify [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n"
534
+ "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n"
535
+ "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n"
536
+ "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n"
537
+ "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n"
538
+ "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n"
539
+ "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n"
540
+ "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n"
541
+ "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n"
542
+ "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n"
543
+ "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n"
544
+ "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n"
545
+ "max_abs_diff happens at coord=[2, 3] with baseline=1.0 target=1.0005\n"
546
+ "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005"
547
+ )
548
+
549
+
550
+ # ---------------------------------------------------------------------------
551
+ # _format_aligner_plan
552
+ # ---------------------------------------------------------------------------
553
+
554
+
555
+ def _wrap_plan(plan: AlignerPlan) -> TracedAlignerPlan:
556
+ """Wrap an AlignerPlan into a TracedAlignerPlan with no snapshots."""
557
+ baseline_traced_steps: list[TracedStepPlan] = [
558
+ TracedStepPlan(
559
+ step=sp.step,
560
+ input_object_indices=sp.input_object_indices,
561
+ sub_plans=[TracedSubPlan(plan=sub) for sub in sp.sub_plans],
562
+ )
563
+ for sp in plan.per_step_plans.x
564
+ ]
565
+ target_traced_steps: list[TracedStepPlan] = [
566
+ TracedStepPlan(
567
+ step=sp.step,
568
+ input_object_indices=sp.input_object_indices,
569
+ sub_plans=[TracedSubPlan(plan=sub) for sub in sp.sub_plans],
570
+ )
571
+ for sp in plan.per_step_plans.y
572
+ ]
573
+ return TracedAlignerPlan(
574
+ plan=plan,
575
+ per_side=Pair(
576
+ x=TracedSidePlan(step_plans=baseline_traced_steps),
577
+ y=TracedSidePlan(step_plans=target_traced_steps),
578
+ ),
579
+ )
580
+
581
+
582
+ class TestFormatAlignerPlan:
583
+ def test_passthrough(self) -> None:
584
+ plan: AlignerPlan = AlignerPlan(
585
+ per_step_plans=Pair(x=[], y=[]),
586
+ )
587
+ result: str = _format_aligner_plan(_wrap_plan(plan))
588
+
589
+ assert result == (
590
+ "Aligner Plan:\n" " baseline: (no steps)\n" " target: (no steps)"
591
+ )
592
+
593
+ def test_unsharder(self) -> None:
594
+ unsharder: UnsharderPlan = UnsharderPlan(
595
+ axis=ParallelAxis.TP,
596
+ params=ConcatParams(dim_name="h"),
597
+ groups=[[0, 1]],
598
+ )
599
+ plan: AlignerPlan = AlignerPlan(
600
+ per_step_plans=Pair(
601
+ x=[],
602
+ y=[
603
+ AlignerPerStepPlan(
604
+ step=0, input_object_indices=[0, 1], sub_plans=[unsharder]
605
+ )
606
+ ],
607
+ ),
608
+ )
609
+ result: str = _format_aligner_plan(_wrap_plan(plan))
610
+
611
+ assert result == (
612
+ "Aligner Plan:\n"
613
+ " baseline: (no steps)\n"
614
+ " target: [step=0: unsharder(tp)]"
615
+ )
616
+
617
+ def test_reorderer(self) -> None:
618
+ reorderer: ReordererPlan = ReordererPlan(
619
+ params=ZigzagToNaturalParams(dim_name="s", cp_size=2),
620
+ )
621
+ plan: AlignerPlan = AlignerPlan(
622
+ per_step_plans=Pair(
623
+ x=[],
624
+ y=[
625
+ AlignerPerStepPlan(
626
+ step=0, input_object_indices=[0], sub_plans=[reorderer]
627
+ )
628
+ ],
629
+ ),
630
+ )
631
+ result: str = _format_aligner_plan(_wrap_plan(plan))
632
+
633
+ assert result == (
634
+ "Aligner Plan:\n"
635
+ " baseline: (no steps)\n"
636
+ " target: [step=0: reorderer(zigzag_to_natural)]"
637
+ )
638
+
639
+ def test_multi_step(self) -> None:
640
+ unsharder: UnsharderPlan = UnsharderPlan(
641
+ axis=ParallelAxis.TP,
642
+ params=ConcatParams(dim_name="h"),
643
+ groups=[[0, 1]],
644
+ )
645
+ reorderer: ReordererPlan = ReordererPlan(
646
+ params=ZigzagToNaturalParams(dim_name="s", cp_size=2),
647
+ )
648
+ plan: AlignerPlan = AlignerPlan(
649
+ per_step_plans=Pair(
650
+ x=[],
651
+ y=[
652
+ AlignerPerStepPlan(
653
+ step=0, input_object_indices=[0, 1], sub_plans=[unsharder]
654
+ ),
655
+ AlignerPerStepPlan(
656
+ step=1, input_object_indices=[0], sub_plans=[reorderer]
657
+ ),
658
+ ],
659
+ ),
660
+ )
661
+ result: str = _format_aligner_plan(_wrap_plan(plan))
662
+
663
+ assert result == (
664
+ "Aligner Plan:\n"
665
+ " baseline: (no steps)\n"
666
+ " target: [step=0: unsharder(tp); step=1: reorderer(zigzag_to_natural)]"
667
+ )
668
+
669
+ def test_with_token_aligner(self) -> None:
670
+ ta_plan: TokenAlignerPlan = TokenAlignerPlan(
671
+ locators=Pair(
672
+ x=TokenLocator(steps=[0, 0, 0], token_index_in_step=[0, 1, 2]),
673
+ y=TokenLocator(steps=[0, 0, 0], token_index_in_step=[0, 1, 2]),
674
+ ),
675
+ layouts=Pair(x=TokenLayout.T, y=TokenLayout.T),
676
+ )
677
+ plan: AlignerPlan = AlignerPlan(
678
+ per_step_plans=Pair(x=[], y=[]),
679
+ token_aligner_plan=ta_plan,
680
+ )
681
+ result: str = _format_aligner_plan(_wrap_plan(plan))
682
+
683
+ assert result == (
684
+ "Aligner Plan:\n"
685
+ " baseline: (no steps)\n"
686
+ " target: (no steps)\n"
687
+ " token_aligner: 3 tokens aligned"
688
+ )
689
+
690
+ def test_with_axis_aligner(self) -> None:
691
+ aa_plan: AxisAlignerPlan = AxisAlignerPlan(
692
+ pattern=Pair(x="b s d -> s b d", y=None),
693
+ )
694
+ plan: AlignerPlan = AlignerPlan(
695
+ per_step_plans=Pair(x=[], y=[]),
696
+ axis_aligner_plan=aa_plan,
697
+ )
698
+ result: str = _format_aligner_plan(_wrap_plan(plan))
699
+
700
+ assert result == (
701
+ "Aligner Plan:\n"
702
+ " baseline: (no steps)\n"
703
+ " target: (no steps)\n"
704
+ " axis_aligner: x: b s d -> s b d"
705
+ )
706
+
707
+
708
+ # ---------------------------------------------------------------------------
709
+ # _OutputRecord log attachment (to_text / to_rich)
710
+ # ---------------------------------------------------------------------------
711
+
712
+
713
+ class TestOutputRecordLogAttachment:
714
+ def test_to_text_no_logs(self) -> None:
715
+ record: ConfigRecord = ConfigRecord(config={"a": 1})
716
+ text: str = record.to_text()
717
+
718
+ assert text == "Config: {'a': 1}"
719
+
720
+ def test_to_text_errors_only(self) -> None:
721
+ record: ConfigRecord = ConfigRecord(
722
+ config={"a": 1},
723
+ errors=[ErrorLog(category="x", message="err1")],
724
+ )
725
+ text: str = record.to_text()
726
+
727
+ assert text == "Config: {'a': 1}\n ✗ err1"
728
+
729
+ def test_to_text_infos_only(self) -> None:
730
+ record: ConfigRecord = ConfigRecord(
731
+ config={"a": 1},
732
+ infos=[InfoLog(category="x", message="note1")],
733
+ )
734
+ text: str = record.to_text()
735
+
736
+ assert text == "Config: {'a': 1}\n ℹ note1"
737
+
738
+ def test_to_text_mixed(self) -> None:
739
+ record: ConfigRecord = ConfigRecord(
740
+ config={"a": 1},
741
+ errors=[ErrorLog(category="x", message="err1")],
742
+ infos=[InfoLog(category="y", message="note1")],
743
+ )
744
+ text: str = record.to_text()
745
+
746
+ assert text == "Config: {'a': 1}\n ✗ err1\n ℹ note1"
747
+
748
+ def test_to_rich_string_body(self) -> None:
749
+ record: ComparisonSkipRecord = ComparisonSkipRecord(
750
+ name="x",
751
+ reason="r",
752
+ errors=[ErrorLog(category="e", message="oops")],
753
+ )
754
+ body = record.to_rich()
755
+
756
+ assert isinstance(body, str)
757
+ assert body == "[dim]⊘ x ── skipped (r)[/]\n [red]✗ oops[/]\n"
758
+
759
+ def test_to_rich_group_body(self) -> None:
760
+ record: ConfigRecord = ConfigRecord(
761
+ config={"a": 1},
762
+ errors=[ErrorLog(category="e", message="oops")],
763
+ )
764
+ body = record.to_rich()
765
+
766
+ # Panel body + log block → Group
767
+ assert isinstance(body, Group)
768
+
769
+
770
+ if __name__ == "__main__":
771
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_per_token_visualizer.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer 2: PNG generation tests for per-token heatmap visualizer.
2
+
3
+ Requires matplotlib — uses pytest.importorskip to gracefully skip if absent.
4
+ """
5
+
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+ import torch
11
+
12
+ from sglang.srt.debug_utils.comparator.output_types import ComparisonTensorRecord
13
+ from sglang.srt.debug_utils.comparator.tensor_comparator.comparator import (
14
+ compare_tensor_pair,
15
+ )
16
+ from sglang.test.ci.ci_register import register_cpu_ci
17
+
18
+ register_cpu_ci(est_time=30, suite="base-a-test-cpu", nightly=True)
19
+
20
+ _PNG_MAGIC: bytes = b"\x89PNG"
21
+
22
+
23
+ @pytest.fixture(autouse=True)
24
+ def _skip_if_no_matplotlib() -> None:
25
+ pytest.importorskip("matplotlib")
26
+
27
+
28
+ def _make_comparison_record(
29
+ *,
30
+ name: str,
31
+ baseline: torch.Tensor,
32
+ target: torch.Tensor,
33
+ seq_dim: int = 0,
34
+ ) -> ComparisonTensorRecord:
35
+ """Build a ComparisonTensorRecord with per-token data from raw tensors."""
36
+ info = compare_tensor_pair(
37
+ x_baseline=baseline,
38
+ x_target=target,
39
+ name=name,
40
+ diff_threshold=1e-3,
41
+ seq_dim=seq_dim,
42
+ )
43
+ return ComparisonTensorRecord(**info.model_dump())
44
+
45
+
46
+ class TestPerTokenVisualizer:
47
+ def test_no_data_returns_none(self, tmp_path: Path) -> None:
48
+ """Empty records list → None returned, no file created."""
49
+ from sglang.srt.debug_utils.comparator.per_token_visualizer import (
50
+ generate_per_token_heatmap,
51
+ )
52
+
53
+ output_path: Path = tmp_path / "empty.png"
54
+ result = generate_per_token_heatmap(records=[], output_path=output_path)
55
+
56
+ assert result is None
57
+ assert not output_path.exists()
58
+
59
+ def test_no_per_token_data_returns_none(self, tmp_path: Path) -> None:
60
+ """Records without per_token_rel_diff → None."""
61
+ from sglang.srt.debug_utils.comparator.per_token_visualizer import (
62
+ generate_per_token_heatmap,
63
+ )
64
+
65
+ info = compare_tensor_pair(
66
+ x_baseline=torch.randn(4, 8),
67
+ x_target=torch.randn(4, 8),
68
+ name="no_per_token",
69
+ diff_threshold=1e-3,
70
+ )
71
+ record = ComparisonTensorRecord(**info.model_dump())
72
+
73
+ output_path: Path = tmp_path / "no_data.png"
74
+ result = generate_per_token_heatmap(records=[record], output_path=output_path)
75
+
76
+ assert result is None
77
+
78
+ def test_generates_valid_png(self, tmp_path: Path) -> None:
79
+ """Records with per-token data → valid PNG file."""
80
+ from sglang.srt.debug_utils.comparator.per_token_visualizer import (
81
+ generate_per_token_heatmap,
82
+ )
83
+
84
+ torch.manual_seed(42)
85
+ records: list[ComparisonTensorRecord] = [
86
+ _make_comparison_record(
87
+ name=f"tensor_{i}",
88
+ baseline=torch.randn(16, 32),
89
+ target=torch.randn(16, 32),
90
+ )
91
+ for i in range(3)
92
+ ]
93
+
94
+ output_path: Path = tmp_path / "heatmap.png"
95
+ result = generate_per_token_heatmap(records=records, output_path=output_path)
96
+
97
+ assert result == output_path
98
+ assert output_path.exists()
99
+ assert output_path.stat().st_size > 0
100
+ with open(output_path, "rb") as f:
101
+ magic: bytes = f.read(4)
102
+ assert magic == _PNG_MAGIC
103
+
104
+ def test_variable_length_sequences(self, tmp_path: Path) -> None:
105
+ """Records with different token lengths → NaN padding, no crash."""
106
+ from sglang.srt.debug_utils.comparator.per_token_visualizer import (
107
+ generate_per_token_heatmap,
108
+ )
109
+
110
+ torch.manual_seed(42)
111
+ records: list[ComparisonTensorRecord] = [
112
+ _make_comparison_record(
113
+ name="short",
114
+ baseline=torch.randn(4, 8),
115
+ target=torch.randn(4, 8),
116
+ ),
117
+ _make_comparison_record(
118
+ name="medium",
119
+ baseline=torch.randn(16, 8),
120
+ target=torch.randn(16, 8),
121
+ ),
122
+ _make_comparison_record(
123
+ name="long",
124
+ baseline=torch.randn(64, 8),
125
+ target=torch.randn(64, 8),
126
+ ),
127
+ ]
128
+
129
+ output_path: Path = tmp_path / "variable.png"
130
+ result = generate_per_token_heatmap(records=records, output_path=output_path)
131
+
132
+ assert result == output_path
133
+ assert output_path.exists()
134
+ with open(output_path, "rb") as f:
135
+ magic: bytes = f.read(4)
136
+ assert magic == _PNG_MAGIC
137
+
138
+ def test_creates_parent_dirs(self, tmp_path: Path) -> None:
139
+ """Output path with non-existent parent dirs → dirs created automatically."""
140
+ from sglang.srt.debug_utils.comparator.per_token_visualizer import (
141
+ generate_per_token_heatmap,
142
+ )
143
+
144
+ torch.manual_seed(42)
145
+ record = _make_comparison_record(
146
+ name="test",
147
+ baseline=torch.randn(8, 16),
148
+ target=torch.randn(8, 16),
149
+ )
150
+
151
+ output_path: Path = tmp_path / "nested" / "deep" / "heatmap.png"
152
+ result = generate_per_token_heatmap(records=[record], output_path=output_path)
153
+
154
+ assert result == output_path
155
+ assert output_path.exists()
156
+
157
+
158
+ if __name__ == "__main__":
159
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_preset.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from sglang.srt.debug_utils.comparator.preset import PRESETS, expand_preset
4
+ from sglang.test.ci.ci_register import register_cpu_ci
5
+
6
+ register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True)
7
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
8
+
9
+
10
+ class TestExpandPreset:
11
+ """Test preset expansion logic."""
12
+
13
+ def test_explicit_preset(self):
14
+ """--preset sglang_megatron expands into its argv."""
15
+ argv = [
16
+ "--baseline-path",
17
+ "/a",
18
+ "--preset",
19
+ "sglang_megatron",
20
+ "--diff-threshold",
21
+ "0.01",
22
+ ]
23
+ result = expand_preset(argv, presets=PRESETS)
24
+ assert "--preset" not in result
25
+ assert "--grouping-skip-keys" in result
26
+ assert "concat_steps" in result
27
+ assert "--baseline-path" in result
28
+ assert "--diff-threshold" in result
29
+
30
+ def test_default_preset_applied(self):
31
+ """No --preset and no --grouping-skip-keys triggers default preset."""
32
+ argv = ["--baseline-path", "/a"]
33
+ result = expand_preset(argv, presets=PRESETS)
34
+ assert "--grouping-skip-keys" in result
35
+
36
+ def test_explicit_skip_keys_prevents_default(self):
37
+ """Explicit --grouping-skip-keys prevents default preset injection."""
38
+ argv = ["--grouping-skip-keys", "rank", "--baseline-path", "/a"]
39
+ result = expand_preset(argv, presets=PRESETS)
40
+ assert result == argv
41
+
42
+ def test_unknown_preset_raises(self):
43
+ """Unknown preset name raises ValueError."""
44
+ with pytest.raises(ValueError, match="Unknown value for --preset"):
45
+ expand_preset(["--preset", "nonexistent"], presets=PRESETS)
46
+
47
+
48
+ if __name__ == "__main__":
49
+ import sys
50
+
51
+ sys.exit(pytest.main([__file__, "-v"]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_utils.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+ import torch
6
+
7
+ from sglang.srt.debug_utils.comparator.output_types import SummaryRecord
8
+ from sglang.srt.debug_utils.comparator.utils import (
9
+ Pair,
10
+ argmax_coord,
11
+ auto_descend_dir,
12
+ calc_per_token_rel_diff,
13
+ calc_rel_diff,
14
+ compute_exit_code,
15
+ compute_smaller_dtype,
16
+ try_unify_shape,
17
+ )
18
+ from sglang.test.ci.ci_register import register_cpu_ci
19
+
20
+ register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True)
21
+ register_cpu_ci(est_time=1, suite="base-c-test-cpu")
22
+
23
+
24
+ class TestCalcRelDiff:
25
+ def test_identical_tensors(self):
26
+ x = torch.randn(10, 10)
27
+ assert calc_rel_diff(x, x).item() == pytest.approx(0.0, abs=1e-5)
28
+
29
+ def test_orthogonal_tensors(self):
30
+ result = calc_rel_diff(
31
+ torch.tensor([1.0, 0.0]), torch.tensor([0.0, 1.0])
32
+ ).item()
33
+ assert result == pytest.approx(1.0, abs=1e-5)
34
+
35
+ def test_similar_tensors(self):
36
+ x = torch.tensor([1.0, 2.0, 3.0])
37
+ y = torch.tensor([1.01, 2.01, 3.01])
38
+ result = calc_rel_diff(x, y).item()
39
+ assert 0.0 < result < 0.01
40
+
41
+ def test_negated_tensors(self):
42
+ x = torch.tensor([1.0, 2.0])
43
+ result = calc_rel_diff(x, -x).item()
44
+ assert result == pytest.approx(2.0, abs=1e-5)
45
+
46
+
47
+ class TestCalcPerTokenRelDiff:
48
+ def test_identical_tensors(self) -> None:
49
+ """Identical tensors → per-token diff all zero."""
50
+ x: torch.Tensor = torch.randn(8, 16)
51
+ result: torch.Tensor = calc_per_token_rel_diff(x, x, seq_dim=0)
52
+
53
+ assert result.shape == (8,)
54
+ assert torch.allclose(result, torch.zeros(8), atol=1e-6)
55
+
56
+ def test_different_tensors(self) -> None:
57
+ """Single token position differs → that position has higher diff."""
58
+ torch.manual_seed(42)
59
+ x: torch.Tensor = torch.randn(8, 16)
60
+ y: torch.Tensor = x.clone()
61
+ y[3, :] += 10.0
62
+
63
+ result: torch.Tensor = calc_per_token_rel_diff(x, y, seq_dim=0)
64
+
65
+ assert result.shape == (8,)
66
+ assert result[3] > result[0]
67
+ assert result[3] > result[7]
68
+ for i in [0, 1, 2, 4, 5, 6, 7]:
69
+ assert result[i] < 1e-6
70
+
71
+ def test_seq_dim_selection(self) -> None:
72
+ """Different seq_dim values produce correct output shapes."""
73
+ x: torch.Tensor = torch.randn(4, 8, 16)
74
+ y: torch.Tensor = x + torch.randn_like(x) * 0.01
75
+
76
+ assert calc_per_token_rel_diff(x, y, seq_dim=0).shape == (4,)
77
+ assert calc_per_token_rel_diff(x, y, seq_dim=1).shape == (8,)
78
+ assert calc_per_token_rel_diff(x, y, seq_dim=2).shape == (16,)
79
+
80
+ def test_1d_tensor(self) -> None:
81
+ """1D tensor with seq_dim=0 returns per-element diff."""
82
+ x: torch.Tensor = torch.tensor([1.0, 2.0, 3.0])
83
+ y: torch.Tensor = torch.tensor([1.0, 2.0, 4.0])
84
+
85
+ result: torch.Tensor = calc_per_token_rel_diff(x, y, seq_dim=0)
86
+
87
+ assert result.shape == (3,)
88
+ assert result[0] < 1e-6
89
+ assert result[1] < 1e-6
90
+ assert result[2] > 0.01
91
+
92
+
93
+ class TestArgmaxCoord:
94
+ def test_1d_tensor(self):
95
+ x = torch.tensor([0.0, 0.0, 5.0, 0.0])
96
+ assert argmax_coord(x) == (2,)
97
+
98
+ def test_2d_tensor(self):
99
+ x = torch.zeros(3, 4)
100
+ x[1, 2] = 10.0
101
+ assert argmax_coord(x) == (1, 2)
102
+
103
+ def test_3d_tensor(self):
104
+ x = torch.zeros(2, 3, 4)
105
+ x[1, 2, 3] = 10.0
106
+ assert argmax_coord(x) == (1, 2, 3)
107
+
108
+
109
+ class TestTryUnifyShape:
110
+ def test_squeeze_leading_ones(self):
111
+ target = torch.Size([3, 4])
112
+ assert try_unify_shape(torch.randn(1, 1, 3, 4), target).shape == target
113
+
114
+ def test_no_squeeze_when_leading_dim_not_one(self):
115
+ target = torch.Size([3, 4])
116
+ assert try_unify_shape(torch.randn(2, 3, 4), target).shape == (2, 3, 4)
117
+
118
+ def test_same_shape_noop(self):
119
+ target = torch.Size([3, 4])
120
+ x = torch.randn(3, 4)
121
+ result = try_unify_shape(x, target)
122
+ assert result.shape == target
123
+ assert result.data_ptr() == x.data_ptr()
124
+
125
+ def test_trailing_dims_mismatch(self):
126
+ target = torch.Size([5, 6])
127
+ x = torch.randn(1, 3, 4)
128
+ result = try_unify_shape(x, target)
129
+ assert result.shape == (1, 3, 4)
130
+
131
+
132
+ class TestComputeSmallerDtype:
133
+ def test_float32_bfloat16(self):
134
+ assert (
135
+ compute_smaller_dtype(Pair(x=torch.float32, y=torch.bfloat16))
136
+ == torch.bfloat16
137
+ )
138
+
139
+ def test_reverse_order(self):
140
+ assert (
141
+ compute_smaller_dtype(Pair(x=torch.bfloat16, y=torch.float32))
142
+ == torch.bfloat16
143
+ )
144
+
145
+ def test_same_dtype_returns_none(self):
146
+ assert compute_smaller_dtype(Pair(x=torch.float32, y=torch.float32)) is None
147
+
148
+ def test_unknown_pair_returns_none(self):
149
+ assert compute_smaller_dtype(Pair(x=torch.int32, y=torch.int64)) is None
150
+
151
+
152
+ class TestPairMap:
153
+ def test_map_basic(self):
154
+ pair = Pair(x=[1, 2, 3], y=[4, 5, 6])
155
+ result = pair.map(lambda lst: sum(lst))
156
+ assert result.x == 6
157
+ assert result.y == 15
158
+
159
+ def test_map_type_change(self):
160
+ pair = Pair(x=[1, 2, 3], y=[10, 20])
161
+ result = pair.map(len)
162
+ assert result.x == 3
163
+ assert result.y == 2
164
+
165
+ def test_map_returns_new_pair(self):
166
+ pair = Pair(x="hello", y="world")
167
+ result = pair.map(str.upper)
168
+ assert result.x == "HELLO"
169
+ assert result.y == "WORLD"
170
+ assert result is not pair
171
+
172
+
173
+ class TestComputeExitCode:
174
+ """Unit tests for compute_exit_code logic."""
175
+
176
+ def test_all_passed(self):
177
+ """All passed → exit 0."""
178
+ summary = SummaryRecord(total=3, passed=3, failed=0, skipped=0)
179
+ assert (
180
+ compute_exit_code(
181
+ summary,
182
+ allow_skipped_pattern=".*",
183
+ skipped_names=[],
184
+ allow_failed_pattern=None,
185
+ failed_names=[],
186
+ )
187
+ == 0
188
+ )
189
+
190
+ def test_has_failed_and_passed(self):
191
+ """Has failed and passed → exit 1."""
192
+ summary = SummaryRecord(total=4, passed=2, failed=2, skipped=0)
193
+ assert (
194
+ compute_exit_code(
195
+ summary,
196
+ allow_skipped_pattern=".*",
197
+ skipped_names=[],
198
+ allow_failed_pattern=None,
199
+ failed_names=["a", "b"],
200
+ )
201
+ == 1
202
+ )
203
+
204
+ def test_all_failed(self):
205
+ """All failed (0 passed) → exit 1."""
206
+ summary = SummaryRecord(total=3, passed=0, failed=3, skipped=0)
207
+ assert (
208
+ compute_exit_code(
209
+ summary,
210
+ allow_skipped_pattern=".*",
211
+ skipped_names=[],
212
+ allow_failed_pattern=None,
213
+ failed_names=["a", "b", "c"],
214
+ )
215
+ == 1
216
+ )
217
+
218
+ def test_all_skipped_allow_all(self):
219
+ """All skipped + allow_skipped_pattern='.*' → exit 1 (nothing passed)."""
220
+ summary = SummaryRecord(total=2, passed=0, failed=0, skipped=2)
221
+ assert (
222
+ compute_exit_code(
223
+ summary,
224
+ allow_skipped_pattern=".*",
225
+ skipped_names=["a", "b"],
226
+ allow_failed_pattern=None,
227
+ failed_names=[],
228
+ )
229
+ == 1
230
+ )
231
+
232
+ def test_all_skipped_forbid_all(self):
233
+ """All skipped + allow_skipped_pattern='^$' → exit 1."""
234
+ summary = SummaryRecord(total=2, passed=0, failed=0, skipped=2)
235
+ assert (
236
+ compute_exit_code(
237
+ summary,
238
+ allow_skipped_pattern="^$",
239
+ skipped_names=["a", "b"],
240
+ allow_failed_pattern=None,
241
+ failed_names=[],
242
+ )
243
+ == 1
244
+ )
245
+
246
+ def test_passed_and_skipped_allow_all(self):
247
+ """Passed + skipped, allow all → exit 0."""
248
+ summary = SummaryRecord(total=3, passed=2, failed=0, skipped=1)
249
+ assert (
250
+ compute_exit_code(
251
+ summary,
252
+ allow_skipped_pattern=".*",
253
+ skipped_names=["a"],
254
+ allow_failed_pattern=None,
255
+ failed_names=[],
256
+ )
257
+ == 0
258
+ )
259
+
260
+ def test_passed_and_skipped_forbid_all(self):
261
+ """Passed + skipped + forbid all → exit 1."""
262
+ summary = SummaryRecord(total=3, passed=2, failed=0, skipped=1)
263
+ assert (
264
+ compute_exit_code(
265
+ summary,
266
+ allow_skipped_pattern="^$",
267
+ skipped_names=["a"],
268
+ allow_failed_pattern=None,
269
+ failed_names=[],
270
+ )
271
+ == 1
272
+ )
273
+
274
+ def test_skip_pattern_matches_specific_name(self):
275
+ """Pattern matching specific name allows that skip, forbids others."""
276
+ summary = SummaryRecord(total=4, passed=2, failed=0, skipped=2)
277
+ assert (
278
+ compute_exit_code(
279
+ summary,
280
+ allow_skipped_pattern="positions|seq_lens",
281
+ skipped_names=["positions", "seq_lens"],
282
+ allow_failed_pattern=None,
283
+ failed_names=[],
284
+ )
285
+ == 0
286
+ )
287
+
288
+ def test_skip_pattern_partial_match_forbidden(self):
289
+ """Pattern matches some skips but not all → exit 1."""
290
+ summary = SummaryRecord(total=4, passed=1, failed=0, skipped=3)
291
+ assert (
292
+ compute_exit_code(
293
+ summary,
294
+ allow_skipped_pattern="positions|seq_lens",
295
+ skipped_names=["positions", "seq_lens", "hidden_states"],
296
+ allow_failed_pattern=None,
297
+ failed_names=[],
298
+ )
299
+ == 1
300
+ )
301
+
302
+ def test_allow_failed_pattern_matches_all(self):
303
+ """allow_failed_pattern='.*' tolerates all failures → exit 0."""
304
+ summary = SummaryRecord(total=3, passed=1, failed=2, skipped=0)
305
+ assert (
306
+ compute_exit_code(
307
+ summary,
308
+ allow_skipped_pattern=".*",
309
+ skipped_names=[],
310
+ allow_failed_pattern=".*",
311
+ failed_names=["a", "b"],
312
+ )
313
+ == 0
314
+ )
315
+
316
+ def test_allow_failed_pattern_matches_specific(self):
317
+ """Pattern matches all failed names → exit 0."""
318
+ summary = SummaryRecord(total=3, passed=1, failed=2, skipped=0)
319
+ assert (
320
+ compute_exit_code(
321
+ summary,
322
+ allow_skipped_pattern=".*",
323
+ skipped_names=[],
324
+ allow_failed_pattern="hidden_states|logits",
325
+ failed_names=["hidden_states", "logits"],
326
+ )
327
+ == 0
328
+ )
329
+
330
+ def test_allow_failed_pattern_partial_match(self):
331
+ """Pattern matches some but not all failures → exit 1."""
332
+ summary = SummaryRecord(total=3, passed=0, failed=3, skipped=0)
333
+ assert (
334
+ compute_exit_code(
335
+ summary,
336
+ allow_skipped_pattern=".*",
337
+ skipped_names=[],
338
+ allow_failed_pattern="hidden_states",
339
+ failed_names=["hidden_states", "logits", "attn"],
340
+ )
341
+ == 1
342
+ )
343
+
344
+ def test_allow_failed_pattern_no_failures(self):
345
+ """Pattern set but no failures → exit 0."""
346
+ summary = SummaryRecord(total=2, passed=2, failed=0, skipped=0)
347
+ assert (
348
+ compute_exit_code(
349
+ summary,
350
+ allow_skipped_pattern=".*",
351
+ skipped_names=[],
352
+ allow_failed_pattern=".*",
353
+ failed_names=[],
354
+ )
355
+ == 0
356
+ )
357
+
358
+ def test_both_failed_and_skipped_patterns(self):
359
+ """Both patterns set, both satisfied → exit 0."""
360
+ summary = SummaryRecord(total=4, passed=1, failed=1, skipped=2)
361
+ assert (
362
+ compute_exit_code(
363
+ summary,
364
+ allow_skipped_pattern="positions|seq_lens",
365
+ skipped_names=["positions", "seq_lens"],
366
+ allow_failed_pattern="logits",
367
+ failed_names=["logits"],
368
+ )
369
+ == 0
370
+ )
371
+
372
+ def test_failed_pattern_satisfied_but_skipped_not(self):
373
+ """Failed pattern OK but skipped pattern fails → exit 1."""
374
+ summary = SummaryRecord(total=3, passed=1, failed=1, skipped=1)
375
+ assert (
376
+ compute_exit_code(
377
+ summary,
378
+ allow_skipped_pattern="^$",
379
+ skipped_names=["a"],
380
+ allow_failed_pattern=".*",
381
+ failed_names=["b"],
382
+ )
383
+ == 1
384
+ )
385
+
386
+ def test_zero_passed_exits_one(self):
387
+ """No tensors passed → exit 1, even when all failures are allowed."""
388
+ summary = SummaryRecord(total=2, passed=0, failed=2, skipped=0)
389
+ assert (
390
+ compute_exit_code(
391
+ summary,
392
+ allow_skipped_pattern=".*",
393
+ skipped_names=[],
394
+ allow_failed_pattern=".*",
395
+ failed_names=["a", "b"],
396
+ )
397
+ == 1
398
+ )
399
+
400
+ def test_zero_passed_all_skipped_exits_one(self):
401
+ """All skipped, nothing passed → exit 1."""
402
+ summary = SummaryRecord(total=3, passed=0, failed=0, skipped=3)
403
+ assert (
404
+ compute_exit_code(
405
+ summary,
406
+ allow_skipped_pattern=".*",
407
+ skipped_names=["a", "b", "c"],
408
+ allow_failed_pattern=None,
409
+ failed_names=[],
410
+ )
411
+ == 1
412
+ )
413
+
414
+ def test_errored_with_passed_exits_one(self):
415
+ """Has errored bundle even with passed → exit 1."""
416
+ summary = SummaryRecord(total=3, passed=2, failed=0, skipped=0, errored=1)
417
+ assert (
418
+ compute_exit_code(
419
+ summary,
420
+ allow_skipped_pattern=".*",
421
+ skipped_names=[],
422
+ allow_failed_pattern=None,
423
+ failed_names=[],
424
+ errored_names=["broken_tensor"],
425
+ )
426
+ == 1
427
+ )
428
+
429
+ def test_errored_only_exits_one(self):
430
+ """All errored → exit 1 (passed==0 already exits 1, but errored also independently triggers)."""
431
+ summary = SummaryRecord(total=1, passed=0, failed=0, skipped=0, errored=1)
432
+ assert (
433
+ compute_exit_code(
434
+ summary,
435
+ allow_skipped_pattern=".*",
436
+ skipped_names=[],
437
+ allow_failed_pattern=None,
438
+ failed_names=[],
439
+ errored_names=["broken_tensor"],
440
+ )
441
+ == 1
442
+ )
443
+
444
+
445
+ def _make_pt(directory: Path) -> None:
446
+ directory.mkdir(parents=True, exist_ok=True)
447
+ torch.save(torch.tensor([1.0]), directory / "dummy.pt")
448
+
449
+
450
+ class TestAutoDescendDir:
451
+ def test_no_descend_when_pt_at_root(self, tmp_path: Path) -> None:
452
+ """Directory with .pt files directly is returned as-is."""
453
+ _make_pt(tmp_path)
454
+ _make_pt(tmp_path / "child_a")
455
+ assert auto_descend_dir(tmp_path, label="test") == tmp_path
456
+
457
+ def test_descend_into_single_child(self, tmp_path: Path) -> None:
458
+ """Single child with .pt triggers descend."""
459
+ child: Path = tmp_path / "engine_0"
460
+ _make_pt(child)
461
+ assert auto_descend_dir(tmp_path, label="test") == child
462
+
463
+ def test_descend_single_nonempty_child_among_empty(self, tmp_path: Path) -> None:
464
+ """Two subdirs but only one has .pt — descend into that one."""
465
+ nonempty: Path = tmp_path / "engine_0"
466
+ _make_pt(nonempty)
467
+ (tmp_path / "empty_child").mkdir()
468
+ assert auto_descend_dir(tmp_path, label="test") == nonempty
469
+
470
+ def test_error_with_multiple_nonempty_children(self, tmp_path: Path) -> None:
471
+ """Two children with .pt files — ambiguous, raises ValueError."""
472
+ _make_pt(tmp_path / "engine_0")
473
+ _make_pt(tmp_path / "engine_1")
474
+ with pytest.raises(ValueError, match="multiple subdirectories contain data"):
475
+ auto_descend_dir(tmp_path, label="test")
476
+
477
+ def test_error_when_no_data_found(self, tmp_path: Path) -> None:
478
+ """No .pt files anywhere — raises ValueError."""
479
+ (tmp_path / "empty_child").mkdir()
480
+ with pytest.raises(ValueError, match="no .pt files found"):
481
+ auto_descend_dir(tmp_path, label="test")
482
+
483
+
484
+ if __name__ == "__main__":
485
+ sys.exit(pytest.main([__file__]))
asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_visualizer.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+ import torch
6
+
7
+ from sglang.srt.debug_utils.comparator.visualizer.preprocessing import (
8
+ _preprocess_tensor,
9
+ _reshape_to_balanced_aspect,
10
+ )
11
+ from sglang.test.ci.ci_register import register_cpu_ci
12
+
13
+ register_cpu_ci(est_time=30, suite="base-a-test-cpu", nightly=True)
14
+
15
+
16
+ class TestPreprocessTensor:
17
+ def test_1d_becomes_2d(self) -> None:
18
+ t: torch.Tensor = torch.randn(100)
19
+ result: torch.Tensor = _preprocess_tensor(t)
20
+ assert result.ndim == 2
21
+
22
+ def test_3d_becomes_2d(self) -> None:
23
+ t: torch.Tensor = torch.randn(2, 3, 4)
24
+ result: torch.Tensor = _preprocess_tensor(t)
25
+ assert result.ndim == 2
26
+ assert result.numel() == t.numel()
27
+
28
+ def test_high_dim_becomes_2d(self) -> None:
29
+ t: torch.Tensor = torch.randn(2, 3, 4, 5)
30
+ result: torch.Tensor = _preprocess_tensor(t)
31
+ assert result.ndim == 2
32
+ assert result.numel() == t.numel()
33
+
34
+ def test_scalar_becomes_2d(self) -> None:
35
+ t: torch.Tensor = torch.tensor(3.14)
36
+ result: torch.Tensor = _preprocess_tensor(t)
37
+ assert result.ndim == 2
38
+ assert result.numel() == 1
39
+
40
+ def test_already_2d_preserves_elements(self) -> None:
41
+ t: torch.Tensor = torch.randn(10, 20)
42
+ result: torch.Tensor = _preprocess_tensor(t)
43
+ assert result.ndim == 2
44
+ assert result.numel() == 200
45
+
46
+
47
+ class TestReshapeToBalancedAspect:
48
+ def test_extreme_wide_gets_fixed(self) -> None:
49
+ t: torch.Tensor = torch.randn(1, 10000)
50
+ result: torch.Tensor = _reshape_to_balanced_aspect(t)
51
+ h, w = result.shape
52
+ ratio: float = max(h, w) / max(min(h, w), 1)
53
+ assert ratio <= 5.0
54
+
55
+ def test_extreme_tall_gets_fixed(self) -> None:
56
+ t: torch.Tensor = torch.randn(10000, 1)
57
+ result: torch.Tensor = _reshape_to_balanced_aspect(t)
58
+ h, w = result.shape
59
+ ratio: float = max(h, w) / max(min(h, w), 1)
60
+ assert ratio <= 5.0
61
+
62
+ def test_already_balanced_unchanged(self) -> None:
63
+ t: torch.Tensor = torch.randn(100, 100)
64
+ result: torch.Tensor = _reshape_to_balanced_aspect(t)
65
+ assert result.shape == (100, 100)
66
+
67
+ def test_preserves_numel(self) -> None:
68
+ t: torch.Tensor = torch.randn(1, 7919)
69
+ result: torch.Tensor = _reshape_to_balanced_aspect(t)
70
+ assert result.numel() == t.numel()
71
+
72
+
73
+ class TestGenerateComparisonFigure:
74
+ @pytest.fixture(autouse=True)
75
+ def _skip_if_no_matplotlib(self) -> None:
76
+ pytest.importorskip("matplotlib")
77
+
78
+ def test_nested_output_dir(self, tmp_path: Path) -> None:
79
+ from sglang.srt.debug_utils.comparator.visualizer import (
80
+ generate_comparison_figure,
81
+ )
82
+
83
+ output_path: Path = tmp_path / "a" / "b" / "c" / "nested.png"
84
+
85
+ generate_comparison_figure(
86
+ baseline=torch.randn(10, 10),
87
+ target=torch.randn(10, 10),
88
+ name="nested",
89
+ output_path=output_path,
90
+ )
91
+
92
+ assert output_path.exists()
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(pytest.main([__file__]))