diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/conftest.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/__init__.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/conftest.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_executor.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..b9bae5e246c441691136d23fd4285aac442f5876 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_executor.py @@ -0,0 +1,334 @@ +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.entrypoint.executor import ( + AlignerResult, + StepPlansResult, + SubPlansResult, + _execute_step_plans, + execute_aligner_plan, + execute_sub_plan, + execute_sub_plans, +) +from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import ( + AlignerPerStepPlan, + AlignerPlan, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( + TokenAlignerPlan, + TokenLocator, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( + ConcatParams, + UnsharderPlan, +) +from sglang.srt.debug_utils.comparator.dims_spec import ( + ParallelAxis, + TokenLayout, + apply_dim_names, + without_dim_names, +) +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestExecuteSubPlans: + def test_empty_tensors_returns_none(self) -> None: + r: SubPlansResult = execute_sub_plans(tensors=[], plans=[]) + assert r.tensor is None + assert r.checks == [] + assert r.snapshots == [] + + def test_no_plans_single_tensor_passthrough(self) -> None: + tensor: torch.Tensor = torch.tensor([1.0, 2.0, 3.0]) + r: SubPlansResult = execute_sub_plans(tensors=[tensor], plans=[]) + assert r.tensor is not None + assert torch.equal(r.tensor, tensor) + assert r.checks == [] + assert r.snapshots == [] + + def test_no_plans_multiple_tensors_returns_none(self) -> None: + tensors: list[torch.Tensor] = [ + torch.tensor([1.0]), + torch.tensor([2.0]), + ] + r: SubPlansResult = execute_sub_plans(tensors=tensors, plans=[]) + assert r.tensor is None + assert r.checks == [] + assert r.snapshots == [] + + def test_with_unsharder_plan(self) -> None: + t0: torch.Tensor = apply_dim_names(torch.tensor([[1.0, 2.0]]), ["b", "h"]) + t1: torch.Tensor = apply_dim_names(torch.tensor([[3.0, 4.0]]), ["b", "h"]) + + plan = UnsharderPlan( + axis=ParallelAxis.TP, + params=ConcatParams(dim_name="h"), + groups=[[0, 1]], + ) + + r: SubPlansResult = execute_sub_plans(tensors=[t0, t1], plans=[plan]) + + assert r.tensor is not None + expected: torch.Tensor = torch.tensor([[1.0, 2.0, 3.0, 4.0]]) + assert torch.equal(without_dim_names(r.tensor), expected) + assert r.checks == [] + assert len(r.snapshots) == 1 + + +class TestExecuteSubPlan: + def test_unknown_plan_type_raises(self) -> None: + class _FakePlan: + pass + + with pytest.raises(NotImplementedError, match="Unknown"): + execute_sub_plan(tensors=[torch.tensor([1.0])], plan=_FakePlan()) + + +class TestExecuteStepPlans: + def test_step_with_none_result_omitted(self) -> None: + tensors: list[torch.Tensor] = [ + torch.tensor([1.0]), + torch.tensor([2.0]), + ] + + step_plan = AlignerPerStepPlan( + step=0, + input_object_indices=[0, 1], + sub_plans=[], + ) + + r: StepPlansResult = _execute_step_plans( + tensors=tensors, step_plans=[step_plan] + ) + + assert r.tensors == {} + assert r.checks == [] + assert len(r.traced_side.step_plans) == 1 + + def test_single_step_passthrough(self) -> None: + tensor: torch.Tensor = torch.tensor([1.0, 2.0]) + + step_plan = AlignerPerStepPlan( + step=5, + input_object_indices=[0], + sub_plans=[], + ) + + r: StepPlansResult = _execute_step_plans( + tensors=[tensor], step_plans=[step_plan] + ) + + assert 5 in r.tensors + assert torch.equal(r.tensors[5], tensor) + assert r.checks == [] + assert len(r.traced_side.step_plans) == 1 + assert r.traced_side.step_plans[0].step == 5 + + +class TestExecuteAlignerPlan: + def _make_step_plan(self, *, step: int, indices: list[int]) -> AlignerPerStepPlan: + return AlignerPerStepPlan(step=step, input_object_indices=indices, sub_plans=[]) + + def test_x_side_empty_returns_failed_x(self) -> None: + plan = AlignerPlan( + per_step_plans=Pair( + x=[self._make_step_plan(step=0, indices=[0, 1])], + y=[self._make_step_plan(step=0, indices=[0])], + ), + token_aligner_plan=None, + ) + + tensors_pair: Pair[list[torch.Tensor]] = Pair( + x=[torch.tensor([1.0]), torch.tensor([2.0])], + y=[torch.tensor([3.0])], + ) + + result: AlignerResult = execute_aligner_plan( + tensors_pair=tensors_pair, plan=plan + ) + + assert result.tensors is None + assert result.failed_side_xy == "x" + + def test_y_side_empty_returns_failed_y(self) -> None: + plan = AlignerPlan( + per_step_plans=Pair( + x=[self._make_step_plan(step=0, indices=[0])], + y=[self._make_step_plan(step=0, indices=[0, 1])], + ), + token_aligner_plan=None, + ) + + tensors_pair: Pair[list[torch.Tensor]] = Pair( + x=[torch.tensor([1.0])], + y=[torch.tensor([2.0]), torch.tensor([3.0])], + ) + + result: AlignerResult = execute_aligner_plan( + tensors_pair=tensors_pair, plan=plan + ) + + assert result.tensors is None + assert result.failed_side_xy == "y" + + def test_no_token_aligner_single_step(self) -> None: + plan = AlignerPlan( + per_step_plans=Pair( + x=[self._make_step_plan(step=0, indices=[0])], + y=[self._make_step_plan(step=0, indices=[0])], + ), + token_aligner_plan=None, + ) + + t_x: torch.Tensor = torch.tensor([1.0, 2.0]) + t_y: torch.Tensor = torch.tensor([3.0, 4.0]) + tensors_pair: Pair[list[torch.Tensor]] = Pair(x=[t_x], y=[t_y]) + + result: AlignerResult = execute_aligner_plan( + tensors_pair=tensors_pair, plan=plan + ) + + assert result.tensors is not None + assert result.failed_side_xy is None + assert torch.equal(result.tensors.x, t_x) + assert torch.equal(result.tensors.y, t_y) + + def test_success_returns_none_failed_side(self) -> None: + plan = AlignerPlan( + per_step_plans=Pair( + x=[self._make_step_plan(step=0, indices=[0])], + y=[self._make_step_plan(step=0, indices=[0])], + ), + token_aligner_plan=None, + ) + + tensors_pair: Pair[list[torch.Tensor]] = Pair( + x=[torch.tensor([10.0])], + y=[torch.tensor([20.0])], + ) + + result: AlignerResult = execute_aligner_plan( + tensors_pair=tensors_pair, plan=plan + ) + + assert result.failed_side_xy is None + assert result.tensors is not None + + +class TestExecuteAlignerPlanWithTokenDim: + """End-to-end tests for AlignerPlan with non-zero token_dim.""" + + def _make_step_plan(self, *, step: int, indices: list[int]) -> AlignerPerStepPlan: + return AlignerPerStepPlan(step=step, input_object_indices=indices, sub_plans=[]) + + def test_token_dim_nonzero_e2e(self) -> None: + """AlignerPlan with token at dim 1 passes through to token aligner correctly.""" + torch.manual_seed(42) + + # shape [3, 4, 8]: dim0=a, dim1=token(4 tokens), dim2=hidden + tensor_x: torch.Tensor = apply_dim_names(torch.randn(3, 4, 8), ["a", "t", "h"]) + tensor_y: torch.Tensor = apply_dim_names(torch.randn(3, 4, 8), ["a", "t", "h"]) + + locator_x = TokenLocator( + steps=[0, 0, 0], + token_index_in_step=[0, 1, 2], + ) + locator_y = TokenLocator( + steps=[0, 0, 0], + token_index_in_step=[0, 1, 2], + ) + token_plan = TokenAlignerPlan( + locators=Pair(x=locator_x, y=locator_y), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.T), + ) + + plan = AlignerPlan( + per_step_plans=Pair( + x=[self._make_step_plan(step=0, indices=[0])], + y=[self._make_step_plan(step=0, indices=[0])], + ), + token_aligner_mode="smart", + token_aligner_plan=token_plan, + ) + + tensors_pair: Pair[list[torch.Tensor]] = Pair(x=[tensor_x], y=[tensor_y]) + result: AlignerResult = execute_aligner_plan( + tensors_pair=tensors_pair, plan=plan + ) + + assert result.tensors is not None + assert result.failed_side_xy is None + # token dim stays at dim 1 -> shape [3, 3, 8] (3 tokens selected from 4) + assert result.tensors.x.shape == (3, 3, 8) + assert result.tensors.y.shape == (3, 3, 8) + + plain_x: torch.Tensor = without_dim_names(tensor_x) + plain_y: torch.Tensor = without_dim_names(tensor_y) + for i in range(3): + assert torch.equal( + result.tensors.x.select(dim=1, index=i), + plain_x.select(dim=1, index=i), + ) + assert torch.equal( + result.tensors.y.select(dim=1, index=i), + plain_y.select(dim=1, index=i), + ) + + def test_bshd_cross_layout_e2e(self) -> None: + """x=SGLang THD, y=Megatron BSHD: planner->executor full flow.""" + torch.manual_seed(42) + + # x side: THD layout, shape [6, 8] (6 tokens, hidden=8), pre-named + tensor_x: torch.Tensor = apply_dim_names(torch.randn(6, 8), ["t", "h"]) + + # y side: BSHD layout, shape [2, 3, 8] (B=2, S=3, H=8), pre-named + tensor_y: torch.Tensor = apply_dim_names(torch.randn(2, 3, 8), ["b", "s", "h"]) + flat_y: torch.Tensor = tensor_y.reshape(6, 8) + + locator = TokenLocator( + steps=[0, 0, 0], + token_index_in_step=[0, 2, 5], + ) + token_plan = TokenAlignerPlan( + locators=Pair(x=locator, y=locator), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.BS), + ) + + plan = AlignerPlan( + per_step_plans=Pair( + x=[self._make_step_plan(step=0, indices=[0])], + y=[self._make_step_plan(step=0, indices=[0])], + ), + token_aligner_mode="smart", + token_aligner_plan=token_plan, + ) + + tensors_pair: Pair[list[torch.Tensor]] = Pair(x=[tensor_x], y=[tensor_y]) + result: AlignerResult = execute_aligner_plan( + tensors_pair=tensors_pair, plan=plan + ) + + assert result.tensors is not None + assert result.failed_side_xy is None + + assert result.tensors.x.shape == (3, 8) + assert result.tensors.y.shape == (3, 8) + + plain_x: torch.Tensor = without_dim_names(tensor_x) + assert torch.equal(result.tensors.x[0], plain_x[0]) + assert torch.equal(result.tensors.x[1], plain_x[2]) + assert torch.equal(result.tensors.x[2], plain_x[5]) + + assert torch.equal(result.tensors.y[0], flat_y[0]) + assert torch.equal(result.tensors.y[1], flat_y[2]) + assert torch.equal(result.tensors.y[2], flat_y[5]) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_planner.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..84d59b54c22c0ff76f05c0a16e5d92097d974b9d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/entrypoint/test_planner.py @@ -0,0 +1,336 @@ +import sys +from typing import Any, Optional + +import pytest + +from sglang.srt.debug_utils.comparator.aligner.entrypoint.planner import ( + _compute_per_step_plans, + compute_aligner_plan, + compute_per_step_sub_plans, +) +from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import ( + AlignerPerStepPlan, + AlignerPerStepSubPlan, + AlignerPlan, +) +from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ( + ReordererPlan, + ZigzagToNaturalThdParams, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( + CpThdConcatParams, + UnsharderPlan, +) +from sglang.srt.debug_utils.comparator.dims_spec import TokenLayout +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +def _make_meta( + *, + step: int = 0, + dims: Optional[str] = None, + tp_rank: int = 0, + tp_size: int = 1, + cp_rank: int = 0, + cp_size: int = 1, + extra_parallel_info: Optional[dict[str, int]] = None, +) -> dict[str, Any]: + meta: dict[str, Any] = {"step": step} + if dims is not None: + meta["dims"] = dims + parallel_info: dict[str, int] = { + "tp_rank": tp_rank, + "tp_size": tp_size, + "cp_rank": cp_rank, + "cp_size": cp_size, + } + if extra_parallel_info is not None: + parallel_info.update(extra_parallel_info) + meta["sglang_parallel_info"] = parallel_info + return meta + + +class TestComputePerStepSubPlans: + def test_empty_metas(self) -> None: + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(metas=[]) + assert result == [] + + def test_single_meta(self) -> None: + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans( + metas=[_make_meta(dims="b h[tp]", tp_size=2)] + ) + assert result == [] + + def test_dims_none(self) -> None: + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans( + metas=[ + _make_meta(tp_rank=0, tp_size=2), + _make_meta(tp_rank=1, tp_size=2), + ] + ) + assert result == [] + + def test_tp_sharded_returns_unsharder_plan(self) -> None: + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans( + metas=[ + _make_meta(dims="b h[tp]", tp_rank=0, tp_size=2), + _make_meta(dims="b h[tp]", tp_rank=1, tp_size=2), + ] + ) + assert len(result) >= 1 + unsharder_plans: list[UnsharderPlan] = [ + p for p in result if isinstance(p, UnsharderPlan) + ] + assert len(unsharder_plans) >= 1 + + def test_zigzag_returns_both_plans(self) -> None: + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans( + metas=[ + _make_meta(dims="b s[cp:zigzag] h", cp_rank=0, cp_size=2), + _make_meta(dims="b s[cp:zigzag] h", cp_rank=1, cp_size=2), + ] + ) + unsharder_plans: list[UnsharderPlan] = [ + p for p in result if isinstance(p, UnsharderPlan) + ] + reorderer_plans: list[ReordererPlan] = [ + p for p in result if isinstance(p, ReordererPlan) + ] + assert len(unsharder_plans) >= 1 + assert len(reorderer_plans) >= 1 + + +class TestComputePerStepPlans: + def test_groups_by_step(self) -> None: + metas: list[dict[str, Any]] = [ + _make_meta(step=0, tp_rank=0, tp_size=2), + _make_meta(step=0, tp_rank=1, tp_size=2), + _make_meta(step=1, tp_rank=0, tp_size=1), + ] + result: list[AlignerPerStepPlan] = _compute_per_step_plans(metas=metas) + + assert len(result) == 2 + assert result[0].step == 0 + assert result[0].input_object_indices == [0, 1] + assert result[1].step == 1 + assert result[1].input_object_indices == [2] + + def test_sorted_by_step(self) -> None: + metas: list[dict[str, Any]] = [ + _make_meta(step=2), + _make_meta(step=0), + _make_meta(step=1), + ] + result: list[AlignerPerStepPlan] = _compute_per_step_plans(metas=metas) + + steps: list[int] = [p.step for p in result] + assert steps == [0, 1, 2] + + def test_single_meta_per_step_empty_sub_plans(self) -> None: + metas: list[dict[str, Any]] = [ + _make_meta(step=0), + _make_meta(step=1), + ] + result: list[AlignerPerStepPlan] = _compute_per_step_plans(metas=metas) + + assert len(result) == 2 + assert all(plan.sub_plans == [] for plan in result) + + +class TestComputeAlignerPlan: + def test_wraps_both_sides(self) -> None: + metas_x: list[dict[str, Any]] = [_make_meta(step=0)] + metas_y: list[dict[str, Any]] = [_make_meta(step=0)] + + plan: AlignerPlan = compute_aligner_plan( + metas_pair=Pair(x=metas_x, y=metas_y), + token_aligner_mode=None, + token_aligner_plan=None, + ) + + assert len(plan.per_step_plans.x) == 1 + assert len(plan.per_step_plans.y) == 1 + assert plan.token_aligner_plan is None + + def test_preserves_token_aligner_plan(self) -> None: + from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( + TokenAlignerPlan, + TokenLocator, + ) + + ta_plan = TokenAlignerPlan( + locators=Pair( + x=TokenLocator(steps=[0], token_index_in_step=[0]), + y=TokenLocator(steps=[0], token_index_in_step=[0]), + ), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.T), + ) + + plan: AlignerPlan = compute_aligner_plan( + metas_pair=Pair(x=[_make_meta()], y=[_make_meta()]), + token_aligner_mode="smart", + token_aligner_plan=ta_plan, + ) + + assert plan.token_aligner_plan is ta_plan + assert plan.token_aligner_mode == "smart" + + +class TestComputePerStepSubPlansThd: + def test_thd_zigzag_returns_thd_plans(self) -> None: + """t[cp:zigzag] h[tp] generates THD-typed unsharder + reorderer plans.""" + thd_global_seq_lens: list[int] = [100, 64, 92] + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans( + metas=[ + _make_meta( + dims="t[cp:zigzag] h[tp]", + cp_rank=0, + cp_size=2, + tp_rank=0, + tp_size=2, + ), + _make_meta( + dims="t[cp:zigzag] h[tp]", + cp_rank=0, + cp_size=2, + tp_rank=1, + tp_size=2, + ), + _make_meta( + dims="t[cp:zigzag] h[tp]", + cp_rank=1, + cp_size=2, + tp_rank=0, + tp_size=2, + ), + _make_meta( + dims="t[cp:zigzag] h[tp]", + cp_rank=1, + cp_size=2, + tp_rank=1, + tp_size=2, + ), + ], + thd_global_seq_lens=thd_global_seq_lens, + ) + + unsharder_plans: list[UnsharderPlan] = [ + p for p in result if isinstance(p, UnsharderPlan) + ] + reorderer_plans: list[ReordererPlan] = [ + p for p in result if isinstance(p, ReordererPlan) + ] + + # Should have at least one THD concat plan for CP axis + thd_concat_plans: list[UnsharderPlan] = [ + p for p in unsharder_plans if isinstance(p.params, CpThdConcatParams) + ] + assert len(thd_concat_plans) == 1 + assert thd_concat_plans[0].params.seq_lens_per_rank == [50, 32, 46] + + # Should have exactly one THD reorder plan + assert len(reorderer_plans) == 1 + assert isinstance(reorderer_plans[0].params, ZigzagToNaturalThdParams) + assert reorderer_plans[0].params.cp_size == 2 + # Reorder seq_lens = global seq_lens (reorder happens after unshard) + assert reorderer_plans[0].params.seq_lens == [100, 64, 92] + + +class TestComputePerStepSubPlansDpFiltered: + """Tests that compute_per_step_sub_plans passes dp_filtered_axis to unsharder, + so DP axes already handled by the upstream DP filter don't cause validation errors. + """ + + def test_dp2_tp2_does_not_raise(self) -> None: + """DP2 + TP2, dims='t h[tp]' → should not raise despite DP being active.""" + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans( + metas=[ + _make_meta( + dims="t h[tp]", + tp_rank=0, + tp_size=2, + extra_parallel_info={"dp_rank": 0, "dp_size": 2}, + ), + _make_meta( + dims="t h[tp]", + tp_rank=1, + tp_size=2, + extra_parallel_info={"dp_rank": 0, "dp_size": 2}, + ), + ] + ) + unsharder_plans: list[UnsharderPlan] = [ + p for p in result if isinstance(p, UnsharderPlan) + ] + assert len(unsharder_plans) == 1 + assert unsharder_plans[0].axis.value == "tp" + + def test_dp2_only_no_sharding_does_not_raise(self) -> None: + """DP2 only, dims='t h' → should not raise, no plans produced.""" + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans( + metas=[ + _make_meta( + dims="t h", + extra_parallel_info={"dp_rank": 0, "dp_size": 2}, + ), + _make_meta( + dims="t h", + extra_parallel_info={"dp_rank": 0, "dp_size": 2}, + ), + ] + ) + assert result == [] + + def test_dp_alias_passes_correct_filtered_axis(self) -> None: + """dims with '# dp:=moe_dp', metas have moe_dp → should not raise.""" + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans( + metas=[ + _make_meta( + dims="t h[tp] # dp:=moe_dp", + tp_rank=0, + tp_size=2, + extra_parallel_info={"moe_dp_rank": 0, "moe_dp_size": 2}, + ), + _make_meta( + dims="t h[tp] # dp:=moe_dp", + tp_rank=1, + tp_size=2, + extra_parallel_info={"moe_dp_rank": 0, "moe_dp_size": 2}, + ), + ] + ) + unsharder_plans: list[UnsharderPlan] = [ + p for p in result if isinstance(p, UnsharderPlan) + ] + assert len(unsharder_plans) == 1 + assert unsharder_plans[0].axis.value == "tp" + + def test_dp2_tp2_cp2_does_not_raise(self) -> None: + """DP2 + TP2 + CP2, dims='s[cp] h[tp]' → should not raise.""" + metas = [] + for cp_rank in range(2): + for tp_rank in range(2): + metas.append( + _make_meta( + dims="s[cp] h[tp]", + tp_rank=tp_rank, + tp_size=2, + cp_rank=cp_rank, + cp_size=2, + extra_parallel_info={"dp_rank": 0, "dp_size": 2}, + ) + ) + result: list[AlignerPerStepSubPlan] = compute_per_step_sub_plans(metas=metas) + unsharder_plans: list[UnsharderPlan] = [ + p for p in result if isinstance(p, UnsharderPlan) + ] + axes = {p.axis.value for p in unsharder_plans} + assert axes == {"cp", "tp"} + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/__init__.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/conftest.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_executor.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..6243a841b35f64d3b7e9cdebfe5fcb2c709d2d97 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_executor.py @@ -0,0 +1,292 @@ +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.reorderer.executor import ( + _reorder_zigzag_to_natural, + _reorder_zigzag_to_natural_thd, + execute_reorderer_plan, +) +from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ( + ReordererPlan, + ZigzagToNaturalThdParams, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.executor import ( + execute_unsharder_plan, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( + CpThdConcatParams, + UnsharderPlan, +) +from sglang.srt.debug_utils.comparator.dims_spec import ( + ParallelAxis, + apply_dim_names, + without_dim_names, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +def _zigzag_order(cp_size: int) -> list[int]: + """Build zigzag interleaving order for 2*cp_size chunks.""" + order: list[int] = [] + num_chunks: int = cp_size * 2 + for i in range(cp_size): + order.append(i) + order.append(num_chunks - 1 - i) + return order + + +def _zigzag_split_seq(seq_natural: torch.Tensor, *, cp_size: int) -> list[torch.Tensor]: + """Split a natural-order seq into per-rank zigzag segments. + + Returns: list of per-rank tensors, where rank_i holds chunks assigned by zigzag. + """ + num_chunks: int = cp_size * 2 + chunks: list[torch.Tensor] = list(seq_natural.chunk(num_chunks, dim=0)) + order: list[int] = _zigzag_order(cp_size) + zigzagged: torch.Tensor = torch.cat([chunks[i] for i in order], dim=0) + return list(zigzagged.chunk(cp_size, dim=0)) + + +class TestZigzagToNatural: + def test_zigzag_to_natural_cp2(self) -> None: + """cp_size=2: zigzag order [0,3,1,2] -> natural [0,1,2,3].""" + natural = torch.arange(24).reshape(4, 6) + chunks = list(natural.chunk(4, dim=0)) + + zigzag_order: list[int] = [0, 3, 1, 2] + zigzagged = torch.cat([chunks[i] for i in zigzag_order], dim=0) + + result = _reorder_zigzag_to_natural(zigzagged, dim=0, cp_size=2) + assert torch.equal(result, natural) + + def test_zigzag_to_natural_cp3(self) -> None: + """cp_size=3: zigzag 162534 -> natural 123456 (1-indexed).""" + natural = torch.arange(60).reshape(6, 10) + chunks = list(natural.chunk(6, dim=0)) + + zigzag_order: list[int] = [0, 5, 1, 4, 2, 3] + zigzagged = torch.cat([chunks[i] for i in zigzag_order], dim=0) + + result = _reorder_zigzag_to_natural(zigzagged, dim=0, cp_size=3) + assert torch.equal(result, natural) + + def test_zigzag_to_natural_arbitrary_dim(self) -> None: + """Reorder along dim=1 instead of dim=0.""" + natural = torch.arange(48).reshape(3, 4, 4) + chunks = list(natural.chunk(4, dim=1)) + + zigzag_order: list[int] = [0, 3, 1, 2] + zigzagged = torch.cat([chunks[i] for i in zigzag_order], dim=1) + + result = _reorder_zigzag_to_natural(zigzagged, dim=1, cp_size=2) + assert torch.equal(result, natural) + + +class TestZigzagToNaturalThd: + def test_single_seq(self) -> None: + """Single seq THD reorder: equivalent to whole-tensor reorder.""" + natural = torch.arange(100) + zigzag_ranks: list[torch.Tensor] = _zigzag_split_seq(natural, cp_size=2) + zigzagged: torch.Tensor = torch.cat(zigzag_ranks, dim=0) + + result = _reorder_zigzag_to_natural_thd( + zigzagged, dim=0, cp_size=2, seq_lens=[100] + ) + assert torch.equal(result, natural) + + def test_multi_seq(self) -> None: + """Two seqs of different lengths, each independently reordered.""" + seq_a_natural = torch.arange(100) + seq_b_natural = torch.arange(100, 164) + + seq_a_zigzag: torch.Tensor = torch.cat( + _zigzag_split_seq(seq_a_natural, cp_size=2), dim=0 + ) + seq_b_zigzag: torch.Tensor = torch.cat( + _zigzag_split_seq(seq_b_natural, cp_size=2), dim=0 + ) + + combined_zigzag: torch.Tensor = torch.cat([seq_a_zigzag, seq_b_zigzag], dim=0) + result = _reorder_zigzag_to_natural_thd( + combined_zigzag, dim=0, cp_size=2, seq_lens=[100, 64] + ) + + expected: torch.Tensor = torch.cat([seq_a_natural, seq_b_natural], dim=0) + assert torch.equal(result, expected) + + def test_with_tail_pad(self) -> None: + """THD reorder with trailing global padding preserved unchanged.""" + seq_natural = torch.arange(100) + pad: torch.Tensor = torch.full((56,), fill_value=-1) + + seq_zigzag: torch.Tensor = torch.cat( + _zigzag_split_seq(seq_natural, cp_size=2), dim=0 + ) + combined: torch.Tensor = torch.cat([seq_zigzag, pad], dim=0) + + result = _reorder_zigzag_to_natural_thd( + combined, dim=0, cp_size=2, seq_lens=[100] + ) + + assert torch.equal(result[:100], seq_natural) + assert torch.equal(result[100:], pad) + + def test_with_hidden_dim(self) -> None: + """THD reorder with trailing hidden dimension (shape [T, H]).""" + torch.manual_seed(42) + hidden: int = 8 + seq_natural = torch.randn(100, hidden) + + seq_zigzag: torch.Tensor = torch.cat( + _zigzag_split_seq(seq_natural, cp_size=2), dim=0 + ) + + result = _reorder_zigzag_to_natural_thd( + seq_zigzag, dim=0, cp_size=2, seq_lens=[100] + ) + assert torch.equal(result, seq_natural) + + def test_with_leading_batch_dim(self) -> None: + """THD reorder with leading batch dim: shape [B, T, H], t is dim=1.""" + torch.manual_seed(42) + batch: int = 2 + hidden: int = 4 + seq_a_natural = torch.randn(batch, 100, hidden) + seq_b_natural = torch.randn(batch, 64, hidden) + full_natural: torch.Tensor = torch.cat([seq_a_natural, seq_b_natural], dim=1) + + # Zigzag each seq along dim=1 + def zigzag_along_dim1(t: torch.Tensor) -> torch.Tensor: + num_chunks: int = 2 * 2 # cp_size=2 + chunks: list[torch.Tensor] = list(t.chunk(num_chunks, dim=1)) + order: list[int] = [0, 3, 1, 2] # zigzag for cp_size=2 + return torch.cat([chunks[i] for i in order], dim=1) + + seq_a_zigzag: torch.Tensor = zigzag_along_dim1(seq_a_natural) + seq_b_zigzag: torch.Tensor = zigzag_along_dim1(seq_b_natural) + combined_zigzag: torch.Tensor = torch.cat([seq_a_zigzag, seq_b_zigzag], dim=1) + + result = _reorder_zigzag_to_natural_thd( + combined_zigzag, dim=1, cp_size=2, seq_lens=[100, 64] + ) + assert torch.equal(result, full_natural) + + +class TestThdCpZigzagE2E: + """End-to-end unshard + reorder tests for THD CP zigzag format. + + Simulates Miles/Megatron forward data splitting: + + cp_size=2, batch with 2 seqs: seqA(100 tokens), seqB(61→pad to 64) + + Forward: + seqA(100): chunk_size=25, 4 chunks → rank0=[chunk0+chunk3](50), rank1=[chunk1+chunk2](50) + seqB(64): chunk_size=16, 4 chunks → rank0=[chunk0+chunk3](32), rank1=[chunk1+chunk2](32) + global pad → align to 128 + rank0: [seqA_r0(50) | seqB_r0(32) | pad(46)] = 128 tokens + rank1: [seqA_r1(50) | seqB_r1(32) | pad(46)] = 128 tokens + global cu_seqlens: [0, 100, 164, 256] + + Comparator undo: + Step 1 THD unshard: per-seq cross-rank concat → [seqA_zigzag(100) | seqB_zigzag(64) | pad(92)] + Step 2 THD reorder: per-seq zigzag→natural → [seqA_natural(100) | seqB_natural(64) | pad(92)] + """ + + def test_thd_cp2_two_seqs(self) -> None: + """cp_size=2, 2 seqs (100, 61→64) + global pad.""" + torch.manual_seed(42) + cp_size: int = 2 + total_per_rank: int = 128 + + seq_a_natural = torch.randn(100) + seq_b_natural_raw = torch.randn(61) + seq_b_padded = torch.cat([seq_b_natural_raw, torch.zeros(3)]) # pad 61→64 + + seq_a_ranks: list[torch.Tensor] = _zigzag_split_seq( + seq_a_natural, cp_size=cp_size + ) + seq_b_ranks: list[torch.Tensor] = _zigzag_split_seq( + seq_b_padded, cp_size=cp_size + ) + + # Build per-rank tensors: [seqA_r | seqB_r | pad_r] + rank_tensors: list[torch.Tensor] = [] + for rank in range(cp_size): + used: int = seq_a_ranks[rank].shape[0] + seq_b_ranks[rank].shape[0] + pad_len: int = total_per_rank - used + rank_tensor: torch.Tensor = apply_dim_names( + torch.cat([seq_a_ranks[rank], seq_b_ranks[rank], torch.zeros(pad_len)]), + ["t"], + ) + rank_tensors.append(rank_tensor) + + # Step 1: THD unshard + seq_lens_per_rank: list[int] = [50, 32, 46] + unshard_plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=seq_lens_per_rank), + groups=[[0, 1]], + ) + unsharder_result = execute_unsharder_plan(unshard_plan, rank_tensors) + unsharded: list[torch.Tensor] = unsharder_result.tensors + assert len(unsharded) == 1 + + # Step 2: THD reorder + reorder_seq_lens: list[int] = [s * cp_size for s in seq_lens_per_rank] + reorder_plan = ReordererPlan( + params=ZigzagToNaturalThdParams( + dim_name="t", cp_size=cp_size, seq_lens=reorder_seq_lens + ) + ) + reordered: list[torch.Tensor] = execute_reorderer_plan(reorder_plan, unsharded) + assert len(reordered) == 1 + + result: torch.Tensor = without_dim_names(reordered[0]) + assert torch.equal(result[:100], seq_a_natural) + assert torch.equal(result[100:164], seq_b_padded) + + def test_thd_cp3_single_seq(self) -> None: + """cp_size=3, single seq (120 tokens).""" + torch.manual_seed(42) + cp_size: int = 3 + seq_natural = torch.randn(120) + + seq_ranks: list[torch.Tensor] = _zigzag_split_seq(seq_natural, cp_size=cp_size) + + rank_tensors: list[torch.Tensor] = [ + apply_dim_names(t, ["t"]) for t in seq_ranks + ] + + # Step 1: THD unshard + seq_len_per_rank: int = 120 // cp_size # 40 + unshard_plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams( + dim_name="t", seq_lens_per_rank=[seq_len_per_rank] + ), + groups=[list(range(cp_size))], + ) + unsharder_result = execute_unsharder_plan(unshard_plan, rank_tensors) + unsharded: list[torch.Tensor] = unsharder_result.tensors + assert len(unsharded) == 1 + + # Step 2: THD reorder + reorder_plan = ReordererPlan( + params=ZigzagToNaturalThdParams( + dim_name="t", cp_size=cp_size, seq_lens=[120] + ) + ) + reordered: list[torch.Tensor] = execute_reorderer_plan(reorder_plan, unsharded) + assert len(reordered) == 1 + + result: torch.Tensor = without_dim_names(reordered[0]) + assert torch.equal(result, seq_natural) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_planner.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..eef1c7f8a44f31368a89fabc839cb77dff18440c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/reorderer/test_planner.py @@ -0,0 +1,259 @@ +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.reorderer.executor import ( + execute_reorderer_plan, +) +from sglang.srt.debug_utils.comparator.aligner.reorderer.planner import ( + compute_reorderer_plans, +) +from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ReordererPlan +from sglang.srt.debug_utils.comparator.aligner.unsharder.executor import ( + execute_unsharder_plan, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.planner import ( + compute_unsharder_plan, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import AxisInfo +from sglang.srt.debug_utils.comparator.dims_spec import ( + DimSpec, + ParallelAxis, + apply_dim_names, + parse_dims, + without_dim_names, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestComputeReordererPlans: + def test_compute_reorderer_plans_zigzag(self) -> None: + """s[cp:zigzag] produces a ReordererPlan.""" + dim_specs = parse_dims("b s[cp:zigzag] h[tp]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + plans = compute_reorderer_plans( + dim_specs=dim_specs, parallel_infos=parallel_infos + ) + + assert len(plans) == 1 + assert plans[0].params.op == "zigzag_to_natural" + assert plans[0].params.dim_name == "s" + assert plans[0].params.cp_size == 2 + + def test_compute_reorderer_plans_thd_zigzag(self) -> None: + """t[cp:zigzag] produces a ZigzagToNaturalThdParams plan.""" + dim_specs = parse_dims("t[cp:zigzag] h[tp]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + thd_global_seq_lens: list[int] = [100, 64, 92] + plans = compute_reorderer_plans( + dim_specs=dim_specs, + parallel_infos=parallel_infos, + thd_global_seq_lens=thd_global_seq_lens, + ) + + assert len(plans) == 1 + assert plans[0].params.op == "zigzag_to_natural_thd" + assert plans[0].params.cp_size == 2 + assert plans[0].params.seq_lens == [100, 64, 92] + + def test_non_seq_dim_still_raises(self) -> None: + """Zigzag on non-sequence/non-token dim (e.g. h[cp:zigzag]) raises ValueError.""" + dim_specs = parse_dims("h[cp:zigzag] d").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + {ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2)}, + ] + with pytest.raises(ValueError, match="only supported on sequence dims"): + compute_reorderer_plans(dim_specs=dim_specs, parallel_infos=parallel_infos) + + def test_thd_zigzag_without_seq_lens_raises(self) -> None: + """t[cp:zigzag] without thd_global_seq_lens raises ValueError.""" + dim_specs = parse_dims("t[cp:zigzag] h[tp]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="thd_global_seq_lens is required"): + compute_reorderer_plans(dim_specs=dim_specs, parallel_infos=parallel_infos) + + def test_thd_natural_no_reorder(self) -> None: + """t[cp:natural] and t[cp] produce no reorder plans.""" + for dims_str in ["t[cp:natural] h[tp]", "t[cp] h[tp]"]: + dim_specs = parse_dims(dims_str).dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + plans = compute_reorderer_plans( + dim_specs=dim_specs, parallel_infos=parallel_infos + ) + assert plans == [] + + def test_compute_reorderer_plans_natural(self) -> None: + """s[cp] and s[cp:natural] produce no reorder plans.""" + for dims_str in ["b s[cp] h[tp]", "b s[cp:natural] h[tp]"]: + dim_specs = parse_dims(dims_str).dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + plans = compute_reorderer_plans( + dim_specs=dim_specs, parallel_infos=parallel_infos + ) + assert plans == [] + + +class TestCpZigzagTpE2E: + def test_cp_zigzag_tp_e2e(self) -> None: + """CP=2 zigzag + TP=2: full pipeline round-trip.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16) + + # Shard: first split seq dim (dim=1) into CP=2 with zigzag ordering, + # then split hidden dim (dim=2) into TP=2. + natural_cp_chunks = list(full_tensor.chunk(4, dim=1)) + zigzag_order: list[int] = [0, 3, 1, 2] + zigzagged = torch.cat([natural_cp_chunks[i] for i in zigzag_order], dim=1) + + cp_chunks = list(zigzagged.chunk(2, dim=1)) + tensors: list[torch.Tensor] = [] + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=2)) + for tp_rank in range(2): + tensors.append(tp_chunks[tp_rank]) + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + dim_specs: list[DimSpec] = parse_dims("b s[cp:zigzag] h[tp]").dims + dim_names: list[str] = [s.name for s in dim_specs] + + unsharder_plans = compute_unsharder_plan( + dim_specs=dim_specs, parallel_infos=parallel_infos + ) + reorderer_plans = compute_reorderer_plans( + dim_specs=dim_specs, parallel_infos=parallel_infos + ) + all_plans = [*unsharder_plans, *reorderer_plans] + + assert len(unsharder_plans) == 2 + assert len(reorderer_plans) == 1 + + current: list[torch.Tensor] = [ + apply_dim_names(t, list(dim_names)) for t in tensors + ] + for plan in all_plans: + if isinstance(plan, ReordererPlan): + current = execute_reorderer_plan(plan, current) + else: + current = execute_unsharder_plan(plan, current).tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + +class TestCpZigzagSpSameDimE2E: + """E2E test for t[cp:zigzag,sp] — two axes sharding the same token dim.""" + + def test_cp2_sp2_zigzag_e2e(self) -> None: + """CP=2 zigzag + SP=2 on same token dim: full unshard + reorder round-trip. + + Shard order (outer to inner, matching left-to-right in dims annotation): + 1. CP zigzag splits token dim into 2 CP chunks (zigzag order) + 2. SP splits each CP chunk into 2 SP chunks + + Unshard order (inner to outer, right-to-left): + 1. SP concat (inner): merge SP chunks back + 2. CP concat (outer): merge CP chunks back + 3. Zigzag reorder: restore natural token order + """ + torch.manual_seed(42) + total_tokens: int = 16 + hidden: int = 8 + full_tensor: torch.Tensor = torch.randn(total_tokens, hidden) + + # Step 1: CP zigzag split — split into 2*cp_size=4 natural chunks, reorder by zigzag + cp_size: int = 2 + sp_size: int = 2 + n_natural_chunks: int = cp_size * 2 + natural_chunks: list[torch.Tensor] = list( + full_tensor.chunk(n_natural_chunks, dim=0) + ) + zigzag_order: list[int] = [0, 3, 1, 2] + zigzagged: torch.Tensor = torch.cat( + [natural_chunks[i] for i in zigzag_order], dim=0 + ) + cp_chunks: list[torch.Tensor] = list(zigzagged.chunk(cp_size, dim=0)) + + # Step 2: SP split within each CP chunk + tensors: list[torch.Tensor] = [] + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(cp_size): + sp_chunks: list[torch.Tensor] = list( + cp_chunks[cp_rank].chunk(sp_size, dim=0) + ) + for sp_rank in range(sp_size): + tensors.append(sp_chunks[sp_rank]) + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=cp_size), + ParallelAxis.SP: AxisInfo(axis_rank=sp_rank, axis_size=sp_size), + } + ) + + dim_specs: list[DimSpec] = parse_dims("t[cp:zigzag,sp] h").dims + dim_names: list[str] = [s.name for s in dim_specs] + + unsharder_plans = compute_unsharder_plan( + dim_specs=dim_specs, parallel_infos=parallel_infos + ) + reorderer_plans = compute_reorderer_plans( + dim_specs=dim_specs, + parallel_infos=parallel_infos, + thd_global_seq_lens=[total_tokens], + ) + all_plans = [*unsharder_plans, *reorderer_plans] + + assert len(unsharder_plans) == 2 # SP concat, CP concat + assert unsharder_plans[0].axis == ParallelAxis.SP + assert unsharder_plans[1].axis == ParallelAxis.CP + assert len(reorderer_plans) == 1 # zigzag reorder + + current: list[torch.Tensor] = [ + apply_dim_names(t, list(dim_names)) for t in tensors + ] + for plan in all_plans: + if isinstance(plan, ReordererPlan): + current = execute_reorderer_plan(plan, current) + else: + current = execute_unsharder_plan(plan, current).tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/test_axis_aligner.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/test_axis_aligner.py new file mode 100644 index 0000000000000000000000000000000000000000..2e065dc7a719c10d17d67c8767b8c7e46476b668 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/test_axis_aligner.py @@ -0,0 +1,555 @@ +import sys +from typing import Optional + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.axis_aligner import ( + AxisAlignerPlan, + compute_axis_aligner_plan, + execute_axis_aligner_plan, +) +from sglang.srt.debug_utils.comparator.dims_spec import ( + apply_dim_names, + without_dim_names, +) +from sglang.srt.debug_utils.comparator.log_sink import log_sink +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestComputeAxisAlignerPlan: + def test_no_dims_returns_none(self) -> None: + assert compute_axis_aligner_plan(Pair(x=None, y=None)) is None + assert compute_axis_aligner_plan(Pair(x="t h d", y=None)) is None + assert compute_axis_aligner_plan(Pair(x=None, y="t h d")) is None + + def test_same_order_returns_none(self) -> None: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t h d", y="t h d") + ) + assert result is None + + def test_different_order(self) -> None: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t h d", y="t d h") + ) + assert result is not None + assert result.pattern.x == "t h d -> t d h" + assert result.pattern.y is None + + def test_name_mismatch_returns_none_with_warning(self) -> None: + with log_sink.context() as warnings: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t h d", y="t h e") + ) + + assert result is None + assert len(warnings) == 1 + assert warnings[0].category == "axis_aligner_dim_mismatch" + assert "dim name sets differ" in warnings[0].message + + def test_modifiers_ignored_for_name_extraction(self) -> None: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t h[tp] d", y="t d h[tp]") + ) + assert result is not None + assert result.pattern.x == "t h d -> t d h" + + def test_squeeze_only_no_swap(self) -> None: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t 1 h", y="t h") + ) + assert result is not None + assert result.pattern.x == "t 1 h -> t h" + assert result.pattern.y is None + + def test_squeeze_both_sides(self) -> None: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t 1 h", y="1 t h") + ) + assert result is not None + assert result.pattern.x == "t 1 h -> t h" + assert result.pattern.y == "1 t h -> t h" + + def test_squeeze_plus_swap(self) -> None: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t 1 h d", y="t d h") + ) + assert result is not None + assert result.pattern.x == "t 1 h d -> t d h" + assert result.pattern.y is None + + def test_squeeze_y_only(self) -> None: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t h", y="t 1 h") + ) + assert result is not None + assert result.pattern.x is None + assert result.pattern.y == "t 1 h -> t h" + + def test_multiple_squeeze_one_side(self) -> None: + """Two squeeze dims on x, none on y.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="1 t 1 h", y="t h") + ) + assert result is not None + assert result.pattern.x == "1 t 1 h -> t h" + assert result.pattern.y is None + + def test_multiple_squeeze_asymmetric(self) -> None: + """Different numbers of squeeze dims on each side.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="1 t 1 h", y="1 t h") + ) + assert result is not None + assert result.pattern.x == "1 t 1 h -> t h" + assert result.pattern.y == "1 t h -> t h" + + def test_four_dim_full_reversal(self) -> None: + """4-dim permutation: full reversal.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="a b c d", y="d c b a") + ) + assert result is not None + assert result.pattern.x == "a b c d -> d c b a" + assert result.pattern.y is None + + +class TestComputeAxisAlignerPlanFused: + def test_fused_vs_separate(self) -> None: + """x=fused 2D, y=separate 3D: y flattens to match x's fused form.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t (num_heads*head_dim)[tp]", y="t num_heads[tp] head_dim") + ) + assert result is not None + assert result.pattern.x is None + assert result.pattern.y == "t num_heads head_dim -> t (num_heads head_dim)" + + def test_separate_vs_fused(self) -> None: + """x=separate 3D, y=fused 2D: x flattens to match y's fused form.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t num_heads[tp] head_dim", y="t (num_heads*head_dim)[tp]") + ) + assert result is not None + assert result.pattern.x == "t num_heads head_dim -> t (num_heads head_dim)" + assert result.pattern.y is None + + def test_both_fused_same_no_plan(self) -> None: + """Both sides fused, same order → None (no-op).""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t (a*b)", y="t (a*b)") + ) + assert result is None + + def test_fused_name_mismatch_returns_none(self) -> None: + """Fused vs separate with mismatched names → None.""" + with log_sink.context() as warnings: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t (a*b)", y="t c d") + ) + assert result is None + assert len(warnings) == 1 + + def test_partial_fused_and_regular(self) -> None: + """x has "(a*b) c", y has "a b c": y flattens a,b to match x's fused form.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="(a*b) c", y="a b c") + ) + assert result is not None + assert result.pattern.x is None + assert result.pattern.y == "a b c -> (a b) c" + + def test_fused_vs_reordered_separate(self) -> None: + """x=fused "(a*b) c", y=reordered separate "b a c": y flattens+reorders.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="(a*b) c", y="b a c") + ) + assert result is not None + assert result.pattern.x is None + assert result.pattern.y == "b a c -> (a b) c" + + def test_fused_reorder_both_sides(self) -> None: + """x=fused "c (a*b)", y=separate "a b c": x reorders fused, y flattens.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="c (a*b)", y="a b c") + ) + assert result is not None + assert result.pattern.x == "c a___b -> a___b c" + assert result.pattern.y == "a b c -> (a b) c" + + def test_fused_with_squeeze(self) -> None: + """Fused + squeeze on one side, separate on other.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t 1 (a*b)", y="t a b") + ) + assert result is not None + assert result.pattern.x == "t 1 a___b -> t a___b" + assert result.pattern.y == "t a b -> t (a b)" + + def test_three_way_fused_vs_separate(self) -> None: + """3-way fused on x, separate on y.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t (a*b*c)", y="t a b c") + ) + assert result is not None + assert result.pattern.x is None + assert result.pattern.y == "t a b c -> t (a b c)" + + def test_separate_vs_three_way_fused(self) -> None: + """Separate on x, 3-way fused on y.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t a b c", y="t (a*b*c)") + ) + assert result is not None + assert result.pattern.x == "t a b c -> t (a b c)" + assert result.pattern.y is None + + def test_both_fused_different_order(self) -> None: + """Both sides fused same group but dims in different order.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="c (a*b)", y="(a*b) c") + ) + assert result is not None + assert result.pattern.x == "c a___b -> a___b c" + assert result.pattern.y is None + + def test_overlapping_fused_groups_returns_none(self) -> None: + """x fuses (a*b), y fuses (b*c): incompatible overlap → None with warning.""" + with log_sink.context() as warnings: + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="(a*b) c", y="a (b*c)") + ) + assert result is None + assert len(warnings) == 1 + assert warnings[0].category == "axis_aligner_fused_conflict" + assert "overlapping fused groups" in warnings[0].message + + +class TestExecuteAxisAlignerPlan: + def test_rearrange(self) -> None: + torch.manual_seed(42) + tensor: torch.Tensor = apply_dim_names(torch.randn(4, 8, 16), ["t", "h", "d"]) + plan = AxisAlignerPlan(pattern=Pair(x="t h d -> t d h", y=None)) + + result: torch.Tensor = execute_axis_aligner_plan( + tensor=tensor, plan=plan, side="x" + ) + + assert result.shape == (4, 16, 8) + for i in range(4): + assert torch.equal(result[i], without_dim_names(tensor)[i].T) + + def test_execute_squeeze(self) -> None: + torch.manual_seed(42) + tensor: torch.Tensor = apply_dim_names( + torch.randn(4, 1, 8), ["t", "singleton0", "h"] + ) + plan = AxisAlignerPlan(pattern=Pair(x="t 1 h -> t h", y=None)) + + result: torch.Tensor = execute_axis_aligner_plan( + tensor=tensor, plan=plan, side="x" + ) + + assert result.shape == (4, 8) + + def test_execute_squeeze_then_swap(self) -> None: + torch.manual_seed(42) + tensor: torch.Tensor = apply_dim_names( + torch.randn(4, 1, 8, 16), ["t", "singleton0", "h", "d"] + ) + plan = AxisAlignerPlan(pattern=Pair(x="t 1 h d -> t d h", y=None)) + + result: torch.Tensor = execute_axis_aligner_plan( + tensor=tensor, plan=plan, side="x" + ) + + assert result.shape == (4, 16, 8) + + def test_execute_y_side(self) -> None: + torch.manual_seed(42) + tensor: torch.Tensor = apply_dim_names( + torch.randn(4, 1, 8), ["t", "singleton0", "h"] + ) + plan = AxisAlignerPlan(pattern=Pair(x=None, y="t 1 h -> t h")) + + result: torch.Tensor = execute_axis_aligner_plan( + tensor=tensor, plan=plan, side="y" + ) + + assert result.shape == (4, 8) + + def test_noop_side(self) -> None: + torch.manual_seed(42) + tensor: torch.Tensor = apply_dim_names(torch.randn(4, 8, 16), ["t", "h", "d"]) + plan = AxisAlignerPlan(pattern=Pair(x="t h d -> t d h", y=None)) + + result: torch.Tensor = execute_axis_aligner_plan( + tensor=tensor, plan=plan, side="y" + ) + + assert result.shape == (4, 8, 16) + + def test_invalid_side_raises(self) -> None: + """Invalid side value should raise ValueError.""" + torch.manual_seed(42) + tensor: torch.Tensor = torch.randn(4, 8, 16) + plan = AxisAlignerPlan(pattern=Pair(x="t h d -> t d h", y=None)) + + with pytest.raises(ValueError, match="side must be"): + execute_axis_aligner_plan(tensor=tensor, plan=plan, side="z") + + +class TestExecuteAxisAlignerPlanFlatten: + def test_flatten_separate_to_match_fused(self) -> None: + """3D (t=4, nh=8, hd=16) → 2D (t=4, nh*hd=128) via einops flatten.""" + torch.manual_seed(42) + tensor_3d: torch.Tensor = torch.randn(4, 8, 16) + plan = AxisAlignerPlan( + pattern=Pair(x=None, y="t nh hd -> t (nh hd)"), + ) + + result: torch.Tensor = execute_axis_aligner_plan( + tensor=tensor_3d, plan=plan, side="y" + ) + + assert result.shape == (4, 128) + assert torch.equal(result, tensor_3d.reshape(4, 128)) + + def test_flatten_preserves_data(self) -> None: + """Flatten should be equivalent to reshape — verify element equality.""" + torch.manual_seed(42) + tensor: torch.Tensor = torch.randn(2, 3, 4, 5) + plan = AxisAlignerPlan( + pattern=Pair(x="a b c d -> a (b c) d", y=None), + ) + + result: torch.Tensor = execute_axis_aligner_plan( + tensor=tensor, plan=plan, side="x" + ) + + assert result.shape == (2, 12, 5) + assert torch.equal(result, tensor.reshape(2, 12, 5)) + + def test_flatten_then_rearrange(self) -> None: + """Flatten + reorder in a single einops pattern.""" + torch.manual_seed(42) + tensor: torch.Tensor = torch.randn(4, 8, 16, 32) + plan = AxisAlignerPlan( + pattern=Pair(x="t a b d -> t d (a b)", y=None), + ) + + result: torch.Tensor = execute_axis_aligner_plan( + tensor=tensor, plan=plan, side="x" + ) + + assert result.shape == (4, 32, 128) + + +class TestEndToEndFusedAlignment: + def test_fused_vs_separate_full_pipeline(self) -> None: + """Full pipeline: x=fused 2D "t nh*hd", y=separate 3D "t nh hd".""" + torch.manual_seed(42) + num_heads: int = 8 + head_dim: int = 16 + + x_tensor: torch.Tensor = torch.randn(4, num_heads * head_dim) + y_tensor: torch.Tensor = x_tensor.reshape(4, num_heads, head_dim) + + plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t (num_heads*head_dim)", y="t num_heads head_dim") + ) + assert plan is not None + + y_aligned: torch.Tensor = execute_axis_aligner_plan( + tensor=y_tensor, plan=plan, side="y" + ) + + assert y_aligned.shape == x_tensor.shape + assert torch.equal(y_aligned, x_tensor) + + def test_separate_vs_fused_full_pipeline(self) -> None: + """Full pipeline: x=separate 3D "t nh hd", y=fused 2D "t nh*hd".""" + torch.manual_seed(42) + num_heads: int = 8 + head_dim: int = 16 + + x_tensor: torch.Tensor = torch.randn(4, num_heads, head_dim) + y_tensor: torch.Tensor = x_tensor.reshape(4, num_heads * head_dim) + + plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t num_heads head_dim", y="t (num_heads*head_dim)") + ) + assert plan is not None + + x_aligned: torch.Tensor = execute_axis_aligner_plan( + tensor=x_tensor, plan=plan, side="x" + ) + + assert x_aligned.shape == y_tensor.shape + assert torch.equal(x_aligned, y_tensor) + + def test_fused_with_reorder(self) -> None: + """Fused x + reordered separate y: both need alignment.""" + torch.manual_seed(42) + a_size: int = 3 + b_size: int = 5 + + # x: fused "c a*b" shape (7, 15) + x_tensor: torch.Tensor = torch.randn(7, a_size * b_size) + # y: separate "a b c" shape (3, 5, 7) + y_tensor: torch.Tensor = x_tensor.reshape(7, a_size, b_size).permute(1, 2, 0) + + plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="c (a*b)", y="a b c") + ) + assert plan is not None + + x_aligned: torch.Tensor = execute_axis_aligner_plan( + tensor=x_tensor, plan=plan, side="x" + ) + y_aligned: torch.Tensor = execute_axis_aligner_plan( + tensor=y_tensor, plan=plan, side="y" + ) + + assert x_aligned.shape == y_aligned.shape + assert torch.allclose(x_aligned, y_aligned) + + +class TestEndToEndThreeWayFused: + def test_three_way_fused_vs_separate(self) -> None: + """Full pipeline: x=3-way fused "t (a*b*c)", y=separate "t a b c".""" + torch.manual_seed(42) + a_size, b_size, c_size = 2, 3, 4 + + x_tensor: torch.Tensor = torch.randn(5, a_size * b_size * c_size) + y_tensor: torch.Tensor = x_tensor.reshape(5, a_size, b_size, c_size) + + plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t (a*b*c)", y="t a b c") + ) + assert plan is not None + + y_aligned: torch.Tensor = execute_axis_aligner_plan( + tensor=y_tensor, plan=plan, side="y" + ) + + assert y_aligned.shape == x_tensor.shape + assert torch.equal(y_aligned, x_tensor) + + +class TestSeqTokenEquivalencePlan: + """Tests for s≡t dimension name equivalence in compute_axis_aligner_plan.""" + + def test_s_t_equivalence_squeeze(self) -> None: + """sglang 't h' vs megatron 's 1 h': plan squeezes y-side singleton, x-side no-op.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t h", y="s 1 h") + ) + assert result is not None + assert result.pattern.x is None + assert result.pattern.y == "s 1 h -> s h" + + def test_s_t_equivalence_same_shape(self) -> None: + """'t h d' vs 's h d': same order after normalization → no plan needed.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t h d", y="s h d") + ) + assert result is None + + def test_s_t_equivalence_with_swap(self) -> None: + """'t d h' vs 's h d': plan not None, x-pattern reorders.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t d h", y="s h d") + ) + assert result is not None + assert result.pattern.x is not None + + def test_s_t_equivalence_with_fused(self) -> None: + """'t (a*b)' vs 's a b': plan not None, y-pattern flattens.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t (a*b)", y="s a b") + ) + assert result is not None + assert result.pattern.y is not None + + def test_s_t_equivalence_with_squeeze_and_fused(self) -> None: + """'t (num_heads*head_dim)' vs 's 1 num_heads head_dim': plan squeezes + flattens.""" + result: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t (num_heads*head_dim)", y="s 1 num_heads head_dim") + ) + assert result is not None + + +class TestSeqTokenEquivalenceExecute: + """Tests for s≡t dimension name equivalence in execute_axis_aligner_plan.""" + + def test_execute_s_t_squeeze(self) -> None: + """Tensor [4,1,8] with pattern 's 1 h -> s h' → shape [4,8].""" + torch.manual_seed(42) + tensor: torch.Tensor = torch.randn(4, 1, 8) + plan = AxisAlignerPlan(pattern=Pair(x=None, y="s 1 h -> s h")) + + result: torch.Tensor = execute_axis_aligner_plan( + tensor=tensor, plan=plan, side="y" + ) + + assert result.shape == (4, 8) + assert torch.equal(result, tensor.squeeze(1)) + + +class TestEndToEndSeqTokenEquivalence: + """End-to-end tests for s≡t equivalence through compute + execute pipeline.""" + + def test_s_t_squeeze_full_pipeline(self) -> None: + """x=tensor(4,8) dims='t h', y=tensor(4,1,8) dims='s 1 h' → both aligned to (4,8).""" + torch.manual_seed(42) + data: torch.Tensor = torch.randn(4, 8) + x_tensor: torch.Tensor = data.clone() + y_tensor: torch.Tensor = data.unsqueeze(1) + + plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t h", y="s 1 h") + ) + assert plan is not None + + x_aligned: torch.Tensor = execute_axis_aligner_plan( + tensor=x_tensor, plan=plan, side="x" + ) + y_aligned: torch.Tensor = execute_axis_aligner_plan( + tensor=y_tensor, plan=plan, side="y" + ) + + assert x_aligned.shape == y_aligned.shape == (4, 8) + assert torch.equal(x_aligned, y_aligned) + + def test_s_t_fused_full_pipeline(self) -> None: + """x=tensor(4,128) dims='t (nh*hd)', y=tensor(4,1,8,16) dims='s 1 nh hd' → both (4,128).""" + torch.manual_seed(42) + num_heads: int = 8 + head_dim: int = 16 + data: torch.Tensor = torch.randn(4, num_heads * head_dim) + x_tensor: torch.Tensor = data.clone() + y_tensor: torch.Tensor = data.reshape(4, num_heads, head_dim).unsqueeze(1) + + plan: Optional[AxisAlignerPlan] = compute_axis_aligner_plan( + Pair(x="t (nh*hd)", y="s 1 nh hd") + ) + assert plan is not None + + x_aligned: torch.Tensor = execute_axis_aligner_plan( + tensor=x_tensor, plan=plan, side="x" + ) + y_aligned: torch.Tensor = execute_axis_aligner_plan( + tensor=y_tensor, plan=plan, side="y" + ) + + assert x_aligned.shape == y_aligned.shape == (4, num_heads * head_dim) + assert torch.equal(x_aligned, y_aligned) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/__init__.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/conftest.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_loader.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..e71c7c1d469b4a2d09ddf2271c4add70707f908d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_loader.py @@ -0,0 +1,388 @@ +import sys +from pathlib import Path + +import polars as pl +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_loader import ( + _detect_plugin, + _ensure_dims_in_metas, + _load_and_align_aux_tensor, + _load_non_tensor_aux, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_plugins import ( + _MegatronPlugin, + _SGLangPlugin, +) +from sglang.srt.debug_utils.comparator.log_sink import LogSink +from sglang.srt.debug_utils.comparator.output_types import ErrorLog, InfoLog +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) + +_sglang_plugin = _SGLangPlugin() +_megatron_plugin = _MegatronPlugin() + + +def _save_pt( + dump_path: Path, + *, + name: str, + step: int, + rank: int, + value: object, + meta: dict | None = None, +) -> str: + filename: str = f"name={name}___step={step}___rank={rank}.pt" + payload: dict = {"value": value, "meta": meta or {}} + torch.save(payload, dump_path / filename) + return filename + + +def _make_df_from_filenames(filenames: list[str]) -> pl.DataFrame: + rows: list[dict] = [] + for fn in filenames: + parts: dict = {} + stem: str = fn.removesuffix(".pt") + for kv in stem.split("___"): + if "=" in kv: + k, v = kv.split("=", 1) + parts[k] = v + rows.append( + { + "filename": fn, + "name": parts["name"], + "step": int(parts["step"]), + "rank": int(parts["rank"]), + } + ) + return pl.DataFrame(rows) + + +class TestEnsureDimsInMetas: + """Tests for _ensure_dims_in_metas.""" + + def _make_meta(self, *, cp_size: int = 1, cp_rank: int = 0) -> dict: + return { + "sglang_parallel_info": { + "tp_rank": 0, + "tp_size": 1, + "cp_rank": cp_rank, + "cp_size": cp_size, + } + } + + def test_no_cp_returns_metas_unchanged(self): + """Without CP parallelism, metas are returned as-is.""" + metas: list[dict] = [self._make_meta(cp_size=1)] + result = _ensure_dims_in_metas( + name="input_ids", plugin=_sglang_plugin, metas=metas, ndim=1 + ) + assert result is metas + + def test_dims_already_present_returns_metas_unchanged(self): + """If dims is already in meta, metas are returned as-is.""" + metas: list[dict] = [{**self._make_meta(cp_size=2, cp_rank=0), "dims": "t"}] + result = _ensure_dims_in_metas( + name="input_ids", plugin=_sglang_plugin, metas=metas, ndim=1 + ) + assert result is metas + + def test_cp_sharded_sglang_input_ids_infers_dims(self): + """CP + input_ids in sglang infers dims 't[cp:zigzag]'.""" + metas: list[dict] = [ + self._make_meta(cp_size=2, cp_rank=0), + self._make_meta(cp_size=2, cp_rank=1), + ] + result = _ensure_dims_in_metas( + name="input_ids", plugin=_sglang_plugin, metas=metas, ndim=1 + ) + assert result is not metas + assert result[0]["dims"] == "t[cp:zigzag]" + assert result[1]["dims"] == "t[cp:zigzag]" + + def test_cp_sharded_sglang_positions_infers_dims(self): + """CP + positions in sglang infers dims 't[cp:zigzag]'.""" + metas: list[dict] = [ + self._make_meta(cp_size=2, cp_rank=0), + self._make_meta(cp_size=2, cp_rank=1), + ] + result = _ensure_dims_in_metas( + name="positions", plugin=_sglang_plugin, metas=metas, ndim=1 + ) + assert result[0]["dims"] == "t[cp:zigzag]" + + def test_cp_sharded_megatron_input_ids_infers_dims_1d(self): + """CP + input_ids in megatron (1D) infers dims 't[cp:zigzag]'.""" + metas: list[dict] = [ + {"megatron_parallel_info": {"cp_rank": 0, "cp_size": 2}}, + {"megatron_parallel_info": {"cp_rank": 1, "cp_size": 2}}, + ] + result = _ensure_dims_in_metas( + name="input_ids", plugin=_megatron_plugin, metas=metas, ndim=1 + ) + assert result[0]["dims"] == "t[cp:zigzag]" + + def test_cp_sharded_megatron_input_ids_infers_dims_2d(self): + """CP + input_ids in megatron (2D) infers dims 'b s[cp:zigzag]'.""" + metas: list[dict] = [ + {"megatron_parallel_info": {"cp_rank": 0, "cp_size": 2}}, + {"megatron_parallel_info": {"cp_rank": 1, "cp_size": 2}}, + ] + result = _ensure_dims_in_metas( + name="input_ids", plugin=_megatron_plugin, metas=metas, ndim=2 + ) + assert result[0]["dims"] == "b s[cp:zigzag]" + + def test_cp_non_sharded_name_returns_metas_unchanged(self): + """CP + non-sharded tensor name (seq_lens) returns metas as-is.""" + metas: list[dict] = [ + self._make_meta(cp_size=2, cp_rank=0), + self._make_meta(cp_size=2, cp_rank=1), + ] + result = _ensure_dims_in_metas( + name="seq_lens", plugin=_sglang_plugin, metas=metas, ndim=1 + ) + assert result is metas + + def test_unknown_plugin_returns_metas_unchanged(self): + """CP + plugin with empty cp_sharded_names returns metas as-is.""" + + class _DummyPlugin(_SGLangPlugin): + @property + def cp_sharded_names(self) -> frozenset[str]: + return frozenset() + + metas: list[dict] = [ + self._make_meta(cp_size=2, cp_rank=0), + self._make_meta(cp_size=2, cp_rank=1), + ] + result = _ensure_dims_in_metas( + name="input_ids", plugin=_DummyPlugin(), metas=metas, ndim=1 + ) + assert result is metas + + +class TestDetectPlugin: + def test_discriminating_names_sglang(self, tmp_path: Path) -> None: + fn: str = _save_pt( + tmp_path, name="seq_lens", step=0, rank=0, value=torch.tensor([3]) + ) + df: pl.DataFrame = _make_df_from_filenames([fn]) + + result = _detect_plugin(df, dump_path=tmp_path) + + assert result is not None + assert result.name == "sglang" + + def test_fallback_to_meta_based_detection(self, tmp_path: Path) -> None: + fn: str = _save_pt( + tmp_path, + name="input_ids", + step=0, + rank=0, + value=torch.tensor([1, 2, 3]), + meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}}, + ) + df: pl.DataFrame = _make_df_from_filenames([fn]) + + result = _detect_plugin(df, dump_path=tmp_path) + + assert result is not None + assert result.name == "sglang" + + def test_returns_none_no_match(self, tmp_path: Path) -> None: + fn: str = _save_pt( + tmp_path, name="unrelated_tensor", step=0, rank=0, value=torch.tensor([1]) + ) + df: pl.DataFrame = _make_df_from_filenames([fn]) + + result = _detect_plugin(df, dump_path=tmp_path) + + assert result is None + + +class TestLoadNonTensorAux: + def test_multi_rank_mismatch_warning(self, tmp_path: Path) -> None: + fn0: str = _save_pt(tmp_path, name="rids", step=0, rank=0, value=["req_A"]) + fn1: str = _save_pt(tmp_path, name="rids", step=0, rank=1, value=["req_B"]) + df: pl.DataFrame = _make_df_from_filenames([fn0, fn1]) + + sink = LogSink() + with sink.context() as warnings: + from unittest.mock import patch + + with patch( + "sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_loader.log_sink", + sink, + ): + result = _load_non_tensor_aux( + name="rids", step=0, df=df, dump_path=tmp_path + ) + + assert result == ["req_A"] + assert len(warnings) == 1 + assert isinstance(warnings[0], ErrorLog) + assert "rids_mismatch" in warnings[0].category + + def test_no_rows_returns_none(self, tmp_path: Path) -> None: + df: pl.DataFrame = _make_df_from_filenames([]) + + result = _load_non_tensor_aux(name="rids", step=0, df=df, dump_path=tmp_path) + + assert result is None + + +class TestLoadAndAlignAuxTensor: + def test_multi_rank_no_dims_emits_warning(self, tmp_path: Path) -> None: + fn0: str = _save_pt( + tmp_path, + name="input_ids", + step=0, + rank=0, + value=torch.tensor([1, 2, 3]), + meta={ + "sglang_parallel_info": { + "tp_rank": 0, + "tp_size": 2, + "cp_rank": 0, + "cp_size": 1, + } + }, + ) + fn1: str = _save_pt( + tmp_path, + name="input_ids", + step=0, + rank=1, + value=torch.tensor([4, 5, 6]), + meta={ + "sglang_parallel_info": { + "tp_rank": 1, + "tp_size": 2, + "cp_rank": 0, + "cp_size": 1, + } + }, + ) + df: pl.DataFrame = _make_df_from_filenames([fn0, fn1]) + + sink = LogSink() + with sink.context() as warnings: + from unittest.mock import patch + + with patch( + "sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_loader.log_sink", + sink, + ): + result = _load_and_align_aux_tensor( + name="input_ids", + step=0, + df=df, + dump_path=tmp_path, + plugin=_sglang_plugin, + ) + + assert result is not None + assert torch.equal(result, torch.tensor([1, 2, 3])) + assert len(warnings) == 1 + assert isinstance(warnings[0], InfoLog) + assert "aux_no_dims" in warnings[0].category + + +class TestLoadNonTensorAuxDp: + """DP filtering in _load_non_tensor_aux.""" + + def test_dp2_non_tensor_returns_value(self, tmp_path: Path) -> None: + """DP=2 non-tensor aux: both ranks have same value, filter keeps all (non-tensor).""" + fn0: str = _save_pt( + tmp_path, + name="rids", + step=0, + rank=0, + value=["req_A"], + meta={ + "sglang_parallel_info": { + "dp_rank": 0, + "dp_size": 2, + } + }, + ) + fn1: str = _save_pt( + tmp_path, + name="rids", + step=0, + rank=1, + value=["req_A"], + meta={ + "sglang_parallel_info": { + "dp_rank": 1, + "dp_size": 2, + } + }, + ) + df: pl.DataFrame = _make_df_from_filenames([fn0, fn1]) + + sink = LogSink() + with sink.context(): + from unittest.mock import patch + + with patch( + "sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_loader.log_sink", + sink, + ): + result = _load_non_tensor_aux( + name="rids", step=0, df=df, dump_path=tmp_path + ) + + assert result == ["req_A"] + + +class TestLoadAndAlignAuxTensorDp: + """DP filtering in _load_and_align_aux_tensor.""" + + def test_dp2_tensor_one_empty(self, tmp_path: Path) -> None: + """DP=2 tensor aux: rank 0 has data, rank 1 empty -> returns rank 0 tensor.""" + fn0: str = _save_pt( + tmp_path, + name="input_ids", + step=0, + rank=0, + value=torch.tensor([10, 20, 30]), + meta={ + "sglang_parallel_info": { + "dp_rank": 0, + "dp_size": 2, + } + }, + ) + fn1: str = _save_pt( + tmp_path, + name="input_ids", + step=0, + rank=1, + value=torch.tensor([]), + meta={ + "sglang_parallel_info": { + "dp_rank": 1, + "dp_size": 2, + } + }, + ) + df: pl.DataFrame = _make_df_from_filenames([fn0, fn1]) + + result = _load_and_align_aux_tensor( + name="input_ids", + step=0, + df=df, + dump_path=tmp_path, + plugin=_sglang_plugin, + ) + + assert result is not None + assert torch.equal(result, torch.tensor([10, 20, 30])) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_plugins.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..7c6d2fd2c65d026a350fac47bcf45e73b1728302 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_aux_plugins.py @@ -0,0 +1,248 @@ +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_plugins import ( + _infer_positions, + _MegatronPlugin, + _SGLangPlugin, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( + PositionalSeqId, + SGLangSeqId, + TokenAlignerStepAux, +) +from sglang.srt.debug_utils.comparator.dims_spec import TokenLayout +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + +_sglang_plugin = _SGLangPlugin() +_megatron_plugin = _MegatronPlugin() + + +class TestNormalizeSGLang: + """Tests for SGLang aux tensor normalization.""" + + def test_with_rids(self): + """SGLang tensors with rids produce string seq_ids.""" + step_data: dict = { + "input_ids": torch.tensor([10, 20, 30]), + "positions": torch.tensor([0, 1, 2]), + "seq_lens": torch.tensor([3]), + "rids": ["A"], + } + + result: TokenAlignerStepAux = _sglang_plugin.compute_step_aux( + step_data, layout=TokenLayout.T, step=0 + ) + + assert result.input_ids == [10, 20, 30] + assert result.positions == [0, 1, 2] + assert result.seq_lens == [3] + assert result.seq_ids == [SGLangSeqId(rid="A")] + + def test_rids_none_fallback(self): + """Missing rids results in (step, index) fallback seq_ids.""" + step_data: dict = { + "input_ids": torch.tensor([10, 20]), + "positions": torch.tensor([0, 1]), + "seq_lens": torch.tensor([2]), + } + + result: TokenAlignerStepAux = _sglang_plugin.compute_step_aux( + step_data, layout=TokenLayout.T, step=3 + ) + assert result.seq_ids == [PositionalSeqId(step=3, seq_index=0)] + + def test_multiple_seqs_with_rids(self): + """Multiple sequences with rids.""" + step_data: dict = { + "input_ids": torch.tensor([10, 20, 30, 40, 50]), + "positions": torch.tensor([0, 1, 2, 0, 1]), + "seq_lens": torch.tensor([3, 2]), + "rids": ["A", "B"], + } + + result: TokenAlignerStepAux = _sglang_plugin.compute_step_aux( + step_data, layout=TokenLayout.T, step=0 + ) + assert result.seq_ids == [SGLangSeqId(rid="A"), SGLangSeqId(rid="B")] + + +class TestNormalizeMegatron: + """Tests for Megatron aux tensor normalization.""" + + def test_cu_seqlens_to_seq_lens(self): + """cu_seqlens_q is converted to seq_lens via differencing.""" + step_data: dict = { + "input_ids": torch.tensor([10, 20, 30, 40, 50]), + "cu_seqlens_q": torch.tensor([0, 3, 5]), + } + + result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux( + step_data, layout=TokenLayout.T, step=0 + ) + + assert result.seq_lens == [3, 2] + + def test_positions_inferred_thd(self): + """Positions inferred from seq_lens in thd layout.""" + step_data: dict = { + "input_ids": torch.tensor([10, 20, 30, 40, 50]), + "cu_seqlens_q": torch.tensor([0, 3, 5]), + } + + result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux( + step_data, layout=TokenLayout.T, step=0 + ) + + assert result.positions == [0, 1, 2, 0, 1] + + def test_position_ids_passthrough(self): + """Explicit position_ids used directly instead of inference.""" + step_data: dict = { + "input_ids": torch.tensor([10, 20, 30, 40, 50]), + "position_ids": torch.tensor([5, 6, 7, 8, 9]), + "cu_seqlens_q": torch.tensor([0, 5]), + } + + result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux( + step_data, layout=TokenLayout.T, step=0 + ) + + assert result.positions == [5, 6, 7, 8, 9] + + def test_seq_ids_are_step_index_tuples(self): + """Megatron seq_ids are (step, seq_index) tuples.""" + step_data: dict = { + "input_ids": torch.tensor([10, 20, 30, 40, 50]), + "cu_seqlens_q": torch.tensor([0, 3, 5]), + } + + result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux( + step_data, layout=TokenLayout.T, step=5 + ) + assert result.seq_ids == [ + PositionalSeqId(step=5, seq_index=0), + PositionalSeqId(step=5, seq_index=1), + ] + + +class TestDetectLayoutMegatron: + """Tests for Megatron layout detection.""" + + def test_detect_layout_bshd_via_qkv_format(self): + """qkv_format containing 'bshd' → layout 'bshd'.""" + raw: dict[int, dict[str, object]] = { + 0: {"qkv_format": "bshd", "input_ids": torch.tensor([1, 2, 3])} + } + assert _megatron_plugin.detect_layout(raw) == TokenLayout.BS + + def test_detect_layout_bshd_via_ndim(self): + """2D input_ids → layout BS.""" + raw: dict[int, dict[str, object]] = { + 0: {"input_ids": torch.tensor([[1, 2], [3, 4]])} + } + assert _megatron_plugin.detect_layout(raw) == TokenLayout.BS + + def test_detect_layout_thd_via_qkv_format(self): + """qkv_format 'thd' → layout T.""" + raw: dict[int, dict[str, object]] = { + 0: {"qkv_format": "thd", "input_ids": torch.tensor([1, 2, 3])} + } + assert _megatron_plugin.detect_layout(raw) == TokenLayout.T + + +class TestNormalizeMegatronBSHD: + """Tests for Megatron BSHD normalization.""" + + def test_basic_bshd(self): + """2D input_ids [2,4] → flat [8], seq_lens=[4,4], positions=[0,1,2,3,0,1,2,3].""" + step_data: dict = { + "input_ids": torch.tensor([[10, 20, 30, 40], [50, 60, 70, 80]]), + } + + result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux( + step_data, layout=TokenLayout.BS, step=0 + ) + + assert result.input_ids == [10, 20, 30, 40, 50, 60, 70, 80] + assert result.seq_lens == [4, 4] + assert result.positions == [0, 1, 2, 3, 0, 1, 2, 3] + assert result.seq_ids == [ + PositionalSeqId(step=0, seq_index=0), + PositionalSeqId(step=0, seq_index=1), + ] + + def test_bshd_with_cu_seqlens(self): + """BSHD with cu_seqlens_q → uses cu_seqlens for seq_lens.""" + step_data: dict = { + "input_ids": torch.tensor([[10, 20, 30, 40], [50, 60, 70, 80]]), + "cu_seqlens_q": torch.tensor([0, 3, 8]), + } + + result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux( + step_data, layout=TokenLayout.BS, step=0 + ) + + assert result.seq_lens == [3, 5] + + def test_bshd_with_position_ids(self): + """BSHD with 2D position_ids → flattened positions.""" + step_data: dict = { + "input_ids": torch.tensor([[10, 20], [30, 40]]), + "position_ids": torch.tensor([[5, 6], [10, 11]]), + } + + result: TokenAlignerStepAux = _megatron_plugin.compute_step_aux( + step_data, layout=TokenLayout.BS, step=0 + ) + + assert result.positions == [5, 6, 10, 11] + + +class TestInferPositions: + """Tests for position inference helper.""" + + def test_thd_multiple_sequences(self): + """thd: positions reset to 0 for each sequence.""" + result = _infer_positions( + seq_lens=torch.tensor([2, 3]), + ) + assert torch.equal(result, torch.tensor([0, 1, 0, 1, 2])) + + +class TestInferCpShardedDims: + """Tests for infer_cp_sharded_dims on each plugin.""" + + def test_megatron_infer_1d(self) -> None: + """Megatron 1D → 't[cp:zigzag]'.""" + result: str = _megatron_plugin.infer_cp_sharded_dims(name="input_ids", ndim=1) + assert result == "t[cp:zigzag]" + + def test_megatron_infer_2d(self) -> None: + """Megatron 2D → 'b s[cp:zigzag]'.""" + result: str = _megatron_plugin.infer_cp_sharded_dims(name="input_ids", ndim=2) + assert result == "b s[cp:zigzag]" + + def test_sglang_infer_1d(self) -> None: + """SGLang 1D → 't[cp:zigzag]'.""" + result: str = _sglang_plugin.infer_cp_sharded_dims(name="input_ids", ndim=1) + assert result == "t[cp:zigzag]" + + def test_megatron_infer_3d_raises(self) -> None: + """Megatron 3D raises ValueError.""" + with pytest.raises(ValueError, match="cannot infer dims"): + _megatron_plugin.infer_cp_sharded_dims(name="input_ids", ndim=3) + + def test_sglang_infer_2d_raises(self) -> None: + """SGLang 2D raises ValueError.""" + with pytest.raises(ValueError, match="cannot infer dims"): + _sglang_plugin.infer_cp_sharded_dims(name="input_ids", ndim=2) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_concat_steps.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_concat_steps.py new file mode 100644 index 0000000000000000000000000000000000000000..345e92ba52e9eb71b2c19a060b36d6e577cb21a3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_concat_steps.py @@ -0,0 +1,86 @@ +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.token_aligner.concat_steps import ( + execute_token_aligner_concat_steps, +) +from sglang.srt.debug_utils.comparator.dims_spec import apply_dim_names +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestExecuteConcat: + def test_single_step_equal_length(self) -> None: + x = torch.tensor([1.0, 2.0, 3.0]) + y = torch.tensor([4.0, 5.0, 6.0]) + result: Pair[torch.Tensor] = execute_token_aligner_concat_steps( + tensor_of_step_pair=Pair(x={0: x}, y={0: y}), + ) + assert torch.equal(result.x, x) + assert torch.equal(result.y, y) + + def test_truncates_to_min(self) -> None: + x = torch.tensor([1.0, 2.0, 3.0, 4.0]) + y = torch.tensor([5.0, 6.0]) + result: Pair[torch.Tensor] = execute_token_aligner_concat_steps( + tensor_of_step_pair=Pair(x={0: x}, y={0: y}), + ) + assert torch.equal(result.x, torch.tensor([1.0, 2.0])) + assert torch.equal(result.y, y) + + def test_multi_step_sorted_concat(self) -> None: + result: Pair[torch.Tensor] = execute_token_aligner_concat_steps( + tensor_of_step_pair=Pair( + x={1: torch.tensor([3.0, 4.0]), 0: torch.tensor([1.0, 2.0])}, + y={0: torch.tensor([5.0, 6.0, 7.0, 8.0])}, + ), + ) + assert torch.equal(result.x, torch.tensor([1.0, 2.0, 3.0, 4.0])) + assert torch.equal(result.y, torch.tensor([5.0, 6.0, 7.0, 8.0])) + + def test_named_token_dim_nonzero(self) -> None: + """Token dim at dim=1 (not dim=0) — concat and truncate along correct dim.""" + # shape [2, 3, 4]: dim0=batch, dim1=token, dim2=hidden + x_step0 = apply_dim_names(torch.randn(2, 3, 4), ["b", "t", "h"]) + x_step1 = apply_dim_names(torch.randn(2, 5, 4), ["b", "t", "h"]) + y_step0 = apply_dim_names(torch.randn(2, 6, 4), ["b", "t", "h"]) + + result: Pair[torch.Tensor] = execute_token_aligner_concat_steps( + tensor_of_step_pair=Pair( + x={0: x_step0, 1: x_step1}, + y={0: y_step0}, + ), + ) + + # x: 3+5=8 tokens; y: 6 tokens → truncate to 6 + assert result.x.shape == (2, 6, 4) + assert result.y.shape == (2, 6, 4) + + def test_named_dims_no_token_dim_fallback(self) -> None: + """Named dims without t or s → fallback to dim 0.""" + x = apply_dim_names(torch.randn(4, 8), ["b", "h"]) + y = apply_dim_names(torch.randn(3, 8), ["b", "h"]) + result: Pair[torch.Tensor] = execute_token_aligner_concat_steps( + tensor_of_step_pair=Pair(x={0: x}, y={0: y}), + ) + assert result.x.shape == (3, 8) + assert result.y.shape == (3, 8) + + def test_seq_dim_fallback(self) -> None: + """Named dims with s but no t → uses s as token dim.""" + x = apply_dim_names(torch.randn(2, 5, 4), ["b", "s", "h"]) + y = apply_dim_names(torch.randn(2, 3, 4), ["b", "s", "h"]) + result: Pair[torch.Tensor] = execute_token_aligner_concat_steps( + tensor_of_step_pair=Pair(x={0: x}, y={0: y}), + ) + assert result.x.shape == (2, 3, 4) + assert result.y.shape == (2, 3, 4) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_executor.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..c2f28aadefa5378e4ddc084202e04fd6a902ebf1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_executor.py @@ -0,0 +1,459 @@ +from __future__ import annotations + +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.executor import ( + execute_token_aligner, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.planner import ( + compute_token_aligner_plan, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.seq_info_builder import ( + build_seqs_info, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( + SGLangSeqId, + TokenAlignerGlobalAux, + TokenAlignerPlan, + TokenAlignerStepAux, + TokenLocator, +) +from sglang.srt.debug_utils.comparator.dims_spec import ( + TokenLayout, + apply_dim_names, + without_dim_names, +) +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +def _named(tensor: torch.Tensor, names: list[str]) -> torch.Tensor: + return apply_dim_names(tensor, names) + + +class TestExecuteAlignment: + """Tests for token alignment execution.""" + + def test_thd_vs_thd_identity(self): + """Two identical thd sides produce element-wise equal aligned tensors.""" + torch.manual_seed(42) + hidden_step0 = apply_dim_names(torch.randn(5, 8), ["t", "h"]) + hidden_step1 = apply_dim_names(torch.randn(2, 8), ["t", "h"]) + + aux = TokenAlignerStepAux( + input_ids=[10, 20, 30, 40, 50], + positions=[0, 1, 2, 0, 1], + seq_lens=[3, 2], + seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")], + ) + aux_step1 = TokenAlignerStepAux( + input_ids=[31, 51], + positions=[3, 2], + seq_lens=[1, 1], + seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")], + ) + + side_aux = TokenAlignerGlobalAux( + step_auxs={0: aux, 1: aux_step1}, + framework="sglang", + layout=TokenLayout.T, + ) + + index = build_seqs_info(side_aux) + plan = compute_token_aligner_plan(seqs_info_pair=Pair(x=index, y=index)) + + tensors = {0: hidden_step0, 1: hidden_step1} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, tensor_of_step_pair=Pair(x=tensors, y=tensors) + ) + + assert torch.equal(aligned.x, aligned.y) + assert aligned.x.shape[0] == len(plan.locators.x.steps) + + def test_zero_matched_tokens(self): + """Empty TokenAlignerPlan (no matched tokens) returns shape[0]==0 without crash.""" + torch.manual_seed(42) + + plan = TokenAlignerPlan( + locators=Pair( + x=TokenLocator(steps=[], token_index_in_step=[]), + y=TokenLocator(steps=[], token_index_in_step=[]), + ), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.T), + ) + + tensors = {0: apply_dim_names(torch.randn(5, 8), ["t", "h"])} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, tensor_of_step_pair=Pair(x=tensors, y=tensors) + ) + + assert aligned.x.shape[0] == 0 + assert aligned.y.shape[0] == 0 + assert aligned.x.shape[1:] == (8,) + assert aligned.y.shape[1:] == (8,) + + +class TestTokenDim: + """Tests for non-zero token_dim support.""" + + def _make_simple_plan(self, *, num_tokens: int) -> TokenAlignerPlan: + locator = TokenLocator( + steps=[0] * num_tokens, + token_index_in_step=list(range(num_tokens)), + ) + return TokenAlignerPlan( + locators=Pair(x=locator, y=locator), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.T), + ) + + def test_token_dim_nonzero(self) -> None: + """tensor shape [3, 5, 8], token_dim=1 -> token dim stays at dim 1.""" + torch.manual_seed(42) + tensor: torch.Tensor = _named(torch.randn(3, 5, 8), ["a", "t", "h"]) + plan: TokenAlignerPlan = self._make_simple_plan(num_tokens=5) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (3, 5, 8) + assert torch.equal(aligned.x, aligned.y) + plain: torch.Tensor = without_dim_names(tensor) + for i in range(5): + assert torch.equal( + aligned.x.select(dim=1, index=i), plain.select(dim=1, index=i) + ) + + def test_token_dim_last(self) -> None: + """tensor shape [3, 8, 5], token_dim=2 -> token dim stays at dim 2.""" + torch.manual_seed(42) + tensor: torch.Tensor = _named(torch.randn(3, 8, 5), ["a", "h", "t"]) + plan: TokenAlignerPlan = self._make_simple_plan(num_tokens=5) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (3, 8, 5) + plain: torch.Tensor = without_dim_names(tensor) + for i in range(5): + assert torch.equal( + aligned.x.select(dim=2, index=i), plain.select(dim=2, index=i) + ) + + def test_token_dim_zero(self) -> None: + """token_dim=0 selects along first dimension (standard t-h-d layout).""" + torch.manual_seed(42) + tensor: torch.Tensor = _named(torch.randn(5, 8), ["t", "h"]) + plan: TokenAlignerPlan = self._make_simple_plan(num_tokens=5) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (5, 8) + plain: torch.Tensor = without_dim_names(tensor) + for i in range(5): + assert torch.equal(aligned.x[i], plain.select(dim=0, index=i)) + + def test_zero_matched_tokens_nonzero_token_dim(self) -> None: + """Empty plan with token_dim=1 produces correct empty shape.""" + torch.manual_seed(42) + + plan = TokenAlignerPlan( + locators=Pair( + x=TokenLocator(steps=[], token_index_in_step=[]), + y=TokenLocator(steps=[], token_index_in_step=[]), + ), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.T), + ) + + tensors: dict[int, torch.Tensor] = { + 0: _named(torch.randn(3, 5, 8), ["a", "t", "h"]) + } + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + # token dim (dim 1) set to 0, other dims preserved -> [3, 0, 8] + assert aligned.x.shape == (3, 0, 8) + assert aligned.y.shape == (3, 0, 8) + + def test_high_rank_tensor(self) -> None: + """tensor shape [2, 3, 5, 4, 8] (a b t c d), token_dim=2 -> stays at dim 2.""" + torch.manual_seed(42) + tensor: torch.Tensor = _named( + torch.randn(2, 3, 5, 4, 8), ["a", "x", "t", "c", "h"] + ) + plan: TokenAlignerPlan = self._make_simple_plan(num_tokens=5) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (2, 3, 5, 4, 8) + plain: torch.Tensor = without_dim_names(tensor) + for i in range(5): + assert torch.equal( + aligned.x.select(dim=2, index=i), plain.select(dim=2, index=i) + ) + + +class TestBSHDExecutor: + """BSHD tensor collapse: B+S dims -> flat token dim for alignment.""" + + def test_bshd_standard_bs_at_front(self): + """Standard "b s h d": B=dim0, S=dim1. [2, 3, 4, 5] -> collapse -> [6, 4, 5].""" + torch.manual_seed(42) + tensor: torch.Tensor = _named(torch.randn(2, 3, 4, 5), ["b", "s", "h", "d"]) + flat: torch.Tensor = tensor.reshape(6, 4, 5) + + locator = TokenLocator( + steps=[0, 0, 0], + token_index_in_step=[0, 3, 5], + ) + plan = TokenAlignerPlan( + locators=Pair(x=locator, y=locator), + layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS), + ) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (3, 4, 5) + assert torch.equal(aligned.x[0], flat[0]) + assert torch.equal(aligned.x[1], flat[3]) + assert torch.equal(aligned.x[2], flat[5]) + + def test_bshd_3d_bs_at_front(self): + """Minimal 3D "b s h": B=dim0, S=dim1. [2, 3, 4] -> collapse -> [6, 4].""" + torch.manual_seed(42) + tensor: torch.Tensor = _named(torch.randn(2, 3, 4), ["b", "s", "h"]) + flat: torch.Tensor = tensor.reshape(6, 4) + + locator = TokenLocator( + steps=[0, 0, 0, 0], + token_index_in_step=[0, 2, 3, 5], + ) + plan = TokenAlignerPlan( + locators=Pair(x=locator, y=locator), + layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS), + ) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (4, 4) + assert torch.equal(aligned.x[0], flat[0]) + assert torch.equal(aligned.x[1], flat[2]) + assert torch.equal(aligned.x[2], flat[3]) + assert torch.equal(aligned.x[3], flat[5]) + + def test_bshd_bs_not_at_front(self): + """Non-leading "h b s d": B=dim1, S=dim2. [4, 2, 3, 5] -> collapse -> [4, 6, 5].""" + torch.manual_seed(42) + tensor: torch.Tensor = _named(torch.randn(4, 2, 3, 5), ["h", "b", "s", "d"]) + flat: torch.Tensor = tensor.reshape(4, 6, 5) + + locator = TokenLocator( + steps=[0, 0, 0], + token_index_in_step=[0, 3, 5], + ) + plan = TokenAlignerPlan( + locators=Pair(x=locator, y=locator), + layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS), + ) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (4, 3, 5) + for idx, flat_idx in enumerate([0, 3, 5]): + assert torch.equal( + aligned.x.select(dim=1, index=idx), + flat.select(dim=1, index=flat_idx), + ) + + def test_bshd_expert_before_bs(self): + """Expert dim before B: "e b s h d". [2, 3, 4, 5, 6] -> collapse -> [2, 12, 5, 6].""" + torch.manual_seed(42) + tensor: torch.Tensor = _named( + torch.randn(2, 3, 4, 5, 6), ["e", "b", "s", "h", "d"] + ) + flat: torch.Tensor = tensor.reshape(2, 12, 5, 6) + + locator = TokenLocator( + steps=[0, 0, 0], + token_index_in_step=[0, 5, 11], + ) + plan = TokenAlignerPlan( + locators=Pair(x=locator, y=locator), + layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS), + ) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (2, 3, 5, 6) + for idx, flat_idx in enumerate([0, 5, 11]): + assert torch.equal( + aligned.x.select(dim=1, index=idx), + flat.select(dim=1, index=flat_idx), + ) + + def test_bshd_bs_at_end(self): + """B and S at end: "h d b s". [4, 5, 2, 3] -> collapse -> [4, 5, 6].""" + torch.manual_seed(42) + tensor: torch.Tensor = _named(torch.randn(4, 5, 2, 3), ["h", "d", "b", "s"]) + flat: torch.Tensor = tensor.reshape(4, 5, 6) + + locator = TokenLocator( + steps=[0, 0, 0], + token_index_in_step=[1, 3, 5], + ) + plan = TokenAlignerPlan( + locators=Pair(x=locator, y=locator), + layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS), + ) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (4, 5, 3) + for idx, flat_idx in enumerate([1, 3, 5]): + assert torch.equal( + aligned.x.select(dim=2, index=idx), + flat.select(dim=2, index=flat_idx), + ) + + def test_cross_layout_thd_vs_bshd(self): + """Cross-layout: x=THD [6, 8], y=BSHD [2, 3, 8] -> y collapse -> [6, 8].""" + torch.manual_seed(42) + tensor_thd: torch.Tensor = _named(torch.randn(6, 8), ["t", "h"]) + tensor_bshd: torch.Tensor = _named(torch.randn(2, 3, 8), ["b", "s", "h"]) + flat_bshd: torch.Tensor = tensor_bshd.reshape(6, 8) + + locator = TokenLocator( + steps=[0, 0, 0], + token_index_in_step=[0, 2, 5], + ) + plan = TokenAlignerPlan( + locators=Pair(x=locator, y=locator), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.BS), + ) + + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x={0: tensor_thd}, y={0: tensor_bshd}), + ) + + assert aligned.x.shape == (3, 8) + assert aligned.y.shape == (3, 8) + assert torch.equal(aligned.x[0], tensor_thd[0]) + assert torch.equal(aligned.y[0], flat_bshd[0]) + assert torch.equal(aligned.y[2], flat_bshd[5]) + + def test_bshd_reversed_sb_order(self): + """Reversed "s b h": S=dim0, B=dim1. Collapse is batch-major: (b s).""" + torch.manual_seed(42) + tensor: torch.Tensor = _named(torch.randn(3, 2, 4), ["s", "b", "h"]) + # batch-major flatten: rearrange("s b h -> (b s) h") + from einops import rearrange + + flat: torch.Tensor = rearrange(tensor, "s b h -> (b s) h") + + locator = TokenLocator( + steps=[0, 0, 0], + token_index_in_step=[0, 2, 5], + ) + plan = TokenAlignerPlan( + locators=Pair(x=locator, y=locator), + layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS), + ) + + tensors: dict[int, torch.Tensor] = {0: tensor} + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (3, 4) + assert torch.equal(aligned.x[0], flat[0]) + assert torch.equal(aligned.x[1], flat[2]) + assert torch.equal(aligned.x[2], flat[5]) + + def test_bshd_empty_plan_bs_not_at_front(self): + """Empty plan with non-leading B,S: "h b s d". [4, 2, 3, 5] -> collapse -> [4, 0, 5].""" + plan = TokenAlignerPlan( + locators=Pair( + x=TokenLocator(steps=[], token_index_in_step=[]), + y=TokenLocator(steps=[], token_index_in_step=[]), + ), + layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS), + ) + + tensors: dict[int, torch.Tensor] = { + 0: _named(torch.randn(4, 2, 3, 5), ["h", "b", "s", "d"]) + } + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (4, 0, 5) + assert aligned.y.shape == (4, 0, 5) + + def test_bshd_empty_plan_bs_at_front(self): + """Empty plan with standard BSHD: "b s h". [2, 3, 4] -> collapse -> [0, 4].""" + plan = TokenAlignerPlan( + locators=Pair( + x=TokenLocator(steps=[], token_index_in_step=[]), + y=TokenLocator(steps=[], token_index_in_step=[]), + ), + layouts=Pair(x=TokenLayout.BS, y=TokenLayout.BS), + ) + + tensors: dict[int, torch.Tensor] = { + 0: _named(torch.randn(2, 3, 4), ["b", "s", "h"]) + } + aligned: Pair[torch.Tensor] = execute_token_aligner( + plan=plan, + tensor_of_step_pair=Pair(x=tensors, y=tensors), + ) + + assert aligned.x.shape == (0, 4) + assert aligned.y.shape == (0, 4) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_planner.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..6bc4c2196403b8daadbade70f97398b57e1ec8de --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_planner.py @@ -0,0 +1,575 @@ +import sys + +import pytest + +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.planner import ( + _match_sequences, + compute_token_aligner_plan, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.seq_info_builder import ( + build_seqs_info, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( + PositionalSeqId, + SeqId, + SGLangSeqId, + TokenAlignerGlobalAux, + TokenAlignerSeqInfo, + TokenAlignerSeqsInfo, + TokenAlignerStepAux, + TokenLocator, +) +from sglang.srt.debug_utils.comparator.dims_spec import TokenLayout +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=30, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestBuildTokenIndexSGLangThd: + """Tests for SGLang thd token index building.""" + + def test_single_step_prefill(self): + """Single prefill step with two sequences.""" + side_aux = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30, 40, 50], + positions=[0, 1, 2, 0, 1], + seq_lens=[3, 2], + seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")], + ), + }, + framework="sglang", + layout=TokenLayout.T, + ) + + index = build_seqs_info(side_aux) + assert len(index.sequences) == 2 + + seq_a = index.sequences[SGLangSeqId(rid="A")] + assert seq_a.input_ids == [10, 20, 30] + assert seq_a.positions == [0, 1, 2] + assert seq_a.locator.steps == [0, 0, 0] + assert seq_a.locator.token_index_in_step == [0, 1, 2] + + seq_b = index.sequences[SGLangSeqId(rid="B")] + assert seq_b.input_ids == [40, 50] + assert seq_b.positions == [0, 1] + assert seq_b.locator.token_index_in_step == [3, 4] + + def test_multi_step_prefill_decode(self): + """Prefill step followed by decode steps, sequences accumulate tokens.""" + side_aux = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30, 40, 50], + positions=[0, 1, 2, 0, 1], + seq_lens=[3, 2], + seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")], + ), + 1: TokenAlignerStepAux( + input_ids=[31, 51], + positions=[3, 2], + seq_lens=[1, 1], + seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")], + ), + }, + framework="sglang", + layout=TokenLayout.T, + ) + + index = build_seqs_info(side_aux) + assert len(index.sequences) == 2 + + seq_a = index.sequences[SGLangSeqId(rid="A")] + assert seq_a.input_ids == [10, 20, 30, 31] + assert seq_a.positions == [0, 1, 2, 3] + assert seq_a.locator.steps == [0, 0, 0, 1] + + seq_b = index.sequences[SGLangSeqId(rid="B")] + assert seq_b.input_ids == [40, 50, 51] + assert seq_b.positions == [0, 1, 2] + + def test_sequence_exit_and_join(self): + """Sequence A exits, new sequence D joins with different seq_id.""" + side_aux = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30], + positions=[0, 1, 2], + seq_lens=[3], + seq_ids=[SGLangSeqId(rid="A")], + ), + 1: TokenAlignerStepAux( + input_ids=[100, 200], + positions=[0, 1], + seq_lens=[2], + seq_ids=[SGLangSeqId(rid="D")], + ), + }, + framework="sglang", + layout=TokenLayout.T, + ) + + index = build_seqs_info(side_aux) + assert len(index.sequences) == 2 + + def test_different_seq_ids_produce_separate_sequences(self): + """Different seq_ids at different steps → separate sequences.""" + side_aux = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20], + positions=[0, 1], + seq_lens=[2], + seq_ids=[SGLangSeqId(rid="A")], + ), + 1: TokenAlignerStepAux( + input_ids=[100, 200, 300], + positions=[0, 1, 2], + seq_lens=[3], + seq_ids=[SGLangSeqId(rid="D")], + ), + }, + framework="sglang", + layout=TokenLayout.T, + ) + + index = build_seqs_info(side_aux) + assert len(index.sequences) == 2 + + all_input_ids = { + seq_id: rec.input_ids for seq_id, rec in index.sequences.items() + } + assert [10, 20] in all_input_ids.values() + assert [100, 200, 300] in all_input_ids.values() + + +class TestBuildTokenIndexMegatronThd: + """Tests for Megatron thd token index building.""" + + def test_single_step_two_sequences(self): + """Single step with two sequences in thd layout.""" + side_aux = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30, 40, 50], + positions=[0, 1, 2, 0, 1], + seq_lens=[3, 2], + seq_ids=[ + PositionalSeqId(step=0, seq_index=0), + PositionalSeqId(step=0, seq_index=1), + ], + ), + }, + framework="megatron", + layout=TokenLayout.T, + ) + + index = build_seqs_info(side_aux) + assert len(index.sequences) == 2 + + seq0 = index.sequences[PositionalSeqId(step=0, seq_index=0)] + assert seq0.input_ids == [10, 20, 30] + assert seq0.positions == [0, 1, 2] + assert seq0.locator.steps == [0, 0, 0] + assert seq0.locator.token_index_in_step == [0, 1, 2] + + seq1 = index.sequences[PositionalSeqId(step=0, seq_index=1)] + assert seq1.input_ids == [40, 50] + assert seq1.positions == [0, 1] + assert seq1.locator.token_index_in_step == [3, 4] + + def test_multi_step_accumulation(self): + """Two steps with different seq_ids produce separate sequences.""" + side_aux = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30, 40], + positions=[0, 1, 0, 1], + seq_lens=[2, 2], + seq_ids=[ + PositionalSeqId(step=0, seq_index=0), + PositionalSeqId(step=0, seq_index=1), + ], + ), + 1: TokenAlignerStepAux( + input_ids=[50, 60, 70, 80], + positions=[0, 1, 0, 1], + seq_lens=[2, 2], + seq_ids=[ + PositionalSeqId(step=1, seq_index=0), + PositionalSeqId(step=1, seq_index=1), + ], + ), + }, + framework="megatron", + layout=TokenLayout.T, + ) + + index = build_seqs_info(side_aux) + assert len(index.sequences) == 4 + + seq0 = index.sequences[PositionalSeqId(step=0, seq_index=0)] + assert seq0.input_ids == [10, 20] + assert seq0.locator.steps == [0, 0] + + seq2 = index.sequences[PositionalSeqId(step=1, seq_index=0)] + assert seq2.input_ids == [50, 60] + assert seq2.locator.steps == [1, 1] + + +class TestMatchSequences: + """Tests for _match_sequences: for each y, find matching x.""" + + def test_exact_match_simple(self): + """Identical input_ids on both sides → all matched.""" + matched = _match_seqs( + x={0: (10, 20, 30), 1: (40, 50)}, + y={0: (10, 20, 30), 1: (40, 50)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(0), S(0)), (S(1), S(1))} + + def test_exact_match_different_order(self): + """Sequences in different order still match by content.""" + matched = _match_seqs( + x={0: (10, 20), 1: (40, 50)}, + y={0: (40, 50), 1: (10, 20)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(1), S(0)), (S(0), S(1))} + + def test_exact_match_different_seq_ids(self): + """Seq IDs don't need to correspond — matching is by content.""" + matched = _match_seqs( + x={5: (10, 20), 9: (30, 40)}, + y={2: (30, 40), 7: (10, 20)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(9), S(2)), (S(5), S(7))} + + def test_no_match(self): + """Completely different input_ids → no matches.""" + matched = _match_seqs( + x={0: (10, 20)}, + y={0: (99, 88)}, + ) + assert matched == [] + + def test_empty_sides(self): + """Empty x or y → no matches.""" + assert _match_seqs(x={}, y={0: (10,)}) == [] + assert _match_seqs(x={0: (10,)}, y={}) == [] + assert _match_seqs(x={}, y={}) == [] + + def test_x_has_more_sequences(self): + """Extra x sequences are ignored (no y needs them).""" + matched = _match_seqs( + x={0: (10, 20), 1: (30, 40), 2: (50, 60)}, + y={0: (30, 40)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(1), S(0))} + + def test_y_has_more_sequences(self): + """Extra y sequences remain unmatched.""" + matched = _match_seqs( + x={0: (10, 20)}, + y={0: (10, 20), 1: (30, 40), 2: (50, 60)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(0), S(0))} + + def test_one_x_not_reused(self): + """Each x can only be claimed once, even if multiple y want it.""" + matched = _match_seqs( + x={0: (10, 20)}, + y={0: (10, 20), 1: (10, 20)}, + ) + assert len(matched) == 1 + + def test_ambiguous_all_matched(self): + """Multiple identical sequences on both sides → all paired (greedy 1:1).""" + matched = _match_seqs( + x={0: (10, 20), 1: (10, 20), 2: (10, 20)}, + y={0: (10, 20), 1: (10, 20), 2: (10, 20)}, + ) + S = _int_to_seq_id + assert len(matched) == 3 + x_ids = {m[0] for m in matched} + y_ids = {m[1] for m in matched} + assert x_ids == {S(0), S(1), S(2)} + assert y_ids == {S(0), S(1), S(2)} + + def test_prefix_x_shorter(self): + """x has fewer tokens (prefix of y) → prefix match.""" + matched = _match_seqs( + x={0: (10, 20)}, + y={0: (10, 20, 30)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(0), S(0))} + + def test_prefix_y_shorter(self): + """y has fewer tokens (prefix of x) → prefix match.""" + matched = _match_seqs( + x={0: (10, 20, 30)}, + y={0: (10, 20)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(0), S(0))} + + def test_prefix_picks_longest(self): + """Among multiple prefix candidates, picks the one with longest overlap.""" + matched = _match_seqs( + x={0: (10,), 1: (10, 20, 30)}, + y={0: (10, 20, 30, 40)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(1), S(0))} + + def test_exact_preferred_over_prefix(self): + """Exact match is tried first, even if a longer prefix candidate exists.""" + matched = _match_seqs( + x={0: (10, 20), 1: (10, 20, 30)}, + y={0: (10, 20)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(0), S(0))} + + def test_prefix_fallback_after_exact(self): + """Exact matches consume sequences, remaining use prefix match.""" + matched = _match_seqs( + x={0: (10, 20, 30), 1: (40, 50)}, + y={0: (10, 20, 30), 1: (40, 50, 60)}, + ) + S = _int_to_seq_id + assert len(matched) == 2 + matched_set = _matched_ids(matched) + assert (S(0), S(0)) in matched_set + assert (S(1), S(1)) in matched_set + + def test_single_token_sequences(self): + """Single-token sequences can match.""" + matched = _match_seqs( + x={0: (42,)}, + y={0: (42,)}, + ) + S = _int_to_seq_id + assert _matched_ids(matched) == {(S(0), S(0))} + + def test_no_partial_overlap_without_prefix(self): + """Overlapping content that isn't a prefix → no match.""" + matched = _match_seqs( + x={0: (10, 20, 30)}, + y={0: (20, 30, 40)}, + ) + assert matched == [] + + +class TestComputeAlignmentPlanCrossFramework: + """Tests for alignment plan across different frameworks and layouts.""" + + def test_thd_vs_thd_different_step_splits(self): + """Two thd sides with same tokens but different step distributions.""" + side_aux_a = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20], + positions=[0, 1], + seq_lens=[2], + seq_ids=[SGLangSeqId(rid="X")], + ), + 1: TokenAlignerStepAux( + input_ids=[30], + positions=[2], + seq_lens=[1], + seq_ids=[SGLangSeqId(rid="X")], + ), + }, + framework="sglang", + layout=TokenLayout.T, + ) + side_aux_b = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30], + positions=[0, 1, 2], + seq_lens=[3], + seq_ids=[SGLangSeqId(rid="X")], + ), + }, + framework="sglang", + layout=TokenLayout.T, + ) + + index_a = build_seqs_info(side_aux_a) + index_b = build_seqs_info(side_aux_b) + + plan = compute_token_aligner_plan(seqs_info_pair=Pair(x=index_a, y=index_b)) + assert len(plan.locators.x.steps) == 3 + + def test_sglang_vs_megatron_thd(self): + """SGLang multi-step thd aligned with Megatron single-step thd.""" + side_aux_a = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30, 40, 50], + positions=[0, 1, 2, 0, 1], + seq_lens=[3, 2], + seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")], + ), + 1: TokenAlignerStepAux( + input_ids=[31, 51], + positions=[3, 2], + seq_lens=[1, 1], + seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")], + ), + }, + framework="sglang", + layout=TokenLayout.T, + ) + side_aux_b = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30, 31, 40, 50, 51], + positions=[0, 1, 2, 3, 0, 1, 2], + seq_lens=[4, 3], + seq_ids=[ + PositionalSeqId(step=0, seq_index=0), + PositionalSeqId(step=0, seq_index=1), + ], + ), + }, + framework="megatron", + layout=TokenLayout.T, + ) + + index_a = build_seqs_info(side_aux_a) + index_b = build_seqs_info(side_aux_b) + + plan = compute_token_aligner_plan(seqs_info_pair=Pair(x=index_a, y=index_b)) + + assert len(plan.locators.x.steps) == 7 + + def test_cross_layout_sglang_thd_vs_megatron_bshd(self): + """SGLang THD vs Megatron BSHD end-to-end alignment via planner. + + SGLang side: two sequences [10,20,30] and [40,50] across 2 steps. + Megatron BSHD side: same tokens as 2 batch slots [10,20,30,PAD] and [40,50,PAD,PAD], + where PAD tokens (99) are included because BSHD treats whole padded row as one seq. + Planner should match by prefix and align the common 5 tokens. + """ + side_sglang = TokenAlignerGlobalAux( + step_auxs={ + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30, 40, 50], + positions=[0, 1, 2, 0, 1], + seq_lens=[3, 2], + seq_ids=[SGLangSeqId(rid="A"), SGLangSeqId(rid="B")], + ), + }, + framework="sglang", + layout=TokenLayout.T, + ) + + side_megatron_bshd = TokenAlignerGlobalAux( + step_auxs={ + # BSHD normalized: flat [B*S] with each batch slot as one seq + 0: TokenAlignerStepAux( + input_ids=[10, 20, 30, 99, 40, 50, 99, 99], + positions=[0, 1, 2, 3, 0, 1, 2, 3], + seq_lens=[4, 4], + seq_ids=[ + PositionalSeqId(step=0, seq_index=0), + PositionalSeqId(step=0, seq_index=1), + ], + ), + }, + framework="megatron", + layout=TokenLayout.BS, + ) + + index_sglang = build_seqs_info(side_sglang) + index_megatron = build_seqs_info(side_megatron_bshd) + + plan = compute_token_aligner_plan( + seqs_info_pair=Pair(x=index_sglang, y=index_megatron) + ) + + # Seq A: [10,20,30] matches prefix of [10,20,30,99] → 3 tokens + # Seq B: [40,50] matches prefix of [40,50,99,99] → 2 tokens + assert len(plan.locators.x.steps) == 5 + assert plan.layouts.x == TokenLayout.T + assert plan.layouts.y == TokenLayout.BS + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _int_to_seq_id(k: int) -> SeqId: + """Convert an int key to a SeqId for test convenience.""" + return SGLangSeqId(rid=str(k)) + + +def _make_index( + *, + sequences: dict[int, tuple[int, ...]], + layout: TokenLayout = TokenLayout.T, +) -> TokenAlignerSeqsInfo: + """Create a TokenAlignerSeqsInfo from simplified input_ids-only specification.""" + records: dict[SeqId, TokenAlignerSeqInfo] = {} + for k, input_ids in sequences.items(): + num_tokens = len(input_ids) + records[_int_to_seq_id(k)] = TokenAlignerSeqInfo( + input_ids=list(input_ids), + positions=list(range(num_tokens)), + locator=TokenLocator( + steps=[0] * num_tokens, + token_index_in_step=list(range(num_tokens)), + ), + ) + return TokenAlignerSeqsInfo(sequences=records, layout=layout) + + +def _make_seq_info_dict( + sequences: dict[int, tuple[int, ...]], +) -> dict[SeqId, TokenAlignerSeqInfo]: + """Create a dict of TokenAlignerSeqInfo from {int_key: input_ids_tuple}.""" + result: dict[SeqId, TokenAlignerSeqInfo] = {} + for k, input_ids in sequences.items(): + num_tokens = len(input_ids) + result[_int_to_seq_id(k)] = TokenAlignerSeqInfo( + input_ids=list(input_ids), + positions=list(range(num_tokens)), + locator=TokenLocator( + steps=[0] * num_tokens, + token_index_in_step=list(range(num_tokens)), + ), + ) + return result + + +def _match_seqs( + *, + x: dict[int, tuple[int, ...]], + y: dict[int, tuple[int, ...]], +) -> list[tuple[SeqId, SeqId]]: + """Shorthand: build SeqInfo dicts and call _match_sequences.""" + return _match_sequences( + seqs=Pair(x=_make_seq_info_dict(x), y=_make_seq_info_dict(y)) + ) + + +def _matched_ids(matched: list[tuple[SeqId, SeqId]]) -> set[tuple[SeqId, SeqId]]: + """Convert matched pairs list to set for order-independent comparison.""" + return set(matched) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_thd_seq_lens_loader.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_thd_seq_lens_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..43449e60b4e81515da0638f0a2910963581c1912 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/token_aligner/test_thd_seq_lens_loader.py @@ -0,0 +1,172 @@ +import sys +from pathlib import Path +from unittest.mock import patch + +import polars as pl +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.token_aligner.concat_steps.thd_seq_lens_loader import ( + load_thd_seq_lens_only, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_plugins import ( + _SGLangPlugin, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) + + +def _save_pt( + dump_path: Path, + *, + name: str, + step: int, + rank: int, + value: object, + meta: dict | None = None, +) -> str: + filename: str = f"name={name}___step={step}___rank={rank}.pt" + payload: dict = {"value": value, "meta": meta or {}} + torch.save(payload, dump_path / filename) + return filename + + +def _make_df_from_filenames(filenames: list[str]) -> pl.DataFrame: + rows: list[dict] = [] + for fn in filenames: + parts: dict = {} + stem: str = fn.removesuffix(".pt") + for kv in stem.split("___"): + if "=" in kv: + k, v = kv.split("=", 1) + parts[k] = v + rows.append( + { + "filename": fn, + "name": parts["name"], + "step": int(parts["step"]), + "rank": int(parts["rank"]), + } + ) + return pl.DataFrame(rows) + + +class TestLoadThdSeqLensOnly: + """Tests for load_thd_seq_lens_only.""" + + def test_returns_none_when_no_plugin(self, tmp_path: Path) -> None: + """No recognized plugin → returns None.""" + fn: str = _save_pt( + tmp_path, name="unrelated_tensor", step=0, rank=0, value=torch.tensor([1]) + ) + df: pl.DataFrame = _make_df_from_filenames([fn]) + + result = load_thd_seq_lens_only(dump_path=tmp_path, df=df) + + assert result is None + + def test_returns_none_when_no_cp_sharded_names(self, tmp_path: Path) -> None: + """Plugin detected but cp_sharded_names is empty → returns None.""" + + class _NoCpPlugin(_SGLangPlugin): + @property + def cp_sharded_names(self) -> frozenset[str]: + return frozenset() + + fn: str = _save_pt( + tmp_path, + name="seq_lens", + step=0, + rank=0, + value=torch.tensor([3, 5]), + meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}}, + ) + df: pl.DataFrame = _make_df_from_filenames([fn]) + + with patch( + "sglang.srt.debug_utils.comparator.aligner.token_aligner.concat_steps.thd_seq_lens_loader._detect_plugin", + return_value=_NoCpPlugin(), + ): + result = load_thd_seq_lens_only(dump_path=tmp_path, df=df) + + assert result is None + + def test_sglang_extracts_seq_lens(self, tmp_path: Path) -> None: + """SGLang format: seq_lens tensor present → extracts per-seq lengths.""" + fn: str = _save_pt( + tmp_path, + name="seq_lens", + step=0, + rank=0, + value=torch.tensor([3, 5]), + meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}}, + ) + df: pl.DataFrame = _make_df_from_filenames([fn]) + + result = load_thd_seq_lens_only(dump_path=tmp_path, df=df) + + assert result is not None + assert result == {0: [3, 5]} + + def test_megatron_extracts_from_cu_seqlens(self, tmp_path: Path) -> None: + """Megatron format: cu_seqlens_q tensor → derives seq_lens via diff.""" + fn: str = _save_pt( + tmp_path, + name="cu_seqlens_q", + step=0, + rank=0, + value=torch.tensor([0, 3, 8], dtype=torch.int64), + meta={"megatron_parallel_info": {"cp_rank": 0, "cp_size": 2}}, + ) + df: pl.DataFrame = _make_df_from_filenames([fn]) + + result = load_thd_seq_lens_only(dump_path=tmp_path, df=df) + + assert result is not None + assert result == {0: [3, 5]} + + def test_multi_step(self, tmp_path: Path) -> None: + """Two steps with different seq_lens → returns both in result dict.""" + fn0: str = _save_pt( + tmp_path, + name="seq_lens", + step=0, + rank=0, + value=torch.tensor([3, 5]), + meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}}, + ) + fn1: str = _save_pt( + tmp_path, + name="seq_lens", + step=1, + rank=0, + value=torch.tensor([10, 20, 30]), + meta={"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}}, + ) + df: pl.DataFrame = _make_df_from_filenames([fn0, fn1]) + + result = load_thd_seq_lens_only(dump_path=tmp_path, df=df) + + assert result is not None + assert result == {0: [3, 5], 1: [10, 20, 30]} + + def test_returns_none_when_seq_lens_missing(self, tmp_path: Path) -> None: + """Plugin with cp_sharded_names but no seq_lens/cu_seqlens_q tensor → None.""" + fn: str = _save_pt( + tmp_path, + name="cu_seqlens_kv", + step=0, + rank=0, + value=torch.tensor([0, 4], dtype=torch.int64), + meta={"megatron_parallel_info": {"cp_rank": 0, "cp_size": 2}}, + ) + df: pl.DataFrame = _make_df_from_filenames([fn]) + + result = load_thd_seq_lens_only(dump_path=tmp_path, df=df) + + assert result is None + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/__init__.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/conftest.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_executor.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..e02f04d21b4753e54b6ff75f62fcbf5a0859fbcb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_executor.py @@ -0,0 +1,1097 @@ +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.aligner.unsharder.executor import ( + UnsharderResult, + _apply_unshard, + _verify_replicated_group, + execute_unsharder_plan, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.planner import ( + compute_unsharder_plan, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( + AxisInfo, + CpThdConcatParams, + PickParams, + ReduceSumParams, + UnsharderPlan, +) +from sglang.srt.debug_utils.comparator.dims_spec import ( + DimSpec, + ParallelAxis, + apply_dim_names, + get_dim_names, + parse_dims, + without_dim_names, +) +from sglang.srt.debug_utils.comparator.output_types import ReplicatedCheckResult +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +def _name_tensors( + tensors: list[torch.Tensor], dim_specs: list[DimSpec] +) -> list[torch.Tensor]: + names: list[str] = [s.sanitized_name for s in dim_specs] + return [apply_dim_names(t, names) for t in tensors] + + +class TestExecuteUnsharderPlan: + def test_tp4_concat(self) -> None: + full_tensor = torch.randn(2, 8, 16) + shards = list(full_tensor.chunk(4, dim=1)) + + dim_specs = parse_dims("b h[tp] d").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + + named_shards: list[torch.Tensor] = _name_tensors(shards, dim_specs) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], named_shards + ) + assert len(unsharder_result.tensors) == 1 + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), full_tensor + ) + assert unsharder_result.replicated_checks == [] + + def test_scrambled_world_ranks_correct_result(self) -> None: + full_tensor = torch.randn(4, 8) + shards = list(full_tensor.chunk(4, dim=0)) + + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)}, + ] + dim_specs = parse_dims("h[tp] d").dims + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + + tensors_ordered_by_world_rank = _name_tensors( + [ + shards[2], # world_rank=0, axis_rank=2 + shards[0], # world_rank=1, axis_rank=0 + shards[3], # world_rank=2, axis_rank=3 + shards[1], # world_rank=3, axis_rank=1 + ], + dim_specs, + ) + + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], tensors_ordered_by_world_rank + ) + assert len(unsharder_result.tensors) == 1 + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), full_tensor + ) + assert unsharder_result.replicated_checks == [] + + def test_single_step_reduces_tensor_count(self) -> None: + """8 tensors with 2 groups of 4 produce 2 output tensors.""" + full_a = torch.randn(4, 8) + full_b = torch.randn(4, 8) + shards_a = list(full_a.chunk(4, dim=0)) + shards_b = list(full_b.chunk(4, dim=0)) + + dim_specs = parse_dims("s[cp] h[tp]").dims + parallel_infos = [] + for cp_rank in range(2): + for tp_rank in range(4): + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=4), + } + ) + + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 2 + + tensors: list[torch.Tensor] = [] + for cp_rank in range(2): + source = shards_a if cp_rank == 0 else shards_b + for tp_rank in range(4): + tensors.append(source[tp_rank]) + + named_tensors: list[torch.Tensor] = _name_tensors(tensors, dim_specs) + intermediate_result: UnsharderResult = execute_unsharder_plan( + plans[0], named_tensors + ) + assert len(intermediate_result.tensors) == 4 + + final_result: UnsharderResult = execute_unsharder_plan( + plans[1], intermediate_result.tensors + ) + assert len(final_result.tensors) == 1 + + def test_cp_tp_concat(self) -> None: + """CP=2 + TP=2: multi-step unshard reconstructs original tensor.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16) + + cp_chunks = list(full_tensor.chunk(2, dim=1)) + tensors: list[torch.Tensor] = [] + parallel_infos = [] + for cp_rank in range(2): + tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=2)) + for tp_rank in range(2): + tensors.append(tp_chunks[tp_rank]) + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + dim_specs = parse_dims("b s[cp] h[tp]").dims + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 2 + + current: list[torch.Tensor] = _name_tensors(tensors, dim_specs) + for plan in plans: + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current) + current = unsharder_result.tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + def test_cp_tp_scrambled(self) -> None: + """Scrambled world_ranks for CP=2 + TP=2 still reconstruct correctly.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16) + + cp_chunks = list(full_tensor.chunk(2, dim=1)) + shard_map: dict[tuple[int, int], torch.Tensor] = {} + for cp_rank in range(2): + tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=2)) + for tp_rank in range(2): + shard_map[(cp_rank, tp_rank)] = tp_chunks[tp_rank] + + scrambled_assignment = [ + (1, 1), # world_rank=0 + (0, 0), # world_rank=1 + (1, 0), # world_rank=2 + (0, 1), # world_rank=3 + ] + + tensors: list[torch.Tensor] = [] + parallel_infos = [] + for cp_rank, tp_rank in scrambled_assignment: + tensors.append(shard_map[(cp_rank, tp_rank)]) + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + dim_specs = parse_dims("b s[cp] h[tp]").dims + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 2 + + current: list[torch.Tensor] = _name_tensors(tensors, dim_specs) + for plan in plans: + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current) + current = unsharder_result.tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + def test_unsupported_params_type_raises(self) -> None: + """_apply_unshard raises ValueError for unknown params type.""" + + class _FakeParams: + pass + + with pytest.raises(ValueError, match="Unsupported unshard"): + _apply_unshard( + _FakeParams(), + [torch.randn(2, 2)], + axis=ParallelAxis.TP, + group_index=0, + ) + + def test_cp_tp_ep_three_axis_concat(self) -> None: + """CP=2 + TP=2 + EP=2: three-step unshard reconstructs original tensor.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16, 32) + + ep_chunks = list(full_tensor.chunk(2, dim=1)) + shard_map: dict[tuple[int, int, int], torch.Tensor] = {} + for ep_rank in range(2): + cp_chunks = list(ep_chunks[ep_rank].chunk(2, dim=2)) + for cp_rank in range(2): + tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=3)) + for tp_rank in range(2): + shard_map[(ep_rank, cp_rank, tp_rank)] = tp_chunks[tp_rank] + + tensors: list[torch.Tensor] = [] + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for ep_rank in range(2): + for cp_rank in range(2): + for tp_rank in range(2): + tensors.append(shard_map[(ep_rank, cp_rank, tp_rank)]) + parallel_infos.append( + { + ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + dim_specs = parse_dims("b e[ep] s[cp] h[tp]").dims + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 3 + + current: list[torch.Tensor] = _name_tensors(tensors, dim_specs) + for plan in plans: + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current) + current = unsharder_result.tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + def test_cp_tp_ep_scrambled_three_axis(self) -> None: + """Scrambled ranks for CP=2 + TP=2 + EP=2 still reconstruct correctly.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16, 32) + + ep_chunks = list(full_tensor.chunk(2, dim=1)) + shard_map: dict[tuple[int, int, int], torch.Tensor] = {} + for ep_rank in range(2): + cp_chunks = list(ep_chunks[ep_rank].chunk(2, dim=2)) + for cp_rank in range(2): + tp_chunks = list(cp_chunks[cp_rank].chunk(2, dim=3)) + for tp_rank in range(2): + shard_map[(ep_rank, cp_rank, tp_rank)] = tp_chunks[tp_rank] + + scrambled_assignment = [ + (1, 0, 1), # world_rank=0 + (0, 1, 0), # world_rank=1 + (1, 1, 0), # world_rank=2 + (0, 0, 0), # world_rank=3 + (0, 1, 1), # world_rank=4 + (1, 0, 0), # world_rank=5 + (0, 0, 1), # world_rank=6 + (1, 1, 1), # world_rank=7 + ] + + tensors: list[torch.Tensor] = [] + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for ep_rank, cp_rank, tp_rank in scrambled_assignment: + tensors.append(shard_map[(ep_rank, cp_rank, tp_rank)]) + parallel_infos.append( + { + ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + dim_specs = parse_dims("b e[ep] s[cp] h[tp]").dims + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 3 + + current: list[torch.Tensor] = _name_tensors(tensors, dim_specs) + for plan in plans: + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current) + current = unsharder_result.tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + +class TestPickOperation: + def test_pick_single_group(self) -> None: + """PickParams picks the first tensor from a single group.""" + tensor = torch.randn(4, 8) + dim_specs = parse_dims("h d # tp:replicated").dims + replicated = frozenset({ParallelAxis.TP}) + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)}, + ] + + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + assert len(plans) == 1 + assert isinstance(plans[0].params, PickParams) + + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], [tensor, tensor.clone()] + ) + assert len(unsharder_result.tensors) == 1 + assert torch.allclose(without_dim_names(unsharder_result.tensors[0]), tensor) + assert all(c.passed for c in unsharder_result.replicated_checks) + + def test_pick_multiple_groups(self) -> None: + """PickParams with multiple groups picks one from each.""" + dim_specs = parse_dims("h[tp] # cp:replicated").dims + replicated = frozenset({ParallelAxis.CP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + pick_plans = [p for p in plans if isinstance(p.params, PickParams)] + assert len(pick_plans) == 1 + assert pick_plans[0].axis == ParallelAxis.CP + + tensor = torch.randn(4) + tensors = [tensor.clone() for _ in range(4)] + + unsharder_result: UnsharderResult = execute_unsharder_plan( + pick_plans[0], tensors + ) + assert len(unsharder_result.tensors) == 2 + assert all(c.passed for c in unsharder_result.replicated_checks) + + def test_replicated_tp_sharded_cp_e2e(self) -> None: + """CP2 TP2, dims='b s[cp] d # tp:replicated': replicated TP pick + sharded CP concat round-trip.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16) + cp_chunks = list(full_tensor.chunk(2, dim=1)) + + tensors: list[torch.Tensor] = [] + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for tp_rank in range(2): + tensors.append(cp_chunks[cp_rank].clone()) + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + dim_specs = parse_dims("b s[cp] d # tp:replicated").dims + replicated = frozenset({ParallelAxis.TP}) + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + assert len(plans) == 2 + + current: list[torch.Tensor] = _name_tensors(tensors, dim_specs) + for plan in plans: + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current) + current = unsharder_result.tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + def test_fully_replicated_e2e(self) -> None: + """CP2 TP2, dims='b h d # cp:replicated tp:replicated': fully replicated -> 2 pick steps -> 1 tensor.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16) + + tensors: list[torch.Tensor] = [] + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for tp_rank in range(2): + tensors.append(full_tensor.clone()) + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + dim_specs = parse_dims("b h d # cp:replicated tp:replicated").dims + replicated = frozenset({ParallelAxis.CP, ParallelAxis.TP}) + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + assert len(plans) == 2 + assert all(isinstance(p.params, PickParams) for p in plans) + + current: list[torch.Tensor] = _name_tensors(tensors, dim_specs) + for plan in plans: + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current) + current = unsharder_result.tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + +class TestVerifyReplicatedGroup: + def test_fails_on_mismatch(self) -> None: + """_verify_replicated_group returns failed check when replicas differ.""" + tensor_a = torch.ones(4) + tensor_b = torch.ones(4) + 0.1 + + checks: list[ReplicatedCheckResult] = _verify_replicated_group( + [tensor_a, tensor_b], + axis=ParallelAxis.TP, + group_index=0, + ) + assert len(checks) == 1 + assert checks[0].axis == "tp" + assert checks[0].group_index == 0 + assert checks[0].compared_index == 1 + assert checks[0].baseline_index == 0 + assert not checks[0].passed + assert checks[0].diff.max_abs_diff == pytest.approx(0.1, abs=1e-5) + + def test_passes_when_identical(self) -> None: + """_verify_replicated_group returns passed check for identical replicas.""" + tensor = torch.randn(4, 8) + + checks: list[ReplicatedCheckResult] = _verify_replicated_group( + [tensor, tensor.clone()], + axis=ParallelAxis.TP, + group_index=0, + ) + assert len(checks) == 1 + assert checks[0].passed + + def test_multiple_mismatches(self) -> None: + """_verify_replicated_group reports each differing replica.""" + baseline = torch.zeros(4) + other_a = torch.ones(4) + other_b = torch.ones(4) * 2 + + checks: list[ReplicatedCheckResult] = _verify_replicated_group( + [baseline, other_a, other_b], + axis=ParallelAxis.CP, + group_index=1, + ) + assert len(checks) == 2 + assert checks[0].compared_index == 1 + assert not checks[0].passed + assert checks[1].compared_index == 2 + assert not checks[1].passed + assert checks[1].diff.max_abs_diff == pytest.approx(2.0, abs=1e-5) + + def test_execute_returns_replicated_checks(self) -> None: + """execute_unsharder_plan returns replicated checks for mismatch.""" + dim_specs = parse_dims("h d # tp:replicated").dims + replicated = frozenset({ParallelAxis.TP}) + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)}, + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + tensor_a = torch.zeros(4) + tensor_b = torch.ones(4) + + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], [tensor_a, tensor_b] + ) + assert len(unsharder_result.tensors) == 1 + assert len(unsharder_result.replicated_checks) == 1 + assert not unsharder_result.replicated_checks[0].passed + assert torch.allclose(without_dim_names(unsharder_result.tensors[0]), tensor_a) + + def test_atol_boundary_within(self) -> None: + """Difference exactly at atol (1e-6) -> passed.""" + baseline = torch.zeros(4) + other = torch.full((4,), 1e-6) + + checks: list[ReplicatedCheckResult] = _verify_replicated_group( + [baseline, other], + axis=ParallelAxis.TP, + group_index=0, + ) + assert len(checks) == 1 + assert checks[0].passed + + def test_atol_boundary_exceeded(self) -> None: + """Difference just above atol (1e-6 + 1e-9) -> failed.""" + baseline = torch.zeros(4) + other = torch.full((4,), 1e-6 + 1e-9) + + checks: list[ReplicatedCheckResult] = _verify_replicated_group( + [baseline, other], + axis=ParallelAxis.TP, + group_index=0, + ) + assert len(checks) == 1 + assert not checks[0].passed + assert checks[0].compared_index == 1 + + def test_recompute_pseudo_mismatch(self) -> None: + """_verify_replicated_group returns failed check for RECOMPUTE_PSEUDO axis mismatch.""" + tensor_a = torch.ones(4) + tensor_b = torch.ones(4) + 0.1 + + checks: list[ReplicatedCheckResult] = _verify_replicated_group( + [tensor_a, tensor_b], + axis=ParallelAxis.RECOMPUTE_PSEUDO, + group_index=0, + ) + assert len(checks) == 1 + assert checks[0].axis == "recompute_pseudo" + assert checks[0].group_index == 0 + assert checks[0].compared_index == 1 + assert checks[0].baseline_index == 0 + assert not checks[0].passed + assert checks[0].diff.max_abs_diff == pytest.approx(0.1, abs=1e-5) + + +class TestThdCpConcat: + def test_single_seq(self) -> None: + """Single seq THD unshard: 2 ranks → per-seq concat.""" + rank0 = apply_dim_names(torch.tensor([1, 2, 3]), ["t"]) + rank1 = apply_dim_names(torch.tensor([4, 5, 6]), ["t"]) + + plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3]), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1]) + + assert len(unsharder_result.tensors) == 1 + expected = torch.tensor([1, 2, 3, 4, 5, 6]) + assert torch.equal(without_dim_names(unsharder_result.tensors[0]), expected) + + def test_multi_seq(self) -> None: + """Multi-seq THD unshard: 2 ranks, seq_lens=[50, 32, 46].""" + # rank0: [seqA_r0(50) | seqB_r0(32) | pad_r0(46)] + # rank1: [seqA_r1(50) | seqB_r1(32) | pad_r1(46)] + seq_a_r0 = torch.arange(0, 50) + seq_b_r0 = torch.arange(100, 132) + pad_r0 = torch.full((46,), -1) + rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0, pad_r0]), ["t"]) + + seq_a_r1 = torch.arange(50, 100) + seq_b_r1 = torch.arange(132, 164) + pad_r1 = torch.full((46,), -2) + rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1, pad_r1]), ["t"]) + + plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[50, 32, 46]), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1]) + + assert len(unsharder_result.tensors) == 1 + unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0]) + + # seqA: r0(50) + r1(50) = 100 tokens, values 0..99 + assert torch.equal(unsharded[:100], torch.cat([seq_a_r0, seq_a_r1])) + # seqB: r0(32) + r1(32) = 64 tokens + assert torch.equal(unsharded[100:164], torch.cat([seq_b_r0, seq_b_r1])) + # pad: r0(46) + r1(46) = 92 tokens + assert torch.equal(unsharded[164:256], torch.cat([pad_r0, pad_r1])) + + def test_with_hidden_dim(self) -> None: + """THD unshard with trailing hidden dim: shape [T, H].""" + torch.manual_seed(42) + hidden: int = 4 + # rank0: [seqA_r0(3, 4) | seqB_r0(2, 4)] + # rank1: [seqA_r1(3, 4) | seqB_r1(2, 4)] + seq_a_r0 = torch.randn(3, hidden) + seq_b_r0 = torch.randn(2, hidden) + rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0]), ["t", "h"]) + + seq_a_r1 = torch.randn(3, hidden) + seq_b_r1 = torch.randn(2, hidden) + rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1]), ["t", "h"]) + + plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3, 2]), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1]) + + assert len(unsharder_result.tensors) == 1 + unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0]) + + assert unsharded.shape == (10, hidden) + assert torch.equal(unsharded[:6], torch.cat([seq_a_r0, seq_a_r1])) + assert torch.equal(unsharded[6:10], torch.cat([seq_b_r0, seq_b_r1])) + + def test_with_leading_batch_dim(self) -> None: + """THD unshard with leading batch dim: shape [B, T, H], t is dim=1.""" + torch.manual_seed(42) + batch: int = 2 + hidden: int = 4 + # rank0: [seqA_r0(3) | seqB_r0(2)] per batch item + # rank1: [seqA_r1(3) | seqB_r1(2)] per batch item + seq_a_r0 = torch.randn(batch, 3, hidden) + seq_b_r0 = torch.randn(batch, 2, hidden) + rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0], dim=1), ["b", "t", "h"]) + + seq_a_r1 = torch.randn(batch, 3, hidden) + seq_b_r1 = torch.randn(batch, 2, hidden) + rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1], dim=1), ["b", "t", "h"]) + + plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3, 2]), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1]) + + assert len(unsharder_result.tensors) == 1 + unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0]) + + assert unsharded.shape == (batch, 10, hidden) + # seqA: r0(3) + r1(3) = 6 tokens per batch + assert torch.equal(unsharded[:, :6, :], torch.cat([seq_a_r0, seq_a_r1], dim=1)) + # seqB: r0(2) + r1(2) = 4 tokens per batch + assert torch.equal( + unsharded[:, 6:10, :], torch.cat([seq_b_r0, seq_b_r1], dim=1) + ) + + +class TestReduceSum: + def test_basic_tp2_reduce(self) -> None: + """2 partial tensors sum to full tensor.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + part_a = full_tensor * 0.6 + part_b = full_tensor * 0.4 + + dim_specs = parse_dims("h[tp:partial] d").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + assert isinstance(plans[0].params, ReduceSumParams) + + named_parts: list[torch.Tensor] = _name_tensors([part_a, part_b], dim_specs) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], named_parts + ) + + assert len(unsharder_result.tensors) == 1 + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), full_tensor + ) + + def test_tp4_reduce(self) -> None: + """4 partial tensors sum to full tensor.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + parts: list[torch.Tensor] = [full_tensor * 0.25 for _ in range(4)] + + dim_specs = parse_dims("h[tp:partial] d").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + + named_parts: list[torch.Tensor] = _name_tensors(parts, dim_specs) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], named_parts + ) + + assert len(unsharder_result.tensors) == 1 + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), full_tensor + ) + + def test_multi_axis_concat_then_reduce(self) -> None: + """CP concat + TP reduce end-to-end.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16) + + cp_chunks = list(full_tensor.chunk(2, dim=1)) + # Each CP chunk is held as partial sums across TP ranks + tensors: list[torch.Tensor] = [] + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for tp_rank in range(2): + tensors.append(cp_chunks[cp_rank] * 0.5) + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + dim_specs = parse_dims("b s[cp] h[tp:partial]").dims + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 2 + + current: list[torch.Tensor] = _name_tensors(tensors, dim_specs) + for plan in plans: + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current) + current = unsharder_result.tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + def test_reduce_scrambled_ranks(self) -> None: + """Scrambled rank order — sum is commutative so result is the same.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + parts: list[torch.Tensor] = [ + full_tensor * 0.1, + full_tensor * 0.2, + full_tensor * 0.3, + full_tensor * 0.4, + ] + + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)}, + ] + dim_specs = parse_dims("h[tp:partial] d").dims + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + named_parts: list[torch.Tensor] = _name_tensors(parts, dim_specs) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], named_parts + ) + + assert len(unsharder_result.tensors) == 1 + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), full_tensor + ) + + def test_reduce_preserves_named_dims(self) -> None: + """Named tensor dimensions are preserved through reduce_sum.""" + dim_specs = parse_dims("h[tp:partial] d").dims + part_a = apply_dim_names(torch.randn(4, 8), ["h", "d"]) + part_b = apply_dim_names(torch.randn(4, 8), ["h", "d"]) + + plan = UnsharderPlan( + axis=ParallelAxis.TP, + params=ReduceSumParams(), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plan, [part_a, part_b] + ) + + assert len(unsharder_result.tensors) == 1 + assert get_dim_names(unsharder_result.tensors[0]) == ("h", "d") + expected = apply_dim_names( + without_dim_names(part_a) + without_dim_names(part_b), ["h", "d"] + ) + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), without_dim_names(expected) + ) + + def test_recompute_pseudo_mismatch(self) -> None: + """_verify_replicated_group returns failed check for RECOMPUTE_PSEUDO axis mismatch.""" + tensor_a = torch.ones(4) + tensor_b = torch.ones(4) + 0.1 + + checks: list[ReplicatedCheckResult] = _verify_replicated_group( + [tensor_a, tensor_b], + axis=ParallelAxis.RECOMPUTE_PSEUDO, + group_index=0, + ) + assert len(checks) == 1 + assert checks[0].axis == "recompute_pseudo" + assert checks[0].group_index == 0 + assert checks[0].compared_index == 1 + assert checks[0].baseline_index == 0 + assert not checks[0].passed + assert checks[0].diff.max_abs_diff == pytest.approx(0.1, abs=1e-5) + + +class TestThdCpConcat: + def test_single_seq(self) -> None: + """Single seq THD unshard: 2 ranks → per-seq concat.""" + rank0 = apply_dim_names(torch.tensor([1, 2, 3]), ["t"]) + rank1 = apply_dim_names(torch.tensor([4, 5, 6]), ["t"]) + + plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3]), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1]) + + assert len(unsharder_result.tensors) == 1 + expected = torch.tensor([1, 2, 3, 4, 5, 6]) + assert torch.equal(without_dim_names(unsharder_result.tensors[0]), expected) + + def test_multi_seq(self) -> None: + """Multi-seq THD unshard: 2 ranks, seq_lens=[50, 32, 46].""" + # rank0: [seqA_r0(50) | seqB_r0(32) | pad_r0(46)] + # rank1: [seqA_r1(50) | seqB_r1(32) | pad_r1(46)] + seq_a_r0 = torch.arange(0, 50) + seq_b_r0 = torch.arange(100, 132) + pad_r0 = torch.full((46,), -1) + rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0, pad_r0]), ["t"]) + + seq_a_r1 = torch.arange(50, 100) + seq_b_r1 = torch.arange(132, 164) + pad_r1 = torch.full((46,), -2) + rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1, pad_r1]), ["t"]) + + plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[50, 32, 46]), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1]) + + assert len(unsharder_result.tensors) == 1 + unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0]) + + # seqA: r0(50) + r1(50) = 100 tokens, values 0..99 + assert torch.equal(unsharded[:100], torch.cat([seq_a_r0, seq_a_r1])) + # seqB: r0(32) + r1(32) = 64 tokens + assert torch.equal(unsharded[100:164], torch.cat([seq_b_r0, seq_b_r1])) + # pad: r0(46) + r1(46) = 92 tokens + assert torch.equal(unsharded[164:256], torch.cat([pad_r0, pad_r1])) + + def test_with_hidden_dim(self) -> None: + """THD unshard with trailing hidden dim: shape [T, H].""" + torch.manual_seed(42) + hidden: int = 4 + # rank0: [seqA_r0(3, 4) | seqB_r0(2, 4)] + # rank1: [seqA_r1(3, 4) | seqB_r1(2, 4)] + seq_a_r0 = torch.randn(3, hidden) + seq_b_r0 = torch.randn(2, hidden) + rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0]), ["t", "h"]) + + seq_a_r1 = torch.randn(3, hidden) + seq_b_r1 = torch.randn(2, hidden) + rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1]), ["t", "h"]) + + plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3, 2]), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1]) + + assert len(unsharder_result.tensors) == 1 + unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0]) + + assert unsharded.shape == (10, hidden) + assert torch.equal(unsharded[:6], torch.cat([seq_a_r0, seq_a_r1])) + assert torch.equal(unsharded[6:10], torch.cat([seq_b_r0, seq_b_r1])) + + def test_with_leading_batch_dim(self) -> None: + """THD unshard with leading batch dim: shape [B, T, H], t is dim=1.""" + torch.manual_seed(42) + batch: int = 2 + hidden: int = 4 + # rank0: [seqA_r0(3) | seqB_r0(2)] per batch item + # rank1: [seqA_r1(3) | seqB_r1(2)] per batch item + seq_a_r0 = torch.randn(batch, 3, hidden) + seq_b_r0 = torch.randn(batch, 2, hidden) + rank0 = apply_dim_names(torch.cat([seq_a_r0, seq_b_r0], dim=1), ["b", "t", "h"]) + + seq_a_r1 = torch.randn(batch, 3, hidden) + seq_b_r1 = torch.randn(batch, 2, hidden) + rank1 = apply_dim_names(torch.cat([seq_a_r1, seq_b_r1], dim=1), ["b", "t", "h"]) + + plan = UnsharderPlan( + axis=ParallelAxis.CP, + params=CpThdConcatParams(dim_name="t", seq_lens_per_rank=[3, 2]), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, [rank0, rank1]) + + assert len(unsharder_result.tensors) == 1 + unsharded: torch.Tensor = without_dim_names(unsharder_result.tensors[0]) + + assert unsharded.shape == (batch, 10, hidden) + # seqA: r0(3) + r1(3) = 6 tokens per batch + assert torch.equal(unsharded[:, :6, :], torch.cat([seq_a_r0, seq_a_r1], dim=1)) + # seqB: r0(2) + r1(2) = 4 tokens per batch + assert torch.equal( + unsharded[:, 6:10, :], torch.cat([seq_b_r0, seq_b_r1], dim=1) + ) + + +class TestReduceSum: + def test_basic_tp2_reduce(self) -> None: + """2 partial tensors sum to full tensor.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + part_a = full_tensor * 0.6 + part_b = full_tensor * 0.4 + + dim_specs = parse_dims("h[tp:partial] d").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + assert isinstance(plans[0].params, ReduceSumParams) + + named_parts: list[torch.Tensor] = _name_tensors([part_a, part_b], dim_specs) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], named_parts + ) + + assert len(unsharder_result.tensors) == 1 + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), full_tensor + ) + + def test_tp4_reduce(self) -> None: + """4 partial tensors sum to full tensor.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + parts: list[torch.Tensor] = [full_tensor * 0.25 for _ in range(4)] + + dim_specs = parse_dims("h[tp:partial] d").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + + named_parts: list[torch.Tensor] = _name_tensors(parts, dim_specs) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], named_parts + ) + + assert len(unsharder_result.tensors) == 1 + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), full_tensor + ) + + def test_multi_axis_concat_then_reduce(self) -> None: + """CP concat + TP reduce end-to-end.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16) + + cp_chunks = list(full_tensor.chunk(2, dim=1)) + # Each CP chunk is held as partial sums across TP ranks + tensors: list[torch.Tensor] = [] + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for tp_rank in range(2): + tensors.append(cp_chunks[cp_rank] * 0.5) + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + dim_specs = parse_dims("b s[cp] h[tp:partial]").dims + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 2 + + current: list[torch.Tensor] = _name_tensors(tensors, dim_specs) + for plan in plans: + unsharder_result: UnsharderResult = execute_unsharder_plan(plan, current) + current = unsharder_result.tensors + + assert len(current) == 1 + assert torch.allclose(without_dim_names(current[0]), full_tensor) + + def test_reduce_scrambled_ranks(self) -> None: + """Scrambled rank order — sum is commutative so result is the same.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + parts: list[torch.Tensor] = [ + full_tensor * 0.1, + full_tensor * 0.2, + full_tensor * 0.3, + full_tensor * 0.4, + ] + + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)}, + ] + dim_specs = parse_dims("h[tp:partial] d").dims + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + named_parts: list[torch.Tensor] = _name_tensors(parts, dim_specs) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], named_parts + ) + + assert len(unsharder_result.tensors) == 1 + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), full_tensor + ) + + def test_reduce_preserves_named_dims(self) -> None: + """Named tensor dimensions are preserved through reduce_sum.""" + dim_specs = parse_dims("h[tp:partial] d").dims + part_a = apply_dim_names(torch.randn(4, 8), ["h", "d"]) + part_b = apply_dim_names(torch.randn(4, 8), ["h", "d"]) + + plan = UnsharderPlan( + axis=ParallelAxis.TP, + params=ReduceSumParams(), + groups=[[0, 1]], + ) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plan, [part_a, part_b] + ) + + assert len(unsharder_result.tensors) == 1 + assert get_dim_names(unsharder_result.tensors[0]) == ("h", "d") + expected = apply_dim_names( + without_dim_names(part_a) + without_dim_names(part_b), ["h", "d"] + ) + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), without_dim_names(expected) + ) + + +class TestFusedDimExecutor: + def test_fused_tp2_concat(self) -> None: + """Fused dim "t (num_heads*head_dim)[tp]": TP=2 concat on fused axis.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 128) # t=4, nh*hd=128 + + shards = list(full_tensor.chunk(2, dim=1)) + + dim_specs = parse_dims("t (num_heads*head_dim)[tp]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + + named_shards: list[torch.Tensor] = _name_tensors(shards, dim_specs) + unsharder_result: UnsharderResult = execute_unsharder_plan( + plans[0], named_shards + ) + + assert len(unsharder_result.tensors) == 1 + assert torch.allclose( + without_dim_names(unsharder_result.tensors[0]), full_tensor + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_parallel_info.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_parallel_info.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c99dd25933860c2c2df72d74a6d4a5ab28e585 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_parallel_info.py @@ -0,0 +1,100 @@ +import sys + +import pytest + +from sglang.srt.debug_utils.comparator.aligner.unsharder.parallel_info import ( + normalize_parallel_info, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import AxisInfo +from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestNormalizeParallelInfo: + def test_sglang_info(self) -> None: + meta = { + "sglang_parallel_info": { + "tp_rank": 2, + "tp_size": 4, + "pp_rank": 0, + "pp_size": 1, + } + } + result = normalize_parallel_info(meta) + assert result == {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)} + + def test_megatron_info(self) -> None: + meta = { + "megatron_parallel_info": { + "tp_rank": 1, + "tp_size": 2, + "cp_rank": 0, + "cp_size": 4, + "dp_rank": 0, + "dp_size": 1, + } + } + result = normalize_parallel_info(meta) + assert result == { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=4), + } + + def test_no_parallel_info(self) -> None: + assert normalize_parallel_info({}) == {} + assert normalize_parallel_info({"other_key": 42}) == {} + + def test_both_present_raises(self) -> None: + meta = { + "sglang_parallel_info": {"tp_rank": 0, "tp_size": 2}, + "megatron_parallel_info": {"tp_rank": 0, "tp_size": 2}, + } + with pytest.raises(ValueError, match="multiple parallel_info"): + normalize_parallel_info(meta) + + def test_megatron_with_sp(self) -> None: + """Megatron SP reuses TP group: sp_rank==tp_rank, sp_size==tp_size.""" + meta = { + "megatron_parallel_info": { + "tp_rank": 1, + "tp_size": 4, + "sp_rank": 1, + "sp_size": 4, + } + } + result = normalize_parallel_info(meta) + assert result == { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4), + ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=4), + } + + def test_size_1_filtered(self) -> None: + meta = { + "sglang_parallel_info": { + "tp_rank": 0, + "tp_size": 1, + "cp_rank": 0, + "cp_size": 1, + } + } + assert normalize_parallel_info(meta) == {} + + def test_recompute_pseudo_from_top_level_meta(self) -> None: + """recompute_pseudo_rank/size at top-level meta is extracted alongside TP.""" + meta = { + "recompute_pseudo_rank": 1, + "recompute_pseudo_size": 2, + "sglang_parallel_info": {"tp_rank": 0, "tp_size": 2}, + } + result = normalize_parallel_info(meta) + assert result == { + ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + } + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_planner.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..db55c59ebbe196fc0729c4e32c18e98d5877ffcd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/aligner/unsharder/test_planner.py @@ -0,0 +1,2067 @@ +import sys + +import pytest + +from sglang.srt.debug_utils.comparator.aligner.unsharder.planner import ( + _compute_dependent_axes, + _is_dependent_axis, + _is_jointly_determined, + _validate_explicit_replicated, + _validate_replicated_axes_orthogonal, + compute_unsharder_plan, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( + AxisInfo, + ConcatParams, + PickParams, + ReduceSumParams, +) +from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis, parse_dims +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestComputeUnsharderPlan: + def test_tp4_plan(self) -> None: + dim_specs = parse_dims("b s h[tp] d").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + assert plans[0].params.dim_name == "h" + assert plans[0].groups == [[0, 1, 2, 3]] + + def test_inconsistent_axis_size_raises(self) -> None: + dim_specs = parse_dims("h[tp]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)}, + ] + with pytest.raises(ValueError, match="Inconsistent axis_size"): + compute_unsharder_plan(dim_specs, parallel_infos) + + def test_missing_axis_in_all_parallel_infos_skipped(self) -> None: + """Axis in dims but absent from all parallel_infos -> axis_size=1, auto-skip. + But CP is active and undeclared → raises undeclared error.""" + dim_specs = parse_dims("h[tp]").dims + parallel_infos = [{ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2)}] + with pytest.raises(ValueError, match="not declared"): + compute_unsharder_plan(dim_specs, parallel_infos) + + def test_empty_parallel_infos_raises(self) -> None: + dim_specs = parse_dims("h[tp]").dims + with pytest.raises(ValueError, match="must not be empty"): + compute_unsharder_plan(dim_specs, []) + + def test_scrambled_world_ranks(self) -> None: + """world_rank order != axis_rank order.""" + dim_specs = parse_dims("h[tp]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)}, + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + assert plans[0].groups == [[1, 3, 0, 2]] + + def test_no_sharded_axes_returns_empty(self) -> None: + dim_specs = parse_dims("b s d").dims + parallel_infos = [{}] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert plans == [] + + def test_multi_axis_plan(self) -> None: + """Multi-axis (TP + CP) produces a 2-step plan.""" + dim_specs = parse_dims("s[cp] h[tp]").dims + parallel_infos = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 2 + assert plans[0].axis == ParallelAxis.CP + assert plans[1].axis == ParallelAxis.TP + + def test_cp_tp_plan(self) -> None: + """CP=2 + TP=4 produces correct 2-step plan with correct groups.""" + dim_specs = parse_dims("s[cp] h[tp]").dims + parallel_infos = [] + for cp_rank in range(2): + for tp_rank in range(4): + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=4), + } + ) + + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 2 + + cp_plan = plans[0] + assert cp_plan.axis == ParallelAxis.CP + assert len(cp_plan.groups) == 4 + for group in cp_plan.groups: + assert len(group) == 2 + + tp_plan = plans[1] + assert tp_plan.axis == ParallelAxis.TP + assert len(tp_plan.groups) == 1 + assert len(tp_plan.groups[0]) == 4 + + def test_cp_tp_scrambled_ranks(self) -> None: + """Scrambled rank assignment still produces correct plan.""" + dim_specs = parse_dims("s[cp] h[tp]").dims + parallel_infos = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 2 + + cp_plan = plans[0] + assert cp_plan.axis == ParallelAxis.CP + assert len(cp_plan.groups) == 2 + for group in cp_plan.groups: + assert len(group) == 2 + + tp_plan = plans[1] + assert tp_plan.axis == ParallelAxis.TP + assert len(tp_plan.groups) == 1 + assert len(tp_plan.groups[0]) == 2 + + def test_axis_rank_coverage_incomplete_raises(self) -> None: + """TP size=4 but only ranks 0,1,3 provided (missing rank 2).""" + dim_specs = parse_dims("h[tp]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)}, + ] + with pytest.raises(ValueError, match="axis_rank coverage.*incomplete"): + compute_unsharder_plan(dim_specs, parallel_infos) + + def test_reduction_partial_returns_reduce_sum(self) -> None: + dim_specs = parse_dims("h[tp:partial]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + assert isinstance(plans[0].params, ReduceSumParams) + assert plans[0].groups == [[0, 1]] + + def test_reduction_partial_tp4(self) -> None: + """TP=4 with partial reduction produces a single ReduceSumParams step.""" + dim_specs = parse_dims("h[tp:partial]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=4)} for i in range(4) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 1 + assert isinstance(plans[0].params, ReduceSumParams) + assert plans[0].groups == [[0, 1, 2, 3]] + + def test_multi_axis_with_reduction_on_one(self) -> None: + """CP concat + TP reduce produces a 2-step plan.""" + dim_specs = parse_dims("s[cp] h[tp:partial]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for tp_rank in range(2): + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 2 + assert plans[0].axis == ParallelAxis.CP + assert isinstance(plans[0].params, ConcatParams) + assert plans[1].axis == ParallelAxis.TP + assert isinstance(plans[1].params, ReduceSumParams) + + def test_reduction_scrambled_ranks(self) -> None: + """Scrambled world_rank order with partial reduction.""" + dim_specs = parse_dims("h[tp:partial]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4)}, + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 1 + assert isinstance(plans[0].params, ReduceSumParams) + assert plans[0].groups == [[1, 3, 0, 2]] + + def test_ordering_zigzag_accepted(self) -> None: + dim_specs = parse_dims("s[cp:zigzag]").dims + parallel_infos = [ + {ParallelAxis.CP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.CP + + def test_ordering_natural_accepted(self) -> None: + dim_specs = parse_dims("s[cp:natural]").dims + parallel_infos = [ + {ParallelAxis.CP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.CP + + def test_three_axis_plan(self) -> None: + """EP=2 + CP=2 + TP=2 produces a 3-step plan.""" + dim_specs = parse_dims("b e[ep] s[cp] h[tp]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for ep_rank in range(2): + for cp_rank in range(2): + for tp_rank in range(2): + parallel_infos.append( + { + ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 3 + assert plans[0].axis == ParallelAxis.EP + assert plans[1].axis == ParallelAxis.CP + assert plans[2].axis == ParallelAxis.TP + + # Step 0 (EP): 8 tensors → 4 (groups of 2) + assert len(plans[0].groups) == 4 + for group in plans[0].groups: + assert len(group) == 2 + + # Step 1 (CP): 4 tensors → 2 (groups of 2) + assert len(plans[1].groups) == 2 + for group in plans[1].groups: + assert len(group) == 2 + + # Step 2 (TP): 2 tensors → 1 (single group of 2) + assert len(plans[2].groups) == 1 + assert len(plans[2].groups[0]) == 2 + + def test_same_dim_cp_sp_plan(self) -> None: + """t[cp:zigzag,sp] with CP=2 SP=2: SP unshards first (inner), then CP.""" + dim_specs = parse_dims("t[cp:zigzag,sp] 1 h").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for sp_rank in range(2): + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=sp_rank, axis_size=2), + } + ) + + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 2 + + # SP unshards first (rightmost modifier = innermost shard) + sp_plan = plans[0] + assert sp_plan.axis == ParallelAxis.SP + assert isinstance(sp_plan.params, ConcatParams) + assert sp_plan.params.dim_name == "t" + assert len(sp_plan.groups) == 2 + for group in sp_plan.groups: + assert len(group) == 2 + + # CP unshards second (leftmost modifier = outermost shard) + cp_plan = plans[1] + assert cp_plan.axis == ParallelAxis.CP + assert isinstance(cp_plan.params, ConcatParams) + assert cp_plan.params.dim_name == "t" + assert len(cp_plan.groups) == 1 + assert len(cp_plan.groups[0]) == 2 + + def test_same_dim_cp_sp_with_thd(self) -> None: + """t[cp:zigzag,sp] with THD: SP → ConcatParams, CP → CpThdConcatParams.""" + from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( + CpThdConcatParams, + ) + + dim_specs = parse_dims("t[cp:zigzag,sp] h").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for sp_rank in range(2): + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=sp_rank, axis_size=2), + } + ) + + thd_global_seq_lens: list[int] = [100, 64] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, thd_global_seq_lens=thd_global_seq_lens + ) + + assert len(plans) == 2 + + # SP unshards first: plain concat (SP is not CP, no THD special handling) + sp_plan = plans[0] + assert sp_plan.axis == ParallelAxis.SP + assert isinstance(sp_plan.params, ConcatParams) + assert sp_plan.params.dim_name == "t" + + # CP unshards second: THD concat because dim is 't' + axis is CP + thd_global_seq_lens provided + cp_plan = plans[1] + assert cp_plan.axis == ParallelAxis.CP + assert isinstance(cp_plan.params, CpThdConcatParams) + assert cp_plan.params.dim_name == "t" + assert cp_plan.params.seq_lens_per_rank == [50, 32] + + def test_sp_in_dims_but_not_in_parallel_info(self) -> None: + """s[sp] in dims but SP absent from parallel_info (SP disabled), should auto-skip.""" + dim_specs = parse_dims("s[sp] b h[tp]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)}, + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + + def test_all_dims_sharded_but_single_gpu(self) -> None: + """Single GPU (TP=1, CP=1), dims has s[cp] h[tp] but parallel_info is empty.""" + dim_specs = parse_dims("b s[cp] h[tp] d").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [{}] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + assert plans == [] + + def test_sharded_axis_missing_from_rank_raises(self) -> None: + """A world_rank missing a sharded axis raises ValueError.""" + dim_specs = parse_dims("s[cp] h[tp]").dims + parallel_infos = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + # missing TP — sharded axis absent from rank + }, + ] + with pytest.raises(ValueError, match="missing parallel_info"): + compute_unsharder_plan(dim_specs, parallel_infos) + + def test_tp_sharded_etp_dependent_auto_resolved(self) -> None: + """dims=h[tp], active={TP, ETP, EP}, EP replicated, etp depends on tp → plan succeeds.""" + dim_specs = parse_dims("b h[tp] d # ep:replicated").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for tp_rank in range(2): + for ep_rank in range(2): + parallel_infos.append( + { + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + ParallelAxis.ETP: AxisInfo(axis_rank=tp_rank, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2), + } + ) + + plans = compute_unsharder_plan( + dim_specs, + parallel_infos, + explicit_replicated_axes=frozenset({ParallelAxis.EP}), + ) + + axes_in_plan = [p.axis for p in plans] + assert ParallelAxis.TP in axes_in_plan + assert ParallelAxis.EP in axes_in_plan + assert ParallelAxis.ETP not in axes_in_plan + + def test_edp_jointly_determined_by_tp_and_cp(self) -> None: + """dims=t[cp:zigzag,sp] h # tp:replicated, EDP determined by (TP,CP) jointly → plan succeeds. + + Simulates tp=2, cp=2, ep=1, etp=1 on 4 GPUs. + """ + dim_specs = parse_dims("t[cp:zigzag,sp] h # tp:replicated").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=3, axis_size=4), + }, + ] + plans = compute_unsharder_plan( + dim_specs, + parallel_infos, + explicit_replicated_axes=frozenset({ParallelAxis.TP}), + ) + axes_in_plan = [p.axis for p in plans] + assert ParallelAxis.CP in axes_in_plan + assert ParallelAxis.TP in axes_in_plan + assert ParallelAxis.EDP not in axes_in_plan + + +class TestExplicitReplicatedAxes: + def test_replicated_tp_with_sharded_cp(self) -> None: + """CP2 TP2, dims='b s[cp] d # tp:replicated' → PickPlan(TP) + ConcatPlan(CP).""" + dim_specs = parse_dims("b s[cp] d # tp:replicated").dims + replicated = frozenset({ParallelAxis.TP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + assert len(plans) == 2 + assert plans[0].axis == ParallelAxis.TP + assert isinstance(plans[0].params, PickParams) + assert len(plans[0].groups) == 2 + for group in plans[0].groups: + assert len(group) == 2 + + assert plans[1].axis == ParallelAxis.CP + assert isinstance(plans[1].params, ConcatParams) + assert plans[1].params.dim_name == "s" + + def test_fully_replicated(self) -> None: + """CP2 TP2, dims='b h d # cp:replicated tp:replicated' → PickPlan(CP) + PickPlan(TP).""" + dim_specs = parse_dims("b h d # cp:replicated tp:replicated").dims + replicated = frozenset({ParallelAxis.CP, ParallelAxis.TP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + assert len(plans) == 2 + assert all(isinstance(p.params, PickParams) for p in plans) + axes = {p.axis for p in plans} + assert axes == {ParallelAxis.CP, ParallelAxis.TP} + + def test_multiple_replicated_one_sharded(self) -> None: + """CP2 TP2 EP2, dims='h[tp] # cp:replicated ep:replicated'.""" + dim_specs = parse_dims("h[tp] # cp:replicated ep:replicated").dims + replicated = frozenset({ParallelAxis.CP, ParallelAxis.EP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for ep_rank in range(2): + for tp_rank in range(2): + parallel_infos.append( + { + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + assert len(plans) == 3 + pick_plans = [p for p in plans if isinstance(p.params, PickParams)] + concat_plans = [p for p in plans if isinstance(p.params, ConcatParams)] + assert len(pick_plans) == 2 + assert len(concat_plans) == 1 + assert concat_plans[0].axis == ParallelAxis.TP + + replicated_axes_in_plan = {p.axis for p in pick_plans} + assert replicated_axes_in_plan == {ParallelAxis.CP, ParallelAxis.EP} + + def test_replicated_scrambled_ranks(self) -> None: + """Scrambled world_rank order with explicit replicated axis.""" + dim_specs = parse_dims("h[tp] # cp:replicated").dims + replicated = frozenset({ParallelAxis.CP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + assert len(plans) == 2 + assert plans[0].axis == ParallelAxis.CP + assert isinstance(plans[0].params, PickParams) + assert plans[1].axis == ParallelAxis.TP + assert isinstance(plans[1].params, ConcatParams) + + def test_replicated_axis_inconsistent_size_raises(self) -> None: + """Replicated axis with inconsistent sizes raises ValueError.""" + dim_specs = parse_dims("h[tp] # cp:replicated").dims + replicated = frozenset({ParallelAxis.CP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=4), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="Inconsistent axis_size"): + compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + def test_replicated_axis_missing_from_rank_raises(self) -> None: + """A rank missing a replicated axis that other ranks have raises ValueError.""" + dim_specs = parse_dims("h[tp] # cp:replicated").dims + replicated = frozenset({ParallelAxis.CP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + # missing CP — replicated axis absent from this rank + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="missing parallel_info"): + compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + def test_recompute_pseudo_auto_replicated(self) -> None: + """RECOMPUTE_PSEUDO is auto-replicated without explicit declaration.""" + dim_specs = parse_dims("h d").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + {ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=0, axis_size=2)}, + {ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=1, axis_size=2)}, + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.RECOMPUTE_PSEUDO + assert isinstance(plans[0].params, PickParams) + assert plans[0].groups == [[0, 1]] + + def test_recompute_pseudo_explicit_replicated_also_works(self) -> None: + """RECOMPUTE_PSEUDO with explicit # recompute_pseudo:replicated also works.""" + dim_specs = parse_dims("h d # recompute_pseudo:replicated").dims + replicated = frozenset({ParallelAxis.RECOMPUTE_PSEUDO}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + {ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=0, axis_size=2)}, + {ParallelAxis.RECOMPUTE_PSEUDO: AxisInfo(axis_rank=1, axis_size=2)}, + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.RECOMPUTE_PSEUDO + assert isinstance(plans[0].params, PickParams) + assert plans[0].groups == [[0, 1]] + + def test_undeclared_active_axis_raises(self) -> None: + """Active axis not declared as sharded or replicated raises ValueError.""" + dim_specs = parse_dims("b s[cp] d").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="tp.*not declared"): + compute_unsharder_plan(dim_specs, parallel_infos) + + def test_replicated_not_in_parallel_infos_raises(self) -> None: + """Declaring replicated axis not in parallel_infos raises ValueError.""" + dim_specs = parse_dims("h[tp] # ep:replicated").dims + replicated = frozenset({ParallelAxis.EP}) + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + with pytest.raises(ValueError, match="not found in parallel_infos"): + compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + def test_explicit_replicated_conflicts_with_sharded_raises(self) -> None: + """Planner-level defense: replicated overlaps sharded → ValueError.""" + dim_specs = parse_dims("h[tp]").dims + replicated = frozenset({ParallelAxis.TP}) + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + with pytest.raises(ValueError, match="both sharded and replicated"): + compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + +class TestComputeUnsharderPlanFusedDims: + def test_fused_dim_tp2(self) -> None: + """Fused dim "(num_heads*head_dim)[tp]" should unshard on the fused tensor name.""" + dim_specs = parse_dims("t (num_heads*head_dim)[tp]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + assert isinstance(plans[0].params, ConcatParams) + assert plans[0].params.dim_name == "num_heads___head_dim" + assert plans[0].groups == [[0, 1]] + + def test_fused_dim_modifier_on_second_sub(self) -> None: + """Modifier on fused dim: "(a*b)[tp]" should produce concat plan.""" + dim_specs = parse_dims("t (a*b)[tp]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + assert isinstance(plans[0].params, ConcatParams) + assert plans[0].params.dim_name == "a___b" + + def test_fused_dim_no_modifier(self) -> None: + """Fused dim without modifier + explicit replicated TP → PickParams.""" + dim_specs = parse_dims("t (a*b) # tp:replicated").dims + replicated = frozenset({ParallelAxis.TP}) + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + assert len(plans) == 1 + assert isinstance(plans[0].params, PickParams) + + def test_fused_dim_with_reduction(self) -> None: + """Fused dim with partial reduction: "(a*b)[tp:partial]".""" + dim_specs = parse_dims("t (a*b)[tp:partial]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan(dim_specs, parallel_infos) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + assert isinstance(plans[0].params, ReduceSumParams) + + +class TestAxisContainment: + def test_tp_replicated_auto_resolves_dependent_axes(self) -> None: + """tp:replicated + attn_tp/moe_tp active but undeclared → no error, correct pick.""" + dim_specs = parse_dims("t h # tp:replicated").dims + replicated = frozenset({ParallelAxis.TP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + assert isinstance(plans[0].params, PickParams) + assert plans[0].groups == [[0, 1, 2, 3]] + + def test_independent_axis_still_requires_declaration(self) -> None: + """cp independent of tp → cp undeclared still raises.""" + dim_specs = parse_dims("t h # tp:replicated").dims + replicated = frozenset({ParallelAxis.TP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="cp.*not declared"): + compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + def test_backward_compat_explicit_children(self) -> None: + """Both tp:replicated and attn_tp:replicated → ValueError (not orthogonal).""" + dim_specs = parse_dims( + "t h # tp:replicated attn_tp:replicated moe_tp:replicated" + ).dims + replicated = frozenset( + {ParallelAxis.TP, ParallelAxis.ATTN_TP, ParallelAxis.MOE_TP} + ) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="not orthogonal"): + compute_unsharder_plan( + dim_specs, parallel_infos, explicit_replicated_axes=replicated + ) + + +class TestDpFilteredAxis: + """Tests for dp_filtered_axis parameter: DP axis handled by upstream DP filter + should be excluded from unsharder validation.""" + + def test_dp_filtered_skips_undeclared_error(self) -> None: + """DP active but dp_filtered_axis=DP → no error, no DP plan produced.""" + dim_specs = parse_dims("b h d").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + {ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2)}, + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP + ) + assert plans == [] + + def test_dp_filtered_with_sharded_tp(self) -> None: + """DP2 + TP2, dims='t h[tp]', dp_filtered_axis=DP → only TP concat plan.""" + dim_specs = parse_dims("t h[tp]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP + ) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + assert isinstance(plans[0].params, ConcatParams) + + def test_dp_filtered_with_replicated_tp(self) -> None: + """DP2 + TP2, dims='b h # tp:replicated', dp_filtered_axis=DP → only TP pick plan.""" + dim_specs = parse_dims("b h # tp:replicated").dims + replicated = frozenset({ParallelAxis.TP}) + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + plans = compute_unsharder_plan( + dim_specs, + parallel_infos, + explicit_replicated_axes=replicated, + dp_filtered_axis=ParallelAxis.DP, + ) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + assert isinstance(plans[0].params, PickParams) + + def test_dp_filtered_does_not_affect_other_undeclared(self) -> None: + """DP filtered + EP active but undeclared (independent of TP) → still raises for EP.""" + dim_specs = parse_dims("t h[tp]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + for tp_rank in range(2) + for ep_rank in range(2) + ] + with pytest.raises(ValueError, match="ep.*not declared"): + compute_unsharder_plan( + dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP + ) + + def test_dp_filtered_none_still_raises_for_undeclared_dp(self) -> None: + """Default dp_filtered_axis=None, DP active but undeclared (independent of TP) → raises.""" + dim_specs = parse_dims("t h[tp]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.DP: AxisInfo(axis_rank=dp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + for tp_rank in range(2) + for dp_rank in range(2) + ] + with pytest.raises(ValueError, match="dp.*not declared"): + compute_unsharder_plan(dim_specs, parallel_infos) + + def test_dp_filtered_custom_alias(self) -> None: + """dp_filtered_axis=MOE_DP (custom alias) skips undeclared error for moe_dp.""" + dim_specs = parse_dims("t h[tp]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.MOE_DP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.MOE_DP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.MOE_DP + ) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + + def test_dp_filtered_not_in_parallel_infos_is_harmless(self) -> None: + """dp_filtered_axis=DP but DP not in parallel_infos → no error, no effect.""" + dim_specs = parse_dims("t h[tp]").dims + parallel_infos = [ + {ParallelAxis.TP: AxisInfo(axis_rank=i, axis_size=2)} for i in range(2) + ] + plans = compute_unsharder_plan( + dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP + ) + + assert len(plans) == 1 + assert plans[0].axis == ParallelAxis.TP + + def test_dp_filtered_with_multi_axis_sharding(self) -> None: + """DP2 + TP2 + CP2, dims='s[cp] h[tp]', dp_filtered_axis=DP → CP+TP plans only.""" + dim_specs = parse_dims("s[cp] h[tp]").dims + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for tp_rank in range(2): + parallel_infos.append( + { + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + } + ) + plans = compute_unsharder_plan( + dim_specs, parallel_infos, dp_filtered_axis=ParallelAxis.DP + ) + + assert len(plans) == 2 + assert plans[0].axis == ParallelAxis.CP + assert plans[1].axis == ParallelAxis.TP + + +class TestIsDependentAxis: + def test_child_determined_by_parent(self) -> None: + """attn_tp uniquely determined by tp → dependent.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert _is_dependent_axis( + parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.ATTN_TP + ) + + def test_child_not_determined_by_parent(self) -> None: + """dp varies independently of tp → not dependent.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert not _is_dependent_axis( + parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.DP + ) + + def test_parent_absent_from_all_infos(self) -> None: + """Parent axis not in any info → vacuously True.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + {ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2)}, + {ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2)}, + ] + assert _is_dependent_axis( + parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.DP + ) + + def test_child_absent_from_all_infos(self) -> None: + """Child axis not in any info → vacuously True.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)}, + ] + assert _is_dependent_axis( + parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.DP + ) + + def test_single_info_always_dependent(self) -> None: + """With one info entry, any pair is trivially dependent.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + assert _is_dependent_axis( + parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.DP + ) + + def test_child_missing_from_some_infos_but_consistent(self) -> None: + """Child absent from some infos but consistent where present → dependent.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + # ATTN_TP absent here + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + assert _is_dependent_axis( + parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.ATTN_TP + ) + + def test_empty_parallel_infos(self) -> None: + """No infos → vacuously True.""" + assert _is_dependent_axis( + [], parent=ParallelAxis.TP, child=ParallelAxis.ATTN_TP + ) + + def test_same_parent_rank_different_child_ranks(self) -> None: + """Explicit conflict: parent_rank=0 maps to child_rank=0 and child_rank=1.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert not _is_dependent_axis( + parallel_infos, parent=ParallelAxis.TP, child=ParallelAxis.ATTN_TP + ) + + +class TestComputeDependentAxes: + def test_dependent_child_found(self) -> None: + """parent={TP}, candidate={ETP}, etp depends on tp → returns {ETP}.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.ETP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.ETP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + result = _compute_dependent_axes( + parent_axes={ParallelAxis.TP}, + candidate_axes={ParallelAxis.ETP}, + parallel_infos=parallel_infos, + ) + assert result == frozenset({ParallelAxis.ETP}) + + def test_independent_child_not_found(self) -> None: + """parent={TP}, candidate={CP}, cp independent → returns empty.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + result = _compute_dependent_axes( + parent_axes={ParallelAxis.TP}, + candidate_axes={ParallelAxis.CP}, + parallel_infos=parallel_infos, + ) + assert result == frozenset() + + def test_multiple_parents(self) -> None: + """parent={TP, EP}, candidate={ETP, MOE_EP}, both dependent → returns both.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.ETP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_EP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.ETP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_EP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.ETP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_EP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.ETP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_EP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + result = _compute_dependent_axes( + parent_axes={ParallelAxis.TP, ParallelAxis.EP}, + candidate_axes={ParallelAxis.ETP, ParallelAxis.MOE_EP}, + parallel_infos=parallel_infos, + ) + assert result == frozenset({ParallelAxis.ETP, ParallelAxis.MOE_EP}) + + +class TestValidateExplicitReplicated: + def test_valid_all_axes_declared(self) -> None: + """All axes declared as sharded or replicated → no error.""" + _validate_explicit_replicated( + explicit_replicated_axes=frozenset({ParallelAxis.CP}), + sharded_axes={ParallelAxis.TP}, + all_axes={ParallelAxis.TP, ParallelAxis.CP}, + parallel_infos=[ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + }, + ], + ) + + def test_replicated_not_in_all_axes_raises(self) -> None: + """Declaring replicated axis absent from all_axes → ValueError.""" + with pytest.raises(ValueError, match="not found in parallel_infos"): + _validate_explicit_replicated( + explicit_replicated_axes=frozenset({ParallelAxis.EP}), + sharded_axes={ParallelAxis.TP}, + all_axes={ParallelAxis.TP}, + parallel_infos=[ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)}, + ], + ) + + def test_replicated_conflicts_with_sharded_raises(self) -> None: + """Same axis declared sharded and replicated → ValueError.""" + with pytest.raises(ValueError, match="both sharded and replicated"): + _validate_explicit_replicated( + explicit_replicated_axes=frozenset({ParallelAxis.TP}), + sharded_axes={ParallelAxis.TP}, + all_axes={ParallelAxis.TP}, + parallel_infos=[ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)}, + ], + ) + + def test_undeclared_active_axis_raises(self) -> None: + """Active axis not sharded/replicated/implicitly_replicated → ValueError.""" + with pytest.raises(ValueError, match="dp.*not declared"): + _validate_explicit_replicated( + explicit_replicated_axes=frozenset({ParallelAxis.TP}), + sharded_axes=set(), + all_axes={ParallelAxis.TP, ParallelAxis.DP}, + parallel_infos=[ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2), + }, + ], + ) + + def test_dependent_child_implicitly_replicated(self) -> None: + """Child axis dependent on replicated parent → no error (implicitly replicated).""" + _validate_explicit_replicated( + explicit_replicated_axes=frozenset({ParallelAxis.TP}), + sharded_axes=set(), + all_axes={ParallelAxis.TP, ParallelAxis.ATTN_TP, ParallelAxis.MOE_TP}, + parallel_infos=[ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ], + ) + + def test_dp_filtered_axis_excluded_from_undeclared(self) -> None: + """dp_filtered_axis is exempt from undeclared check.""" + _validate_explicit_replicated( + explicit_replicated_axes=frozenset(), + sharded_axes={ParallelAxis.TP}, + all_axes={ParallelAxis.TP, ParallelAxis.DP}, + parallel_infos=[ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + }, + ], + dp_filtered_axis=ParallelAxis.DP, + ) + + def test_dp_filtered_does_not_exempt_other_axes(self) -> None: + """dp_filtered_axis=DP, but EP still undeclared (independent of TP) → raises.""" + with pytest.raises(ValueError, match="ep.*not declared"): + _validate_explicit_replicated( + explicit_replicated_axes=frozenset(), + sharded_axes={ParallelAxis.TP}, + all_axes={ParallelAxis.TP, ParallelAxis.DP, ParallelAxis.EP}, + parallel_infos=[ + { + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2), + } + for tp_rank in range(2) + for ep_rank in range(2) + ], + dp_filtered_axis=ParallelAxis.DP, + ) + + def test_independent_child_not_implicitly_replicated(self) -> None: + """Child axis independent of replicated parent → still raises.""" + with pytest.raises(ValueError, match="dp.*not declared"): + _validate_explicit_replicated( + explicit_replicated_axes=frozenset({ParallelAxis.TP}), + sharded_axes=set(), + all_axes={ParallelAxis.TP, ParallelAxis.DP}, + parallel_infos=[ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=1, axis_size=2), + }, + ], + ) + + def test_sharded_axis_determines_undeclared_implicitly_sharded(self) -> None: + """TP sharded, ETP dependent on TP → no error (implicitly sharded).""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for tp_rank in range(2): + for ep_rank in range(2): + parallel_infos.append( + { + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + ParallelAxis.ETP: AxisInfo(axis_rank=tp_rank, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=ep_rank, axis_size=2), + } + ) + _validate_explicit_replicated( + explicit_replicated_axes=frozenset({ParallelAxis.EP}), + sharded_axes={ParallelAxis.TP}, + all_axes={ParallelAxis.TP, ParallelAxis.ETP, ParallelAxis.EP}, + parallel_infos=parallel_infos, + ) + + def test_sharded_axis_does_not_resolve_independent_child(self) -> None: + """TP sharded, CP active but independent of TP → still raises.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="cp.*not declared"): + _validate_explicit_replicated( + explicit_replicated_axes=frozenset(), + sharded_axes={ParallelAxis.TP}, + all_axes={ParallelAxis.TP, ParallelAxis.CP}, + parallel_infos=parallel_infos, + ) + + def test_no_axes_at_all(self) -> None: + """Empty axes sets → no error.""" + _validate_explicit_replicated( + explicit_replicated_axes=frozenset(), + sharded_axes=set(), + all_axes=set(), + parallel_infos=[{}], + ) + + def test_jointly_determined_axis_passes(self) -> None: + """EDP determined by (TP, CP) jointly but not by either alone → no error. + + Simulates tp=2, cp=2, ep=1, etp=1 on 4 GPUs where edp_size=4 + and edp_rank = unique per (tp_rank, cp_rank) combination. + """ + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=3, axis_size=4), + }, + ] + _validate_explicit_replicated( + explicit_replicated_axes=frozenset({ParallelAxis.TP}), + sharded_axes={ParallelAxis.CP, ParallelAxis.SP}, + all_axes={ + ParallelAxis.TP, + ParallelAxis.CP, + ParallelAxis.SP, + ParallelAxis.EDP, + }, + parallel_infos=parallel_infos, + ) + + def test_jointly_undetermined_axis_still_raises(self) -> None: + """Axis not determined even by the combination of all declared axes → raises. + + DP is orthogonal to TP (each TP rank pairs with both DP ranks), + so (TP,) cannot determine DP. + """ + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=dp_rank, axis_size=2), + } + for tp_rank in range(2) + for dp_rank in range(2) + ] + with pytest.raises(ValueError, match="dp.*not declared"): + _validate_explicit_replicated( + explicit_replicated_axes=frozenset(), + sharded_axes={ParallelAxis.TP}, + all_axes={ParallelAxis.TP, ParallelAxis.DP}, + parallel_infos=parallel_infos, + ) + + +class TestIsJointlyDetermined: + def test_edp_determined_by_tp_and_cp(self) -> None: + """EDP rank = unique per (TP, CP) combination → True.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=3, axis_size=4), + }, + ] + assert _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_dp_not_determined_by_tp_alone(self) -> None: + """DP is orthogonal to TP → False.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=2), + ParallelAxis.DP: AxisInfo(axis_rank=dp_rank, axis_size=2), + } + for tp_rank in range(2) + for dp_rank in range(2) + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP}), + child=ParallelAxis.DP, + ) + + def test_empty_parallel_infos_returns_false(self) -> None: + """No parallel_info entries → False (no evidence).""" + assert not _is_jointly_determined( + [], + parent_axes=frozenset({ParallelAxis.TP}), + child=ParallelAxis.EDP, + ) + + def test_child_absent_from_infos_returns_false(self) -> None: + """Child axis not present in any info → False.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)}, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP}), + child=ParallelAxis.EDP, + ) + + def test_empty_parent_axes_returns_false(self) -> None: + """Empty parent_axes → False (no parents to determine child).""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset(), + child=ParallelAxis.EDP, + ) + + def test_single_parent_determines_child(self) -> None: + """Single parent tp_rank uniquely maps to edp_rank → True (degenerate joint case).""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP}), + child=ParallelAxis.EDP, + ) + + def test_conflict_returns_false(self) -> None: + """Same (tp_rank, cp_rank) maps to different edp_rank → False.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4), + }, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_two_parents_jointly_determine_child(self) -> None: + """(tp_rank, cp_rank) tuple uniquely determines edp_rank → True.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=3, axis_size=4), + }, + ] + assert _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_three_parents_jointly_determine_child(self) -> None: + """(tp, cp, ep) triple uniquely determines edp → True.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=tp, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=cp, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=ep, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=tp * 4 + cp * 2 + ep, axis_size=8), + } + for tp in range(2) + for cp in range(2) + for ep in range(2) + ] + assert _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP, ParallelAxis.EP}), + child=ParallelAxis.EDP, + ) + + def test_parent_partially_absent_causes_ambiguity(self) -> None: + """Some infos lack a parent axis → False, even if child values differ. + + When cp is missing from some infos, the joint determination is + incomplete because we cannot construct a full parent key. + """ + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=4), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + # cp absent — parent key is incomplete + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=4), + }, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_partial_parent_first_info_missing_returns_false(self) -> None: + """First info lacks a parent axis; second info has all parents → False.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + # cp absent + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_universally_absent_parent_ignored_remaining_determines(self) -> None: + """Parent axis absent from ALL infos is ignored; remaining parent determines child → True. + + Models the real scenario where DP (size 1) is in declared_axes but + filtered out of all parallel_infos by normalize_parallel_info. + """ + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_all_parents_universally_absent_returns_false(self) -> None: + """Every parent axis absent from ALL infos → no active parents → False.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_universally_absent_parent_remaining_conflict_returns_false(self) -> None: + """Parent axis absent from ALL infos ignored, but remaining parent has conflict → False.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_partial_parent_matching_child_still_returns_false(self) -> None: + """Even when child values match across infos, incomplete parent → False. + + Ensures the check is about parent completeness, not child conflict. + """ + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + # cp absent — but edp_rank is SAME as first info + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_many_infos_consistent_joint_mapping(self) -> None: + """8 ranks with (tp, cp) consistently mapping to edp → True.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=tp, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=cp, axis_size=2), + ParallelAxis.EP: AxisInfo(axis_rank=ep, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=tp * 2 + cp, axis_size=4), + } + for tp in range(2) + for cp in range(2) + for ep in range(2) + ] + assert _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_partial_parent_middle_info_missing_returns_false(self) -> None: + """Middle info in a 3-info list lacks a parent → False.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=3), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + # cp absent + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=3), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=2, axis_size=3), + }, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_child_absent_from_some_infos_still_true(self) -> None: + """Child absent from some infos but consistent where present → True. + + Infos without the child are skipped; no parent completeness issue. + """ + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + # edp absent — this info is skipped + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_child_absent_from_all_infos_returns_false(self) -> None: + """Child not present in any info → mapping is empty → False.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)}, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP}), + child=ParallelAxis.CP, + ) + + def test_parent_present_in_some_but_missing_with_child_returns_false(self) -> None: + """Parent present in some infos but absent in an info that has child. + + This is the potential false-positive scenario: an info has child but + not all active parents, so the parent key cannot be fully constructed. + """ + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + # TP present in first info so it's active, but absent here + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.EDP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + assert not _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + child=ParallelAxis.EDP, + ) + + def test_single_info_with_all_axes_returns_true(self) -> None: + """Single info entry with parent and child → trivially determined → True.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=1), + ParallelAxis.EDP: AxisInfo(axis_rank=0, axis_size=1), + }, + ] + assert _is_jointly_determined( + parallel_infos, + parent_axes=frozenset({ParallelAxis.TP}), + child=ParallelAxis.EDP, + ) + + +class TestReplicatedAxesOrthogonality: + """Tests for _validate_replicated_axes_orthogonal: every pair of explicitly + replicated axes must be fully orthogonal (no dependency relationship).""" + + def test_tp_determines_moe_tp_raises(self) -> None: + """TP4 + MOE_TP2 where tp_rank determines moe_tp_rank → ValueError.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="not orthogonal"): + _validate_replicated_axes_orthogonal( + explicit_replicated_axes=frozenset( + {ParallelAxis.TP, ParallelAxis.MOE_TP} + ), + parallel_infos=parallel_infos, + ) + + def test_tp_determines_sp_identical_group_raises(self) -> None: + """TP2 + SP2 where sp_rank == tp_rank → ValueError.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.SP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="not orthogonal"): + _validate_replicated_axes_orthogonal( + explicit_replicated_axes=frozenset({ParallelAxis.TP, ParallelAxis.SP}), + parallel_infos=parallel_infos, + ) + + def test_three_axes_two_overlapping_pairs_raises(self) -> None: + """TP4 + ATTN_TP2 + MOE_TP2, TP determines both → error mentions two pairs.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=2, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=3, axis_size=4), + ParallelAxis.ATTN_TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.MOE_TP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + with pytest.raises(ValueError, match="not orthogonal") as exc_info: + _validate_replicated_axes_orthogonal( + explicit_replicated_axes=frozenset( + {ParallelAxis.TP, ParallelAxis.ATTN_TP, ParallelAxis.MOE_TP} + ), + parallel_infos=parallel_infos, + ) + msg = str(exc_info.value) + assert "attn_tp" in msg + assert "moe_tp" in msg + + def test_three_axes_one_overlap_one_orthogonal_raises(self) -> None: + """TP4 + MOE_TP2 (dependent) + CP2 (independent) → only tp/moe_tp pair errors.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [] + for cp_rank in range(2): + for tp_rank in range(4): + parallel_infos.append( + { + ParallelAxis.TP: AxisInfo(axis_rank=tp_rank, axis_size=4), + ParallelAxis.MOE_TP: AxisInfo( + axis_rank=tp_rank % 2, axis_size=2 + ), + ParallelAxis.CP: AxisInfo(axis_rank=cp_rank, axis_size=2), + } + ) + with pytest.raises(ValueError, match="not orthogonal") as exc_info: + _validate_replicated_axes_orthogonal( + explicit_replicated_axes=frozenset( + {ParallelAxis.TP, ParallelAxis.MOE_TP, ParallelAxis.CP} + ), + parallel_infos=parallel_infos, + ) + msg = str(exc_info.value) + assert "moe_tp" in msg + assert "cp" not in msg + + def test_single_replicated_axis_no_check(self) -> None: + """Only one replicated axis → no orthogonality check needed, passes.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + {ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2)}, + {ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2)}, + ] + _validate_replicated_axes_orthogonal( + explicit_replicated_axes=frozenset({ParallelAxis.TP}), + parallel_infos=parallel_infos, + ) + + def test_two_independent_axes_ok(self) -> None: + """TP2 + CP2 fully orthogonal → no error.""" + parallel_infos: list[dict[ParallelAxis, AxisInfo]] = [ + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=0, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=0, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + }, + { + ParallelAxis.TP: AxisInfo(axis_rank=1, axis_size=2), + ParallelAxis.CP: AxisInfo(axis_rank=1, axis_size=2), + }, + ] + _validate_replicated_axes_orthogonal( + explicit_replicated_axes=frozenset({ParallelAxis.TP, ParallelAxis.CP}), + parallel_infos=parallel_infos, + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/conftest.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..52b76cab5b3d166555f8f3963b5fcb88788e0116 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/conftest.py @@ -0,0 +1,40 @@ +import sys +import warnings +from pathlib import Path + +warnings.filterwarnings( + "ignore", message="builtin type Swig.*", category=DeprecationWarning +) + +# Add the test root to sys.path so `registered.debug_utils.comparator.testing_helpers` +# can be imported by test modules. +_TEST_ROOT: Path = Path(__file__).resolve().parents[3] +if str(_TEST_ROOT) not in sys.path: + sys.path.insert(0, str(_TEST_ROOT)) + +import pytest + +from sglang.srt.debug_utils.comparator.report_sink import report_sink + +collect_ignore_glob: list[str] = [] + + +def pytest_configure(config: pytest.Config) -> None: + config.addinivalue_line( + "filterwarnings", + "ignore:Unknown config option. asyncio_mode:pytest.PytestConfigWarning", + ) + config.addinivalue_line( + "filterwarnings", + "ignore:builtin type Swig.*:DeprecationWarning", + ) + config.addinivalue_line( + "filterwarnings", + "ignore:Named tensors and all their associated APIs:UserWarning", + ) + + +@pytest.fixture(autouse=True) +def _reset_report_sink() -> None: + yield + report_sink._reset() diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/__init__.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dim_parser.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dim_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef9f7f5062222aa236523ba99bd79dbeea6ba98 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dim_parser.py @@ -0,0 +1,152 @@ +import sys + +import pytest + +from sglang.srt.debug_utils.comparator.dims_spec import ( + DimSpec, + Ordering, + ParallelAxis, + ParallelModifier, + Reduction, + parse_dim, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestParseDim: + def test_plain_name(self) -> None: + assert parse_dim("b") == DimSpec(name="b") + + def test_parallel_axis(self) -> None: + assert parse_dim("h[tp]") == DimSpec( + name="h", + parallel_modifiers=[ParallelModifier(axis=ParallelAxis.TP)], + ) + + def test_all_parallel_axes(self) -> None: + assert parse_dim("a[tp]").parallel_modifiers[0].axis == ParallelAxis.TP + assert parse_dim("a[cp]").parallel_modifiers[0].axis == ParallelAxis.CP + assert parse_dim("a[ep]").parallel_modifiers[0].axis == ParallelAxis.EP + assert parse_dim("a[sp]").parallel_modifiers[0].axis == ParallelAxis.SP + + def test_ordering(self) -> None: + assert ( + parse_dim("s[cp:zigzag]").parallel_modifiers[0].ordering == Ordering.ZIGZAG + ) + assert ( + parse_dim("s[cp:natural]").parallel_modifiers[0].ordering + == Ordering.NATURAL + ) + + def test_reduction(self) -> None: + assert ( + parse_dim("h[tp:partial]").parallel_modifiers[0].reduction + == Reduction.PARTIAL + ) + + def test_all_qualifiers(self) -> None: + assert parse_dim("s[cp:zigzag+partial]") == DimSpec( + name="s", + parallel_modifiers=[ + ParallelModifier( + axis=ParallelAxis.CP, + ordering=Ordering.ZIGZAG, + reduction=Reduction.PARTIAL, + ), + ], + ) + + def test_multi_axis(self) -> None: + result: DimSpec = parse_dim("t[cp:zigzag,sp]") + assert result.name == "t" + assert len(result.parallel_modifiers) == 2 + assert result.parallel_modifiers[0] == ParallelModifier( + axis=ParallelAxis.CP, ordering=Ordering.ZIGZAG + ) + assert result.parallel_modifiers[1] == ParallelModifier(axis=ParallelAxis.SP) + + def test_invalid_token_raises(self) -> None: + with pytest.raises(ValueError, match="Invalid dim token"): + parse_dim("h[]") + with pytest.raises(ValueError, match="Invalid dim token"): + parse_dim("h[tp[x]]") + + def test_unknown_axis_raises(self) -> None: + with pytest.raises(ValueError, match="Unknown axis"): + parse_dim("h[xyz]") + + def test_unknown_qualifier_raises(self) -> None: + with pytest.raises(ValueError, match="Unknown qualifier"): + parse_dim("h[tp:foobar]") + + def test_multiple_ordering_raises(self) -> None: + with pytest.raises(ValueError, match="Multiple ordering"): + parse_dim("s[cp:zigzag+natural]") + + def test_multiple_reduction_raises(self) -> None: + with pytest.raises(ValueError, match="Multiple reduction"): + parse_dim("h[tp:partial+partial]") + + def test_duplicate_axis_raises(self) -> None: + with pytest.raises(ValueError, match="Duplicate axis"): + parse_dim("h[tp,tp]") + + def test_squeeze_dim(self) -> None: + assert parse_dim("1") == DimSpec(name="1") + + def test_squeeze_dim_rejects_modifiers(self) -> None: + with pytest.raises(ValueError, match="Invalid dim token"): + parse_dim("1[tp]") + + +class TestParseFusedDim: + def test_basic_fused(self) -> None: + result: DimSpec = parse_dim("(num_heads*head_dim)") + assert result.name == "num_heads*head_dim" + assert result.parallel_modifiers == [] + assert result.is_fused + assert result.sub_dims == ["num_heads", "head_dim"] + + def test_fused_with_modifier(self) -> None: + result: DimSpec = parse_dim("(num_heads*head_dim)[tp]") + assert result.name == "num_heads*head_dim" + assert result.parallel_modifiers == [ParallelModifier(axis=ParallelAxis.TP)] + assert result.sub_dims == ["num_heads", "head_dim"] + + def test_three_way_fused(self) -> None: + result: DimSpec = parse_dim("(a*b*c)") + assert result.name == "a*b*c" + assert len(result.sub_dims) == 3 + assert result.sub_dims == ["a", "b", "c"] + + def test_three_way_fused_with_modifier(self) -> None: + result: DimSpec = parse_dim("(a*b*c)[tp]") + assert result.parallel_modifiers == [ParallelModifier(axis=ParallelAxis.TP)] + assert len(result.sub_dims) == 3 + + def test_fused_with_complex_modifier(self) -> None: + result: DimSpec = parse_dim("(a*b)[cp:zigzag]") + assert result.parallel_modifiers == [ + ParallelModifier(axis=ParallelAxis.CP, ordering=Ordering.ZIGZAG) + ] + assert result.sub_dims == ["a", "b"] + + def test_regular_dim_not_fused(self) -> None: + result: DimSpec = parse_dim("h[tp]") + assert not result.is_fused + assert result.sub_dims == ["h"] + + def test_fused_duplicate_sub_names_raises(self) -> None: + with pytest.raises(ValueError, match="Duplicate sub-dim"): + parse_dim("(a*a)") + + def test_fused_invalid_sub_dim_raises(self) -> None: + with pytest.raises(ValueError, match="Invalid sub-dim"): + parse_dim("(a*1)") + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dims_parser.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dims_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..15490f82eb168a97a41619abc4b64464edeca739 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_dims_parser.py @@ -0,0 +1,295 @@ +import sys + +import pytest + +from sglang.srt.debug_utils.comparator.dims_spec import ( + SQUEEZE_DIM_NAME, + DimSpec, + DimsSpec, + Ordering, + ParallelAxis, + ParallelModifier, + _SingletonDimUtil, + parse_dims, + resolve_dim_names, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestSingletonDimUtilFilterOut: + def test_no_squeeze(self) -> None: + specs: list[DimSpec] = parse_dims("t h d").dims + assert _SingletonDimUtil.filter_out(specs) == specs + + def test_with_squeeze(self) -> None: + specs: list[DimSpec] = parse_dims("t 1 h").dims + filtered: list[DimSpec] = _SingletonDimUtil.filter_out(specs) + assert len(filtered) == 2 + assert filtered[0].name == "t" + assert filtered[1].name == "h" + + def test_all_squeeze(self) -> None: + specs: list[DimSpec] = parse_dims("1 1").dims + assert _SingletonDimUtil.filter_out(specs) == [] + + +class TestSingletonDimUtilIsSqueeze: + def test_squeeze(self) -> None: + assert _SingletonDimUtil.is_squeeze(DimSpec(name=SQUEEZE_DIM_NAME)) is True + + def test_non_squeeze(self) -> None: + assert _SingletonDimUtil.is_squeeze(DimSpec(name="t")) is False + + +class TestSingletonDimUtilMakeName: + def test_indices(self) -> None: + assert _SingletonDimUtil.make_name(0) == "singleton0" + assert _SingletonDimUtil.make_name(1) == "singleton1" + assert _SingletonDimUtil.make_name(99) == "singleton99" + + +class TestSingletonDimUtilSanitizeNames: + def test_no_squeeze(self) -> None: + assert _SingletonDimUtil.sanitize_names(["t", "h", "d"]) == ["t", "h", "d"] + + def test_single_squeeze(self) -> None: + assert _SingletonDimUtil.sanitize_names(["t", "1", "h"]) == [ + "t", + "singleton0", + "h", + ] + + def test_multiple_squeeze(self) -> None: + assert _SingletonDimUtil.sanitize_names(["1", "t", "1", "h"]) == [ + "singleton0", + "t", + "singleton1", + "h", + ] + + def test_empty(self) -> None: + assert _SingletonDimUtil.sanitize_names([]) == [] + + +class TestParseDims: + def test_multi_dims(self) -> None: + assert parse_dims("b s h d").dims == [ + DimSpec(name="b"), + DimSpec(name="s"), + DimSpec(name="h"), + DimSpec(name="d"), + ] + + def test_single_dim(self) -> None: + assert parse_dims("t").dims == [DimSpec(name="t")] + + def test_mixed_annotated(self) -> None: + assert parse_dims("b s[cp:zigzag] h[tp] d").dims == [ + DimSpec(name="b"), + DimSpec( + name="s", + parallel_modifiers=[ + ParallelModifier(axis=ParallelAxis.CP, ordering=Ordering.ZIGZAG), + ], + ), + DimSpec( + name="h", + parallel_modifiers=[ParallelModifier(axis=ParallelAxis.TP)], + ), + DimSpec(name="d"), + ] + + def test_empty_string_raises(self) -> None: + with pytest.raises(ValueError, match="empty"): + parse_dims("") + + def test_whitespace_only_raises(self) -> None: + with pytest.raises(ValueError, match="empty"): + parse_dims(" ") + + def test_duplicate_name_raises(self) -> None: + with pytest.raises(ValueError, match="Duplicate"): + parse_dims("h h") + + def test_with_squeeze_dims(self) -> None: + dims: list[DimSpec] = parse_dims("t 1 h").dims + assert len(dims) == 3 + assert dims[0] == DimSpec(name="t") + assert dims[1] == DimSpec(name="1") + assert dims[2] == DimSpec(name="h") + + def test_multiple_squeeze_dims_no_duplicate_error(self) -> None: + dims: list[DimSpec] = parse_dims("t 1 h 1 d").dims + assert len(dims) == 5 + assert dims[1] == DimSpec(name="1") + assert dims[3] == DimSpec(name="1") + + +class TestParseDimsWithFused: + def test_fused_in_dims(self) -> None: + result: DimsSpec = parse_dims("t (num_heads*head_dim)[tp]") + assert len(result.dims) == 2 + assert result.dims[0] == DimSpec(name="t") + assert result.dims[1].is_fused + assert result.dims[1].name == "num_heads*head_dim" + + def test_fused_and_regular_mixed(self) -> None: + result: DimsSpec = parse_dims("t (num_heads*head_dim)[tp] d") + assert len(result.dims) == 3 + assert not result.dims[0].is_fused + assert result.dims[1].is_fused + assert not result.dims[2].is_fused + + def test_fused_sub_name_conflicts_with_regular_raises(self) -> None: + with pytest.raises(ValueError, match="Duplicate"): + parse_dims("t num_heads (num_heads*head_dim)") + + def test_multiple_fused_dims(self) -> None: + result: DimsSpec = parse_dims("(a*b) (c*d)") + assert len(result.dims) == 2 + assert result.dims[0].is_fused + assert result.dims[1].is_fused + + def test_cross_fused_duplicate_sub_name_raises(self) -> None: + with pytest.raises(ValueError, match="Duplicate"): + parse_dims("(a*b) (c*a)") + + +class TestParseDimsWithHash: + """parse_dims strips the ``#`` declaration section from dims.""" + + def test_shape_dims_unchanged(self) -> None: + assert parse_dims("b s h[tp] # dp:=moe_dp").dims == parse_dims("b s h[tp]").dims + + def test_dp_group_alias_extracted(self) -> None: + assert parse_dims("b s h[tp] # dp:=moe_dp").dp_group_alias == "moe_dp" + + def test_no_hash_no_alias(self) -> None: + assert parse_dims("b s h[tp]").dp_group_alias is None + + def test_whitespace_around_hash(self) -> None: + assert parse_dims("t h # dp:=foo ").dims == parse_dims("t h").dims + assert parse_dims("t h # dp:=foo ").dp_group_alias == "foo" + + def test_multiple_declarations_picks_dp(self) -> None: + result: DimsSpec = parse_dims("t h[tp] # dp:=moe_dp ep:replicated") + assert result.dims == parse_dims("t h[tp]").dims + assert result.dp_group_alias == "moe_dp" + assert result.replicated_axes == frozenset({ParallelAxis.EP}) + + def test_no_dp_alias_token(self) -> None: + result: DimsSpec = parse_dims("t h[tp] # ep:replicated") + assert result.dp_group_alias is None + assert result.replicated_axes == frozenset({ParallelAxis.EP}) + + +class TestDpGroupAlias: + def test_basic(self) -> None: + assert parse_dims("b s h[tp] # dp:=moe_dp").dp_group_alias == "moe_dp" + + def test_no_hash_returns_none(self) -> None: + assert parse_dims("t h").dp_group_alias is None + + def test_no_dp_alias_token(self) -> None: + assert parse_dims("t h[tp] # ep:replicated").dp_group_alias is None + + def test_multiple_tokens_picks_dp(self) -> None: + assert ( + parse_dims("b s # ep:replicated dp:=custom_dp").dp_group_alias + == "custom_dp" + ) + + +class TestExplicitReplicatedAxes: + def test_single_replicated(self) -> None: + result: DimsSpec = parse_dims("b s h[tp] d # ep:replicated") + assert result.replicated_axes == frozenset({ParallelAxis.EP}) + + def test_explicit_sharded_equivalent(self) -> None: + assert parse_dims("b s h[tp:sharded] d").dims == parse_dims("b s h[tp] d").dims + + def test_multiple_replicated(self) -> None: + result: DimsSpec = parse_dims("b s h[tp] d # ep:replicated cp:replicated") + assert result.replicated_axes == frozenset({ParallelAxis.EP, ParallelAxis.CP}) + + def test_dp_alias_and_replicated_coexist(self) -> None: + result: DimsSpec = parse_dims("b s h[tp] d # dp:=moe_dp ep:replicated") + assert result.dp_group_alias == "moe_dp" + assert result.replicated_axes == frozenset({ParallelAxis.EP}) + + def test_no_hash_replicated_empty(self) -> None: + result: DimsSpec = parse_dims("b s h[tp] d") + assert result.replicated_axes == frozenset() + + def test_hash_without_replicated(self) -> None: + result: DimsSpec = parse_dims("b s h[tp] d # dp:=moe_dp") + assert result.replicated_axes == frozenset() + + def test_replicated_conflicts_with_sharded_raises(self) -> None: + with pytest.raises(ValueError, match="both sharded.*and replicated"): + parse_dims("b s h[tp] d # tp:replicated") + + def test_unknown_axis_in_replicated_raises(self) -> None: + with pytest.raises(ValueError, match="Unknown axis"): + parse_dims("b s h[tp] d # xyz:replicated") + + def test_duplicate_replicated_declaration_raises(self) -> None: + with pytest.raises(ValueError, match="Duplicate replicated"): + parse_dims("b s h d # ep:replicated ep:replicated") + + def test_unrecognized_token_in_comment_raises(self) -> None: + with pytest.raises(ValueError, match="Unrecognized token"): + parse_dims("b s h[tp] d # ep:replicatd") + + def test_duplicate_dp_alias_raises(self) -> None: + with pytest.raises(ValueError, match="Duplicate dp alias"): + parse_dims("b s h d # dp:=foo dp:=bar") + + +class TestResolveDimNames: + def test_no_squeeze(self) -> None: + assert resolve_dim_names("t h d") == ["t", "h", "d"] + + def test_single_squeeze(self) -> None: + assert resolve_dim_names("t 1 h") == ["t", "singleton0", "h"] + + def test_multiple_squeeze(self) -> None: + assert resolve_dim_names("1 t 1 h") == [ + "singleton0", + "t", + "singleton1", + "h", + ] + + +class TestResolveDimNamesWithFused: + def test_fused_dim_uses_triple_underscore(self) -> None: + assert resolve_dim_names("t (num_heads*head_dim)") == [ + "t", + "num_heads___head_dim", + ] + + def test_fused_with_regular_dims(self) -> None: + assert resolve_dim_names("t (num_heads*head_dim)[tp] d") == [ + "t", + "num_heads___head_dim", + "d", + ] + + def test_three_way_fused(self) -> None: + assert resolve_dim_names("(a*b*c)") == ["a___b___c"] + + def test_fused_with_squeeze(self) -> None: + assert resolve_dim_names("t 1 (a*b)") == ["t", "singleton0", "a___b"] + + +class TestResolveDimNamesWithHash: + def test_hash_stripped(self) -> None: + assert resolve_dim_names("t h # dp:=moe_dp") == ["t", "h"] + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_tensor_naming.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_tensor_naming.py new file mode 100644 index 0000000000000000000000000000000000000000..4e42fdb2011bbda41a199df377ff542b8ae19b92 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_tensor_naming.py @@ -0,0 +1,98 @@ +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.dims_spec import ( + DimSpec, + apply_dim_names, + find_dim_index, + get_dim_names, + parse_dims, + resolve_dim_by_name, + without_dim_names, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestFindDimIndex: + def test_found(self) -> None: + specs: list[DimSpec] = parse_dims("b s h d").dims + assert find_dim_index(specs, "s") == 1 + + def test_not_found(self) -> None: + specs: list[DimSpec] = parse_dims("b s h d").dims + assert find_dim_index(specs, "t") is None + + def test_first_dim(self) -> None: + specs: list[DimSpec] = parse_dims("t h d").dims + assert find_dim_index(specs, "t") == 0 + + def test_last_dim(self) -> None: + specs: list[DimSpec] = parse_dims("b s h d").dims + assert find_dim_index(specs, "d") == 3 + + def test_with_modifiers(self) -> None: + specs: list[DimSpec] = parse_dims("b s[cp:zigzag] h[tp] d").dims + assert find_dim_index(specs, "h") == 2 + + def test_empty_list(self) -> None: + assert find_dim_index([], "t") is None + + +class TestResolveDimByName: + def test_resolve_found(self) -> None: + tensor: torch.Tensor = apply_dim_names(torch.randn(2, 3, 4), ["b", "s", "h"]) + assert resolve_dim_by_name(tensor, "b") == 0 + assert resolve_dim_by_name(tensor, "s") == 1 + assert resolve_dim_by_name(tensor, "h") == 2 + + def test_resolve_not_found_raises(self) -> None: + tensor: torch.Tensor = apply_dim_names(torch.randn(2, 3), ["b", "s"]) + with pytest.raises(ValueError, match="not in tensor names"): + resolve_dim_by_name(tensor, "h") + + def test_resolve_unnamed_raises(self) -> None: + tensor: torch.Tensor = torch.randn(2, 3) + with pytest.raises(ValueError, match="no names"): + resolve_dim_by_name(tensor, "b") + + +class TestApplyDimNames: + def test_apply(self) -> None: + tensor: torch.Tensor = torch.randn(2, 3, 4) + named: torch.Tensor = apply_dim_names(tensor, ["b", "s", "h"]) + assert get_dim_names(named) == ("b", "s", "h") + assert named.shape == (2, 3, 4) + + def test_apply_preserves_data(self) -> None: + tensor: torch.Tensor = torch.randn(2, 3) + named: torch.Tensor = apply_dim_names(tensor, ["x", "y"]) + assert torch.equal(without_dim_names(named), tensor) + + def test_ndim_mismatch_gives_clear_error(self) -> None: + tensor: torch.Tensor = torch.randn(10, 1, 128) + with pytest.raises( + ValueError, + match=r"dims metadata mismatch.*3 dims.*shape \[10, 1, 128\].*2 names \['t', 'num_experts'\].*fix the dims string", + ): + apply_dim_names(tensor, ["t", "num_experts"]) + + +class TestStripDimNames: + def test_strip(self) -> None: + tensor: torch.Tensor = apply_dim_names(torch.randn(2, 3), ["a", "b"]) + stripped: torch.Tensor = without_dim_names(tensor) + assert get_dim_names(stripped) == (None, None) + + def test_strip_already_unnamed(self) -> None: + tensor: torch.Tensor = torch.randn(2, 3) + stripped: torch.Tensor = without_dim_names(tensor) + assert get_dim_names(stripped) == (None, None) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_types.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..47c88c87ac331d85d910bd6576bc4e93bd32e7e4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/dims_spec/test_types.py @@ -0,0 +1,28 @@ +import sys + +import pytest + +from sglang.srt.debug_utils.comparator.dims_spec import ( + BATCH_DIM_NAME, + SEQ_DIM_NAME, + TOKEN_DIM_NAME, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestDimConstants: + def test_token_dim_name(self) -> None: + assert TOKEN_DIM_NAME == "t" + + def test_batch_dim_name(self) -> None: + assert BATCH_DIM_NAME == "b" + + def test_seq_dim_name(self) -> None: + assert SEQ_DIM_NAME == "s" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/__init__.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/conftest.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_comparator.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_comparator.py new file mode 100644 index 0000000000000000000000000000000000000000..288364f7a3abad557d4f501cad38315d076f256f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_comparator.py @@ -0,0 +1,380 @@ +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.tensor_comparator.comparator import ( + QUANTILE_NUMEL_THRESHOLD, + SAMPLE_DIFF_THRESHOLD, + _compute_tensor_stats, + compare_tensor_pair, + compute_diff, + compute_tensor_info, +) +from sglang.srt.debug_utils.comparator.tensor_comparator.types import DiffInfo +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=20, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestComputeTensorInfo: + def test_basic_tensor_returns_correct_shape_and_dtype(self) -> None: + tensor = torch.randn(2, 3) + info = compute_tensor_info(tensor) + assert info.shape == [2, 3] + assert info.dtype == "torch.float32" + assert info.stats.mean == pytest.approx(tensor.float().mean().item(), abs=1e-4) + + def test_include_sample_false_returns_none_sample(self) -> None: + tensor = torch.randn(2, 3) + info = compute_tensor_info(tensor, include_sample=False) + assert info.sample is None + + def test_include_sample_true_returns_string_sample(self) -> None: + tensor = torch.randn(2, 3) + info = compute_tensor_info(tensor, include_sample=True) + assert info.sample is not None + assert isinstance(info.sample, str) + + def test_empty_tensor_stats_are_zero(self) -> None: + tensor = torch.tensor([]) + info = compute_tensor_info(tensor) + assert info.stats.mean == 0.0 + assert info.stats.std == 0.0 + assert info.shape == [0] + + def test_integer_tensor_converted_to_float_for_stats(self) -> None: + """Integer tensors should be cast to float internally for stats computation.""" + tensor = torch.tensor([1, 2, 3, 4], dtype=torch.int32) + info = compute_tensor_info(tensor) + assert info.dtype == "torch.int32" + assert info.stats.mean == pytest.approx(2.5, abs=1e-4) + assert info.stats.min == pytest.approx(1.0, abs=1e-4) + assert info.stats.max == pytest.approx(4.0, abs=1e-4) + + def test_bfloat16_tensor_shape_and_stats(self) -> None: + """bfloat16 tensors produce correct shape and dtype string.""" + tensor = torch.ones(3, 4, dtype=torch.bfloat16) + info = compute_tensor_info(tensor) + assert info.shape == [3, 4] + assert info.dtype == "torch.bfloat16" + assert info.stats.mean == pytest.approx(1.0, abs=1e-2) + + def test_multidimensional_shape(self) -> None: + """Shape is preserved for high-rank tensors.""" + tensor = torch.randn(2, 3, 4, 5) + info = compute_tensor_info(tensor) + assert info.shape == [2, 3, 4, 5] + + def test_scalar_tensor(self) -> None: + """Scalar (0-dim) tensor produces empty shape list.""" + tensor = torch.tensor(3.14) + info = compute_tensor_info(tensor) + assert info.shape == [] + assert info.stats.mean == pytest.approx(3.14, abs=1e-4) + assert info.stats.min == pytest.approx(3.14, abs=1e-4) + assert info.stats.max == pytest.approx(3.14, abs=1e-4) + + def test_include_sample_true_contains_tensor_representation(self) -> None: + """Sample string should contain some recognizable tensor content.""" + tensor = torch.tensor([1.0, 2.0]) + info = compute_tensor_info(tensor, include_sample=True) + assert info.sample is not None + assert "1." in info.sample or "2." in info.sample + + def test_percentiles_present_for_small_tensor(self) -> None: + """Small tensors (< threshold) should have percentile data.""" + tensor = torch.randn(100) + info = compute_tensor_info(tensor) + assert len(info.stats.percentiles) > 0 + assert 50 in info.stats.percentiles + + +class TestComputeTensorInfo: + def test_basic_tensor_returns_correct_shape_and_dtype(self) -> None: + tensor = torch.randn(2, 3) + info = compute_tensor_info(tensor) + assert info.shape == [2, 3] + assert info.dtype == "torch.float32" + assert info.stats.mean == pytest.approx(tensor.float().mean().item(), abs=1e-4) + + def test_include_sample_false_returns_none_sample(self) -> None: + tensor = torch.randn(2, 3) + info = compute_tensor_info(tensor, include_sample=False) + assert info.sample is None + + def test_include_sample_true_returns_string_sample(self) -> None: + tensor = torch.randn(2, 3) + info = compute_tensor_info(tensor, include_sample=True) + assert info.sample is not None + assert isinstance(info.sample, str) + + def test_empty_tensor_stats_are_zero(self) -> None: + tensor = torch.tensor([]) + info = compute_tensor_info(tensor) + assert info.stats.mean == 0.0 + assert info.stats.std == 0.0 + assert info.shape == [0] + + def test_integer_tensor_converted_to_float_for_stats(self) -> None: + """Integer tensors should be cast to float internally for stats computation.""" + tensor = torch.tensor([1, 2, 3, 4], dtype=torch.int32) + info = compute_tensor_info(tensor) + assert info.dtype == "torch.int32" + assert info.stats.mean == pytest.approx(2.5, abs=1e-4) + assert info.stats.min == pytest.approx(1.0, abs=1e-4) + assert info.stats.max == pytest.approx(4.0, abs=1e-4) + + def test_bfloat16_tensor_shape_and_stats(self) -> None: + """bfloat16 tensors produce correct shape and dtype string.""" + tensor = torch.ones(3, 4, dtype=torch.bfloat16) + info = compute_tensor_info(tensor) + assert info.shape == [3, 4] + assert info.dtype == "torch.bfloat16" + assert info.stats.mean == pytest.approx(1.0, abs=1e-2) + + def test_multidimensional_shape(self) -> None: + """Shape is preserved for high-rank tensors.""" + tensor = torch.randn(2, 3, 4, 5) + info = compute_tensor_info(tensor) + assert info.shape == [2, 3, 4, 5] + + def test_scalar_tensor(self) -> None: + """Scalar (0-dim) tensor produces empty shape list.""" + tensor = torch.tensor(3.14) + info = compute_tensor_info(tensor) + assert info.shape == [] + assert info.stats.mean == pytest.approx(3.14, abs=1e-4) + assert info.stats.min == pytest.approx(3.14, abs=1e-4) + assert info.stats.max == pytest.approx(3.14, abs=1e-4) + + def test_include_sample_true_contains_tensor_representation(self) -> None: + """Sample string should contain some recognizable tensor content.""" + tensor = torch.tensor([1.0, 2.0]) + info = compute_tensor_info(tensor, include_sample=True) + assert info.sample is not None + assert "1." in info.sample or "2." in info.sample + + def test_percentiles_present_for_small_tensor(self) -> None: + """Small tensors (< threshold) should have percentile data.""" + tensor = torch.randn(100) + info = compute_tensor_info(tensor) + assert len(info.stats.percentiles) > 0 + assert 50 in info.stats.percentiles + + +class TestComputeTensorStats: + def test_basic_stats(self): + x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0]) + stats = _compute_tensor_stats(x) + + assert stats.mean == pytest.approx(3.0, abs=1e-4) + assert stats.abs_mean == pytest.approx(3.0, abs=1e-4) + assert stats.std == pytest.approx(1.5811, abs=1e-3) + assert stats.min == pytest.approx(1.0, abs=1e-4) + assert stats.max == pytest.approx(5.0, abs=1e-4) + + def test_abs_mean_with_negative_values(self): + x = torch.tensor([-3.0, -1.0, 1.0, 3.0]) + stats = _compute_tensor_stats(x) + + assert stats.mean == pytest.approx(0.0, abs=1e-4) + assert stats.abs_mean == pytest.approx(2.0, abs=1e-4) + + def test_quantile_values(self): + x = torch.linspace(0.0, 100.0, steps=1000) + stats = _compute_tensor_stats(x) + + assert stats.percentiles[1] == pytest.approx(1.0, abs=0.5) + assert stats.percentiles[5] == pytest.approx(5.0, abs=0.5) + assert stats.percentiles[50] == pytest.approx(50.0, abs=0.5) + assert stats.percentiles[95] == pytest.approx(95.0, abs=0.5) + assert stats.percentiles[99] == pytest.approx(99.0, abs=0.5) + + def test_percentiles_exact_for_uniform_range(self): + """Percentiles of arange(0, 101) equal the percentile index exactly (linear interp).""" + x = torch.arange(0, 101, dtype=torch.float32) + stats = _compute_tensor_stats(x) + + for p in (1, 5, 50, 95, 99): + assert stats.percentiles[p] == pytest.approx(float(p), abs=1e-4) + + def test_percentiles_match_torch_quantile_reference(self): + """numpy-based percentiles must match torch.quantile on the same data within tight tolerance.""" + torch.manual_seed(0) + x = torch.randn(5000) + stats = _compute_tensor_stats(x) + + for p in (1, 5, 50, 95, 99): + expected = torch.quantile(x.float(), p / 100.0).item() + assert stats.percentiles[p] == pytest.approx(expected, abs=1e-4) + + def test_large_tensor_skips_quantiles(self): + x = torch.randn(QUANTILE_NUMEL_THRESHOLD + 1) + stats = _compute_tensor_stats(x) + + assert stats.mean is not None + assert stats.percentiles == {} + + +class TestComputeDiff: + def test_identical_tensors(self): + x = torch.ones(10, 10) + diff = compute_diff(x_baseline=x, x_target=x) + + assert diff.rel_diff == pytest.approx(0.0, abs=1e-5) + assert diff.max_abs_diff == pytest.approx(0.0, abs=1e-5) + assert diff.mean_abs_diff == pytest.approx(0.0, abs=1e-5) + assert diff.abs_diff_percentiles[50] == pytest.approx(0.0, abs=1e-5) + assert diff.abs_diff_percentiles[95] == pytest.approx(0.0, abs=1e-5) + assert diff.abs_diff_percentiles[99] == pytest.approx(0.0, abs=1e-5) + assert diff.passed is True + + def test_known_offset(self): + x = torch.ones(10, 10) + y = x.clone() + y[3, 7] = 1.5 + + diff = compute_diff(x_baseline=x, x_target=y) + + assert diff.max_abs_diff == pytest.approx(0.5, abs=1e-4) + assert diff.max_diff_coord == [3, 7] + assert diff.baseline_at_max == pytest.approx(1.0, abs=1e-4) + assert diff.target_at_max == pytest.approx(1.5, abs=1e-4) + assert diff.mean_abs_diff == pytest.approx(0.5 / 100, abs=1e-4) + assert diff.abs_diff_percentiles[1] == pytest.approx(0.0, abs=1e-4) + assert diff.abs_diff_percentiles[50] == pytest.approx(0.0, abs=1e-4) + assert diff.abs_diff_percentiles[99] > 0 + assert diff.passed is False + + def test_large_tensor_skips_diff_quantiles(self): + x = torch.randn(QUANTILE_NUMEL_THRESHOLD + 1) + y = x + 0.001 + diff = compute_diff(x_baseline=x, x_target=y) + + assert diff.abs_diff_percentiles == {} + + def test_rel_diff_value(self): + x = torch.tensor([1.0, 0.0]) + y = torch.tensor([0.0, 1.0]) + diff = compute_diff(x_baseline=x, x_target=y) + + assert diff.rel_diff == pytest.approx(1.0, abs=1e-5) + assert diff.passed is False + + def test_per_token_with_seq_dim(self) -> None: + """seq_dim provided → per_token_rel_diff is list[float].""" + torch.manual_seed(42) + x: torch.Tensor = torch.randn(8, 16) + y: torch.Tensor = x + torch.randn_like(x) * 0.01 + + diff: DiffInfo = compute_diff( + x_baseline=x, x_target=y, diff_threshold=1e-3, seq_dim=0 + ) + + assert diff.per_token_rel_diff is not None + assert isinstance(diff.per_token_rel_diff, list) + assert len(diff.per_token_rel_diff) == 8 + assert all(isinstance(v, float) for v in diff.per_token_rel_diff) + + def test_per_token_without_seq_dim(self) -> None: + """No seq_dim → per_token_rel_diff is None.""" + x: torch.Tensor = torch.randn(8, 16) + y: torch.Tensor = x + torch.randn_like(x) * 0.01 + + diff: DiffInfo = compute_diff(x_baseline=x, x_target=y, diff_threshold=1e-3) + + assert diff.per_token_rel_diff is None + + def test_per_token_json_roundtrip(self) -> None: + """DiffInfo with per_token_rel_diff survives JSON serialization.""" + torch.manual_seed(42) + x: torch.Tensor = torch.randn(4, 8) + y: torch.Tensor = x + torch.randn_like(x) * 0.01 + + diff: DiffInfo = compute_diff( + x_baseline=x, x_target=y, diff_threshold=1e-3, seq_dim=0 + ) + + json_str: str = diff.model_dump_json() + assert "per_token_rel_diff" in json_str + + roundtripped: DiffInfo = DiffInfo.model_validate_json(json_str) + assert roundtripped.per_token_rel_diff is not None + assert len(roundtripped.per_token_rel_diff) == 4 + + +class TestCompareTensors: + def test_normal(self): + x = torch.randn(5, 5) + y = x + torch.randn(5, 5) * 0.001 + + info = compare_tensor_pair(x_baseline=x, x_target=y, name="test") + + assert info.name == "test" + assert info.baseline.shape == [5, 5] + assert info.target.shape == [5, 5] + assert info.shape_mismatch is False + assert info.diff is not None + assert info.diff_downcast is None + + def test_shape_mismatch(self): + x = torch.randn(3, 4) + y = torch.randn(5, 6) + + info = compare_tensor_pair(x_baseline=x, x_target=y, name="mismatch") + + assert info.shape_mismatch is True + assert info.diff is None + + def test_dtype_mismatch(self): + x = torch.randn(5, 5, dtype=torch.float32) + y = torch.randn(5, 5, dtype=torch.bfloat16) + + info = compare_tensor_pair(x_baseline=x, x_target=y, name="dtype_test") + + assert info.shape_mismatch is False + assert info.diff is not None + assert info.diff_downcast is not None + assert info.downcast_dtype == "torch.bfloat16" + + def test_shape_unification(self): + torch.manual_seed(0) + core = torch.randn(4, 8) + x = core.unsqueeze(0).unsqueeze(0) # [1, 1, 4, 8] + y = core.clone() # [4, 8] + + info = compare_tensor_pair(x_baseline=x, x_target=y, name="unify") + + assert info.baseline.shape == [1, 1, 4, 8] + assert info.unified_shape == [4, 8] + assert info.shape_mismatch is False + assert info.diff is not None + assert info.diff.max_abs_diff == pytest.approx(0.0, abs=1e-5) + + def test_sample_generated_when_large_diff(self): + x = torch.zeros(5, 5) + y = torch.ones(5, 5) + + info = compare_tensor_pair(x_baseline=x, x_target=y, name="big_diff") + + assert info.diff is not None + assert info.diff.max_abs_diff > SAMPLE_DIFF_THRESHOLD + assert info.baseline.sample is not None + assert info.target.sample is not None + + def test_no_sample_when_small_diff(self): + x = torch.ones(5, 5) + y = x + 1e-5 + + info = compare_tensor_pair(x_baseline=x, x_target=y, name="tiny_diff") + + assert info.diff is not None + assert info.diff.max_abs_diff < SAMPLE_DIFF_THRESHOLD + assert info.baseline.sample is None + assert info.target.sample is None + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_formatter.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_formatter.py new file mode 100644 index 0000000000000000000000000000000000000000..a64d684ebcb6ea0f88621b8aa3549f836b7bbf17 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_formatter.py @@ -0,0 +1,1113 @@ +import sys + +import pytest +from registered.debug_utils.comparator.testing_helpers import ( + assert_rich_tags_balanced, +) +from registered.debug_utils.comparator.testing_helpers import make_diff as _make_diff +from registered.debug_utils.comparator.testing_helpers import make_stats as _make_stats +from registered.debug_utils.comparator.testing_helpers import ( + make_tensor_info as _make_tensor_info, +) + +from sglang.srt.debug_utils.comparator.aligner.axis_aligner import AxisAlignerPlan +from sglang.srt.debug_utils.comparator.aligner.entrypoint.traced_types import ( + TracedAlignerPlan, + TracedSidePlan, + TracedStepPlan, + TracedSubPlan, +) +from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import ( + AlignerPerStepPlan, + AlignerPlan, +) +from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ( + ReordererPlan, + ZigzagToNaturalParams, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( + TokenAlignerPlan, + TokenLocator, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( + ConcatParams, + UnsharderPlan, +) +from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis, TokenLayout +from sglang.srt.debug_utils.comparator.output_types import ( + BundleFileInfo, + BundleSideInfo, + ComparisonTensorRecord, + ReplicatedCheckResult, + ShapeSnapshot, +) +from sglang.srt.debug_utils.comparator.tensor_comparator.formatter import ( + _format_abs_diff_percentiles_rich, + _format_bundle_section, + _format_plan_section_rich, + _format_stats_rich, + format_comparison, + format_comparison_rich, + format_replicated_checks, +) +from sglang.srt.debug_utils.comparator.tensor_comparator.types import ( + DiffInfo, + TensorComparisonInfo, + TensorStats, +) +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) + +_DEFAULT_PERCENTILE_LINES: list[str] = [ + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]", + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]", + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]", + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]", + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]", +] + +_DEFAULT_PERCENTILE_LINES: list[str] = [ + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]", + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]", + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]", + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]", + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]", +] + + +# Snapshot strings below are intentionally spelled out in full per test. +# The shared skeleton (stats block, diff block) looks duplicated, but keeping +# each test self-contained makes failures immediately readable without chasing +# helper functions. Do not extract common fragments. +class TestFormatComparison: + def test_normal(self): + info = TensorComparisonInfo( + name="test", + baseline=_make_tensor_info( + stats=_make_stats(mean=0.1, std=1.0, min=-2.0, max=2.0), + ), + target=_make_tensor_info( + stats=_make_stats(mean=0.1001, std=1.0001, min=-2.0001, max=2.0001), + ), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(), + ) + + assert format_comparison(info) == ( + "Raw [shape] [4, 8] vs [4, 8]\t" + "[dtype] torch.float32 vs torch.float32\n" + "After unify [shape] [4, 8] vs [4, 8]\t" + "[dtype] torch.float32 vs torch.float32\n" + "[mean] 0.1000 vs 0.1001 (diff: 0.0001)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0001 (diff: 0.0001)\n" + "[min] -2.0000 vs -2.0001 (diff: -0.0001)\n" + "[max] 2.0000 vs 2.0001 (diff: 0.0001)\n" + "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n" + "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n" + "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n" + "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n" + "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n" + "max_abs_diff happens at coord=[2, 3] with " + "baseline=1.0 target=1.0005\n" + "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005" + ) + + def test_shape_mismatch(self): + info = TensorComparisonInfo( + name="mismatch", + baseline=_make_tensor_info(shape=[3, 4]), + target=_make_tensor_info(shape=[5, 6]), + unified_shape=[3, 4], + shape_mismatch=True, + ) + + assert format_comparison(info) == ( + "Raw [shape] [3, 4] vs [5, 6]\t" + "[dtype] torch.float32 vs torch.float32\n" + "After unify [shape] [3, 4] vs [5, 6]\t" + "[dtype] torch.float32 vs torch.float32\n" + "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n" + "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n" + "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n" + "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n" + "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n" + "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n" + "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n" + "⚠️ Shape mismatch" + ) + + def test_with_downcast(self): + info = TensorComparisonInfo( + name="downcast", + baseline=_make_tensor_info(), + target=_make_tensor_info(dtype="torch.bfloat16"), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff( + rel_diff=0.002, max_abs_diff=0.005, mean_abs_diff=0.001, passed=False + ), + diff_downcast=_make_diff( + rel_diff=0.0001, max_abs_diff=0.0005, mean_abs_diff=0.0002, passed=True + ), + downcast_dtype="torch.bfloat16", + ) + + assert format_comparison(info) == ( + "Raw [shape] [4, 8] vs [4, 8]\t" + "[🟠dtype] torch.float32 vs torch.bfloat16\n" + "After unify [shape] [4, 8] vs [4, 8]\t" + "[dtype] torch.float32 vs torch.bfloat16\n" + "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n" + "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n" + "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n" + "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n" + "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n" + "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n" + "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n" + "❌ rel_diff=0.002\tmax_abs_diff=0.005\tmean_abs_diff=0.001\n" + "max_abs_diff happens at coord=[2, 3] with " + "baseline=1.0 target=1.0005\n" + "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005\n" + "When downcast to torch.bfloat16: " + "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n" + "max_abs_diff happens at coord=[2, 3] with " + "baseline=1.0 target=1.0005\n" + "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005" + ) + + def test_with_shape_unification(self): + info = TensorComparisonInfo( + name="unify", + baseline=_make_tensor_info(shape=[1, 1, 4, 8]), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(), + ) + + assert format_comparison(info) == ( + "Raw [shape] [1, 1, 4, 8] vs [4, 8]\t" + "[dtype] torch.float32 vs torch.float32\n" + "Unify shape: [1, 1, 4, 8] -> [4, 8] " + "(to match [4, 8])\n" + "After unify [shape] [4, 8] vs [4, 8]\t" + "[dtype] torch.float32 vs torch.float32\n" + "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n" + "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n" + "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n" + "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n" + "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n" + "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n" + "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n" + "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n" + "max_abs_diff happens at coord=[2, 3] with " + "baseline=1.0 target=1.0005\n" + "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005" + ) + + def test_with_samples(self): + info = TensorComparisonInfo( + name="samples", + baseline=_make_tensor_info(sample="tensor([0.1, 0.2, ...])"), + target=_make_tensor_info(sample="tensor([0.1, 0.3, ...])"), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(), + ) + + assert format_comparison(info) == ( + "Raw [shape] [4, 8] vs [4, 8]\t" + "[dtype] torch.float32 vs torch.float32\n" + "After unify [shape] [4, 8] vs [4, 8]\t" + "[dtype] torch.float32 vs torch.float32\n" + "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n" + "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n" + "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n" + "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n" + "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n" + "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n" + "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n" + "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n" + "max_abs_diff happens at coord=[2, 3] with " + "baseline=1.0 target=1.0005\n" + "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005\n" + "x_baseline(sample)=tensor([0.1, 0.2, ...])\n" + "x_target(sample)=tensor([0.1, 0.3, ...])" + ) + + def test_empty_percentiles(self): + stats_no_quantiles = _make_stats(percentiles={}) + + info = TensorComparisonInfo( + name="no_quantiles", + baseline=_make_tensor_info(stats=stats_no_quantiles), + target=_make_tensor_info(stats=stats_no_quantiles), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(abs_diff_percentiles={}), + ) + + assert format_comparison(info) == ( + "Raw [shape] [4, 8] vs [4, 8]\t" + "[dtype] torch.float32 vs torch.float32\n" + "After unify [shape] [4, 8] vs [4, 8]\t" + "[dtype] torch.float32 vs torch.float32\n" + "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n" + "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n" + "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n" + "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n" + "max_abs_diff happens at coord=[2, 3] with " + "baseline=1.0 target=1.0005" + ) + + +def _make_comparison_record( + name: str = "hidden_states", + shape: list[int] | None = None, + dtype: str = "torch.float32", + diff: DiffInfo | None = None, + shape_mismatch: bool = False, + sample: str | None = None, + diff_downcast: DiffInfo | None = None, + downcast_dtype: str | None = None, + replicated_checks: list[ReplicatedCheckResult] | None = None, + raw_bundle_info: Pair[BundleSideInfo] | None = None, + traced_plan: TracedAlignerPlan | None = None, +) -> ComparisonTensorRecord: + s: list[int] = shape if shape is not None else [4, 8] + return ComparisonTensorRecord( + name=name, + baseline=_make_tensor_info(shape=s, dtype=dtype, sample=sample), + target=_make_tensor_info(shape=s, dtype=dtype, sample=sample), + unified_shape=s, + shape_mismatch=shape_mismatch, + diff=diff, + diff_downcast=diff_downcast, + downcast_dtype=downcast_dtype, + replicated_checks=replicated_checks or [], + raw_bundle_info=raw_bundle_info, + traced_plan=traced_plan, + ) + + +def _make_bundle_side_info( + num_files: int = 2, + shape: list[int] | None = None, + dtype: str = "torch.float32", + dims: str | None = None, + with_parallel_info: bool = False, +) -> BundleSideInfo: + s: list[int] = shape if shape is not None else [2, 4096] + files: list[BundleFileInfo] = [] + for i in range(num_files): + par: dict[str, str] | None = ( + {"tp": f"{i}/{num_files}"} if with_parallel_info else None + ) + files.append(BundleFileInfo(shape=s, dtype=dtype, rank=i, parallel_info=par)) + return BundleSideInfo(num_files=num_files, files=files, dims=dims) + + +def _make_simple_aligner_plan( + *, + with_unsharder: bool = False, + with_reorderer: bool = False, + with_token_aligner: bool = False, + with_axis_aligner: bool = False, + axis_aligner_noop: bool = False, +) -> AlignerPlan: + baseline_plans: list[AlignerPerStepPlan] = [] + target_plans: list[AlignerPerStepPlan] = [] + + if with_unsharder: + unsharder: UnsharderPlan = UnsharderPlan( + axis=ParallelAxis.TP, + params=ConcatParams(dim_name="h"), + groups=[[0, 1]], + ) + target_plans.append( + AlignerPerStepPlan( + step=0, input_object_indices=[0, 1], sub_plans=[unsharder] + ) + ) + + if with_reorderer: + reorderer: ReordererPlan = ReordererPlan( + params=ZigzagToNaturalParams(dim_name="s", cp_size=2), + ) + target_plans.append( + AlignerPerStepPlan(step=0, input_object_indices=[0], sub_plans=[reorderer]) + ) + + token_aligner_plan: TokenAlignerPlan | None = None + if with_token_aligner: + token_aligner_plan = TokenAlignerPlan( + locators=Pair( + x=TokenLocator(steps=[0, 0, 0], token_index_in_step=[0, 1, 2]), + y=TokenLocator(steps=[0, 0, 0], token_index_in_step=[0, 1, 2]), + ), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.T), + ) + + axis_aligner_plan: AxisAlignerPlan | None = None + if with_axis_aligner: + if axis_aligner_noop: + axis_aligner_plan = AxisAlignerPlan(pattern=Pair(x=None, y=None)) + else: + axis_aligner_plan = AxisAlignerPlan( + pattern=Pair(x="b s d -> s b d", y=None) + ) + + return AlignerPlan( + per_step_plans=Pair(x=baseline_plans, y=target_plans), + token_aligner_plan=token_aligner_plan, + axis_aligner_plan=axis_aligner_plan, + ) + + +def _make_traced_plan( + plan: AlignerPlan, + *, + target_input_shapes: list[list[int]] | None = None, + target_output_shapes: list[list[int]] | None = None, +) -> TracedAlignerPlan: + """Build a TracedAlignerPlan by attaching snapshots to target sub_plans.""" + baseline_traced_steps: list[TracedStepPlan] = [ + TracedStepPlan( + step=sp.step, + input_object_indices=sp.input_object_indices, + sub_plans=[TracedSubPlan(plan=sub) for sub in sp.sub_plans], + ) + for sp in plan.per_step_plans.x + ] + + target_traced_steps: list[TracedStepPlan] = [] + for sp in plan.per_step_plans.y: + traced_subs: list[TracedSubPlan] = [] + for sub in sp.sub_plans: + snapshot: ShapeSnapshot | None = None + if target_input_shapes is not None or target_output_shapes is not None: + snapshot = ShapeSnapshot( + input_shapes=target_input_shapes or [[2, 4096], [2, 4096]], + output_shapes=target_output_shapes or [[4, 4096]], + ) + traced_subs.append(TracedSubPlan(plan=sub, snapshot=snapshot)) + target_traced_steps.append( + TracedStepPlan( + step=sp.step, + input_object_indices=sp.input_object_indices, + sub_plans=traced_subs, + ) + ) + + return TracedAlignerPlan( + plan=plan, + per_side=Pair( + x=TracedSidePlan(step_plans=baseline_traced_steps), + y=TracedSidePlan(step_plans=target_traced_steps), + ), + ) + + +# --------------------------------------------------------------------------- +# Rich format snapshot tests +# --------------------------------------------------------------------------- + + +class TestFormatComparisonRichMinimal: + """format_comparison_rich() with verbosity='minimal'.""" + + def test_passed(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff(rel_diff=1e-4, passed=True), + ) + result: str = format_comparison_rich(record, verbosity="minimal") + assert_rich_tags_balanced(result) + + assert result == ( + "[green]✅[/] [bold green]hidden_states [/] " + "rel_diff=1.00e-04" + ) + + def test_failed(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff(rel_diff=0.5, passed=False), + ) + result: str = format_comparison_rich(record, verbosity="minimal") + assert_rich_tags_balanced(result) + + assert result == ( + "[red]❌[/] [bold red]hidden_states [/] " + "rel_diff=5.00e-01" + ) + + def test_shape_mismatch(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + shape_mismatch=True, + ) + result: str = format_comparison_rich(record, verbosity="minimal") + assert_rich_tags_balanced(result) + + assert result == ( + "[red]❌[/] [bold red]hidden_states [/] " + "[yellow]shape mismatch[/]" + ) + + def test_no_diff(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record() + result: str = format_comparison_rich(record, verbosity="minimal") + assert_rich_tags_balanced(result) + + assert result == ("[red]❌[/] [bold red]hidden_states [/]") + + +class TestFormatComparisonRichNormal: + """format_comparison_rich() with verbosity='normal'.""" + + def test_passed(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff(rel_diff=1e-4, passed=True), + ) + result: str = format_comparison_rich(record, verbosity="normal") + assert_rich_tags_balanced(result) + + assert result == ( + "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n" + " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n" + " [dim]Aligned[/]\n" + " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n" + " [dim]Stats[/]\n" + " [dim] baseline target Δ[/]\n" + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n" + " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n" + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n" + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n" + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n" + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]" + ) + + def test_failed(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff( + rel_diff=0.5, max_abs_diff=1.0, mean_abs_diff=0.3, passed=False + ), + ) + result: str = format_comparison_rich(record, verbosity="normal") + assert_rich_tags_balanced(result) + + assert result == ( + "[red]❌[/] [bold red]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n" + " [bold red]rel_diff=5.00e-01[/] max_abs=1.00e+00 mean_abs=3.00e-01\n" + " max_abs @ [2, 3]: baseline=1.0 target=1.0005\n" + " [dim]Aligned[/]\n" + " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n" + " [dim]Stats[/]\n" + " [dim] baseline target Δ[/]\n" + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n" + " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n" + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n" + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n" + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n" + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n" + " [dim]Abs Diff Percentiles[/]\n" + " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04" + ) + + def test_shape_mismatch(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + shape_mismatch=True, + ) + result: str = format_comparison_rich(record, verbosity="normal") + assert_rich_tags_balanced(result) + + assert result == ( + "[red]❌[/] [bold red]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n" + " [yellow]⚠ Shape mismatch[/]\n" + " [dim]Aligned[/]\n" + " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n" + " [dim]Stats[/]\n" + " [dim] baseline target Δ[/]\n" + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n" + " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n" + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n" + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n" + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n" + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]" + ) + + def test_with_downcast(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff(rel_diff=0.01, passed=False), + diff_downcast=_make_diff(rel_diff=1e-5, passed=True), + downcast_dtype="torch.bfloat16", + ) + result: str = format_comparison_rich(record, verbosity="normal") + assert_rich_tags_balanced(result) + + assert result == ( + "[red]❌[/] [bold red]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n" + " [bold red]rel_diff=1.00e-02[/] max_abs=5.00e-04 mean_abs=2.00e-04\n" + " max_abs @ [2, 3]: baseline=1.0 target=1.0005\n" + " [green]✅[/] downcast to torch.bfloat16: rel_diff=1.00e-05\n" + " [dim]Aligned[/]\n" + " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n" + " [dim]Stats[/]\n" + " [dim] baseline target Δ[/]\n" + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n" + " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n" + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n" + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n" + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n" + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n" + " [dim]Abs Diff Percentiles[/]\n" + " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04" + ) + + def test_with_bundle_info(self) -> None: + bundle_info: Pair[BundleSideInfo] = Pair( + x=_make_bundle_side_info(num_files=2, dims="b s h(tp) d"), + y=_make_bundle_side_info(num_files=2, dims="b s h(tp) d"), + ) + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff(passed=True), + raw_bundle_info=bundle_info, + ) + result: str = format_comparison_rich(record, verbosity="normal") + assert_rich_tags_balanced(result) + + assert result == ( + "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n" + " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n" + " [dim]Bundle[/]\n" + " baseline [cyan]2 files[/] × [2, 4096] float32 [dim]dims: b s h(tp) d[/]\n" + " target [cyan]2 files[/] × [2, 4096] float32 [dim]dims: b s h(tp) d[/]\n" + " [dim]Aligned[/]\n" + " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n" + " [dim]Stats[/]\n" + " [dim] baseline target Δ[/]\n" + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n" + " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n" + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n" + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n" + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n" + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]" + ) + + def test_with_plan(self) -> None: + plan: AlignerPlan = _make_simple_aligner_plan(with_unsharder=True) + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff(passed=True), + traced_plan=_make_traced_plan(plan), + ) + result: str = format_comparison_rich(record, verbosity="normal") + assert_rich_tags_balanced(result) + + assert result == ( + "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n" + " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n" + " [dim]Plan[/]\n" + " baseline [dim](passthrough)[/]\n" + " target [magenta]unsharder(tp)[/]\n" + " [dim]Aligned[/]\n" + " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n" + " [dim]Stats[/]\n" + " [dim] baseline target Δ[/]\n" + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n" + " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]\n" + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n" + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n" + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n" + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]" + ) + + +class TestFormatComparisonRichVerbose: + """format_comparison_rich() with verbosity='verbose'.""" + + def test_passed_full_detail(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff(rel_diff=1e-4, passed=True), + sample="tensor([0.1, 0.2, ...])", + ) + result: str = format_comparison_rich(record, verbosity="verbose") + assert_rich_tags_balanced(result) + + assert result == ( + "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n" + " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n" + " [dim]Aligned[/]\n" + " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n" + " [dim]Stats[/]\n" + " [dim] baseline target Δ[/]\n" + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]\n" + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n" + " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]\n" + " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]\n" + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n" + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n" + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n" + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n" + " [dim]Abs Diff Percentiles[/]\n" + " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04\n" + " [dim]Samples[/]\n" + " baseline tensor([0.1, 0.2, ...])\n" + " target tensor([0.1, 0.2, ...])" + ) + + def test_with_bundle_verbose(self) -> None: + bundle_info: Pair[BundleSideInfo] = Pair( + x=_make_bundle_side_info(num_files=2, with_parallel_info=True), + y=_make_bundle_side_info(num_files=2, with_parallel_info=True), + ) + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff(passed=True), + raw_bundle_info=bundle_info, + ) + result: str = format_comparison_rich(record, verbosity="verbose") + assert_rich_tags_balanced(result) + + assert result == ( + "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n" + " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n" + " [dim]Bundle[/]\n" + " baseline [cyan]2 files[/] float32\n" + " [0] [2, 4096] rank=0 tp=0/2\n" + " [1] [2, 4096] rank=1 tp=1/2\n" + " target [cyan]2 files[/] float32\n" + " [0] [2, 4096] rank=0 tp=0/2\n" + " [1] [2, 4096] rank=1 tp=1/2\n" + " [dim]Aligned[/]\n" + " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n" + " [dim]Stats[/]\n" + " [dim] baseline target Δ[/]\n" + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]\n" + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n" + " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]\n" + " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]\n" + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n" + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n" + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n" + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n" + " [dim]Abs Diff Percentiles[/]\n" + " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04" + ) + + def test_with_plan_and_traces(self) -> None: + plan: AlignerPlan = _make_simple_aligner_plan(with_unsharder=True) + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff(passed=True), + traced_plan=_make_traced_plan( + plan, + target_input_shapes=[[2, 4096], [2, 4096]], + target_output_shapes=[[4, 4096]], + ), + ) + result: str = format_comparison_rich(record, verbosity="verbose") + assert_rich_tags_balanced(result) + + assert result == ( + "[green]✅[/] [bold green]hidden_states[/] [dim cyan]── float32 [4, 8][/]\n" + " [green]rel_diff=1.00e-04[/] max_abs=5.00e-04 mean_abs=2.00e-04\n" + " [dim]Plan[/]\n" + " baseline [dim](passthrough)[/]\n" + " target [magenta]unsharder(tp)[/] (2×[2, 4096] → 1×[4, 4096])\n" + " [dim]Aligned[/]\n" + " [4, 8] vs [4, 8] torch.float32 vs torch.float32\n" + " [dim]Stats[/]\n" + " [dim] baseline target Δ[/]\n" + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]\n" + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]\n" + " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]\n" + " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]\n" + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]\n" + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]\n" + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]\n" + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]\n" + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]\n" + " [dim]Abs Diff Percentiles[/]\n" + " p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 p95=4.00e-04 p99=5.00e-04" + ) + + +class TestFormatBundleSection: + """_format_bundle_section() snapshot tests.""" + + def test_single_shape(self) -> None: + bundle: Pair[BundleSideInfo] = Pair( + x=_make_bundle_side_info(num_files=2, shape=[2, 4096]), + y=_make_bundle_side_info(num_files=2, shape=[2, 4096]), + ) + lines: list[str] = _format_bundle_section(bundle) + + assert lines == [ + " baseline [cyan]2 files[/] × [2, 4096] float32", + " target [cyan]2 files[/] × [2, 4096] float32", + ] + + def test_mixed_shapes(self) -> None: + side: BundleSideInfo = BundleSideInfo( + num_files=2, + files=[ + BundleFileInfo(shape=[2, 4096], dtype="torch.float32", rank=0), + BundleFileInfo(shape=[3, 4096], dtype="torch.float32", rank=1), + ], + ) + bundle: Pair[BundleSideInfo] = Pair(x=side, y=side) + lines: list[str] = _format_bundle_section(bundle) + + assert lines == [ + " baseline [cyan]2 files[/] × mixed shapes float32", + " target [cyan]2 files[/] × mixed shapes float32", + ] + + def test_no_files(self) -> None: + empty: BundleSideInfo = BundleSideInfo(num_files=0, files=[]) + bundle: Pair[BundleSideInfo] = Pair(x=empty, y=empty) + lines: list[str] = _format_bundle_section(bundle) + + assert lines == [ + " baseline [dim](no files)[/]", + " target [dim](no files)[/]", + ] + + def test_with_dims(self) -> None: + bundle: Pair[BundleSideInfo] = Pair( + x=_make_bundle_side_info(num_files=1, dims="b s h(tp) d"), + y=_make_bundle_side_info(num_files=1, dims="b s h(tp) d"), + ) + lines: list[str] = _format_bundle_section(bundle) + + assert lines == [ + " baseline [cyan]1 files[/] × [2, 4096] float32 [dim]dims: b s h(tp) d[/]", + " target [cyan]1 files[/] × [2, 4096] float32 [dim]dims: b s h(tp) d[/]", + ] + + +class TestFormatBundleSectionVerbose: + """_format_bundle_section(verbose=True) snapshot tests.""" + + def test_per_file_listing(self) -> None: + bundle: Pair[BundleSideInfo] = Pair( + x=_make_bundle_side_info(num_files=2, with_parallel_info=True), + y=_make_bundle_side_info(num_files=2, with_parallel_info=True), + ) + lines: list[str] = _format_bundle_section(bundle, verbose=True) + + assert lines == [ + " baseline [cyan]2 files[/] float32", + " [0] [2, 4096] rank=0 tp=0/2", + " [1] [2, 4096] rank=1 tp=1/2", + " target [cyan]2 files[/] float32", + " [0] [2, 4096] rank=0 tp=0/2", + " [1] [2, 4096] rank=1 tp=1/2", + ] + + def test_no_files(self) -> None: + empty: BundleSideInfo = BundleSideInfo(num_files=0, files=[]) + bundle: Pair[BundleSideInfo] = Pair(x=empty, y=empty) + lines: list[str] = _format_bundle_section(bundle, verbose=True) + + assert lines == [ + " baseline [dim](no files)[/]", + " target [dim](no files)[/]", + ] + + +class TestFormatPlanSectionRich: + """_format_plan_section_rich() snapshot tests.""" + + def test_passthrough(self) -> None: + plan: AlignerPlan = _make_simple_aligner_plan() + traced: TracedAlignerPlan = _make_traced_plan(plan) + lines: list[str] = _format_plan_section_rich(traced_plan=traced) + + assert lines == [ + " baseline [dim](passthrough)[/]", + " target [dim](passthrough)[/]", + ] + + def test_unsharder_op(self) -> None: + plan: AlignerPlan = _make_simple_aligner_plan(with_unsharder=True) + traced: TracedAlignerPlan = _make_traced_plan(plan) + lines: list[str] = _format_plan_section_rich(traced_plan=traced) + + assert lines == [ + " baseline [dim](passthrough)[/]", + " target [magenta]unsharder(tp)[/]", + ] + + def test_reorderer_op(self) -> None: + plan: AlignerPlan = _make_simple_aligner_plan(with_reorderer=True) + traced: TracedAlignerPlan = _make_traced_plan(plan) + lines: list[str] = _format_plan_section_rich(traced_plan=traced) + + assert lines == [ + " baseline [dim](passthrough)[/]", + " target [magenta]reorderer(zigzag_to_natural)[/]", + ] + + def test_with_shape_traces(self) -> None: + plan: AlignerPlan = _make_simple_aligner_plan(with_unsharder=True) + traced: TracedAlignerPlan = _make_traced_plan( + plan, + target_input_shapes=[[2, 4096], [2, 4096]], + target_output_shapes=[[4, 4096]], + ) + lines: list[str] = _format_plan_section_rich(traced_plan=traced) + + assert lines == [ + " baseline [dim](passthrough)[/]", + " target [magenta]unsharder(tp)[/] (2×[2, 4096] → 1×[4, 4096])", + ] + + def test_with_token_aligner(self) -> None: + plan: AlignerPlan = _make_simple_aligner_plan(with_token_aligner=True) + traced: TracedAlignerPlan = _make_traced_plan(plan) + lines: list[str] = _format_plan_section_rich(traced_plan=traced) + + assert lines == [ + " baseline [dim](passthrough)[/]", + " target [dim](passthrough)[/]", + " token_aligner [dim]3 tokens[/]", + ] + + def test_with_axis_aligner(self) -> None: + plan: AlignerPlan = _make_simple_aligner_plan(with_axis_aligner=True) + traced: TracedAlignerPlan = _make_traced_plan(plan) + lines: list[str] = _format_plan_section_rich(traced_plan=traced) + + assert lines == [ + " baseline [dim](passthrough)[/]", + " target [dim](passthrough)[/]", + " axis_aligner [dim]x=b s d -> s b d[/]", + ] + + def test_axis_aligner_noop(self) -> None: + plan: AlignerPlan = _make_simple_aligner_plan( + with_axis_aligner=True, axis_aligner_noop=True + ) + traced: TracedAlignerPlan = _make_traced_plan(plan) + lines: list[str] = _format_plan_section_rich(traced_plan=traced) + + assert lines == [ + " baseline [dim](passthrough)[/]", + " target [dim](passthrough)[/]", + " axis_aligner [dim](no-op)[/]", + ] + + +class TestFormatStatsRich: + """_format_stats_rich() snapshot tests.""" + + def test_basic(self) -> None: + baseline: TensorStats = _make_stats(mean=0.0, std=1.0, min=-2.0, max=2.0) + target: TensorStats = _make_stats( + mean=0.0001, std=1.0001, min=-2.0001, max=2.0001 + ) + lines: list[str] = _format_stats_rich(baseline=baseline, target=target) + assert_rich_tags_balanced("\n".join(lines)) + + assert lines == [ + " [dim] baseline target Δ[/]", + " [blue]mean [/] 0.0000 0.0001 [dim]+1.00e-04[/]", + " [blue]std [/] 1.0000 1.0001 [dim]+1.00e-04[/]", + " [blue]range [/] [-2.0000, 2.0000] [-2.0001, 2.0001]", + *_DEFAULT_PERCENTILE_LINES, + ] + + def test_large_delta(self) -> None: + baseline: TensorStats = _make_stats(mean=0.0) + target: TensorStats = _make_stats(mean=1.0) + lines: list[str] = _format_stats_rich(baseline=baseline, target=target) + assert_rich_tags_balanced("\n".join(lines)) + + assert lines == [ + " [dim] baseline target Δ[/]", + " [blue]mean [/] 0.0000 1.0000 [yellow]+1.00e+00[/]", + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]", + " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]", + *_DEFAULT_PERCENTILE_LINES, + ] + + def test_small_delta(self) -> None: + baseline: TensorStats = _make_stats(mean=0.0) + target: TensorStats = _make_stats(mean=0.001) + lines: list[str] = _format_stats_rich(baseline=baseline, target=target) + assert_rich_tags_balanced("\n".join(lines)) + + assert lines == [ + " [dim] baseline target Δ[/]", + " [blue]mean [/] 0.0000 0.0010 [dim]+1.00e-03[/]", + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]", + " [blue]range [/] [-2.0000, 2.0000] [-2.0000, 2.0000]", + *_DEFAULT_PERCENTILE_LINES, + ] + + +class TestFormatStatsRichVerbose: + """_format_stats_rich(verbose=True) snapshot tests.""" + + def test_all_stats_with_percentiles(self) -> None: + baseline: TensorStats = _make_stats() + target: TensorStats = _make_stats() + lines: list[str] = _format_stats_rich( + baseline=baseline, target=target, verbose=True + ) + + assert lines == [ + " [dim] baseline target Δ[/]", + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]", + " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]", + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]", + " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]", + " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]", + " [blue]p1 [/] -1.8000 -1.8000 [dim]+0.00e+00[/]", + " [blue]p5 [/] -1.5000 -1.5000 [dim]+0.00e+00[/]", + " [blue]p50 [/] 0.0000 0.0000 [dim]+0.00e+00[/]", + " [blue]p95 [/] 1.5000 1.5000 [dim]+0.00e+00[/]", + " [blue]p99 [/] 1.8000 1.8000 [dim]+0.00e+00[/]", + ] + + def test_no_percentiles(self) -> None: + baseline: TensorStats = _make_stats(percentiles={}) + target: TensorStats = _make_stats(percentiles={}) + lines: list[str] = _format_stats_rich( + baseline=baseline, target=target, verbose=True + ) + + assert lines == [ + " [dim] baseline target Δ[/]", + " [blue]mean [/] 0.0000 0.0000 [dim]+0.00e+00[/]", + " [blue]abs_mean [/] 0.8000 0.8000 [dim]+0.00e+00[/]", + " [blue]std [/] 1.0000 1.0000 [dim]+0.00e+00[/]", + " [blue]min [/] -2.0000 -2.0000 [dim]+0.00e+00[/]", + " [blue]max [/] 2.0000 2.0000 [dim]+0.00e+00[/]", + ] + + +class TestFormatAbsDiffPercentilesRich: + """_format_abs_diff_percentiles_rich() snapshot tests.""" + + def test_normal_values(self) -> None: + diff: DiffInfo = _make_diff() + result: str = _format_abs_diff_percentiles_rich(diff) + + assert result == ( + "p1=1.00e-04 p5=1.00e-04 p50=2.00e-04 " "p95=4.00e-04 p99=5.00e-04" + ) + + def test_high_p99_coloring(self) -> None: + diff: DiffInfo = _make_diff( + abs_diff_percentiles={99: 0.5}, + ) + result: str = _format_abs_diff_percentiles_rich(diff) + + assert result == "[yellow]p99=5.00e-01[/]" + + def test_low_p99_no_coloring(self) -> None: + diff: DiffInfo = _make_diff( + abs_diff_percentiles={99: 0.01}, + ) + result: str = _format_abs_diff_percentiles_rich(diff) + + assert result == "p99=1.00e-02" + + +class TestFormatReplicatedChecks: + """format_replicated_checks() snapshot tests.""" + + def test_all_passed(self) -> None: + checks: list[ReplicatedCheckResult] = [ + ReplicatedCheckResult( + axis="tp", + group_index=0, + compared_index=1, + baseline_index=0, + passed=True, + atol=1e-3, + diff=_make_diff(rel_diff=1e-6, max_abs_diff=1e-5, mean_abs_diff=1e-6), + ), + ] + result: str = format_replicated_checks(checks) + + assert result == ( + "Replicated checks:\n" + " ✅ axis=tp group=0 idx=1 vs 0: " + "rel_diff=1.000000e-06 max_abs_diff=1.000000e-05 mean_abs_diff=1.000000e-06" + ) + + def test_one_failed(self) -> None: + checks: list[ReplicatedCheckResult] = [ + ReplicatedCheckResult( + axis="tp", + group_index=0, + compared_index=1, + baseline_index=0, + passed=False, + atol=1e-3, + diff=_make_diff(rel_diff=0.5, max_abs_diff=1.0, mean_abs_diff=0.3), + ), + ] + result: str = format_replicated_checks(checks) + + assert result == ( + "Replicated checks:\n" + " ❌ axis=tp group=0 idx=1 vs 0: " + "rel_diff=5.000000e-01 max_abs_diff=1.000000e+00 mean_abs_diff=3.000000e-01" + ) + + def test_no_diff(self) -> None: + checks: list[ReplicatedCheckResult] = [ + ReplicatedCheckResult( + axis="tp", + group_index=0, + compared_index=1, + baseline_index=0, + passed=True, + atol=1e-3, + ), + ] + result: str = format_replicated_checks(checks) + + assert result == ( + "Replicated checks:\n" " ✅ axis=tp group=0 idx=1 vs 0: n/a diff" + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_types.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..0d1e14a147c6b234831ac0eb606cde7bb2e35af7 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/tensor_comparator/test_types.py @@ -0,0 +1,262 @@ +import json +import sys + +import pytest + +from sglang.srt.debug_utils.comparator.output_types import ( + ComparisonSkipRecord, + ComparisonTensorRecord, + ConfigRecord, + ErrorLog, + InfoLog, + LogRecord, + ReplicatedCheckResult, + SummaryRecord, + parse_record_json, +) +from sglang.srt.debug_utils.comparator.tensor_comparator.types import ( + DiffInfo, + TensorInfo, + TensorStats, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +def _make_stats(**overrides) -> TensorStats: + defaults: dict = dict( + mean=0.5, + abs_mean=1.2, + std=1.0, + min=-2.0, + max=3.0, + percentiles={1: -1.8, 5: -1.5, 50: 0.0, 95: 2.5, 99: 2.8}, + ) + defaults.update(overrides) + return TensorStats(**defaults) + + +def _make_diff(**overrides) -> DiffInfo: + defaults = dict( + rel_diff=1e-4, + max_abs_diff=5e-4, + mean_abs_diff=2e-4, + max_diff_coord=[2, 3], + baseline_at_max=1.0, + target_at_max=1.0005, + diff_threshold=1e-3, + passed=True, + ) + defaults.update(overrides) + return DiffInfo(**defaults) + + +def _make_tensor_info(**overrides) -> TensorInfo: + defaults = dict( + shape=[4, 8], + dtype="torch.float32", + stats=_make_stats(), + ) + defaults.update(overrides) + return TensorInfo(**defaults) + + +class TestStrictBase: + def test_rejects_extra_fields(self): + with pytest.raises(Exception): + TensorStats(mean=0.0, abs_mean=0.5, std=1.0, min=-1.0, max=1.0, bogus=42) + + def test_rejects_extra_fields_on_diff(self): + with pytest.raises(Exception): + DiffInfo( + rel_diff=0.0, + max_abs_diff=0.0, + mean_abs_diff=0.0, + max_diff_coord=[0], + baseline_at_max=0.0, + target_at_max=0.0, + diff_threshold=1e-3, + passed=True, + extra_field=123, + ) + + +class TestRecordTypes: + def test_comparison_record_inherits_tensor_fields(self): + record = ComparisonTensorRecord( + name="hidden_states", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(), + ) + parsed = json.loads(record.model_dump_json()) + assert parsed["type"] == "comparison_tensor" + assert parsed["name"] == "hidden_states" + assert "baseline" in parsed + assert "diff" in parsed + + def test_discriminated_union_parsing(self): + for record in [ + ConfigRecord( + config={ + "baseline_path": "/a", + "target_path": "/b", + "diff_threshold": 1e-3, + "start_step": 0, + "end_step": 100, + } + ), + ComparisonSkipRecord(name="attn", reason="no_baseline"), + ComparisonTensorRecord( + name="mlp", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + ), + SummaryRecord(total=10, passed=8, failed=1, skipped=1), + LogRecord( + errors=[ErrorLog(category="test", message="test warning")], + ), + ]: + restored = parse_record_json(record.model_dump_json()) + assert type(restored) is type(record) + assert restored == record + + +def _make_replicated_check(**overrides) -> ReplicatedCheckResult: + defaults: dict = dict( + axis="tp", + group_index=0, + compared_index=1, + baseline_index=0, + passed=False, + atol=1e-6, + diff=_make_diff( + rel_diff=0.1, + max_abs_diff=0.1, + mean_abs_diff=0.05, + diff_threshold=1e-6, + passed=False, + ), + ) + defaults.update(overrides) + return ReplicatedCheckResult(**defaults) + + +class TestWarnings: + def test_comparison_record_failed_when_diff_passed_but_errors(self): + """ComparisonTensorRecord with diff.passed=True but errors → category=='failed'.""" + record = ComparisonTensorRecord( + name="hidden", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(passed=True), + errors=[ErrorLog(category="test", message="some warning")], + ) + assert record.category == "failed" + + def test_skip_record_failed_when_errors(self): + """ComparisonSkipRecord with errors → category=='failed' instead of 'skipped'.""" + record = ComparisonSkipRecord( + name="x", + reason="no_baseline", + errors=[ErrorLog(category="test", message="some warning")], + ) + assert record.category == "failed" + + def test_replicated_checks_all_passed(self): + """ComparisonTensorRecord with all replicated_checks passed → category=='passed'.""" + record = ComparisonTensorRecord( + name="hidden", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(passed=True), + replicated_checks=[_make_replicated_check(passed=True)], + ) + assert record.category == "passed" + + def test_replicated_checks_failed_means_record_failed(self): + """ComparisonTensorRecord with any replicated_check.passed=False → category=='failed'.""" + record = ComparisonTensorRecord( + name="hidden", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(passed=True), + replicated_checks=[_make_replicated_check(passed=False)], + ) + assert record.category == "failed" + + def test_replicated_check_json_round_trip(self): + """ReplicatedCheckResult survives JSON round-trip via ComparisonTensorRecord.""" + check = _make_replicated_check( + axis="cp", + group_index=2, + compared_index=3, + baseline_index=0, + passed=False, + ) + record = ComparisonTensorRecord( + name="mlp", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(), + replicated_checks=[check], + ) + + restored = parse_record_json(record.model_dump_json()) + assert isinstance(restored, ComparisonTensorRecord) + assert len(restored.replicated_checks) == 1 + + restored_check: ReplicatedCheckResult = restored.replicated_checks[0] + assert restored_check.axis == "cp" + assert restored_check.group_index == 2 + assert restored_check.compared_index == 3 + assert restored_check.baseline_index == 0 + assert not restored_check.passed + + def test_any_log_discriminated_union_round_trip(self): + """ErrorLog and InfoLog survive JSON round-trip via a LogRecord.""" + all_errors = [ + ErrorLog( + category="rids_mismatch", + message="rids mismatch across ranks: rank 0 has [1,2,3], " + "rank 1 has [4,5,6]", + ), + ] + all_infos = [ + InfoLog( + category="aux_tensors_missing", + message="Aux tensors missing, skipping token alignment", + ), + ] + + record = LogRecord(errors=all_errors, infos=all_infos) + restored = parse_record_json(record.model_dump_json()) + assert isinstance(restored, LogRecord) + assert len(restored.errors) == len(all_errors) + assert len(restored.infos) == len(all_infos) + + for original, parsed in zip(all_errors, restored.errors): + assert type(parsed) is type(original) + assert parsed == original + + for original, parsed in zip(all_infos, restored.infos): + assert type(parsed) is type(original) + assert parsed == original + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_comparator.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_comparator.py new file mode 100644 index 0000000000000000000000000000000000000000..a71c7af08dfbea1d5876e040b35fb31eac2590c4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_comparator.py @@ -0,0 +1,210 @@ +import sys +from pathlib import Path +from unittest.mock import patch + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.bundle_comparator import ( + _build_skip_from_one_empty_side, + _load_all_values, +) +from sglang.srt.debug_utils.comparator.log_sink import LogSink +from sglang.srt.debug_utils.comparator.output_types import ErrorLog +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.srt.debug_utils.dump_loader import ValueWithMeta +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) + + +def _save_tensor( + dump_path: Path, + *, + name: str, + step: int = 0, + rank: int = 0, +) -> str: + filename: str = f"step={step}___rank={rank}___dump_index=0___name={name}.pt" + tensor: torch.Tensor = torch.randn(4) + torch.save({"value": tensor, "meta": {}}, dump_path / filename) + return filename + + +class TestLoadAllValues: + def test_all_success(self, tmp_path: Path) -> None: + """All files load successfully — no warnings emitted.""" + fn0: str = _save_tensor(tmp_path, name="a", rank=0) + fn1: str = _save_tensor(tmp_path, name="a", rank=1) + + sink = LogSink() + with sink.context() as warnings: + with patch( + "sglang.srt.debug_utils.comparator.bundle_comparator.log_sink", + sink, + ): + result = _load_all_values(filenames=[fn0, fn1], base_path=tmp_path) + + assert len(result) == 2 + assert len(warnings) == 0 + + def test_one_corrupted_emits_warning(self, tmp_path: Path) -> None: + """One corrupted file is filtered out and emits a load_failed warning.""" + fn_good: str = _save_tensor(tmp_path, name="a", rank=0) + + fn_bad: str = "step=0___rank=1___dump_index=0___name=a.pt" + (tmp_path / fn_bad).write_text("not a valid pt file") + + sink = LogSink() + with sink.context() as warnings: + with patch( + "sglang.srt.debug_utils.comparator.bundle_comparator.log_sink", + sink, + ): + result = _load_all_values( + filenames=[fn_good, fn_bad], base_path=tmp_path + ) + + assert len(result) == 1 + assert len(warnings) == 1 + assert isinstance(warnings[0], ErrorLog) + assert warnings[0].category == "load_failed" + assert fn_bad in warnings[0].message + + def test_all_corrupted_emits_warnings_returns_empty(self, tmp_path: Path) -> None: + """All files corrupted — returns empty list and emits one warning per file.""" + fn0: str = "step=0___rank=0___dump_index=0___name=a.pt" + fn1: str = "step=0___rank=1___dump_index=0___name=a.pt" + (tmp_path / fn0).write_text("corrupt") + (tmp_path / fn1).write_text("corrupt") + + sink = LogSink() + with sink.context() as warnings: + with patch( + "sglang.srt.debug_utils.comparator.bundle_comparator.log_sink", + sink, + ): + result = _load_all_values(filenames=[fn0, fn1], base_path=tmp_path) + + assert len(result) == 0 + assert len(warnings) == 2 + assert all(w.category == "load_failed" for w in warnings) + + +def _tensor_item(value: torch.Tensor, rank: int = 0) -> ValueWithMeta: + return ValueWithMeta( + value=value, + meta={ + "rank": rank, + "dims": "b s", + "sglang_parallel_info": {}, + "megatron_parallel_info": {}, + "filename": f"rank_{rank}.pt", + }, + ) + + +class TestBuildSkipFromOneEmptySide: + def test_baseline_empty_sets_reason_and_side(self) -> None: + """Empty baseline → reason='baseline_load_failed', available_side='target'.""" + item = _tensor_item(torch.randn(2, 3)) + record = _build_skip_from_one_empty_side( + name="test_tensor", + pair=Pair(x=[], y=[item]), + ) + assert record.reason == "baseline_load_failed" + assert record.available_side == "target" + assert record.available_tensor_info is not None + + def test_target_empty_sets_reason_and_side(self) -> None: + """Empty target → reason='target_load_failed', available_side='baseline'.""" + item = _tensor_item(torch.randn(2, 3)) + record = _build_skip_from_one_empty_side( + name="test_tensor", + pair=Pair(x=[item], y=[]), + ) + assert record.reason == "target_load_failed" + assert record.available_side == "baseline" + assert record.available_tensor_info is not None + + def test_no_tensor_items_returns_minimal_skip(self) -> None: + """All items are non-tensor → skip record with no tensor info.""" + non_tensor_item = ValueWithMeta(value="not_a_tensor", meta={"rank": 0}) + record = _build_skip_from_one_empty_side( + name="test_tensor", + pair=Pair(x=[], y=[non_tensor_item]), + ) + assert record.reason == "baseline_load_failed" + assert record.available_tensor_info is None + assert record.available_bundle_info is None + + def test_with_tensor_items_populates_info(self) -> None: + """Tensor items present → tensor_info and bundle_info are populated.""" + item = _tensor_item(torch.randn(2, 3)) + record = _build_skip_from_one_empty_side( + name="test_tensor", + pair=Pair(x=[], y=[item]), + ) + assert record.available_tensor_info is not None + assert record.available_tensor_info.shape == [2, 3] + assert record.available_bundle_info is not None + assert record.available_bundle_info.num_files >= 1 + + def test_multiple_tensor_items_uses_first_for_info(self) -> None: + """When multiple tensor items exist, tensor_info comes from the first.""" + item1 = _tensor_item(torch.randn(2, 3), rank=0) + item2 = _tensor_item(torch.randn(4, 5), rank=1) + record = _build_skip_from_one_empty_side( + name="multi", + pair=Pair(x=[], y=[item1, item2]), + ) + assert record.available_tensor_info is not None + assert record.available_tensor_info.shape == [2, 3] + assert record.available_bundle_info is not None + assert record.available_bundle_info.num_files == 2 + + def test_mixed_tensor_and_non_tensor_filters_non_tensor(self) -> None: + """Non-tensor items are filtered; tensor_info comes from tensor items only.""" + non_tensor = ValueWithMeta(value="string_value", meta={"rank": 0}) + tensor_item = _tensor_item(torch.randn(5, 6), rank=1) + record = _build_skip_from_one_empty_side( + name="mixed", + pair=Pair(x=[], y=[non_tensor, tensor_item]), + ) + assert record.available_tensor_info is not None + assert record.available_tensor_info.shape == [5, 6] + assert record.available_bundle_info is not None + assert record.available_bundle_info.num_files == 1 + + def test_tensor_info_includes_sample(self) -> None: + """Tensor info should include a sample string for skip records.""" + item = _tensor_item(torch.tensor([1.0, 2.0, 3.0])) + record = _build_skip_from_one_empty_side( + name="sample_check", + pair=Pair(x=[item], y=[]), + ) + assert record.available_tensor_info is not None + assert record.available_tensor_info.sample is not None + + def test_name_preserved_in_record(self) -> None: + """The tensor name is preserved in the skip record.""" + item = _tensor_item(torch.randn(2, 3)) + record = _build_skip_from_one_empty_side( + name="my_layer.weight", + pair=Pair(x=[], y=[item]), + ) + assert record.name == "my_layer.weight" + + def test_bundle_info_has_dims_from_meta(self) -> None: + """Bundle info dims field should come from the meta.""" + item = _tensor_item(torch.randn(2, 3)) + record = _build_skip_from_one_empty_side( + name="dims_check", + pair=Pair(x=[], y=[item]), + ) + assert record.available_bundle_info is not None + assert record.available_bundle_info.dims == "b s" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_matcher.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..17333cd6bbccb1953d40596fce425424f7f48f27 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_bundle_matcher.py @@ -0,0 +1,341 @@ +import sys +from typing import Any + +import polars as pl +import pytest + +from sglang.srt.debug_utils.comparator.bundle_matcher import ( + TensorBundleInfo, + TensorFileInfo, + _rows_to_tensor_infos, + match_bundles, +) +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) + + +def _make_row( + *, + name: str, + step: int = 0, + rank: int = 0, + layer_id: int | None = None, + filename: str | None = None, +) -> dict[str, Any]: + if filename is None: + layer_part: str = f"___layer_id={layer_id}" if layer_id is not None else "" + filename = f"name={name}___step={step}___rank={rank}{layer_part}.pt" + row: dict[str, Any] = { + "name": name, + "step": step, + "rank": rank, + "filename": filename, + } + if layer_id is not None: + row["layer_id"] = layer_id + return row + + +def _make_df(rows: list[dict[str, Any]]) -> pl.DataFrame: + if not rows: + return pl.DataFrame(rows) + + all_keys: set[str] = set() + for row in rows: + all_keys.update(row.keys()) + normalized: list[dict[str, Any]] = [ + {k: row.get(k, None) for k in all_keys} for row in rows + ] + return pl.DataFrame(normalized) + + +class TestMatchBundles: + def test_single_tensor_single_step(self) -> None: + target_df: pl.DataFrame = _make_df([_make_row(name="t_a")]) + baseline_df: pl.DataFrame = _make_df([_make_row(name="t_a")]) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys={"filename"}, + ) + + assert len(results) == 1 + assert len(results[0].x) == 1 + assert len(results[0].y) == 1 + assert results[0].y[0].name == "t_a" + + def test_multiple_names_separate_bundles(self) -> None: + target_df: pl.DataFrame = _make_df( + [ + _make_row(name="t_a"), + _make_row(name="t_b"), + ] + ) + baseline_df: pl.DataFrame = _make_df( + [ + _make_row(name="t_a"), + _make_row(name="t_b"), + ] + ) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys={"filename"}, + ) + + assert len(results) == 2 + result_names: list[str] = [r.y[0].name for r in results] + assert "t_a" in result_names + assert "t_b" in result_names + + def test_skip_rank_groups_across_ranks(self) -> None: + target_df: pl.DataFrame = _make_df( + [ + _make_row(name="t_a", rank=0), + _make_row(name="t_a", rank=1), + ] + ) + baseline_df: pl.DataFrame = _make_df( + [ + _make_row(name="t_a", rank=0), + _make_row(name="t_a", rank=1), + ] + ) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys={"filename", "rank"}, + ) + + assert len(results) == 1 + assert len(results[0].y) == 2 + + def test_baseline_missing_tensor(self) -> None: + target_df: pl.DataFrame = _make_df( + [ + _make_row(name="t_a"), + _make_row(name="t_extra"), + ] + ) + baseline_df: pl.DataFrame = _make_df( + [ + _make_row(name="t_a"), + ] + ) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys={"filename"}, + ) + + assert len(results) == 2 + extra_pair: Pair[TensorBundleInfo] = [ + r for r in results if r.y[0].name == "t_extra" + ][0] + assert extra_pair.x == [] + + def test_empty_target_returns_empty(self) -> None: + target_df: pl.DataFrame = _make_df([]) + baseline_df: pl.DataFrame = _make_df([_make_row(name="t_a")]) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys={"filename"}, + ) + + assert results == [] + + def test_skip_step_groups_across_steps(self) -> None: + target_df: pl.DataFrame = _make_df( + [ + _make_row(name="t_a", step=0), + _make_row(name="t_a", step=1), + ] + ) + baseline_df: pl.DataFrame = _make_df( + [ + _make_row(name="t_a", step=0), + _make_row(name="t_a", step=1), + ] + ) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys={"filename", "step"}, + ) + + assert len(results) == 1 + assert len(results[0].y) == 2 + + +class TestMatchBundlesPipelineParallel: + """Tests verifying that PP works correctly with the existing matching logic.""" + + LOGICAL_SKIP_KEYS: set[str] = {"filename", "rank", "dump_index", "recompute_status"} + + def test_same_layer_id_different_ranks_match(self) -> None: + """SGLang PP=2 rank 0 (layers 0-31) vs Megatron PP=4 rank 2 (layers 16-31): + layer_id=20 should match regardless of world rank.""" + target_df: pl.DataFrame = _make_df( + [_make_row(name="hidden", rank=0, layer_id=20)] + ) + baseline_df: pl.DataFrame = _make_df( + [_make_row(name="hidden", rank=2, layer_id=20)] + ) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys=self.LOGICAL_SKIP_KEYS, + ) + + assert len(results) == 1 + assert len(results[0].x) == 1 + assert len(results[0].y) == 1 + + def test_layer_id_none_non_layer_tensors_match(self) -> None: + """Non-layer tensors (embedding, lm_head) have no layer_id. + They should match across different PP ranks.""" + target_df: pl.DataFrame = _make_df([_make_row(name="embed_tokens", rank=0)]) + baseline_df: pl.DataFrame = _make_df([_make_row(name="embed_tokens", rank=0)]) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys=self.LOGICAL_SKIP_KEYS, + ) + + assert len(results) == 1 + assert len(results[0].x) == 1 + assert len(results[0].y) == 1 + + def test_different_pp_sizes_layer_and_non_layer_bundles(self) -> None: + """SGLang PP=2 TP=2 (4 ranks) vs Megatron PP=4 TP=2 (8 ranks). + Layer tensors match by (name, layer_id); non-layer tensors match by name. + All ranks are grouped into the same bundle when rank is skipped.""" + target_df: pl.DataFrame = _make_df( + [ + # SGLang: pp_stage=0 has ranks 0,1 (TP=2) + _make_row(name="hidden", rank=0, layer_id=20), + _make_row(name="hidden", rank=1, layer_id=20), + # SGLang: embedding on pp_stage=0 + _make_row(name="embed_tokens", rank=0), + _make_row(name="embed_tokens", rank=1), + # SGLang: lm_head on pp_stage=1, ranks 2,3 + _make_row(name="lm_head", rank=2), + _make_row(name="lm_head", rank=3), + ] + ) + baseline_df: pl.DataFrame = _make_df( + [ + # Megatron: pp_stage=1 has ranks 2,3 for layer 20 + _make_row(name="hidden", rank=2, layer_id=20), + _make_row(name="hidden", rank=3, layer_id=20), + # Megatron: embedding on pp_stage=0 + _make_row(name="embed_tokens", rank=0), + _make_row(name="embed_tokens", rank=1), + # Megatron: lm_head on pp_stage=3, ranks 6,7 + _make_row(name="lm_head", rank=6), + _make_row(name="lm_head", rank=7), + ] + ) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys=self.LOGICAL_SKIP_KEYS, + ) + + assert len(results) == 3 + names_to_pairs: dict[str, Pair[TensorBundleInfo]] = {} + for pair in results: + key: str = pair.y[0].name + layer_suffix: str = "" + if "layer_id" in target_df.columns: + row_match = [ + r + for r in target_df.to_dicts() + if r["filename"] == pair.y[0].filename + ] + if row_match and row_match[0].get("layer_id") is not None: + layer_suffix = f"_{row_match[0]['layer_id']}" + names_to_pairs[key + layer_suffix] = pair + + assert len(names_to_pairs["hidden_20"].x) == 2 + assert len(names_to_pairs["hidden_20"].y) == 2 + assert len(names_to_pairs["embed_tokens"].x) == 2 + assert len(names_to_pairs["embed_tokens"].y) == 2 + assert len(names_to_pairs["lm_head"].x) == 2 + assert len(names_to_pairs["lm_head"].y) == 2 + + def test_unmatched_layer_id_creates_empty_baseline(self) -> None: + """If target has a layer_id that baseline doesn't, the baseline side + should be empty (not incorrectly matched to a different layer).""" + target_df: pl.DataFrame = _make_df( + [ + _make_row(name="hidden", rank=0, layer_id=10), + _make_row(name="hidden", rank=0, layer_id=20), + ] + ) + baseline_df: pl.DataFrame = _make_df( + [ + _make_row(name="hidden", rank=0, layer_id=10), + ] + ) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys=self.LOGICAL_SKIP_KEYS, + ) + + assert len(results) == 2 + matched: list[Pair[TensorBundleInfo]] = [r for r in results if r.x] + unmatched: list[Pair[TensorBundleInfo]] = [r for r in results if not r.x] + assert len(matched) == 1 + assert len(unmatched) == 1 + + def test_pp1_vs_pp_gt1_matches_by_layer_id(self) -> None: + """PP=1 (all layers on 1 rank) vs PP>1 (layers split across ranks). + Should match correctly by layer_id regardless of rank.""" + target_df: pl.DataFrame = _make_df( + [ + # PP=1: all on rank 0 + _make_row(name="hidden", rank=0, layer_id=0), + _make_row(name="hidden", rank=0, layer_id=1), + ] + ) + baseline_df: pl.DataFrame = _make_df( + [ + # PP=2: layer 0 on rank 0, layer 1 on rank 1 + _make_row(name="hidden", rank=0, layer_id=0), + _make_row(name="hidden", rank=1, layer_id=1), + ] + ) + + results: list[Pair[TensorBundleInfo]] = match_bundles( + dfs=Pair(x=baseline_df, y=target_df), + skip_keys=self.LOGICAL_SKIP_KEYS, + ) + + assert len(results) == 2 + for pair in results: + assert len(pair.x) == 1 + assert len(pair.y) == 1 + + +class TestRowsToTensorInfos: + def test_filters_extra_columns(self) -> None: + rows: list[dict[str, Any]] = [ + {"filename": "a.pt", "name": "t_a", "step": 0, "rank": 7} + ] + infos: list[TensorFileInfo] = _rows_to_tensor_infos(rows) + + assert len(infos) == 1 + assert infos[0] == TensorFileInfo(filename="a.pt", name="t_a", step=0) + + def test_empty_rows(self) -> None: + infos: list[TensorFileInfo] = _rows_to_tensor_infos([]) + assert infos == [] + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_display.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_display.py new file mode 100644 index 0000000000000000000000000000000000000000..46b63ad64e031d9ad31ff16f44eb857a35b318fd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_display.py @@ -0,0 +1,500 @@ +import sys +from io import StringIO +from pathlib import Path +from typing import Any, Optional + +import polars as pl +import pytest +import torch +from rich.console import Console + +from sglang.srt.debug_utils.comparator.display import ( + _collect_input_ids_and_positions, + _collect_rank_info, + _extract_parallel_info, + _render_polars_as_rich_table, + _render_polars_as_text, +) +from sglang.srt.debug_utils.comparator.output_types import ( + InputIdsRecord, + RankInfoRecord, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) + + +def _render_rich(renderable: object) -> str: + buf: StringIO = StringIO() + Console(file=buf, force_terminal=False, width=120).print(renderable) + return buf.getvalue().rstrip("\n") + + +def _save_dump_file( + directory: Path, + *, + name: str, + step: int, + rank: int, + dump_index: int, + value: torch.Tensor, + meta: dict, +) -> str: + filename = f"name={name}___step={step}___rank={rank}___dump_index={dump_index}.pt" + torch.save({"value": value, "meta": meta}, directory / filename) + return filename + + +def _make_df(rows: list[dict]) -> pl.DataFrame: + df = pl.DataFrame(rows) + df = df.with_columns( + pl.col("step").cast(int), + pl.col("rank").cast(int), + pl.col("dump_index").cast(int), + ) + return df + + +class TestRenderPolarsAsText: + def test_renders_table(self) -> None: + df = pl.DataFrame({"col_a": [1, 2], "col_b": ["x", "y"]}) + text: str = _render_polars_as_text(df, title="test table") + + assert "test table" in text + assert "col_a" in text + assert "col_b" in text + + def test_renders_empty_dataframe(self) -> None: + df = pl.DataFrame({"a": [], "b": []}) + text: str = _render_polars_as_text(df, title="empty") + assert "empty" in text + + +class TestCollectRankInfo: + def test_collects_rank_info(self, tmp_path: Path) -> None: + sglang_info = { + "tp_rank": 0, + "tp_size": 2, + "pp_rank": 0, + "pp_size": 1, + } + filename: str = _save_dump_file( + tmp_path, + name="input_ids", + step=0, + rank=0, + dump_index=0, + value=torch.tensor([1, 2, 3]), + meta={"sglang_parallel_info": sglang_info}, + ) + df = _make_df( + [ + { + "filename": filename, + "name": "input_ids", + "step": 0, + "rank": 0, + "dump_index": 0, + } + ] + ) + + rows: Optional[list[dict[str, Any]]] = _collect_rank_info(df, dump_dir=tmp_path) + + assert rows is not None + assert len(rows) == 1 + assert rows[0]["rank"] == 0 + assert rows[0]["tp"] == "0/2" + assert rows[0]["pp"] == "0/1" + + def test_returns_none_when_no_input_ids(self, tmp_path: Path) -> None: + df = _make_df( + [ + { + "filename": "f.pt", + "name": "some_other", + "step": 0, + "rank": 0, + "dump_index": 0, + } + ] + ) + result = _collect_rank_info(df, dump_dir=tmp_path) + assert result is None + + def test_deduplicates_ranks(self, tmp_path: Path) -> None: + meta = {"sglang_parallel_info": {"tp_rank": 0, "tp_size": 1}} + f1: str = _save_dump_file( + tmp_path, + name="input_ids", + step=0, + rank=0, + dump_index=0, + value=torch.tensor([1]), + meta=meta, + ) + f2: str = _save_dump_file( + tmp_path, + name="input_ids", + step=1, + rank=0, + dump_index=1, + value=torch.tensor([2]), + meta=meta, + ) + df = _make_df( + [ + { + "filename": f1, + "name": "input_ids", + "step": 0, + "rank": 0, + "dump_index": 0, + }, + { + "filename": f2, + "name": "input_ids", + "step": 1, + "rank": 0, + "dump_index": 1, + }, + ] + ) + + rows = _collect_rank_info(df, dump_dir=tmp_path) + + assert rows is not None + assert len(rows) == 1 + + +class TestCollectInputIdsAndPositions: + def test_collects_ids_and_positions(self, tmp_path: Path) -> None: + f_ids: str = _save_dump_file( + tmp_path, + name="input_ids", + step=0, + rank=0, + dump_index=0, + value=torch.tensor([10, 20, 30]), + meta={}, + ) + f_pos: str = _save_dump_file( + tmp_path, + name="positions", + step=0, + rank=0, + dump_index=1, + value=torch.tensor([0, 1, 2]), + meta={}, + ) + df = _make_df( + [ + { + "filename": f_ids, + "name": "input_ids", + "step": 0, + "rank": 0, + "dump_index": 0, + }, + { + "filename": f_pos, + "name": "positions", + "step": 0, + "rank": 0, + "dump_index": 1, + }, + ] + ) + + rows = _collect_input_ids_and_positions(df, dump_dir=tmp_path) + + assert rows is not None + assert len(rows) == 1 + assert rows[0]["step"] == 0 + assert rows[0]["rank"] == 0 + assert rows[0]["num_tokens"] == 3 + assert "10" in rows[0]["input_ids"] + assert "0" in rows[0]["positions"] + + def test_returns_none_when_empty(self, tmp_path: Path) -> None: + df = _make_df( + [ + { + "filename": "f.pt", + "name": "weight", + "step": 0, + "rank": 0, + "dump_index": 0, + } + ] + ) + result = _collect_input_ids_and_positions(df, dump_dir=tmp_path) + assert result is None + + def test_with_mock_tokenizer(self, tmp_path: Path) -> None: + f_ids: str = _save_dump_file( + tmp_path, + name="input_ids", + step=0, + rank=0, + dump_index=0, + value=torch.tensor([1, 2]), + meta={}, + ) + df = _make_df( + [ + { + "filename": f_ids, + "name": "input_ids", + "step": 0, + "rank": 0, + "dump_index": 0, + } + ] + ) + + class _MockTokenizer: + def decode(self, ids: list[int], skip_special_tokens: bool = False) -> str: + return f"decoded:{ids}" + + rows = _collect_input_ids_and_positions( + df, dump_dir=tmp_path, tokenizer=_MockTokenizer() + ) + + assert rows is not None + assert "decoded_text" in rows[0] + assert "decoded:" in rows[0]["decoded_text"] + + +class TestRankInfoRecordSnapshot: + def test_to_text_snapshot(self) -> None: + record = RankInfoRecord( + label="baseline", + rows=[ + {"rank": 0, "tp": "0/2", "pp": "0/1"}, + {"rank": 1, "tp": "1/2", "pp": "0/1"}, + ], + ) + text: str = record.to_text() + + assert "baseline ranks" in text + assert "rank" in text + assert "tp" in text + assert "pp" in text + assert "0/2" in text + assert "1/2" in text + assert "0/1" in text + + def test_to_rich_snapshot(self) -> None: + from rich.table import Table + + record = RankInfoRecord( + label="baseline", + rows=[ + {"rank": 0, "tp": "0/2", "pp": "0/1"}, + {"rank": 1, "tp": "1/2", "pp": "0/1"}, + ], + ) + body = record._format_rich_body() + + assert isinstance(body, Table) + rendered: str = _render_rich(body) + assert "baseline ranks" in rendered + assert "0/2" in rendered + assert "1/2" in rendered + + def test_json_roundtrip(self) -> None: + record = RankInfoRecord( + label="target", + rows=[{"rank": 0, "tp": "0/4"}], + ) + json_str: str = record.model_dump_json() + + assert '"type":"rank_info"' in json_str + assert '"label":"target"' in json_str + assert '"tp":"0/4"' in json_str + + +class TestInputIdsRecordSnapshot: + def test_to_text_snapshot(self) -> None: + record = InputIdsRecord( + label="target", + rows=[ + { + "step": 0, + "rank": 0, + "num_tokens": 3, + "input_ids": "[10, 20, 30]", + "positions": "[0, 1, 2]", + }, + ], + ) + text: str = record.to_text() + + assert "target input_ids & positions" in text + assert "step" in text + assert "num_tokens" in text + assert "10, 20, 30" in text + assert "0, 1, 2" in text + + def test_to_rich_snapshot(self) -> None: + from rich.table import Table + + record = InputIdsRecord( + label="target", + rows=[ + { + "step": 0, + "rank": 0, + "num_tokens": 3, + "input_ids": "[10, 20, 30]", + "positions": "[0, 1, 2]", + }, + ], + ) + body = record._format_rich_body() + + assert isinstance(body, Table) + rendered: str = _render_rich(body) + assert "target input_ids & positions" in rendered + assert "10, 20, 30" in rendered + assert "0, 1, 2" in rendered + + def test_json_roundtrip(self) -> None: + record = InputIdsRecord( + label="baseline", + rows=[ + { + "step": 0, + "rank": 0, + "num_tokens": 2, + "input_ids": "[1, 2]", + "positions": "[0, 1]", + "decoded_text": "'hello'", + }, + ], + ) + json_str: str = record.model_dump_json() + + assert '"type":"input_ids"' in json_str + assert '"label":"baseline"' in json_str + assert '"decoded_text"' in json_str + + def test_to_text_with_decoded(self) -> None: + record = InputIdsRecord( + label="test", + rows=[ + { + "step": 0, + "rank": 0, + "num_tokens": 2, + "input_ids": "[1, 2]", + "positions": "[0, 1]", + "decoded_text": "'hello world'", + }, + ], + ) + text: str = record.to_text() + + assert "decoded_text" in text + assert "hello world" in text + + +class TestExtractParallelInfo: + def test_extracts_rank_size_pairs(self) -> None: + info: dict = { + "tp_rank": 1, + "tp_size": 4, + "pp_rank": 0, + "pp_size": 2, + } + row_data: dict = {} + _extract_parallel_info(row_data=row_data, info=info) + + assert row_data["tp"] == "1/4" + assert row_data["pp"] == "0/2" + + def test_skips_error_info(self) -> None: + row_data: dict = {} + _extract_parallel_info( + row_data=row_data, info={"error": True, "tp_rank": 0, "tp_size": 1} + ) + assert row_data == {} + + def test_skips_empty_info(self) -> None: + row_data: dict = {} + _extract_parallel_info(row_data=row_data, info={}) + assert row_data == {} + + def test_ignores_rank_without_size(self) -> None: + row_data: dict = {} + _extract_parallel_info(row_data=row_data, info={"tp_rank": 0}) + assert "tp" not in row_data + + +class TestRenderPolarsAsRichTable: + def test_basic_dataframe_renders_table(self) -> None: + df = pl.DataFrame({"a": [1, 2], "b": ["x", "y"]}) + table = _render_polars_as_rich_table(df) + assert len(table.columns) == 2 + assert table.row_count == 2 + + def test_empty_dataframe_returns_table_with_no_rows(self) -> None: + df = pl.DataFrame( + {"a": pl.Series([], dtype=pl.Int64), "b": pl.Series([], dtype=pl.Utf8)} + ) + table = _render_polars_as_rich_table(df) + assert len(table.columns) == 2 + assert table.row_count == 0 + + def test_title_passed_to_table(self) -> None: + df = pl.DataFrame({"a": [1]}) + table = _render_polars_as_rich_table(df, title="My Title") + assert table.title == "My Title" + + def test_no_title_defaults_to_none(self) -> None: + df = pl.DataFrame({"x": [1]}) + table = _render_polars_as_rich_table(df) + assert table.title is None + + def test_column_names_match_dataframe(self) -> None: + df = pl.DataFrame({"alpha": [1], "beta": [2], "gamma": [3]}) + table = _render_polars_as_rich_table(df) + column_headers: list[str] = [col.header for col in table.columns] + assert column_headers == ["alpha", "beta", "gamma"] + + def test_values_converted_to_strings(self) -> None: + """Numeric and None values should be stringified in the rendered output.""" + df = pl.DataFrame({"num": [42], "text": ["hello"]}) + table = _render_polars_as_rich_table(df) + rendered: str = _render_rich(table) + assert "42" in rendered + assert "hello" in rendered + + def test_single_column_dataframe(self) -> None: + df = pl.DataFrame({"only_col": [10, 20, 30]}) + table = _render_polars_as_rich_table(df) + assert len(table.columns) == 1 + assert table.row_count == 3 + + def test_many_rows_all_present(self) -> None: + """All rows from the dataframe appear in the rich table.""" + df = pl.DataFrame({"val": list(range(50))}) + table = _render_polars_as_rich_table(df) + assert table.row_count == 50 + + def test_null_values_rendered_as_string(self) -> None: + """Null values should be converted to their string representation.""" + df = pl.DataFrame({"a": [1, None, 3]}) + table = _render_polars_as_rich_table(df) + assert table.row_count == 3 + rendered: str = _render_rich(table) + assert ( + "null" in rendered.lower() + or "none" in rendered.lower() + or "None" in rendered + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dp_utils.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a624f78b0b0486bc909bea4ef38d791458566ee6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dp_utils.py @@ -0,0 +1,350 @@ +import sys + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis +from sglang.srt.debug_utils.comparator.dp_utils import ( + _extract_dp_info, + _group_has_data, + filter_to_non_empty_dp_rank, +) +from sglang.srt.debug_utils.dump_loader import ValueWithMeta +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="base-a-test-cpu", nightly=True) + + +def _make_sglang_meta( + *, tp_rank: int = 0, tp_size: int = 1, dp_rank: int = 0, dp_size: int = 1 +) -> dict: + return { + "sglang_parallel_info": { + "tp_rank": tp_rank, + "tp_size": tp_size, + "dp_rank": dp_rank, + "dp_size": dp_size, + } + } + + +def _make_megatron_meta( + *, tp_rank: int = 0, tp_size: int = 1, dp_rank: int = 0, dp_size: int = 1 +) -> dict: + return { + "megatron_parallel_info": { + "tp_rank": tp_rank, + "tp_size": tp_size, + "dp_rank": dp_rank, + "dp_size": dp_size, + } + } + + +def _make_item(value: object, meta: dict) -> ValueWithMeta: + return ValueWithMeta(value=value, meta=meta) + + +# --------------------------------------------------------------------------- +# _extract_dp_info +# --------------------------------------------------------------------------- + + +class TestExtractDpInfo: + def test_sglang_dp(self) -> None: + meta: dict = _make_sglang_meta(dp_rank=1, dp_size=4) + assert _extract_dp_info(meta, dp_axis=ParallelAxis.DP) == (1, 4) + + def test_megatron_dp(self) -> None: + meta: dict = _make_megatron_meta(dp_rank=2, dp_size=8) + assert _extract_dp_info(meta, dp_axis=ParallelAxis.DP) == (2, 8) + + def test_no_parallel_info(self) -> None: + assert _extract_dp_info({}, dp_axis=ParallelAxis.DP) is None + + def test_no_dp_fields(self) -> None: + meta: dict = {"sglang_parallel_info": {"tp_rank": 0, "tp_size": 2}} + assert _extract_dp_info(meta, dp_axis=ParallelAxis.DP) is None + + +# --------------------------------------------------------------------------- +# _group_has_data +# --------------------------------------------------------------------------- + + +class TestGroupHasData: + def test_non_empty_tensor(self) -> None: + item: ValueWithMeta = _make_item(value=torch.tensor([1, 2, 3]), meta={}) + assert _group_has_data([item]) is True + + def test_empty_tensor(self) -> None: + item: ValueWithMeta = _make_item(value=torch.tensor([]), meta={}) + assert _group_has_data([item]) is False + + def test_non_tensor_value(self) -> None: + item: ValueWithMeta = _make_item(value="hello", meta={}) + assert _group_has_data([item]) is False + + def test_empty_group(self) -> None: + assert _group_has_data([]) is False + + +# --------------------------------------------------------------------------- +# filter_to_non_empty_dp_rank +# --------------------------------------------------------------------------- + + +class TestFilterToNonEmptyDpRank: + def test_dp_size_1_returns_unchanged(self) -> None: + items: list[ValueWithMeta] = [ + _make_item( + value=torch.tensor([1.0]), + meta=_make_sglang_meta(dp_size=1), + ), + ] + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.DP + ) + assert result is items + + def test_no_parallel_info_returns_unchanged(self) -> None: + items: list[ValueWithMeta] = [ + _make_item(value=torch.tensor([1.0]), meta={}), + ] + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.DP + ) + assert result is items + + def test_empty_list_returns_empty(self) -> None: + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + [], dp_axis=ParallelAxis.DP + ) + assert result == [] + + def test_dp2_all_non_tensor_returns_unchanged(self) -> None: + """DP=2 with non-tensor values: skip filtering, return unchanged.""" + items: list[ValueWithMeta] = [ + _make_item( + value=["req_A"], + meta=_make_sglang_meta(dp_rank=0, dp_size=2), + ), + _make_item( + value=["req_A"], + meta=_make_sglang_meta(dp_rank=1, dp_size=2), + ), + ] + + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.DP + ) + + assert result is items + + def test_dp2_one_empty_one_nonempty_sglang(self) -> None: + """DP=2, rank 0 has data, rank 1 has empty tensor.""" + items: list[ValueWithMeta] = [ + _make_item( + value=torch.tensor([1.0, 2.0]), + meta=_make_sglang_meta(dp_rank=0, dp_size=2), + ), + _make_item( + value=torch.tensor([]), + meta=_make_sglang_meta(dp_rank=1, dp_size=2), + ), + ] + + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.DP + ) + + assert len(result) == 1 + assert torch.equal(result[0].value, torch.tensor([1.0, 2.0])) + + def test_dp2_one_empty_one_nonempty_megatron(self) -> None: + """DP=2 megatron, rank 1 has data, rank 0 has empty tensor.""" + items: list[ValueWithMeta] = [ + _make_item( + value=torch.tensor([]), + meta=_make_megatron_meta(dp_rank=0, dp_size=2), + ), + _make_item( + value=torch.tensor([3.0, 4.0]), + meta=_make_megatron_meta(dp_rank=1, dp_size=2), + ), + ] + + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.DP + ) + + assert len(result) == 1 + assert torch.equal(result[0].value, torch.tensor([3.0, 4.0])) + + def test_dp2_both_nonempty_raises(self) -> None: + """DP=2, both ranks have data: assertion error.""" + items: list[ValueWithMeta] = [ + _make_item( + value=torch.tensor([1.0]), + meta=_make_sglang_meta(dp_rank=0, dp_size=2), + ), + _make_item( + value=torch.tensor([2.0]), + meta=_make_sglang_meta(dp_rank=1, dp_size=2), + ), + ] + + with pytest.raises( + AssertionError, match="Expected exactly 1 non-empty dp_rank" + ): + filter_to_non_empty_dp_rank(items, dp_axis=ParallelAxis.DP) + + def test_dp2_with_tp2_filters_correctly(self) -> None: + """DP=2 x TP=2: 4 items total, 2 non-empty from dp_rank=0.""" + items: list[ValueWithMeta] = [ + _make_item( + value=torch.tensor([1.0]), + meta=_make_sglang_meta(tp_rank=0, tp_size=2, dp_rank=0, dp_size=2), + ), + _make_item( + value=torch.tensor([2.0]), + meta=_make_sglang_meta(tp_rank=1, tp_size=2, dp_rank=0, dp_size=2), + ), + _make_item( + value=torch.tensor([]), + meta=_make_sglang_meta(tp_rank=0, tp_size=2, dp_rank=1, dp_size=2), + ), + _make_item( + value=torch.tensor([]), + meta=_make_sglang_meta(tp_rank=1, tp_size=2, dp_rank=1, dp_size=2), + ), + ] + + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.DP + ) + + assert len(result) == 2 + assert torch.equal(result[0].value, torch.tensor([1.0])) + assert torch.equal(result[1].value, torch.tensor([2.0])) + + +# --------------------------------------------------------------------------- +# dp_axis tests (non-default axis) +# --------------------------------------------------------------------------- + + +class TestExtractDpInfoWithAxis: + def test_moe_dp_axis_found(self) -> None: + meta: dict = { + "sglang_parallel_info": { + "dp_rank": 0, + "dp_size": 2, + "moe_dp_rank": 1, + "moe_dp_size": 4, + } + } + assert _extract_dp_info(meta, dp_axis=ParallelAxis.MOE_DP) == (1, 4) + + def test_moe_dp_axis_not_found_returns_none(self) -> None: + meta: dict = _make_sglang_meta(dp_rank=0, dp_size=2) + assert _extract_dp_info(meta, dp_axis=ParallelAxis.MOE_DP) is None + + def test_dp_axis_uses_default_fields(self) -> None: + meta: dict = _make_sglang_meta(dp_rank=1, dp_size=4) + assert _extract_dp_info(meta, dp_axis=ParallelAxis.DP) == (1, 4) + + +class TestFilterToNonEmptyDpRankWithAxis: + def test_dp_axis_unchanged_behavior(self) -> None: + """dp_axis=ParallelAxis.DP → same behavior as default (regression).""" + items: list[ValueWithMeta] = [ + _make_item( + value=torch.tensor([1.0, 2.0]), + meta=_make_sglang_meta(dp_rank=0, dp_size=2), + ), + _make_item( + value=torch.tensor([]), + meta=_make_sglang_meta(dp_rank=1, dp_size=2), + ), + ] + + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.DP + ) + + assert len(result) == 1 + assert torch.equal(result[0].value, torch.tensor([1.0, 2.0])) + + def test_moe_dp_axis_absent_noop(self) -> None: + """MOE_DP axis fields not in metadata → noop, return items unchanged.""" + items: list[ValueWithMeta] = [ + _make_item( + value=torch.tensor([1.0]), + meta=_make_sglang_meta(dp_rank=0, dp_size=2), + ), + _make_item( + value=torch.tensor([2.0]), + meta=_make_sglang_meta(dp_rank=1, dp_size=2), + ), + ] + + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.MOE_DP + ) + + assert result is items + + def test_moe_dp_axis_size_1_noop(self) -> None: + """MOE_DP axis present but size=1 → noop.""" + meta: dict = { + "sglang_parallel_info": { + "dp_rank": 0, + "dp_size": 2, + "moe_dp_rank": 0, + "moe_dp_size": 1, + } + } + items: list[ValueWithMeta] = [ + _make_item(value=torch.tensor([1.0]), meta=meta), + ] + + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.MOE_DP + ) + + assert result is items + + def test_moe_dp_axis_filters_correctly(self) -> None: + """MOE_DP axis size=2, one empty rank → correctly filters.""" + meta_rank0: dict = { + "sglang_parallel_info": { + "dp_rank": 0, + "dp_size": 2, + "moe_dp_rank": 0, + "moe_dp_size": 2, + } + } + meta_rank1: dict = { + "sglang_parallel_info": { + "dp_rank": 0, + "dp_size": 2, + "moe_dp_rank": 1, + "moe_dp_size": 2, + } + } + items: list[ValueWithMeta] = [ + _make_item(value=torch.tensor([1.0, 2.0]), meta=meta_rank0), + _make_item(value=torch.tensor([]), meta=meta_rank1), + ] + + result: list[ValueWithMeta] = filter_to_non_empty_dp_rank( + items, dp_axis=ParallelAxis.MOE_DP + ) + + assert len(result) == 1 + assert torch.equal(result[0].value, torch.tensor([1.0, 2.0])) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dump_loader.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dump_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..40df022b7bdcf1236d8e6d8a0011dd1523297e08 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_dump_loader.py @@ -0,0 +1,62 @@ +import sys +from pathlib import Path + +import pytest +import torch + +from sglang.srt.debug_utils.dump_loader import read_tokenizer_path +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) + + +def _save_pt( + directory: Path, filename: str, *, value: torch.Tensor, meta: dict +) -> None: + torch.save({"value": value, "meta": meta}, directory / filename) + + +class TestReadTokenizerPath: + def test_finds_tokenizer_path(self, tmp_path: Path) -> None: + _save_pt( + tmp_path, + "name=x___step=0___rank=0___dump_index=0.pt", + value=torch.tensor([1.0]), + meta={"tokenizer_path": "/models/llama-3"}, + ) + result = read_tokenizer_path(tmp_path) + assert result == "/models/llama-3" + + def test_returns_none_when_no_tokenizer_path(self, tmp_path: Path) -> None: + _save_pt( + tmp_path, + "name=x___step=0___rank=0___dump_index=0.pt", + value=torch.tensor([1.0]), + meta={}, + ) + result = read_tokenizer_path(tmp_path) + assert result is None + + def test_returns_none_for_empty_directory(self, tmp_path: Path) -> None: + result = read_tokenizer_path(tmp_path) + assert result is None + + def test_skips_files_without_tokenizer_path(self, tmp_path: Path) -> None: + _save_pt( + tmp_path, + "name=a___step=0___rank=0___dump_index=0.pt", + value=torch.tensor([1.0]), + meta={}, + ) + _save_pt( + tmp_path, + "name=b___step=0___rank=0___dump_index=1.pt", + value=torch.tensor([2.0]), + meta={"tokenizer_path": "/models/deepseek"}, + ) + result = read_tokenizer_path(tmp_path) + assert result == "/models/deepseek" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_e2e_demo.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_e2e_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..7c3926bb1a4dc68bb6d40a694e2053c7927a7ac3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_e2e_demo.py @@ -0,0 +1,249 @@ +"""Minimal demo: run the comparator on synthetic data and print its output. + +This is NOT a correctness test suite. +The sole purpose is to let a new user run ``pytest -s test_e2e_demo.py`` +and immediately see what comparator text output looks like (passed, failed, +skipped in one shot). Correctness is verified via the JSONL report file. +""" + +from __future__ import annotations + +import sys +from pathlib import Path +from typing import Dict, List, Optional + +import pytest +import torch + +import sglang.srt.debug_utils.dumper as _dumper_module +from sglang.srt.debug_utils.comparator.entrypoint import parse_args, run +from sglang.srt.debug_utils.comparator.output_types import ( + AnyRecord, + ComparisonErrorRecord, + SummaryRecord, + parse_record_json, +) +from sglang.srt.debug_utils.dumper import DumperConfig, _Dumper +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="default", nightly=True) + +_EXP_NAME = "demo_exp" + + +# This file has exactly ONE test. All demo scenarios go here — do not add separate tests. +def test_demo(tmp_path: Path) -> None: + """Passed + failed + skipped + sharded + errored in a single demo file.""" + torch.manual_seed(0) + good_tensor = torch.randn(4, 8) + sharded_full = torch.randn(2, 8, 16) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + # Step 1: simple tensors (single rank, no parallelism) + _dump_single(baseline_dir, name="my_good_tensor", tensor=good_tensor) + _dump_single(baseline_dir, name="my_bad_tensor", tensor=torch.randn(4, 8)) + + _dump_single( + target_dir, name="my_good_tensor", tensor=good_tensor + torch.randn(4, 8) * 1e-5 + ) + _dump_single(target_dir, name="my_bad_tensor", tensor=torch.randn(4, 8) * 100) + _dump_single(target_dir, name="my_orphan_tensor", tensor=torch.randn(4, 8)) + + # Step 2: sharded tensor (BSHD) — baseline: TP=2 on h, target: CP=2 zigzag + SP=2 on s + sharded_target = sharded_full + torch.randn_like(sharded_full) * 1e-5 + _dump_tp_sharded( + baseline_dir, name="my_sharded_tensor", full_tensor=sharded_full, tp_size=2 + ) + _dump_cp_zigzag_sp_sharded( + target_dir, + name="my_sharded_tensor", + full_tensor=sharded_target, + cp_size=2, + sp_size=2, + ) + + # Step 3: bad dims — target says h[cp] but parallel_info has tp → undeclared axis error + bad_dims_tensor = torch.randn(2, 8, 16) + for tp_rank, shard in enumerate(bad_dims_tensor.chunk(2, dim=-1)): + _dump_rank( + baseline_dir, + rank=tp_rank, + name="my_bad_dims_tensor", + tensor=shard, + dims="b s h[tp]", + parallel_info={"tp_rank": tp_rank, "tp_size": 2}, + ) + _dump_rank( + target_dir, + rank=tp_rank, + name="my_bad_dims_tensor", + tensor=shard, + dims="b s h[cp]", + parallel_info={"tp_rank": tp_rank, "tp_size": 2}, + ) + + baseline_exp = baseline_dir / _EXP_NAME + target_exp = target_dir / _EXP_NAME + + # Step 4: run normal, then verbose + for verbosity in ("normal", "verbose"): + report_path = tmp_path / f"report_{verbosity}.jsonl" + _run( + baseline_exp, + target_exp, + report_path=report_path, + output_format="text", + verbosity=verbosity, + ) + _assert_summary(report_path, passed=2, failed=1, skipped=1, errored=1) + + # Step 5: verify error record content + records = _read_report(tmp_path / "report_verbose.jsonl") + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) == 1 + assert "tp" in errors[0].exception_message + assert "--override-dims" in errors[0].traceback_str + + +# ── Helpers ────────────────────────────────────────────────────────── + + +def _assert_summary( + report_path: Path, *, passed: int, failed: int, skipped: int, errored: int = 0 +) -> None: + records = _read_report(report_path) + summary = next(r for r in records if isinstance(r, SummaryRecord)) + assert summary.passed == passed + assert summary.failed == failed + assert summary.skipped == skipped + assert summary.errored == errored + + +def _dump_single(directory: Path, *, name: str, tensor: torch.Tensor) -> None: + _dump_rank(directory, rank=0, name=name, tensor=tensor) + + +def _dump_tp_sharded( + directory: Path, + *, + name: str, + full_tensor: torch.Tensor, + tp_size: int, +) -> None: + """Dump TP-sharded tensor: dims="b s h[tp]", shard along last dim.""" + shards = list(full_tensor.chunk(tp_size, dim=-1)) + for tp_rank, shard in enumerate(shards): + _dump_rank( + directory, + rank=tp_rank, + name=name, + tensor=shard, + dims="b s h[tp]", + parallel_info={"tp_rank": tp_rank, "tp_size": tp_size}, + ) + + +def _dump_cp_zigzag_sp_sharded( + directory: Path, + *, + name: str, + full_tensor: torch.Tensor, + cp_size: int, + sp_size: int, +) -> None: + """Dump CP-zigzag+SP sharded tensor: dims="b s[cp:zigzag,sp] h", shard seq dim.""" + seq_dim = 1 + num_chunks = cp_size * 2 + natural_chunks = list(full_tensor.chunk(num_chunks, dim=seq_dim)) + + zigzag_order: List[int] = [] + for i in range(cp_size): + zigzag_order.append(i) + zigzag_order.append(num_chunks - 1 - i) + + zigzagged = torch.cat([natural_chunks[idx] for idx in zigzag_order], dim=seq_dim) + cp_chunks = list(zigzagged.chunk(cp_size, dim=seq_dim)) + + rank = 0 + for cp_rank in range(cp_size): + sp_chunks = list(cp_chunks[cp_rank].chunk(sp_size, dim=seq_dim)) + for sp_rank in range(sp_size): + _dump_rank( + directory, + rank=rank, + name=name, + tensor=sp_chunks[sp_rank], + dims="b s[cp:zigzag,sp] h", + parallel_info={ + "cp_rank": cp_rank, + "cp_size": cp_size, + "sp_rank": sp_rank, + "sp_size": sp_size, + }, + ) + rank += 1 + + +def _dump_rank( + directory: Path, + *, + rank: int, + name: str, + tensor: torch.Tensor, + dims: Optional[str] = None, + parallel_info: Optional[Dict[str, int]] = None, +) -> None: + with pytest.MonkeyPatch.context() as mp: + mp.setattr(_dumper_module, "_get_rank", lambda: rank) + dumper = _Dumper( + config=DumperConfig(enable=True, dir=str(directory), exp_name=_EXP_NAME) + ) + static_meta: Dict[str, object] = {"world_rank": rank, "world_size": 1} + if parallel_info is not None: + static_meta["sglang_parallel_info"] = parallel_info + dumper.__dict__["_static_meta"] = static_meta + dumper.dump(name, tensor, dims=dims) + dumper.step() + + +def _run( + baseline_path: Path, + target_path: Path, + *, + report_path: Path, + output_format: str = "text", + verbosity: str = "normal", +) -> int: + argv = [ + "--baseline-path", + str(baseline_path), + "--target-path", + str(target_path), + "--output-format", + output_format, + "--verbosity", + verbosity, + "--preset", + "sglang_dev", + "--report-path", + str(report_path), + ] + print( + f"\n $ python -m sglang.srt.debug_utils.comparator {' '.join(argv)}\n", + flush=True, + ) + return run(parse_args(argv)) + + +def _read_report(report_path: Path) -> List[AnyRecord]: + return [ + parse_record_json(line) for line in report_path.read_text().strip().splitlines() + ] + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-s", "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_entrypoint.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e37ce25a4723f609c1e39e5a8f2e922fd9492e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_entrypoint.py @@ -0,0 +1,4997 @@ +import subprocess +import sys +import textwrap +from argparse import Namespace +from pathlib import Path + +import pytest +import torch + +import sglang.srt.debug_utils.comparator.entrypoint as _entrypoint_module +import sglang.srt.debug_utils.dumper as _dumper_module +from sglang.srt.debug_utils.comparator.entrypoint import ( + parse_args, + run, +) +from sglang.srt.debug_utils.comparator.output_types import ( + AnyRecord, + ComparisonErrorRecord, + ComparisonNonTensorRecord, + ComparisonSkipRecord, + ComparisonTensorRecord, + ConfigRecord, + InfoLog, + LogRecord, + ReplicatedCheckResult, + SummaryRecord, + _OutputRecord, + parse_record_json, +) +from sglang.srt.debug_utils.dumper import DumperConfig, _Dumper, _RecomputeStatus +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=30, suite="base-a-test-cpu", nightly=True) + +_FIXED_EXP_NAME = "my_exp_name" + +# Each test has a one-line docstring describing the scenario it covers. + + +class TestEntrypointGroupingRaw: + """Test `--grouping-skip-keys` empty (raw) scenarios""" + + def test_run_basic(self, tmp_path, capsys): + """Two matching tensors produce ConfigRecord, 2 ComparisonTensorRecords, and SummaryRecord.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a", "tensor_b"]) + argv = _make_argv(baseline_path, target_path, preset="raw") + + records, _ = _run_and_parse(argv, capsys) + assert isinstance(records[0], ConfigRecord) + + assert len(_get_comparisons(records)) == 2 + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 2 + assert summary.skipped == 0 + + def test_filter(self, tmp_path, capsys): + """--filter selects only the matching tensor, producing 1 ComparisonTensorRecord.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a", "tensor_b"]) + argv = _make_argv(baseline_path, target_path, filter="tensor_a", preset="raw") + + records, _ = _run_and_parse(argv, capsys) + assert len(_get_comparisons(records)) == 1 + + def test_no_baseline_skip(self, tmp_path, capsys): + """Target tensor missing from baseline emits a ComparisonSkipRecord with reason baseline_load_failed.""" + baseline_path, target_path = _create_dumps( + tmp_path, + tensor_names=["tensor_a", "tensor_extra"], + baseline_names=["tensor_a"], + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + + records, _ = _run_and_parse(argv, capsys) + skips = [r for r in records if isinstance(r, ComparisonSkipRecord)] + assert len(skips) == 1 + assert skips[0].reason == "baseline_load_failed" + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.skipped == 1 + + def test_step_range(self, tmp_path, capsys): + """--start_step/--end_step restricts comparison to a single step out of three.""" + baseline_path, target_path = _create_dumps(tmp_path, ["t"], num_steps=3) + argv = _make_argv( + baseline_path, target_path, start_step=1, end_step=1, preset="raw" + ) + + records, _ = _run_and_parse(argv, capsys) + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 1 + + def test_all_valid_records(self, tmp_path, capsys): + """Every emitted JSON record is a valid _OutputRecord subclass.""" + baseline_path, target_path = _create_dumps(tmp_path, ["t"], num_steps=2) + argv = _make_argv(baseline_path, target_path, preset="raw") + + records, _ = _run_and_parse(argv, capsys) + assert all(isinstance(r, _OutputRecord) for r in records) + + def test_comparison_failed(self, tmp_path, capsys): + """Completely different tensors produce a failed ComparisonTensorRecord.""" + torch.manual_seed(42) + baseline_path = _create_rank_dump( + tmp_path / "baseline", rank=0, name="tensor_a", tensor=torch.randn(10, 10) + ) + target_path = _create_rank_dump( + tmp_path / "target", + rank=0, + name="tensor_a", + tensor=torch.randn(10, 10) * 100, + ) + argv = _make_argv(baseline_path, target_path, preset="raw", diff_threshold=1e-3) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].diff is not None + assert not comparisons[0].diff.passed + assert comparisons[0].category == "failed" + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.failed == 1 + + def test_shape_mismatch(self, tmp_path, capsys): + """Different shapes produce shape_mismatch=True and category='failed'.""" + torch.manual_seed(42) + baseline_path = _create_rank_dump( + tmp_path / "baseline", rank=0, name="tensor_a", tensor=torch.randn(4, 8) + ) + target_path = _create_rank_dump( + tmp_path / "target", rank=0, name="tensor_a", tensor=torch.randn(4, 10) + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].shape_mismatch is True + assert comparisons[0].diff is None + assert comparisons[0].category == "failed" + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.failed == 1 + + def test_unify_shape_leading_dims(self, tmp_path, capsys): + """Leading singleton dims on baseline are squeezed to match target shape.""" + torch.manual_seed(42) + base_tensor = torch.randn(4, 8) + baseline_tensor = base_tensor.unsqueeze(0) # (1, 4, 8) + target_tensor = base_tensor + torch.randn(4, 8) * 0.0001 # (4, 8) + + baseline_path = _create_rank_dump( + tmp_path / "baseline", rank=0, name="tensor_a", tensor=baseline_tensor + ) + target_path = _create_rank_dump( + tmp_path / "target", rank=0, name="tensor_a", tensor=target_tensor + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + + comp = comparisons[0] + assert comp.shape_mismatch is False + assert comp.baseline.shape == [1, 4, 8] + assert comp.target.shape == [4, 8] + assert comp.unified_shape == [4, 8] + assert comp.diff is not None + assert comp.diff.passed + + def test_dtype_mismatch_downcast(self, tmp_path, capsys): + """Baseline float32 vs target bfloat16 produces diff_downcast.""" + torch.manual_seed(42) + baseline_tensor = torch.randn(4, 8, dtype=torch.float32) + target_tensor = (baseline_tensor + torch.randn(4, 8) * 0.0001).to( + torch.bfloat16 + ) + + baseline_path = _create_rank_dump( + tmp_path / "baseline", rank=0, name="tensor_a", tensor=baseline_tensor + ) + target_path = _create_rank_dump( + tmp_path / "target", rank=0, name="tensor_a", tensor=target_tensor + ) + argv = _make_argv(baseline_path, target_path, preset="raw", diff_threshold=0.01) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].diff_downcast is not None + assert comparisons[0].downcast_dtype is not None + + def test_mixed_summary(self, tmp_path, capsys): + """One passed, one failed, one skipped tensor in a single run.""" + torch.manual_seed(42) + similar_tensor = torch.randn(4, 4) + different_baseline = torch.randn(4, 4) + different_target = torch.randn(4, 4) * 100 + extra_tensor = torch.randn(4, 4) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_rank_dump(baseline_dir, rank=0, name="similar", tensor=similar_tensor) + _create_rank_dump( + baseline_dir, rank=0, name="different", tensor=different_baseline + ) + + _create_rank_dump( + target_dir, + rank=0, + name="similar", + tensor=similar_tensor + torch.randn(4, 4) * 0.0001, + ) + _create_rank_dump(target_dir, rank=0, name="different", tensor=different_target) + _create_rank_dump(target_dir, rank=0, name="extra", tensor=extra_tensor) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + preset="raw", + diff_threshold=1e-3, + ) + + records, _ = _run_and_parse(argv, capsys) + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 1 + assert summary.failed == 1 + assert summary.skipped == 1 + assert summary.total == 3 + + def test_filter_empty_result(self, tmp_path, capsys): + """--filter matching nothing produces summary with total=0.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + argv = _make_argv( + baseline_path, + target_path, + filter="nonexistent_pattern", + preset="raw", + ) + + records, _ = _run_and_parse(argv, capsys) + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 0 + + def test_raw_multi_rank(self, tmp_path, capsys): + """Two ranks in raw grouping produce two ComparisonTensorRecords (one per rank).""" + torch.manual_seed(42) + tensor = torch.randn(4, 4) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for rank in range(2): + _create_rank_dump(baseline_dir, rank=rank, name="hidden", tensor=tensor) + _create_rank_dump( + target_dir, + rank=rank, + name="hidden", + tensor=tensor + torch.randn(4, 4) * 0.0001, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + preset="raw", + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 2 + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 2 + assert summary.passed == 2 + + def test_text_output_format(self, tmp_path, capsys): + """Text output format renders without errors and contains Config/Summary sections.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + argv = _make_argv( + baseline_path, target_path, output_format="text", preset="raw" + ) + capsys.readouterr() + + run(parse_args(argv)) + + output = capsys.readouterr().out + assert "Comparator Config" in output + assert "SUMMARY" in output + + def test_text_output_with_failure(self, tmp_path, capsys): + """Text output with a failed comparison renders failure info.""" + torch.manual_seed(42) + baseline_path = _create_rank_dump( + tmp_path / "baseline", rank=0, name="tensor_a", tensor=torch.randn(10, 10) + ) + target_path = _create_rank_dump( + tmp_path / "target", + rank=0, + name="tensor_a", + tensor=torch.randn(10, 10) * 100, + ) + argv = _make_argv( + baseline_path, target_path, output_format="text", preset="raw" + ) + capsys.readouterr() + + run(parse_args(argv)) + + output = capsys.readouterr().out + assert "SUMMARY" in output + assert "failed" in output.lower() + + def test_duplicate_dump_pairing(self, tmp_path, capsys): + """Same name dumped twice (different values) pairs by duplicate_index: 0th↔0th, 1st↔1st.""" + torch.manual_seed(42) + tensor_v0 = torch.randn(4, 4) + tensor_v1 = torch.randn(4, 4) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir in [baseline_dir, target_dir]: + with pytest.MonkeyPatch.context() as mp: + mp.setattr(_dumper_module, "_get_rank", lambda: 0) + dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(side_dir), + exp_name=_FIXED_EXP_NAME, + ) + ) + dumper.__dict__["_static_meta"] = {"world_rank": 0, "world_size": 1} + + dumper.dump("tensor_a", tensor_v0) + dumper.dump("tensor_a", tensor_v1) + dumper.step() + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + preset="raw", + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 2 + assert all(c.diff is not None and c.diff.passed for c in comparisons) + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 2 + assert summary.passed == 2 + + +class TestEntrypointGroupingLogical: + """Test `--grouping-skip-keys rank` (logical) scenarios""" + + def test_no_dims_single_rank(self, tmp_path, capsys): + """Single-rank dumps without dims fall back to raw loading.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a", "tensor_b"]) + argv = _make_argv(baseline_path, target_path) + + records, _ = _run_and_parse(argv, capsys) + assert len(_get_comparisons(records)) == 2 + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 2 + assert summary.skipped == 0 + + def test_tp_unshard_same_size(self, tmp_path, capsys): + """Both sides TP=2: shards are concatenated before comparison.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8) + full_target = full_baseline + torch.randn(4, 8) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + baseline_path = _create_tp_sharded_dumps( + baseline_dir, + full_tensor=full_baseline, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + target_path = _create_tp_sharded_dumps( + target_dir, + full_tensor=full_target, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + + argv = _make_argv(baseline_path, target_path, diff_threshold=0.01) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 1 + assert summary.passed == 1 + + def test_tp_unshard_different_sizes(self, tmp_path, capsys): + """Baseline TP=4 vs target TP=2: different shard counts are handled correctly.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8) + full_target = full_baseline + torch.randn(4, 8) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + baseline_path = _create_tp_sharded_dumps( + baseline_dir, + full_tensor=full_baseline, + name="hidden", + tp_size=4, + shard_dim=1, + dims_str="b h[tp]", + ) + target_path = _create_tp_sharded_dumps( + target_dir, + full_tensor=full_target, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + + argv = _make_argv(baseline_path, target_path, diff_threshold=0.01) + + records, _ = _run_and_parse(argv, capsys) + _assert_single_comparison_passed(records) + + def test_one_side_dims_single_baseline(self, tmp_path, capsys): + """Baseline has no dims (single rank), target has TP shards: unshard target only.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + target_full = full_tensor + torch.randn(4, 8) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + baseline_path = _create_rank_dump( + baseline_dir, rank=0, name="hidden", tensor=full_tensor + ) + + target_path = _create_tp_sharded_dumps( + target_dir, + full_tensor=target_full, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + + argv = _make_argv(baseline_path, target_path, diff_threshold=0.01) + + records, _ = _run_and_parse(argv, capsys) + _assert_single_comparison_passed(records) + + @pytest.mark.parametrize( + "bad_side, expected_reason", + [ + ("baseline", "baseline_load_failed"), + ("target", "target_load_failed"), + ], + ) + def test_ambiguous_no_dims_skip(self, tmp_path, capsys, bad_side, expected_reason): + """Multi-rank without dims on one side produces a ComparisonSkipRecord with the appropriate reason.""" + torch.manual_seed(42) + tensor = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + good_dir = target_dir if bad_side == "baseline" else baseline_dir + bad_dir = baseline_dir if bad_side == "baseline" else target_dir + + _create_rank_dump(good_dir, rank=0, name="hidden", tensor=tensor) + for rank, shard in [(0, tensor[:, :4]), (1, tensor[:, 4:])]: + _create_rank_dump(bad_dir, rank=rank, name="hidden", tensor=shard) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + ) + + records, _ = _run_and_parse(argv, capsys) + skips = [r for r in records if isinstance(r, ComparisonSkipRecord)] + assert len(skips) == 1 + assert skips[0].reason == expected_reason + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.skipped == 1 + + def test_summary_counts_unshard(self, tmp_path, capsys): + """Two TP-sharded tensors: summary counts total=2, passed=2, skipped=0.""" + torch.manual_seed(42) + full_a = torch.randn(4, 8) + full_b = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for tensor_name, tensor in [("t_a", full_a), ("t_b", full_b)]: + baseline_path = _create_tp_sharded_dumps( + baseline_dir, + full_tensor=tensor, + name=tensor_name, + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + target_tensor = tensor + torch.randn_like(tensor) * 0.0001 + target_path = _create_tp_sharded_dumps( + target_dir, + full_tensor=target_tensor, + name=tensor_name, + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + + argv = _make_argv(baseline_path, target_path, diff_threshold=0.01) + + records, _ = _run_and_parse(argv, capsys) + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 2 + assert summary.passed == 2 + assert summary.failed == 0 + assert summary.skipped == 0 + + def test_multi_step_tp(self, tmp_path, capsys): + """Two steps with TP=2 shards: concat mode merges into one comparison.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + baseline_path = _create_tp_sharded_dumps( + baseline_dir, + full_tensor=full_tensor, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + num_steps=2, + ) + target_path = _create_tp_sharded_dumps( + target_dir, + full_tensor=full_tensor + torch.randn(4, 8) * 0.0001, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + num_steps=2, + ) + + argv = _make_argv( + baseline_path, + target_path, + diff_threshold=0.01, + preset="sglang_megatron", + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + # concat along dim 0 (fallback, no token dim) → 2 steps × [4, 8] = [8, 8] + assert comparisons[0].baseline.shape == [8, 8] + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 1 + assert summary.passed == 1 + + def test_cp_axis_unshard(self, tmp_path, capsys): + """CP-sharded tensors are correctly concatenated along the sequence dim.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 6) + full_target = full_baseline + torch.randn(4, 8, 6) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir, full_tensor in [ + (baseline_dir, full_baseline), + (target_dir, full_target), + ]: + shards = list(full_tensor.chunk(2, dim=1)) + for cp_rank in range(2): + _create_rank_dump( + side_dir, + rank=cp_rank, + name="attn_out", + tensor=shards[cp_rank], + dims="b s[cp] h", + parallel_info={"cp_rank": cp_rank, "cp_size": 2}, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "attn_out" + + def test_filter_logical(self, tmp_path, capsys): + """--filter in logical grouping selects only matching tensor bundles.""" + torch.manual_seed(42) + full_a = torch.randn(4, 8) + full_b = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for tensor_name, tensor in [("t_a", full_a), ("t_b", full_b)]: + _create_tp_sharded_dumps( + baseline_dir, + full_tensor=tensor, + name=tensor_name, + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + _create_tp_sharded_dumps( + target_dir, + full_tensor=tensor + torch.randn_like(tensor) * 0.0001, + name=tensor_name, + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + filter="t_a", + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].name == "t_a" + + def test_mixed_dims_logical(self, tmp_path, capsys): + """TP-sharded and single-rank tensors in the same logical run both compare successfully.""" + torch.manual_seed(42) + full_tp_tensor = torch.randn(4, 8) + single_tensor = torch.randn(4, 4) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_tp_sharded_dumps( + baseline_dir, + full_tensor=full_tp_tensor, + name="tensor_a", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + _create_tp_sharded_dumps( + target_dir, + full_tensor=full_tp_tensor + torch.randn(4, 8) * 0.0001, + name="tensor_a", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + + _create_rank_dump(baseline_dir, rank=0, name="tensor_b", tensor=single_tensor) + _create_rank_dump( + target_dir, + rank=0, + name="tensor_b", + tensor=single_tensor + torch.randn(4, 4) * 0.0001, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 2 + assert all(c.diff is not None and c.diff.passed for c in comparisons) + assert {c.name for c in comparisons} == {"tensor_a", "tensor_b"} + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 2 + assert summary.passed == 2 + + def test_cp_tp_unshard(self, tmp_path, capsys): + """CP=2 + TP=2: multi-axis shards are unsharded before comparison.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 16) + full_target = full_baseline + torch.randn(4, 8, 16) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir, full_tensor in [ + (baseline_dir, full_baseline), + (target_dir, full_target), + ]: + _create_cp_tp_sharded_dumps( + side_dir, + full_tensor=full_tensor, + name="hidden", + cp_size=2, + tp_size=2, + seq_dim=1, + head_dim=2, + dims_str="b s[cp] h[tp]", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + def test_cp_tp_different_sizes(self, tmp_path, capsys): + """Baseline CP=2+TP=2 vs target CP=1+TP=4: both sides independently unsharder.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 16) + full_target = full_baseline + torch.randn(4, 8, 16) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_cp_tp_sharded_dumps( + baseline_dir, + full_tensor=full_baseline, + name="hidden", + cp_size=2, + tp_size=2, + seq_dim=1, + head_dim=2, + dims_str="b s[cp] h[tp]", + ) + + _create_tp_sharded_dumps( + target_dir, + full_tensor=full_target, + name="hidden", + tp_size=4, + shard_dim=2, + dims_str="b s h[tp]", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + _assert_single_comparison_passed(records) + + def test_ep_cp_tp_three_axis_unshard(self, tmp_path, capsys): + """EP=2 + CP=2 + TP=2: three-axis shards are unsharded before comparison.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 16, 32) + full_target = full_baseline + torch.randn(4, 8, 16, 32) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir, full_tensor in [ + (baseline_dir, full_baseline), + (target_dir, full_target), + ]: + _create_ep_cp_tp_sharded_dumps( + side_dir, + full_tensor=full_tensor, + name="hidden", + ep_size=2, + cp_size=2, + tp_size=2, + expert_dim=1, + seq_dim=2, + head_dim=3, + dims_str="b e[ep] s[cp] h[tp]", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + def test_cp_zigzag_unshard(self, tmp_path, capsys): + """CP=2 zigzag reorder is correctly undone through the full pipeline.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 6) + full_target = full_baseline + torch.randn(4, 8, 6) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir, full_tensor in [ + (baseline_dir, full_baseline), + (target_dir, full_target), + ]: + _create_cp_zigzag_tp_sharded_dumps( + side_dir, + full_tensor=full_tensor, + name="attn_out", + cp_size=2, + tp_size=1, + seq_dim=1, + head_dim=2, + dims_str="b s[cp:zigzag] h", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "attn_out" + + def test_cp_zigzag_tp_unshard(self, tmp_path, capsys): + """CP=2 zigzag + TP=2: multi-axis unshard with reorder through full pipeline.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 16) + full_target = full_baseline + torch.randn(4, 8, 16) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir, full_tensor in [ + (baseline_dir, full_baseline), + (target_dir, full_target), + ]: + _create_cp_zigzag_tp_sharded_dumps( + side_dir, + full_tensor=full_tensor, + name="hidden", + cp_size=2, + tp_size=2, + seq_dim=1, + head_dim=2, + dims_str="b s[cp:zigzag] h[tp]", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + def test_recompute_pseudo_replicated_verification(self, tmp_path, capsys): + """Recompute pseudo-axis with identical original/recompute tensors → passed.""" + torch.manual_seed(42) + tensor = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir in [baseline_dir, target_dir]: + _create_recompute_rank_dump( + side_dir, + rank=0, + name="hidden", + original_tensor=tensor, + recompute_tensor=tensor.clone(), + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + grouping_skip_keys=["rank", "recompute_status"], + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + def test_recompute_pseudo_mismatch_warning(self, tmp_path, capsys): + """Recompute pseudo-axis with differing original/recompute → failed replicated_checks.""" + torch.manual_seed(42) + tensor = torch.randn(4, 8) + mismatched_tensor = tensor + torch.randn(4, 8) * 10.0 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir in [baseline_dir, target_dir]: + _create_recompute_rank_dump( + side_dir, + rank=0, + name="hidden", + original_tensor=tensor, + recompute_tensor=mismatched_tensor, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + grouping_skip_keys=["rank", "recompute_status"], + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + + recompute_checks: list[ReplicatedCheckResult] = [ + c for c in comparisons[0].replicated_checks if c.axis == "recompute_pseudo" + ] + assert len(recompute_checks) > 0 + assert any(not c.passed for c in recompute_checks) + + def test_tp_partial_reduction_unshard(self, tmp_path, capsys): + """TP=2 with partial reduction: element-wise sum reconstructs full tensor.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8) + full_target = full_baseline + torch.randn(4, 8) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + baseline_path = _create_tp_partial_dumps( + baseline_dir, + full_tensor=full_baseline, + name="attn_out", + tp_size=2, + dims_str="b h[tp:partial]", + ) + target_path = _create_tp_partial_dumps( + target_dir, + full_tensor=full_target, + name="attn_out", + tp_size=2, + dims_str="b h[tp:partial]", + ) + + argv = _make_argv(baseline_path, target_path, diff_threshold=0.01) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "attn_out" + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 1 + assert summary.passed == 1 + + def test_tp_partial_vs_single_rank(self, tmp_path, capsys): + """Baseline single rank vs target TP=2 partial: unshard target then compare.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + target_full = full_tensor + torch.randn(4, 8) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + baseline_path = _create_rank_dump( + baseline_dir, rank=0, name="attn_out", tensor=full_tensor + ) + target_path = _create_tp_partial_dumps( + target_dir, + full_tensor=target_full, + name="attn_out", + tp_size=2, + dims_str="b h[tp:partial]", + ) + + argv = _make_argv(baseline_path, target_path, diff_threshold=0.01) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "attn_out" + + def test_cp_concat_tp_partial_reduction(self, tmp_path, capsys): + """CP=2 concat + TP=2 partial reduction: multi-axis unshard.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 16) + full_target = full_baseline + torch.randn(4, 8, 16) * 0.001 + + for side_dir, full_tensor in [ + (tmp_path / "baseline", full_baseline), + (tmp_path / "target", full_target), + ]: + side_dir.mkdir() + cp_chunks = list(full_tensor.chunk(2, dim=1)) + rank = 0 + for cp_rank in range(2): + for tp_rank in range(2): + _create_rank_dump( + side_dir, + rank=rank, + name="hidden", + tensor=cp_chunks[cp_rank] / 2, + dims="b s[cp] h[tp:partial]", + parallel_info={ + "cp_rank": cp_rank, + "cp_size": 2, + "tp_rank": tp_rank, + "tp_size": 2, + }, + ) + rank += 1 + + argv = _make_argv( + tmp_path / "baseline" / _FIXED_EXP_NAME, + tmp_path / "target" / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + def test_cp_zigzag_sp_same_dim_unshard(self, tmp_path, capsys): + """CP=2 zigzag + SP=2 on same seq dim: multi-axis unshard + reorder.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 6) + full_target = full_baseline + torch.randn(4, 8, 6) * 0.001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir, full_tensor in [ + (baseline_dir, full_baseline), + (target_dir, full_target), + ]: + _create_cp_zigzag_sp_sharded_dumps( + side_dir, + full_tensor=full_tensor, + name="hidden", + cp_size=2, + sp_size=2, + dims_str="b s[cp:zigzag,sp] h", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + +class TestEntrypointPerStepMode: + """Test per-step comparison mode (sglang_dev preset behavior).""" + + def test_multi_step_per_step_comparison(self, tmp_path, capsys): + """Multiple steps produce one ComparisonTensorRecord per step with step field set.""" + torch.manual_seed(42) + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"], num_steps=3) + argv = _make_argv(baseline_path, target_path, diff_threshold=0.1) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 3 + + steps: list[int] = sorted(c.location.step for c in comparisons) + assert steps == [0, 1, 2] + assert all(c.diff is not None and c.diff.passed for c in comparisons) + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 3 + assert summary.passed == 3 + + def test_per_step_with_tp_unshard(self, tmp_path, capsys): + """Per-step mode with TP=2: each step independently unsharded and compared.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + baseline_path = _create_tp_sharded_dumps( + baseline_dir, + full_tensor=full_tensor, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + num_steps=2, + ) + target_path = _create_tp_sharded_dumps( + target_dir, + full_tensor=full_tensor + torch.randn(4, 8) * 0.0001, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + num_steps=2, + ) + + argv = _make_argv(baseline_path, target_path, diff_threshold=0.01) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 2 + + steps: list[int] = sorted(c.location.step for c in comparisons) + assert steps == [0, 1] + assert all(c.diff is not None and c.diff.passed for c in comparisons) + assert all(c.baseline.shape == [4, 8] for c in comparisons) + + def test_single_step_has_step_field(self, tmp_path, capsys): + """Single step produces ComparisonTensorRecord with location.step=0.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"], num_steps=1) + argv = _make_argv(baseline_path, target_path) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].location.step == 0 + + +class TestEntrypointConcatMode: + """Test concat token-aligner mode through the full entrypoint pipeline.""" + + @staticmethod + def _make_dirs(tmp_path: Path) -> tuple[Path, Path]: + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + return baseline_dir, target_dir + + @staticmethod + def _create_both_sides( + tmp_path: Path, + *, + baseline_steps: list[torch.Tensor], + target_steps: list[torch.Tensor], + name: str = "hidden", + dims: str | None = None, + ) -> tuple[Path, Path]: + """Create multi-step rank-0 dumps for both sides and return exp paths.""" + baseline_dir, target_dir = TestEntrypointConcatMode._make_dirs(tmp_path) + + for side_dir, steps in [ + (baseline_dir, baseline_steps), + (target_dir, target_steps), + ]: + _create_multi_step_rank_dump( + side_dir, + rank=0, + name=name, + tensors_per_step=steps, + dims=dims, + ) + + return baseline_dir / _FIXED_EXP_NAME, target_dir / _FIXED_EXP_NAME + + @staticmethod + def _run_concat( + tmp_path: Path, + capsys: pytest.CaptureFixture, + *, + baseline_steps: list[torch.Tensor], + target_steps: list[torch.Tensor], + name: str = "hidden", + dims: str | None = None, + diff_threshold: float = 0.01, + ) -> list[AnyRecord]: + """Create both-side dumps, run comparator, return parsed records.""" + baseline_path, target_path = TestEntrypointConcatMode._create_both_sides( + tmp_path, + baseline_steps=baseline_steps, + target_steps=target_steps, + name=name, + dims=dims, + ) + argv: list[str] = _make_argv( + baseline_path, + target_path, + diff_threshold=diff_threshold, + preset="sglang_megatron", + ) + records, _ = _run_and_parse(argv, capsys) + return records + + def test_concat_multi_step_different_data(self, tmp_path, capsys): + """Multi-step concat with different data per step + truncation.""" + torch.manual_seed(42) + + # baseline: 2 steps [5,4] + [3,4] → concat → [8,4] + baseline_step0 = torch.randn(5, 4) + baseline_step1 = torch.randn(3, 4) + baseline_concat = torch.cat([baseline_step0, baseline_step1], dim=0) + + # target: 1 step [6,4] — will be truncated to min(8,6)=6 + target_step0 = baseline_concat[:6] + torch.randn(6, 4) * 0.0001 + + records = self._run_concat( + tmp_path, + capsys, + baseline_steps=[baseline_step0, baseline_step1], + target_steps=[target_step0], + ) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + # truncated to min(8,6) = 6 along concat dim + assert comparisons[0].baseline.shape == [6, 4] + assert comparisons[0].target.shape == [6, 4] + + def test_concat_multi_step_tp_unshard(self, tmp_path, capsys): + """Multi-step different data + TP=2 unshard + concat.""" + torch.manual_seed(42) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + # 2 steps: [4,8] each → concat → [8,8] + full_step0 = torch.randn(4, 8) + full_step1 = torch.randn(4, 8) + + _create_multi_step_tp_sharded_dumps( + baseline_dir, + full_tensors_per_step=[full_step0, full_step1], + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + _create_multi_step_tp_sharded_dumps( + target_dir, + full_tensors_per_step=[ + full_step0 + torch.randn(4, 8) * 0.0001, + full_step1 + torch.randn(4, 8) * 0.0001, + ], + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp]", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + preset="sglang_megatron", + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + # 2 steps × [4, 8] concat along dim 0 (fallback) → [8, 8] + assert comparisons[0].baseline.shape == [8, 8] + assert comparisons[0].diff is not None + assert comparisons[0].diff.passed + + def test_concat_unequal_step_counts(self, tmp_path, capsys): + """Baseline 3 steps vs target 2 steps with truncation.""" + torch.manual_seed(42) + + # baseline: 3 steps [3]+[4]+[2] = 9 tokens along dim 0 + b_step0 = torch.randn(3, 4) + b_step1 = torch.randn(4, 4) + b_step2 = torch.randn(2, 4) + b_concat = torch.cat([b_step0, b_step1, b_step2], dim=0) + + # target: 2 steps [5]+[3] = 8 tokens along dim 0 + t_step0 = b_concat[:5] + torch.randn(5, 4) * 0.0001 + t_step1 = b_concat[5:8] + torch.randn(3, 4) * 0.0001 + + records = self._run_concat( + tmp_path, + capsys, + baseline_steps=[b_step0, b_step1, b_step2], + target_steps=[t_step0, t_step1], + ) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + # truncated to min(9,8) = 8 + assert comparisons[0].baseline.shape == [8, 4] + assert comparisons[0].target.shape == [8, 4] + assert comparisons[0].diff is not None + assert comparisons[0].diff.passed + + def test_concat_token_dim_nonzero(self, tmp_path, capsys): + """Token dim at dim=1 (dims='b t h') — concat along dim 1.""" + torch.manual_seed(42) + + # 2 steps: [2,5,4] + [2,3,4] → concat along dim 1 → [2,8,4] + b_step0 = torch.randn(2, 5, 4) + b_step1 = torch.randn(2, 3, 4) + b_concat = torch.cat([b_step0, b_step1], dim=1) + + t_step0 = b_concat[:, :5, :] + torch.randn(2, 5, 4) * 0.0001 + t_step1 = b_concat[:, 5:, :] + torch.randn(2, 3, 4) * 0.0001 + + records = self._run_concat( + tmp_path, + capsys, + baseline_steps=[b_step0, b_step1], + target_steps=[t_step0, t_step1], + dims="b t h", + ) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].baseline.shape == [2, 8, 4] + assert comparisons[0].diff is not None + assert comparisons[0].diff.passed + + def test_concat_seq_dim_fallback(self, tmp_path, capsys): + """No 't' dim but 's' dim present (dims='b s h') → concat along s.""" + torch.manual_seed(42) + + # 2 steps: [2,5,4] + [2,3,4] → concat along dim 1 (s) → [2,8,4] + b_step0 = torch.randn(2, 5, 4) + b_step1 = torch.randn(2, 3, 4) + b_concat = torch.cat([b_step0, b_step1], dim=1) + + t_step0 = b_concat[:, :5, :] + torch.randn(2, 5, 4) * 0.0001 + t_step1 = b_concat[:, 5:, :] + torch.randn(2, 3, 4) * 0.0001 + + records = self._run_concat( + tmp_path, + capsys, + baseline_steps=[b_step0, b_step1], + target_steps=[t_step0, t_step1], + dims="b s h", + ) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].baseline.shape == [2, 8, 4] + assert comparisons[0].diff is not None + assert comparisons[0].diff.passed + + def test_concat_no_dims_fallback(self, tmp_path, capsys): + """No dims annotation → fallback to concat along dim 0.""" + torch.manual_seed(42) + + # 2 steps: [5,4] + [3,4] → concat along dim 0 → [8,4] + b_step0 = torch.randn(5, 4) + b_step1 = torch.randn(3, 4) + b_concat = torch.cat([b_step0, b_step1], dim=0) + + t_step0 = b_concat[:5] + torch.randn(5, 4) * 0.0001 + t_step1 = b_concat[5:] + torch.randn(3, 4) * 0.0001 + + records = self._run_concat( + tmp_path, + capsys, + baseline_steps=[b_step0, b_step1], + target_steps=[t_step0, t_step1], + ) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].baseline.shape == [8, 4] + assert comparisons[0].diff is not None + assert comparisons[0].diff.passed + + def test_concat_preserves_step_order(self, tmp_path, capsys): + """Verify step0 data precedes step1 data in the concatenated result.""" + # deterministic integer data: step0=[1,2,3], step1=[4,5] + b_step0 = torch.tensor([[1.0], [2.0], [3.0]]) + b_step1 = torch.tensor([[4.0], [5.0]]) + + # target: same data, single step [1,2,3,4,5] + t_full = torch.tensor([[1.0], [2.0], [3.0], [4.0], [5.0]]) + + records = self._run_concat( + tmp_path, + capsys, + baseline_steps=[b_step0, b_step1], + target_steps=[t_full], + ) + comp = _assert_single_comparison_passed(records) + # if order were wrong, diff would not pass with exact integer data + assert comp.baseline.shape == [5, 1] + assert comp.diff is not None + assert comp.diff.max_abs_diff == 0.0 + + def test_concat_aux_tensors_not_filtered(self, tmp_path, capsys): + """Concat mode does not filter aux tensors — all participate in comparison.""" + torch.manual_seed(42) + + baseline_dir, target_dir = self._make_dirs(tmp_path) + + hidden = torch.randn(4, 8) + input_ids = torch.randint(0, 100, (4,)) + positions = torch.arange(4) + + _create_rank_dump( + baseline_dir, + rank=0, + name="hidden_states", + tensor=hidden, + extra_dumps=[("input_ids", input_ids), ("positions", positions)], + ) + _create_rank_dump( + target_dir, + rank=0, + name="hidden_states", + tensor=hidden + torch.randn(4, 8) * 0.0001, + extra_dumps=[("input_ids", input_ids), ("positions", positions)], + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + # all 3 tensors should be compared (not filtered out) + names = {c.name for c in comparisons} + assert "hidden_states" in names + assert "input_ids" in names + assert "positions" in names + assert len(comparisons) == 3 + + def test_concat_aligner_plan_fields(self, tmp_path, capsys): + """ComparisonTensorRecord.traced_plan reports mode='concat' with plan=None.""" + torch.manual_seed(42) + + records = self._run_concat( + tmp_path, + capsys, + baseline_steps=[torch.randn(3, 4), torch.randn(2, 4)], + target_steps=[torch.randn(3, 4), torch.randn(2, 4)], + diff_threshold=100.0, + ) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + traced_plan = comparisons[0].traced_plan + assert traced_plan is not None + plan = traced_plan.plan + assert plan.token_aligner_mode == "concat_steps" + assert plan.token_aligner_plan is None + + def test_concat_comparison_fails(self, tmp_path, capsys): + """Completely different data → comparison fails.""" + torch.manual_seed(42) + b_step0 = torch.randn(4, 4) + b_step1 = torch.randn(3, 4) + + # target: completely different random data + torch.manual_seed(99) + t_step0 = torch.randn(4, 4) * 100 + t_step1 = torch.randn(3, 4) * 100 + + records = self._run_concat( + tmp_path, + capsys, + baseline_steps=[b_step0, b_step1], + target_steps=[t_step0, t_step1], + diff_threshold=1e-6, + ) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].diff is not None + assert not comparisons[0].diff.passed + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.failed == 1 + assert summary.passed == 0 + + def test_concat_multi_step_cp_unshard(self, tmp_path, capsys): + """Multi-step different data + CP=2 unshard along seq dim + concat.""" + torch.manual_seed(42) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + # 2 steps: [4,8,6] each → concat along seq dim (dim 1) → [4,16,6] + full_step0 = torch.randn(4, 8, 6) + full_step1 = torch.randn(4, 8, 6) + + for side_dir, steps in [ + (baseline_dir, [full_step0, full_step1]), + ( + target_dir, + [ + full_step0 + torch.randn(4, 8, 6) * 0.0001, + full_step1 + torch.randn(4, 8, 6) * 0.0001, + ], + ), + ]: + for cp_rank in range(2): + per_step_shards: list[torch.Tensor] = [ + t.chunk(2, dim=1)[cp_rank] for t in steps + ] + _create_multi_step_rank_dump( + side_dir, + rank=cp_rank, + name="attn_out", + tensors_per_step=per_step_shards, + dims="b s[cp] h", + parallel_info={"cp_rank": cp_rank, "cp_size": 2}, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + preset="sglang_megatron", + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + # CP unshard: [4,4,6] × 2 ranks → [4,8,6] per step + # concat along seq dim (dim 1): 2 steps × [4,8,6] → [4,16,6] + assert comparisons[0].baseline.shape == [4, 16, 6] + assert comparisons[0].diff is not None + assert comparisons[0].diff.passed + + def test_concat_thd_cp_zigzag(self, tmp_path: Path, capsys) -> None: + """Concat mode with THD CP=2 zigzag (Megatron format) — unshard + reorder works.""" + torch.manual_seed(42) + cp_size: int = 2 + seq_lens: list[int] = [100, 64] + total_tokens: int = sum(seq_lens) + total_per_rank: int = 128 + num_steps: int = 2 + + full_tensor: torch.Tensor = torch.randn(total_tokens + 92) + + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + baseline_path: Path = _create_thd_cp_zigzag_dumps( + baseline_dir, + full_tensor=full_tensor, + name="hidden_states", + seq_lens=seq_lens, + cp_size=cp_size, + total_per_rank=total_per_rank, + num_steps=num_steps, + ) + + target_tensor: torch.Tensor = full_tensor + torch.randn_like(full_tensor) * 1e-5 + target_path: Path = _create_thd_cp_zigzag_dumps( + target_dir, + full_tensor=target_tensor, + name="hidden_states", + seq_lens=seq_lens, + cp_size=cp_size, + total_per_rank=total_per_rank, + num_steps=num_steps, + ) + + argv: list[str] = _make_argv( + baseline_path, + target_path, + preset="sglang_megatron", + diff_threshold=1e-3, + ) + records, _ = _run_and_parse(argv, capsys) + + comparisons: list[ComparisonTensorRecord] = _get_comparisons(records) + hidden_comparisons: list[ComparisonTensorRecord] = [ + c for c in comparisons if c.name == "hidden_states" + ] + assert len(hidden_comparisons) >= 1 + assert all(c.diff is not None and c.diff.passed for c in hidden_comparisons) + + +class TestEntrypointAxisAligner: + """Test cross-framework dim reordering through the full entrypoint pipeline.""" + + def test_axis_swap_different_dim_order(self, tmp_path, capsys): + """Baseline dims 'b h d' vs target dims 'b d h': axis swapper rearranges baseline to match.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_rank_dump( + baseline_dir, + rank=0, + name="hidden", + tensor=full_tensor, + dims="b h d", + ) + _create_rank_dump( + target_dir, + rank=0, + name="hidden", + tensor=full_tensor.permute(0, 2, 1).contiguous(), + dims="b d h", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + assert comp.baseline.shape == [4, 16, 8] + assert comp.target.shape == [4, 16, 8] + + def test_axis_swap_with_tp_unshard(self, tmp_path, capsys): + """Baseline TP=2 with dims 'b h[tp] d' vs target TP=2 with dims 'b d h[tp]': unshard + axis swap.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8, 16) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_tp_sharded_dumps( + baseline_dir, + full_tensor=full_tensor, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="b h[tp] d", + ) + _create_tp_sharded_dumps( + target_dir, + full_tensor=full_tensor.permute(0, 2, 1).contiguous(), + name="hidden", + tp_size=2, + shard_dim=2, + dims_str="b d h[tp]", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + def test_squeeze_dim_one_side(self, tmp_path, capsys): + """SGLang dims 't h' vs Megatron dims 't 1 h': axis aligner squeezes the singleton dim.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_rank_dump( + baseline_dir, + rank=0, + name="hidden", + tensor=full_tensor, + dims="t h", + ) + _create_rank_dump( + target_dir, + rank=0, + name="hidden", + tensor=full_tensor.unsqueeze(1), + dims="t 1 h", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + assert comp.baseline.shape == [4, 8] + assert comp.target.shape == [4, 8] + + +class TestEntrypointSeqTokenEquivalence: + """Test s≡t dim name equivalence through the full entrypoint pipeline.""" + + def test_s_t_squeeze_single_rank(self, tmp_path, capsys): + """Baseline dims='t h' (2D [4,8]), target dims='s 1 h' (3D [4,1,8]) → comparator passes.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_rank_dump( + baseline_dir, + rank=0, + name="hidden", + tensor=full_tensor, + dims="t h", + ) + _create_rank_dump( + target_dir, + rank=0, + name="hidden", + tensor=full_tensor.unsqueeze(1), + dims="s 1 h", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + assert comp.baseline.shape == [4, 8] + assert comp.target.shape == [4, 8] + + def test_s_t_squeeze_with_tp_unshard(self, tmp_path, capsys): + """Baseline TP=2 dims='t h[tp]', target TP=2 dims='s 1 h[tp]' → unshard + squeeze + s≡t.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_tp_sharded_dumps( + baseline_dir, + full_tensor=full_tensor, + name="hidden", + tp_size=2, + shard_dim=1, + dims_str="t h[tp]", + ) + _create_tp_sharded_dumps( + target_dir, + full_tensor=full_tensor.unsqueeze(1), + name="hidden", + tp_size=2, + shard_dim=2, + dims_str="s 1 h[tp]", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + def test_s_t_fused_with_squeeze(self, tmp_path, capsys): + """Baseline dims='t (num_heads*head_dim)[tp]' (2D), target dims='s 1 num_heads[tp] head_dim' (4D).""" + torch.manual_seed(42) + num_heads = 8 + head_dim = 16 + full_tensor_2d = torch.randn(4, num_heads * head_dim) + full_tensor_4d = full_tensor_2d.reshape(4, num_heads, head_dim).unsqueeze(1) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_tp_sharded_dumps( + baseline_dir, + full_tensor=full_tensor_2d, + name="attn_pre_o_proj", + tp_size=2, + shard_dim=1, + dims_str="t (num_heads*head_dim)[tp]", + ) + _create_tp_sharded_dumps( + target_dir, + full_tensor=full_tensor_4d, + name="attn_pre_o_proj", + tp_size=2, + shard_dim=2, + dims_str="s 1 num_heads[tp] head_dim", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.name == "attn_pre_o_proj" + + def test_s_t_mismatch_with_named_batch_fails(self, tmp_path, capsys): + """Baseline dims='t h', target dims='s b h' (named b, not constant 1) → dim mismatch → skip/error.""" + torch.manual_seed(42) + full_tensor = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_rank_dump( + baseline_dir, + rank=0, + name="hidden", + tensor=full_tensor, + dims="t h", + ) + _create_rank_dump( + target_dir, + rank=0, + name="hidden", + tensor=full_tensor.unsqueeze(1).expand(4, 1, 8).contiguous(), + dims="s b h", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = [r for r in records if isinstance(r, ComparisonTensorRecord)] + assert len(comparisons) == 1 + comp = comparisons[0] + assert ( + comp.shape_mismatch + or (comp.diff is not None and not comp.diff.passed) + or len(comp.errors) > 0 + ) + + +class TestEntrypointReplicatedAxis: + """Test replicated-axis scenarios through the full entrypoint pipeline.""" + + def test_replicated_axis_identical_replicas_passed(self, tmp_path, capsys): + """CP2 TP2, TP replicated and identical → passed, replicated_checks all passed.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 6) + full_target = full_baseline + torch.randn(4, 8, 6) * 0.0001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir, full_tensor in [ + (baseline_dir, full_baseline), + (target_dir, full_target), + ]: + _create_replicated_tp_sharded_cp_dumps( + side_dir, + full_tensor=full_tensor, + name="attn_out", + cp_size=2, + tp_size=2, + seq_dim=1, + dims_str="b s[cp] d # tp:replicated", + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comp = _assert_single_comparison_passed(records) + assert comp.errors == [] + assert comp.infos == [] + assert all(c.passed for c in comp.replicated_checks) + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 1 + + def test_replicated_mismatch_fails(self, tmp_path, capsys): + """CP2 TP2, TP replicas differ (> atol) → failed with replicated_checks.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 6) + full_target = full_baseline + torch.randn(4, 8, 6) * 0.0001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir, full_tensor in [ + (baseline_dir, full_baseline), + (target_dir, full_target), + ]: + _create_replicated_tp_sharded_cp_dumps( + side_dir, + full_tensor=full_tensor, + name="attn_out", + cp_size=2, + tp_size=2, + seq_dim=1, + dims_str="b s[cp] d # tp:replicated", + tp_noise=0.5, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].category == "failed" + assert any(not c.passed for c in comparisons[0].replicated_checks) + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.failed == 1 + + def test_summary_counts_failed_from_replicated_checks_only(self, tmp_path, capsys): + """Diff itself passes but TP replicas differ → summary.failed=1 from replicated_checks.""" + torch.manual_seed(42) + full_baseline = torch.randn(4, 8, 6) + full_target = full_baseline + torch.randn(4, 8, 6) * 0.0001 + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_replicated_tp_sharded_cp_dumps( + baseline_dir, + full_tensor=full_baseline, + name="attn_out", + cp_size=2, + tp_size=2, + seq_dim=1, + dims_str="b s[cp] d # tp:replicated", + tp_noise=0.5, + ) + _create_replicated_tp_sharded_cp_dumps( + target_dir, + full_tensor=full_target, + name="attn_out", + cp_size=2, + tp_size=2, + seq_dim=1, + dims_str="b s[cp] d # tp:replicated", + tp_noise=0.5, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.5, + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + + comp = comparisons[0] + assert comp.diff is not None + assert comp.diff.passed + assert any(not c.passed for c in comp.replicated_checks) + assert comp.category == "failed" + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.failed == 1 + assert summary.passed == 0 + + def test_replicated_shape_mismatch(self, tmp_path, capsys): + """TP replicated tensors with different shapes → failed, replicated diff=None.""" + torch.manual_seed(42) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir in [baseline_dir, target_dir]: + # rank 0 (cp=0, tp=0): shape (4, 4, 6) + _create_rank_dump( + side_dir, + rank=0, + name="attn_out", + tensor=torch.randn(4, 4, 6), + dims="b s[cp] d # tp:replicated", + parallel_info={ + "cp_rank": 0, + "cp_size": 2, + "tp_rank": 0, + "tp_size": 2, + }, + ) + # rank 1 (cp=0, tp=1): shape (4, 4, 3) — different last dim + _create_rank_dump( + side_dir, + rank=1, + name="attn_out", + tensor=torch.randn(4, 4, 3), + dims="b s[cp] d # tp:replicated", + parallel_info={ + "cp_rank": 0, + "cp_size": 2, + "tp_rank": 1, + "tp_size": 2, + }, + ) + # rank 2 (cp=1, tp=0): shape (4, 4, 6) + _create_rank_dump( + side_dir, + rank=2, + name="attn_out", + tensor=torch.randn(4, 4, 6), + dims="b s[cp] d # tp:replicated", + parallel_info={ + "cp_rank": 1, + "cp_size": 2, + "tp_rank": 0, + "tp_size": 2, + }, + ) + # rank 3 (cp=1, tp=1): shape (4, 4, 3) — different last dim + _create_rank_dump( + side_dir, + rank=3, + name="attn_out", + tensor=torch.randn(4, 4, 3), + dims="b s[cp] d # tp:replicated", + parallel_info={ + "cp_rank": 1, + "cp_size": 2, + "tp_rank": 1, + "tp_size": 2, + }, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, _ = _run_and_parse(argv, capsys) + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].category == "failed" + + failed_checks = [c for c in comparisons[0].replicated_checks if not c.passed] + assert len(failed_checks) >= 1 + assert all(c.diff is None for c in failed_checks) + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.failed == 1 + + def test_dependent_replicated_axes_error(self, tmp_path, capsys): + """TP4 + MOE_TP2 both replicated, tp determines moe_tp → ComparisonErrorRecord.""" + torch.manual_seed(42) + tensor = torch.randn(4, 8) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + # TP4 with MOE_TP2: tp_rank determines moe_tp_rank (rank%2) + for side_dir in [baseline_dir, target_dir]: + for tp_rank in range(4): + _create_rank_dump( + side_dir, + rank=tp_rank, + name="gate_out", + tensor=tensor, + dims="b h # tp:replicated moe_tp:replicated", + parallel_info={ + "tp_rank": tp_rank, + "tp_size": 4, + "moe_tp_rank": tp_rank % 2, + "moe_tp_size": 2, + }, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, exit_code = _run_and_parse(argv, capsys) + + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) == 1 + assert "not orthogonal" in errors[0].exception_message + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.errored == 1 + assert exit_code == 1 + + def test_sharded_tp_with_dependent_etp_passes(self, tmp_path, capsys): + """TP2 sharded + ETP2 dependent (etp=tp) + EP2 replicated → no undeclared error.""" + torch.manual_seed(42) + full_tensor = torch.randn(2, 4, 8) + tp_shards = list(full_tensor.chunk(2, dim=1)) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir in [baseline_dir, target_dir]: + rank = 0 + for tp_rank in range(2): + for ep_rank in range(2): + _create_rank_dump( + side_dir, + rank=rank, + name="attn_v", + tensor=tp_shards[tp_rank], + dims="b num_kv_heads[tp] d # ep:replicated", + parallel_info={ + "tp_rank": tp_rank, + "tp_size": 2, + "etp_rank": tp_rank, + "etp_size": 2, + "ep_rank": ep_rank, + "ep_size": 2, + }, + ) + rank += 1 + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, exit_code = _run_and_parse(argv, capsys) + + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) == 0, f"Unexpected errors: {errors}" + + comp = _assert_single_comparison_passed(records) + assert comp.errors == [] + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 1 + assert summary.errored == 0 + assert exit_code == 0 + + +class TestEntrypointAlignment: + """Test smart token alignment with aux tensors.""" + + def test_sglang_multi_step_alignment(self, tmp_path, capsys): + """SGLang multi-step dumps with aux tensors auto-trigger alignment.""" + torch.manual_seed(42) + hidden_dim = 8 + + hidden_step0 = torch.randn(5, hidden_dim) + hidden_step1 = torch.randn(2, hidden_dim) + + exp_paths: list[Path] = [] + for side_dir in ["baseline", "target"]: + d = tmp_path / side_dir + d.mkdir() + + dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(d), + exp_name=_FIXED_EXP_NAME, + ) + ) + + # Step 0: prefill with 2 sequences (3+2 tokens) + dumper.dump("input_ids", torch.tensor([10, 20, 30, 40, 50])) + dumper.dump("positions", torch.tensor([0, 1, 2, 0, 1])) + dumper.dump("seq_lens", torch.tensor([3, 2])) + dumper.dump("req_pool_indices", torch.tensor([7, 3])) + dumper.dump("rids", ["A", "B"]) + dumper.dump("hidden_states", hidden_step0) + dumper.step() + + # Step 1: decode (1 token per sequence) + dumper.dump("input_ids", torch.tensor([31, 51])) + dumper.dump("positions", torch.tensor([3, 2])) + dumper.dump("seq_lens", torch.tensor([1, 1])) + dumper.dump("req_pool_indices", torch.tensor([7, 3])) + dumper.dump("rids", ["A", "B"]) + dumper.dump("hidden_states", hidden_step1) + dumper.step() + + exp_paths.append(d / _FIXED_EXP_NAME) + + argv = _make_argv( + exp_paths[0], + exp_paths[1], + grouping_skip_keys=["rank", "step"], + token_aligner="smart", + ) + records, _ = _run_and_parse(argv, capsys) + + comparisons = _get_comparisons(records) + # AUX_NAMES are filtered out after plan computation → only hidden_states remains + assert len(comparisons) == 1 + assert comparisons[0].name == "hidden_states" + assert comparisons[0].diff is not None + assert comparisons[0].diff.passed + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 1 + assert summary.failed == 0 + assert summary.skipped == 0 + + def test_sglang_vs_megatron_cross_framework(self, tmp_path, capsys): + """SGLang 4-step thd baseline vs Megatron 1-step thd target align correctly.""" + torch.manual_seed(42) + hidden_dim: int = 8 + + all_hiddens: torch.Tensor = torch.randn(11, hidden_dim) + seq_a_hiddens: torch.Tensor = all_hiddens[:6] + seq_b_hiddens: torch.Tensor = all_hiddens[6:] + + # --- SGLang baseline: 1 prefill + 3 decode --- + sglang_dir: Path = tmp_path / "baseline" + sglang_dir.mkdir() + sglang_dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(sglang_dir), + exp_name=_FIXED_EXP_NAME, + ) + ) + + # Step 0: prefill — seq A (3 tokens) + seq B (2 tokens) + sglang_dumper.dump("input_ids", torch.tensor([10, 20, 30, 40, 50])) + sglang_dumper.dump("positions", torch.tensor([0, 1, 2, 0, 1])) + sglang_dumper.dump("seq_lens", torch.tensor([3, 2])) + sglang_dumper.dump("req_pool_indices", torch.tensor([7, 3])) + sglang_dumper.dump("rids", ["A", "B"]) + sglang_dumper.dump( + "hidden_states", + torch.stack( + [ + seq_a_hiddens[0], + seq_a_hiddens[1], + seq_a_hiddens[2], + seq_b_hiddens[0], + seq_b_hiddens[1], + ] + ), + ) + sglang_dumper.step() + + # Steps 1-3: decode — 1 token per sequence + decode_data: list[dict[str, object]] = [ + { + "input_ids": torch.tensor([31, 51]), + "positions": torch.tensor([3, 2]), + "hidden": torch.stack([seq_a_hiddens[3], seq_b_hiddens[2]]), + }, + { + "input_ids": torch.tensor([32, 52]), + "positions": torch.tensor([4, 3]), + "hidden": torch.stack([seq_a_hiddens[4], seq_b_hiddens[3]]), + }, + { + "input_ids": torch.tensor([33, 53]), + "positions": torch.tensor([5, 4]), + "hidden": torch.stack([seq_a_hiddens[5], seq_b_hiddens[4]]), + }, + ] + for step_data in decode_data: + sglang_dumper.dump("input_ids", step_data["input_ids"]) + sglang_dumper.dump("positions", step_data["positions"]) + sglang_dumper.dump("seq_lens", torch.tensor([1, 1])) + sglang_dumper.dump("req_pool_indices", torch.tensor([7, 3])) + sglang_dumper.dump("rids", ["A", "B"]) + sglang_dumper.dump("hidden_states", step_data["hidden"]) + sglang_dumper.step() + + # --- Megatron target: 1 step, thd [T, H] --- + megatron_dir: Path = tmp_path / "target" + megatron_dir.mkdir() + megatron_dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(megatron_dir), + exp_name=_FIXED_EXP_NAME, + ) + ) + + # THD flat: seq A (6 tokens) + seq B (5 tokens) = 11 tokens total + megatron_input_ids: torch.Tensor = torch.tensor( + [10, 20, 30, 31, 32, 33, 40, 50, 51, 52, 53] + ) + megatron_cu_seqlens: torch.Tensor = torch.tensor([0, 6, 11]) + + megatron_hidden: torch.Tensor = torch.cat([seq_a_hiddens, seq_b_hiddens], dim=0) + + megatron_dumper.dump("input_ids", megatron_input_ids) + megatron_dumper.dump("cu_seqlens_q", megatron_cu_seqlens) + megatron_dumper.dump("hidden_states", megatron_hidden) + megatron_dumper.step() + + # --- Run comparison --- + argv = _make_argv( + sglang_dir / _FIXED_EXP_NAME, + megatron_dir / _FIXED_EXP_NAME, + grouping_skip_keys=["rank", "step"], + token_aligner="smart", + ) + + records, _ = _run_and_parse(argv, capsys) + + log_records = [r for r in records if isinstance(r, LogRecord)] + layout_infos = [ + i + for lr in log_records + for i in lr.infos + if isinstance(i, InfoLog) and i.category == "layout_detection_fallback" + ] + assert len(layout_infos) == 1 + + comparisons = _get_comparisons(records) + # AUX_NAMES filtered out → only hidden_states remains + assert len(comparisons) == 1 + assert comparisons[0].name == "hidden_states" + assert comparisons[0].diff is not None + assert comparisons[0].diff.passed + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 1 + assert summary.failed == 0 + assert summary.skipped == 0 + + def test_alignment_fallback_when_no_aux(self, tmp_path, capsys): + """Without aux tensors, smart alignment falls back to per-step comparison.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"], num_steps=2) + argv = _make_argv( + baseline_path, + target_path, + token_aligner="smart", + diff_threshold=0.1, + ) + + capsys.readouterr() + run(parse_args(argv)) + captured = capsys.readouterr() + records = _parse_jsonl(captured.out) + log_records = [r for r in records if isinstance(r, LogRecord)] + aux_missing_infos = [ + i + for lr in log_records + for i in lr.infos + if isinstance(i, InfoLog) and i.category == "aux_tensors_missing" + ] + assert len(aux_missing_infos) == 1 + + comparisons = _get_comparisons(records) + assert len(comparisons) == 2 + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.total == 2 + assert summary.passed == 2 + + +class TestEntrypointNonTensorValues: + """Test non-tensor value comparison through the full entrypoint pipeline.""" + + def test_non_tensor_float_same_value(self, tmp_path: Path, capsys) -> None: + """Two sides dump the same float → ComparisonNonTensorRecord with values_equal=True, category=passed.""" + baseline_path, target_path = _create_non_tensor_dumps( + tmp_path, name="sm_scale", baseline_value=0.125, target_value=0.125 + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + records, _ = _run_and_parse(argv, capsys) + + non_tensors = _get_non_tensors(records) + assert len(non_tensors) == 1 + assert non_tensors[0].name == "sm_scale" + assert non_tensors[0].values_equal is True + assert non_tensors[0].category == "passed" + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 1 + assert summary.failed == 0 + + def test_non_tensor_float_different_value(self, tmp_path: Path, capsys) -> None: + """Two sides dump different floats → ComparisonNonTensorRecord with values_equal=False, category=failed.""" + baseline_path, target_path = _create_non_tensor_dumps( + tmp_path, name="sm_scale", baseline_value=0.125, target_value=0.25 + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + records, _ = _run_and_parse(argv, capsys) + + non_tensors = _get_non_tensors(records) + assert len(non_tensors) == 1 + assert non_tensors[0].values_equal is False + assert non_tensors[0].category == "failed" + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.failed == 1 + + def test_non_tensor_string_value(self, tmp_path: Path, capsys) -> None: + """String non-tensor values are compared and displayed correctly.""" + baseline_path, target_path = _create_non_tensor_dumps( + tmp_path, + name="attn_backend", + baseline_value="flash_attn", + target_value="flash_attn", + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + records, _ = _run_and_parse(argv, capsys) + + non_tensors = _get_non_tensors(records) + assert len(non_tensors) == 1 + assert non_tensors[0].values_equal is True + assert non_tensors[0].baseline_type == "str" + assert non_tensors[0].target_type == "str" + + def test_non_tensor_mixed_with_tensor(self, tmp_path: Path, capsys) -> None: + """Tensors and non_tensors in the same dump are each handled correctly.""" + torch.manual_seed(42) + tensor = torch.randn(4, 4) + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + for side_dir in [baseline_dir, target_dir]: + _create_non_tensor_rank_dump( + side_dir, + rank=0, + name="sm_scale", + value=0.125, + extra_tensor_dumps=[("hidden", tensor)], + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + preset="raw", + ) + records, _ = _run_and_parse(argv, capsys) + + comparisons = _get_comparisons(records) + non_tensors = _get_non_tensors(records) + assert len(comparisons) == 1 + assert comparisons[0].name == "hidden" + assert len(non_tensors) == 1 + assert non_tensors[0].name == "sm_scale" + assert non_tensors[0].values_equal is True + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 2 + + def test_non_tensor_complex_object(self, tmp_path: Path, capsys) -> None: + """Complex objects (e.g. dict containing a tensor) are displayed via repr, not skipped.""" + value = {"a": 1, "b": "hello", "c": torch.tensor([1.0, 2.0])} + baseline_path, target_path = _create_non_tensor_dumps( + tmp_path, name="debug_info", baseline_value=value, target_value=value + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + records, _ = _run_and_parse(argv, capsys) + + non_tensors = _get_non_tensors(records) + assert len(non_tensors) == 1 + assert non_tensors[0].name == "debug_info" + assert non_tensors[0].baseline_type == "dict" + assert non_tensors[0].target_type == "dict" + + def test_non_tensor_none_value(self, tmp_path: Path, capsys) -> None: + """Dumping None is displayed as ComparisonNonTensorRecord, not skipped as load failure.""" + baseline_path, target_path = _create_non_tensor_dumps( + tmp_path, name="optional_param", baseline_value=None, target_value=None + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + records, _ = _run_and_parse(argv, capsys) + + non_tensors = _get_non_tensors(records) + assert len(non_tensors) == 1 + assert non_tensors[0].name == "optional_param" + assert non_tensors[0].values_equal is True + assert non_tensors[0].baseline_value == "None" + assert non_tensors[0].baseline_type == "NoneType" + assert non_tensors[0].category == "passed" + + def test_non_tensor_json_roundtrip(self, tmp_path: Path, capsys) -> None: + """ComparisonNonTensorRecord JSON output can be parsed back correctly.""" + baseline_path, target_path = _create_non_tensor_dumps( + tmp_path, name="sm_scale", baseline_value=0.125, target_value=0.125 + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + records, _ = _run_and_parse(argv, capsys) + + non_tensors = _get_non_tensors(records) + assert len(non_tensors) == 1 + + json_str: str = non_tensors[0].model_dump_json() + roundtripped = parse_record_json(json_str) + assert isinstance(roundtripped, ComparisonNonTensorRecord) + assert roundtripped.name == "sm_scale" + assert roundtripped.values_equal is True + + +# ───────────────────── Visualization integration tests ───────────────────── + + +class TestEntrypointVisualize: + """Test --visualize-bundle-details integration.""" + + @pytest.fixture(autouse=True) + def _skip_if_no_matplotlib(self) -> None: + pytest.importorskip("matplotlib") + + def test_visualize_creates_pngs(self, tmp_path, capsys): + """--visualize-bundle-details with --filter produces PNG files.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a", "tensor_b"]) + viz_dir = tmp_path / "viz_out" + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + filter="tensor_a", + viz_bundle_details=True, + viz_output_dir=str(viz_dir), + ) + + records, _ = _run_and_parse(argv, capsys) + assert len(_get_comparisons(records)) == 1 + + png_files = list(viz_dir.glob("*.png")) + assert len(png_files) == 1 + assert png_files[0].stat().st_size > 0 + + def test_no_visualize_no_png(self, tmp_path, capsys): + """Without --visualize-bundle-details, no PNGs are created.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + viz_dir = tmp_path / "viz_out" + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + viz_bundle_details=False, + viz_output_dir=str(viz_dir), + ) + + _run_and_parse(argv, capsys) + assert not viz_dir.exists() or len(list(viz_dir.glob("*.png"))) == 0 + + +# --------------------------- Assertion helpers ------------------- + + +def _get_comparisons(records: list[AnyRecord]) -> list[ComparisonTensorRecord]: + return [r for r in records if isinstance(r, ComparisonTensorRecord)] + + +def _get_non_tensors(records: list[AnyRecord]) -> list[ComparisonNonTensorRecord]: + return [r for r in records if isinstance(r, ComparisonNonTensorRecord)] + + +def _assert_single_comparison_passed( + records: list[AnyRecord], +) -> ComparisonTensorRecord: + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].diff is not None + assert comparisons[0].diff.passed + return comparisons[0] + + +# --------------------------- Utils ------------------------------ + + +def _make_dumper(directory: Path) -> _Dumper: + return _Dumper(config=DumperConfig(enable=True, dir=str(directory))) + + +def _create_dumps( + tmp_path: Path, + tensor_names: list[str], + *, + baseline_names: list[str] | None = None, + num_steps: int = 1, +) -> tuple[Path, Path]: + """Create baseline and target dump directories with given tensor names. + + If baseline_names is None, uses the same names as tensor_names. + Each step dumps all names with the same tensor (different per baseline/target). + """ + if baseline_names is None: + baseline_names = tensor_names + + d_baseline = tmp_path / "baseline" + d_target = tmp_path / "target" + d_baseline.mkdir() + d_target.mkdir() + + torch.manual_seed(42) + baseline_tensor = torch.randn(10, 10) + target_tensor = baseline_tensor + torch.randn(10, 10) * 0.01 + + exp_paths: list[Path] = [] + for d, names, tensor in [ + (d_baseline, baseline_names, baseline_tensor), + (d_target, tensor_names, target_tensor), + ]: + dumper = _make_dumper(d) + for _ in range(num_steps): + for name in names: + dumper.dump(name, tensor) + dumper.step() + exp_paths.append(d / dumper._config.exp_name) + + return exp_paths[0], exp_paths[1] + + +def _create_non_tensor_rank_dump( + directory: Path, + *, + rank: int, + name: str, + value: object, + extra_tensor_dumps: list[tuple[str, torch.Tensor]] | None = None, +) -> Path: + with pytest.MonkeyPatch.context() as mp: + mp.setattr(_dumper_module, "_get_rank", lambda: rank) + + dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(directory), + exp_name=_FIXED_EXP_NAME, + ) + ) + dumper.__dict__["_static_meta"] = {"world_rank": rank, "world_size": 1} + + dumper.dump(name, value) + for extra_name, extra_tensor in extra_tensor_dumps or []: + dumper.dump(extra_name, extra_tensor) + dumper.step() + + return directory / _FIXED_EXP_NAME + + +def _create_non_tensor_dumps( + tmp_path: Path, + *, + name: str, + baseline_value: object, + target_value: object, +) -> tuple[Path, Path]: + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + baseline_path = _create_non_tensor_rank_dump( + baseline_dir, rank=0, name=name, value=baseline_value + ) + target_path = _create_non_tensor_rank_dump( + target_dir, rank=0, name=name, value=target_value + ) + return baseline_path, target_path + + +def _make_argv( + baseline_path: Path, + target_path: Path, + *, + preset: str | None = None, + grouping_skip_keys: list[str] | None = None, + token_aligner: str | None = None, + diff_threshold: float = 1e-3, + output_format: str = "json", + start_step: int | None = None, + end_step: int | None = None, + filter: str | None = None, + override_dims: list[str] | None = None, + override_baseline_dims: list[str] | None = None, + override_target_dims: list[str] | None = None, + override_config: str | None = None, + allow_skipped_pattern: str | None = None, + allow_failed_pattern: str | None = None, + report_path: str | None = "", + viz_bundle_details: bool = False, + viz_output_dir: str | None = None, + visualize_per_token: str | None = None, +) -> list[str]: + argv: list[str] = [ + "--baseline-path", + str(baseline_path), + "--target-path", + str(target_path), + "--diff-threshold", + str(diff_threshold), + "--output-format", + output_format, + ] + + if preset is not None: + argv += ["--preset", preset] + if grouping_skip_keys is not None: + argv += ["--grouping-skip-keys"] + grouping_skip_keys + if token_aligner is not None: + argv += ["--token-aligner", token_aligner] + if start_step is not None: + argv += ["--start-step", str(start_step)] + if end_step is not None: + argv += ["--end-step", str(end_step)] + if filter is not None: + argv += ["--filter", filter] + for dim in override_dims or []: + argv += ["--override-dims", dim] + for dim in override_baseline_dims or []: + argv += ["--override-baseline-dims", dim] + for dim in override_target_dims or []: + argv += ["--override-target-dims", dim] + if override_config is not None: + argv += ["--override-config", override_config] + if allow_skipped_pattern is not None: + argv += ["--allow-skipped-pattern", allow_skipped_pattern] + if allow_failed_pattern is not None: + argv += ["--allow-failed-pattern", allow_failed_pattern] + if report_path is not None: + argv += ["--report-path", report_path] + if viz_bundle_details: + argv += ["--viz-bundle-details"] + if viz_output_dir is not None: + argv += ["--viz-output-dir", viz_output_dir] + if visualize_per_token is not None: + argv += ["--visualize-per-token", visualize_per_token] + + return argv + + +def _run_and_parse( + argv: list[str], capsys: pytest.CaptureFixture +) -> tuple[list[AnyRecord], int]: + args: Namespace = parse_args(argv) + capsys.readouterr() + exit_code: int = run(args) + return _parse_jsonl(capsys.readouterr().out), exit_code + + +def _parse_jsonl(output: str) -> list[AnyRecord]: + return [parse_record_json(line) for line in output.strip().splitlines()] + + +def _create_rank_dump( + directory: Path, + *, + rank: int, + name: str, + tensor: torch.Tensor, + dims: str | None = None, + parallel_info: dict | None = None, + framework: str = "sglang", + num_steps: int = 1, + extra_dumps: list[tuple[str, object]] | None = None, +) -> Path: + """Create a dump file via the real dumper, as if running on the given rank. + + extra_dumps: additional (name, value) pairs to dump alongside the main tensor each step. + """ + with pytest.MonkeyPatch.context() as mp: + mp.setattr(_dumper_module, "_get_rank", lambda: rank) + + dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(directory), + exp_name=_FIXED_EXP_NAME, + ) + ) + + static_meta: dict = {"world_rank": rank, "world_size": 1} + if parallel_info is not None: + static_meta[f"{framework}_parallel_info"] = parallel_info + dumper.__dict__["_static_meta"] = static_meta + + for _ in range(num_steps): + dumper.dump(name, tensor, dims=dims) + for extra_name, extra_value in extra_dumps or []: + dumper.dump(extra_name, extra_value) + dumper.step() + + return directory / _FIXED_EXP_NAME + + +def _create_multi_step_rank_dump( + directory: Path, + *, + rank: int, + name: str, + tensors_per_step: list[torch.Tensor], + dims: str | None = None, + parallel_info: dict | None = None, + framework: str = "sglang", +) -> Path: + """Create a dump file with *different* tensors per step. + + Unlike ``_create_rank_dump`` (which repeats the same tensor), + this helper accepts a list of tensors — one per step. + """ + with pytest.MonkeyPatch.context() as mp: + mp.setattr(_dumper_module, "_get_rank", lambda: rank) + + dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(directory), + exp_name=_FIXED_EXP_NAME, + ) + ) + + static_meta: dict = {"world_rank": rank, "world_size": 1} + if parallel_info is not None: + static_meta[f"{framework}_parallel_info"] = parallel_info + dumper.__dict__["_static_meta"] = static_meta + + for tensor in tensors_per_step: + dumper.dump(name, tensor, dims=dims) + dumper.step() + + return directory / _FIXED_EXP_NAME + + +def _create_cp_tp_sharded_dumps( + directory: Path, + *, + full_tensor: torch.Tensor, + name: str, + cp_size: int, + tp_size: int, + seq_dim: int, + head_dim: int, + dims_str: str, + num_steps: int = 1, +) -> Path: + """Create CP+TP multi-axis sharded dump files from a full tensor.""" + cp_chunks = list(full_tensor.chunk(cp_size, dim=seq_dim)) + rank = 0 + for cp_rank in range(cp_size): + tp_chunks = list(cp_chunks[cp_rank].chunk(tp_size, dim=head_dim)) + for tp_rank in range(tp_size): + _create_rank_dump( + directory, + rank=rank, + name=name, + tensor=tp_chunks[tp_rank], + dims=dims_str, + parallel_info={ + "cp_rank": cp_rank, + "cp_size": cp_size, + "tp_rank": tp_rank, + "tp_size": tp_size, + }, + num_steps=num_steps, + ) + rank += 1 + return directory / _FIXED_EXP_NAME + + +def _create_ep_cp_tp_sharded_dumps( + directory: Path, + *, + full_tensor: torch.Tensor, + name: str, + ep_size: int, + cp_size: int, + tp_size: int, + expert_dim: int, + seq_dim: int, + head_dim: int, + dims_str: str, + num_steps: int = 1, +) -> Path: + """Create EP+CP+TP three-axis sharded dump files from a full tensor.""" + ep_chunks = list(full_tensor.chunk(ep_size, dim=expert_dim)) + rank = 0 + for ep_rank in range(ep_size): + cp_chunks = list(ep_chunks[ep_rank].chunk(cp_size, dim=seq_dim)) + for cp_rank in range(cp_size): + tp_chunks = list(cp_chunks[cp_rank].chunk(tp_size, dim=head_dim)) + for tp_rank in range(tp_size): + _create_rank_dump( + directory, + rank=rank, + name=name, + tensor=tp_chunks[tp_rank], + dims=dims_str, + parallel_info={ + "ep_rank": ep_rank, + "ep_size": ep_size, + "cp_rank": cp_rank, + "cp_size": cp_size, + "tp_rank": tp_rank, + "tp_size": tp_size, + }, + num_steps=num_steps, + ) + rank += 1 + return directory / _FIXED_EXP_NAME + + +def _create_cp_zigzag_tp_sharded_dumps( + directory: Path, + *, + full_tensor: torch.Tensor, + name: str, + cp_size: int, + tp_size: int, + seq_dim: int, + head_dim: int, + dims_str: str, + num_steps: int = 1, +) -> Path: + """Create CP-zigzag (+optional TP) sharded dump files from a full tensor.""" + num_chunks: int = cp_size * 2 + natural_chunks: list[torch.Tensor] = list( + full_tensor.chunk(num_chunks, dim=seq_dim) + ) + + zigzag_order: list[int] = [] + for i in range(cp_size): + zigzag_order.append(i) + zigzag_order.append(num_chunks - 1 - i) + + zigzagged: torch.Tensor = torch.cat( + [natural_chunks[idx] for idx in zigzag_order], dim=seq_dim + ) + + cp_chunks: list[torch.Tensor] = list(zigzagged.chunk(cp_size, dim=seq_dim)) + + rank: int = 0 + for cp_rank in range(cp_size): + tp_chunks: list[torch.Tensor] = ( + list(cp_chunks[cp_rank].chunk(tp_size, dim=head_dim)) + if tp_size > 1 + else [cp_chunks[cp_rank]] + ) + for tp_rank in range(tp_size): + parallel_info: dict[str, int] = { + "cp_rank": cp_rank, + "cp_size": cp_size, + } + if tp_size > 1: + parallel_info["tp_rank"] = tp_rank + parallel_info["tp_size"] = tp_size + + _create_rank_dump( + directory, + rank=rank, + name=name, + tensor=tp_chunks[tp_rank], + dims=dims_str, + parallel_info=parallel_info, + num_steps=num_steps, + ) + rank += 1 + + return directory / _FIXED_EXP_NAME + + +def _create_cp_zigzag_sp_sharded_dumps( + directory: Path, + *, + full_tensor: torch.Tensor, + name: str, + cp_size: int, + sp_size: int, + dims_str: str, + seq_dim: int = 1, + num_steps: int = 1, +) -> Path: + """Create CP-zigzag + SP sharded dump files for a seq dim (b s h format). + + Shard order (outer to inner, matching left-to-right in dims annotation): + 1. CP zigzag splits seq dim into cp_size chunks (zigzag order) + 2. SP splits each CP chunk into sp_size chunks + """ + num_chunks: int = cp_size * 2 + natural_chunks: list[torch.Tensor] = list( + full_tensor.chunk(num_chunks, dim=seq_dim) + ) + + zigzag_order: list[int] = [] + for i in range(cp_size): + zigzag_order.append(i) + zigzag_order.append(num_chunks - 1 - i) + + zigzagged: torch.Tensor = torch.cat( + [natural_chunks[idx] for idx in zigzag_order], dim=seq_dim + ) + cp_chunks: list[torch.Tensor] = list(zigzagged.chunk(cp_size, dim=seq_dim)) + + rank: int = 0 + for cp_rank in range(cp_size): + sp_chunks: list[torch.Tensor] = list( + cp_chunks[cp_rank].chunk(sp_size, dim=seq_dim) + ) + for sp_rank in range(sp_size): + _create_rank_dump( + directory, + rank=rank, + name=name, + tensor=sp_chunks[sp_rank], + dims=dims_str, + parallel_info={ + "cp_rank": cp_rank, + "cp_size": cp_size, + "sp_rank": sp_rank, + "sp_size": sp_size, + }, + num_steps=num_steps, + ) + rank += 1 + + return directory / _FIXED_EXP_NAME + + +def _create_replicated_tp_sharded_cp_dumps( + directory: Path, + *, + full_tensor: torch.Tensor, + name: str, + cp_size: int, + tp_size: int, + seq_dim: int, + dims_str: str, + tp_noise: float = 0.0, +) -> Path: + """Create CP-sharded + TP-replicated dump files from a full tensor. + + CP direction: chunks along seq_dim (sharded). + TP direction: clones (replicated), with optional noise to simulate mismatch. + """ + cp_chunks: list[torch.Tensor] = list(full_tensor.chunk(cp_size, dim=seq_dim)) + + rank: int = 0 + for cp_rank in range(cp_size): + for tp_rank in range(tp_size): + shard = cp_chunks[cp_rank].clone() + if tp_noise > 0 and tp_rank > 0: + shard = shard + torch.randn_like(shard) * tp_noise + + _create_rank_dump( + directory, + rank=rank, + name=name, + tensor=shard, + dims=dims_str, + parallel_info={ + "cp_rank": cp_rank, + "cp_size": cp_size, + "tp_rank": tp_rank, + "tp_size": tp_size, + }, + ) + rank += 1 + + return directory / _FIXED_EXP_NAME + + +def _create_tp_sharded_dumps( + directory: Path, + *, + full_tensor: torch.Tensor, + name: str, + tp_size: int, + shard_dim: int, + dims_str: str, + num_steps: int = 1, +) -> Path: + """Create TP-sharded dump files from a full tensor via the real dumper.""" + shards = list(full_tensor.chunk(tp_size, dim=shard_dim)) + for tp_rank in range(tp_size): + _create_rank_dump( + directory, + rank=tp_rank, + name=name, + tensor=shards[tp_rank], + dims=dims_str, + parallel_info={"tp_rank": tp_rank, "tp_size": tp_size}, + num_steps=num_steps, + ) + return directory / _FIXED_EXP_NAME + + +def _create_multi_step_tp_sharded_dumps( + directory: Path, + *, + full_tensors_per_step: list[torch.Tensor], + name: str, + tp_size: int, + shard_dim: int, + dims_str: str, +) -> Path: + """Create TP-sharded dump files with *different* tensors per step. + + Each step's full tensor is chunked across TP ranks, then + ``_create_multi_step_rank_dump`` writes one file per rank. + """ + shards_per_rank: list[list[torch.Tensor]] = [[] for _ in range(tp_size)] + for full_tensor in full_tensors_per_step: + shards = list(full_tensor.chunk(tp_size, dim=shard_dim)) + for tp_rank in range(tp_size): + shards_per_rank[tp_rank].append(shards[tp_rank]) + + for tp_rank in range(tp_size): + _create_multi_step_rank_dump( + directory, + rank=tp_rank, + name=name, + tensors_per_step=shards_per_rank[tp_rank], + dims=dims_str, + parallel_info={"tp_rank": tp_rank, "tp_size": tp_size}, + ) + return directory / _FIXED_EXP_NAME + + +def _create_tp_partial_dumps( + directory: Path, + *, + full_tensor: torch.Tensor, + name: str, + tp_size: int, + dims_str: str, + num_steps: int = 1, +) -> Path: + """Create TP-partial dump files where each rank holds full_tensor / tp_size. + + Each rank stores an equal fraction of the full tensor so that + element-wise summation across ranks reconstructs the original. + """ + for tp_rank in range(tp_size): + _create_rank_dump( + directory, + rank=tp_rank, + name=name, + tensor=full_tensor / tp_size, + dims=dims_str, + parallel_info={"tp_rank": tp_rank, "tp_size": tp_size}, + num_steps=num_steps, + ) + return directory / _FIXED_EXP_NAME + + +def _create_recompute_rank_dump( + directory: Path, + *, + rank: int, + name: str, + original_tensor: torch.Tensor, + recompute_tensor: torch.Tensor, + dims: str = "h d", +) -> Path: + """Create a dump with both original and recompute forward passes via monkeypatched dumper. + + The dumper naturally produces recompute_pseudo_rank=0 for original and =1 for recompute, + plus recompute_pseudo_size=2. + """ + with pytest.MonkeyPatch.context() as mp: + mp.setattr(_dumper_module, "_get_rank", lambda: rank) + + dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(directory), + exp_name=_FIXED_EXP_NAME, + ) + ) + dumper.__dict__["_static_meta"] = {"world_rank": rank, "world_size": 1} + + # dump original forward + mp.setattr( + _dumper_module, + "_detect_recompute_status", + lambda: _RecomputeStatus.ORIGINAL, + ) + dumper.dump(name, original_tensor, dims=dims) + + # dump recompute forward + mp.setattr( + _dumper_module, + "_detect_recompute_status", + lambda: _RecomputeStatus.RECOMPUTE, + ) + dumper.dump(name, recompute_tensor, dims=dims) + + dumper.step() + + return directory / _FIXED_EXP_NAME + + +def _zigzag_split_seq(seq_natural: torch.Tensor, *, cp_size: int) -> list[torch.Tensor]: + """Split a natural-order seq into per-rank zigzag segments.""" + num_chunks: int = cp_size * 2 + chunks: list[torch.Tensor] = list(seq_natural.chunk(num_chunks, dim=0)) + order: list[int] = [] + for i in range(cp_size): + order.append(i) + order.append(num_chunks - 1 - i) + zigzagged: torch.Tensor = torch.cat([chunks[i] for i in order], dim=0) + return list(zigzagged.chunk(cp_size, dim=0)) + + +def _create_thd_cp_zigzag_dumps( + directory: Path, + *, + full_tensor: torch.Tensor, + name: str, + seq_lens: list[int], + cp_size: int, + total_per_rank: int, + dims_str: str = "t[cp:zigzag]", + num_steps: int = 1, +) -> Path: + """Create THD CP-zigzag sharded dump files simulating Megatron forward. + + Args: + full_tensor: 1D tensor of shape [T] in natural order. + seq_lens: per-seq token counts in natural order (e.g. [100, 64]). + cp_size: context parallelism size. + total_per_rank: total tokens per rank (including padding). + dims_str: dims annotation for the main tensor. + """ + # Build per-rank tensors from natural-order full_tensor + offset: int = 0 + rank_segments: list[list[torch.Tensor]] = [[] for _ in range(cp_size)] + + for seq_len in seq_lens: + seq_natural: torch.Tensor = full_tensor[offset : offset + seq_len] + seq_ranks: list[torch.Tensor] = _zigzag_split_seq(seq_natural, cp_size=cp_size) + for rank_idx in range(cp_size): + rank_segments[rank_idx].append(seq_ranks[rank_idx]) + offset += seq_len + + # Build cu_seqlens from seq_lens (global, replicated across ranks) + cu_seqlens_values: list[int] = [0] + for slen in seq_lens: + cu_seqlens_values.append(cu_seqlens_values[-1] + slen) + + # Pad to total_per_rank per rank (global pad = last cu_seqlens entry to total_per_rank * cp_size) + total_global: int = total_per_rank * cp_size + if cu_seqlens_values[-1] < total_global: + pad_global: int = total_global - cu_seqlens_values[-1] + cu_seqlens_values.append(total_global) + pad_per_rank: int = pad_global // cp_size + for rank_idx in range(cp_size): + rank_segments[rank_idx].append(torch.zeros(pad_per_rank)) + + cu_seqlens_q: torch.Tensor = torch.tensor(cu_seqlens_values, dtype=torch.int64) + + # Dump each rank + for cp_rank in range(cp_size): + rank_tensor: torch.Tensor = torch.cat(rank_segments[cp_rank], dim=0) + assert ( + rank_tensor.shape[0] == total_per_rank + ), f"rank {cp_rank}: expected {total_per_rank} tokens, got {rank_tensor.shape[0]}" + + _create_rank_dump( + directory, + rank=cp_rank, + name=name, + tensor=rank_tensor, + dims=dims_str, + parallel_info={ + "cp_rank": cp_rank, + "cp_size": cp_size, + }, + framework="megatron", + num_steps=num_steps, + extra_dumps=[ + ("cu_seqlens_q", cu_seqlens_q), + ("input_ids", rank_tensor.to(torch.int64)), + ], + ) + + return directory / _FIXED_EXP_NAME + + +class TestEntrypointPerTokenVisualization: + """Test --visualize-per-token CLI flag integration.""" + + def test_visualize_per_token_creates_png(self, tmp_path: Path, capsys) -> None: + """--visualize-per-token with dims metadata produces per-token data in records.""" + pytest.importorskip("matplotlib") + + torch.manual_seed(42) + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + baseline_tensor: torch.Tensor = torch.randn(10, 10) + target_tensor: torch.Tensor = baseline_tensor + torch.randn(10, 10) * 0.01 + + for name in ["tensor_a", "tensor_b"]: + _create_rank_dump( + baseline_dir, + rank=0, + name=name, + tensor=baseline_tensor, + dims="t h", + ) + _create_rank_dump( + target_dir, + rank=0, + name=name, + tensor=target_tensor, + dims="t h", + ) + + baseline_path: Path = baseline_dir / _FIXED_EXP_NAME + target_path: Path = target_dir / _FIXED_EXP_NAME + + output_png: Path = tmp_path / "per_token.png" + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + visualize_per_token=str(output_png), + ) + records, _ = _run_and_parse(argv, capsys) + + comparisons = _get_comparisons(records) + assert len(comparisons) == 2 + + # per_token_rel_diff should be populated + for comp in comparisons: + assert comp.diff is not None + assert comp.diff.per_token_rel_diff is not None + assert isinstance(comp.diff.per_token_rel_diff, list) + assert len(comp.diff.per_token_rel_diff) == 10 + + def test_no_visualize_no_per_token(self, tmp_path: Path, capsys) -> None: + """Without --visualize-per-token, per_token_rel_diff is None.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + argv = _make_argv(baseline_path, target_path, preset="raw") + + records, _ = _run_and_parse(argv, capsys) + + comparisons = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].diff is not None + assert comparisons[0].diff.per_token_rel_diff is None + + +class TestEntrypointThdCpZigzag: + """E2E entrypoint tests for THD CP zigzag format. + + Tests the full pipeline: dump creation → metadata loading → aligner plan → + unshard + reorder → tensor comparison. + """ + + def test_sglang_vs_megatron_zigzag_cp(self, tmp_path: Path, capsys) -> None: + """SGLang single-rank THD baseline vs Megatron CP=2 zigzag target.""" + torch.manual_seed(42) + hidden_dim: int = 8 + cp_size: int = 2 + + # Two sequences: 8 and 4 tokens (divisible by cp_size*2=4 for clean zigzag) + seq_a_ids: list[int] = [10, 20, 30, 40, 50, 60, 70, 80] + seq_b_ids: list[int] = [100, 200, 300, 400] + all_ids: list[int] = seq_a_ids + seq_b_ids + total_tokens: int = len(all_ids) + seq_lens: list[int] = [len(seq_a_ids), len(seq_b_ids)] + + hidden_states: torch.Tensor = torch.randn(total_tokens, hidden_dim) + + # --- SGLang baseline: single rank, 1 step --- + sglang_dir: Path = tmp_path / "baseline" + sglang_dir.mkdir() + sglang_dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(sglang_dir), + exp_name=_FIXED_EXP_NAME, + ) + ) + + positions: list[int] = list(range(seq_lens[0])) + list(range(seq_lens[1])) + sglang_dumper.dump("input_ids", torch.tensor(all_ids)) + sglang_dumper.dump("positions", torch.tensor(positions)) + sglang_dumper.dump("seq_lens", torch.tensor(seq_lens)) + sglang_dumper.dump("rids", ["A", "B"]) + sglang_dumper.dump("hidden_states", hidden_states) + sglang_dumper.step() + + # --- Megatron target: CP=2, zigzag, 1 step --- + megatron_dir: Path = tmp_path / "target" + megatron_dir.mkdir() + + # Zigzag-split input_ids and hidden_states per sequence, then concat + ids_tensor: torch.Tensor = torch.tensor(all_ids, dtype=torch.int64) + offset: int = 0 + rank_id_segments: list[list[torch.Tensor]] = [[] for _ in range(cp_size)] + rank_hidden_segments: list[list[torch.Tensor]] = [[] for _ in range(cp_size)] + for slen in seq_lens: + seq_ids: torch.Tensor = ids_tensor[offset : offset + slen] + seq_hidden: torch.Tensor = hidden_states[offset : offset + slen] + zigzag_ids: list[torch.Tensor] = _zigzag_split_seq(seq_ids, cp_size=cp_size) + zigzag_hidden: list[torch.Tensor] = _zigzag_split_seq( + seq_hidden, cp_size=cp_size + ) + for rank_idx in range(cp_size): + rank_id_segments[rank_idx].append(zigzag_ids[rank_idx]) + rank_hidden_segments[rank_idx].append(zigzag_hidden[rank_idx]) + offset += slen + + cu_seqlens_q: torch.Tensor = torch.tensor( + [0] + [sum(seq_lens[: i + 1]) for i in range(len(seq_lens))], + dtype=torch.int64, + ) + + for cp_rank in range(cp_size): + rank_ids: torch.Tensor = torch.cat(rank_id_segments[cp_rank]) + rank_hidden: torch.Tensor = torch.cat(rank_hidden_segments[cp_rank]) + _create_rank_dump( + megatron_dir, + rank=cp_rank, + name="hidden_states", + tensor=rank_hidden, + dims="t[cp:zigzag] h", + parallel_info={"cp_rank": cp_rank, "cp_size": cp_size}, + framework="megatron", + extra_dumps=[ + ("cu_seqlens_q", cu_seqlens_q), + ("input_ids", rank_ids), + ], + ) + + # --- Run comparison --- + argv: list[str] = _make_argv( + sglang_dir / _FIXED_EXP_NAME, + megatron_dir / _FIXED_EXP_NAME, + grouping_skip_keys=["rank", "step"], + token_aligner="smart", + diff_threshold=1e-3, + ) + records, _ = _run_and_parse(argv, capsys) + + comparisons: list[ComparisonTensorRecord] = _get_comparisons(records) + hidden_comparisons: list[ComparisonTensorRecord] = [ + c for c in comparisons if c.name == "hidden_states" + ] + assert len(hidden_comparisons) >= 1 + assert all(c.diff is not None and c.diff.passed for c in hidden_comparisons) + + def test_thd_cp_zigzag_unshard(self, tmp_path: Path, capsys) -> None: + """Both sides THD CP=2 zigzag, comparison should pass.""" + torch.manual_seed(42) + cp_size: int = 2 + seq_lens: list[int] = [100, 64] + total_tokens: int = sum(seq_lens) + total_per_rank: int = 128 + + full_tensor: torch.Tensor = torch.randn(total_tokens + 92) + + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + baseline_path: Path = _create_thd_cp_zigzag_dumps( + baseline_dir, + full_tensor=full_tensor, + name="hidden_states", + seq_lens=seq_lens, + cp_size=cp_size, + total_per_rank=total_per_rank, + ) + + # Target: same data with small noise + target_tensor: torch.Tensor = full_tensor + torch.randn_like(full_tensor) * 1e-5 + target_path: Path = _create_thd_cp_zigzag_dumps( + target_dir, + full_tensor=target_tensor, + name="hidden_states", + seq_lens=seq_lens, + cp_size=cp_size, + total_per_rank=total_per_rank, + ) + + argv: list[str] = _make_argv( + baseline_path, + target_path, + grouping_skip_keys=["rank", "step"], + token_aligner="smart", + diff_threshold=1e-3, + ) + records, _ = _run_and_parse(argv, capsys) + + # hidden_states should pass comparison (after unshard + reorder) + comparisons: list[ComparisonTensorRecord] = _get_comparisons(records) + hidden_comparisons: list[ComparisonTensorRecord] = [ + c for c in comparisons if c.name == "hidden_states" + ] + assert len(hidden_comparisons) >= 1 + assert all(c.diff is not None and c.diff.passed for c in hidden_comparisons) + + +class TestEntrypointDpFilter: + """E2E tests for DP (data parallel) filtering. + + When DP > 1, only one dp_rank has non-empty tensors; the others + dump empty (numel=0) tensors. The comparator should filter out the + empty dp_rank items and produce correct comparison results. + """ + + def test_dp2_sglang_both_sides(self, tmp_path: Path, capsys) -> None: + """DP=2 sglang: both baseline and target have 1 non-empty + 1 empty dp_rank.""" + torch.manual_seed(42) + tensor_data: torch.Tensor = torch.randn(10, 8) + target_data: torch.Tensor = tensor_data + torch.randn(10, 8) * 0.001 + + for side, side_dir_name, data in [ + ("baseline", "baseline", tensor_data), + ("target", "target", target_data), + ]: + side_dir: Path = tmp_path / side_dir_name + side_dir.mkdir() + + # dp_rank=0: non-empty tensor + _create_rank_dump( + side_dir, + rank=0, + name="hidden", + tensor=data, + dims="t h", + parallel_info={ + "tp_rank": 0, + "tp_size": 1, + "dp_rank": 0, + "dp_size": 2, + }, + framework="sglang", + ) + + # dp_rank=1: empty tensor + _create_rank_dump( + side_dir, + rank=1, + name="hidden", + tensor=torch.empty(0, 8), + dims="t h", + parallel_info={ + "tp_rank": 0, + "tp_size": 1, + "dp_rank": 1, + "dp_size": 2, + }, + framework="sglang", + ) + + argv: list[str] = _make_argv( + tmp_path / "baseline" / _FIXED_EXP_NAME, + tmp_path / "target" / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + records, _ = _run_and_parse(argv, capsys) + + comparison: ComparisonTensorRecord = _assert_single_comparison_passed(records) + assert comparison.name == "hidden" + + def test_dp2_megatron_both_sides(self, tmp_path: Path, capsys) -> None: + """DP=2 megatron: both baseline and target have 1 non-empty + 1 empty dp_rank.""" + torch.manual_seed(42) + tensor_data: torch.Tensor = torch.randn(10, 8) + target_data: torch.Tensor = tensor_data + torch.randn(10, 8) * 0.001 + + for side, side_dir_name, data in [ + ("baseline", "baseline", tensor_data), + ("target", "target", target_data), + ]: + side_dir: Path = tmp_path / side_dir_name + side_dir.mkdir() + + # dp_rank=0: non-empty tensor + _create_rank_dump( + side_dir, + rank=0, + name="hidden", + tensor=data, + dims="t h", + parallel_info={ + "tp_rank": 0, + "tp_size": 1, + "dp_rank": 0, + "dp_size": 2, + }, + framework="megatron", + ) + + # dp_rank=1: empty tensor + _create_rank_dump( + side_dir, + rank=1, + name="hidden", + tensor=torch.empty(0, 8), + dims="t h", + parallel_info={ + "tp_rank": 0, + "tp_size": 1, + "dp_rank": 1, + "dp_size": 2, + }, + framework="megatron", + ) + + argv: list[str] = _make_argv( + tmp_path / "baseline" / _FIXED_EXP_NAME, + tmp_path / "target" / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + records, _ = _run_and_parse(argv, capsys) + + comparison: ComparisonTensorRecord = _assert_single_comparison_passed(records) + assert comparison.name == "hidden" + + def test_dp2_tp2_sglang(self, tmp_path: Path, capsys) -> None: + """DP=2 x TP=2 sglang: 4 ranks, dp_rank=0 has data, dp_rank=1 empty.""" + torch.manual_seed(42) + full_tensor: torch.Tensor = torch.randn(10, 8) + tp_chunks: list[torch.Tensor] = list(full_tensor.chunk(2, dim=1)) + + target_full: torch.Tensor = full_tensor + torch.randn(10, 8) * 0.001 + target_tp_chunks: list[torch.Tensor] = list(target_full.chunk(2, dim=1)) + + for side, side_dir_name, chunks in [ + ("baseline", "baseline", tp_chunks), + ("target", "target", target_tp_chunks), + ]: + side_dir: Path = tmp_path / side_dir_name + side_dir.mkdir() + + rank: int = 0 + for dp_rank in range(2): + for tp_rank in range(2): + tensor: torch.Tensor = ( + chunks[tp_rank] if dp_rank == 0 else torch.empty(0, 4) + ) + _create_rank_dump( + side_dir, + rank=rank, + name="hidden", + tensor=tensor, + dims="t h[tp]", + parallel_info={ + "tp_rank": tp_rank, + "tp_size": 2, + "dp_rank": dp_rank, + "dp_size": 2, + }, + framework="sglang", + ) + rank += 1 + + argv: list[str] = _make_argv( + tmp_path / "baseline" / _FIXED_EXP_NAME, + tmp_path / "target" / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + records, _ = _run_and_parse(argv, capsys) + + comparison: ComparisonTensorRecord = _assert_single_comparison_passed(records) + assert comparison.name == "hidden" + + def test_dp2_both_nonempty_raises(self, tmp_path: Path, capsys) -> None: + """DP=2 sglang: both dp_rank=0 and dp_rank=1 have non-empty tensors => AssertionError.""" + torch.manual_seed(42) + tensor_data: torch.Tensor = torch.randn(10, 8) + target_data: torch.Tensor = tensor_data + torch.randn(10, 8) * 0.001 + + for side, side_dir_name, data in [ + ("baseline", "baseline", tensor_data), + ("target", "target", target_data), + ]: + side_dir: Path = tmp_path / side_dir_name + side_dir.mkdir() + + for dp_rank in range(2): + _create_rank_dump( + side_dir, + rank=dp_rank, + name="hidden", + tensor=data, + dims="t h", + parallel_info={ + "tp_rank": 0, + "tp_size": 1, + "dp_rank": dp_rank, + "dp_size": 2, + }, + framework="sglang", + ) + + argv: list[str] = _make_argv( + tmp_path / "baseline" / _FIXED_EXP_NAME, + tmp_path / "target" / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + + records, exit_code = _run_and_parse(argv, capsys) + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) == 1 + assert errors[0].exception_type == "AssertionError" + assert "Expected exactly 1 non-empty dp_rank" in errors[0].exception_message + assert exit_code == 1 + + +class TestEntrypointDpGroupAlias: + """E2E tests for the ``# dp:=`` dp group alias feature. + + In dp_attn mode, dp_size > 1 but MLP tensors after dp_gather have data + on all ranks. With ``# dp:=moe_dp`` in dims, the dp filter uses + ``moe_dp_rank/moe_dp_size`` instead of ``dp_rank/dp_size``. + """ + + def test_dp_alias_absent_group_noop(self, tmp_path: Path, capsys) -> None: + """Single rank with ``# dp:=moe_dp`` in dims → parse_dims strips ``#``, comparison OK.""" + torch.manual_seed(42) + tensor_data: torch.Tensor = torch.randn(10, 8) + target_data: torch.Tensor = tensor_data + torch.randn(10, 8) * 0.001 + + for side_dir_name, data in [("baseline", tensor_data), ("target", target_data)]: + side_dir: Path = tmp_path / side_dir_name + side_dir.mkdir() + + _create_rank_dump( + side_dir, + rank=0, + name="hidden", + tensor=data, + dims="t h # dp:=moe_dp", + parallel_info={ + "tp_rank": 0, + "tp_size": 1, + "dp_rank": 0, + "dp_size": 1, + }, + framework="sglang", + ) + + argv: list[str] = _make_argv( + tmp_path / "baseline" / _FIXED_EXP_NAME, + tmp_path / "target" / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + records, _ = _run_and_parse(argv, capsys) + + comparison: ComparisonTensorRecord = _assert_single_comparison_passed(records) + assert comparison.name == "hidden" + + def test_dp_alias_via_override_dims(self, tmp_path: Path, capsys) -> None: + """--override-dims adds ``# dp:=moe_dp`` → dp filter uses alias, filters correctly.""" + torch.manual_seed(42) + tensor_data: torch.Tensor = torch.randn(10, 8) + target_data: torch.Tensor = tensor_data + torch.randn(10, 8) * 0.001 + + for side_dir_name, data in [("baseline", tensor_data), ("target", target_data)]: + side_dir: Path = tmp_path / side_dir_name + side_dir.mkdir() + + # moe_dp_rank=0: non-empty + _create_rank_dump( + side_dir, + rank=0, + name="hidden", + tensor=data, + dims="t h", + parallel_info={ + "tp_rank": 0, + "tp_size": 1, + "dp_rank": 0, + "dp_size": 1, + "moe_dp_rank": 0, + "moe_dp_size": 2, + }, + framework="sglang", + ) + + # moe_dp_rank=1: empty + _create_rank_dump( + side_dir, + rank=1, + name="hidden", + tensor=torch.empty(0, 8), + dims="t h", + parallel_info={ + "tp_rank": 0, + "tp_size": 1, + "dp_rank": 0, + "dp_size": 1, + "moe_dp_rank": 1, + "moe_dp_size": 2, + }, + framework="sglang", + ) + + argv: list[str] = _make_argv( + tmp_path / "baseline" / _FIXED_EXP_NAME, + tmp_path / "target" / _FIXED_EXP_NAME, + diff_threshold=1e-3, + override_dims=["hidden:t h # dp:=moe_dp"], + ) + records, _ = _run_and_parse(argv, capsys) + + comparison: ComparisonTensorRecord = _assert_single_comparison_passed(records) + assert comparison.name == "hidden" + + def test_dp_alias_with_real_alias_group_filters( + self, tmp_path: Path, capsys + ) -> None: + """Alias group present with moe_dp_size=2, one empty rank → filters correctly.""" + torch.manual_seed(42) + tensor_data: torch.Tensor = torch.randn(10, 8) + target_data: torch.Tensor = tensor_data + torch.randn(10, 8) * 0.001 + + for side_dir_name, data in [("baseline", tensor_data), ("target", target_data)]: + side_dir: Path = tmp_path / side_dir_name + side_dir.mkdir() + + for moe_dp_rank in range(2): + tensor: torch.Tensor = data if moe_dp_rank == 0 else torch.empty(0, 8) + _create_rank_dump( + side_dir, + rank=moe_dp_rank, + name="hidden", + tensor=tensor, + dims="t h # dp:=moe_dp", + parallel_info={ + "tp_rank": 0, + "tp_size": 1, + "dp_rank": 0, + "dp_size": 1, + "moe_dp_rank": moe_dp_rank, + "moe_dp_size": 2, + }, + framework="sglang", + ) + + argv: list[str] = _make_argv( + tmp_path / "baseline" / _FIXED_EXP_NAME, + tmp_path / "target" / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + records, _ = _run_and_parse(argv, capsys) + + comparison: ComparisonTensorRecord = _assert_single_comparison_passed(records) + assert comparison.name == "hidden" + + +class TestEntrypointMetaOverride: + """E2E: dump with wrong dims → --override-dims / --override-config corrects at comparison time.""" + + @staticmethod + def _create_single_rank_pair( + tmp_path: Path, + *, + name: str = "hidden", + baseline_dims: str | None = "x y", + target_dims: str | None = "x y", + ) -> tuple[Path, Path]: + """Create single-rank baseline+target dumps with a close tensor pair.""" + torch.manual_seed(42) + tensor: torch.Tensor = torch.randn(10, 8) + target: torch.Tensor = tensor + torch.randn(10, 8) * 0.001 + + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + _create_rank_dump( + baseline_dir, rank=0, name=name, tensor=tensor, dims=baseline_dims + ) + _create_rank_dump( + target_dir, rank=0, name=name, tensor=target, dims=target_dims + ) + + return baseline_dir / _FIXED_EXP_NAME, target_dir / _FIXED_EXP_NAME + + @staticmethod + def _assert_all_passed( + records: list[AnyRecord], *, expected_count: int = 1 + ) -> None: + """Assert that exactly expected_count comparisons exist and all passed.""" + comparisons: list[ComparisonTensorRecord] = _get_comparisons(records) + assert len(comparisons) == expected_count + assert all(c.diff is not None and c.diff.passed for c in comparisons) + + def test_override_dims_fixes_wrong_dims(self, tmp_path: Path, capsys) -> None: + """Tensor dumped with wrong dims='h d' is fixed by --override-dims to 't h[tp]'.""" + torch.manual_seed(42) + + full_tensor: torch.Tensor = torch.randn(10, 8) + tp_chunks: list[torch.Tensor] = list(full_tensor.chunk(2, dim=1)) + + target_full: torch.Tensor = full_tensor + torch.randn(10, 8) * 0.001 + target_tp_chunks: list[torch.Tensor] = list(target_full.chunk(2, dim=1)) + + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + # Dump with WRONG dims "h d" instead of correct "t h[tp]" + for tp_rank in range(2): + _create_rank_dump( + baseline_dir, + rank=tp_rank, + name="hidden", + tensor=tp_chunks[tp_rank], + dims="h d", + parallel_info={"tp_rank": tp_rank, "tp_size": 2}, + ) + _create_rank_dump( + target_dir, + rank=tp_rank, + name="hidden", + tensor=target_tp_chunks[tp_rank], + dims="h d", + parallel_info={"tp_rank": tp_rank, "tp_size": 2}, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + override_dims=["hidden:t h[tp]"], + ) + self._assert_all_passed(_run_and_parse(argv, capsys)[0]) + + @pytest.mark.parametrize( + "baseline_dims, target_dims, override_kwarg", + [ + ("x y", "t h", {"override_baseline_dims": ["hidden:t h"]}), + ("t h", "x y", {"override_target_dims": ["hidden:t h"]}), + ("x y", "x y", {"override_dims": ["hidden:t h"]}), + ], + ids=["baseline_only", "target_only", "both_via_override_dims"], + ) + def test_single_side_override( + self, + tmp_path: Path, + capsys, + baseline_dims: str, + target_dims: str, + override_kwarg: dict, + ) -> None: + """Per-side override fixes the wrong dims on one or both sides.""" + baseline_path, target_path = self._create_single_rank_pair( + tmp_path, + baseline_dims=baseline_dims, + target_dims=target_dims, + ) + + argv = _make_argv(baseline_path, target_path, preset="raw", **override_kwarg) + self._assert_all_passed(_run_and_parse(argv, capsys)[0]) + + def test_override_config_yaml(self, tmp_path: Path, capsys) -> None: + """--override-config YAML overrides dims.""" + baseline_path, target_path = self._create_single_rank_pair(tmp_path) + + yaml_path: Path = tmp_path / "override.yaml" + yaml_path.write_text(textwrap.dedent("""\ + overrides: + - match: "hidden" + dims: "t h" + """)) + + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + override_config=str(yaml_path), + ) + self._assert_all_passed(_run_and_parse(argv, capsys)[0]) + + def test_no_match_uses_original_dims(self, tmp_path: Path, capsys) -> None: + """When override regex doesn't match, original dims from dump are used.""" + baseline_path, target_path = self._create_single_rank_pair( + tmp_path, + baseline_dims="t h", + target_dims="t h", + ) + + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + override_dims=["no_match_pattern:b s d"], + ) + self._assert_all_passed(_run_and_parse(argv, capsys)[0]) + + def test_selective_match_multi_tensor(self, tmp_path: Path, capsys) -> None: + """Override matches only 'logits'; 'hidden' uses original dims.""" + torch.manual_seed(42) + + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + hidden_b: torch.Tensor = torch.randn(10, 8) + hidden_t: torch.Tensor = hidden_b + torch.randn(10, 8) * 0.001 + logits_b: torch.Tensor = torch.randn(10, 4) + logits_t: torch.Tensor = logits_b + torch.randn(10, 4) * 0.001 + + for name, b_tensor, t_tensor, dims in [ + ("hidden", hidden_b, hidden_t, "t h"), + ("logits", logits_b, logits_t, "x y"), + ]: + _create_rank_dump( + baseline_dir, rank=0, name=name, tensor=b_tensor, dims=dims + ) + _create_rank_dump(target_dir, rank=0, name=name, tensor=t_tensor, dims=dims) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + preset="raw", + override_dims=["logits:t v"], + ) + self._assert_all_passed(_run_and_parse(argv, capsys)[0], expected_count=2) + + def test_multiple_cli_override_dims(self, tmp_path: Path, capsys) -> None: + """Multiple --override-dims for different tensors.""" + torch.manual_seed(42) + + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + hidden_b: torch.Tensor = torch.randn(10, 8) + hidden_t: torch.Tensor = hidden_b + torch.randn(10, 8) * 0.001 + logits_b: torch.Tensor = torch.randn(10, 4) + logits_t: torch.Tensor = logits_b + torch.randn(10, 4) * 0.001 + + for name, b_tensor, t_tensor in [ + ("hidden", hidden_b, hidden_t), + ("logits", logits_b, logits_t), + ]: + _create_rank_dump( + baseline_dir, rank=0, name=name, tensor=b_tensor, dims="x y" + ) + _create_rank_dump( + target_dir, rank=0, name=name, tensor=t_tensor, dims="x y" + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + preset="raw", + override_dims=["hidden:t h", "logits:t v"], + ) + self._assert_all_passed(_run_and_parse(argv, capsys)[0], expected_count=2) + + def test_per_side_dims_different_parallelism(self, tmp_path: Path, capsys) -> None: + """baseline TP-sharded, target EP-sharded — per-side override fixes both.""" + torch.manual_seed(42) + full_tensor: torch.Tensor = torch.randn(10, 8) + target_full: torch.Tensor = full_tensor + torch.randn(10, 8) * 0.001 + + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + b_chunks: list[torch.Tensor] = list(full_tensor.chunk(2, dim=1)) + for tp_rank in range(2): + _create_rank_dump( + baseline_dir, + rank=tp_rank, + name="hidden", + tensor=b_chunks[tp_rank], + dims="x y", + parallel_info={"tp_rank": tp_rank, "tp_size": 2}, + ) + + t_chunks: list[torch.Tensor] = list(target_full.chunk(2, dim=1)) + for ep_rank in range(2): + _create_rank_dump( + target_dir, + rank=ep_rank, + name="hidden", + tensor=t_chunks[ep_rank], + dims="x y", + parallel_info={"ep_rank": ep_rank, "ep_size": 2}, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + override_baseline_dims=["hidden:t h[tp]"], + override_target_dims=["hidden:t h[ep]"], + ) + self._assert_all_passed(_run_and_parse(argv, capsys)[0]) + + def test_yaml_first_match_wins_e2e(self, tmp_path: Path, capsys) -> None: + """YAML with two matching rules: first rule wins in real pipeline.""" + baseline_path, target_path = self._create_single_rank_pair(tmp_path) + + yaml_path: Path = tmp_path / "override.yaml" + yaml_path.write_text(textwrap.dedent("""\ + overrides: + - match: "hidden" + dims: "t h" + - match: "hidden" + dims: "a b" + """)) + + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + override_config=str(yaml_path), + ) + self._assert_all_passed(_run_and_parse(argv, capsys)[0]) + + def test_cli_overrides_yaml_e2e(self, tmp_path: Path, capsys) -> None: + """CLI --override-dims wins over YAML rule for the same tensor.""" + baseline_path, target_path = self._create_single_rank_pair(tmp_path) + + yaml_path: Path = tmp_path / "override.yaml" + yaml_path.write_text(textwrap.dedent("""\ + overrides: + - match: "hidden" + dims: "a b" + """)) + + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + override_dims=["hidden:t h"], + override_config=str(yaml_path), + ) + self._assert_all_passed(_run_and_parse(argv, capsys)[0]) + + def test_override_injects_dims_when_absent(self, tmp_path: Path, capsys) -> None: + """Override injects dims into meta even when dump had no dims annotation.""" + baseline_path, target_path = self._create_single_rank_pair( + tmp_path, + baseline_dims=None, + target_dims=None, + ) + + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + override_dims=["hidden:t h"], + ) + self._assert_all_passed(_run_and_parse(argv, capsys)[0]) + + def test_non_tensor_unaffected_by_override(self, tmp_path: Path, capsys) -> None: + """Non-tensor values pass through without error even with active override.""" + torch.manual_seed(42) + tensor: torch.Tensor = torch.randn(4, 4) + + baseline_dir: Path = tmp_path / "baseline" + target_dir: Path = tmp_path / "target" + baseline_dir.mkdir() + target_dir.mkdir() + + for side_dir in [baseline_dir, target_dir]: + _create_non_tensor_rank_dump( + side_dir, + rank=0, + name="sm_scale", + value=0.125, + extra_tensor_dumps=[("hidden", tensor)], + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + preset="raw", + override_dims=["hidden:x y"], + ) + records, _ = _run_and_parse(argv, capsys) + + non_tensors: list[ComparisonNonTensorRecord] = [ + r for r in records if isinstance(r, ComparisonNonTensorRecord) + ] + assert len(non_tensors) == 1 + assert non_tensors[0].name == "sm_scale" + assert non_tensors[0].values_equal + + comparisons: list[ComparisonTensorRecord] = _get_comparisons(records) + assert len(comparisons) == 1 + assert comparisons[0].name == "hidden" + + summary: SummaryRecord = [r for r in records if isinstance(r, SummaryRecord)][0] + assert summary.failed == 0 + + +class TestExitCode: + """E2E tests for exit code behavior based on comparison results.""" + + def test_e2e_all_passed_exit_zero(self, tmp_path, capsys): + """Integration: all comparisons pass → run() returns 0.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a", "tensor_b"]) + argv = _make_argv(baseline_path, target_path, preset="raw") + + records, exit_code = _run_and_parse(argv, capsys) + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 2 + assert summary.failed == 0 + assert exit_code == 0 + + def test_e2e_has_failed_exit_nonzero(self, tmp_path, capsys): + """Integration: a failed comparison → run() returns 1.""" + torch.manual_seed(42) + baseline_path = _create_rank_dump( + tmp_path / "baseline", rank=0, name="tensor_a", tensor=torch.randn(10, 10) + ) + target_path = _create_rank_dump( + tmp_path / "target", + rank=0, + name="tensor_a", + tensor=torch.randn(10, 10) * 100, + ) + argv = _make_argv(baseline_path, target_path, preset="raw", diff_threshold=1e-3) + + records, exit_code = _run_and_parse(argv, capsys) + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.failed == 1 + assert exit_code == 1 + + def test_e2e_allow_failed_pattern_exit_zero(self, tmp_path, capsys): + """E2E: failed tensor matched by allow_failed_pattern + a passing tensor → exit 0.""" + torch.manual_seed(42) + shared_tensor = torch.randn(10, 10) + + baseline_path = _create_rank_dump( + tmp_path / "baseline", + rank=0, + name="tensor_bad", + tensor=torch.randn(10, 10), + extra_dumps=[("tensor_good", shared_tensor)], + ) + target_path = _create_rank_dump( + tmp_path / "target", + rank=0, + name="tensor_bad", + tensor=torch.randn(10, 10) * 100, + extra_dumps=[("tensor_good", shared_tensor)], + ) + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + diff_threshold=1e-3, + allow_failed_pattern="tensor_bad", + ) + + records, exit_code = _run_and_parse(argv, capsys) + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 1 + assert summary.failed == 1 + assert exit_code == 0 + + def test_e2e_allow_failed_pattern_no_match_exit_one(self, tmp_path, capsys): + """E2E: failed tensor NOT matched by allow_failed_pattern → exit 1.""" + torch.manual_seed(42) + shared_tensor = torch.randn(10, 10) + + baseline_path = _create_rank_dump( + tmp_path / "baseline", + rank=0, + name="tensor_bad", + tensor=torch.randn(10, 10), + extra_dumps=[("tensor_good", shared_tensor)], + ) + target_path = _create_rank_dump( + tmp_path / "target", + rank=0, + name="tensor_bad", + tensor=torch.randn(10, 10) * 100, + extra_dumps=[("tensor_good", shared_tensor)], + ) + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + diff_threshold=1e-3, + allow_failed_pattern="other_tensor", + ) + + records, exit_code = _run_and_parse(argv, capsys) + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.passed == 1 + assert summary.failed == 1 + assert exit_code == 1 + + +class TestExitCodeSubprocess: + """E2E subprocess tests: invoke comparator as a child process and verify exit code.""" + + @staticmethod + def _run_comparator( + baseline_path: Path, + target_path: Path, + *, + preset: str = "raw", + allow_skipped_pattern: str = ".*", + ) -> subprocess.CompletedProcess[str]: + cmd: list[str] = [ + sys.executable, + "-m", + "sglang.srt.debug_utils.comparator", + "--baseline-path", + str(baseline_path), + "--target-path", + str(target_path), + "--preset", + preset, + "--output-format", + "json", + "--allow-skipped-pattern", + allow_skipped_pattern, + ] + return subprocess.run(cmd, capture_output=True, text=True) + + def test_all_passed_exit_zero(self, tmp_path): + """Subprocess: all comparisons pass → exit 0.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + result = self._run_comparator(baseline_path, target_path) + assert result.returncode == 0 + + def test_failed_exit_nonzero(self, tmp_path): + """Subprocess: failed comparison → exit 1.""" + torch.manual_seed(42) + baseline_path = _create_rank_dump( + tmp_path / "baseline", rank=0, name="t", tensor=torch.randn(10, 10) + ) + target_path = _create_rank_dump( + tmp_path / "target", rank=0, name="t", tensor=torch.randn(10, 10) * 100 + ) + result = self._run_comparator(baseline_path, target_path) + assert result.returncode == 1 + + def test_skipped_allow_all_exit_zero(self, tmp_path): + """Subprocess: skipped comparison with allow_skipped_pattern='.*' → exit 0.""" + baseline_path, target_path = _create_dumps( + tmp_path, + tensor_names=["tensor_a", "tensor_extra"], + baseline_names=["tensor_a"], + ) + result = self._run_comparator( + baseline_path, target_path, allow_skipped_pattern=".*" + ) + assert result.returncode == 0 + + def test_skipped_forbid_all_exit_nonzero(self, tmp_path): + """Subprocess: skipped comparison with allow_skipped_pattern='^$' → exit 1.""" + baseline_path, target_path = _create_dumps( + tmp_path, + tensor_names=["tensor_a", "tensor_extra"], + baseline_names=["tensor_a"], + ) + result = self._run_comparator( + baseline_path, target_path, allow_skipped_pattern="^$" + ) + assert result.returncode == 1 + + +class TestReportOutput: + """Test JSONL report file output via ReportSink.""" + + def test_default_report_path(self, tmp_path, capsys): + """Default writes to /comparator_report.jsonl with ConfigRecord + SummaryRecord.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + argv = _make_argv(baseline_path, target_path, preset="raw", report_path=None) + + exit_code: int = run(parse_args(argv)) + + report_file: Path = target_path / "comparator_report.jsonl" + assert report_file.exists() + + report_records: list[AnyRecord] = _parse_jsonl(report_file.read_text()) + assert isinstance(report_records[0], ConfigRecord) + assert isinstance(report_records[-1], SummaryRecord) + assert exit_code == 0 + + def test_custom_report_path(self, tmp_path, capsys): + """--report-path writes to the specified location.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + custom_path: Path = tmp_path / "custom" / "report.jsonl" + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + report_path=str(custom_path), + ) + + run(parse_args(argv)) + + assert custom_path.exists() + report_records: list[AnyRecord] = _parse_jsonl(custom_path.read_text()) + assert isinstance(report_records[0], ConfigRecord) + assert isinstance(report_records[-1], SummaryRecord) + + def test_disabled_report(self, tmp_path, capsys): + """--report-path '' disables file generation.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + argv = _make_argv(baseline_path, target_path, preset="raw", report_path="") + + run(parse_args(argv)) + + report_file: Path = target_path / "comparator_report.jsonl" + assert not report_file.exists() + + def test_report_matches_stdout_json(self, tmp_path, capsys): + """In json mode, report content matches stdout output.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + report_file: Path = tmp_path / "report.jsonl" + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + output_format="json", + report_path=str(report_file), + ) + + capsys.readouterr() + run(parse_args(argv)) + + stdout_lines: list[str] = capsys.readouterr().out.strip().splitlines() + report_lines: list[str] = report_file.read_text().strip().splitlines() + assert stdout_lines == report_lines + + def test_text_mode_also_writes_report(self, tmp_path, capsys): + """Text stdout mode still writes JSONL report.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + report_file: Path = tmp_path / "report.jsonl" + argv = _make_argv( + baseline_path, + target_path, + preset="raw", + output_format="text", + report_path=str(report_file), + ) + + run(parse_args(argv)) + + assert report_file.exists() + report_records: list[AnyRecord] = _parse_jsonl(report_file.read_text()) + assert isinstance(report_records[0], ConfigRecord) + assert isinstance(report_records[-1], SummaryRecord) + + def test_streaming_flush(self, tmp_path, capsys): + """Report file is flushed after each record (readable before close).""" + from sglang.srt.debug_utils.comparator.report_sink import report_sink + + report_file: Path = tmp_path / "stream_report.jsonl" + report_sink.configure( + output_format="json", + report_path=report_file, + ) + + report_sink.add(ConfigRecord(config={"test": True})) + + content: str = report_file.read_text() + assert len(content.strip().splitlines()) == 1 + parsed: AnyRecord = parse_record_json(content.strip()) + assert isinstance(parsed, ConfigRecord) + + +class TestEntrypointDpAttentionMissingAlias: + """Regression: dp-attention without ``# dp:=attn_dp`` → shape mismatch failure. + + In dp-attention mode (tp_size=2, attn_dp_size=2), layer_input is dumped + after prepare_attn which DP-distributes tokens. One rank gets 0 tokens + (shape [0, H]), the other gets all tokens (shape [T, H]). + + Without ``# dp:=attn_dp`` in dims, the comparator has no dp_rank/dp_size + to filter on, so it picks one rank via TP pick — potentially the empty + one — causing a shape mismatch with the baseline. + """ + + @staticmethod + def _sglang_dp_attn_parallel_info(*, tp_rank: int) -> dict: + return { + "tp_rank": tp_rank, + "tp_size": 2, + "pp_rank": 0, + "pp_size": 1, + "moe_ep_rank": 0, + "moe_ep_size": 1, + "moe_tp_rank": tp_rank, + "moe_tp_size": 2, + "moe_dp_rank": 0, + "moe_dp_size": 1, + "enable_dp_attention": True, + "attn_tp_rank": 0, + "attn_tp_size": 1, + "attn_dp_rank": tp_rank, + "attn_dp_size": 2, + "local_attn_dp_rank": tp_rank, + "local_attn_dp_size": 2, + "attn_cp_rank": 0, + "attn_cp_size": 1, + } + + def test_missing_dp_alias_causes_shape_mismatch( + self, tmp_path: Path, capsys + ) -> None: + """dims='t h' (no dp:=attn_dp) → comparator picks empty rank → shape_mismatch failure.""" + torch.manual_seed(42) + tensor_data: torch.Tensor = torch.randn(5, 8) + target_data: torch.Tensor = tensor_data + torch.randn(5, 8) * 0.001 + + for side_name, data in [("baseline", tensor_data), ("target", target_data)]: + side_dir: Path = tmp_path / side_name + side_dir.mkdir() + + # Baseline: single rank, no DP attention + if side_name == "baseline": + _create_rank_dump( + side_dir, + rank=0, + name="layer_input", + tensor=data, + dims="t h", + parallel_info={"tp_rank": 0, "tp_size": 1}, + framework="sglang", + ) + else: + # Target: dp-attention, tp_rank=0 gets 0 tokens, tp_rank=1 gets all + _create_rank_dump( + side_dir, + rank=0, + name="layer_input", + tensor=torch.empty(0, 8), + dims="t h", + parallel_info=self._sglang_dp_attn_parallel_info(tp_rank=0), + framework="sglang", + ) + _create_rank_dump( + side_dir, + rank=1, + name="layer_input", + tensor=data, + dims="t h", + parallel_info=self._sglang_dp_attn_parallel_info(tp_rank=1), + framework="sglang", + ) + + argv: list[str] = _make_argv( + tmp_path / "baseline" / _FIXED_EXP_NAME, + tmp_path / "target" / _FIXED_EXP_NAME, + diff_threshold=1e-3, + ) + records, exit_code = _run_and_parse(argv, capsys) + + assert exit_code == 1 + + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) == 1 + assert errors[0].category == "errored" + + +class TestEntrypointAutoDescend: + """Test auto-descend: --baseline-path / --target-path pointing to a parent + directory that contains a single subdirectory with .pt files.""" + + def test_auto_descend_single_engine(self, tmp_path: Path, capsys) -> None: + """Parent dir wrapping a single engine subdir is auto-descended and comparison succeeds.""" + baseline_exp, target_exp = _create_dumps(tmp_path, ["tensor_a"]) + + baseline_wrapper: Path = tmp_path / "baseline_wrap" + target_wrapper: Path = tmp_path / "target_wrap" + baseline_wrapper.mkdir() + target_wrapper.mkdir() + baseline_exp.rename(baseline_wrapper / "engine_0") + target_exp.rename(target_wrapper / "engine_0") + + argv = _make_argv(baseline_wrapper, target_wrapper, preset="raw") + records, exit_code = _run_and_parse(argv, capsys) + + assert exit_code == 0 + _assert_single_comparison_passed(records) + + def test_no_descend_when_pt_at_root(self, tmp_path: Path, capsys) -> None: + """Direct .pt files — no descend needed, comparison still works.""" + baseline_exp, target_exp = _create_dumps(tmp_path, ["tensor_a"]) + + argv = _make_argv(baseline_exp, target_exp, preset="raw") + records, exit_code = _run_and_parse(argv, capsys) + + assert exit_code == 0 + _assert_single_comparison_passed(records) + + def test_auto_descend_emits_log_record(self, tmp_path: Path, capsys) -> None: + """Auto-descend emits a LogRecord with the info message.""" + baseline_exp, target_exp = _create_dumps(tmp_path, ["tensor_a"]) + + wrapper: Path = tmp_path / "target_wrap" + wrapper.mkdir() + target_exp.rename(wrapper / "engine_0") + + argv = _make_argv(baseline_exp, wrapper, preset="raw") + records, _ = _run_and_parse(argv, capsys) + + log_records: list[LogRecord] = [r for r in records if isinstance(r, LogRecord)] + auto_descend_msgs: list[str] = [ + info.message + for lr in log_records + for info in lr.infos + if "auto-descend" in info.message + ] + assert any("target_path" in m for m in auto_descend_msgs) + + def test_auto_descend_single_nonempty_among_empty( + self, tmp_path: Path, capsys + ) -> None: + """Two subdirs but only one has .pt — auto-descend picks the non-empty one.""" + baseline_exp, target_exp = _create_dumps(tmp_path, ["tensor_a"]) + + wrapper: Path = tmp_path / "target_wrap" + wrapper.mkdir() + target_exp.rename(wrapper / "engine_0") + (wrapper / "empty_subdir").mkdir() + + argv = _make_argv(baseline_exp, wrapper, preset="raw") + records, exit_code = _run_and_parse(argv, capsys) + + assert exit_code == 0 + _assert_single_comparison_passed(records) + + def test_error_multiple_nonempty_subdirs(self, tmp_path: Path) -> None: + """Two subdirs both with .pt — raises ValueError with clear message.""" + baseline_exp, target_exp = _create_dumps(tmp_path, ["tensor_a"]) + + wrapper: Path = tmp_path / "target_wrap" + wrapper.mkdir() + target_exp.rename(wrapper / "engine_0") + engine_1: Path = wrapper / "engine_1" + engine_1.mkdir() + torch.save(torch.tensor([1.0]), engine_1 / "dummy.pt") + + argv: list[str] = _make_argv(baseline_exp, wrapper, preset="raw") + with pytest.raises(ValueError, match="multiple subdirectories contain data"): + run(parse_args(argv)) + + def test_error_no_data_found(self, tmp_path: Path) -> None: + """No .pt files anywhere — raises ValueError.""" + baseline_exp, _ = _create_dumps(tmp_path, ["tensor_a"]) + + empty_dir: Path = tmp_path / "empty_target" + empty_dir.mkdir() + (empty_dir / "subdir").mkdir() + + argv: list[str] = _make_argv(baseline_exp, empty_dir, preset="raw") + with pytest.raises(ValueError, match="no .pt files found"): + run(parse_args(argv)) + + +class TestPartialParallelInfo: + """Regression tests for _is_jointly_determined with incomplete parallel_info. + + When some ranks lack a parallel axis that other ranks have, the unsharder + planner must detect the inconsistency and report the axis as undeclared + rather than silently accepting it as jointly determined. + """ + + def test_missing_parent_axis_triggers_undeclared_error( + self, tmp_path: Path, capsys: pytest.CaptureFixture + ) -> None: + """Ranks with inconsistent parallel_info → undeclared axis error. + + # Step 1: Create 4 target ranks where moe_tp is absent from ranks 2-3. + # This makes moe_tp implicitly-sharded (dependent on tp for ranks 0-1), + # but edp is NOT dependent on tp alone (tp=0 maps to edp=0 AND edp=2). + # Step 2: _is_jointly_determined is called with parent_axes={tp, moe_tp} + # for child=edp. Ranks 2-3 lack moe_tp → returns False. + # Step 3: edp remains undeclared → ValueError emitted as error record. + """ + torch.manual_seed(42) + full_tensor = torch.randn(2, 8) + shard0 = full_tensor[:, :4] + shard1 = full_tensor[:, 4:] + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_rank_dump( + baseline_dir, + rank=0, + name="hidden", + tensor=full_tensor, + dims="b h", + ) + + # Ranks 0-1: have tp + moe_tp + edp + _create_rank_dump( + target_dir, + rank=0, + name="hidden", + tensor=shard0, + dims="b h[tp]", + parallel_info={ + "tp_rank": 0, + "tp_size": 2, + "moe_tp_rank": 0, + "moe_tp_size": 2, + "edp_rank": 0, + "edp_size": 4, + }, + ) + _create_rank_dump( + target_dir, + rank=1, + name="hidden", + tensor=shard1, + dims="b h[tp]", + parallel_info={ + "tp_rank": 1, + "tp_size": 2, + "moe_tp_rank": 1, + "moe_tp_size": 2, + "edp_rank": 1, + "edp_size": 4, + }, + ) + + # Ranks 2-3: have tp + edp but NO moe_tp + _create_rank_dump( + target_dir, + rank=2, + name="hidden", + tensor=shard0, + dims="b h[tp]", + parallel_info={ + "tp_rank": 0, + "tp_size": 2, + "edp_rank": 2, + "edp_size": 4, + }, + ) + _create_rank_dump( + target_dir, + rank=3, + name="hidden", + tensor=shard1, + dims="b h[tp]", + parallel_info={ + "tp_rank": 1, + "tp_size": 2, + "edp_rank": 3, + "edp_size": 4, + }, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, exit_code = _run_and_parse(argv, capsys) + + assert exit_code == 1 + + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) >= 1 + assert any("not declared" in e.traceback_str for e in errors) + + def test_consistent_parallel_info_allows_joint_determination( + self, tmp_path: Path, capsys: pytest.CaptureFixture + ) -> None: + """All ranks have complete parallel_info → edp is jointly determined, comparison succeeds. + + # Step 1: 4 target ranks with TP=2, CP=2 (replicated), EDP=4. + # edp is NOT dependent on tp alone (tp=0→edp=0,2) or cp alone (cp=0→edp=0,1). + # Step 2: _is_jointly_determined is called with parent_axes={tp, cp}, child=edp. + # All infos have both tp and cp → joint mapping is consistent → True. + # Step 3: CP replicated picks one rank per tp group → TP concat → correct shape. + """ + torch.manual_seed(42) + full_tensor = torch.randn(2, 8) + shard0 = full_tensor[:, :4] + shard1 = full_tensor[:, 4:] + + baseline_dir = tmp_path / "baseline" + target_dir = tmp_path / "target" + + _create_rank_dump( + baseline_dir, + rank=0, + name="hidden", + tensor=full_tensor, + dims="b h", + ) + + # CP=replicated → ranks with different cp_rank have same tensor shard + for rank, tp, cp, edp, shard in [ + (0, 0, 0, 0, shard0), + (1, 1, 0, 1, shard1), + (2, 0, 1, 2, shard0), + (3, 1, 1, 3, shard1), + ]: + _create_rank_dump( + target_dir, + rank=rank, + name="hidden", + tensor=shard, + dims="b h[tp] # cp:replicated", + parallel_info={ + "tp_rank": tp, + "tp_size": 2, + "cp_rank": cp, + "cp_size": 2, + "edp_rank": edp, + "edp_size": 4, + }, + ) + + argv = _make_argv( + baseline_dir / _FIXED_EXP_NAME, + target_dir / _FIXED_EXP_NAME, + diff_threshold=0.01, + ) + + records, exit_code = _run_and_parse(argv, capsys) + + assert exit_code == 0 + comp = _assert_single_comparison_passed(records) + assert comp.name == "hidden" + + +class TestErrorResilience: + """Bundle comparison exception → continue with remaining bundles.""" + + def test_one_bundle_errors_others_continue(self, tmp_path, capsys, monkeypatch): + """One bundle raises exception → other bundles still compared, summary correct.""" + baseline_path, target_path = _create_dumps( + tmp_path, ["tensor_a", "tensor_b", "tensor_c"] + ) + argv = _make_argv(baseline_path, target_path, preset="raw") + + original = _entrypoint_module.compare_bundle_pair + + def _patched(**kwargs): + if kwargs["name"] == "tensor_b": + raise RuntimeError("intentional test error") + return original(**kwargs) + + monkeypatch.setattr(_entrypoint_module, "compare_bundle_pair", _patched) + + records, exit_code = _run_and_parse(argv, capsys) + + comparisons = _get_comparisons(records) + assert len(comparisons) == 2 + + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) == 1 + assert errors[0].name == "tensor_b" + assert errors[0].exception_type == "RuntimeError" + assert "intentional test error" in errors[0].exception_message + assert "--override-dims" in errors[0].traceback_str + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.errored == 1 + assert summary.passed == 2 + assert summary.total == 3 + + assert exit_code == 1 + + def test_all_bundles_error_exits_one(self, tmp_path, capsys, monkeypatch): + """All bundles error → exit 1, summary all errored.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + argv = _make_argv(baseline_path, target_path, preset="raw") + + def _always_raise(**kwargs): + raise ValueError("always fail") + + monkeypatch.setattr(_entrypoint_module, "compare_bundle_pair", _always_raise) + + records, exit_code = _run_and_parse(argv, capsys) + + summary = records[-1] + assert isinstance(summary, SummaryRecord) + assert summary.errored == 1 + assert summary.passed == 0 + assert exit_code == 1 + + def test_error_record_json_roundtrip_in_output(self, tmp_path, capsys, monkeypatch): + """ComparisonErrorRecord correctly serializes and deserializes in output.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + argv = _make_argv(baseline_path, target_path, preset="raw") + + def _raise(**kwargs): + raise TypeError("bad type") + + monkeypatch.setattr(_entrypoint_module, "compare_bundle_pair", _raise) + + records, _ = _run_and_parse(argv, capsys) + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) == 1 + assert errors[0].exception_type == "TypeError" + + def test_error_record_contains_dims_hint(self, tmp_path, capsys, monkeypatch): + """Error record includes --override-dims hint with all variant flags.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + argv = _make_argv(baseline_path, target_path, preset="raw") + + def _raise(**kwargs): + raise ValueError("Invalid dim token: 'zzz'") + + monkeypatch.setattr(_entrypoint_module, "compare_bundle_pair", _raise) + + records, _ = _run_and_parse(argv, capsys) + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) == 1 + + assert "Invalid dim token: 'zzz'" in errors[0].exception_message + tb = errors[0].traceback_str + assert "--override-dims" in tb + assert "--override-baseline-dims" in tb + assert "--override-target-dims" in tb + assert "--override-config" in tb + assert "do NOT re-run expensive dumps" in tb + + def test_error_record_hint_appears_before_traceback( + self, tmp_path, capsys, monkeypatch + ): + """Hint appears before the full stack trace in traceback_str.""" + baseline_path, target_path = _create_dumps(tmp_path, ["tensor_a"]) + argv = _make_argv(baseline_path, target_path, preset="raw") + + def _raise(**kwargs): + raise RuntimeError("some dims problem") + + monkeypatch.setattr(_entrypoint_module, "compare_bundle_pair", _raise) + + records, _ = _run_and_parse(argv, capsys) + errors = [r for r in records if isinstance(r, ComparisonErrorRecord)] + assert len(errors) == 1 + + tb = errors[0].traceback_str + hint_pos = tb.index("--override-dims") + traceback_pos = tb.index("Traceback (most recent call last)") + assert hint_pos < traceback_pos + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_log_sink.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_log_sink.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf203272f8a58eab265433be84bc2061262012c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_log_sink.py @@ -0,0 +1,118 @@ +import json +import sys + +import pytest + +from sglang.srt.debug_utils.comparator.log_sink import LogSink +from sglang.srt.debug_utils.comparator.output_types import ( + ErrorLog, + InfoLog, +) +from sglang.srt.debug_utils.comparator.report_sink import report_sink +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +def _make_error_log(**overrides) -> ErrorLog: + defaults: dict = dict( + category="test", + message="test warning", + ) + defaults.update(overrides) + return ErrorLog(**defaults) + + +class TestLogSink: + def test_basic_collection(self) -> None: + sink = LogSink() + log = _make_error_log() + + with sink.context() as collected: + sink.add(log) + + assert len(collected) == 1 + assert collected[0] is log + + def test_nested_contexts(self) -> None: + sink = LogSink() + outer_log = _make_error_log(message="outer") + inner_log = _make_error_log(message="inner") + + with sink.context() as outer: + sink.add(outer_log) + with sink.context() as inner: + sink.add(inner_log) + assert len(inner) == 1 + assert inner[0] is inner_log + + assert len(outer) == 1 + assert outer[0] is outer_log + + def test_empty_context(self) -> None: + sink = LogSink() + with sink.context() as collected: + pass + assert collected == [] + + def test_add_outside_context_prints(self, capsys) -> None: + sink = LogSink() + report_sink.configure(output_format="text") + + sink.add(_make_error_log()) + + captured = capsys.readouterr() + assert "test warning" in captured.out + + def test_context_captures_instead_of_printing(self, capsys) -> None: + sink = LogSink() + report_sink.configure(output_format="text") + + with sink.context() as collected: + sink.add(_make_error_log()) + + assert len(collected) == 1 + captured = capsys.readouterr() + assert captured.out == "" + + def test_json_output_outside_context(self, capsys) -> None: + sink = LogSink() + report_sink.configure(output_format="json") + + sink.add(_make_error_log()) + + captured = capsys.readouterr() + parsed: dict = json.loads(captured.out.strip()) + assert "errors" in parsed + assert len(parsed["errors"]) == 1 + + def test_info_log_outside_context_routes_to_infos(self, capsys) -> None: + """InfoLog added outside context populates LogRecord.infos, not errors.""" + sink = LogSink() + report_sink.configure(output_format="json") + + sink.add(InfoLog(category="test", message="info msg")) + + parsed: dict = json.loads(capsys.readouterr().out.strip()) + assert len(parsed["infos"]) == 1 + assert len(parsed["errors"]) == 0 + + def test_exception_in_context_cleans_stack(self, capsys) -> None: + sink = LogSink() + report_sink.configure(output_format="text") + + with pytest.raises(RuntimeError): + with sink.context() as collected: + sink.add(_make_error_log()) + raise RuntimeError("boom") + + assert len(collected) == 1 + + sink.add(_make_error_log(message="after exception")) + captured = capsys.readouterr() + assert "after exception" in captured.out + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_manually_verify.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_manually_verify.py new file mode 100644 index 0000000000000000000000000000000000000000..7d9c144381e2a2f9be25c464b7c0e576c556f49a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_manually_verify.py @@ -0,0 +1,295 @@ +"""Visual comparison figure tests — CI sanity check + human verification. + +This file serves two purposes: +1. CI sanity check: ensures generate_comparison_figure() runs without errors + across various tensor scenarios (registered via register_cpu_ci). +2. Human verification: all generated PNGs are copied to /tmp/comparator_manual_verify/ + so they can be pulled back to a local machine for visual inspection. + +Run: + python -m pytest test/registered/debug_utils/comparator/test_manually_verify.py -x -v + +Human verification: + After running, images are at /tmp/comparator_manual_verify/. + Each test's docstring describes the expected visual appearance. +""" + +import shutil +import sys +from pathlib import Path + +import pytest +import torch + +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=60, suite="base-a-test-cpu", nightly=True) + +_PUBLISH_DIR: Path = Path("/tmp/comparator_manual_verify") +_PNG_MAGIC: bytes = b"\x89PNG" + + +@pytest.fixture(scope="session") +def publish_dir() -> Path: + """Fixed output dir for human inspection — files are copied here after generation.""" + if _PUBLISH_DIR.exists(): + shutil.rmtree(_PUBLISH_DIR) + _PUBLISH_DIR.mkdir(parents=True) + return _PUBLISH_DIR + + +def _assert_valid_png(path: Path) -> None: + assert path.exists(), f"PNG not created: {path}" + assert path.stat().st_size > 0, f"PNG is empty: {path}" + with open(path, "rb") as f: + magic: bytes = f.read(4) + assert magic == _PNG_MAGIC, f"Not a valid PNG: {path}" + + +def _generate_and_publish( + *, + baseline: torch.Tensor, + target: torch.Tensor, + name: str, + tmp_path: Path, + publish_dir: Path, +) -> Path: + from sglang.srt.debug_utils.comparator.visualizer import ( + generate_comparison_figure, + ) + + output_path: Path = tmp_path / f"{name}.png" + generate_comparison_figure( + baseline=baseline, + target=target, + name=name, + output_path=output_path, + ) + + _assert_valid_png(output_path) + shutil.copy2(src=output_path, dst=publish_dir / output_path.name) + return output_path + + +@pytest.fixture(autouse=True) +def _skip_if_no_matplotlib() -> None: + pytest.importorskip("matplotlib") + + +class TestBundleDetailsManualVerify: + def test_normal_small_diff(self, tmp_path: Path, publish_dir: Path) -> None: + """Two nearly-identical tensors (randn + 0.01 noise). + + Expected: All 6 panel rows visible. Diff heatmap nearly uniform light color. + Hist2d tightly clustered along the red diagonal line. + """ + baseline: torch.Tensor = torch.randn(32, 64) + target: torch.Tensor = baseline + torch.randn(32, 64) * 0.01 + + _generate_and_publish( + baseline=baseline, + target=target, + name="normal_small_diff", + tmp_path=tmp_path, + publish_dir=publish_dir, + ) + + def test_significant_diff(self, tmp_path: Path, publish_dir: Path) -> None: + """Two tensors with larger differences (randn + 0.5 noise). + + Expected: All 6 panel rows visible. Diff heatmap shows noticeable structure. + Hist2d scatter is broader, spread away from the diagonal. + """ + baseline: torch.Tensor = torch.randn(32, 64) + target: torch.Tensor = baseline + torch.randn(32, 64) * 0.5 + + _generate_and_publish( + baseline=baseline, + target=target, + name="significant_diff", + tmp_path=tmp_path, + publish_dir=publish_dir, + ) + + def test_shape_mismatch(self, tmp_path: Path, publish_dir: Path) -> None: + """Baseline 32x64, target 16x32 — shapes do not match. + + Expected: Only 2 panel rows (baseline heatmap, target heatmap). + No diff/histogram/hist2d/sampled panels since diff cannot be computed. + """ + baseline: torch.Tensor = torch.randn(32, 64) + target: torch.Tensor = torch.randn(16, 32) + + _generate_and_publish( + baseline=baseline, + target=target, + name="shape_mismatch", + tmp_path=tmp_path, + publish_dir=publish_dir, + ) + + def test_large_tensor(self, tmp_path: Path, publish_dir: Path) -> None: + """4000x4000 tensor — triggers internal downsampling. + + Expected: Figure renders normally without OOM. Downsampled panels + should still look reasonable. + """ + baseline: torch.Tensor = torch.randn(4000, 4000) + target: torch.Tensor = baseline + torch.randn(4000, 4000) * 0.001 + + _generate_and_publish( + baseline=baseline, + target=target, + name="large_tensor", + tmp_path=tmp_path, + publish_dir=publish_dir, + ) + + def test_1d_tensor(self, tmp_path: Path, publish_dir: Path) -> None: + """1D tensor (256,) — internally reshaped to 2D before plotting. + + Expected: All 6 panel rows visible. The heatmap shape reflects the + reshaped 2D form, not the original 1D. + """ + baseline: torch.Tensor = torch.randn(256) + target: torch.Tensor = baseline + 0.01 + + _generate_and_publish( + baseline=baseline, + target=target, + name="1d_tensor", + tmp_path=tmp_path, + publish_dir=publish_dir, + ) + + def test_constant_tensor(self, tmp_path: Path, publish_dir: Path) -> None: + """All-zero baseline, tiny-valued target. + + Expected: Colorbar range is extremely small. Histogram concentrates in + a single bin. No rendering errors from near-zero variance. + """ + baseline: torch.Tensor = torch.zeros(32, 64) + target: torch.Tensor = torch.ones(32, 64) * 1e-8 + + _generate_and_publish( + baseline=baseline, + target=target, + name="constant_tensor", + tmp_path=tmp_path, + publish_dir=publish_dir, + ) + + def test_extreme_values(self, tmp_path: Path, publish_dir: Path) -> None: + """Tensor containing values spanning 1e-10 to 1e10. + + Expected: Log10 panels handle the wide range gracefully. No inf/nan + artifacts in the rendered figure. + """ + baseline: torch.Tensor = torch.randn(32, 64).abs() + baseline[0, 0] = 1e-10 + baseline[0, 1] = 1e10 + target: torch.Tensor = baseline + torch.randn(32, 64) * 0.01 + + _generate_and_publish( + baseline=baseline, + target=target, + name="extreme_values", + tmp_path=tmp_path, + publish_dir=publish_dir, + ) + + +class TestPerTokenHeatmapManualVerify: + def test_increasing_diff(self, tmp_path: Path, publish_dir: Path) -> None: + """Per-token heatmap with linearly increasing diff across token positions. + + Expected: Heatmap shows a clear left-to-right gradient — dark/cold on + the left (small diff), bright/hot on the right (large diff). Multiple + rows for different tensor names. Colorbar shows log10 scale. + """ + from sglang.srt.debug_utils.comparator.output_types import ( + ComparisonTensorRecord, + ) + from sglang.srt.debug_utils.comparator.per_token_visualizer import ( + generate_per_token_heatmap, + ) + from sglang.srt.debug_utils.comparator.tensor_comparator.comparator import ( + compare_tensor_pair, + ) + + torch.manual_seed(42) + seq_len: int = 64 + hidden_dim: int = 128 + num_tensors: int = 5 + + records: list[ComparisonTensorRecord] = [] + for i in range(num_tensors): + baseline: torch.Tensor = torch.randn(seq_len, hidden_dim) + noise_scale: torch.Tensor = torch.linspace( + 1e-6, 0.5, steps=seq_len + ).unsqueeze(1) + target: torch.Tensor = baseline + torch.randn_like(baseline) * noise_scale + + info = compare_tensor_pair( + x_baseline=baseline, + x_target=target, + name=f"layer_{i}_hidden_states", + diff_threshold=1e-3, + seq_dim=0, + ) + records.append(ComparisonTensorRecord(**info.model_dump())) + + output_path: Path = tmp_path / "per_token_increasing_diff.png" + result = generate_per_token_heatmap(records=records, output_path=output_path) + + assert result is not None + _assert_valid_png(output_path) + shutil.copy2(src=output_path, dst=publish_dir / output_path.name) + + def test_single_spike(self, tmp_path: Path, publish_dir: Path) -> None: + """Per-token heatmap where only one token position has large diff. + + Expected: Heatmap shows one bright vertical stripe at the spike position, + rest is dark/cold. + """ + from sglang.srt.debug_utils.comparator.output_types import ( + ComparisonTensorRecord, + ) + from sglang.srt.debug_utils.comparator.per_token_visualizer import ( + generate_per_token_heatmap, + ) + from sglang.srt.debug_utils.comparator.tensor_comparator.comparator import ( + compare_tensor_pair, + ) + + torch.manual_seed(42) + seq_len: int = 64 + hidden_dim: int = 128 + spike_pos: int = 32 + num_tensors: int = 4 + + records: list[ComparisonTensorRecord] = [] + for i in range(num_tensors): + baseline: torch.Tensor = torch.randn(seq_len, hidden_dim) + target: torch.Tensor = baseline.clone() + target[spike_pos, :] += torch.randn(hidden_dim) * 5.0 + + info = compare_tensor_pair( + x_baseline=baseline, + x_target=target, + name=f"layer_{i}_attn_output", + diff_threshold=1e-3, + seq_dim=0, + ) + records.append(ComparisonTensorRecord(**info.model_dump())) + + output_path: Path = tmp_path / "per_token_single_spike.png" + result = generate_per_token_heatmap(records=records, output_path=output_path) + + assert result is not None + _assert_valid_png(output_path) + shutil.copy2(src=output_path, dst=publish_dir / output_path.name) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_meta_overrider.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_meta_overrider.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f119576b0f3c648664cce15f4f284c0a1a0b2d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_meta_overrider.py @@ -0,0 +1,298 @@ +"""Tests for meta_overrider — unit tests.""" + +from __future__ import annotations + +import sys +import textwrap +from pathlib import Path + +import pytest + +from sglang.srt.debug_utils.comparator.meta_overrider import ( + MetaOverrider, + MetaOverrideRule, + _load_yaml_rules, + _parse_cli_override_arg, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +# ───────────────────── Unit: MetaOverrideRule ───────────────────── + + +class TestMetaOverrideRule: + """Pydantic validation for MetaOverrideRule.""" + + def test_shared_dims_both(self) -> None: + """Default side='both' applies dims to both sides.""" + rule = MetaOverrideRule(match="hidden", dims="b s h d") + assert rule.dims == "b s h d" + assert rule.side == "both" + + def test_side_baseline(self) -> None: + """side='baseline' is accepted.""" + rule = MetaOverrideRule(match="logits", dims="b s v[tp]", side="baseline") + assert rule.dims == "b s v[tp]" + assert rule.side == "baseline" + + def test_side_target(self) -> None: + """side='target' is accepted.""" + rule = MetaOverrideRule(match="logits", dims="b s v[ep]", side="target") + assert rule.dims == "b s v[ep]" + assert rule.side == "target" + + def test_invalid_side_rejected(self) -> None: + """Invalid side value is rejected.""" + with pytest.raises(Exception): + MetaOverrideRule(match="x", dims="b s", side="invalid") + + def test_dims_required(self) -> None: + """Must specify dims.""" + with pytest.raises(Exception): + MetaOverrideRule(match="x") + + def test_extra_field_rejected(self) -> None: + """Extra fields are rejected by _StrictBase.""" + with pytest.raises(Exception): + MetaOverrideRule(match="x", dims="b s", bogus="y") + + +# ──────────────────── Unit: _parse_cli_override_arg ──────────────────── + + +class TestParseCLIOverrideArg: + """CLI arg parsing for 'name:dims_string' format.""" + + def test_basic(self) -> None: + """Standard 'name:dims' parsing.""" + name, dims_str = _parse_cli_override_arg("hidden_states:b s h d") + assert name == "hidden_states" + assert dims_str == "b s h d" + + def test_colon_in_dims(self) -> None: + """Extra colons in dims are kept (maxsplit=1).""" + name, dims_str = _parse_cli_override_arg("x:a:b") + assert name == "x" + assert dims_str == "a:b" + + def test_whitespace_trimmed(self) -> None: + """Leading/trailing whitespace around name and dims is stripped.""" + name, dims_str = _parse_cli_override_arg(" foo : b s ") + assert name == "foo" + assert dims_str == "b s" + + def test_missing_colon(self) -> None: + """No colon raises ValueError.""" + with pytest.raises(ValueError, match="Invalid override format"): + _parse_cli_override_arg("no_colon_here") + + def test_empty_name(self) -> None: + """Empty name raises ValueError.""" + with pytest.raises(ValueError, match="Invalid override format"): + _parse_cli_override_arg(":b s h") + + def test_empty_dims(self) -> None: + """Empty dims raises ValueError.""" + with pytest.raises(ValueError, match="Invalid override format"): + _parse_cli_override_arg("foo:") + + +# ──────────────────── Unit: MetaOverrider ──────────────────── + + +class TestMetaOverrider: + """MetaOverrider logic: matching, priority, apply_to_meta.""" + + def test_first_match_wins(self) -> None: + """First matching rule takes effect; later rules ignored.""" + overrider = MetaOverrider( + rules=[ + MetaOverrideRule(match="hidden", dims="FIRST"), + MetaOverrideRule(match="hidden", dims="SECOND"), + ] + ) + result: dict = overrider.apply_to_meta( + name="hidden_states", + meta={"dims": "old"}, + side="baseline", + ) + assert result["dims"] == "FIRST" + + def test_regex_contains_match(self) -> None: + """match is a regex contains search, not exact match.""" + overrider = MetaOverrider( + rules=[MetaOverrideRule(match=r"\.q_proj\.", dims="h d")] + ) + result: dict = overrider.apply_to_meta( + name="layers.0.q_proj.weight", + meta={"dims": "old"}, + side="baseline", + ) + assert result["dims"] == "h d" + + def test_no_match_preserves_original(self) -> None: + """No matching rule leaves meta untouched.""" + overrider = MetaOverrider( + rules=[MetaOverrideRule(match="logits", dims="b s v")] + ) + result: dict = overrider.apply_to_meta( + name="hidden_states", + meta={"dims": "original"}, + side="baseline", + ) + assert result["dims"] == "original" + + @pytest.mark.parametrize( + "rule_side,apply_side,should_match", + [ + ("baseline", "baseline", True), + ("baseline", "target", False), + ("target", "target", True), + ("target", "baseline", False), + ("both", "baseline", True), + ("both", "target", True), + ], + ) + def test_side_filtering( + self, rule_side: str, apply_side: str, should_match: bool + ) -> None: + """Rule only applies when its side matches the apply side.""" + overrider = MetaOverrider( + rules=[MetaOverrideRule(match="logits", dims="NEW", side=rule_side)] + ) + result: dict = overrider.apply_to_meta( + name="logits", + meta={"dims": "old"}, + side=apply_side, + ) + assert result["dims"] == ("NEW" if should_match else "old") + + def test_is_empty(self) -> None: + """Empty overrider reports is_empty=True.""" + assert MetaOverrider(rules=[]).is_empty + assert not MetaOverrider(rules=[MetaOverrideRule(match="x", dims="d")]).is_empty + + def test_meta_without_dims_key(self) -> None: + """Override adds 'dims' even if original meta lacks it.""" + overrider = MetaOverrider(rules=[MetaOverrideRule(match="hidden", dims="NEW")]) + result: dict = overrider.apply_to_meta( + name="hidden", + meta={"other": "val"}, + side="baseline", + ) + assert result["dims"] == "NEW" + + +# ──────────────────── Unit: from_args_and_config ──────────────────── + + +class TestFromArgsAndConfig: + """MetaOverrider.from_args_and_config merges CLI + YAML rules.""" + + def test_cli_before_yaml(self, tmp_path: Path) -> None: + """CLI rules are ordered before YAML rules (CLI wins on conflict).""" + yaml_path = tmp_path / "override.yaml" + yaml_path.write_text(textwrap.dedent("""\ + overrides: + - match: "hidden" + dims: "FROM_YAML" + """)) + + overrider = MetaOverrider.from_args_and_config( + override_dims=["hidden:FROM_CLI"], + override_baseline_dims=[], + override_target_dims=[], + override_config=yaml_path, + ) + + result: dict = overrider.apply_to_meta( + name="hidden", + meta={"dims": "old"}, + side="baseline", + ) + assert result["dims"] == "FROM_CLI" + + def test_no_config_no_cli(self) -> None: + """Empty CLI + no YAML yields empty overrider.""" + overrider = MetaOverrider.from_args_and_config( + override_dims=[], + override_baseline_dims=[], + override_target_dims=[], + override_config=None, + ) + assert overrider.is_empty + + def test_per_side_cli_produces_separate_rules(self) -> None: + """--override-baseline-dims and --override-target-dims produce separate rules with side field.""" + overrider = MetaOverrider.from_args_and_config( + override_dims=[], + override_baseline_dims=["hidden:b s h[tp]"], + override_target_dims=["hidden:b s h[ep]"], + override_config=None, + ) + + baseline: dict = overrider.apply_to_meta( + name="hidden", + meta={"dims": "old"}, + side="baseline", + ) + target: dict = overrider.apply_to_meta( + name="hidden", + meta={"dims": "old"}, + side="target", + ) + assert baseline["dims"] == "b s h[tp]" + assert target["dims"] == "b s h[ep]" + + +# ──────────────────── Unit: _load_yaml_rules ──────────────────── + + +class TestLoadYamlRules: + """YAML loading and validation.""" + + def test_valid_yaml(self, tmp_path: Path) -> None: + """Valid YAML with override rules loads correctly.""" + yaml_path = tmp_path / "override.yaml" + yaml_path.write_text(textwrap.dedent("""\ + overrides: + - match: "hidden" + dims: "b s h d" + - match: "logits" + dims: "b s v[tp]" + side: baseline + """)) + rules = _load_yaml_rules(yaml_path) + assert len(rules) == 2 + assert rules[0].dims == "b s h d" + assert rules[0].side == "both" + assert rules[1].dims == "b s v[tp]" + assert rules[1].side == "baseline" + + def test_empty_yaml(self, tmp_path: Path) -> None: + """Empty YAML file returns no rules.""" + yaml_path = tmp_path / "empty.yaml" + yaml_path.write_text("") + rules = _load_yaml_rules(yaml_path) + assert rules == [] + + def test_unknown_top_key_rejected(self, tmp_path: Path) -> None: + """Unknown top-level key is rejected by OverrideConfig.""" + yaml_path = tmp_path / "bad.yaml" + yaml_path.write_text("unknown_key: 42\n") + with pytest.raises(Exception): + _load_yaml_rules(yaml_path) + + def test_overrides_empty_list(self, tmp_path: Path) -> None: + """Only 'overrides' key with no entries returns empty list.""" + yaml_path = tmp_path / "minimal.yaml" + yaml_path.write_text("overrides: []\n") + rules = _load_yaml_rules(yaml_path) + assert rules == [] + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_model_validation.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_model_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4f11a830d22dd2e7a00f04cb87b8831776249a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_model_validation.py @@ -0,0 +1,471 @@ +import json +import sys + +import pytest +from pydantic import ValidationError + +from sglang.srt.debug_utils.comparator.aligner.entrypoint.traced_types import ( + TracedAlignerPlan, + TracedSidePlan, + TracedStepPlan, + TracedSubPlan, +) +from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import ( + AlignerPerStepPlan, + AlignerPlan, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( + PositionalSeqId, + TokenAlignerPlan, + TokenAlignerSeqInfo, + TokenAlignerStepAux, + TokenLocator, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( + AxisInfo, + ConcatParams, + UnsharderPlan, +) +from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis, TokenLayout +from sglang.srt.debug_utils.comparator.output_types import ( + ComparisonErrorRecord, + ComparisonNonTensorRecord, + ComparisonSkipRecord, + ComparisonTensorRecord, + ErrorLog, + SummaryRecord, + parse_record_json, +) +from sglang.srt.debug_utils.comparator.tensor_comparator.types import ( + DiffInfo, + TensorInfo, + TensorStats, +) +from sglang.srt.debug_utils.comparator.utils import Pair, _check_equal_lengths +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestCheckEqualLengths: + def test_all_equal(self): + _check_equal_lengths(a=[1, 2], b=[3, 4]) + + def test_empty_lists(self): + _check_equal_lengths(a=[], b=[]) + + def test_mismatch_raises(self): + with pytest.raises(ValueError, match="Length mismatch"): + _check_equal_lengths(a=[1, 2], b=[3]) + + +class TestTokenAlignerStepAux: + def test_valid(self): + aux = TokenAlignerStepAux( + input_ids=[10, 20, 30], + positions=[0, 1, 2], + seq_lens=[2, 1], + seq_ids=[ + PositionalSeqId(step=0, seq_index=0), + PositionalSeqId(step=0, seq_index=1), + ], + ) + assert len(aux.input_ids) == 3 + + def test_token_length_mismatch(self): + with pytest.raises(ValueError, match="Length mismatch"): + TokenAlignerStepAux( + input_ids=[10, 20, 30], + positions=[0, 1], + seq_lens=[2, 1], + seq_ids=[ + PositionalSeqId(step=0, seq_index=0), + PositionalSeqId(step=0, seq_index=1), + ], + ) + + def test_seq_length_mismatch(self): + with pytest.raises(ValueError, match="Length mismatch"): + TokenAlignerStepAux( + input_ids=[10, 20, 30], + positions=[0, 1, 2], + seq_lens=[2, 1], + seq_ids=[PositionalSeqId(step=0, seq_index=0)], + ) + + def test_sum_seq_lens_mismatch(self): + with pytest.raises(ValueError, match="sum\\(seq_lens\\)"): + TokenAlignerStepAux( + input_ids=[10, 20, 30], + positions=[0, 1, 2], + seq_lens=[1, 1], + seq_ids=[ + PositionalSeqId(step=0, seq_index=0), + PositionalSeqId(step=0, seq_index=1), + ], + ) + + +class TestTokenAlignerSeqInfo: + def test_valid(self): + info = TokenAlignerSeqInfo( + input_ids=[10, 20, 30], + positions=[0, 1, 2], + locator=TokenLocator(steps=[0, 0, 1], token_index_in_step=[0, 1, 0]), + ) + assert len(info.input_ids) == 3 + + def test_length_mismatch(self): + with pytest.raises(ValidationError): + TokenAlignerSeqInfo( + input_ids=[10, 20, 30], + positions=[0, 1, 2], + locator=TokenLocator(steps=[0, 0], token_index_in_step=[0, 1, 0]), + ) + + def test_positions_not_sequential(self): + with pytest.raises(ValidationError, match="positions must be"): + TokenAlignerSeqInfo( + input_ids=[10, 20, 30], + positions=[0, 2, 1], + locator=TokenLocator(steps=[0, 0, 1], token_index_in_step=[0, 1, 0]), + ) + + +class TestTokenAlignerPlan: + def test_valid(self): + plan = TokenAlignerPlan( + locators=Pair( + x=TokenLocator(steps=[0, 0, 1], token_index_in_step=[0, 1, 0]), + y=TokenLocator(steps=[0, 1, 1], token_index_in_step=[0, 0, 1]), + ), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.T), + ) + assert len(plan.locators.x.steps) == 3 + + def test_length_mismatch(self): + with pytest.raises(ValidationError, match="Length mismatch"): + TokenAlignerPlan( + locators=Pair( + x=TokenLocator(steps=[0, 0], token_index_in_step=[0, 1]), + y=TokenLocator(steps=[0, 1, 1], token_index_in_step=[0, 0, 1]), + ), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.T), + ) + + +class TestSummaryRecord: + def test_valid(self): + record = SummaryRecord(total=10, passed=7, failed=2, skipped=1) + assert record.total == 10 + + def test_total_mismatch(self): + with pytest.raises(ValidationError, match="total=10"): + SummaryRecord(total=10, passed=5, failed=2, skipped=1) + + def test_valid_with_errored(self): + record = SummaryRecord(total=10, passed=6, failed=2, skipped=1, errored=1) + assert record.errored == 1 + + def test_total_mismatch_with_errored(self): + with pytest.raises(ValidationError, match="total=10"): + SummaryRecord(total=10, passed=6, failed=2, skipped=1, errored=0) + + +class TestAxisInfo: + def test_valid(self): + info = AxisInfo(axis_rank=0, axis_size=4) + assert info.axis_rank == 0 + + def test_axis_size_zero(self): + with pytest.raises(ValidationError, match="axis_size must be > 0"): + AxisInfo(axis_rank=0, axis_size=0) + + def test_axis_size_negative(self): + with pytest.raises(ValidationError, match="axis_size must be > 0"): + AxisInfo(axis_rank=0, axis_size=-1) + + def test_axis_rank_negative(self): + with pytest.raises(ValidationError, match="axis_rank must be in"): + AxisInfo(axis_rank=-1, axis_size=4) + + def test_axis_rank_too_large(self): + with pytest.raises(ValidationError, match="axis_rank must be in"): + AxisInfo(axis_rank=4, axis_size=4) + + def test_axis_rank_equals_size_minus_one(self): + info = AxisInfo(axis_rank=3, axis_size=4) + assert info.axis_rank == 3 + + +def _make_tensor_info() -> TensorInfo: + return TensorInfo( + shape=[4, 4], + dtype="float32", + stats=TensorStats(mean=0.0, abs_mean=0.8, std=1.0, min=-2.0, max=2.0), + ) + + +def _make_diff_info(*, passed: bool) -> DiffInfo: + return DiffInfo( + rel_diff=0.001, + max_abs_diff=0.01, + mean_abs_diff=0.005, + max_diff_coord=[0, 0], + baseline_at_max=1.0, + target_at_max=1.01, + diff_threshold=1e-3, + passed=passed, + ) + + +def _make_comparison_record( + *, + diff: DiffInfo | None, + errors: list | None = None, +) -> ComparisonTensorRecord: + ti: TensorInfo = _make_tensor_info() + return ComparisonTensorRecord( + name="t", + baseline=ti, + target=ti, + unified_shape=[4, 4], + shape_mismatch=False, + diff=diff, + errors=errors or [], + ) + + +class TestOutputRecordCategories: + def test_skip_record_with_errors_is_failed(self) -> None: + record = ComparisonSkipRecord( + name="t", + reason="test", + errors=[ErrorLog(category="c", message="m")], + ) + assert record.category == "failed" + + def test_skip_record_no_warnings_is_skipped(self) -> None: + record = ComparisonSkipRecord(name="t", reason="test") + assert record.category == "skipped" + + def test_comparison_record_diff_none_is_failed(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record(diff=None) + assert record.category == "failed" + + def test_comparison_record_passed_with_errors_is_failed(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff_info(passed=True), + errors=[ErrorLog(category="c", message="m")], + ) + assert record.category == "failed" + + def test_comparison_record_passed_no_warnings_is_passed(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff_info(passed=True), + ) + assert record.category == "passed" + + def test_non_tensor_record_equal_is_passed(self) -> None: + record = ComparisonNonTensorRecord( + name="sm_scale", + baseline_value="0.125", + target_value="0.125", + baseline_type="float", + target_type="float", + values_equal=True, + ) + assert record.category == "passed" + + def test_non_tensor_record_different_is_failed(self) -> None: + record = ComparisonNonTensorRecord( + name="sm_scale", + baseline_value="0.125", + target_value="0.25", + baseline_type="float", + target_type="float", + values_equal=False, + ) + assert record.category == "failed" + + def test_non_tensor_record_with_errors_is_failed(self) -> None: + record = ComparisonNonTensorRecord( + name="sm_scale", + baseline_value="0.125", + target_value="0.125", + baseline_type="float", + target_type="float", + values_equal=True, + errors=[ErrorLog(category="c", message="m")], + ) + assert record.category == "failed" + + def test_non_tensor_record_json_roundtrip(self) -> None: + record = ComparisonNonTensorRecord( + name="sm_scale", + baseline_value="0.125", + target_value="0.25", + baseline_type="float", + target_type="float", + values_equal=False, + ) + json_str: str = record.model_dump_json() + roundtripped = parse_record_json(json_str) + assert isinstance(roundtripped, ComparisonNonTensorRecord) + assert roundtripped.name == "sm_scale" + assert roundtripped.values_equal is False + assert roundtripped.baseline_value == "0.125" + assert roundtripped.target_value == "0.25" + + def test_non_tensor_record_text_format_equal(self) -> None: + record = ComparisonNonTensorRecord( + name="sm_scale", + baseline_value="0.125", + target_value="0.125", + baseline_type="float", + target_type="float", + values_equal=True, + ) + text: str = record.to_text() + assert "sm_scale" in text + assert "[equal]" in text + + def test_non_tensor_record_text_format_different(self) -> None: + record = ComparisonNonTensorRecord( + name="sm_scale", + baseline_value="0.125", + target_value="0.25", + baseline_type="float", + target_type="float", + values_equal=False, + ) + text: str = record.to_text() + assert "baseline" in text + assert "target" in text + + def test_error_record_category_is_errored(self) -> None: + record = ComparisonErrorRecord( + name="t", + exception_type="ValueError", + exception_message="bad", + traceback_str="...", + ) + assert record.category == "errored" + + def test_error_record_json_roundtrip(self) -> None: + record = ComparisonErrorRecord( + name="t", + exception_type="ValueError", + exception_message="bad", + traceback_str="traceback...", + ) + json_str: str = record.model_dump_json() + roundtripped = parse_record_json(json_str) + assert isinstance(roundtripped, ComparisonErrorRecord) + assert roundtripped.name == "t" + assert roundtripped.exception_type == "ValueError" + assert roundtripped.exception_message == "bad" + + def test_error_record_text_format(self) -> None: + record = ComparisonErrorRecord( + name="t", + exception_type="RuntimeError", + exception_message="oops", + traceback_str="Traceback...", + ) + text: str = record.to_text() + assert "RuntimeError" in text + assert "oops" in text + assert "Traceback" in text + + +def _make_traced_aligner_plan() -> TracedAlignerPlan: + unsharder = UnsharderPlan( + axis=ParallelAxis.TP, + params=ConcatParams(dim_name="h"), + groups=[[0, 1]], + ) + plan = AlignerPlan( + per_step_plans=Pair( + x=[ + AlignerPerStepPlan( + step=0, input_object_indices=[0, 1], sub_plans=[unsharder] + ) + ], + y=[ + AlignerPerStepPlan( + step=0, input_object_indices=[0, 1], sub_plans=[unsharder] + ) + ], + ), + ) + traced_sub = TracedSubPlan(plan=unsharder, snapshot=None) + traced_step = TracedStepPlan( + step=0, input_object_indices=[0, 1], sub_plans=[traced_sub] + ) + return TracedAlignerPlan( + plan=plan, + per_side=Pair( + x=TracedSidePlan(step_plans=[traced_step]), + y=TracedSidePlan(step_plans=[traced_step]), + ), + ) + + +class TestAlignerPlanInComparisonTensorRecord: + def test_comparison_record_with_traced_plan(self) -> None: + traced_plan: TracedAlignerPlan = _make_traced_aligner_plan() + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff_info(passed=True), + ) + record_with_plan = record.model_copy(update={"traced_plan": traced_plan}) + assert record_with_plan.traced_plan is not None + assert record_with_plan.traced_plan.per_side.x.step_plans[0].step == 0 + + def test_traced_plan_json_roundtrip(self) -> None: + traced_plan: TracedAlignerPlan = _make_traced_aligner_plan() + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff_info(passed=True), + ) + record_with_plan = record.model_copy(update={"traced_plan": traced_plan}) + + json_str: str = record_with_plan.model_dump_json() + parsed = json.loads(json_str) + assert "traced_plan" in parsed + assert ( + parsed["traced_plan"]["per_side"]["x"]["step_plans"][0]["sub_plans"][0][ + "plan" + ]["type"] + == "unsharder" + ) + + roundtripped: ComparisonTensorRecord = parse_record_json(json_str) + assert roundtripped.traced_plan is not None + assert ( + roundtripped.traced_plan.per_side.x.step_plans[0].sub_plans[0].plan.type + == "unsharder" + ) + + def test_comparison_record_without_traced_plan(self) -> None: + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff_info(passed=True), + ) + json_str: str = record.model_dump_json() + roundtripped: ComparisonTensorRecord = parse_record_json(json_str) + assert roundtripped.traced_plan is None + + def test_traced_plan_text_format(self) -> None: + traced_plan: TracedAlignerPlan = _make_traced_aligner_plan() + record: ComparisonTensorRecord = _make_comparison_record( + diff=_make_diff_info(passed=True), + ) + record_with_plan = record.model_copy(update={"traced_plan": traced_plan}) + + text: str = record_with_plan.to_text() + assert "Aligner Plan:" in text + assert "unsharder" in text + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_output_types.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_output_types.py new file mode 100644 index 0000000000000000000000000000000000000000..1932639517a315475ee9bb5e5900522f63adac49 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_output_types.py @@ -0,0 +1,771 @@ +import sys +from io import StringIO + +import pytest +from registered.debug_utils.comparator.testing_helpers import ( + assert_rich_tags_balanced, +) +from registered.debug_utils.comparator.testing_helpers import make_diff as _make_diff +from registered.debug_utils.comparator.testing_helpers import make_stats as _make_stats +from registered.debug_utils.comparator.testing_helpers import ( + make_tensor_info as _make_tensor_info, +) +from rich.console import Console, Group +from rich.panel import Panel + +from sglang.srt.debug_utils.comparator.aligner.axis_aligner import AxisAlignerPlan +from sglang.srt.debug_utils.comparator.aligner.entrypoint.traced_types import ( + TracedAlignerPlan, + TracedSidePlan, + TracedStepPlan, + TracedSubPlan, +) +from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import ( + AlignerPerStepPlan, + AlignerPlan, +) +from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ( + ReordererPlan, + ZigzagToNaturalParams, +) +from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( + TokenAlignerPlan, + TokenLocator, +) +from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( + ConcatParams, + UnsharderPlan, +) +from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis, TokenLayout +from sglang.srt.debug_utils.comparator.output_types import ( + BundleFileInfo, + BundleSideInfo, + ComparisonNonTensorRecord, + ComparisonSkipRecord, + ComparisonTensorRecord, + ConfigRecord, + ErrorLog, + InfoLog, + LogRecord, + RecordLocation, + SummaryRecord, + _format_aligner_plan, + _split_logs, +) +from sglang.srt.debug_utils.comparator.utils import Pair +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) + + +def _render_rich(renderable: object) -> str: + buf: StringIO = StringIO() + Console(file=buf, force_terminal=False, width=120).print(renderable) + return buf.getvalue().rstrip("\n") + + +# --------------------------------------------------------------------------- +# Existing tests (preserved) +# --------------------------------------------------------------------------- + + +def test_split_logs_mixed_list() -> None: + """_split_logs correctly partitions a mixed list of ErrorLog and InfoLog.""" + errors, infos = _split_logs( + [ + ErrorLog(category="a", message="err"), + InfoLog(category="b", message="info"), + ErrorLog(category="c", message="err2"), + ] + ) + assert len(errors) == 2 + assert len(infos) == 1 + assert errors[0].message == "err" + assert errors[1].message == "err2" + assert infos[0].message == "info" + + +def test_log_record_to_text_format() -> None: + """LogRecord.to_text() renders errors with ✗ and infos with ℹ markers.""" + record = LogRecord( + errors=[ErrorLog(category="a", message="bad thing")], + infos=[InfoLog(category="b", message="fyi")], + ) + text: str = record.to_text() + assert "✗ bad thing" in text + assert "ℹ fyi" in text + + +class TestLogRecord: + def test_format_body_returns_empty(self) -> None: + record: LogRecord = LogRecord() + assert record._format_body() == "" + + def test_format_rich_body_returns_empty(self) -> None: + record: LogRecord = LogRecord() + assert record._format_rich_body() == "" + + def test_to_text_empty_no_logs(self) -> None: + record: LogRecord = LogRecord() + assert record.to_text() == "" + + def test_to_text_with_errors_and_infos(self) -> None: + record: LogRecord = LogRecord( + errors=[ErrorLog(category="a", message="bad thing")], + infos=[InfoLog(category="b", message="fyi")], + ) + text: str = record.to_text() + assert text == "\n ✗ bad thing\n ℹ fyi" + + +# --------------------------------------------------------------------------- +# ConfigRecord +# --------------------------------------------------------------------------- + + +class TestConfigRecord: + def test_format_body(self) -> None: + record: ConfigRecord = ConfigRecord(config={"a": 1, "b": "two"}) + assert record._format_body() == "Config: {'a': 1, 'b': 'two'}" + + def test_format_rich_body(self) -> None: + record: ConfigRecord = ConfigRecord(config={"threshold": 0.001, "mode": "fast"}) + body = record._format_rich_body() + + assert isinstance(body, Panel) + rendered: str = _render_rich(body) + assert rendered == ( + "╭───────────────────────────────────────────────── Comparator Config " + "──────────────────────────────────────────────────╮\n" + "│ threshold : 0.001" + " │\n" + "│ mode : fast" + " │\n" + "╰──────────────────────────────────────────────────────────────────────" + "────────────────────────────────────────────────╯" + ) + + def test_to_text_with_errors(self) -> None: + record: ConfigRecord = ConfigRecord( + config={"x": 1}, + errors=[ErrorLog(category="cfg", message="bad config")], + ) + text: str = record.to_text() + assert text.startswith("Config: {'x': 1}") + assert "✗ bad config" in text + + +# --------------------------------------------------------------------------- +# ComparisonSkipRecord +# --------------------------------------------------------------------------- + + +class TestComparisonSkipRecord: + def test_format_body_no_step(self) -> None: + record: ComparisonSkipRecord = ComparisonSkipRecord( + name="layer.weight", + reason="zero-dim tensor", + ) + assert record._format_body() == "Skip: layer.weight (zero-dim tensor)" + + def test_format_body_with_step(self) -> None: + record: ComparisonSkipRecord = ComparisonSkipRecord( + name="layer.weight", + reason="scalar", + location=RecordLocation(step=3), + ) + assert record._format_body() == "Skip: layer.weight (step=3) (scalar)" + + def test_format_rich_body(self) -> None: + record: ComparisonSkipRecord = ComparisonSkipRecord( + name="attn.qkv", + reason="no baseline", + ) + body: str = record._format_rich_body() + assert body == "[dim]⊘ attn.qkv ── skipped (no baseline)[/]" + + def test_category_skipped(self) -> None: + record: ComparisonSkipRecord = ComparisonSkipRecord( + name="x", + reason="r", + ) + assert record.category == "skipped" + + def test_category_failed(self) -> None: + record: ComparisonSkipRecord = ComparisonSkipRecord( + name="x", + reason="r", + errors=[ErrorLog(category="e", message="boom")], + ) + assert record.category == "failed" + + def test_format_body_with_available_side(self) -> None: + record: ComparisonSkipRecord = ComparisonSkipRecord( + name="layer.weight", + reason="baseline_load_failed", + available_side="target", + available_tensor_info=_make_tensor_info( + shape=[4, 8], + dtype="torch.float32", + stats=_make_stats(mean=0.5, std=1.2, min=-2.0, max=3.0), + sample="tensor([0.1, 0.2, ...])", + ), + ) + body: str = record._format_body() + assert "baseline_load_failed" in body + assert "target: shape=[4, 8]" in body + assert "mean=0.5000" in body + assert "sample: tensor([0.1, 0.2, ...])" in body + + def test_format_rich_body_with_available_side(self) -> None: + record: ComparisonSkipRecord = ComparisonSkipRecord( + name="attn.qkv", + reason="baseline_load_failed", + available_side="target", + available_tensor_info=_make_tensor_info( + shape=[4, 8], + dtype="torch.float32", + stats=_make_stats(mean=0.5, std=1.2, min=-2.0, max=3.0), + sample="tensor([0.1, 0.2, ...])", + ), + available_bundle_info=BundleSideInfo( + num_files=2, + files=[ + BundleFileInfo(shape=[4, 8], dtype="torch.float32"), + BundleFileInfo(shape=[4, 8], dtype="torch.float32"), + ], + ), + ) + body: str = record._format_rich_body() + assert "skipped (baseline_load_failed)" in body + assert "target" in body + assert "2 files" in body + assert "mean=0.5000" in body + assert "tensor(" in body + assert_rich_tags_balanced(body) + + def test_format_rich_body_minimal_hides_available_side(self) -> None: + record: ComparisonSkipRecord = ComparisonSkipRecord( + name="x", + reason="target_load_failed", + available_side="baseline", + available_tensor_info=_make_tensor_info(), + ) + body: str = record._format_rich_body(verbosity="minimal") + assert "skipped" in body + assert "stats" not in body + assert_rich_tags_balanced(body) + + +# --------------------------------------------------------------------------- +# ComparisonNonTensorRecord +# --------------------------------------------------------------------------- + + +class TestComparisonNonTensorRecord: + def test_format_body_equal(self) -> None: + record: ComparisonNonTensorRecord = ComparisonNonTensorRecord( + name="config.lr", + baseline_value="0.001", + target_value="0.001", + baseline_type="float", + target_type="float", + values_equal=True, + ) + assert record._format_body() == "NonTensor: config.lr = 0.001 (float) [equal]" + + def test_format_body_not_equal(self) -> None: + record: ComparisonNonTensorRecord = ComparisonNonTensorRecord( + name="config.lr", + baseline_value="0.001", + target_value="0.01", + baseline_type="float", + target_type="float", + values_equal=False, + ) + assert record._format_body() == ( + "NonTensor: config.lr\n" + " baseline = 0.001 (float)\n" + " target = 0.01 (float)" + ) + + def test_format_rich_body_equal(self) -> None: + record: ComparisonNonTensorRecord = ComparisonNonTensorRecord( + name="config.lr", + baseline_value="0.001", + target_value="0.001", + baseline_type="float", + target_type="float", + values_equal=True, + ) + assert record._format_rich_body() == ("═ config.lr = 0.001 (float) [green]✓[/]") + + def test_format_rich_body_not_equal(self) -> None: + record: ComparisonNonTensorRecord = ComparisonNonTensorRecord( + name="config.lr", + baseline_value="0.001", + target_value="0.01", + baseline_type="float", + target_type="float", + values_equal=False, + ) + assert record._format_rich_body() == ( + "═ [bold red]config.lr[/]\n" + " baseline = 0.001 (float)\n" + " target = 0.01 (float)" + ) + + def test_with_step(self) -> None: + record: ComparisonNonTensorRecord = ComparisonNonTensorRecord( + name="bias", + baseline_value="True", + target_value="True", + baseline_type="bool", + target_type="bool", + values_equal=True, + location=RecordLocation(step=5), + ) + assert "(step=5)" in record._format_body() + + def test_category(self) -> None: + passed: ComparisonNonTensorRecord = ComparisonNonTensorRecord( + name="x", + baseline_value="1", + target_value="1", + baseline_type="int", + target_type="int", + values_equal=True, + ) + failed: ComparisonNonTensorRecord = ComparisonNonTensorRecord( + name="x", + baseline_value="1", + target_value="2", + baseline_type="int", + target_type="int", + values_equal=False, + ) + assert passed.category == "passed" + assert failed.category == "failed" + + +# --------------------------------------------------------------------------- +# SummaryRecord +# --------------------------------------------------------------------------- + + +class TestSummaryRecord: + def test_format_body(self) -> None: + record: SummaryRecord = SummaryRecord( + total=10, + passed=7, + failed=2, + skipped=1, + ) + assert record._format_body() == ( + "Summary: 7 passed, 2 failed, 1 skipped (total 10)" + ) + + def test_format_rich_body(self) -> None: + record: SummaryRecord = SummaryRecord( + total=10, + passed=7, + failed=2, + skipped=1, + ) + body = record._format_rich_body() + assert isinstance(body, Panel) + + rendered: str = _render_rich(body) + assert rendered == ( + "╭────────────────────────────────────────────────────── SUMMARY " + "───────────────────────────────────────────────────────╮\n" + "│ 7 passed │ 2 failed │ 1 skipped │ 10 total" + " │\n" + "╰──────────────────────────────────────────────────────────────────────" + "────────────────────────────────────────────────╯" + ) + + def test_validation_error(self) -> None: + with pytest.raises(ValueError, match="total=5 !="): + SummaryRecord(total=5, passed=1, failed=1, skipped=1) + + +# --------------------------------------------------------------------------- +# ComparisonTensorRecord._format_body +# --------------------------------------------------------------------------- + + +class TestComparisonTensorRecordFormatBody: + def test_basic(self) -> None: + record: ComparisonTensorRecord = ComparisonTensorRecord( + name="hidden", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(), + ) + body: str = record._format_body() + + assert body == ( + "Raw [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n" + "After unify [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n" + "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n" + "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n" + "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n" + "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n" + "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n" + "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n" + "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n" + "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n" + "max_abs_diff happens at coord=[2, 3] with baseline=1.0 target=1.0005\n" + "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005" + ) + + def test_with_replicated_checks(self) -> None: + from sglang.srt.debug_utils.comparator.output_types import ReplicatedCheckResult + + record: ComparisonTensorRecord = ComparisonTensorRecord( + name="hidden", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(), + replicated_checks=[ + ReplicatedCheckResult( + axis="tp", + group_index=0, + compared_index=1, + baseline_index=0, + passed=True, + atol=1e-3, + diff=_make_diff( + rel_diff=1e-6, max_abs_diff=1e-5, mean_abs_diff=1e-6 + ), + ), + ], + ) + body: str = record._format_body() + + assert body == ( + "Raw [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n" + "After unify [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n" + "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n" + "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n" + "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n" + "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n" + "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n" + "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n" + "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n" + "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n" + "max_abs_diff happens at coord=[2, 3] with baseline=1.0 target=1.0005\n" + "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005\n" + "Replicated checks:\n" + " ✅ axis=tp group=0 idx=1 vs 0: " + "rel_diff=1.000000e-06 max_abs_diff=1.000000e-05 mean_abs_diff=1.000000e-06" + ) + + def test_with_aligner_plan(self) -> None: + plan: AlignerPlan = AlignerPlan( + per_step_plans=Pair(x=[], y=[]), + ) + traced: TracedAlignerPlan = TracedAlignerPlan( + plan=plan, + per_side=Pair( + x=TracedSidePlan(step_plans=[]), + y=TracedSidePlan(step_plans=[]), + ), + ) + record: ComparisonTensorRecord = ComparisonTensorRecord( + name="hidden", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(), + traced_plan=traced, + ) + body: str = record._format_body() + + assert body == ( + "Raw [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n" + "After unify [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n" + "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n" + "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n" + "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n" + "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n" + "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n" + "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n" + "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n" + "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n" + "max_abs_diff happens at coord=[2, 3] with baseline=1.0 target=1.0005\n" + "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005\n" + "Aligner Plan:\n" + " baseline: (no steps)\n" + " target: (no steps)" + ) + + def test_with_step(self) -> None: + record: ComparisonTensorRecord = ComparisonTensorRecord( + name="hidden", + baseline=_make_tensor_info(), + target=_make_tensor_info(), + unified_shape=[4, 8], + shape_mismatch=False, + diff=_make_diff(), + location=RecordLocation(step=2), + ) + body: str = record._format_body() + + assert body == ( + "[step=2] " + "Raw [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n" + "After unify [shape] [4, 8] vs [4, 8]\t[dtype] torch.float32 vs torch.float32\n" + "[mean] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[abs_mean] 0.8000 vs 0.8000 (diff: 0.0000)\n" + "[std] 1.0000 vs 1.0000 (diff: 0.0000)\n" + "[min] -2.0000 vs -2.0000 (diff: 0.0000)\n" + "[max] 2.0000 vs 2.0000 (diff: 0.0000)\n" + "[p1] -1.8000 vs -1.8000 (diff: 0.0000)\n" + "[p5] -1.5000 vs -1.5000 (diff: 0.0000)\n" + "[p50] 0.0000 vs 0.0000 (diff: 0.0000)\n" + "[p95] 1.5000 vs 1.5000 (diff: 0.0000)\n" + "[p99] 1.8000 vs 1.8000 (diff: 0.0000)\n" + "✅ rel_diff=0.0001\tmax_abs_diff=0.0005\tmean_abs_diff=0.0002\n" + "max_abs_diff happens at coord=[2, 3] with baseline=1.0 target=1.0005\n" + "[abs_diff] p1=0.0001 p5=0.0001 p50=0.0002 p95=0.0004 p99=0.0005" + ) + + +# --------------------------------------------------------------------------- +# _format_aligner_plan +# --------------------------------------------------------------------------- + + +def _wrap_plan(plan: AlignerPlan) -> TracedAlignerPlan: + """Wrap an AlignerPlan into a TracedAlignerPlan with no snapshots.""" + baseline_traced_steps: list[TracedStepPlan] = [ + TracedStepPlan( + step=sp.step, + input_object_indices=sp.input_object_indices, + sub_plans=[TracedSubPlan(plan=sub) for sub in sp.sub_plans], + ) + for sp in plan.per_step_plans.x + ] + target_traced_steps: list[TracedStepPlan] = [ + TracedStepPlan( + step=sp.step, + input_object_indices=sp.input_object_indices, + sub_plans=[TracedSubPlan(plan=sub) for sub in sp.sub_plans], + ) + for sp in plan.per_step_plans.y + ] + return TracedAlignerPlan( + plan=plan, + per_side=Pair( + x=TracedSidePlan(step_plans=baseline_traced_steps), + y=TracedSidePlan(step_plans=target_traced_steps), + ), + ) + + +class TestFormatAlignerPlan: + def test_passthrough(self) -> None: + plan: AlignerPlan = AlignerPlan( + per_step_plans=Pair(x=[], y=[]), + ) + result: str = _format_aligner_plan(_wrap_plan(plan)) + + assert result == ( + "Aligner Plan:\n" " baseline: (no steps)\n" " target: (no steps)" + ) + + def test_unsharder(self) -> None: + unsharder: UnsharderPlan = UnsharderPlan( + axis=ParallelAxis.TP, + params=ConcatParams(dim_name="h"), + groups=[[0, 1]], + ) + plan: AlignerPlan = AlignerPlan( + per_step_plans=Pair( + x=[], + y=[ + AlignerPerStepPlan( + step=0, input_object_indices=[0, 1], sub_plans=[unsharder] + ) + ], + ), + ) + result: str = _format_aligner_plan(_wrap_plan(plan)) + + assert result == ( + "Aligner Plan:\n" + " baseline: (no steps)\n" + " target: [step=0: unsharder(tp)]" + ) + + def test_reorderer(self) -> None: + reorderer: ReordererPlan = ReordererPlan( + params=ZigzagToNaturalParams(dim_name="s", cp_size=2), + ) + plan: AlignerPlan = AlignerPlan( + per_step_plans=Pair( + x=[], + y=[ + AlignerPerStepPlan( + step=0, input_object_indices=[0], sub_plans=[reorderer] + ) + ], + ), + ) + result: str = _format_aligner_plan(_wrap_plan(plan)) + + assert result == ( + "Aligner Plan:\n" + " baseline: (no steps)\n" + " target: [step=0: reorderer(zigzag_to_natural)]" + ) + + def test_multi_step(self) -> None: + unsharder: UnsharderPlan = UnsharderPlan( + axis=ParallelAxis.TP, + params=ConcatParams(dim_name="h"), + groups=[[0, 1]], + ) + reorderer: ReordererPlan = ReordererPlan( + params=ZigzagToNaturalParams(dim_name="s", cp_size=2), + ) + plan: AlignerPlan = AlignerPlan( + per_step_plans=Pair( + x=[], + y=[ + AlignerPerStepPlan( + step=0, input_object_indices=[0, 1], sub_plans=[unsharder] + ), + AlignerPerStepPlan( + step=1, input_object_indices=[0], sub_plans=[reorderer] + ), + ], + ), + ) + result: str = _format_aligner_plan(_wrap_plan(plan)) + + assert result == ( + "Aligner Plan:\n" + " baseline: (no steps)\n" + " target: [step=0: unsharder(tp); step=1: reorderer(zigzag_to_natural)]" + ) + + def test_with_token_aligner(self) -> None: + ta_plan: TokenAlignerPlan = TokenAlignerPlan( + locators=Pair( + x=TokenLocator(steps=[0, 0, 0], token_index_in_step=[0, 1, 2]), + y=TokenLocator(steps=[0, 0, 0], token_index_in_step=[0, 1, 2]), + ), + layouts=Pair(x=TokenLayout.T, y=TokenLayout.T), + ) + plan: AlignerPlan = AlignerPlan( + per_step_plans=Pair(x=[], y=[]), + token_aligner_plan=ta_plan, + ) + result: str = _format_aligner_plan(_wrap_plan(plan)) + + assert result == ( + "Aligner Plan:\n" + " baseline: (no steps)\n" + " target: (no steps)\n" + " token_aligner: 3 tokens aligned" + ) + + def test_with_axis_aligner(self) -> None: + aa_plan: AxisAlignerPlan = AxisAlignerPlan( + pattern=Pair(x="b s d -> s b d", y=None), + ) + plan: AlignerPlan = AlignerPlan( + per_step_plans=Pair(x=[], y=[]), + axis_aligner_plan=aa_plan, + ) + result: str = _format_aligner_plan(_wrap_plan(plan)) + + assert result == ( + "Aligner Plan:\n" + " baseline: (no steps)\n" + " target: (no steps)\n" + " axis_aligner: x: b s d -> s b d" + ) + + +# --------------------------------------------------------------------------- +# _OutputRecord log attachment (to_text / to_rich) +# --------------------------------------------------------------------------- + + +class TestOutputRecordLogAttachment: + def test_to_text_no_logs(self) -> None: + record: ConfigRecord = ConfigRecord(config={"a": 1}) + text: str = record.to_text() + + assert text == "Config: {'a': 1}" + + def test_to_text_errors_only(self) -> None: + record: ConfigRecord = ConfigRecord( + config={"a": 1}, + errors=[ErrorLog(category="x", message="err1")], + ) + text: str = record.to_text() + + assert text == "Config: {'a': 1}\n ✗ err1" + + def test_to_text_infos_only(self) -> None: + record: ConfigRecord = ConfigRecord( + config={"a": 1}, + infos=[InfoLog(category="x", message="note1")], + ) + text: str = record.to_text() + + assert text == "Config: {'a': 1}\n ℹ note1" + + def test_to_text_mixed(self) -> None: + record: ConfigRecord = ConfigRecord( + config={"a": 1}, + errors=[ErrorLog(category="x", message="err1")], + infos=[InfoLog(category="y", message="note1")], + ) + text: str = record.to_text() + + assert text == "Config: {'a': 1}\n ✗ err1\n ℹ note1" + + def test_to_rich_string_body(self) -> None: + record: ComparisonSkipRecord = ComparisonSkipRecord( + name="x", + reason="r", + errors=[ErrorLog(category="e", message="oops")], + ) + body = record.to_rich() + + assert isinstance(body, str) + assert body == "[dim]⊘ x ── skipped (r)[/]\n [red]✗ oops[/]\n" + + def test_to_rich_group_body(self) -> None: + record: ConfigRecord = ConfigRecord( + config={"a": 1}, + errors=[ErrorLog(category="e", message="oops")], + ) + body = record.to_rich() + + # Panel body + log block → Group + assert isinstance(body, Group) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_per_token_visualizer.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_per_token_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..3263cb3aa29fcf011d1a69eda9f59d7389883b77 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_per_token_visualizer.py @@ -0,0 +1,159 @@ +"""Layer 2: PNG generation tests for per-token heatmap visualizer. + +Requires matplotlib — uses pytest.importorskip to gracefully skip if absent. +""" + +import sys +from pathlib import Path + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.output_types import ComparisonTensorRecord +from sglang.srt.debug_utils.comparator.tensor_comparator.comparator import ( + compare_tensor_pair, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=30, suite="base-a-test-cpu", nightly=True) + +_PNG_MAGIC: bytes = b"\x89PNG" + + +@pytest.fixture(autouse=True) +def _skip_if_no_matplotlib() -> None: + pytest.importorskip("matplotlib") + + +def _make_comparison_record( + *, + name: str, + baseline: torch.Tensor, + target: torch.Tensor, + seq_dim: int = 0, +) -> ComparisonTensorRecord: + """Build a ComparisonTensorRecord with per-token data from raw tensors.""" + info = compare_tensor_pair( + x_baseline=baseline, + x_target=target, + name=name, + diff_threshold=1e-3, + seq_dim=seq_dim, + ) + return ComparisonTensorRecord(**info.model_dump()) + + +class TestPerTokenVisualizer: + def test_no_data_returns_none(self, tmp_path: Path) -> None: + """Empty records list → None returned, no file created.""" + from sglang.srt.debug_utils.comparator.per_token_visualizer import ( + generate_per_token_heatmap, + ) + + output_path: Path = tmp_path / "empty.png" + result = generate_per_token_heatmap(records=[], output_path=output_path) + + assert result is None + assert not output_path.exists() + + def test_no_per_token_data_returns_none(self, tmp_path: Path) -> None: + """Records without per_token_rel_diff → None.""" + from sglang.srt.debug_utils.comparator.per_token_visualizer import ( + generate_per_token_heatmap, + ) + + info = compare_tensor_pair( + x_baseline=torch.randn(4, 8), + x_target=torch.randn(4, 8), + name="no_per_token", + diff_threshold=1e-3, + ) + record = ComparisonTensorRecord(**info.model_dump()) + + output_path: Path = tmp_path / "no_data.png" + result = generate_per_token_heatmap(records=[record], output_path=output_path) + + assert result is None + + def test_generates_valid_png(self, tmp_path: Path) -> None: + """Records with per-token data → valid PNG file.""" + from sglang.srt.debug_utils.comparator.per_token_visualizer import ( + generate_per_token_heatmap, + ) + + torch.manual_seed(42) + records: list[ComparisonTensorRecord] = [ + _make_comparison_record( + name=f"tensor_{i}", + baseline=torch.randn(16, 32), + target=torch.randn(16, 32), + ) + for i in range(3) + ] + + output_path: Path = tmp_path / "heatmap.png" + result = generate_per_token_heatmap(records=records, output_path=output_path) + + assert result == output_path + assert output_path.exists() + assert output_path.stat().st_size > 0 + with open(output_path, "rb") as f: + magic: bytes = f.read(4) + assert magic == _PNG_MAGIC + + def test_variable_length_sequences(self, tmp_path: Path) -> None: + """Records with different token lengths → NaN padding, no crash.""" + from sglang.srt.debug_utils.comparator.per_token_visualizer import ( + generate_per_token_heatmap, + ) + + torch.manual_seed(42) + records: list[ComparisonTensorRecord] = [ + _make_comparison_record( + name="short", + baseline=torch.randn(4, 8), + target=torch.randn(4, 8), + ), + _make_comparison_record( + name="medium", + baseline=torch.randn(16, 8), + target=torch.randn(16, 8), + ), + _make_comparison_record( + name="long", + baseline=torch.randn(64, 8), + target=torch.randn(64, 8), + ), + ] + + output_path: Path = tmp_path / "variable.png" + result = generate_per_token_heatmap(records=records, output_path=output_path) + + assert result == output_path + assert output_path.exists() + with open(output_path, "rb") as f: + magic: bytes = f.read(4) + assert magic == _PNG_MAGIC + + def test_creates_parent_dirs(self, tmp_path: Path) -> None: + """Output path with non-existent parent dirs → dirs created automatically.""" + from sglang.srt.debug_utils.comparator.per_token_visualizer import ( + generate_per_token_heatmap, + ) + + torch.manual_seed(42) + record = _make_comparison_record( + name="test", + baseline=torch.randn(8, 16), + target=torch.randn(8, 16), + ) + + output_path: Path = tmp_path / "nested" / "deep" / "heatmap.png" + result = generate_per_token_heatmap(records=[record], output_path=output_path) + + assert result == output_path + assert output_path.exists() + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_preset.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_preset.py new file mode 100644 index 0000000000000000000000000000000000000000..9b183467fe2447d085650b23085a940212d5bf8c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_preset.py @@ -0,0 +1,51 @@ +import pytest + +from sglang.srt.debug_utils.comparator.preset import PRESETS, expand_preset +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestExpandPreset: + """Test preset expansion logic.""" + + def test_explicit_preset(self): + """--preset sglang_megatron expands into its argv.""" + argv = [ + "--baseline-path", + "/a", + "--preset", + "sglang_megatron", + "--diff-threshold", + "0.01", + ] + result = expand_preset(argv, presets=PRESETS) + assert "--preset" not in result + assert "--grouping-skip-keys" in result + assert "concat_steps" in result + assert "--baseline-path" in result + assert "--diff-threshold" in result + + def test_default_preset_applied(self): + """No --preset and no --grouping-skip-keys triggers default preset.""" + argv = ["--baseline-path", "/a"] + result = expand_preset(argv, presets=PRESETS) + assert "--grouping-skip-keys" in result + + def test_explicit_skip_keys_prevents_default(self): + """Explicit --grouping-skip-keys prevents default preset injection.""" + argv = ["--grouping-skip-keys", "rank", "--baseline-path", "/a"] + result = expand_preset(argv, presets=PRESETS) + assert result == argv + + def test_unknown_preset_raises(self): + """Unknown preset name raises ValueError.""" + with pytest.raises(ValueError, match="Unknown value for --preset"): + expand_preset(["--preset", "nonexistent"], presets=PRESETS) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_utils.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..498dc901bc193e378c424b656eb778f647cfa380 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_utils.py @@ -0,0 +1,485 @@ +import sys +from pathlib import Path + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.output_types import SummaryRecord +from sglang.srt.debug_utils.comparator.utils import ( + Pair, + argmax_coord, + auto_descend_dir, + calc_per_token_rel_diff, + calc_rel_diff, + compute_exit_code, + compute_smaller_dtype, + try_unify_shape, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestCalcRelDiff: + def test_identical_tensors(self): + x = torch.randn(10, 10) + assert calc_rel_diff(x, x).item() == pytest.approx(0.0, abs=1e-5) + + def test_orthogonal_tensors(self): + result = calc_rel_diff( + torch.tensor([1.0, 0.0]), torch.tensor([0.0, 1.0]) + ).item() + assert result == pytest.approx(1.0, abs=1e-5) + + def test_similar_tensors(self): + x = torch.tensor([1.0, 2.0, 3.0]) + y = torch.tensor([1.01, 2.01, 3.01]) + result = calc_rel_diff(x, y).item() + assert 0.0 < result < 0.01 + + def test_negated_tensors(self): + x = torch.tensor([1.0, 2.0]) + result = calc_rel_diff(x, -x).item() + assert result == pytest.approx(2.0, abs=1e-5) + + +class TestCalcPerTokenRelDiff: + def test_identical_tensors(self) -> None: + """Identical tensors → per-token diff all zero.""" + x: torch.Tensor = torch.randn(8, 16) + result: torch.Tensor = calc_per_token_rel_diff(x, x, seq_dim=0) + + assert result.shape == (8,) + assert torch.allclose(result, torch.zeros(8), atol=1e-6) + + def test_different_tensors(self) -> None: + """Single token position differs → that position has higher diff.""" + torch.manual_seed(42) + x: torch.Tensor = torch.randn(8, 16) + y: torch.Tensor = x.clone() + y[3, :] += 10.0 + + result: torch.Tensor = calc_per_token_rel_diff(x, y, seq_dim=0) + + assert result.shape == (8,) + assert result[3] > result[0] + assert result[3] > result[7] + for i in [0, 1, 2, 4, 5, 6, 7]: + assert result[i] < 1e-6 + + def test_seq_dim_selection(self) -> None: + """Different seq_dim values produce correct output shapes.""" + x: torch.Tensor = torch.randn(4, 8, 16) + y: torch.Tensor = x + torch.randn_like(x) * 0.01 + + assert calc_per_token_rel_diff(x, y, seq_dim=0).shape == (4,) + assert calc_per_token_rel_diff(x, y, seq_dim=1).shape == (8,) + assert calc_per_token_rel_diff(x, y, seq_dim=2).shape == (16,) + + def test_1d_tensor(self) -> None: + """1D tensor with seq_dim=0 returns per-element diff.""" + x: torch.Tensor = torch.tensor([1.0, 2.0, 3.0]) + y: torch.Tensor = torch.tensor([1.0, 2.0, 4.0]) + + result: torch.Tensor = calc_per_token_rel_diff(x, y, seq_dim=0) + + assert result.shape == (3,) + assert result[0] < 1e-6 + assert result[1] < 1e-6 + assert result[2] > 0.01 + + +class TestArgmaxCoord: + def test_1d_tensor(self): + x = torch.tensor([0.0, 0.0, 5.0, 0.0]) + assert argmax_coord(x) == (2,) + + def test_2d_tensor(self): + x = torch.zeros(3, 4) + x[1, 2] = 10.0 + assert argmax_coord(x) == (1, 2) + + def test_3d_tensor(self): + x = torch.zeros(2, 3, 4) + x[1, 2, 3] = 10.0 + assert argmax_coord(x) == (1, 2, 3) + + +class TestTryUnifyShape: + def test_squeeze_leading_ones(self): + target = torch.Size([3, 4]) + assert try_unify_shape(torch.randn(1, 1, 3, 4), target).shape == target + + def test_no_squeeze_when_leading_dim_not_one(self): + target = torch.Size([3, 4]) + assert try_unify_shape(torch.randn(2, 3, 4), target).shape == (2, 3, 4) + + def test_same_shape_noop(self): + target = torch.Size([3, 4]) + x = torch.randn(3, 4) + result = try_unify_shape(x, target) + assert result.shape == target + assert result.data_ptr() == x.data_ptr() + + def test_trailing_dims_mismatch(self): + target = torch.Size([5, 6]) + x = torch.randn(1, 3, 4) + result = try_unify_shape(x, target) + assert result.shape == (1, 3, 4) + + +class TestComputeSmallerDtype: + def test_float32_bfloat16(self): + assert ( + compute_smaller_dtype(Pair(x=torch.float32, y=torch.bfloat16)) + == torch.bfloat16 + ) + + def test_reverse_order(self): + assert ( + compute_smaller_dtype(Pair(x=torch.bfloat16, y=torch.float32)) + == torch.bfloat16 + ) + + def test_same_dtype_returns_none(self): + assert compute_smaller_dtype(Pair(x=torch.float32, y=torch.float32)) is None + + def test_unknown_pair_returns_none(self): + assert compute_smaller_dtype(Pair(x=torch.int32, y=torch.int64)) is None + + +class TestPairMap: + def test_map_basic(self): + pair = Pair(x=[1, 2, 3], y=[4, 5, 6]) + result = pair.map(lambda lst: sum(lst)) + assert result.x == 6 + assert result.y == 15 + + def test_map_type_change(self): + pair = Pair(x=[1, 2, 3], y=[10, 20]) + result = pair.map(len) + assert result.x == 3 + assert result.y == 2 + + def test_map_returns_new_pair(self): + pair = Pair(x="hello", y="world") + result = pair.map(str.upper) + assert result.x == "HELLO" + assert result.y == "WORLD" + assert result is not pair + + +class TestComputeExitCode: + """Unit tests for compute_exit_code logic.""" + + def test_all_passed(self): + """All passed → exit 0.""" + summary = SummaryRecord(total=3, passed=3, failed=0, skipped=0) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern=None, + failed_names=[], + ) + == 0 + ) + + def test_has_failed_and_passed(self): + """Has failed and passed → exit 1.""" + summary = SummaryRecord(total=4, passed=2, failed=2, skipped=0) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern=None, + failed_names=["a", "b"], + ) + == 1 + ) + + def test_all_failed(self): + """All failed (0 passed) → exit 1.""" + summary = SummaryRecord(total=3, passed=0, failed=3, skipped=0) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern=None, + failed_names=["a", "b", "c"], + ) + == 1 + ) + + def test_all_skipped_allow_all(self): + """All skipped + allow_skipped_pattern='.*' → exit 1 (nothing passed).""" + summary = SummaryRecord(total=2, passed=0, failed=0, skipped=2) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=["a", "b"], + allow_failed_pattern=None, + failed_names=[], + ) + == 1 + ) + + def test_all_skipped_forbid_all(self): + """All skipped + allow_skipped_pattern='^$' → exit 1.""" + summary = SummaryRecord(total=2, passed=0, failed=0, skipped=2) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern="^$", + skipped_names=["a", "b"], + allow_failed_pattern=None, + failed_names=[], + ) + == 1 + ) + + def test_passed_and_skipped_allow_all(self): + """Passed + skipped, allow all → exit 0.""" + summary = SummaryRecord(total=3, passed=2, failed=0, skipped=1) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=["a"], + allow_failed_pattern=None, + failed_names=[], + ) + == 0 + ) + + def test_passed_and_skipped_forbid_all(self): + """Passed + skipped + forbid all → exit 1.""" + summary = SummaryRecord(total=3, passed=2, failed=0, skipped=1) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern="^$", + skipped_names=["a"], + allow_failed_pattern=None, + failed_names=[], + ) + == 1 + ) + + def test_skip_pattern_matches_specific_name(self): + """Pattern matching specific name allows that skip, forbids others.""" + summary = SummaryRecord(total=4, passed=2, failed=0, skipped=2) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern="positions|seq_lens", + skipped_names=["positions", "seq_lens"], + allow_failed_pattern=None, + failed_names=[], + ) + == 0 + ) + + def test_skip_pattern_partial_match_forbidden(self): + """Pattern matches some skips but not all → exit 1.""" + summary = SummaryRecord(total=4, passed=1, failed=0, skipped=3) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern="positions|seq_lens", + skipped_names=["positions", "seq_lens", "hidden_states"], + allow_failed_pattern=None, + failed_names=[], + ) + == 1 + ) + + def test_allow_failed_pattern_matches_all(self): + """allow_failed_pattern='.*' tolerates all failures → exit 0.""" + summary = SummaryRecord(total=3, passed=1, failed=2, skipped=0) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern=".*", + failed_names=["a", "b"], + ) + == 0 + ) + + def test_allow_failed_pattern_matches_specific(self): + """Pattern matches all failed names → exit 0.""" + summary = SummaryRecord(total=3, passed=1, failed=2, skipped=0) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern="hidden_states|logits", + failed_names=["hidden_states", "logits"], + ) + == 0 + ) + + def test_allow_failed_pattern_partial_match(self): + """Pattern matches some but not all failures → exit 1.""" + summary = SummaryRecord(total=3, passed=0, failed=3, skipped=0) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern="hidden_states", + failed_names=["hidden_states", "logits", "attn"], + ) + == 1 + ) + + def test_allow_failed_pattern_no_failures(self): + """Pattern set but no failures → exit 0.""" + summary = SummaryRecord(total=2, passed=2, failed=0, skipped=0) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern=".*", + failed_names=[], + ) + == 0 + ) + + def test_both_failed_and_skipped_patterns(self): + """Both patterns set, both satisfied → exit 0.""" + summary = SummaryRecord(total=4, passed=1, failed=1, skipped=2) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern="positions|seq_lens", + skipped_names=["positions", "seq_lens"], + allow_failed_pattern="logits", + failed_names=["logits"], + ) + == 0 + ) + + def test_failed_pattern_satisfied_but_skipped_not(self): + """Failed pattern OK but skipped pattern fails → exit 1.""" + summary = SummaryRecord(total=3, passed=1, failed=1, skipped=1) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern="^$", + skipped_names=["a"], + allow_failed_pattern=".*", + failed_names=["b"], + ) + == 1 + ) + + def test_zero_passed_exits_one(self): + """No tensors passed → exit 1, even when all failures are allowed.""" + summary = SummaryRecord(total=2, passed=0, failed=2, skipped=0) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern=".*", + failed_names=["a", "b"], + ) + == 1 + ) + + def test_zero_passed_all_skipped_exits_one(self): + """All skipped, nothing passed → exit 1.""" + summary = SummaryRecord(total=3, passed=0, failed=0, skipped=3) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=["a", "b", "c"], + allow_failed_pattern=None, + failed_names=[], + ) + == 1 + ) + + def test_errored_with_passed_exits_one(self): + """Has errored bundle even with passed → exit 1.""" + summary = SummaryRecord(total=3, passed=2, failed=0, skipped=0, errored=1) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern=None, + failed_names=[], + errored_names=["broken_tensor"], + ) + == 1 + ) + + def test_errored_only_exits_one(self): + """All errored → exit 1 (passed==0 already exits 1, but errored also independently triggers).""" + summary = SummaryRecord(total=1, passed=0, failed=0, skipped=0, errored=1) + assert ( + compute_exit_code( + summary, + allow_skipped_pattern=".*", + skipped_names=[], + allow_failed_pattern=None, + failed_names=[], + errored_names=["broken_tensor"], + ) + == 1 + ) + + +def _make_pt(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + torch.save(torch.tensor([1.0]), directory / "dummy.pt") + + +class TestAutoDescendDir: + def test_no_descend_when_pt_at_root(self, tmp_path: Path) -> None: + """Directory with .pt files directly is returned as-is.""" + _make_pt(tmp_path) + _make_pt(tmp_path / "child_a") + assert auto_descend_dir(tmp_path, label="test") == tmp_path + + def test_descend_into_single_child(self, tmp_path: Path) -> None: + """Single child with .pt triggers descend.""" + child: Path = tmp_path / "engine_0" + _make_pt(child) + assert auto_descend_dir(tmp_path, label="test") == child + + def test_descend_single_nonempty_child_among_empty(self, tmp_path: Path) -> None: + """Two subdirs but only one has .pt — descend into that one.""" + nonempty: Path = tmp_path / "engine_0" + _make_pt(nonempty) + (tmp_path / "empty_child").mkdir() + assert auto_descend_dir(tmp_path, label="test") == nonempty + + def test_error_with_multiple_nonempty_children(self, tmp_path: Path) -> None: + """Two children with .pt files — ambiguous, raises ValueError.""" + _make_pt(tmp_path / "engine_0") + _make_pt(tmp_path / "engine_1") + with pytest.raises(ValueError, match="multiple subdirectories contain data"): + auto_descend_dir(tmp_path, label="test") + + def test_error_when_no_data_found(self, tmp_path: Path) -> None: + """No .pt files anywhere — raises ValueError.""" + (tmp_path / "empty_child").mkdir() + with pytest.raises(ValueError, match="no .pt files found"): + auto_descend_dir(tmp_path, label="test") + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_visualizer.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..56a3c87bee34f15597c194874ea436da1fa3af6a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/test_visualizer.py @@ -0,0 +1,96 @@ +import sys +from pathlib import Path + +import pytest +import torch + +from sglang.srt.debug_utils.comparator.visualizer.preprocessing import ( + _preprocess_tensor, + _reshape_to_balanced_aspect, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=30, suite="base-a-test-cpu", nightly=True) + + +class TestPreprocessTensor: + def test_1d_becomes_2d(self) -> None: + t: torch.Tensor = torch.randn(100) + result: torch.Tensor = _preprocess_tensor(t) + assert result.ndim == 2 + + def test_3d_becomes_2d(self) -> None: + t: torch.Tensor = torch.randn(2, 3, 4) + result: torch.Tensor = _preprocess_tensor(t) + assert result.ndim == 2 + assert result.numel() == t.numel() + + def test_high_dim_becomes_2d(self) -> None: + t: torch.Tensor = torch.randn(2, 3, 4, 5) + result: torch.Tensor = _preprocess_tensor(t) + assert result.ndim == 2 + assert result.numel() == t.numel() + + def test_scalar_becomes_2d(self) -> None: + t: torch.Tensor = torch.tensor(3.14) + result: torch.Tensor = _preprocess_tensor(t) + assert result.ndim == 2 + assert result.numel() == 1 + + def test_already_2d_preserves_elements(self) -> None: + t: torch.Tensor = torch.randn(10, 20) + result: torch.Tensor = _preprocess_tensor(t) + assert result.ndim == 2 + assert result.numel() == 200 + + +class TestReshapeToBalancedAspect: + def test_extreme_wide_gets_fixed(self) -> None: + t: torch.Tensor = torch.randn(1, 10000) + result: torch.Tensor = _reshape_to_balanced_aspect(t) + h, w = result.shape + ratio: float = max(h, w) / max(min(h, w), 1) + assert ratio <= 5.0 + + def test_extreme_tall_gets_fixed(self) -> None: + t: torch.Tensor = torch.randn(10000, 1) + result: torch.Tensor = _reshape_to_balanced_aspect(t) + h, w = result.shape + ratio: float = max(h, w) / max(min(h, w), 1) + assert ratio <= 5.0 + + def test_already_balanced_unchanged(self) -> None: + t: torch.Tensor = torch.randn(100, 100) + result: torch.Tensor = _reshape_to_balanced_aspect(t) + assert result.shape == (100, 100) + + def test_preserves_numel(self) -> None: + t: torch.Tensor = torch.randn(1, 7919) + result: torch.Tensor = _reshape_to_balanced_aspect(t) + assert result.numel() == t.numel() + + +class TestGenerateComparisonFigure: + @pytest.fixture(autouse=True) + def _skip_if_no_matplotlib(self) -> None: + pytest.importorskip("matplotlib") + + def test_nested_output_dir(self, tmp_path: Path) -> None: + from sglang.srt.debug_utils.comparator.visualizer import ( + generate_comparison_figure, + ) + + output_path: Path = tmp_path / "a" / "b" / "c" / "nested.png" + + generate_comparison_figure( + baseline=torch.randn(10, 10), + target=torch.randn(10, 10), + name="nested", + output_path=output_path, + ) + + assert output_path.exists() + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/testing_helpers.py b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/testing_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..4e282fb97e4e4efe556f43ab1b07b21e15e76d18 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/comparator/testing_helpers.py @@ -0,0 +1,129 @@ +"""Shared test helpers for comparator tests.""" + +from __future__ import annotations + +import re +from io import StringIO +from typing import Optional + +from rich.console import Console + +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci( + est_time=0, + suite="base-a-test-cpu", + nightly=True, + disabled="helper module, no tests", +) + +from sglang.srt.debug_utils.comparator.tensor_comparator.types import ( + DiffInfo, + TensorInfo, + TensorStats, +) + +DEFAULT_PERCENTILES: dict[int, float] = { + 1: -1.8, + 5: -1.5, + 50: 0.0, + 95: 1.5, + 99: 1.8, +} + +DEFAULT_ABS_DIFF_PERCENTILES: dict[int, float] = { + 1: 0.0001, + 5: 0.0001, + 50: 0.0002, + 95: 0.0004, + 99: 0.0005, +} + + +def make_stats( + mean: float = 0.0, + abs_mean: float = 0.8, + std: float = 1.0, + min: float = -2.0, + max: float = 2.0, + percentiles: Optional[dict[int, float]] = None, +) -> TensorStats: + return TensorStats( + mean=mean, + abs_mean=abs_mean, + std=std, + min=min, + max=max, + percentiles=percentiles if percentiles is not None else DEFAULT_PERCENTILES, + ) + + +def make_diff( + rel_diff: float = 0.0001, + max_abs_diff: float = 0.0005, + mean_abs_diff: float = 0.0002, + abs_diff_percentiles: Optional[dict[int, float]] = None, + diff_threshold: float = 1e-3, + passed: bool = True, +) -> DiffInfo: + return DiffInfo( + rel_diff=rel_diff, + max_abs_diff=max_abs_diff, + mean_abs_diff=mean_abs_diff, + abs_diff_percentiles=( + abs_diff_percentiles + if abs_diff_percentiles is not None + else DEFAULT_ABS_DIFF_PERCENTILES + ), + max_diff_coord=[2, 3], + baseline_at_max=1.0, + target_at_max=1.0005, + diff_threshold=diff_threshold, + passed=passed, + ) + + +_ANSI_ESCAPE_RE = re.compile(r"\033\[([0-9;]*)m") + + +def assert_rich_tags_balanced(markup: str) -> None: + """Render Rich markup to ANSI and verify no styles are active at the end. + + Tracks ANSI style state through the output. A ``\\033[0m`` (reset) + clears all active styles; any other ``\\033[Nm`` sets a style. + At the end of the output, no style should remain active. + """ + buf = StringIO() + console = Console(file=buf, force_terminal=True, width=10000, highlight=False) + console.print(markup, end="") + ansi_output: str = buf.getvalue() + + if "\033[" not in ansi_output: + return + + styled = False + for match in _ANSI_ESCAPE_RE.finditer(ansi_output): + params: str = match.group(1) + if params == "0" or params == "": + styled = False + else: + styled = True + + assert not styled, ( + f"ANSI styles still active at end of output — likely unclosed Rich tag.\n" + f"Last 200 chars of ANSI output: {ansi_output[-200:]!r}" + ) + + +def make_tensor_info( + shape: Optional[list[int]] = None, + dtype: str = "torch.float32", + stats: Optional[TensorStats] = None, + sample: Optional[str] = None, +) -> TensorInfo: + return TensorInfo( + shape=shape if shape is not None else [4, 8], + dtype=dtype, + stats=stats if stats is not None else make_stats(), + sample=sample, + ) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/conftest.py b/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..e82883e54b0ceeb6d61fba9446daf10488427e06 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/conftest.py @@ -0,0 +1,66 @@ +"""Shared fixtures for source_patcher tests. + +The sample module is defined as an inline string and written to a temp file +at test time, avoiding CI complaints about fixture files without test registration. +""" + +import importlib.util +import sys +import tempfile +from pathlib import Path +from types import ModuleType + +import pytest + +SAMPLE_MODULE_NAME = "_source_patcher_test_fixtures.sample_module" + +SAMPLE_MODULE_SOURCE = '''\ +GLOBAL_VAR = "global_value" + + +class HelperClass: + """Utility class referenced by SampleClass to test cross-class calls.""" + + @staticmethod + def format_value(value: str) -> str: + return f"[{value}]" + + +class SampleClass: + def greet(self, name: str) -> str: + greeting = f"hello {name}" + return greeting + + def compute(self, x: int) -> int: + result = x * 2 + 1 + return result + + def uses_global(self) -> str: + return f"value={GLOBAL_VAR}" + + def uses_helper(self, value: str) -> str: + return HelperClass.format_value(value) + + +def standalone_function(a: int, b: int) -> int: + return a + b +''' + + +@pytest.fixture(scope="session") +def sample_module() -> ModuleType: + """Load the sample module from a temp file and register it in sys.modules.""" + if SAMPLE_MODULE_NAME in sys.modules: + return sys.modules[SAMPLE_MODULE_NAME] + + tmpdir = tempfile.mkdtemp(prefix="source_patcher_fixtures_") + module_path = Path(tmpdir) / "sample_module.py" + module_path.write_text(SAMPLE_MODULE_SOURCE) + + spec = importlib.util.spec_from_file_location(SAMPLE_MODULE_NAME, module_path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[SAMPLE_MODULE_NAME] = module + spec.loader.exec_module(module) + return module diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/test_code_patcher.py b/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/test_code_patcher.py new file mode 100644 index 0000000000000000000000000000000000000000..284d871736b6ae7bdb96b3e1578769089f228d0a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/test_code_patcher.py @@ -0,0 +1,263 @@ +from types import ModuleType + +import pytest + +from sglang.srt.debug_utils.source_patcher.code_patcher import ( + CodePatcher, + _resolve_target, + patch_function, +) +from sglang.srt.debug_utils.source_patcher.types import EditSpec, PatchSpec +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=7, suite="base-c-test-cpu") + +SAMPLE_MODULE_NAME = "_source_patcher_test_fixtures.sample_module" + + +class TestPatchFunction: + def test_basic_patch_changes_behavior(self, sample_module: ModuleType) -> None: + cls = sample_module.SampleClass + obj = cls() + assert obj.greet("world") == "hello world" + + state = patch_function( + target=cls.greet, + edits=[ + EditSpec( + match='greeting = f"hello {name}"', + replacement='greeting = f"patched {name}"', + ) + ], + ) + try: + assert obj.greet("world") == "patched world" + finally: + state.restore() + + assert obj.greet("world") == "hello world" + + def test_globals_preserved_after_patch(self, sample_module: ModuleType) -> None: + cls = sample_module.SampleClass + obj = cls() + assert obj.uses_global() == "value=global_value" + + state = patch_function( + target=cls.uses_global, + edits=[ + EditSpec( + match='return f"value={GLOBAL_VAR}"', + replacement='return f"patched_value={GLOBAL_VAR}"', + ) + ], + ) + try: + assert obj.uses_global() == "patched_value=global_value" + finally: + state.restore() + + def test_function_identity_preserved(self, sample_module: ModuleType) -> None: + cls = sample_module.SampleClass + fn_id_before = id(cls.greet) + + state = patch_function( + target=cls.greet, + edits=[ + EditSpec( + match='greeting = f"hello {name}"', + replacement='greeting = f"patched {name}"', + ) + ], + ) + try: + assert id(cls.greet) == fn_id_before + finally: + state.restore() + + def test_patch_standalone_function(self, sample_module: ModuleType) -> None: + fn = sample_module.standalone_function + assert fn(2, 3) == 5 + + state = patch_function( + target=fn, + edits=[ + EditSpec( + match="return a + b", + replacement="return a * b", + ) + ], + ) + try: + assert fn(2, 3) == 6 + finally: + state.restore() + + assert fn(2, 3) == 5 + + def test_patched_code_can_reference_global_variable( + self, sample_module: ModuleType + ) -> None: + """Replacement code that references a module-level global should work.""" + cls = sample_module.SampleClass + obj = cls() + + state = patch_function( + target=cls.greet, + edits=[ + EditSpec( + match='greeting = f"hello {name}"', + replacement='greeting = f"{GLOBAL_VAR} {name}"', + ) + ], + ) + try: + assert obj.greet("world") == "global_value world" + finally: + state.restore() + + def test_patched_code_can_call_another_class_method( + self, sample_module: ModuleType + ) -> None: + """Replacement code that calls HelperClass.format_value should work.""" + cls = sample_module.SampleClass + obj = cls() + + state = patch_function( + target=cls.greet, + edits=[ + EditSpec( + match='greeting = f"hello {name}"', + replacement="greeting = HelperClass.format_value(name)", + ) + ], + ) + try: + assert obj.greet("world") == "[world]" + finally: + state.restore() + + def test_patched_code_uses_helper_via_existing_method( + self, sample_module: ModuleType + ) -> None: + """The uses_helper method already calls HelperClass; verify it survives patching.""" + cls = sample_module.SampleClass + obj = cls() + assert obj.uses_helper("test") == "[test]" + + state = patch_function( + target=cls.uses_helper, + edits=[ + EditSpec( + match="return HelperClass.format_value(value)", + replacement='return HelperClass.format_value("patched_" + value)', + ) + ], + ) + try: + assert obj.uses_helper("test") == "[patched_test]" + finally: + state.restore() + + assert obj.uses_helper("test") == "[test]" + + +class TestResolveTarget: + def test_resolve_class_method(self, sample_module: ModuleType) -> None: + target = _resolve_target(f"{SAMPLE_MODULE_NAME}.SampleClass.greet") + assert target is sample_module.SampleClass.greet + + def test_resolve_standalone_function(self, sample_module: ModuleType) -> None: + target = _resolve_target(f"{SAMPLE_MODULE_NAME}.standalone_function") + assert target is sample_module.standalone_function + + def test_resolve_nonexistent_raises(self, sample_module: ModuleType) -> None: + with pytest.raises((ImportError, AttributeError)): + _resolve_target(f"{SAMPLE_MODULE_NAME}.NonexistentClass.method") + + +class TestCodePatcher: + def test_context_manager_patches_and_restores( + self, sample_module: ModuleType + ) -> None: + cls = sample_module.SampleClass + obj = cls() + assert obj.greet("world") == "hello world" + + patches = [ + PatchSpec( + target=f"{SAMPLE_MODULE_NAME}.SampleClass.greet", + edits=[ + EditSpec( + match='greeting = f"hello {name}"', + replacement='greeting = f"ctx_patched {name}"', + ) + ], + ) + ] + + with CodePatcher(patches=patches): + assert obj.greet("world") == "ctx_patched world" + + assert obj.greet("world") == "hello world" + + def test_context_manager_multiple_patches(self, sample_module: ModuleType) -> None: + cls = sample_module.SampleClass + obj = cls() + + patches = [ + PatchSpec( + target=f"{SAMPLE_MODULE_NAME}.SampleClass.greet", + edits=[ + EditSpec( + match='greeting = f"hello {name}"', + replacement='greeting = f"p1 {name}"', + ) + ], + ), + PatchSpec( + target=f"{SAMPLE_MODULE_NAME}.SampleClass.compute", + edits=[ + EditSpec( + match="result = x * 2 + 1", + replacement="result = x * 100", + ) + ], + ), + ] + + with CodePatcher(patches=patches): + assert obj.greet("world") == "p1 world" + assert obj.compute(5) == 500 + + assert obj.greet("world") == "hello world" + assert obj.compute(5) == 11 + + def test_restores_on_exception(self, sample_module: ModuleType) -> None: + cls = sample_module.SampleClass + obj = cls() + + patches = [ + PatchSpec( + target=f"{SAMPLE_MODULE_NAME}.SampleClass.greet", + edits=[ + EditSpec( + match='greeting = f"hello {name}"', + replacement='greeting = f"err_patched {name}"', + ) + ], + ) + ] + + with pytest.raises(RuntimeError): + with CodePatcher(patches=patches): + assert obj.greet("world") == "err_patched world" + raise RuntimeError("test error") + + assert obj.greet("world") == "hello world" + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/test_dumper_integration.py b/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/test_dumper_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..9b1ec42043f934502f7cf666b8e71caa3b76cab6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/test_dumper_integration.py @@ -0,0 +1,66 @@ +"""Test dumper.apply_source_patches() integration with source_patcher.""" + +from pathlib import Path +from types import ModuleType + +import yaml + +from sglang.srt.debug_utils.dumper import DumperConfig, _Dumper +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=8, suite="base-c-test-cpu") + +SAMPLE_MODULE_NAME = "_source_patcher_test_fixtures.sample_module" + + +class TestDumperApplySourcePatches: + def test_no_config_is_noop(self) -> None: + config = DumperConfig(source_patcher_config=None) + d = _Dumper(config=config) + d.apply_source_patches() + + def test_patches_applied_from_yaml( + self, sample_module: ModuleType, tmp_path: Path + ) -> None: + cls = sample_module.SampleClass + obj = cls() + assert obj.greet("world") == "hello world" + + original_code = cls.greet.__code__ + + patch_config = { + "patches": [ + { + "target": f"{SAMPLE_MODULE_NAME}.SampleClass.greet", + "edits": [ + { + "match": 'greeting = f"hello {name}"', + "replacement": 'greeting = f"dumper_patched {name}"', + } + ], + } + ] + } + + config_path = tmp_path / "patch_config.yaml" + config_path.write_text(yaml.dump(patch_config)) + + config = DumperConfig(source_patcher_config=str(config_path)) + d = _Dumper(config=config) + + try: + d.apply_source_patches() + assert obj.greet("world") == "dumper_patched world" + finally: + cls.greet.__code__ = original_code + + assert obj.greet("world") == "hello world" + + +if __name__ == "__main__": + import sys + + import pytest + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/test_source_editor.py b/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/test_source_editor.py new file mode 100644 index 0000000000000000000000000000000000000000..84bb271ad67049bed07b9363dc1e9d2bb7915a3c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/source_patcher/test_source_editor.py @@ -0,0 +1,417 @@ +import pytest +from pydantic import ValidationError + +from sglang.srt.debug_utils.source_patcher.source_editor import apply_edits +from sglang.srt.debug_utils.source_patcher.types import EditSpec, PatchApplicationError +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=7, suite="base-c-test-cpu") + + +class TestApplyEdits: + """Tests for the apply_edits() source text transformation function.""" + + def test_single_line_match_to_multiline_replacement(self) -> None: + source = "def foo():\n" " x = compute()\n" " return x\n" + edits = [ + EditSpec( + match="x = compute()", + replacement="x = compute()\nprint(x)", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ( + "def foo():\n" " x = compute()\n" " print(x)\n" " return x\n" + ) + + def test_pure_insertion(self) -> None: + source = "def foo():\n" " a = 1\n" " b = 2\n" + edits = [ + EditSpec( + match="a = 1", + replacement="a = 1\nprint(a)", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ("def foo():\n" " a = 1\n" " print(a)\n" " b = 2\n") + + def test_pure_deletion_via_empty_replacement(self) -> None: + source = "def foo():\n" " debug_log()\n" " return 42\n" + edits = [ + EditSpec( + match="debug_log()", + replacement="", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ("def foo():\n" " return 42\n") + + def test_deletion_fewer_lines(self) -> None: + source = "def foo():\n" " a = 1\n" " b = 2\n" " c = 3\n" + edits = [ + EditSpec( + match="a = 1\nb = 2", + replacement="ab = 3", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ("def foo():\n" " ab = 3\n" " c = 3\n") + + def test_multiline_match_to_multiline_replacement(self) -> None: + source = ( + "def foo():\n" + " result = self.attn(\n" + " q=q,\n" + " k=k,\n" + " )\n" + " return result\n" + ) + edits = [ + EditSpec( + match="result = self.attn(\n q=q,\n k=k,\n)", + replacement="result = self.attn(\n q=q,\n k=k,\n v=v,\n)", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ( + "def foo():\n" + " result = self.attn(\n" + " q=q,\n" + " k=k,\n" + " v=v,\n" + " )\n" + " return result\n" + ) + + def test_indent_alignment_deep_nesting(self) -> None: + source = ( + "class Foo:\n" + " class Bar:\n" + " def method(self):\n" + " x = compute()\n" + " return x\n" + ) + edits = [ + EditSpec( + match="x = compute()", + replacement="x = compute()\nprint(x)", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ( + "class Foo:\n" + " class Bar:\n" + " def method(self):\n" + " x = compute()\n" + " print(x)\n" + " return x\n" + ) + + def test_match_not_found_raises(self) -> None: + source = "def foo():\n return 1\n" + edits = [EditSpec(match="nonexistent_call()", replacement="replaced()")] + with pytest.raises(PatchApplicationError, match="not found"): + apply_edits(source=source, edits=edits) + + def test_not_found_diagnostic_reports_source_len(self) -> None: + """diagnostic includes total source line count.""" + source = "line0\nline1\nline2\nline3\nline4\n" + edits = [EditSpec(match="absent()", replacement="x")] + with pytest.raises(PatchApplicationError) as exc_info: + apply_edits(source=source, edits=edits) + assert "source_len=5 lines" in str(exc_info.value) + + def test_not_found_diagnostic_when_first_match_line_absent(self) -> None: + """diagnostic says 'does NOT appear anywhere' when first line is never present.""" + source = "def foo():\n return 1\n" + edits = [EditSpec(match="nope_xyz()", replacement="x")] + with pytest.raises(PatchApplicationError) as exc_info: + apply_edits(source=source, edits=edits) + msg = str(exc_info.value) + assert "does NOT appear anywhere in source" in msg + assert "'nope_xyz()'" in msg + + def test_not_found_diagnostic_single_window_with_marker(self) -> None: + """first line is present once but full match doesn't fit: one window with '>' on the match-region line.""" + source = ( + "line0\n" + "line1\n" + "line2\n" + "anchor()\n" + "wrong_next()\n" + "line5\n" + "line6\n" + ) + edits = [EditSpec(match="anchor()\nright_next()", replacement="x")] + with pytest.raises(PatchApplicationError) as exc_info: + apply_edits(source=source, edits=edits) + msg = str(exc_info.value) + assert "appears 1 time(s)" in msg + assert msg.count("--") == 1 + assert "> 3: anchor()" in msg + assert "> 4: wrong_next()" in msg + assert " 1: line1" in msg + assert " 2: line2" in msg + assert " 5: line5" in msg + assert " 6: line6" in msg + + def test_not_found_diagnostic_multiple_windows_separated(self) -> None: + """when first line appears N (<=8) times, N windows are shown separated by '--'.""" + source = ( + "anchor()\n" + "tail_a()\n" + "filler\n" + "anchor()\n" + "tail_b()\n" + "filler\n" + "anchor()\n" + "tail_c()\n" + ) + edits = [EditSpec(match="anchor()\nnope()", replacement="x")] + with pytest.raises(PatchApplicationError) as exc_info: + apply_edits(source=source, edits=edits) + msg = str(exc_info.value) + assert "appears 3 time(s)" in msg + assert msg.count("--") == 3 + assert "> 0: anchor()" in msg + assert "> 3: anchor()" in msg + assert "> 6: anchor()" in msg + + def test_not_found_diagnostic_caps_at_8_windows(self) -> None: + """when first line appears >8 times, only the first 8 windows are rendered.""" + source = "\n".join(["anchor()"] * 12) + "\n" + edits = [EditSpec(match="anchor()\nnope()", replacement="x")] + with pytest.raises(PatchApplicationError) as exc_info: + apply_edits(source=source, edits=edits) + msg = str(exc_info.value) + assert "appears 12 time(s)" in msg + assert "up to 8 windows" in msg + assert msg.count("--") == 8 + + def test_not_found_diagnostic_window_clamps_at_source_boundaries(self) -> None: + """window does not include negative indices or indices past the end of source.""" + source = "anchor()\nfoo\n" + edits = [EditSpec(match="anchor()\nbar", replacement="x")] + with pytest.raises(PatchApplicationError) as exc_info: + apply_edits(source=source, edits=edits) + msg = str(exc_info.value) + assert "> 0: anchor()" in msg + assert "> 1: foo" in msg + assert "-1:" not in msg + assert " 2:" not in msg + + def test_not_found_diagnostic_multiline_match_marks_full_region(self) -> None: + """match spanning N lines: marker '>' covers all N lines of the intended match region.""" + source = ( + "filler0\n" + "filler1\n" + "filler2\n" + "filler3\n" + "anchor()\n" + "middle()\n" + "wrong_tail()\n" + "filler7\n" + "filler8\n" + "filler9\n" + ) + edits = [ + EditSpec(match="anchor()\nmiddle()\nright_tail()", replacement="x"), + ] + with pytest.raises(PatchApplicationError) as exc_info: + apply_edits(source=source, edits=edits) + msg = str(exc_info.value) + assert "> 4: anchor()" in msg + assert "> 5: middle()" in msg + assert "> 6: wrong_tail()" in msg + assert " 2: filler2" in msg + assert " 3: filler3" in msg + assert " 7: filler7" in msg + assert " 8: filler8" in msg + assert "filler0" not in msg + assert "filler1" not in msg + assert "filler9" not in msg + + def test_match_found_multiple_times_raises(self) -> None: + source = "def foo():\n" " print(1)\n" " print(1)\n" + edits = [EditSpec(match="print(1)", replacement="print(2)")] + with pytest.raises(PatchApplicationError, match="multiple"): + apply_edits(source=source, edits=edits) + + def test_multiple_edits_applied_sequentially(self) -> None: + source = "def foo():\n" " a = 1\n" " b = 2\n" " return a + b\n" + edits = [ + EditSpec(match="a = 1", replacement="a = 10"), + EditSpec(match="b = 2", replacement="b = 20"), + ] + result = apply_edits(source=source, edits=edits) + assert result == ( + "def foo():\n" " a = 10\n" " b = 20\n" " return a + b\n" + ) + + def test_strip_matching_ignores_leading_trailing_whitespace(self) -> None: + source = "def foo():\n" " x = compute()\n" " return x\n" + edits = [ + EditSpec( + match=" x = compute() ", + replacement="x = replaced()", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ("def foo():\n" " x = replaced()\n" " return x\n") + + def test_replacement_indented_text_realigned(self) -> None: + """replacement text with its own indentation gets realigned to match source.""" + source = "def foo():\n" " x = compute()\n" " return x\n" + edits = [ + EditSpec( + match="x = compute()", + replacement="x = compute()\nprint(x)", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ( + "def foo():\n" + " x = compute()\n" + " print(x)\n" + " return x\n" + ) + + def test_replacement_with_existing_indent_realigned(self) -> None: + """replacement text already has indentation that should be rebased.""" + source = "def foo():\n" " if True:\n" " x = 1\n" " return x\n" + edits = [ + EditSpec( + match="x = 1", + replacement="x = 1\nif x > 0:\n print(x)", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ( + "def foo():\n" + " if True:\n" + " x = 1\n" + " if x > 0:\n" + " print(x)\n" + " return x\n" + ) + + def test_append_keeps_match_and_adds_after(self) -> None: + source = "def foo():\n" " x = compute()\n" " return x\n" + edits = [EditSpec(match="x = compute()", append="print(x)")] + result = apply_edits(source=source, edits=edits) + assert result == ( + "def foo():\n" " x = compute()\n" " print(x)\n" " return x\n" + ) + + def test_append_multiline_match(self) -> None: + source = ( + "def foo():\n" + " result = call(\n" + " a=1,\n" + " b=2,\n" + " )\n" + " return result\n" + ) + edits = [ + EditSpec( + match="result = call(\n a=1,\n b=2,\n)", + append="dumper.dump('result', result)", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ( + "def foo():\n" + " result = call(\n" + " a=1,\n" + " b=2,\n" + " )\n" + " dumper.dump('result', result)\n" + " return result\n" + ) + + def test_prepend_adds_before_match(self) -> None: + source = "def foo():\n" " x = compute()\n" " return x\n" + edits = [EditSpec(match="x = compute()", prepend="print('before')")] + result = apply_edits(source=source, edits=edits) + assert result == ( + "def foo():\n" + " print('before')\n" + " x = compute()\n" + " return x\n" + ) + + def test_prepend_multiline(self) -> None: + source = "def foo():\n" " return x\n" + edits = [EditSpec(match="return x", prepend="a = 1\nb = 2")] + result = apply_edits(source=source, edits=edits) + assert result == ("def foo():\n" " a = 1\n" " b = 2\n" " return x\n") + + def test_prepend_deep_indent(self) -> None: + source = ( + "class Foo:\n" + " class Bar:\n" + " def method(self):\n" + " return x\n" + ) + edits = [EditSpec(match="return x", prepend="dumper.dump('x', x)")] + result = apply_edits(source=source, edits=edits) + assert result == ( + "class Foo:\n" + " class Bar:\n" + " def method(self):\n" + " dumper.dump('x', x)\n" + " return x\n" + ) + + def test_prepend_multiline_match(self) -> None: + source = ( + "def foo():\n" + " result = call(\n" + " a=1,\n" + " )\n" + " return result\n" + ) + edits = [ + EditSpec( + match="result = call(\n a=1,\n)", + prepend="dumper.dump('before', x)", + ) + ] + result = apply_edits(source=source, edits=edits) + assert result == ( + "def foo():\n" + " dumper.dump('before', x)\n" + " result = call(\n" + " a=1,\n" + " )\n" + " return result\n" + ) + + def test_replacement_and_append_mutually_exclusive(self) -> None: + with pytest.raises(ValidationError, match="only one of"): + EditSpec(match="x = 1", replacement="x = 2", append="print(x)") + + def test_replacement_and_prepend_mutually_exclusive(self) -> None: + with pytest.raises(ValidationError, match="only one of"): + EditSpec(match="x = 1", replacement="x = 2", prepend="print(x)") + + def test_prepend_and_append_mutually_exclusive(self) -> None: + with pytest.raises(ValidationError, match="only one of"): + EditSpec(match="x = 1", prepend="a()", append="b()") + + def test_second_edit_sees_result_of_first(self) -> None: + """Edits are applied sequentially; second edit matches modified source.""" + source = "def foo():\n" " x = 1\n" " return x\n" + edits = [ + EditSpec(match="x = 1", replacement="x = 1\ny = 2"), + EditSpec(match="y = 2", replacement="y = 20"), + ] + result = apply_edits(source=source, edits=edits) + assert result == ("def foo():\n" " x = 1\n" " y = 20\n" " return x\n") + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/test_crash_dump.py b/asian_ai/performance/SGLang/test/registered/debug_utils/test_crash_dump.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac75d4c8efc2738ce661910648e92215d8d5dcd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/test_crash_dump.py @@ -0,0 +1,122 @@ +import glob +import os +import pickle +import tempfile +import time +import unittest + +import requests + +from sglang.srt.environ import envs +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import ( + register_amd_ci, + register_cpu_ci, + register_cuda_ci, +) +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=40, suite="nightly-1-gpu", nightly=True) +register_amd_ci(est_time=40, suite="nightly-amd-1-gpu", nightly=True) +register_cpu_ci(est_time=225, suite="base-c-test-cpu") + + +class TestCrashDump(CustomTestCase): + crash_dump_folder = None + MAX_NEW_TOKENS = 4 + NUM_REQUESTS_BEFORE_CRASH = 5 + + @classmethod + def setUpClass(cls): + cls.crash_dump_folder = tempfile.mkdtemp(prefix="crash_dump_test_") + + with envs.SGLANG_TEST_CRASH_AFTER_STREAM_OUTPUTS.override( + cls.NUM_REQUESTS_BEFORE_CRASH * cls.MAX_NEW_TOKENS + 10 + ): + cls.process = popen_launch_server( + "Qwen/Qwen3-0.6B", + DEFAULT_URL_FOR_TEST, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--crash-dump-folder", + cls.crash_dump_folder, + "--skip-server-warmup", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_crash_dump_generated(self): + """Test that crash dump file is generated after server crash.""" + # Send multiple requests to trigger the crash + for i in range(self.NUM_REQUESTS_BEFORE_CRASH * 2): + try: + response = requests.post( + DEFAULT_URL_FOR_TEST + "/generate", + json={ + "text": f"Hello, this is request {i}.", + "sampling_params": { + "max_new_tokens": self.MAX_NEW_TOKENS, + "temperature": 0, + }, + }, + timeout=30, + ) + except requests.exceptions.RequestException: + # Connection error expected after crash + pass + + # Wait for crash dump to be written + time.sleep(5) + + # Find the crash dump file + dump_pattern = os.path.join(self.crash_dump_folder, "*", "crash_dump_*.pkl") + dump_files = glob.glob(dump_pattern) + + # Check that a dump file was created + self.assertTrue( + len(dump_files) > 0, + f"No crash dump file found in {self.crash_dump_folder}. " + f"Pattern: {dump_pattern}", + ) + + # Read the dump file and verify contents + dump_file = dump_files[0] + with open(dump_file, "rb") as f: + dump_data = pickle.load(f) + + # Verify the dump structure + self.assertIn("server_args", dump_data) + self.assertIn("requests", dump_data) + + # Check that there are more than 5 requests in the dump + requests_list = dump_data["requests"] + self.assertGreater( + len(requests_list), + self.NUM_REQUESTS_BEFORE_CRASH, + f"Expected more than {self.NUM_REQUESTS_BEFORE_CRASH} requests in dump, but got {len(requests_list)}", + ) + + # Verify each request tuple has the expected structure (obj, out, created_time, finish_time) + for i, req_tuple in enumerate(requests_list): + self.assertIsInstance( + req_tuple, + tuple, + f"Request {i} should be a tuple, got {type(req_tuple)}", + ) + self.assertGreaterEqual( + len(req_tuple), + 4, + f"Request {i} tuple should have at least 4 elements", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/test_dump_comparator.py b/asian_ai/performance/SGLang/test/registered/debug_utils/test_dump_comparator.py new file mode 100644 index 0000000000000000000000000000000000000000..f399b7201f32a93848cec953aad517712770b44e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/test_dump_comparator.py @@ -0,0 +1,60 @@ +import pytest +import torch + +from sglang.srt.debug_utils.dump_comparator import ( + _argmax_coord, + _calc_rel_diff, + _compute_smaller_dtype, + _try_unify_shape, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=30, suite="base-a-test-cpu", nightly=True) + + +# ----------------------------- Unit tests ----------------------------- + + +class TestCalcRelDiff: + def test_identical_vectors(self) -> None: + x: torch.Tensor = torch.randn(10, 10) + assert _calc_rel_diff(x, x).item() == pytest.approx(0.0, abs=1e-5) + + def test_zero_vectors(self) -> None: + z: torch.Tensor = torch.zeros(5) + result = _calc_rel_diff(z, z) + assert not torch.isnan(result) or True # should not crash + + +class TestArgmaxCoord: + def test_known_position(self) -> None: + x: torch.Tensor = torch.zeros(2, 3, 4) + x[1, 2, 3] = 10.0 + assert _argmax_coord(x) == (1, 2, 3) + + +class TestTryUnifyShape: + def test_squeeze_leading_ones(self) -> None: + target_shape: torch.Size = torch.Size([3, 4]) + result: torch.Tensor = _try_unify_shape(torch.randn(1, 1, 3, 4), target_shape) + assert result.shape == target_shape + + def test_no_op_when_no_leading_ones(self) -> None: + target_shape: torch.Size = torch.Size([3, 4]) + result: torch.Tensor = _try_unify_shape(torch.randn(2, 3, 4), target_shape) + assert result.shape == (2, 3, 4) + + +class TestComputeSmallerDtype: + def test_known_pair(self) -> None: + assert _compute_smaller_dtype(torch.float32, torch.bfloat16) == torch.bfloat16 + assert _compute_smaller_dtype(torch.bfloat16, torch.float32) == torch.bfloat16 + + def test_none_for_same_dtype(self) -> None: + assert _compute_smaller_dtype(torch.float32, torch.float32) is None + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/test_dump_loader.py b/asian_ai/performance/SGLang/test/registered/debug_utils/test_dump_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..88e5db5452203635110d218e0c25d8251fcf24ff --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/test_dump_loader.py @@ -0,0 +1,128 @@ +import sys + +import polars as pl +import pytest +import torch + +from sglang.srt.debug_utils.dump_loader import ( + LOAD_FAILED, + ValueWithMeta, + _add_duplicate_index, + _cast_to_polars_dtype, + find_row, + parse_meta_from_filename, + read_meta, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=30, suite="base-a-test-cpu", nightly=True) + + +class TestReadMeta: + def test_basic(self, tmp_path): + for fn in [ + "step=1___rank=0___dump_index=1___name=a.pt", + "step=2___rank=0___dump_index=2___name=b.pt", + ]: + torch.save(torch.randn(5), tmp_path / fn) + + df = read_meta(str(tmp_path)) + assert len(df) == 2 + assert all(c in df.columns for c in ["step", "rank", "name"]) + + +class TestFindRow: + def test_single_match(self): + df = pl.DataFrame({"id": [1, 2], "name": ["a", "b"], "file": ["f1", "f2"]}) + assert find_row(df, {"id": 2})["file"] == "f2" + + def test_no_match(self): + df = pl.DataFrame({"id": [1, 2], "name": ["a", "b"], "file": ["f1", "f2"]}) + assert find_row(df, {"id": 999}) is None + + def test_ambiguous(self): + df = pl.DataFrame({"id": [1, 1], "file": ["f1", "f2"]}) + assert find_row(df, {"id": 1}) is None + + +class TestCastToPolars: + def test_int(self): + assert _cast_to_polars_dtype("42", pl.Int64) == 42 + + def test_float(self): + assert _cast_to_polars_dtype("3.14", pl.Float64) == pytest.approx(3.14) + + +class TestAddDuplicateIndex: + def test_basic(self): + df = pl.DataFrame( + { + "name": ["a", "a", "b"], + "dump_index": [1, 2, 3], + "filename": ["f1", "f2", "f3"], + } + ) + result = _add_duplicate_index(df) + assert result.filter(pl.col("name") == "a").sort("dump_index")[ + "duplicate_index" + ].to_list() == [0, 1] + + +class TestValueWithMeta: + def test_load_dict_format(self, tmp_path) -> None: + path = tmp_path / "step=0___rank=0___dump_index=1___name=hidden.pt" + tensor = torch.randn(4, 8) + torch.save({"value": tensor, "meta": {"custom": "field"}}, path) + + loaded = ValueWithMeta.load(path) + assert torch.allclose(loaded.value, tensor) + assert loaded.meta["custom"] == "field" + assert loaded.meta["name"] == "hidden" + assert loaded.meta["rank"] == 0 + + def test_load_bare_tensor(self, tmp_path) -> None: + path = tmp_path / "step=0___rank=0___dump_index=1___name=bare.pt" + tensor = torch.randn(3, 3) + torch.save(tensor, path) + + loaded = ValueWithMeta.load(path) + assert torch.allclose(loaded.value, tensor) + assert loaded.meta["name"] == "bare" + + def test_load_corrupted_file(self, tmp_path) -> None: + path = tmp_path / "step=0___rank=0___dump_index=1___name=bad.pt" + path.write_text("not a valid pt file") + + loaded = ValueWithMeta.load(path) + assert loaded.value is LOAD_FAILED + assert loaded.meta["name"] == "bad" + + +class TestRecomputeStatusParsing: + def test_parse_recompute_status_from_filename(self) -> None: + from pathlib import Path + + meta_disabled = parse_meta_from_filename( + Path( + "step=0___rank=0___dump_index=1___name=x___recompute_status=disabled.pt" + ) + ) + assert meta_disabled["recompute_status"] == "disabled" + + meta_recompute = parse_meta_from_filename( + Path( + "step=0___rank=0___dump_index=1___name=x___recompute_status=recompute.pt" + ) + ) + assert meta_recompute["recompute_status"] == "recompute" + + meta_original = parse_meta_from_filename( + Path( + "step=0___rank=0___dump_index=1___name=x___recompute_status=original.pt" + ) + ) + assert meta_original["recompute_status"] == "original" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/test_dumper.py b/asian_ai/performance/SGLang/test/registered/debug_utils/test_dumper.py new file mode 100644 index 0000000000000000000000000000000000000000..a55822d2511055aa514bf17685fb21ef67da10b1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/test_dumper.py @@ -0,0 +1,4319 @@ +import io +import multiprocessing +import os +import re +import sys +import threading +import time +from contextlib import contextmanager +from pathlib import Path +from typing import Optional + +import pytest +import requests +import torch +import torch.distributed as dist + +from sglang.srt.debug_utils.dumper import ( + DumperConfig, + _collect_parallel_rank_tags, + _collective_with_timeout, + _compare_tensors_quick, + _deepcopy_or_clone, + _detect_recompute_status, + _Dumper, + _format_tags, + _get_default_exp_name, + _Grafter, + _load_function, + _log, + _map_tensor, + _materialize_value, + _MegatronPlugin, + _obj_to_dict, + _RecomputeStatus, + _register_forward_hook_or_replace_fn, + _SGLangPlugin, + _torch_save, + dumper, + get_tensor_info, + get_truncated_value, +) +from sglang.srt.environ import temp_set_env +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + find_available_port, + popen_launch_server, + run_distributed_test, +) + +register_cuda_ci(est_time=30, suite="nightly-2-gpu", nightly=True) +register_amd_ci(est_time=60, suite="nightly-amd", nightly=True) + + +@contextmanager +def _capture_stdout(): + captured = io.StringIO() + old_stdout = sys.stdout + sys.stdout = captured + try: + yield captured + finally: + sys.stdout = old_stdout + + +class TestDumperConfig: + def test_from_env_defaults_match_dataclass_defaults(self): + assert DumperConfig.from_env() == DumperConfig() + + def test_from_env_bool(self): + with temp_set_env(DUMPER_ENABLE="1"): + assert DumperConfig.from_env().enable is True + with temp_set_env(DUMPER_ENABLE="false"): + assert DumperConfig.from_env().enable is False + + def test_from_env_str(self): + with temp_set_env(DUMPER_FILTER="layer_id=0"): + assert DumperConfig.from_env().filter == "layer_id=0" + + def test_from_env_dir(self): + with temp_set_env(DUMPER_DIR="/my/dir"): + assert DumperConfig.from_env().dir == "/my/dir" + + def test_from_env_int(self): + with temp_set_env(DUMPER_COLLECTIVE_TIMEOUT="120"): + assert DumperConfig.from_env().collective_timeout == 120 + + def test_configure_overrides(self): + d = _make_test_dumper("/tmp") + d.configure(enable=False) + assert d._config.enable is False + d.configure(enable=True) + assert d._config.enable is True + + def test_type_validation(self): + with pytest.raises(TypeError, match="enable.*expected bool.*got str"): + DumperConfig(enable="yes") + with pytest.raises( + TypeError, match="collective_timeout.*expected int.*got str" + ): + DumperConfig(collective_timeout="abc") + with pytest.raises(TypeError, match="filter.*expected str.*got int"): + DumperConfig(filter=123) + + def test_configure_default_skips_when_env_set(self): + with temp_set_env(DUMPER_FILTER="from_env"): + d = _Dumper(config=DumperConfig.from_env()) + d.configure_default(filter="from_code") + assert d._config.filter == "from_env" + + def test_configure_default_applies_when_no_env(self): + d = _Dumper(config=DumperConfig.from_env()) + d.configure_default(filter="from_code") + assert d._config.filter == "from_code" + + def test_from_env_whitespace_treated_as_unset(self): + with temp_set_env(DUMPER_FILTER=" "): + assert DumperConfig.from_env().filter is None + + def test_may_enable_default_false(self): + d = _Dumper(config=DumperConfig()) + assert d.may_enable is False + + def test_may_enable_true_when_enabled(self): + d = _Dumper(config=DumperConfig(enable=True)) + assert d.may_enable is True + + def test_may_enable_true_when_server_port_set(self): + d = _Dumper(config=DumperConfig(server_port="40000")) + assert d.may_enable is True + + d2 = _Dumper(config=DumperConfig(server_port="reuse")) + assert d2.may_enable is True + + +class TestServerPortParsed: + def test_negative_returns_none(self): + assert DumperConfig(server_port="-1").server_port_parsed is None + + def test_zero_returns_none(self): + assert DumperConfig(server_port="0").server_port_parsed is None + + def test_positive_returns_int(self): + result = DumperConfig(server_port="40000").server_port_parsed + assert result == 40000 + assert isinstance(result, int) + + def test_reuse_returns_string(self): + assert DumperConfig(server_port="reuse").server_port_parsed == "reuse" + + +class TestDefaultExpName: + def test_starts_with_prefix(self): + name = _get_default_exp_name(timeout_seconds=5) + assert name.startswith("dump_") + + def test_suffix_format(self): + name = _get_default_exp_name(timeout_seconds=5) + suffix = name[len("dump_") :] + assert len(suffix) == 22 + assert suffix[8] == "_" + + +class TestKvPairsParsing: + def test_from_kv_pairs_none_returns_defaults(self): + assert DumperConfig.from_kv_pairs(None) == DumperConfig() + + def test_from_kv_pairs_empty_returns_defaults(self): + assert DumperConfig.from_kv_pairs([]) == DumperConfig() + + def test_from_kv_pairs_bool_field(self): + cfg = DumperConfig.from_kv_pairs(["enable=true"]) + assert cfg.enable is True + assert cfg.dir == "/tmp/dumper" + + def test_from_kv_pairs_bool_numeric(self): + assert DumperConfig.from_kv_pairs(["enable=1"]).enable is True + assert DumperConfig.from_kv_pairs(["enable=0"]).enable is False + + def test_from_kv_pairs_int_field(self): + cfg = DumperConfig.from_kv_pairs(["collective_timeout=120"]) + assert cfg.collective_timeout == 120 + assert type(cfg.collective_timeout) is int + + def test_from_kv_pairs_int_field_zero_stays_int(self): + cfg = DumperConfig.from_kv_pairs(["collective_timeout=0"]) + assert cfg.collective_timeout == 0 + assert type(cfg.collective_timeout) is int + + def test_from_kv_pairs_str_field_not_coerced(self): + cfg = DumperConfig.from_kv_pairs(["server_port=0"]) + assert cfg.server_port == "0" + assert type(cfg.server_port) is str + + def test_from_kv_pairs_str_field_one_stays_str(self): + cfg = DumperConfig.from_kv_pairs(["server_port=1"]) + assert cfg.server_port == "1" + assert type(cfg.server_port) is str + + def test_from_kv_pairs_optional_str_field(self): + cfg = DumperConfig.from_kv_pairs( + ["filter=layer_id is not None and layer_id < 3"] + ) + assert cfg.filter == "layer_id is not None and layer_id < 3" + + def test_from_kv_pairs_optional_str_exp_name(self): + cfg = DumperConfig.from_kv_pairs(["exp_name=my_experiment"]) + assert cfg.exp_name == "my_experiment" + + def test_from_kv_pairs_multiple_fields(self): + cfg = DumperConfig.from_kv_pairs( + [ + "enable=true", + "dir=/my/dir", + "filter=name == 'foo'", + "collective_timeout=30", + "enable_grad=1", + ] + ) + assert cfg.enable is True + assert cfg.dir == "/my/dir" + assert cfg.filter == "name == 'foo'" + assert cfg.collective_timeout == 30 + assert cfg.enable_grad is True + + def test_from_kv_pairs_missing_equals_raises(self): + with pytest.raises(ValueError, match="missing '='"): + DumperConfig.from_kv_pairs(["enable"]) + + def test_from_kv_pairs_unknown_key_raises(self): + with pytest.raises(ValueError, match="Unknown config key"): + DumperConfig.from_kv_pairs(["nonexistent=true"]) + + def test_kv_pairs_to_dict_returns_only_explicit(self): + d = DumperConfig._kv_pairs_to_dict(["enable=true", "dir=/x"]) + assert d == {"enable": True, "dir": "/x"} + assert "filter" not in d + assert "collective_timeout" not in d + + def test_kv_pairs_to_dict_none_returns_empty(self): + assert DumperConfig._kv_pairs_to_dict(None) == {} + + def test_kv_pairs_to_dict_empty_returns_empty(self): + assert DumperConfig._kv_pairs_to_dict([]) == {} + + def test_from_kv_pairs_value_with_equals_in_value(self): + cfg = DumperConfig.from_kv_pairs(["filter=name == 'foo'"]) + assert cfg.filter == "name == 'foo'" + + def test_from_kv_pairs_type_validation_still_works(self): + with pytest.raises(TypeError, match="collective_timeout.*expected int"): + DumperConfig.from_kv_pairs(["collective_timeout=not_a_number"]) + + +class TestDumperPureFunctions: + def test_get_truncated_value(self): + assert get_truncated_value(None) is None + assert get_truncated_value(42) == 42 + assert len(get_truncated_value((torch.randn(10), torch.randn(20)))) == 2 + assert get_truncated_value(torch.randn(10, 10)).shape == (10, 10) + assert get_truncated_value(torch.randn(100, 100)).shape == (5, 5) + + def test_obj_to_dict(self): + assert _obj_to_dict({"a": 1}) == {"a": 1} + + class Obj: + x, y = 10, 20 + + def method(self): + pass + + result = _obj_to_dict(Obj()) + assert result["x"] == 10 + assert "method" not in result + + def test_deepcopy_or_clone_tensor(self): + original = torch.randn(3, 3) + cloned = _deepcopy_or_clone(original) + assert torch.equal(cloned, original) + original.fill_(999.0) + assert not torch.equal(cloned, original) + + def test_deepcopy_or_clone_non_tensor(self): + original = {"a": [1, 2, 3]} + cloned = _deepcopy_or_clone(original) + assert cloned == original + assert cloned is not original + original["a"].append(4) + assert len(cloned["a"]) == 3 + + def test_get_tensor_info(self): + info = get_tensor_info(torch.randn(10, 10)) + for key in ["shape=", "dtype=", "min=", "max=", "mean="]: + assert key in info + + assert "value=42" in get_tensor_info(42) + assert "min=None" in get_tensor_info(torch.tensor([])) + + +class TestMapTensor: + def test_bare_tensor(self): + t = torch.randn(4) + result = _map_tensor(t, lambda x: x * 2) + assert torch.equal(result, t * 2) + + def test_bare_tensor_no_change(self): + t = torch.randn(4) + result = _map_tensor(t, lambda x: x) + assert result is t + + def test_dict_with_tensor_values(self): + t1 = torch.randn(3) + t2 = torch.randn(5) + value = {"a": t1, "b": t2, "meta": "not a tensor"} + result = _map_tensor(value, lambda x: x.clone()) + assert torch.equal(result["a"], t1) + assert torch.equal(result["b"], t2) + assert result["a"] is not t1 + assert result["b"] is not t2 + assert result["meta"] == "not a tensor" + + def test_dict_no_tensors(self): + value = {"a": 1, "b": "hello"} + result = _map_tensor(value, lambda x: x.clone()) + assert result == value + + def test_nested_dict(self): + inner_t = torch.randn(3) + value = {"outer": {"inner": inner_t, "label": "ok"}, "top": torch.randn(2)} + result = _map_tensor(value, lambda x: x.clone()) + assert torch.equal(result["outer"]["inner"], inner_t) + assert result["outer"]["inner"] is not inner_t + assert result["outer"]["label"] == "ok" + assert result is not value + assert result["outer"] is not value["outer"] + + def test_non_tensor_non_dict(self): + result = _map_tensor(42, lambda x: x.clone()) + assert result == 42 + + +class TestTorchSave: + def test_normal(self, tmp_path): + path = str(tmp_path / "a.pt") + tensor = torch.randn(3, 3) + + _torch_save(tensor, path) + + assert torch.equal(torch.load(path, weights_only=True), tensor) + + def test_parameter_fallback(self, tmp_path): + class BadParam(torch.nn.Parameter): + def __reduce_ex__(self, protocol): + raise RuntimeError("not pickleable") + + path = str(tmp_path / "b.pt") + param = BadParam(torch.randn(4)) + + _torch_save(param, path) + + assert torch.equal(torch.load(path, weights_only=True), param.data) + + def test_shared_storage_not_bloated(self, tmp_path): + big = torch.randn(1000, 1000) + view = big[0] + path = str(tmp_path / "view.pt") + + _torch_save({"value": view, "meta": {}}, path) + + file_size = Path(path).stat().st_size + expected_max = view.nelement() * view.element_size() * 10 + assert file_size < expected_max, ( + f"File {file_size} bytes but view is only " + f"{view.nelement() * view.element_size()} bytes — " + f"torch.save likely serialized the full " + f"{big.nelement() * big.element_size()} byte storage" + ) + + def test_silent_skip(self, tmp_path, capsys): + path = str(tmp_path / "c.pt") + + _torch_save({"fn": lambda: None}, path) + + captured = capsys.readouterr() + assert "[Dumper, rank=" in captured.out + assert "Observe error=" in captured.out + assert "skip the tensor" in captured.out + + +class TestLog: + def test_log_format(self): + with _capture_stdout() as captured: + _log("hello") + out = captured.getvalue() + assert "hello" in out, out + assert "[Dumper, rank=" in out, out + assert ", t=" in out, out + + +class TestCompareTensorsQuick: + def test_identical(self): + a = torch.tensor([1.0, 2.0, 3.0]) + s = _compare_tensors_quick(a, a.clone()) + assert "rel_diff=0" in s, s + assert "max_abs=0" in s, s + + def test_diverged(self): + a = torch.tensor([1.0, 2.0, 3.0]) + b = torch.tensor([1.0, 2.0, 4.0]) # last element differs by 1 + s = _compare_tensors_quick(a, b) + assert "max_abs=1" in s, s + assert "rel_diff=" in s, s + + def test_shape_mismatch(self): + s = _compare_tensors_quick(torch.zeros(3), torch.zeros(4)) + assert "shape mismatch" in s, s + + def test_dtype_unified(self): + s = _compare_tensors_quick( + torch.zeros(3, dtype=torch.float32), + torch.zeros(3, dtype=torch.float64), + ) + assert "rel_diff=" in s, s + assert "max_abs=" in s, s + + def test_empty(self): + s = _compare_tensors_quick(torch.zeros(0), torch.zeros(0)) + assert s == "empty" + + +class TestCollectiveTimeout: + def test_watchdog_fires_on_timeout(self): + block_event = threading.Event() + output = "" + + def run_with_timeout(): + nonlocal output + with _capture_stdout() as captured: + _collective_with_timeout( + lambda: block_event.wait(), + operation_name="test_blocked_op", + timeout_seconds=2, + ) + output = captured.getvalue() + + worker = threading.Thread(target=run_with_timeout) + worker.start() + + time.sleep(4) + block_event.set() + worker.join(timeout=5) + + print(f"Captured output: {output!r}") + assert "WARNING" in output + assert "test_blocked_op" in output + assert "2s" in output + + +class TestDumperDistributed: + def test_basic(self, tmp_path): + with temp_set_env( + DUMPER_ENABLE="1", + DUMPER_DIR=str(tmp_path), + ): + run_distributed_test(self._test_basic_func, tmpdir=str(tmp_path)) + + @staticmethod + def _test_basic_func(rank, tmpdir): + tensor = torch.randn(10, 10, device=f"cuda:{rank}") + + dumper.dump("tensor_a", tensor, arg=100) + dumper.step() + + dumper.set_ctx(ctx_arg=200) + dumper.dump("tensor_b", tensor) + dumper.set_ctx(ctx_arg=None) + dumper.step() + + dumper.configure(filter="False") + dumper.dump("tensor_skip", tensor) + dumper.configure(filter=None) + dumper.step() + + dumper.dump_dict("obj", {"a": torch.randn(3, device=f"cuda:{rank}"), "b": 42}) + dumper.step() + + dist.barrier() + filenames = _get_filenames(tmpdir) + _assert_files( + filenames, + exist=["tensor_a", "tensor_b", "arg=100", "ctx_arg=200", "obj_a", "obj_b"], + not_exist=["tensor_skip"], + ) + + def test_collective_timeout(self): + with temp_set_env(DUMPER_ENABLE="1"): + run_distributed_test(self._test_collective_timeout_func) + + @staticmethod + def _test_collective_timeout_func(rank): + dumper = _Dumper( + config=DumperConfig( + enable=True, + collective_timeout=3, + ), + ) + + with _capture_stdout() as captured: + if rank != 0: + time.sleep(6) + dumper.step() + + output = captured.getvalue() + print(f"Rank {rank} captured output: {output!r}") + + if rank == 0: + assert "WARNING" in output, f"Expected WARNING in rank 0 output: {output}" + assert "has not completed after 3s" in output + + def test_file_content_correctness(self, tmp_path): + with temp_set_env( + DUMPER_ENABLE="1", + DUMPER_DIR=str(tmp_path), + ): + run_distributed_test(self._test_file_content_func, tmpdir=str(tmp_path)) + + @staticmethod + def _test_file_content_func(rank, tmpdir): + tensor = torch.arange(12, device=f"cuda:{rank}").reshape(3, 4).float() + + dumper.dump("content_check", tensor) + dumper.step() + + dist.barrier() + path = _find_dump_file(tmpdir, rank=rank, name="content_check") + raw = _load_dump(path) + assert isinstance(raw, dict), f"Expected dict, got {type(raw)}" + assert "value" in raw and "meta" in raw + assert torch.equal(raw["value"], tensor.cpu()) + assert raw["meta"]["name"] == "content_check" + assert raw["meta"]["rank"] == rank + + +class TestDumperFileWriteControl: + def test_filter(self, tmp_path): + with temp_set_env( + DUMPER_ENABLE="1", + DUMPER_DIR=str(tmp_path), + DUMPER_FILTER="name.startswith('keep')", + ): + run_distributed_test(self._test_filter_func, tmpdir=str(tmp_path)) + + @staticmethod + def _test_filter_func(rank, tmpdir): + dumper.dump("keep_this", torch.randn(5, device=f"cuda:{rank}")) + dumper.dump("skip_this", torch.randn(5, device=f"cuda:{rank}")) + dumper.dump("not_keep_this", torch.randn(5, device=f"cuda:{rank}")) + dumper.step() + + dist.barrier() + filenames = _get_filenames(tmpdir) + _assert_files( + filenames, + exist=["keep_this"], + not_exist=["skip_this", "not_keep_this"], + ) + + def test_save_false(self, tmp_path): + with temp_set_env( + DUMPER_ENABLE="1", + DUMPER_DIR=str(tmp_path), + ): + run_distributed_test(self._test_save_false_func, tmpdir=str(tmp_path)) + + @staticmethod + def _test_save_false_func(rank, tmpdir): + dumper.dump("no_save_tensor", torch.randn(5, device=f"cuda:{rank}"), save=False) + dumper.step() + + dist.barrier() + assert len(_get_filenames(tmpdir)) == 0 + + +class TestDumpEnableFlags: + def test_all_enables_false_no_output(self, tmp_path): + d = _make_test_dumper(tmp_path, enable_value=False, enable_grad=False) + d.dump("should_skip", torch.randn(3, 3)) + assert len(_get_filenames(tmp_path)) == 0 + + +class TestOutputControl: + def test_file_enabled_by_default(self, tmp_path): + d = _make_test_dumper(tmp_path) + d.dump("file_on", torch.randn(3, 3)) + + _assert_files(_get_filenames(tmp_path), exist=["file_on"]) + + def test_file_disabled(self, tmp_path, capsys): + d = _make_test_dumper(tmp_path, enable_output_file=False) + d.dump("file_off", torch.randn(3, 3)) + + assert len(_get_filenames(tmp_path)) == 0 + assert "file_off" in capsys.readouterr().out + + def test_console_enabled_by_default(self, tmp_path, capsys): + d = _make_test_dumper(tmp_path) + d.dump("console_on", torch.randn(3, 3)) + + captured = capsys.readouterr() + assert "[Dumper.Value]" in captured.out + assert "console_on" in captured.out + + def test_console_disabled(self, tmp_path, capsys): + d = _make_test_dumper(tmp_path, enable_output_console=False) + d.dump("console_off", torch.randn(3, 3)) + + assert "console_off" not in capsys.readouterr().out + _assert_files(_get_filenames(tmp_path), exist=["console_off"]) + + def test_capture_output_basic(self, tmp_path): + d = _make_test_dumper(tmp_path) + tensor = torch.randn(4, 4) + + with d.capture_output() as captured: + d.dump("cap_basic", tensor) + + assert "cap_basic" in captured + assert set(captured["cap_basic"].keys()) == {"value", "meta"} + assert torch.equal(captured["cap_basic"]["value"], tensor) + assert captured["cap_basic"]["meta"]["name"] == "cap_basic" + + def test_capture_output_no_file(self, tmp_path): + d = _make_test_dumper(tmp_path) + + with d.capture_output() as captured: + d.dump("cap_no_file", torch.randn(3, 3)) + + assert "cap_no_file" in captured + assert len(_get_filenames(tmp_path)) == 0 + + def test_capture_output_multiple(self, tmp_path): + d = _make_test_dumper(tmp_path) + + with d.capture_output() as captured: + d.dump("first", torch.randn(2, 2)) + d.dump("second", torch.randn(3, 3)) + + assert set(captured.keys()) == {"first", "second"} + assert captured["first"]["value"].shape == (2, 2) + assert captured["second"]["value"].shape == (3, 3) + + def test_capture_output_value_cloned(self, tmp_path): + d = _make_test_dumper(tmp_path) + tensor = torch.zeros(3, 3) + + with d.capture_output() as captured: + d.dump("clone_check", tensor) + + tensor.fill_(999.0) + assert torch.equal(captured["clone_check"]["value"], torch.zeros(3, 3)) + + def test_capture_output_nested_raises(self, tmp_path): + d = _make_test_dumper(tmp_path) + with d.capture_output(): + with pytest.raises(AssertionError): + with d.capture_output(): + pass + + def test_capture_output_respects_filter(self, tmp_path): + d = _make_test_dumper(tmp_path, filter="'keep' in name") + + with d.capture_output() as captured: + d.dump("keep_this", torch.randn(3, 3)) + d.dump("skip_this", torch.randn(3, 3)) + + assert "keep_this" in captured + assert "skip_this" not in captured + + +class TestDumpDictFormat: + """Verify that dump files use the dict output format: {"value": ..., "meta": {...}}.""" + + def test_dict_format_structure(self, tmp_path): + dumper = _make_test_dumper(tmp_path) + tensor = torch.randn(4, 4) + dumper.dump("fmt_test", tensor, custom_key="hello") + + path = _find_dump_file(str(tmp_path), rank=0, name="fmt_test") + raw = _load_dump(path) + + assert isinstance(raw, dict) + assert set(raw.keys()) == {"value", "meta"} + assert torch.equal(raw["value"], tensor) + + meta = raw["meta"] + assert meta["name"] == "fmt_test" + assert meta["custom_key"] == "hello" + assert "step" in meta + assert "rank" in meta + assert "dump_index" in meta + + def test_dict_format_with_context(self, tmp_path): + dumper = _make_test_dumper(tmp_path) + dumper.set_ctx(ctx_val=42) + tensor = torch.randn(2, 2) + dumper.dump("ctx_fmt", tensor) + + path = _find_dump_file(str(tmp_path), rank=0, name="ctx_fmt") + raw = _load_dump(path) + + assert raw["meta"]["ctx_val"] == 42 + assert torch.equal(raw["value"], tensor) + + +def _make_test_dumper(tmp_path, **overrides) -> _Dumper: + """Create a _Dumper for CPU testing without distributed.""" + defaults = dict( + enable=True, + dir=str(tmp_path), + exp_name="test", + ) + defaults.update(overrides) + config = DumperConfig(**defaults) + return _Dumper(config=config) + + +def _get_filenames(tmpdir): + return {f.name for f in Path(tmpdir).glob("*/*.pt")} + + +def _assert_files(filenames, *, exist=(), not_exist=()): + for p in exist: + assert any(p in f for f in filenames), f"{p} not found in {filenames}" + for p in not_exist: + assert not any( + p in f for f in filenames + ), f"{p} should not exist in {filenames}" + + +def _load_dump(path: Path) -> dict: + """Load a dump file and return the raw dict (with 'value' and 'meta' keys).""" + return torch.load(path, map_location="cpu", weights_only=False) + + +def _find_dump_file(tmpdir, *, rank: int = 0, name: str) -> Path: + matches = [ + f + for f in Path(tmpdir).glob("*/*.pt") + if f"rank={rank}" in f.name and name in f.name + ] + assert ( + len(matches) == 1 + ), f"Expected 1 file matching rank={rank} name={name}, got {matches}" + return matches[0] + + +class TestMaterializeValue: + def test_materialize_value_callable(self): + tensor = torch.randn(3, 3) + result = _materialize_value(lambda: tensor) + assert torch.equal(result, tensor) + + def test_materialize_value_passthrough(self): + tensor = torch.randn(3, 3) + result = _materialize_value(tensor) + assert result is tensor + + def test_dump_with_callable_value(self, tmp_path): + d = _make_test_dumper(tmp_path) + tensor = torch.randn(4, 4) + d.dump("lazy_tensor", lambda: tensor) + + _assert_files(_get_filenames(tmp_path), exist=["name=lazy_tensor"]) + + path = _find_dump_file(tmp_path, rank=0, name="lazy_tensor") + assert torch.equal(_load_dump(path)["value"], tensor) + + +class TestSaveValue: + def test_dump_output_format(self, tmp_path): + dumper = _make_test_dumper(tmp_path) + tensor = torch.randn(4, 4) + + dumper.dump("dict_test", tensor) + + path = _find_dump_file(tmp_path, rank=0, name="dict_test") + loaded = _load_dump(path) + assert torch.equal(loaded["value"], tensor) + assert loaded["meta"]["name"] == "dict_test" + assert loaded["meta"]["rank"] == 0 + + +class TestStaticMetadata: + def test_static_meta_contains_world_info(self): + dumper = _make_test_dumper("/tmp") + meta = dumper._static_meta + assert "world_rank" in meta + assert "world_size" in meta + assert meta["world_rank"] == 0 + assert meta["world_size"] == 1 + + def test_static_meta_caching(self): + dumper = _make_test_dumper("/tmp") + meta1 = dumper._static_meta + meta2 = dumper._static_meta + assert meta1 is meta2 + + def test_parallel_info_graceful_fallback(self): + sglang_info = _SGLangPlugin().collect_parallel_info() + assert isinstance(sglang_info, dict) + + megatron_info = _MegatronPlugin().collect_parallel_info() + assert isinstance(megatron_info, dict) + + def test_dump_includes_static_meta(self, tmp_path): + dumper = _make_test_dumper(tmp_path) + tensor = torch.randn(2, 2) + + dumper.dump("meta_test", tensor) + + path = _find_dump_file(tmp_path, rank=0, name="meta_test") + loaded = _load_dump(path) + meta = loaded["meta"] + assert "world_rank" in meta + assert "world_size" in meta + + +class TestDumpGrad: + def test_dump_grad_basic(self, tmp_path): + d = _make_test_dumper(tmp_path, enable_grad=True) + x = torch.randn(3, 3, requires_grad=True) + y = (x * 2).sum() + + d.dump("test_tensor", x) + y.backward() + + filenames = _get_filenames(tmp_path) + assert any("name=test_tensor" in f and "grad__" not in f for f in filenames) + _assert_files(filenames, exist=["grad__test_tensor"]) + + def test_dump_grad_non_tensor_skipped(self, tmp_path): + d = _make_test_dumper(tmp_path, enable_grad=True) + d.dump("not_tensor", 42) + + _assert_files(_get_filenames(tmp_path), not_exist=["grad__"]) + + def test_dump_grad_no_requires_grad_skipped(self, tmp_path): + d = _make_test_dumper(tmp_path, enable_grad=True) + x = torch.randn(3, 3, requires_grad=False) + d.dump("no_grad_tensor", x) + + _assert_files( + _get_filenames(tmp_path), + exist=["name=no_grad_tensor"], + not_exist=["grad__"], + ) + + def test_dump_grad_captures_step(self, tmp_path): + d = _make_test_dumper(tmp_path, enable_grad=True) + d._state.step = 42 + x = torch.randn(3, 3, requires_grad=True) + y = (x * 2).sum() + + d.dump("id_test", x) + d._state.step = 999 + y.backward() + + grad_file = _find_dump_file(tmp_path, name="grad__id_test") + assert "step=42" in grad_file.name + + def test_dump_grad_file_content(self, tmp_path): + d = _make_test_dumper(tmp_path, enable_grad=True) + x = torch.tensor([[1.0, 2.0], [3.0, 4.0]], requires_grad=True) + y = (x * 3).sum() + + d.dump("content_check", x) + y.backward() + + grad_path = _find_dump_file(tmp_path, name="grad__content_check") + expected_grad = torch.full((2, 2), 3.0) + assert torch.equal(_load_dump(grad_path)["value"], expected_grad) + + def test_disable_value(self, tmp_path): + d = _make_test_dumper(tmp_path, enable_value=False, enable_grad=True) + x = torch.randn(3, 3, requires_grad=True) + y = (x * 2).sum() + + d.dump("fwd_disabled", x) + y.backward() + + filenames = _get_filenames(tmp_path) + assert not any( + "name=fwd_disabled" in f and "grad__" not in f for f in filenames + ) + _assert_files(filenames, exist=["grad__fwd_disabled"]) + + def test_disable_grad(self, tmp_path): + d = _make_test_dumper(tmp_path, enable_grad=False) + x = torch.randn(3, 3, requires_grad=True) + y = (x * 2).sum() + + d.dump("grad_disabled", x) + y.backward() + + _assert_files( + _get_filenames(tmp_path), + exist=["name=grad_disabled"], + not_exist=["grad__"], + ) + + +class TestKvFilter: + def test_format_tags(self): + assert _format_tags({"a": 1, "b": "hello"}) == "a=1___b=hello" + assert _format_tags({}) == "" + + def test_filter_matches_extra_kwargs(self, tmp_path): + d = _make_test_dumper(tmp_path, filter="layer_id == 0") + d.dump("tensor_a", torch.randn(3), layer_id=0) + d.dump("tensor_b", torch.randn(3), layer_id=1) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["tensor_a"], not_exist=["tensor_b"]) + + def test_filter_matches_global_ctx(self, tmp_path): + d = _make_test_dumper(tmp_path, filter="ctx_arg == 200") + d.set_ctx(ctx_arg=200) + d.dump("tensor_a", torch.randn(3)) + d.set_ctx(ctx_arg=None) + d.dump("tensor_b", torch.randn(3)) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["tensor_a"], not_exist=["tensor_b"]) + + def test_filter_matches_name(self, tmp_path): + d = _make_test_dumper(tmp_path, filter="'keep' in name") + d.dump("keep_this", torch.randn(3)) + d.dump("skip_this", torch.randn(3)) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["keep_this"], not_exist=["skip_this"]) + + def test_filter_expr_range(self, tmp_path): + d = _make_test_dumper(tmp_path, filter="layer_id is not None and layer_id < 3") + d.dump("t0", torch.randn(3), layer_id=0) + d.dump("t1", torch.randn(3), layer_id=1) + d.dump("t5", torch.randn(3), layer_id=5) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["name=t0", "name=t1"], not_exist=["name=t5"]) + + def test_filter_expr_with_none(self, tmp_path): + d = _make_test_dumper(tmp_path, filter="layer_id is None or layer_id < 3") + d.dump("no_layer", torch.randn(3)) + d.dump("layer0", torch.randn(3), layer_id=0) + d.dump("layer5", torch.randn(3), layer_id=5) + + filenames = _get_filenames(tmp_path) + _assert_files( + filenames, + exist=["no_layer", "layer0"], + not_exist=["layer5"], + ) + + def test_filter_expr_with_re_search(self, tmp_path): + d = _make_test_dumper(tmp_path, filter="search(r'attn|mlp', name)") + d.dump("self_attn", torch.randn(3)) + d.dump("mlp_proj", torch.randn(3)) + d.dump("layernorm", torch.randn(3)) + + filenames = _get_filenames(tmp_path) + _assert_files( + filenames, + exist=["self_attn", "mlp_proj"], + not_exist=["layernorm"], + ) + + def test_filter_expr_syntax_error(self, tmp_path): + d = _make_test_dumper(tmp_path, filter="layer_id ===") + with pytest.raises(SyntaxError): + d.dump("tensor", torch.randn(3)) + + def test_no_filter_dumps_all(self, tmp_path): + d = _make_test_dumper(tmp_path) + d.dump("a", torch.randn(3)) + d.dump("b", torch.randn(3)) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["name=a", "name=b"]) + + +class TestDumpModel: + def test_grad_basic(self, tmp_path): + d = _make_test_dumper( + tmp_path, enable_model_grad=True, enable_model_value=False + ) + model = torch.nn.Linear(4, 2) + x = torch.randn(3, 4) + y = model(x).sum() + y.backward() + + d.dump_model(model, name_prefix="model") + + _assert_files( + _get_filenames(tmp_path), + exist=["grad__model__weight", "grad__model__bias"], + ) + + def test_value_basic(self, tmp_path): + d = _make_test_dumper( + tmp_path, enable_model_value=True, enable_model_grad=False + ) + model = torch.nn.Linear(4, 2, bias=False) + + d.dump_model(model, name_prefix="model") + + _assert_files( + _get_filenames(tmp_path), + exist=["model__weight"], + ) + + def test_no_grad_skipped(self, tmp_path): + d = _make_test_dumper( + tmp_path, enable_model_grad=True, enable_model_value=False + ) + model = torch.nn.Linear(4, 2) + + d.dump_model(model, name_prefix="model") + + filenames = _get_filenames(tmp_path) + assert len(filenames) == 0 + + def test_filter(self, tmp_path): + d = _make_test_dumper( + tmp_path, + enable_model_value=True, + enable_model_grad=True, + filter="'weight' in name", + ) + model = torch.nn.Linear(4, 2) + x = torch.randn(3, 4) + y = model(x).sum() + y.backward() + + d.dump_model(model, name_prefix="model") + + _assert_files( + _get_filenames(tmp_path), + exist=["model__weight", "grad__model__weight"], + not_exist=["model__bias", "grad__model__bias"], + ) + + def test_grad_file_content(self, tmp_path): + d = _make_test_dumper( + tmp_path, enable_model_grad=True, enable_model_value=False + ) + model = torch.nn.Linear(4, 2, bias=False) + x = torch.ones(1, 4) + y = model(x).sum() + y.backward() + + d.dump_model(model, name_prefix="p") + + path = _find_dump_file(tmp_path, name="grad__p__weight") + assert torch.equal(_load_dump(path)["value"], model.weight.grad) + + def test_disable_model_grad(self, tmp_path): + d = _make_test_dumper( + tmp_path, enable_model_value=True, enable_model_grad=False + ) + model = torch.nn.Linear(4, 2) + x = torch.randn(3, 4) + y = model(x).sum() + y.backward() + + d.dump_model(model, name_prefix="model") + + filenames = _get_filenames(tmp_path) + assert all("grad" not in f for f in filenames) + + def test_parameter_saved_as_parameter(self, tmp_path): + d = _make_test_dumper( + tmp_path, enable_model_value=True, enable_model_grad=False + ) + model = torch.nn.Linear(4, 2, bias=False) + + d.dump_model(model, name_prefix="p") + + path = _find_dump_file(tmp_path, name="p__weight") + loaded = _load_dump(path) + assert isinstance(loaded["value"], torch.nn.Parameter) + assert torch.equal(loaded["value"], model.weight) + + def test_unpicklable_parameter_falls_back_to_data(self, tmp_path): + class BadParam(torch.nn.Parameter): + def __reduce_ex__(self, protocol): + raise RuntimeError("not pickleable") + + d = _make_test_dumper( + tmp_path, enable_model_value=True, enable_model_grad=False + ) + model = torch.nn.Linear(4, 2, bias=False) + model.weight = BadParam(model.weight.data) + + d.dump_model(model, name_prefix="p") + + path = _find_dump_file(tmp_path, name="p__weight") + loaded = _load_dump(path) + assert isinstance(loaded["value"], torch.Tensor) + assert not isinstance(loaded["value"], torch.nn.Parameter) + assert torch.equal(loaded["value"], model.weight.data) + + def test_disable_model_value(self, tmp_path): + d = _make_test_dumper( + tmp_path, enable_model_grad=True, enable_model_value=False + ) + model = torch.nn.Linear(4, 2, bias=False) + x = torch.ones(1, 4) + y = model(x).sum() + y.backward() + + d.dump_model(model, name_prefix="model") + + filenames = _get_filenames(tmp_path) + assert all("grad" in f for f in filenames) + + +class TestParallelRankInFilename: + def test_config_default_false(self): + """include_parallel_rank_in_filename defaults to False.""" + assert DumperConfig().include_parallel_rank_in_filename is False + + def test_config_from_kv_pairs(self): + """include_parallel_rank_in_filename is parsed as a bool from kv pairs.""" + cfg = DumperConfig.from_kv_pairs(["include_parallel_rank_in_filename=true"]) + assert cfg.include_parallel_rank_in_filename is True + + def test_collect_tags_merges_keys_across_plugins(self, monkeypatch): + """_collect_parallel_rank_tags keeps only rank keys, merging across plugins.""" + plugin_a = type( + "PluginA", + (), + {"collect_parallel_info": lambda self: {"pp_rank": 1, "ignored": 9}}, + )() + plugin_b = type( + "PluginB", + (), + {"collect_parallel_info": lambda self: {"tp_rank": 2, "cp_rank": 3}}, + )() + monkeypatch.setattr( + "sglang.srt.debug_utils.dumper._plugins", [plugin_a, plugin_b] + ) + + tags = _collect_parallel_rank_tags() + assert tags == {"pp_rank": 1, "tp_rank": 2, "cp_rank": 3} + + def test_collect_tags_first_plugin_wins_on_conflict(self, monkeypatch): + """When two plugins report the same rank key, the first plugin wins.""" + plugin_a = type( + "PluginA", (), {"collect_parallel_info": lambda self: {"pp_rank": 1}} + )() + plugin_b = type( + "PluginB", (), {"collect_parallel_info": lambda self: {"pp_rank": 7}} + )() + monkeypatch.setattr( + "sglang.srt.debug_utils.dumper._plugins", [plugin_a, plugin_b] + ) + + assert _collect_parallel_rank_tags() == {"pp_rank": 1} + + def test_collect_tags_skips_empty_plugin_info(self, monkeypatch): + """Plugins that report no parallel info are skipped without error.""" + plugin_empty = type( + "PluginEmpty", (), {"collect_parallel_info": lambda self: {}} + )() + plugin_real = type( + "PluginReal", (), {"collect_parallel_info": lambda self: {"tp_rank": 4}} + )() + monkeypatch.setattr( + "sglang.srt.debug_utils.dumper._plugins", [plugin_empty, plugin_real] + ) + + assert _collect_parallel_rank_tags() == {"tp_rank": 4} + + def test_disabled_filename_has_no_rank_tags(self, tmp_path, monkeypatch): + """When disabled, dump filenames do not include parallel-rank tags.""" + monkeypatch.setattr( + _SGLangPlugin, + "collect_parallel_info", + lambda self: {"pp_rank": 2, "tp_rank": 3}, + ) + + d = _make_test_dumper(tmp_path, include_parallel_rank_in_filename=False) + d.dump("hidden", torch.randn(3)) + + filenames = _get_filenames(tmp_path) + assert filenames + assert all("pp_rank=" not in f and "tp_rank=" not in f for f in filenames) + + def test_enabled_filename_includes_rank_tags(self, tmp_path, monkeypatch): + """When enabled, dump filenames include the collected parallel-rank tags.""" + monkeypatch.setattr( + _SGLangPlugin, + "collect_parallel_info", + lambda self: {"pp_rank": 2, "tp_rank": 3}, + ) + + d = _make_test_dumper(tmp_path, include_parallel_rank_in_filename=True) + d.dump("hidden", torch.randn(3)) + + filenames = _get_filenames(tmp_path) + assert any("pp_rank=2" in f and "tp_rank=3" in f for f in filenames) + + +class TestTransformModelParamName: + def test_base_plugin_returns_none(self): + """The default plugin hook keeps the original name (returns None).""" + plugin = _SGLangPlugin() + assert ( + plugin.transform_model_param_name(torch.nn.Linear(2, 2), "layers.0.weight") + is None + ) + + def test_dump_model_keeps_name_without_transform(self, tmp_path): + """With no plugin rewriting names, dump_model uses the original param name.""" + model = torch.nn.Module() + model.layers = torch.nn.ModuleList([torch.nn.Linear(2, 2, bias=False)]) + d = _make_test_dumper( + tmp_path, enable_model_value=True, enable_model_grad=False + ) + + d.dump_model(model, name_prefix="m") + + _assert_files(_get_filenames(tmp_path), exist=["m__layers.0.weight"]) + + def test_dump_model_applies_plugin_transform(self, tmp_path, monkeypatch): + """dump_model rewrites param names through the plugin transform hook.""" + + def _shift_layers(self, model, param_name): + return re.sub( + r"layers\.(\d+)", lambda m: f"layers.{int(m.group(1)) + 4}", param_name + ) + + monkeypatch.setattr(_SGLangPlugin, "transform_model_param_name", _shift_layers) + + model = torch.nn.Module() + model.layers = torch.nn.ModuleList([torch.nn.Linear(2, 2, bias=False)]) + d = _make_test_dumper( + tmp_path, enable_model_value=True, enable_model_grad=False + ) + + d.dump_model(model, name_prefix="m") + + _assert_files( + _get_filenames(tmp_path), + exist=["m__layers.4.weight"], + not_exist=["m__layers.0.weight"], + ) + + def test_get_model_config_unwraps_module_chain(self): + """_get_model_config peels nested .module wrappers to find .config.""" + config = object() + leaf = type("Leaf", (), {"config": config})() + wrapped = type("W", (), {"module": type("W2", (), {"module": leaf})()})() + assert _MegatronPlugin._get_model_config(wrapped) is config + + def test_get_model_config_returns_none_when_absent(self): + """_get_model_config returns None when no .config is reachable.""" + assert _MegatronPlugin._get_model_config(object()) is None + + +class _FakeMpu: + _pp_size = 2 + + @classmethod + def get_pipeline_model_parallel_world_size(cls): + return cls._pp_size + + +class TestMegatronTransformModelParamName: + @pytest.fixture(autouse=True) + def _patch_megatron(self, monkeypatch): + monkeypatch.setattr(_MegatronPlugin, "_available", True) + monkeypatch.setattr(_MegatronPlugin, "_mpu", _FakeMpu, raising=False) + monkeypatch.setattr( + _MegatronPlugin, + "_get_model_config", + staticmethod(lambda model: object()), + ) + monkeypatch.setattr( + _MegatronPlugin, + "_get_transformer_layer_offset", + staticmethod(lambda config: 4), + ) + + def test_remaps_local_layer_index_to_global(self): + """layers.N is shifted by the PP-stage offset; other tokens untouched.""" + plugin = _MegatronPlugin() + result = plugin.transform_model_param_name(object(), "decoder.layers.0.weight") + assert result == "decoder.layers.4.weight" + + def test_remaps_all_layer_occurrences(self): + """Every ``layers.N`` occurrence in the name is shifted.""" + plugin = _MegatronPlugin() + result = plugin.transform_model_param_name(object(), "layers.1.x.layers.2.y") + assert result == "layers.5.x.layers.6.y" + + def test_returns_none_when_not_available(self, monkeypatch): + """No transform when megatron is unavailable.""" + monkeypatch.setattr(_MegatronPlugin, "_available", False) + plugin = _MegatronPlugin() + assert plugin.transform_model_param_name(object(), "layers.0.weight") is None + + def test_returns_none_when_pp_size_one(self, monkeypatch): + """No transform without pipeline parallelism (pp_size == 1).""" + monkeypatch.setattr(_FakeMpu, "_pp_size", 1) + plugin = _MegatronPlugin() + assert plugin.transform_model_param_name(object(), "layers.0.weight") is None + monkeypatch.setattr(_FakeMpu, "_pp_size", 2) + + def test_returns_none_when_offset_zero(self, monkeypatch): + """A zero offset (e.g. first PP stage) leaves the name unchanged (None).""" + monkeypatch.setattr( + _MegatronPlugin, + "_get_transformer_layer_offset", + staticmethod(lambda config: 0), + ) + plugin = _MegatronPlugin() + assert plugin.transform_model_param_name(object(), "layers.0.weight") is None + + +class TestCleanup: + def test_cleanup_removes_old_dumps(self, tmp_path): + old_dir = tmp_path / "dump_old" + old_dir.mkdir() + (old_dir / "dummy.pt").touch() + + dumper = _make_test_dumper(tmp_path, cleanup_previous=True) + dumper.dump("new_tensor", torch.randn(3, 3)) + + assert not old_dir.exists() + _assert_files(_get_filenames(tmp_path), exist=["new_tensor"]) + + def test_cleanup_removes_exp_name_dir(self, tmp_path): + exp_name = "my_custom_exp" + old_exp_dir = tmp_path / exp_name + old_exp_dir.mkdir() + (old_exp_dir / "old_data.pt").touch() + + dumper = _make_test_dumper(tmp_path, exp_name=exp_name, cleanup_previous=True) + dumper.dump("new_tensor", torch.randn(3, 3)) + + assert not (tmp_path / exp_name / "old_data.pt").exists() + _assert_files(_get_filenames(tmp_path), exist=["new_tensor"]) + + def test_cleanup_removes_both_dump_prefix_and_exp_name(self, tmp_path): + old_dump = tmp_path / "dump_old" + old_dump.mkdir() + (old_dump / "dummy.pt").touch() + + exp_name = "custom_run" + old_exp = tmp_path / exp_name + old_exp.mkdir() + (old_exp / "stale.pt").touch() + + dumper = _make_test_dumper(tmp_path, exp_name=exp_name, cleanup_previous=True) + dumper.dump("new_tensor", torch.randn(3, 3)) + + assert not old_dump.exists() + assert not (tmp_path / exp_name / "stale.pt").exists() + _assert_files(_get_filenames(tmp_path), exist=["new_tensor"]) + + def test_no_cleanup_by_default(self, tmp_path): + old_dir = tmp_path / "dump_old" + old_dir.mkdir() + (old_dir / "dummy.pt").touch() + + dumper = _make_test_dumper(tmp_path) + dumper.dump("new_tensor", torch.randn(3, 3)) + + assert old_dir.exists() + _assert_files(_get_filenames(tmp_path), exist=["new_tensor"]) + + +class TestReset: + def test_reset_clears_state(self, tmp_path): + d = _make_test_dumper(tmp_path) + d.set_ctx(layer_id=1) + d.dump("before_reset", torch.randn(3, 3)) + + d.reset() + + assert d._state.dump_index == 0 + assert d._state.step == 0 + assert d._state.global_ctx == {} + + def test_dump_works_after_reset(self, tmp_path): + d = _make_test_dumper(tmp_path) + d.dump("pre", torch.randn(3, 3)) + + d.reset() + d.dump("post", torch.randn(3, 3)) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["pre", "post"]) + post_file = _find_dump_file(tmp_path, name="post") + assert "dump_index=1" in post_file.name + + def test_cleanup_previous_re_triggers_after_reset(self, tmp_path): + """Miles pattern: reset() + configure(cleanup_previous=True) should re-clean.""" + exp_alpha = "exp_alpha" + exp_beta = "exp_beta" + + (tmp_path / exp_alpha).mkdir() + (tmp_path / exp_alpha / "stale.pt").touch() + (tmp_path / exp_beta).mkdir() + (tmp_path / exp_beta / "stale.pt").touch() + + d = _make_test_dumper(tmp_path, exp_name=exp_alpha, cleanup_previous=True) + d.dump("phase1", torch.randn(2, 2)) + + d.reset() + d.configure(exp_name=exp_beta, cleanup_previous=True) + d.dump("phase2", torch.randn(2, 2)) + + assert not (tmp_path / exp_alpha / "stale.pt").exists() + assert not (tmp_path / exp_beta / "stale.pt").exists() + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["phase1", "phase2"]) + + def test_no_cleanup_when_config_false(self, tmp_path): + """cleanup_previous=False: handled stays False but no cleanup runs.""" + old_dir = tmp_path / "dump_old" + old_dir.mkdir() + (old_dir / "dummy.pt").touch() + + d = _make_test_dumper(tmp_path, cleanup_previous=False) + d.dump("tensor", torch.randn(2, 2)) + + assert old_dir.exists() + assert d._state.cleanup_previous_handled is False + + def test_multi_phase_switch(self, tmp_path): + """Simulate Miles multi-phase: configure → dump → reset → configure new phase → dump.""" + d = _make_test_dumper(tmp_path, cleanup_previous=True) + + d.configure(exp_name="fwd_only") + d.dump("weight", torch.randn(2, 2)) + d.step() + d.configure(enable=False) + + d.reset() + d.configure(exp_name="fwd_bwd", enable=True, cleanup_previous=True) + d.dump("weight", torch.randn(2, 2)) + d.step() + + fwd_only_files = list(Path(tmp_path).glob("fwd_only/*.pt")) + fwd_bwd_files = list(Path(tmp_path).glob("fwd_bwd/*.pt")) + assert len(fwd_only_files) > 0 + assert len(fwd_bwd_files) > 0 + assert d._state.step == 1 + assert d._state.dump_index == 1 + + def test_reset_removes_non_intrusive_hooks(self, tmp_path): + model = torch.nn.Sequential( + torch.nn.Linear(4, 4), + torch.nn.ReLU(), + torch.nn.Linear(4, 4), + ) + d = _make_test_dumper(tmp_path, non_intrusive_mode="all") + d.register_non_intrusive_dumper(model) + + x = torch.randn(2, 4) + with d.capture_output() as captured: + model(x) + assert len(captured) > 0 + + d.reset() + d.configure(enable=True, dir=str(tmp_path), non_intrusive_mode="all") + + with d.capture_output() as captured_after: + model(x) + assert len(captured_after) == 0 + + def test_reset_removes_non_intrusive_hooks_multiple_models(self, tmp_path): + model_a = torch.nn.Sequential( + torch.nn.Linear(4, 4), + torch.nn.ReLU(), + ) + model_b = torch.nn.Sequential( + torch.nn.Linear(4, 4), + torch.nn.ReLU(), + ) + d = _make_test_dumper(tmp_path, non_intrusive_mode="all") + d.register_non_intrusive_dumper(model_a) + d.register_non_intrusive_dumper(model_b) + + x = torch.randn(2, 4) + with d.capture_output() as captured: + model_a(x) + model_b(x) + assert len(captured) > 0 + + d.reset() + d.configure(enable=True, dir=str(tmp_path), non_intrusive_mode="all") + + with d.capture_output() as captured_a: + model_a(x) + assert len(captured_a) == 0 + + with d.capture_output() as captured_b: + model_b(x) + assert len(captured_b) == 0 + + +def _dumper_worker(rank, http_port: int, stop_event): + """Minimal distributed dumper worker: configure, step (triggers ZMQ setup), then wait.""" + dumper.configure(enable=False, server_port=str(http_port)) + dumper.step() + stop_event.wait() + + +def _wait_for_dumper_http(url: str, timeout: float = 30) -> None: + deadline = time.time() + timeout + while time.time() < deadline: + try: + requests.post(f"{url}/dumper/configure", json={}, timeout=2) + return + except requests.ConnectionError: + time.sleep(0.5) + raise TimeoutError(f"Dumper HTTP server not reachable at {url}") + + +class TestZmqPortIsolation: + """Multiple independent dumper instances (each with 2 ranks) must not conflict on ZMQ ports.""" + + NUM_INSTANCES = 3 + + def test_concurrent_instances_no_port_conflict(self): + ports = [ + find_available_port(40000 + i * 1000) for i in range(self.NUM_INSTANCES) + ] + stop_events = [] + threads = [] + ctx = multiprocessing.get_context("spawn") + + for port in ports: + stop_event = ctx.Event() + stop_events.append(stop_event) + thread = threading.Thread( + target=run_distributed_test, + args=(_dumper_worker,), + kwargs={"http_port": port, "stop_event": stop_event}, + ) + thread.start() + threads.append(thread) + + try: + for port in ports: + _wait_for_dumper_http(f"http://127.0.0.1:{port}") + + for i, port in enumerate(ports): + resp = requests.post( + f"http://127.0.0.1:{port}/dumper/get_state", json={} + ) + resp.raise_for_status() + states = resp.json() + assert ( + len(states) == 2 + ), f"Instance {i} (port {port}): expected 2 ranks, got {len(states)}" + finally: + for event in stop_events: + event.set() + for thread in threads: + thread.join(timeout=10) + + +class TestDumperHttp: + """Test /dumper/* HTTP control — parametrized over standalone vs sglang server.""" + + @pytest.fixture(scope="class", params=["standalone", "sglang"]) + def dumper_http_url(self, request): + if request.param == "standalone": + http_port = find_available_port(40000) + base_url = f"http://127.0.0.1:{http_port}" + stop_event = multiprocessing.get_context("spawn").Event() + thread = threading.Thread( + target=run_distributed_test, + args=(_dumper_worker,), + kwargs={"http_port": http_port, "stop_event": stop_event}, + ) + thread.start() + try: + _wait_for_dumper_http(base_url) + yield base_url + finally: + stop_event.set() + thread.join(timeout=10) + else: + base_url = DEFAULT_URL_FOR_TEST + env = {**os.environ, "DUMPER_SERVER_PORT": "reuse"} + proc = popen_launch_server( + "Qwen/Qwen3-0.6B", + base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=["--max-total-tokens", "128"], + env=env, + ) + try: + yield base_url + finally: + kill_process_tree(proc.pid) + + @staticmethod + def _post(base_url: str, method: str, **kwargs) -> list[dict]: + resp = requests.post(f"{base_url}/dumper/{method}", json=kwargs or None) + resp.raise_for_status() + states = resp.json() + assert isinstance(states, list) and len(states) >= 1 + return states + + @staticmethod + def _assert_all_ranks(states: list[dict], path: str, expected): + """Assert that ``state[path]`` equals ``expected`` on every rank.""" + keys = path.split(".") + for rank, state in enumerate(states): + val = state + for k in keys: + val = val[k] + assert ( + val == expected + ), f"rank {rank}: {path}={val!r}, expected {expected!r}" + + def test_configure_enable_toggle(self, dumper_http_url: str): + for enable in [True, False]: + self._post(dumper_http_url, "configure", enable=enable) + states = self._post(dumper_http_url, "get_state") + self._assert_all_ranks(states, "config.enable", enable) + + def test_configure_multi_field(self, dumper_http_url: str): + self._post( + dumper_http_url, + "configure", + enable=True, + filter="layer_id == 0", + dir="/tmp/test_http", + ) + states = self._post(dumper_http_url, "get_state") + self._assert_all_ranks(states, "config.enable", True) + self._assert_all_ranks(states, "config.filter", "layer_id == 0") + self._assert_all_ranks(states, "config.dir", "/tmp/test_http") + + def test_configure_clear_optional(self, dumper_http_url: str): + self._post(dumper_http_url, "configure", filter="layer_id == 0") + self._post(dumper_http_url, "configure", filter=None) + states = self._post(dumper_http_url, "get_state") + self._assert_all_ranks(states, "config.filter", None) + + def test_reset(self, dumper_http_url: str): + self._post(dumper_http_url, "configure", enable=True) + self._post(dumper_http_url, "reset") + states = self._post(dumper_http_url, "get_state") + self._assert_all_ranks(states, "dump_index", 0) + self._assert_all_ranks(states, "step", 0) + + def test_get_state(self, dumper_http_url: str): + self._post( + dumper_http_url, + "configure", + enable=True, + filter="layer_id is not None and layer_id < 3", + ) + states = self._post(dumper_http_url, "get_state") + self._assert_all_ranks(states, "config.enable", True) + self._assert_all_ranks( + states, "config.filter", "layer_id is not None and layer_id < 3" + ) + for state in states: + assert "dump_index" in state + assert "step" in state + + def test_all_ranks_consistent(self, dumper_http_url: str): + self._post(dumper_http_url, "configure", enable=True, dir="/tmp/multi") + states = self._post(dumper_http_url, "get_state") + configs = [s["config"] for s in states] + for rank_config in configs[1:]: + assert rank_config == configs[0], f"rank configs diverged: {configs}" + + def test_error_unknown_field(self, dumper_http_url: str): + resp = requests.post( + f"{dumper_http_url}/dumper/configure", + json={"nonexistent_field": 123}, + ) + assert resp.status_code == 400 + + def test_error_unknown_method(self, dumper_http_url: str): + resp = requests.post( + f"{dumper_http_url}/dumper/nonexistent", + json={}, + ) + assert resp.status_code == 400 + + def test_error_wrong_type(self, dumper_http_url: str): + resp = requests.post( + f"{dumper_http_url}/dumper/configure", + json={"enable": "not_a_bool"}, + ) + assert resp.status_code == 400 + + +class TestRegisterForwardHookOrReplaceFn: + def test_unknown_mode_raises(self): + module = torch.nn.Linear(4, 4) + with pytest.raises(ValueError, match="Unknown mode"): + _register_forward_hook_or_replace_fn( + module, + pre_hook=lambda _mod, _input: None, + hook=lambda _mod, _input, _output: None, + mode="bad", + ) + + +class _NonIntrusiveTestBase: + _PREFIX = "non_intrusive__" + + @staticmethod + def _assert_captured_contains( + captured: dict, expected: list[str], prefix: str = "non_intrusive__" + ) -> None: + for suffix in expected: + key = f"{prefix}{suffix}" + assert key in captured, f"missing {key}" + + @staticmethod + def _wrap_as_outer(inner_cls: type) -> torch.nn.Module: + """Wrap an inner module class as OuterModel.model, mimicking typical model nesting.""" + + class OuterModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.model = inner_cls() + + def forward(self, *args, **kwargs): + return self.model(*args, **kwargs) + + return OuterModel() + + @staticmethod + def _make_dumper(tmp_path, **overrides) -> "_Dumper": + return _make_test_dumper(tmp_path, non_intrusive_mode="all", **overrides) + + def _run(self, tmp_path, inner_cls, **dumper_overrides): + d = self._make_dumper(tmp_path, **dumper_overrides) + model = self._wrap_as_outer(inner_cls) + d.register_non_intrusive_dumper(model) + x = torch.randn(2, 4) + with d.capture_output() as captured: + output = model(x) + return captured, x, output + + +class TestNonIntrusiveDumper(_NonIntrusiveTestBase): + """Tests for mode='all' — hooks on every module, non_intrusive__ prefix.""" + + def test_basic_inputs_and_outputs(self, tmp_path): + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(4, 4) + self.relu = torch.nn.ReLU() + + def forward(self, x): + return self.relu(self.linear(x)) + + captured, x, output = self._run(tmp_path, Inner) + + self._assert_captured_contains( + captured, + [ + "output", + "inputs.0", + "model.output", + "model.inputs.0", + "model.linear.output", + "model.linear.inputs.0", + "model.relu.output", + "model.relu.inputs.0", + ], + ) + P = self._PREFIX + assert torch.allclose(captured[f"{P}output"]["value"], output) + + def test_inputs_dumped_before_forward(self, tmp_path): + """Inputs are captured *before* forward(); in-place mutation must not affect them.""" + + class Mutator(torch.nn.Module): + def forward(self, x): + x.fill_(999.0) + return x + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.mutator = Mutator() + + def forward(self, x): + return self.mutator(x) + + d = self._make_dumper(tmp_path) + model = self._wrap_as_outer(Inner) + d.register_non_intrusive_dumper(model) + + x = torch.randn(2, 4) + original_x = x.clone() + with d.capture_output() as captured: + model(x) + + P = self._PREFIX + dumped_input = captured[f"{P}model.mutator.inputs.0"]["value"] + assert torch.allclose(dumped_input, original_x), ( + f"pre-hook should capture inputs before forward mutates them; " + f"got {dumped_input} but expected {original_x}" + ) + + dumped_output = captured[f"{P}model.mutator.output"]["value"] + assert ( + dumped_output == 999.0 + ).all(), "post-hook should capture outputs after forward" + + def test_hooks_all_module_levels(self, tmp_path): + class Attention(torch.nn.Module): + def __init__(self): + super().__init__() + self.qkv_proj = torch.nn.Linear(4, 12) + self.o_proj = torch.nn.Linear(4, 4) + + def forward(self, x): + _qkv = self.qkv_proj(x) + return self.o_proj(x) + + class Layer(torch.nn.Module): + def __init__(self): + super().__init__() + self.self_attn = Attention() + self.mlp = torch.nn.Linear(4, 4) + + def forward(self, x): + x = self.self_attn(x) + return self.mlp(x) + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.layers = torch.nn.ModuleList([Layer()]) + + def forward(self, x): + for layer in self.layers: + x = layer(x) + return x + + captured, x, output = self._run(tmp_path, Inner) + + self._assert_captured_contains( + captured, + [ + "output", + "model.output", + "model.layers.0.output", + "model.layers.0.self_attn.output", + "model.layers.0.self_attn.qkv_proj.output", + "model.layers.0.self_attn.o_proj.output", + "model.layers.0.mlp.output", + "model.layers.0.self_attn.qkv_proj.inputs.0", + "model.layers.0.self_attn.o_proj.inputs.0", + "model.layers.0.mlp.inputs.0", + ], + ) + P = self._PREFIX + assert f"{P}model.layers.output" not in captured + + def test_multi_tensor_tuple_output(self, tmp_path): + class TupleModule(torch.nn.Module): + def forward(self, x): + return x, x * 2 + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.split = TupleModule() + self.linear = torch.nn.Linear(4, 4) + + def forward(self, x): + a, b = self.split(x) + return self.linear(a + b) + + captured, x, output = self._run(tmp_path, Inner) + + assert "non_intrusive__model.split.output.0" in captured + assert "non_intrusive__model.split.output.1" in captured + assert torch.allclose( + captured["non_intrusive__model.split.output.0"]["value"], x + ) + + def test_single_tensor_tuple_collapses(self, tmp_path): + class SingleTupleModule(torch.nn.Module): + def forward(self, x): + return (x * 3,) + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.wrap = SingleTupleModule() + + def forward(self, x): + return self.wrap(x)[0] + + captured, x, output = self._run(tmp_path, Inner) + + assert "non_intrusive__model.wrap.output" in captured + assert "non_intrusive__model.wrap.output.0" not in captured + + def test_multiple_forward_inputs(self, tmp_path): + class TwoInputModule(torch.nn.Module): + def forward(self, x, mask): + return x * mask + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.mul = TwoInputModule() + + def forward(self, x): + mask = torch.ones_like(x) + return self.mul(x, mask) + + captured, x, output = self._run(tmp_path, Inner) + + assert "non_intrusive__model.mul.inputs.0" in captured + assert "non_intrusive__model.mul.inputs.1" in captured + + def test_none_output_only_dumps_inputs(self, tmp_path): + class NoneModule(torch.nn.Module): + def forward(self, x): + return None + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.sink = NoneModule() + + def forward(self, x): + self.sink(x) + return x + + captured, x, output = self._run(tmp_path, Inner) + + assert "non_intrusive__model.sink.inputs.0" in captured + assert not any( + k.startswith("non_intrusive__model.sink.output") for k in captured + ) + + def test_non_tensor_value_silently_skipped(self, tmp_path): + class IntModule(torch.nn.Module): + def forward(self, x): + return 42 + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.const = IntModule() + + def forward(self, x): + self.const(x) + return x + + captured, x, output = self._run(tmp_path, Inner) + + assert "non_intrusive__model.const.inputs.0" in captured + assert not any( + k.startswith("non_intrusive__model.const.output") for k in captured + ) + + def test_root_module_name_no_malformed_dots(self, tmp_path): + d = self._make_dumper(tmp_path) + model = torch.nn.Linear(4, 4) + d.register_non_intrusive_dumper(model) + + x = torch.randn(2, 4) + with d.capture_output() as captured: + model(x) + + for key in captured: + assert not key.startswith("non_intrusive__."), f"malformed key: {key}" + assert ".." not in key, f"double dot in key: {key}" + + assert "non_intrusive__output" in captured + assert "non_intrusive__inputs.0" in captured + + def test_respects_dumper_filter(self, tmp_path): + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(4, 4) + self.relu = torch.nn.ReLU() + + def forward(self, x): + return self.relu(self.linear(x)) + + captured, x, output = self._run( + tmp_path, Inner, filter="name == 'non_intrusive__model.linear.output'" + ) + + assert "non_intrusive__model.linear.output" in captured + assert "non_intrusive__model.relu.output" not in captured + assert "non_intrusive__model.linear.inputs.0" not in captured + + def test_disabled_dumper_no_output(self, tmp_path): + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(4, 4) + + def forward(self, x): + return self.linear(x) + + d = self._make_dumper(tmp_path) + d.configure(enable=False) + model = self._wrap_as_outer(Inner) + d.register_non_intrusive_dumper(model) + + x = torch.randn(2, 4) + with d.capture_output() as captured: + model(x) + + assert len(captured) == 0 + + +def _make_forward_batch(): + from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode + + return ForwardBatch( + forward_mode=ForwardMode.DECODE, + batch_size=2, + input_ids=torch.tensor([10, 20]), + req_pool_indices=torch.zeros(2, dtype=torch.long), + seq_lens=torch.tensor([5, 6]), + out_cache_loc=torch.zeros(2, dtype=torch.long), + seq_lens_sum=11, + positions=torch.tensor([0, 1]), + ) + + +class TestNonIntrusiveDumperConfigMode(_NonIntrusiveTestBase): + @staticmethod + def _build_model() -> torch.nn.Module: + class SubLayer(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(4, 4) + + def forward(self, forward_batch): + return self.linear( + forward_batch.input_ids.float().unsqueeze(-1).expand(-1, 4) + ) + + class Root(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = SubLayer() + + def forward(self, forward_batch): + return self.layer(forward_batch) + + return Root() + + def _run(self, tmp_path, mode: str) -> tuple: + d = _make_test_dumper(tmp_path, non_intrusive_mode=mode) + model = self._build_model() + d.register_non_intrusive_dumper(model) + forward_batch = _make_forward_batch() + with d.capture_output() as captured: + model(forward_batch) + return captured, forward_batch + + def test_off_mode(self, tmp_path): + captured, _ = self._run(tmp_path, "off") + assert len(captured) == 0 + + def test_core_mode(self, tmp_path): + captured, fb = self._run(tmp_path, "core") + + # core fields dumped with clean names + assert "input_ids" in captured + assert "positions" in captured + assert "seq_lens" in captured + assert torch.equal(captured["input_ids"]["value"], fb.input_ids) + assert torch.equal(captured["positions"]["value"], fb.positions) + assert torch.equal(captured["seq_lens"]["value"], fb.seq_lens) + + # nothing with non_intrusive__ prefix + assert not any(k.startswith("non_intrusive__") for k in captured) + + def test_all_mode(self, tmp_path): + captured, fb = self._run(tmp_path, "all") + + # core fields dumped with clean names + assert "input_ids" in captured + assert "positions" in captured + assert "seq_lens" in captured + assert torch.equal(captured["input_ids"]["value"], fb.input_ids) + assert torch.equal(captured["positions"]["value"], fb.positions) + assert torch.equal(captured["seq_lens"]["value"], fb.seq_lens) + + # core fields NOT duplicated with prefix + for field in ("input_ids", "positions", "seq_lens"): + assert not any( + k.startswith("non_intrusive__") and k.endswith(field) for k in captured + ) + + # ForwardBatch skipped on sub-modules (no duplication) + assert not any( + k.startswith("non_intrusive__layer.inputs.") and "seq_lens" in k + for k in captured + ), f"ForwardBatch skipped on sub-module, got: {list(captured.keys())}" + + # regular tensor outputs on sub-modules still dumped + assert "non_intrusive__layer.linear.output" in captured + assert "non_intrusive__layer.output" in captured + + +class _LayerWithNumber(torch.nn.Module): + """Test helper: module with a ``layer_number`` attribute (Megatron style).""" + + def __init__(self, layer_number: int): + super().__init__() + self.layer_number = layer_number + self.linear = torch.nn.Linear(4, 4) + + def forward(self, x): + return self.linear(x) + + +class TestNonIntrusiveLayerIdCtx(_NonIntrusiveTestBase): + """Tests for automatic layer_id context injection via set_ctx.""" + + def test_layer_id_from_layer_number(self, tmp_path): + """Megatron PP: layer_number (1-based global) -> layer_id = layer_number - 1.""" + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.layers = torch.nn.ModuleList( + [_LayerWithNumber(10), _LayerWithNumber(11)] + ) + + def forward(self, x): + for layer in self.layers: + x = layer(x) + return x + + captured, x, output = self._run(tmp_path, Inner) + + layer0_key = "non_intrusive__model.layers.0.linear.output" + layer1_key = "non_intrusive__model.layers.1.linear.output" + assert layer0_key in captured + assert layer1_key in captured + assert captured[layer0_key]["meta"]["layer_id"] == 9 + assert captured[layer1_key]["meta"]["layer_id"] == 10 + + root_key = "non_intrusive__output" + assert root_key in captured + assert "layer_id" not in captured[root_key]["meta"] + + def test_layer_id_from_layer_id_attr(self, tmp_path): + """SGLang style: module has layer_id attribute directly.""" + + class Layer(torch.nn.Module): + def __init__(self, layer_id: int): + super().__init__() + self.layer_id = layer_id + self.linear = torch.nn.Linear(4, 4) + + def forward(self, x): + return self.linear(x) + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.layers = torch.nn.ModuleList([Layer(5)]) + + def forward(self, x): + for layer in self.layers: + x = layer(x) + return x + + captured, x, output = self._run(tmp_path, Inner) + + layer_key = "non_intrusive__model.layers.0.linear.output" + assert layer_key in captured + assert captured[layer_key]["meta"]["layer_id"] == 5 + + def test_layer_id_fallback_from_module_name(self, tmp_path): + """layers.N modules without layer_number/layer_id -> layer_id from module name.""" + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.layers = torch.nn.ModuleList( + [torch.nn.Linear(4, 4), torch.nn.Linear(4, 4)] + ) + + def forward(self, x): + for layer in self.layers: + x = layer(x) + return x + + captured, x, output = self._run(tmp_path, Inner) + + assert len(captured) > 0 + input_keys: list[str] = [ + k for k in captured if "model.layers." in k and "inputs" in k + ] + assert len(input_keys) > 0 + for key in input_keys: + meta = captured[key]["meta"] + assert "layer_id" in meta, f"{key} missing layer_id" + if "layers.0" in key: + assert meta["layer_id"] == 0 + elif "layers.1" in key: + assert meta["layer_id"] == 1 + + def test_filter_by_layer_id(self, tmp_path): + """filter='layer_id == 0' keeps only layer 0 dumps.""" + + class Inner(torch.nn.Module): + def __init__(self): + super().__init__() + self.layers = torch.nn.ModuleList( + [_LayerWithNumber(1), _LayerWithNumber(2)] + ) + + def forward(self, x): + for layer in self.layers: + x = layer(x) + return x + + captured, x, output = self._run(tmp_path, Inner, filter="layer_id == 0") + + layer0_keys = [k for k in captured if "layers.0" in k] + layer1_keys = [k for k in captured if "layers.1" in k] + assert len(layer0_keys) > 0, "layer 0 dumps should be kept" + assert len(layer1_keys) == 0, f"layer 1 dumps should be filtered: {layer1_keys}" + + +class TestDumperE2E: + def test_step_and_non_intrusive_hooks(self, tmp_path): + base_url = DEFAULT_URL_FOR_TEST + dump_dir = str(tmp_path) + env = { + **os.environ, + "DUMPER_SERVER_PORT": "reuse", + } + proc = popen_launch_server( + "Qwen/Qwen3-0.6B", + base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=["--tp", "2", "--max-total-tokens", "128"], + env=env, + ) + try: + states = requests.post(f"{base_url}/dumper/get_state", json={}).json() + assert len(states) == 2, f"Expected 2 ranks (tp=2), got {len(states)}" + for state in states: + assert state["config"]["enable"] is False + assert state["step"] == 0 + + requests.post( + f"{base_url}/dumper/configure", + json={"enable": True, "dir": dump_dir}, + ).raise_for_status() + + states = requests.post(f"{base_url}/dumper/get_state", json={}).json() + assert len(states) == 2 + for rank, state in enumerate(states): + assert ( + state["config"]["enable"] is True + ), f"rank {rank}: enable should be True after configure" + assert state["config"]["dir"] == dump_dir + + resp = requests.post( + f"{base_url}/generate", + json={"text": "Hello", "sampling_params": {"max_new_tokens": 8}}, + ) + assert resp.status_code == 200, f"Generate failed: {resp.text}" + + states = requests.post(f"{base_url}/dumper/get_state", json={}).json() + assert len(states) == 2 + steps = [s["step"] for s in states] + for rank, step in enumerate(steps): + assert step > 0, f"rank {rank}: step should be > 0, got {step}" + assert steps[0] == steps[1], f"step mismatch across ranks: {steps}" + + dump_files = list(Path(dump_dir).glob("dump_*/*.pt")) + assert len(dump_files) > 0, f"No dump files in {dump_dir}" + filenames = {f.name for f in dump_files} + + for field in ("input_ids", "positions", "rids"): + assert any(f"name={field}" in f for f in filenames), ( + f"Missing {field} dump from non-intrusive hooks, " + f"got: {sorted(filenames)[:10]}" + ) + + for rank in range(2): + assert any( + f"rank={rank}" in f for f in filenames + ), f"No dump files for rank {rank}" + + sample_file = dump_files[0] + loaded = torch.load(sample_file, map_location="cpu", weights_only=False) + assert isinstance(loaded, dict), f"Expected dict, got {type(loaded)}" + assert ( + "value" in loaded and "meta" in loaded + ), f"Missing value/meta keys: {loaded.keys()}" + assert "name" in loaded["meta"] + assert "rank" in loaded["meta"] + assert "step" in loaded["meta"] + + par = loaded["meta"].get("sglang_parallel_info", {}) + expected_keys = [ + "tp_rank", + "tp_size", + "pp_rank", + "pp_size", + "moe_ep_rank", + "moe_ep_size", + "moe_tp_rank", + "moe_tp_size", + "moe_dp_rank", + "moe_dp_size", + "enable_dp_attention", + "attn_tp_rank", + "attn_tp_size", + "attn_dp_rank", + "attn_dp_size", + "local_attn_dp_rank", + "local_attn_dp_size", + "attn_cp_rank", + "attn_cp_size", + ] + for key in expected_keys: + assert ( + key in par + ), f"Missing {key} in sglang_parallel_info, got: {sorted(par)}" + + rids_files = [f for f in dump_files if "name=rids" in f.name] + rids_loaded = torch.load( + rids_files[0], map_location="cpu", weights_only=False + ) + rids_value = rids_loaded["value"] + assert isinstance( + rids_value, list + ), f"rids should be a list, got {type(rids_value)}" + assert len(rids_value) > 0, "rids should be non-empty" + assert all( + isinstance(r, str) for r in rids_value + ), f"each rid should be a str, got {[type(r) for r in rids_value]}" + finally: + kill_process_tree(proc.pid) + + +class TestRegisterForwardHook: + @pytest.mark.parametrize("mode", ["hook", "replace_fn"]) + def test_handles_removable(self, mode): + call_log: list[str] = [] + + def pre_hook(_module, _args, _kwargs): + call_log.append("pre") + + def hook(_module, _input, _output): + call_log.append("post") + + module = torch.nn.Linear(4, 4) + handles = _register_forward_hook_or_replace_fn( + module, + pre_hook=pre_hook, + hook=hook, + mode=mode, + ) + + x = torch.randn(2, 4) + if mode == "hook": + module(x) + else: + module.forward(x) + assert call_log == ["pre", "post"] + + call_log.clear() + for h in handles: + h.remove() + + if mode == "hook": + module(x) + else: + module.forward(x) + assert call_log == [] + + @pytest.mark.parametrize("mode", ["hook", "replace_fn"]) + def test_kwargs_passed_to_pre_hook(self, mode): + received: list[tuple] = [] + + class KwargsModule(torch.nn.Module): + def forward(self, x, *, scale=1.0): + return x * scale + + def pre_hook(_module, _args, _kwargs): + received.append((_args, _kwargs)) + + def hook(_module, _input, _output): + pass + + module = KwargsModule() + _register_forward_hook_or_replace_fn( + module, + pre_hook=pre_hook, + hook=hook, + mode=mode, + ) + + x = torch.randn(2, 4) + if mode == "hook": + module(x, scale=2.0) + else: + module.forward(x, scale=2.0) + + assert len(received) == 1 + args, kwargs = received[0] + assert len(args) == 1 + assert torch.equal(args[0], x) + assert kwargs == {"scale": 2.0} + + def test_replace_fn_remove_asserts_on_rewrap(self): + module = torch.nn.Linear(4, 4) + handles = _register_forward_hook_or_replace_fn( + module, + pre_hook=lambda _m, _a, _kw: None, + hook=lambda _m, _i, _o: None, + mode="replace_fn", + ) + + module.forward = lambda *a, **kw: None + + with pytest.raises(AssertionError): + handles[0].remove() + + +class TestPluginCoreFields: + def test_sglang_core_fields(self): + plugin = _SGLangPlugin() + assert plugin.core_fields() == frozenset( + {"input_ids", "positions", "seq_lens", "req_pool_indices", "rids"} + ) + + def test_megatron_core_fields(self): + plugin = _MegatronPlugin() + assert plugin.core_fields() == frozenset( + {"input_ids", "position_ids", "cu_seqlens_q", "cu_seqlens_kv", "qkv_format"} + ) + + +class TestMegatronConvertValue: + @pytest.fixture(autouse=True) + def _patch_megatron(self, monkeypatch): + class FakePackedSeqParams: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + + monkeypatch.setattr(_MegatronPlugin, "_available", True) + monkeypatch.setattr( + _MegatronPlugin, "PackedSeqParams", FakePackedSeqParams, raising=False + ) + self._FakePackedSeqParams = FakePackedSeqParams + + def test_extracts_packed_seq_params(self): + plugin = _MegatronPlugin() + cu_q = torch.tensor([0, 3, 7]) + cu_kv = torch.tensor([0, 3, 7]) + value = self._FakePackedSeqParams( + cu_seqlens_q=cu_q, cu_seqlens_kv=cu_kv, qkv_format="thd" + ) + + result = plugin.convert_value(value, skip_forward_batch=False) + assert set(result.keys()) == {"cu_seqlens_q", "cu_seqlens_kv", "qkv_format"} + assert torch.equal(result["cu_seqlens_q"], cu_q) + assert torch.equal(result["cu_seqlens_kv"], cu_kv) + assert result["qkv_format"] == "thd" + + def test_non_packed_returns_none(self): + plugin = _MegatronPlugin() + assert plugin.convert_value(torch.randn(4), skip_forward_batch=False) is None + assert plugin.convert_value("hello", skip_forward_batch=False) is None + + +class TestNonIntrusiveKwargsModel(_NonIntrusiveTestBase): + def test_kwargs_core_fields(self, tmp_path): + class KwargsModel(torch.nn.Module): + def forward(self, *, input_ids, position_ids): + return input_ids + position_ids + + model = KwargsModel() + d = _make_test_dumper(tmp_path, non_intrusive_mode="core") + d.register_non_intrusive_dumper(model) + + ids = torch.randn(4) + pos = torch.randn(4) + with d.capture_output() as captured: + model(input_ids=ids, position_ids=pos) + + assert "input_ids" in captured + assert "position_ids" in captured + assert torch.equal(captured["input_ids"]["value"], ids) + assert torch.equal(captured["position_ids"]["value"], pos) + + def test_kwargs_all_mode(self, tmp_path): + class KwargsModel(torch.nn.Module): + def forward(self, *, input_ids, position_ids, custom_value): + return input_ids + position_ids + custom_value + + model = KwargsModel() + d = _make_test_dumper(tmp_path, non_intrusive_mode="all") + d.register_non_intrusive_dumper(model) + + ids = torch.randn(4) + pos = torch.randn(4) + custom = torch.randn(4) + with d.capture_output() as captured: + model(input_ids=ids, position_ids=pos, custom_value=custom) + + assert "input_ids" in captured + assert "position_ids" in captured + + P = self._PREFIX + assert f"{P}inputs.custom_value" in captured + + def test_mixed_args_and_kwargs(self, tmp_path): + class MixedModel(torch.nn.Module): + def forward(self, x, *, input_ids): + return x + input_ids + + model = MixedModel() + d = _make_test_dumper(tmp_path, non_intrusive_mode="all") + d.register_non_intrusive_dumper(model) + + x = torch.randn(4) + ids = torch.randn(4) + with d.capture_output() as captured: + model(x, input_ids=ids) + + assert "input_ids" in captured + + P = self._PREFIX + assert f"{P}inputs.0" in captured + + def test_packed_seq_params_core_fields(self, tmp_path, monkeypatch): + class FakePackedSeqParams: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + + monkeypatch.setattr(_MegatronPlugin, "_available", True) + monkeypatch.setattr( + _MegatronPlugin, "PackedSeqParams", FakePackedSeqParams, raising=False + ) + + class MegatronLikeModel(torch.nn.Module): + def forward(self, *, input_ids, packed_seq_params): + return input_ids + + model = MegatronLikeModel() + d = _make_test_dumper(tmp_path, non_intrusive_mode="core") + d.register_non_intrusive_dumper(model) + + ids = torch.randn(4) + cu_q = torch.tensor([0, 3, 7]) + cu_kv = torch.tensor([0, 3, 7]) + psp = FakePackedSeqParams( + cu_seqlens_q=cu_q, cu_seqlens_kv=cu_kv, qkv_format="thd" + ) + with d.capture_output() as captured: + model(input_ids=ids, packed_seq_params=psp) + + assert "input_ids" in captured + assert torch.equal(captured["input_ids"]["value"], ids) + assert "cu_seqlens_q" in captured + assert torch.equal(captured["cu_seqlens_q"]["value"], cu_q) + assert "cu_seqlens_kv" in captured + assert torch.equal(captured["cu_seqlens_kv"]["value"], cu_kv) + assert "qkv_format" in captured + assert captured["qkv_format"]["value"] == "thd" + + +class TestDumperDims: + def test_dims_in_meta_not_filename(self, tmp_path) -> None: + dumper = _make_test_dumper(tmp_path) + tensor = torch.randn(4, 8) + dumper.dump("hidden", tensor, dims="b h(tp)") + dumper.step() + + exp_dir = tmp_path / dumper._config.exp_name + pt_files = list(exp_dir.glob("*.pt")) + assert len(pt_files) == 1 + + assert "dims" not in pt_files[0].stem + + data = torch.load(pt_files[0], weights_only=False) + assert "dims" in data["meta"] + assert data["meta"]["dims"] == "b h(tp)" + + def test_dims_grad_override(self, tmp_path) -> None: + dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(tmp_path), + enable_grad=True, + ) + ) + + tensor = torch.randn(4, 8, requires_grad=True) + dumper.dump("hidden", tensor, dims="b h(tp)", dims_grad="b h(tp:partial)") + dumper.step() + + tensor.backward(torch.ones_like(tensor)) + + exp_dir = tmp_path / dumper._config.exp_name + pt_files = sorted(exp_dir.glob("*.pt")) + assert len(pt_files) == 2 + + value_file = [f for f in pt_files if "grad__" not in f.stem][0] + grad_file = [f for f in pt_files if "grad__" in f.stem][0] + + value_data = torch.load(value_file, weights_only=False) + assert value_data["meta"]["dims"] == "b h(tp)" + assert value_data["meta"]["dims_grad"] == "b h(tp:partial)" + + grad_data = torch.load(grad_file, weights_only=False) + assert grad_data["meta"]["dims"] == "b h(tp:partial)" + + def test_dims_grad_inherits(self, tmp_path) -> None: + dumper = _Dumper( + config=DumperConfig( + enable=True, + dir=str(tmp_path), + enable_grad=True, + ) + ) + + tensor = torch.randn(4, 8, requires_grad=True) + dumper.dump("hidden", tensor, dims="b h(tp)") + dumper.step() + + tensor.backward(torch.ones_like(tensor)) + + exp_dir = tmp_path / dumper._config.exp_name + grad_file = [f for f in exp_dir.glob("*.pt") if "grad__" in f.stem][0] + grad_data = torch.load(grad_file, weights_only=False) + assert grad_data["meta"]["dims"] == "b h(tp)" + + +class TestCtxDecorator: + def test_ctx_dynamic_lambda(self, tmp_path: Path) -> None: + d = _make_test_dumper(tmp_path) + + class FakeLayer: + def __init__(self, layer_id: int) -> None: + self.layer_id = layer_id + + @d.ctx(lambda self: dict(layer_id=self.layer_id)) + def forward(self, x: torch.Tensor) -> torch.Tensor: + d.dump("hidden", x) + return x + + layer = FakeLayer(layer_id=42) + layer.forward(torch.randn(3)) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["layer_id=42"]) + + def test_ctx_static_kwargs(self, tmp_path: Path) -> None: + d = _make_test_dumper(tmp_path) + + @d.ctx(phase="decode") + def decode_step(x: torch.Tensor) -> torch.Tensor: + d.dump("step_out", x) + return x + + decode_step(torch.randn(3)) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["phase=decode"]) + + def test_ctx_clears_on_exception(self, tmp_path: Path) -> None: + d = _make_test_dumper(tmp_path) + + @d.ctx(phase="train") + def buggy_fn() -> None: + raise RuntimeError("boom") + + with pytest.raises(RuntimeError, match="boom"): + buggy_fn() + + assert d._state.global_ctx == {} + + def test_ctx_rejects_mixed_args(self) -> None: + d = _make_test_dumper("/tmp") + + with pytest.raises(ValueError, match="cannot mix"): + d.ctx(lambda self: dict(a=1), phase="x") + + def test_ctx_rejects_empty_args(self) -> None: + d = _make_test_dumper("/tmp") + + with pytest.raises(ValueError, match="must provide"): + d.ctx() + + +class TestRecomputeStatus: + def test_disabled_by_default(self, tmp_path: Path) -> None: + d = _make_test_dumper(tmp_path) + tensor = torch.randn(3, 3) + d.dump("test_tensor", tensor) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["recompute_status=disabled"]) + + def test_recompute_status_in_embedded_meta(self, tmp_path: Path) -> None: + d = _make_test_dumper(tmp_path) + tensor = torch.randn(3, 3) + d.dump("test_tensor", tensor) + + path = _find_dump_file(tmp_path, rank=0, name="test_tensor") + raw = _load_dump(path) + assert raw["meta"]["recompute_status"] == "disabled" + + def test_recompute_status_recompute(self, tmp_path: Path, monkeypatch) -> None: + import sglang.srt.debug_utils.dumper as dumper_mod + + monkeypatch.setattr( + dumper_mod, "_detect_recompute_status", lambda: _RecomputeStatus.RECOMPUTE + ) + + d = _make_test_dumper(tmp_path) + tensor = torch.randn(3, 3) + d.dump("test_tensor", tensor) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["recompute_status=recompute"]) + + path = _find_dump_file(tmp_path, rank=0, name="test_tensor") + raw = _load_dump(path) + assert raw["meta"]["recompute_status"] == "recompute" + assert raw["meta"]["recompute_pseudo_rank"] == 1 + assert raw["meta"]["recompute_pseudo_size"] == 2 + + def test_recompute_status_original(self, tmp_path: Path, monkeypatch) -> None: + import sglang.srt.debug_utils.dumper as dumper_mod + + monkeypatch.setattr( + dumper_mod, + "_detect_recompute_status", + lambda: _RecomputeStatus.ORIGINAL, + ) + + d = _make_test_dumper(tmp_path) + tensor = torch.randn(3, 3) + d.dump("test_tensor", tensor) + + filenames = _get_filenames(tmp_path) + _assert_files(filenames, exist=["recompute_status=original"]) + + path = _find_dump_file(tmp_path, rank=0, name="test_tensor") + raw = _load_dump(path) + assert raw["meta"]["recompute_status"] == "original" + assert raw["meta"]["recompute_pseudo_rank"] == 0 + assert raw["meta"]["recompute_pseudo_size"] == 2 + + def test_disabled_no_recompute_pseudo_fields(self, tmp_path: Path) -> None: + d = _make_test_dumper(tmp_path) + tensor = torch.randn(3, 3) + d.dump("test_tensor", tensor) + + path = _find_dump_file(tmp_path, rank=0, name="test_tensor") + raw = _load_dump(path) + assert "recompute_pseudo_rank" not in raw["meta"] + assert "recompute_pseudo_size" not in raw["meta"] + + def test_grad_hook_has_no_recompute_status(self, tmp_path: Path) -> None: + d = _make_test_dumper(tmp_path, enable_grad=True) + x = torch.randn(3, 3, requires_grad=True) + y = (x * 2).sum() + + d.dump("test_tensor", x) + y.backward() + + grad_files = [f for f in _get_filenames(tmp_path) if "grad__test_tensor" in f] + assert len(grad_files) == 1 + assert "recompute_status" not in grad_files[0] + + def test_non_intrusive_hooks_have_recompute_status(self, tmp_path: Path) -> None: + class Simple(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(4, 4) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.linear(x) + + model = Simple() + d = _make_test_dumper(tmp_path, non_intrusive_mode="all") + d.register_non_intrusive_dumper(model) + + with d.capture_output() as captured: + model(torch.randn(2, 4)) + + for key, data in captured.items(): + assert ( + "recompute_status" in data["meta"] + ), f"missing recompute_status in {key}" + assert data["meta"]["recompute_status"] == "disabled" + + def test_detect_recompute_status_default(self) -> None: + assert _detect_recompute_status() == _RecomputeStatus.DISABLED + + +class TestGrafterConfig: + def test_from_env_parses_filters(self): + with temp_set_env( + DUMPER_GRAFTER_B2T_FILTER="name == 'x'", + DUMPER_GRAFTER_T2B_FILTER="name == 'y'", + ): + cfg = DumperConfig.from_env() + assert cfg.grafter_b2t_filter == "name == 'x'" + assert cfg.grafter_t2b_filter == "name == 'y'" + + def test_from_env_parses_int_fields(self): + with temp_set_env( + DUMPER_GRAFTER_BASELINE_WORLD_SIZE="8", + DUMPER_GRAFTER_TARGET_WORLD_SIZE="8", + DUMPER_GRAFTER_MASTER_PORT="29999", + DUMPER_GRAFTER_TIMEOUT="120", + ): + cfg = DumperConfig.from_env() + assert cfg.grafter_baseline_world_size == 8 + assert type(cfg.grafter_baseline_world_size) is int + assert cfg.grafter_target_world_size == 8 + assert cfg.grafter_master_port == 29999 + assert cfg.grafter_timeout == 120 + + def test_from_env_role(self): + with temp_set_env(DUMPER_GRAFTER_ROLE="baseline"): + assert DumperConfig.from_env().grafter_role == "baseline" + + def test_from_env_enable_flag(self): + # enable=True requires all of role, master_address/port, world sizes, + # and at least one filter per DumperConfig.__post_init__. + with temp_set_env( + DUMPER_GRAFTER_ENABLE="1", + DUMPER_GRAFTER_ROLE="baseline", + DUMPER_GRAFTER_MASTER_ADDRESS="127.0.0.1", + DUMPER_GRAFTER_MASTER_PORT="29999", + DUMPER_GRAFTER_BASELINE_WORLD_SIZE="1", + DUMPER_GRAFTER_TARGET_WORLD_SIZE="1", + DUMPER_GRAFTER_B2T_FILTER="name == 'x'", + ): + assert DumperConfig.from_env().grafter_enable is True + with temp_set_env(DUMPER_GRAFTER_ENABLE="false"): + assert DumperConfig.from_env().grafter_enable is False + + def test_enable_without_required_fields_raises(self): + with pytest.raises(AssertionError, match=r"grafter_role"): + DumperConfig(grafter_enable=True) + with pytest.raises(AssertionError, match=r"grafter_master_address"): + DumperConfig(grafter_enable=True, grafter_role="baseline") + with pytest.raises(AssertionError, match=r"grafter_master_port"): + DumperConfig( + grafter_enable=True, + grafter_role="baseline", + grafter_master_address="127.0.0.1", + ) + with pytest.raises(AssertionError, match=r"grafter_baseline_world_size"): + DumperConfig( + grafter_enable=True, + grafter_role="baseline", + grafter_master_address="127.0.0.1", + grafter_master_port=12345, + ) + with pytest.raises(AssertionError, match=r"neither grafter_b2t_filter nor"): + DumperConfig( + grafter_enable=True, + grafter_role="baseline", + grafter_master_address="127.0.0.1", + grafter_master_port=12345, + grafter_baseline_world_size=1, + grafter_target_world_size=1, + ) + + def test_env_name_for_grafter_field(self): + assert ( + DumperConfig._env_name("grafter_b2t_filter") == "DUMPER_GRAFTER_B2T_FILTER" + ) + + +def _unit_grafter_config(**overrides) -> DumperConfig: + """Build a fully-valid DumperConfig for unit-test use. + + All grafter_* required fields default to dummy values; overrides patch + individual fields (e.g., grafter_enable=False or filter strings). + Dummy values are never reached because these unit tests short-circuit + before _ensure_group runs. + """ + base = dict( + grafter_enable=True, + grafter_role="baseline", + grafter_master_address="127.0.0.1", + grafter_master_port=12345, + grafter_baseline_world_size=1, + grafter_target_world_size=1, + grafter_b2t_filter="name == 'x'", + ) + base.update(overrides) + return DumperConfig(**base) + + +class TestLog: + def test_log_format(self): + with _capture_stdout() as captured: + _log("hello") + out = captured.getvalue() + assert "hello" in out, out + assert "[Dumper, rank=" in out, out + assert ", t=" in out, out + + +class TestCompareTensorsQuick: + def test_identical(self): + a = torch.tensor([1.0, 2.0, 3.0]) + s = _compare_tensors_quick(a, a.clone()) + assert "rel_diff=0" in s, s + assert "max_abs=0" in s, s + + def test_diverged(self): + a = torch.tensor([1.0, 2.0, 3.0]) + b = torch.tensor([1.0, 2.0, 4.0]) # last element differs by 1 + s = _compare_tensors_quick(a, b) + # rel_diff > 0 implies divergence; max_abs should equal 1.0 + assert "max_abs=1" in s, s + assert "rel_diff=" in s, s + + def test_shape_mismatch(self): + s = _compare_tensors_quick(torch.zeros(3), torch.zeros(4)) + assert "shape mismatch" in s, s + + def test_dtype_unified(self): + # Different dtypes should NOT error — both are cast to fp32 internally. + s = _compare_tensors_quick( + torch.zeros(3, dtype=torch.float32), + torch.zeros(3, dtype=torch.float64), + ) + assert "rel_diff=" in s, s + assert "max_abs=" in s, s + + def test_empty(self): + s = _compare_tensors_quick(torch.zeros(0), torch.zeros(0)) + assert s == "empty" + + +class TestGrafterFilterMatching: + """Unit tests for the filter-matching short-circuit logic. + + These don't initialize a process group, so the network-related fields + are dummy values via _unit_grafter_config. + """ + + def test_disabled_returns_silently(self): + grafter = _Grafter(config=_unit_grafter_config(grafter_enable=False)) + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "x"}) + assert grafter._pg is None # never initialized + + def test_unmatched_non_tensor_silent(self): + """Non-tensor + unmatched name → silent skip, no print.""" + grafter = _Grafter(config=_unit_grafter_config()) + with _capture_stdout() as captured: + grafter.maybe_intercept(value=42, tags={"name": "other"}) + assert grafter._pg is None + assert "[Grafter]" not in captured.getvalue(), captured.getvalue() + + def test_matched_non_tensor_prints_and_skips(self): + """Non-tensor that matches a filter → print explanation, then skip. + + This catches misconfigured filters (e.g. matching a name that maps to a + dict/list at some call sites) without silently masking the issue.""" + grafter = _Grafter(config=_unit_grafter_config()) + with _capture_stdout() as captured: + grafter.maybe_intercept(value={"not": "a tensor"}, tags={"name": "x"}) + output = captured.getvalue() + assert grafter._pg is None # still no PG init + assert "value is not a torch.Tensor" in output, output + assert "type=dict" in output, output + + def test_unmatched_name_returns_silently(self): + grafter = _Grafter( + config=_unit_grafter_config(grafter_t2b_filter="name == 'y'") + ) + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "z"}) + assert grafter._pg is None + + def test_overlap_filters_raise(self): + grafter = _Grafter( + config=_unit_grafter_config( + grafter_b2t_filter="name == 'x'", + grafter_t2b_filter="name == 'x'", + ) + ) + with pytest.raises( + RuntimeError, + match=r"matched BOTH grafter_b2t_filter and grafter_t2b_filter", + ): + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "x"}) + + def test_filter_expression_uses_extra_tags(self): + """Filter expressions can reference any tag key, not just 'name'.""" + grafter = _Grafter( + config=_unit_grafter_config( + grafter_b2t_filter="name == 'x' and layer_id < 3", + grafter_t2b_filter="name == 'x' and layer_id < 3", + ) + ) + # layer_id=1 → both filters match → overlap raise (proves filter saw layer_id). + with pytest.raises(RuntimeError, match=r"matched BOTH"): + grafter.maybe_intercept( + value=torch.zeros(2), + tags={"name": "x", "layer_id": 1}, + ) + # layer_id=5 → neither filter matches → silent skip. + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "x", "layer_id": 5}) + assert grafter._pg is None + + def test_load_function_bad_module(self): + with pytest.raises(ModuleNotFoundError): + _load_function("no_such_pkg.no_such_module.transform") + + def test_load_function_missing_attr(self): + # `os.path` exists but has no `definitely_no_such_attr`. + with pytest.raises(AttributeError): + _load_function("os.path.definitely_no_such_attr") + + def test_load_function_no_dotted_prefix(self): + with pytest.raises(ValueError, match=r"missing dotted prefix"): + _load_function("only_one_segment") + + def test_load_function_non_callable_resolves_but_call_fails(self): + """`_load_function` itself only does attribute lookup — it doesn't + verify the result is callable. A non-callable target manifests at + call time as TypeError; we still want the failure to be debuggable.""" + sep = _load_function("os.path.sep") # str, not a callable + assert isinstance(sep, str) + with pytest.raises(TypeError): + sep() + + def test_filter_expression_only_uses_non_name_tag(self): + """A filter that doesn't reference `name` at all is still valid; it + should match purely on the other tag(s).""" + grafter = _Grafter( + config=_unit_grafter_config( + grafter_b2t_filter=None, + grafter_t2b_filter="layer_id < 3", + ) + ) + # layer_id absent → resolves to None; `None < 3` raises TypeError in py3. + with pytest.raises(TypeError): + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "x"}) + + def test_filter_expression_unknown_tag_resolves_to_none(self): + """Unknown tag keys resolve to None inside filter expressions, so + `layer_id is None` works as an "absent" probe without raising.""" + grafter = _Grafter( + config=_unit_grafter_config( + grafter_b2t_filter=None, + grafter_t2b_filter="layer_id is None and name == 'x'", + ) + ) + # No `layer_id` in tags → resolves to None → filter matches → tries + # to init the recv group (which we can't actually do here without a + # real PG, so we expect the assertion failure from _ensure_group). + with pytest.raises(AssertionError, match="default torch.distributed"): + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "x"}) + + def test_filter_expression_syntax_error_raises(self): + """A filter string that isn't valid Python should surface as a + SyntaxError so the misconfiguration is loud, not silent.""" + grafter = _Grafter( + config=_unit_grafter_config(grafter_b2t_filter="name == "), + ) + with pytest.raises(SyntaxError): + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "x"}) + + def test_filter_expression_undefined_helper_raises(self): + """Referencing an undefined helper inside a filter (e.g. a function + the user expected to be in scope) should NOT be silently treated as + False. The filter namespace is a `_DefaultNoneDict` (unknown keys + resolve to None), so calling an undefined helper raises TypeError + (`'NoneType' object is not callable`) — loud enough to surface the + misconfiguration.""" + grafter = _Grafter( + config=_unit_grafter_config( + grafter_b2t_filter="totally_undefined_helper(name)" + ), + ) + with pytest.raises(TypeError, match=r"NoneType.* not callable"): + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "x"}) + + def test_filter_can_use_re_search(self): + """`re.search` is exposed inside filter expressions as `search()`.""" + grafter = _Grafter( + config=_unit_grafter_config( + grafter_b2t_filter="search(r'attn.*', name) is not None", + grafter_t2b_filter=None, + ) + ) + # name='attn_input' matches /attn.*/ → tries to init group (hits + # the no-default-PG assertion, proving the regex matched). + with pytest.raises(AssertionError, match="default torch.distributed"): + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "attn_input"}) + # name='other' does not match → silent skip. + grafter.maybe_intercept(value=torch.zeros(2), tags={"name": "other"}) + assert grafter._pg is None + + +def _run_graft_test(worker_func, **kwargs): + """Spawn one GPU-using process per role (rank 0 = baseline, rank 1 = target). + + Limited to 1+1 because CI machines we can rely on have only 2 GPUs. + Each process initializes its OWN default PG (nccl, world_size=1) from + the start, mirroring production where baseline and target are + independently launched. + + For asymmetric / multi-rank coverage that doesn't need GPU, see + `_run_graft_test_cpu_multi` below. + """ + import torch.multiprocessing as mp + + role_ports = [find_available_port(29700 + i * 100) for i in range(2)] + + ctx = mp.get_context("spawn") + result_queue = ctx.Queue() + processes = [] + for rank in range(2): + p = ctx.Process( + target=_graft_worker_entry, + args=(rank, role_ports[rank], worker_func, result_queue, kwargs), + ) + p.start() + processes.append(p) + + for p in processes: + p.join() + + errors = [result_queue.get() for _ in range(2)] + errors = [e for e in errors if e] + if errors: + raise AssertionError("\n".join(errors)) + + +def _graft_worker_entry(rank, role_port, worker_func, result_queue, kwargs): + import traceback + + torch.cuda.set_device(rank) + dist.init_process_group( + backend="nccl", + init_method=f"tcp://127.0.0.1:{role_port}", + world_size=1, + rank=0, + ) + try: + worker_func(rank=rank, **kwargs) + result_queue.put(None) + except Exception as e: + result_queue.put(f"rank={rank}: {e}\n{traceback.format_exc()}") + finally: + dist.destroy_process_group() + + +def _run_graft_test_split(worker_baseline, worker_target, **kwargs) -> dict: + """Like `_run_graft_test`, but each role runs its OWN dedicated worker + function (no `if rank == 0:` branching) and stdout is captured per role. + + Returns ``{"baseline": stdout_str, "target": stdout_str}`` so tests can + snapshot/assert on the per-role logs. Used by the E2E example for + educational clarity (each role's logic reads top-to-bottom) and to assert + the user-visible log output matches expectations. + """ + import torch.multiprocessing as mp + + role_ports = { + "baseline": find_available_port(29700), + "target": find_available_port(29800), + } + + ctx = mp.get_context("spawn") + result_queue = ctx.Queue() + processes = [] + for global_rank, (role, worker) in enumerate( + [("baseline", worker_baseline), ("target", worker_target)] + ): + p = ctx.Process( + target=_graft_split_worker_entry, + args=(global_rank, role, role_ports[role], worker, result_queue, kwargs), + ) + p.start() + processes.append(p) + + for p in processes: + p.join() + + outputs: dict = {} + errors: list = [] + for _ in range(2): + role, error, captured = result_queue.get() + outputs[role] = captured + if error: + errors.append(f"role={role}: {error}") + if errors: + raise AssertionError( + "\n".join(errors) + + "\nCaptured outputs:\n" + + f"--- baseline ---\n{outputs.get('baseline', '')}\n" + + f"--- target ---\n{outputs.get('target', '')}" + ) + return outputs + + +def _graft_split_worker_entry( + global_rank, role, role_port, worker_func, result_queue, kwargs +): + import io + import traceback + + captured = io.StringIO() + old_stdout = sys.stdout + sys.stdout = captured + error = None + try: + # Set per-role env BEFORE we (re)build the module-level `dumper`. The + # parent left DUMPER_GRAFTER_ENABLE/ROLE unset because they vary per + # child; we set them here, then rebuild the global so that worker + # code can simply call `from sglang.srt.debug_utils.dumper import dumper` + # and get a properly-configured Grafter — exactly mirroring how + # production code uses the global. + os.environ["DUMPER_GRAFTER_ENABLE"] = "1" + os.environ["DUMPER_GRAFTER_ROLE"] = role + import sglang.srt.debug_utils.dumper as _dumper_module + + _dumper_module.dumper = _dumper_module._Dumper( + config=_dumper_module.DumperConfig.from_env() + ) + + torch.cuda.set_device(global_rank) + dist.init_process_group( + backend="nccl", + init_method=f"tcp://127.0.0.1:{role_port}", + world_size=1, + rank=0, + ) + try: + worker_func(**kwargs) + except Exception as e: + error = f"{e}\n{traceback.format_exc()}" + finally: + try: + dist.destroy_process_group() + except Exception: + pass + finally: + sys.stdout = old_stdout + result_queue.put((role, error, captured.getvalue())) + + +def _run_graft_test_cpu_multi( + worker_func, *, baseline_world: int, target_world: int, **kwargs +): + """Spawn (baseline_world + target_world) CPU-only processes (gloo backend). + + Used to exercise asymmetric multi-rank cases (e.g. 4 baseline ranks and + 2 target ranks) that we can't run on the 2-GPU CI fleet. Each role gets + its OWN default PG (gloo, world=role_world); the graft cross-system PG + spans all ranks. + + The worker function receives (role, local_rank, **kwargs). + """ + import torch.multiprocessing as mp + + # One default-PG port per role (baseline-side ranks share one PG, target + # ranks share another). Allocated up-front to avoid child races. + role_ports = { + "baseline": find_available_port(29800), + "target": find_available_port(29900), + } + + ctx = mp.get_context("spawn") + result_queue = ctx.Queue() + processes = [] + total = baseline_world + target_world + for global_rank in range(total): + if global_rank < baseline_world: + role = "baseline" + local_rank = global_rank + local_world = baseline_world + else: + role = "target" + local_rank = global_rank - baseline_world + local_world = target_world + p = ctx.Process( + target=_graft_cpu_worker_entry, + args=( + role, + local_rank, + local_world, + role_ports[role], + worker_func, + result_queue, + kwargs, + ), + ) + p.start() + processes.append(p) + + for p in processes: + p.join() + + errors = [result_queue.get() for _ in range(total)] + errors = [e for e in errors if e] + if errors: + raise AssertionError("\n".join(errors)) + + +def _graft_cpu_worker_entry( + role, local_rank, local_world, port, worker_func, result_queue, kwargs +): + import traceback + + dist.init_process_group( + backend="gloo", + init_method=f"tcp://127.0.0.1:{port}", + world_size=local_world, + rank=local_rank, + ) + try: + worker_func(role=role, local_rank=local_rank, **kwargs) + result_queue.put(None) + except Exception as e: + result_queue.put( + f"role={role} local_rank={local_rank}: {e}\n{traceback.format_exc()}" + ) + finally: + dist.destroy_process_group() + + +def _make_grafter_test_config( + *, + rank: int, + graft_port: int, + group_name: str, + timeout: int = 30, + transform_path: Optional[str] = None, + b2t_filter: Optional[str] = "name == 'x'", + t2b_filter: Optional[str] = None, +) -> DumperConfig: + """Helper for distributed grafter tests. + + Same b2t/t2b filters on both sides; only `grafter_role` differs (rank 0 = + baseline, rank 1 = target). Both sides are world_size=1 within their own + role's default PG. + """ + role = "baseline" if rank == 0 else "target" + return DumperConfig( + grafter_enable=True, + grafter_role=role, + grafter_b2t_filter=b2t_filter, + grafter_t2b_filter=t2b_filter, + grafter_master_address="127.0.0.1", + grafter_master_port=graft_port, + grafter_baseline_world_size=1, + grafter_target_world_size=1, + grafter_group_name=group_name, + grafter_timeout=timeout, + # Loading the user transform on the recv side; for b2t the recv is + # the target side (rank 1). + grafter_transform_path=transform_path if rank == 1 else None, + ) + + +class TestGrafterDistributed: + def test_b2t_copy_roundtrip(self): + """Baseline (rank 0) sends 'x' to target (rank 1), target.copy_'s it.""" + graft_port = find_available_port(29600) + _run_graft_test( + self._test_b2t_func, graft_port=graft_port, group_name="grafter_b2t" + ) + + @staticmethod + def _test_b2t_func(rank, graft_port, group_name): + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, graft_port=graft_port, group_name=group_name + ) + ) + try: + if rank == 0: + tensor = torch.tensor([1.0, 2.0, 3.0], device="cuda:0") + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + target = torch.zeros(3, device="cuda:1") + with _capture_stdout() as captured: + grafter.maybe_intercept(value=target, tags={"name": "x"}) + assert target.tolist() == [1.0, 2.0, 3.0], f"got {target.tolist()}" + # Success log must include the pre/new diff summary. + assert "diff_pre_vs_new=" in captured.getvalue(), captured.getvalue() + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_t2b_copy_roundtrip(self): + """Target (rank 1) sends 'x' to baseline (rank 0), baseline.copy_'s it.""" + graft_port = find_available_port(29605) + _run_graft_test( + self._test_t2b_func, graft_port=graft_port, group_name="grafter_t2b" + ) + + @staticmethod + def _test_t2b_func(rank, graft_port, group_name): + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, + graft_port=graft_port, + group_name=group_name, + b2t_filter=None, + t2b_filter="name == 'x'", + ) + ) + try: + if rank == 1: + tensor = torch.tensor([4.0, 5.0, 6.0], device="cuda:1") + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + target = torch.zeros(3, device="cuda:0") + grafter.maybe_intercept(value=target, tags={"name": "x"}) + assert target.tolist() == [4.0, 5.0, 6.0], f"got {target.tolist()}" + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_recv_with_user_transform(self, tmp_path: Path): + # Write a tiny module that defines `transform(graft_input)`. The + # worker prepends tmp_path to sys.path so import_module sees it. + module_name = "_xform_user_basic" + (tmp_path / f"{module_name}.py").write_text( + "def transform(graft_input):\n" + " return graft_input.received_list[0] * 2\n" + ) + graft_port = find_available_port(29610) + _run_graft_test( + self._test_user_transform_func, + graft_port=graft_port, + group_name="grafter_transform", + transform_dir=str(tmp_path), + transform_path=f"{module_name}.transform", + ) + + @staticmethod + def _test_user_transform_func( + rank, graft_port, group_name, transform_dir, transform_path + ): + sys.path.insert(0, transform_dir) + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, + graft_port=graft_port, + group_name=group_name, + transform_path=transform_path, + ) + ) + try: + if rank == 0: + tensor = torch.tensor([1.0, 2.0, 3.0], device="cuda:0") + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + target = torch.zeros(3, device="cuda:1") + grafter.maybe_intercept(value=target, tags={"name": "x"}) + assert target.tolist() == [2.0, 4.0, 6.0], f"got {target.tolist()}" + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_unmatched_name_skipped(self): + graft_port = find_available_port(29620) + _run_graft_test( + self._test_unmatched_func, + graft_port=graft_port, + group_name="grafter_unmatched", + ) + + @staticmethod + def _test_unmatched_func(rank, graft_port, group_name): + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, graft_port=graft_port, group_name=group_name + ) + ) + try: + target = torch.tensor([7.0, 7.0, 7.0], device=f"cuda:{rank}") + grafter.maybe_intercept(value=target, tags={"name": "other"}) + assert target.tolist() == [7.0, 7.0, 7.0], "tensor must not be modified" + assert grafter._pg is None, "group must not init for unmatched name" + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_default_fallback_shape_mismatch_does_not_crash(self): + """When sender shape != target shape, default identity fallback raises; + the grafter must catch it, log, and leave target unchanged.""" + graft_port = find_available_port(29615) + _run_graft_test( + self._test_shape_mismatch_func, + graft_port=graft_port, + group_name="grafter_shape_mismatch", + ) + + @staticmethod + def _test_shape_mismatch_func(rank, graft_port, group_name): + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, graft_port=graft_port, group_name=group_name + ) + ) + try: + if rank == 0: + # Baseline sends shape=(3,) + tensor = torch.tensor([1.0, 2.0, 3.0], device="cuda:0") + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + # Target's local target has shape=(4,) — mismatch with sender. + target = torch.tensor([7.0, 7.0, 7.0, 7.0], device="cuda:1") + # No exception should propagate; tensor must stay unchanged. + grafter.maybe_intercept(value=target, tags={"name": "x"}) + assert target.tolist() == [ + 7.0, + 7.0, + 7.0, + 7.0, + ], f"target should be unchanged after shape-mismatch graft, got {target.tolist()}" + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_user_transform_exception_does_not_crash(self, tmp_path: Path): + """A user transform that raises must NOT bring down the system; the + grafter logs and skips the copy_, leaving target unchanged.""" + module_name = "_xform_throws" + (tmp_path / f"{module_name}.py").write_text( + "def transform(graft_input):\n" + " raise RuntimeError('intentional test error from user transform')\n" + ) + graft_port = find_available_port(29635) + _run_graft_test( + self._test_transform_throws_func, + graft_port=graft_port, + group_name="grafter_throws", + transform_dir=str(tmp_path), + transform_path=f"{module_name}.transform", + module_name=module_name, + ) + + @staticmethod + def _test_transform_throws_func( + rank, graft_port, group_name, transform_dir, transform_path, module_name + ): + sys.path.insert(0, transform_dir) + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, + graft_port=graft_port, + group_name=group_name, + transform_path=transform_path, + ) + ) + try: + if rank == 0: + tensor = torch.tensor([1.0, 2.0, 3.0], device="cuda:0") + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + target = torch.tensor([9.0, 9.0, 9.0], device="cuda:1") + with _capture_stdout() as captured: + grafter.maybe_intercept(value=target, tags={"name": "x"}) + assert target.tolist() == [ + 9.0, + 9.0, + 9.0, + ], f"target must be unchanged when transform throws, got {target.tolist()}" + output = captured.getvalue() + assert "transform/copy_ raised RuntimeError" in output, output + assert "intentional test error" in output, output + # Full traceback must be included so the bug is debuggable. + assert "Traceback (most recent call last)" in output, output + assert f"{module_name}.py" in output, output + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_extras_flow_to_recv_transform(self, tmp_path: Path): + """Sender attaches per-call grafter_extras; recv transform reads them + and uses them to compute the override value.""" + module_name = "_xform_uses_extras" + (tmp_path / f"{module_name}.py").write_text( + "import torch\n" + "def transform(graft_input):\n" + " fill = graft_input.received_extras_list[0]['fill_value']\n" + " return torch.full_like(graft_input.target, fill)\n" + ) + graft_port = find_available_port(29645) + _run_graft_test( + self._test_extras_func, + graft_port=graft_port, + group_name="grafter_extras", + transform_dir=str(tmp_path), + transform_path=f"{module_name}.transform", + ) + + @staticmethod + def _test_extras_func(rank, graft_port, group_name, transform_dir, transform_path): + sys.path.insert(0, transform_dir) + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, + graft_port=graft_port, + group_name=group_name, + transform_path=transform_path, + ) + ) + try: + if rank == 0: + # Baseline (sender) attaches an extras dict. + tensor = torch.tensor([1.0, 2.0, 3.0], device="cuda:0") + grafter.maybe_intercept( + value=tensor, + tags={"name": "x"}, + extras={"fill_value": 42.0}, + ) + else: + target = torch.zeros(3, device="cuda:1") + grafter.maybe_intercept(value=target, tags={"name": "x"}) + assert target.tolist() == [ + 42.0, + 42.0, + 42.0, + ], f"target should be filled from sender extras, got {target.tolist()}" + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_init_timeout_warns(self): + graft_port = find_available_port(29630) + _run_graft_test( + self._test_init_timeout_func, + graft_port=graft_port, + group_name="grafter_timeout", + ) + + @staticmethod + def _test_init_timeout_func(rank, graft_port, group_name): + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, graft_port=graft_port, group_name=group_name, timeout=2 + ) + ) + try: + with _capture_stdout() as captured: + if rank == 1: + time.sleep(4) + tensor = torch.tensor([1.0, 2.0, 3.0], device=f"cuda:{rank}") + if rank == 0: + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + target = torch.zeros(3, device=f"cuda:{rank}") + grafter.maybe_intercept(value=target, tags={"name": "x"}) + output = captured.getvalue() + if rank == 0: + assert ( + "WARNING" in output + ), f"expected WARNING in rank 0 output: {output}" + assert "has not completed after 2s" in output, output + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_extras_default_none_flow(self): + """When the sender omits `grafter_extras`, the recv transform sees a + list of Nones — but len(received_extras_list) still matches n_senders.""" + graft_port = find_available_port(29650) + _run_graft_test( + self._test_extras_none_func, + graft_port=graft_port, + group_name="grafter_extras_none", + ) + + @staticmethod + def _test_extras_none_func(rank, graft_port, group_name): + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, graft_port=graft_port, group_name=group_name + ) + ) + try: + if rank == 0: + tensor = torch.tensor([1.0, 2.0, 3.0], device="cuda:0") + # Note: extras kwarg omitted entirely → None on the wire. + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + target = torch.zeros(3, device="cuda:1") + with _capture_stdout() as captured: + grafter.maybe_intercept(value=target, tags={"name": "x"}) + # Default identity transform copies tensor through; recv log + # must reflect that received_extras_list == [None]. + output = captured.getvalue() + assert "sender_extras=[None]" in output, output + assert target.tolist() == [1.0, 2.0, 3.0], target.tolist() + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_group_init_is_cached_across_calls(self): + """The graft process group is initialized lazily on the first + matched dump() and cached afterwards — subsequent dumps must reuse + the same `_pg` object, not re-init.""" + graft_port = find_available_port(29660) + _run_graft_test( + self._test_group_cache_func, + graft_port=graft_port, + group_name="grafter_cache", + ) + + @staticmethod + def _test_group_cache_func(rank, graft_port, group_name): + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, graft_port=graft_port, group_name=group_name + ) + ) + try: + if rank == 0: + t1 = torch.tensor([1.0, 2.0, 3.0], device="cuda:0") + t2 = torch.tensor([4.0, 5.0, 6.0], device="cuda:0") + grafter.maybe_intercept(value=t1, tags={"name": "x"}) + pg_after_first = grafter._pg + assert pg_after_first is not None + grafter.maybe_intercept(value=t2, tags={"name": "x"}) + assert ( + grafter._pg is pg_after_first + ), "_pg must be cached across calls, not re-initialized" + else: + target1 = torch.zeros(3, device="cuda:1") + target2 = torch.zeros(3, device="cuda:1") + grafter.maybe_intercept(value=target1, tags={"name": "x"}) + pg_after_first = grafter._pg + assert pg_after_first is not None + grafter.maybe_intercept(value=target2, tags={"name": "x"}) + assert grafter._pg is pg_after_first + assert target1.tolist() == [1.0, 2.0, 3.0] + assert target2.tolist() == [4.0, 5.0, 6.0] + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_copy_failure_does_not_crash(self, tmp_path: Path): + """If the user transform returns a tensor whose shape doesn't match + target, `value.copy_(value_to_override)` raises — and that error + must be caught, logged with traceback, and target left unchanged + (same robustness contract as transform-throws).""" + module_name = "_xform_returns_wrong_shape" + (tmp_path / f"{module_name}.py").write_text( + "import torch\n" + "def transform(graft_input):\n" + " # Deliberately return a shape that copy_ will reject.\n" + " return torch.zeros(99, device=graft_input.target.device)\n" + ) + graft_port = find_available_port(29665) + _run_graft_test( + self._test_copy_failure_func, + graft_port=graft_port, + group_name="grafter_copy_fail", + transform_dir=str(tmp_path), + transform_path=f"{module_name}.transform", + ) + + @staticmethod + def _test_copy_failure_func( + rank, graft_port, group_name, transform_dir, transform_path + ): + sys.path.insert(0, transform_dir) + grafter = _Grafter( + config=_make_grafter_test_config( + rank=rank, + graft_port=graft_port, + group_name=group_name, + transform_path=transform_path, + ) + ) + try: + if rank == 0: + tensor = torch.tensor([1.0, 2.0, 3.0], device="cuda:0") + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + target = torch.tensor([7.0, 7.0, 7.0], device="cuda:1") + with _capture_stdout() as captured: + grafter.maybe_intercept(value=target, tags={"name": "x"}) + # target must be unchanged; error must be logged with traceback. + assert target.tolist() == [ + 7.0, + 7.0, + 7.0, + ], f"target must be unchanged on copy_ failure, got {target.tolist()}" + output = captured.getvalue() + assert "transform/copy_ raised" in output, output + assert "Traceback (most recent call last)" in output, output + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + +class TestGrafterMultiRankCpu: + """Coverage of asymmetric multi-rank cases via CPU/gloo (CI fleet has + only 2 GPUs, which is too few for these cases).""" + + def test_4_baseline_2_target_b2t_with_user_transform(self, tmp_path: Path): + """4 baseline senders -> 2 target receivers via b2t graft. + The user transform asserts received_list has length 4 with each + sender's tensor matching its rank, then returns a marker tensor.""" + module_name = "_xform_assert_4_senders" + (tmp_path / f"{module_name}.py").write_text( + "import torch\n" + "def transform(graft_input):\n" + " rl = graft_input.received_list\n" + " assert len(rl) == 4, f'expected 4 senders, got {len(rl)}'\n" + " for i, t in enumerate(rl):\n" + " v = float(t.flatten()[0].item())\n" + " assert v == float(i), f'rl[{i}][0]={v}, want {float(i)}'\n" + " return torch.full_like(graft_input.target, 999.0)\n" + ) + graft_port = find_available_port(29655) + _run_graft_test_cpu_multi( + self._test_4b_2t_func, + baseline_world=4, + target_world=2, + graft_port=graft_port, + group_name="grafter_4b_2t", + transform_dir=str(tmp_path), + transform_path=f"{module_name}.transform", + ) + + @staticmethod + def _test_4b_2t_func( + role, local_rank, graft_port, group_name, transform_dir, transform_path + ): + sys.path.insert(0, transform_dir) + cfg = _make_multi_rank_config( + role=role, + graft_port=graft_port, + group_name=group_name, + baseline_world=4, + target_world=2, + transform_path=transform_path, + direction="b2t", + ) + grafter = _Grafter(config=cfg) + try: + if role == "baseline": + # rank-i baseline contributes [i, i, i]. + tensor = torch.full((3,), float(local_rank)) + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + # Target's local tensor (will be overwritten with 999s by transform). + target = torch.full((3,), 99.0) + grafter.maybe_intercept(value=target, tags={"name": "x"}) + assert target.tolist() == [999.0, 999.0, 999.0], target.tolist() + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_2_target_4_baseline_t2b_with_user_transform(self, tmp_path: Path): + """Mirror image of the b2t case: 2 target senders -> 4 baseline + receivers via t2b graft. Confirms the (role, direction) algebra and + sender_slice work correctly when target is the SENDER side.""" + module_name = "_xform_assert_2_senders_t2b" + (tmp_path / f"{module_name}.py").write_text( + "import torch\n" + "def transform(graft_input):\n" + " rl = graft_input.received_list\n" + " assert len(rl) == 2, f'expected 2 senders, got {len(rl)}'\n" + " for i, t in enumerate(rl):\n" + " v = float(t.flatten()[0].item())\n" + " assert v == float(i + 100), (\n" + " f'rl[{i}][0]={v}, want {float(i + 100)}'\n" + " )\n" + " return torch.full_like(graft_input.target, 7.0)\n" + ) + graft_port = find_available_port(29670) + _run_graft_test_cpu_multi( + self._test_2t_4b_func, + baseline_world=4, + target_world=2, + graft_port=graft_port, + group_name="grafter_2t_4b", + transform_dir=str(tmp_path), + transform_path=f"{module_name}.transform", + ) + + @staticmethod + def _test_2t_4b_func( + role, local_rank, graft_port, group_name, transform_dir, transform_path + ): + sys.path.insert(0, transform_dir) + cfg = _make_multi_rank_config( + role=role, + graft_port=graft_port, + group_name=group_name, + baseline_world=4, + target_world=2, + transform_path=transform_path, + direction="t2b", + ) + grafter = _Grafter(config=cfg) + try: + if role == "target": + # rank-i target contributes [i+100, i+100, i+100]. + tensor = torch.full((3,), float(local_rank + 100)) + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + target = torch.full((3,), 99.0) + grafter.maybe_intercept(value=target, tags={"name": "x"}) + assert target.tolist() == [7.0, 7.0, 7.0], target.tolist() + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_default_transform_with_asymmetric_world_logs_and_skips(self): + """The default identity-by-rank fallback requires #senders == #recvs. + With baseline=4 and target=2 and no user transform, the recv side + must catch the RuntimeError, log it with traceback, and leave the + target unchanged.""" + graft_port = find_available_port(29675) + _run_graft_test_cpu_multi( + self._test_default_asym_func, + baseline_world=4, + target_world=2, + graft_port=graft_port, + group_name="grafter_default_asym", + ) + + @staticmethod + def _test_default_asym_func(role, local_rank, graft_port, group_name): + cfg = _make_multi_rank_config( + role=role, + graft_port=graft_port, + group_name=group_name, + baseline_world=4, + target_world=2, + transform_path=None, # default identity-by-rank fallback + direction="b2t", + ) + grafter = _Grafter(config=cfg) + try: + if role == "baseline": + tensor = torch.full((3,), float(local_rank)) + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + target = torch.full((3,), 42.0) + with _capture_stdout() as captured: + grafter.maybe_intercept(value=target, tags={"name": "x"}) + assert target.tolist() == [42.0, 42.0, 42.0], ( + f"target must be unchanged when default transform raises, " + f"got {target.tolist()}" + ) + output = captured.getvalue() + assert "transform/copy_ raised RuntimeError" in output, output + # The error message must explain WHY the default fell through. + assert "#senders=4" in output and "#recvs=2" in output, output + assert "Traceback (most recent call last)" in output, output + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + def test_mixed_shape_senders_via_user_transform(self, tmp_path: Path): + """`all_gather_object` is pickle-routed, so sender ranks may + contribute tensors with DIFFERENT shapes. The user transform sees + the full list and is responsible for picking/reducing. Asserts that + rank-i baseline's tensor has shape (i+1,) and the transform + concatenates them on the recv side.""" + module_name = "_xform_concat_mixed_shape" + (tmp_path / f"{module_name}.py").write_text( + "import torch\n" + "def transform(graft_input):\n" + " rl = graft_input.received_list\n" + " # Each baseline sent shape=(rank+1,) tensors filled with rank.\n" + " expected_shapes = [(i + 1,) for i in range(len(rl))]\n" + " actual_shapes = [tuple(t.shape) for t in rl]\n" + " assert actual_shapes == expected_shapes, (\n" + " f'shape mismatch: expected {expected_shapes}, got {actual_shapes}'\n" + " )\n" + " # Concat to length 1+2+3+4 = 10 == target's length.\n" + " return torch.cat(rl)\n" + ) + graft_port = find_available_port(29680) + _run_graft_test_cpu_multi( + self._test_mixed_shape_func, + baseline_world=4, + target_world=2, + graft_port=graft_port, + group_name="grafter_mixed_shape", + transform_dir=str(tmp_path), + transform_path=f"{module_name}.transform", + ) + + @staticmethod + def _test_mixed_shape_func( + role, local_rank, graft_port, group_name, transform_dir, transform_path + ): + sys.path.insert(0, transform_dir) + cfg = _make_multi_rank_config( + role=role, + graft_port=graft_port, + group_name=group_name, + baseline_world=4, + target_world=2, + transform_path=transform_path, + direction="b2t", + ) + grafter = _Grafter(config=cfg) + try: + if role == "baseline": + # rank-i baseline contributes shape=(i+1,) filled with i. + tensor = torch.full((local_rank + 1,), float(local_rank)) + grafter.maybe_intercept(value=tensor, tags={"name": "x"}) + else: + # 1 + 2 + 3 + 4 = 10 elements after concat. + target = torch.zeros(10) + grafter.maybe_intercept(value=target, tags={"name": "x"}) + expected = [0.0] + [1.0] * 2 + [2.0] * 3 + [3.0] * 4 + assert target.tolist() == expected, target.tolist() + finally: + if grafter._pg is not None: + dist.destroy_process_group(grafter._pg) + + +def _make_multi_rank_config( + *, + role: str, + graft_port: int, + group_name: str, + baseline_world: int, + target_world: int, + transform_path: Optional[str], + direction: str, +) -> DumperConfig: + return DumperConfig( + grafter_enable=True, + grafter_role=role, + grafter_b2t_filter="name == 'x'" if direction == "b2t" else None, + grafter_t2b_filter="name == 'x'" if direction == "t2b" else None, + grafter_master_address="127.0.0.1", + grafter_master_port=graft_port, + grafter_baseline_world_size=baseline_world, + grafter_target_world_size=target_world, + grafter_backend="gloo", + grafter_group_name=group_name, + grafter_timeout=30, + grafter_transform_path=transform_path, + ) + + +def _e2e_transform(graft_input): + """User transform used by the E2E example test. Demonstrates the two + customization hooks reviewers should learn from: + + 1. The transform receives a `GraftTransformInput` and returns the + tensor that the recv side will `.copy_()` into its local target. + 2. `graft_input.received_extras_list` carries whatever the sender + passed via `grafter_extras={...}` — useful for any per-call + metadata the recv side needs (layer ids, calibration knobs, ...). + + Here we keep the example minimal: the sender attaches a single dummy + key/value so the recv side has something concrete to assert on, then + the transform is just identity. Real workflows would compute a + non-trivial override (scale, reshape, decode, ...) using the extras. + """ + assert ( + graft_input.received_extras_list[0]["my_extra_key"] == "my_extra_value" + ), graft_input.received_extras_list + return graft_input.received_list[0] + + +class TestGrafterE2eExample: + """End-to-end example: target has a (suspected) buggy attention kernel. + + Story: target's attention kernel produces wrong outputs and we want to + test "if we replace target's attention with baseline's, does the rest of + the model converge?". The full graft wiring is: + + - At the attention call site, target sends its inputs (q/k/v) to + baseline → baseline's local inputs are overwritten by target's, so + baseline runs its (known-good) attention against the same inputs. + This is a t->b graft on `attn_input`. + - Both sides run the kernel. + - Baseline sends its outputs back to target → target's outputs are + overwritten by baseline's, so target's downstream sees baseline's + attention result. This is a b->t graft on `attn_output`. + + Net effect: target's attention is semantically replaced by baseline's, + without modifying target's source beyond inserting `dumper.dump` at the + input/output sites. This test additionally demonstrates two recv-side + customization hooks via `_e2e_transform`: + + * `grafter_extras={...}` per dump call — arbitrary per-call metadata + the recv side can consume. + * `DUMPER_GRAFTER_TRANSFORM_PATH` — a user-supplied function that + decides what value the recv side actually copy_'s in (defaults to + identity-by-rank when unset). + + The remaining call-site code is exactly: + + dumper.dump("attn_input", q, grafter_extras={"layer_id": 7}) # t -> b + out = target_attention_kernel(q, ...) + dumper.dump("attn_output", out, grafter_extras={"scale": 0.5}) # b -> t + """ + + def test_e2e_buggy_attn_replaced_by_baseline(self): + graft_port = find_available_port(29640) + # All non-role env is shared by both sides; we set it in the parent + # so the spawned subprocesses inherit it. DUMPER_GRAFTER_ENABLE and + # DUMPER_GRAFTER_ROLE are deliberately *not* set here — they are set + # by `_run_graft_test_split` per-rank, after which the global + # `dumper` is rebuilt (so workers can use the global directly). + with temp_set_env( + DUMPER_ENABLE="1", + DUMPER_ENABLE_OUTPUT_FILE="false", # skip disk I/O for the test + DUMPER_ENABLE_OUTPUT_CONSOLE="false", + # Pin exp_name so the dumper doesn't auto-pick + log "Choose + # exp_name=..." into the captured snapshot. + DUMPER_EXP_NAME="grafter_e2e_test", + DUMPER_GRAFTER_MASTER_ADDRESS="127.0.0.1", + DUMPER_GRAFTER_MASTER_PORT=str(graft_port), + DUMPER_GRAFTER_BASELINE_WORLD_SIZE="1", + DUMPER_GRAFTER_TARGET_WORLD_SIZE="1", + DUMPER_GRAFTER_B2T_FILTER="name == 'attn_output'", + DUMPER_GRAFTER_T2B_FILTER="name == 'attn_input'", + DUMPER_GRAFTER_GROUP_NAME="grafter_e2e", + DUMPER_GRAFTER_TIMEOUT="30", + DUMPER_GRAFTER_TRANSFORM_PATH=f"{__name__}._e2e_transform", + ): + outputs = _run_graft_test_split(self._worker_baseline, self._worker_target) + + self._assert_e2e_snapshot(outputs) + + @staticmethod + def _assert_e2e_snapshot(outputs: dict) -> None: + """Snapshot of the FULL per-role log timeline. + + Volatile fields (timestamps, ports, float diff values, tensor + min/max/mean/samples, struct addresses) are masked with ad-hoc regex + placeholders so the snapshot stays stable while still pinning + everything else. The snapshot doubles as documentation of the logs a + reader will see when running this E2E setup. + + Captured logs are unconditionally printed before asserting so a + snapshot failure doesn't require a re-run. + """ + baseline_log = outputs["baseline"] + target_log = outputs["target"] + + print("\n=========== captured baseline log ===========") + print(baseline_log) + print("=========== captured target log ===========") + print(target_log) + print("===========================================") + + # Convenience tokens for verbose volatile substrings. + prefix = r"\[Dumper, rank=\d+, t=\d+\.\d+\] " + # `get_tensor_info(t)` for our tensors expands to a long line; we + # match the leading struct fields verbatim and let the trailing + # min/max/mean/sample fields wildcard out. + tinfo_f32_4 = ( + r"type= shape=torch\.Size\(\[4\]\) " + r"dtype=torch\.float32 device=cuda:\d stride=\(1,\) " + r"req_grad=False .*" + ) + diff = r"rel_diff=[-\d.eE+]+ max_abs=[-\d.eE+]+ mean_abs=[-\d.eE+]+" + + # `_dump_inner` automatically annotates tags with `recompute_status` + # (always present, value depends on whether autograd recompute is + # active — "disabled" in this test env). + attn_input_tags = r"\{'name': 'attn_input', 'recompute_status': 'disabled'\}" + attn_output_tags = r"\{'name': 'attn_output', 'recompute_status': 'disabled'\}" + + # Same dummy extras dict travels in both directions. + extras_lit = r"\{'my_extra_key': 'my_extra_value'\}" + + baseline_pattern = ( + r"\A" + f"{prefix}\\[Grafter\\] init group: role=baseline " + r"baseline_world=1 target_world=1 rank=0 " + r"init_method=tcp://127\.0\.0\.1:\d+ backend=nccl " + r"name=grafter_e2e\n" + f"{prefix}\\[Grafter\\] recv role=baseline dir=t2b " + f"tags={attn_input_tags} n_senders=1 " + f"sender_extras=\\[{extras_lit}\\] " + f"before_overridden={tinfo_f32_4} " + f"to_override={tinfo_f32_4} " + f"diff_pre_vs_new={diff}\n" + f"{prefix}\\[Grafter\\] send role=baseline dir=b2t " + f"tags={attn_output_tags} extras={extras_lit} " + f"local={tinfo_f32_4}\n" + r"\Z" + ) + target_pattern = ( + r"\A" + f"{prefix}\\[Grafter\\] init group: role=target " + r"baseline_world=1 target_world=1 rank=1 " + r"init_method=tcp://127\.0\.0\.1:\d+ backend=nccl " + r"name=grafter_e2e\n" + f"{prefix}\\[Grafter\\] send role=target dir=t2b " + f"tags={attn_input_tags} extras={extras_lit} " + f"local={tinfo_f32_4}\n" + f"{prefix}\\[Grafter\\] recv role=target dir=b2t " + f"tags={attn_output_tags} n_senders=1 " + f"sender_extras=\\[{extras_lit}\\] " + f"before_overridden={tinfo_f32_4} " + f"to_override={tinfo_f32_4} " + f"diff_pre_vs_new={diff}\n" + r"\Z" + ) + + assert re.fullmatch(baseline_pattern, baseline_log, flags=re.DOTALL), ( + f"baseline log did not match snapshot.\n" + f"--- pattern ---\n{baseline_pattern}\n" + f"--- actual ---\n{baseline_log}" + ) + assert re.fullmatch(target_pattern, target_log, flags=re.DOTALL), ( + f"target log did not match snapshot.\n" + f"--- pattern ---\n{target_pattern}\n" + f"--- actual ---\n{target_log}" + ) + + @staticmethod + def _worker_baseline(): + # In production code, callers just `from sglang.srt.debug_utils.dumper + # import dumper` and call `dumper.dump(name, value)` — the env + # configures the global Grafter for them. We do the same here. + from sglang.srt.debug_utils.dumper import dumper + + # Step 1: graft input. target sends its q to baseline; baseline's + # `_e2e_transform` runs on the recv side, asserts the dummy extras + # made it across, then returns target's q so baseline's local + # placeholder is overwritten via .copy_(). + q = torch.tensor([99.0, 99.0, 99.0, 99.0], device="cuda:0") + dumper.dump("attn_input", q) + assert q.tolist() == [1.0, 2.0, 3.0, 4.0], ( + f"baseline's q should be overwritten by target's via the t->b graft, " + f"got {q.tolist()}" + ) + + # Step 2: baseline runs the known-good attention kernel. + attn_out = q * 10.0 # → [10, 20, 30, 40] + + # Step 3: graft output. baseline sends attn_out to target with a + # dummy extras key the recv-side transform will assert on. + dumper.dump( + "attn_output", + attn_out, + grafter_extras={"my_extra_key": "my_extra_value"}, + ) + + @staticmethod + def _worker_target(): + from sglang.srt.debug_utils.dumper import dumper + + # Step 1: graft input. target sends its real q to baseline along + # with a dummy extras key the recv-side transform will assert on. + q = torch.tensor([1.0, 2.0, 3.0, 4.0], device="cuda:1") + dumper.dump( + "attn_input", + q, + grafter_extras={"my_extra_key": "my_extra_value"}, + ) + + # Step 2: target runs the (suspected buggy) attention kernel — + # here it returns all zeros to mimic a broken implementation. + attn_out = torch.zeros_like(q) + + # Step 3: graft output. baseline sends its (good) attn_out to + # target; target's recv-side transform identity-passes it, so + # target's local attn_out ends up = baseline's [10, 20, 30, 40]. + dumper.dump("attn_output", attn_out) + assert attn_out.tolist() == [10.0, 20.0, 30.0, 40.0], ( + f"target's attn_out should be overwritten by baseline's via " + f"the b->t graft, got {attn_out.tolist()}" + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/test_engine_dumper_comparator_e2e.py b/asian_ai/performance/SGLang/test/registered/debug_utils/test_engine_dumper_comparator_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..e6aa8ef09bb0f2e94d703667d85e58e33d17f276 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/test_engine_dumper_comparator_e2e.py @@ -0,0 +1,385 @@ +"""E2E test: source patcher + dumper + comparator on SGLang server. + +Patches Qwen3MoeDecoderLayer.forward (and related methods) to insert +dumper.dump() calls at 7 points, launches servers with Qwen3-30B-A3B +(MOE model), runs inference, verifies patched dump fields exist, then +runs comparator to verify numerical consistency. + +Test cases: +- test_patch_dump_and_compare: TP=2 baseline vs TP=4 target +- test_dp_attention: TP=2 baseline vs TP=2+DP=2+dp-attention target + +The dumper.apply_source_patches() auto-injects ``from ... import dumper`` +so the YAML only needs ``dumper.dump(...)`` calls. +""" + +import os +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Optional + +import pytest +import requests + +pytestmark = pytest.mark.filterwarnings( + "ignore:Unknown config option. asyncio_mode:pytest.PytestConfigWarning", +) + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + popen_launch_server, +) + +register_cuda_ci(est_time=300, suite="nightly-4-gpu", nightly=True) +register_amd_ci( + est_time=300, + suite="nightly-amd-4-gpu", + nightly=True, + disabled="TP=2 vs TP=4 numerical mismatch on AMD (comparator fails tolerance check)", +) + +MODEL = "Qwen/Qwen3-30B-A3B" +BASELINE_TP = 2 +TARGET_TP = 4 +EXP_NAME = "e2e_source_patcher" +DUMPER_FILTER = "layer_id in [0, 1, 2]" + +_FIELDS_TO_VERIFY: list[str] = [ + # decoder layer level (aligned with miles) + "layer_input", + "attn_output", + "pre_mlp_residual", + "mlp_output", + # attention internals + "attn_pre_o_proj", + # moe internals + "moe_router_logits", + "moe_expert_output", +] + +PATCH_CONFIG_YAML: str = """\ +patches: + # --- decoder layer level (aligned with miles test) --- + - target: sglang.srt.models.qwen3_moe.Qwen3MoeDecoderLayer.forward + edits: + - match: | + hidden_states, residual = ( + self.layer_communicator.prepare_attn_and_capture_last_layer_outputs( + hidden_states, + residual, + forward_batch, + captured_last_layer_outputs=captured_last_layer_outputs, + **kwargs, + ) + ) + append: "dumper.dump('layer_input', hidden_states, dims='t h # tp:replicated')" + - match: | + hidden_states = self.self_attn( + positions=positions, + hidden_states=hidden_states, + forward_batch=forward_batch, + ) + append: "dumper.dump('attn_output', hidden_states, dims='t h[attn_tp:partial] # tp:replicated')" + - match: | + hidden_states, residual = self.layer_communicator.prepare_mlp( + hidden_states, residual, forward_batch + ) + append: "dumper.dump('pre_mlp_residual', hidden_states, dims='t h # tp:replicated')" + - match: | + hidden_states = self.mlp( + hidden_states, forward_batch, should_allreduce_fusion, use_reduce_scatter + ) + append: "dumper.dump('mlp_output', hidden_states, dims='t h[moe_tp:partial] # tp:replicated')" + + # --- attention internals --- + - target: sglang.srt.models.qwen3_moe.Qwen3MoeAttention.forward_core + edits: + - match: "output, _ = self.o_proj(attn_output)" + prepend: "dumper.dump('attn_pre_o_proj', attn_output, dims='t attn_h[attn_tp] # tp:replicated')" + + # --- moe internals --- + - target: sglang.srt.models.qwen3_moe.Qwen3MoeSparseMoeBlock.forward_normal + edits: + - match: "router_logits, _ = self.gate(hidden_states)" + append: "dumper.dump('moe_router_logits', router_logits, dims='t num_experts # tp:replicated')" + - match: "final_hidden_states = self.experts(hidden_states, topk_output)" + append: "dumper.dump('moe_expert_output', final_hidden_states, dims='t h[moe_tp:partial] # tp:replicated')" +""" + +PATCH_CONFIG_DP_ATTENTION_YAML: str = """\ +patches: + # --- decoder layer level (aligned with miles test) --- + # dp-attention TP=2 DP=2 uses only 2 GPUs: + # GPU 0: tp=0, attn_tp=0 (attn_tp_size=1), attn_dp=0 + # GPU 1: tp=1, attn_tp=0 (attn_tp_size=1), attn_dp=1 + # All sub-axes (attn_tp, moe_tp, attn_dp) are uniquely determined by tp_rank, + # so only tp:replicated is needed — sub-axes are auto-resolved as implicitly replicated. + # + # Attn tensors are NOT TP-sharded (attn_tp_size=1). + # mlp_output is still moe_tp:partial — the reduce-scatter happens in + # postprocess_layer(), after the dump point. + # layer_input is dumped after prepare_attn which DP-distributes tokens, + # so it needs dp:=attn_dp to filter to the non-empty DP rank. + - target: sglang.srt.models.qwen3_moe.Qwen3MoeDecoderLayer.forward + edits: + - match: | + hidden_states, residual = ( + self.layer_communicator.prepare_attn_and_capture_last_layer_outputs( + hidden_states, + residual, + forward_batch, + captured_last_layer_outputs=captured_last_layer_outputs, + **kwargs, + ) + ) + append: "dumper.dump('layer_input', hidden_states, dims='t h # tp:replicated dp:=attn_dp')" + - match: | + hidden_states = self.self_attn( + positions=positions, + hidden_states=hidden_states, + forward_batch=forward_batch, + ) + append: "dumper.dump('attn_output', hidden_states, dims='t h # tp:replicated')" + - match: | + hidden_states, residual = self.layer_communicator.prepare_mlp( + hidden_states, residual, forward_batch + ) + append: "dumper.dump('pre_mlp_residual', hidden_states, dims='t h # tp:replicated')" + - match: | + hidden_states = self.mlp( + hidden_states, forward_batch, should_allreduce_fusion, use_reduce_scatter + ) + append: "dumper.dump('mlp_output', hidden_states, dims='t h[moe_tp:partial] # tp:replicated')" + + # --- attention internals --- + - target: sglang.srt.models.qwen3_moe.Qwen3MoeAttention.forward_core + edits: + - match: "output, _ = self.o_proj(attn_output)" + prepend: "dumper.dump('attn_pre_o_proj', attn_output, dims='t attn_h # tp:replicated dp:=attn_dp')" + + # --- moe internals --- + - target: sglang.srt.models.qwen3_moe.Qwen3MoeSparseMoeBlock.forward_normal + edits: + - match: "router_logits, _ = self.gate(hidden_states)" + append: "dumper.dump('moe_router_logits', router_logits, dims='t num_experts # tp:replicated')" + - match: "final_hidden_states = self.experts(hidden_states, topk_output)" + append: "dumper.dump('moe_expert_output', final_hidden_states, dims='t h[moe_tp:partial] # tp:replicated')" +""" + + +class TestSourcePatcherE2ESGLang: + """E2E: patch Qwen3Moe forward -> dump -> compare.""" + + def test_patch_dump_and_compare(self, tmp_path: Path) -> None: + """TP=2 baseline vs TP=4 target.""" + _run_e2e_scenario( + tmp_path=tmp_path, + target_tp=TARGET_TP, + ) + + def test_dp_attention(self, tmp_path: Path) -> None: + """TP=2 baseline vs TP=2+DP=2+dp-attention target. + + In dp-attention mode (attn_tp_size=1, attn_dp_size=2), attention + tensors are NOT TP-sharded and mlp_output is still moe_tp:partial + (the reduce-scatter happens in postprocess_layer, after the dump + point). A separate patch config with corrected dims is used for + the target. + + Comparison is limited to step 0 (prefill) because the decode + step has tokens on both DP ranks, which breaks the dp:=attn_dp + single-rank assumption and causes comparator errors. + + The ``concat_steps`` token aligner is required because dp-attention + gathers tokens across DP ranks before the dump point, so the + non-empty rank's buffer holds the real tokens plus padding tokens + contributed by the empty DP rank (with a single request one DP + rank is always empty). The aligner reconstructs the real per-step + token sequence from the dumped seq-lens, trimming that padding so + the target lines up with the un-padded TP baseline. + + mlp_output is allowed to fail because the FusedMoE dispatcher + combine path may include an implicit all-reduce that makes the + dumped value differ from the raw partial expert output. All + other tensors (layer_input, attn_output, attn_pre_o_proj, + pre_mlp_residual, moe_router_logits, moe_expert_output) must + pass at step 0. + """ + _run_e2e_scenario( + tmp_path=tmp_path, + target_tp=BASELINE_TP, + extra_target_server_args=["--dp", "2", "--enable-dp-attention"], + target_patch_config_yaml=PATCH_CONFIG_DP_ATTENTION_YAML, + extra_comparator_args=[ + "--token-aligner", + "concat_steps", + "--end-step", + "0", + "--allow-failed-pattern", + "mlp_output", + ], + ) + + +# --------------------------------- helpers --------------------------------- + + +def _run_e2e_scenario( + *, + tmp_path: Path, + target_tp: int, + extra_target_server_args: Optional[list[str]] = None, + target_patch_config_yaml: Optional[str] = None, + extra_comparator_args: Optional[list[str]] = None, +) -> None: + """Full e2e: write patch config -> baseline run -> target run -> compare.""" + base_url: str = DEFAULT_URL_FOR_TEST + + baseline_config_path: Path = tmp_path / "patch_config.yaml" + baseline_config_path.write_text(PATCH_CONFIG_YAML) + + target_config_path: Path = tmp_path / "patch_config_target.yaml" + target_config_path.write_text(target_patch_config_yaml or PATCH_CONFIG_YAML) + + baseline_dir: Path = tmp_path / "baseline" + _run_server_and_generate( + dump_dir=baseline_dir, + config_path=baseline_config_path, + tp=BASELINE_TP, + base_url=base_url, + ) + _verify_patched_fields(dump_dir=baseline_dir, field_names=_FIELDS_TO_VERIFY) + + target_dir: Path = tmp_path / "target" + _run_server_and_generate( + dump_dir=target_dir, + config_path=target_config_path, + tp=target_tp, + base_url=base_url, + extra_server_args=extra_target_server_args, + ) + _verify_patched_fields(dump_dir=target_dir, field_names=_FIELDS_TO_VERIFY) + + baseline_exp: Path = baseline_dir / EXP_NAME + target_exp: Path = target_dir / EXP_NAME + + cmd: list[str] = [ + "python", + "-m", + "sglang.srt.debug_utils.comparator", + "--baseline-path", + str(baseline_exp), + "--target-path", + str(target_exp), + "--output-format", + "json", + "--allow-skipped-pattern", + "input_ids|positions", + ] + if extra_comparator_args: + cmd.extend(extra_comparator_args) + + result: subprocess.CompletedProcess[str] = subprocess.run( + cmd, + capture_output=True, + text=True, + ) + + debug_file: Path = _save_comparator_output( + stdout=result.stdout, stderr=result.stderr + ) + print(f"Comparator debug output: {debug_file}") + + assert result.returncode == 0, ( + f"Comparator failed (rc={result.returncode}). " f"Debug output: {debug_file}" + ) + + +def _run_server_and_generate( + *, + dump_dir: Path, + config_path: Path, + tp: int, + base_url: str, + extra_server_args: Optional[list[str]] = None, +) -> None: + """Launch SGLang server with source patcher + dumper, send a generate request.""" + env: dict[str, str] = { + **os.environ, + "DUMPER_SOURCE_PATCHER_CONFIG": str(config_path), + "DUMPER_DIR": str(dump_dir), + "DUMPER_EXP_NAME": EXP_NAME, + "DUMPER_SERVER_PORT": "reuse", + } + + server_args: list[str] = [ + "--tp", + str(tp), + "--max-total-tokens", + "128", + "--mem-fraction-static", + "0.5", + "--disable-cuda-graph", + "--cuda-graph-backend-prefill=disabled", + "--disable-radix-cache", + ] + if extra_server_args: + server_args.extend(extra_server_args) + + proc = popen_launch_server( + MODEL, + base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=server_args, + env=env, + ) + try: + requests.post( + f"{base_url}/dumper/configure", + json={ + "enable": True, + "filter": DUMPER_FILTER, + "cleanup_previous": True, + }, + ).raise_for_status() + + resp = requests.post( + f"{base_url}/generate", + json={ + "text": "The capital of France is", + "sampling_params": {"max_new_tokens": 1, "temperature": 0}, + }, + ) + assert resp.status_code == 200, f"Generate failed: {resp.text}" + finally: + kill_process_tree(proc.pid) + + +def _verify_patched_fields(*, dump_dir: Path, field_names: list[str]) -> None: + """Verify that patched dump fields exist as .pt files.""" + for field in field_names: + matches: list[Path] = list(dump_dir.rglob(f"*name={field}*.pt")) + assert len(matches) > 0, ( + f"Expected patched field '{field}' not found under {dump_dir}. " + f"Available files: {sorted(f.name for f in dump_dir.rglob('*.pt'))[:20]}" + ) + + +def _save_comparator_output(*, stdout: str, stderr: str) -> Path: + """Save comparator stdout+stderr to a temp file that persists for debugging.""" + fd, path_str = tempfile.mkstemp(prefix="comparator_e2e_", suffix=".log", dir="/tmp") + with os.fdopen(fd, "w") as f: + f.write("=== STDOUT ===\n") + f.write(stdout) + f.write("\n=== STDERR ===\n") + f.write(stderr) + return Path(path_str) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/test_nightly_precision_regression.py b/asian_ai/performance/SGLang/test/registered/debug_utils/test_nightly_precision_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..1fc7e1715491d9d68971ff2c77993686ab1bacbc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/test_nightly_precision_regression.py @@ -0,0 +1,758 @@ +"""Nightly precision regression CI test: dump per-layer hidden states and +compare day-over-day against a rolling baseline. + +Env knobs: + SGLANG_PRECISION_MODELS comma-separated model ids (default GLM-5.2-FP8) + SGLANG_PRECISION_BASELINE_DIR local baseline dir + SGLANG_PRECISION_DIFF_THRESHOLD per-tensor rel_diff cutoff (default 1e-3) + SGLANG_PRECISION_FORCE_UPDATE=1 skip comparison, refresh baseline + SGLANG_PRECISION_COMMIT override sglang sha (7-40 hex) tagged on push + SGLANG_PRECISION_HF_REPO required HF dataset repo for cross-runner + baseline storage; see precision_baseline_store +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +import warnings +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Optional + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + ModelLaunchSettings, + is_in_ci, + parse_models, + popen_launch_server, + write_github_step_summary, +) + +# Soft dep: missing huggingface_hub → import fails loudly in setUpClass. +try: + from sglang.test import precision_baseline_store as _hfs +except Exception: # pragma: no cover + _hfs = None + +register_cuda_ci(est_time=3600, suite="nightly-precision-8-gpu-h200", nightly=True) + +DEFAULT_MODELS_FOR_NIGHTLY_PRECISION = "zai-org/GLM-5.2-FP8" +DEFAULT_DIFF_THRESHOLD = 1e-3 +# Fallback when the layer count can't be resolved: never silently shrink coverage. +DUMPER_FILTER_ALL_LAYERS = ( + r"match(r'^non_intrusive__model\.layers\.\d+\.inputs\.1$', name)" +) +LAYER_CAPTURE_STRIDE = 8 +MAX_TOKENS = 2 +SCHEMA_VERSION = 3 +EXP_NAME = "nightly_precision" +PROMPT = "The capital of France is" +NIGHTLY_PRECISION_SERVER_TIMEOUT = 3600 +# Pin fusion ON: captured inputs.1 must be TP-partial (the comparator's tp:partial +# contract), and SM90 auto-enable was dropped in #23402. +PRECISION_FUSION_BACKEND = "trtllm" + + +def _sanitize_model_name(model: str) -> str: + return model.replace("/", "__").replace(" ", "_") + + +def _select_capture_layers( + num_layers: int, stride: int = LAYER_CAPTURE_STRIDE +) -> list[int]: + # First + last + every stride-th: the residual stream is cumulative, so the + # last layer still reflects drift originating in any earlier layer. + layers = set(range(0, num_layers, stride)) + layers.add(0) + layers.add(num_layers - 1) + return sorted(i for i in layers if 0 <= i < num_layers) + + +def _build_dumper_filter(capture_layers: Optional[list[int]]) -> str: + if not capture_layers: + return DUMPER_FILTER_ALL_LAYERS + # The dumper evals this with builtins stripped (no int()/arithmetic), so the + # layer subset is baked into the regex; longest-first avoids ambiguous matches. + alt = "|".join( + str(i) for i in sorted(capture_layers, key=lambda x: (-len(str(x)), x)) + ) + return rf"match(r'^non_intrusive__model\.layers\.({alt})\.inputs\.1$', name)" + + +def _resolve_num_layers(model_path: str) -> Optional[int]: + # None on any failure -> caller captures every layer rather than a wrong subset. + try: + from transformers import AutoConfig + + config = AutoConfig.from_pretrained(model_path, trust_remote_code=True) + except Exception as e: + warnings.warn(f"could not load config for {model_path}: {e}") + return None + text_config = getattr(config, "text_config", None) # VL configs nest LM dims here + for obj in (text_config, config): + if obj is None: + continue + for attr in ("num_hidden_layers", "num_layers"): + n = getattr(obj, attr, None) + if isinstance(n, int) and n > 0: + return n + warnings.warn(f"could not read layer count from config for {model_path}") + return None + + +def _assert_decode_captured(exp_dir: Path, *, tp_size: int) -> None: + # One dump per (layer, rank) == prefill only: decode never ran, which would + # pass the comparison while silently halving coverage. Fail loudly instead. + pts = list(exp_dir.glob("*.pt")) + if not pts: + raise AssertionError(f"no .pt dumps produced in {exp_dir}") + layers: set[str] = set() + steps: set[str] = set() + for p in pts: + for kv in p.stem.split("___"): + if kv.startswith("layer_id="): + layers.add(kv[len("layer_id=") :]) + elif kv.startswith("step="): + steps.add(kv[len("step=") :]) + prefill_only = len(layers) * tp_size + if len(pts) <= prefill_only: + raise AssertionError( + f"decode path not captured: {len(pts)} .pt files for {len(layers)} " + f"layers x {tp_size} tp (== {prefill_only}, prefill-only); " + f"steps={sorted(steps)}. The model generated no decode tokens " + f"(check --max-total-tokens vs the decode reservation, max_tokens, " + f"and ignore_eos)." + ) + + +def _capture_signature(dump_cfg: dict[str, Any], tp_size: int) -> str: + # Identifies the dump shape; fetch only compares against baselines with the + # same signature, so changing layers/forwards/tp re-establishes cleanly + # instead of erroring against incompatible tensors. + raw = "|".join( + str(x) + for x in ( + SCHEMA_VERSION, + dump_cfg["max_tokens"], + dump_cfg["ignore_eos"], + tp_size, + dump_cfg["dumper_filter"], + dump_cfg["fusion_backend"], + ) + ) + return hashlib.sha1(raw.encode()).hexdigest()[:12] + + +_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,40}$") + + +def _get_git_commit() -> str: + val = os.environ.get("SGLANG_PRECISION_COMMIT", "").strip() + if _SHA_RE.match(val): + return val + try: + return ( + subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], timeout=10) + .decode() + .strip() + ) + except Exception: + return "unknown" + + +_NVIDIA_SMI_NAME_RE = re.compile(r"NVIDIA\s+([A-Za-z0-9]+)") + + +def _collect_runtime_context() -> dict[str, Any]: + # Each probe is independently guarded — missing nvidia-smi/torch never blocks. + ctx: dict[str, Any] = {} + try: + import torch + + ctx["torch_version"] = torch.__version__ + if torch.version.cuda: + ctx["cuda_version"] = torch.version.cuda + if torch.cuda.is_available(): + ctx["num_gpus"] = torch.cuda.device_count() + except Exception: + pass + try: + import sglang + + ctx["sglang_version"] = getattr(sglang, "__version__", None) + except Exception: + pass + try: + out = subprocess.check_output( + ["nvidia-smi", "-L"], stderr=subprocess.DEVNULL, timeout=5 + ).decode() + m = _NVIDIA_SMI_NAME_RE.search(out) + if m: + ctx["hardware"] = m.group(1) + except Exception: + pass + return ctx + + +def _collect_ci_context() -> dict[str, Any]: + ctx: dict[str, Any] = {} + run_id = os.environ.get("GITHUB_RUN_ID") + if run_id: + ctx["ci_run_id"] = run_id + server = os.environ.get("GITHUB_SERVER_URL", "https://github.com") + repo = os.environ.get("GITHUB_REPOSITORY", "") + if repo: + ctx["ci_run_url"] = f"{server}/{repo}/actions/runs/{run_id}" + for env_key, meta_key in ( + ("GITHUB_ACTOR", "ci_actor"), + ("GITHUB_REF", "git_ref"), + ("GITHUB_WORKFLOW", "ci_workflow"), + ): + v = os.environ.get(env_key) + if v: + ctx[meta_key] = v + return ctx + + +def _parse_comparator_stats(stdout: str) -> dict[str, Any]: + # Only passing records contribute to max/mean — failed records' rel_diff + # would corrupt the headline. NaN/inf is dropped before aggregation. + n_total = 0 + n_passed = 0 + n_failed = 0 + rel_diffs: list[float] = [] + abs_diffs: list[float] = [] + failing: list[str] = [] + + def _record_failure(name: str) -> None: + nonlocal n_failed + n_failed += 1 + if len(failing) < 10: + failing.append(name) + + def _safe_float(v: Any) -> Optional[float]: + if v is None: + return None + try: + f = float(v) + except (TypeError, ValueError): + return None + return f if math.isfinite(f) else None + + for line in stdout.strip().splitlines(): + try: + rec = json.loads(line) + except json.JSONDecodeError: + continue + if rec.get("type") != "comparison_tensor": + continue + n_total += 1 + name = rec.get("name", "?") + diff = rec.get("diff") or {} + if rec.get("errors"): + _record_failure(name) + continue + if not diff.get("passed", True): + _record_failure(name) + continue + bad_rep = next( + (c for c in rec.get("replicated_checks", []) if not c.get("passed", True)), + None, + ) + if bad_rep is not None: + _record_failure(name) + continue + rel = _safe_float(diff.get("rel_diff")) + if rel is not None: + rel_diffs.append(rel) + abs_ = _safe_float(diff.get("abs_diff")) + if abs_ is not None: + abs_diffs.append(abs_) + n_passed += 1 + + out: dict[str, Any] = { + "num_layers_compared": n_total, + "num_layers_passed": n_passed, + "num_layers_failed": n_failed, + } + if rel_diffs: + out["max_rel_diff"] = max(rel_diffs) + out["mean_rel_diff"] = sum(rel_diffs) / len(rel_diffs) + if abs_diffs: + out["max_abs_diff"] = max(abs_diffs) + if failing: + out["failing_layers"] = failing + return out + + +class TestNightlyPrecisionRegression(unittest.TestCase): + @classmethod + def setUpClass(cls): + models_str = os.environ.get( + "SGLANG_PRECISION_MODELS", DEFAULT_MODELS_FOR_NIGHTLY_PRECISION + ) + cls.models = [ + ModelLaunchSettings(m, tp_size=8) for m in parse_models(models_str) + ] + cls.baseline_dir = Path( + os.environ.get( + "SGLANG_PRECISION_BASELINE_DIR", "/tmp/sglang_precision_baselines" + ) + ) + cls.baseline_dir.mkdir(parents=True, exist_ok=True) + cls.diff_threshold = float( + os.environ.get( + "SGLANG_PRECISION_DIFF_THRESHOLD", str(DEFAULT_DIFF_THRESHOLD) + ) + ) + cls.force_update = os.environ.get("SGLANG_PRECISION_FORCE_UPDATE", "0") == "1" + cls.base_url = DEFAULT_URL_FOR_TEST + + if _hfs is None: + raise RuntimeError( + "precision baseline store unavailable: could not import " + "sglang.test.precision_baseline_store" + ) + # Raises if SGLANG_PRECISION_HF_REPO is unset — the test requires a + # remote baseline store, there is no local-only mode. + cls.hf_cfg = _hfs.HfStoreConfig.from_env() + + def test_precision_all_models(self): + warnings.filterwarnings( + "ignore", category=ResourceWarning, message="unclosed.*socket" + ) + all_results = [] + for model_setup in self.models: + with self.subTest(model=model_setup.model_path): + try: + result = _test_one_model( + model_setup=model_setup, + baseline_dir=self.baseline_dir, + diff_threshold=self.diff_threshold, + force_update=self.force_update, + base_url=self.base_url, + hf_cfg=self.hf_cfg, + ) + all_results.append(result) + except Exception as e: + all_results.append((model_setup.model_path, "ERROR", str(e))) + + _report_summary(all_results) + + failed = [r for r in all_results if r[1] == "FAILED"] + errored = [r for r in all_results if r[1] == "ERROR"] + if failed or errored: + msg = "Nightly precision regression failures:\n" + for model, status, details in failed + errored: + msg += f" {model}: {status} - {details}\n" + self.fail(msg) + + +def _test_one_model( + *, + model_setup: ModelLaunchSettings, + baseline_dir: Path, + diff_threshold: float, + force_update: bool, + base_url: str, + hf_cfg, +): + model = model_setup.model_path + model_dir_name = _sanitize_model_name(model) + model_baseline_dir = baseline_dir / model_dir_name + baseline_exp_dir = model_baseline_dir / EXP_NAME + + # Resolve the capture shape once and reuse it for the dump request and every + # meta push, so the manifest always reflects exactly what was dumped. + num_layers = _resolve_num_layers(model) + capture_layers = _select_capture_layers(num_layers) if num_layers else None + dump_cfg = { + "max_tokens": MAX_TOKENS, + "ignore_eos": True, + "dumper_filter": _build_dumper_filter(capture_layers), + "num_hidden_layers": num_layers, + "capture_layers": capture_layers, + "fusion_backend": PRECISION_FUSION_BACKEND, + } + dump_cfg["capture_signature"] = _capture_signature(dump_cfg, model_setup.tp_size) + + _maybe_hf_fetch( + hf_cfg=hf_cfg, + model=model, + baseline_exp_dir=baseline_exp_dir, + capture_signature=dump_cfg["capture_signature"], + ) + + with tempfile.TemporaryDirectory() as today_tmp: + today_dump_dir = Path(today_tmp) + _run_server_and_dump( + model_setup=model_setup, + dump_dir=today_dump_dir, + base_url=base_url, + dumper_filter=dump_cfg["dumper_filter"], + max_tokens=dump_cfg["max_tokens"], + ignore_eos=dump_cfg["ignore_eos"], + ) + today_exp_dir = today_dump_dir / EXP_NAME + _assert_decode_captured(today_exp_dir, tp_size=model_setup.tp_size) + + has_baseline = baseline_exp_dir.exists() and any(baseline_exp_dir.glob("*.pt")) + + if has_baseline and not force_update: + result = _run_comparator( + baseline=baseline_exp_dir, + target=today_exp_dir, + threshold=diff_threshold, + ) + debug_file = _save_comparator_output( + stdout=result.stdout, stderr=result.stderr, prefix=model_dir_name + ) + print(f"Comparator output for {model}: {debug_file}") + report_path = model_baseline_dir / "comparator_report.jsonl" + report_path.parent.mkdir(parents=True, exist_ok=True) + report_path.write_text(result.stdout, encoding="utf-8") + comparator_stats = _parse_comparator_stats(result.stdout) + if comparator_stats.get("num_layers_compared", 0) == 0: + # A clean returncode with nothing compared means the baseline + # and target tensor names never lined up — fail loudly rather + # than pass on an empty comparison. + return ( + model, + "FAILED", + "comparator compared 0 layers (baseline/target name mismatch?)", + ) + + if result.returncode == 0: + _update_baseline(model_baseline_dir, today_exp_dir) + _maybe_hf_push( + hf_cfg=hf_cfg, + model=model, + model_setup=model_setup, + tensors_dir=baseline_exp_dir, + pass_label="passed", + diff_threshold=diff_threshold, + dump_cfg=dump_cfg, + comparator_report=report_path, + comparator_stats=comparator_stats, + ) + return (model, "PASSED", "comparison ok, baseline updated") + # FAILED: push today's tensors as pass_label="failed" so the + # diagnostic diff survives on HF without rerunning the comparator. + _maybe_hf_push( + hf_cfg=hf_cfg, + model=model, + model_setup=model_setup, + tensors_dir=today_exp_dir, + pass_label="failed", + diff_threshold=diff_threshold, + dump_cfg=dump_cfg, + comparator_report=report_path, + comparator_stats=comparator_stats, + ) + summary = _extract_diff_summary(result.stdout) + return (model, "FAILED", summary) + else: + _update_baseline(model_baseline_dir, today_exp_dir) + _maybe_hf_push( + hf_cfg=hf_cfg, + model=model, + model_setup=model_setup, + tensors_dir=baseline_exp_dir, + pass_label="baseline_established", + diff_threshold=diff_threshold, + dump_cfg=dump_cfg, + comparator_report=None, + comparator_stats=None, + ) + reason = "forced update" if force_update else "first run" + return (model, "BASELINE_ESTABLISHED", reason) + + +def _maybe_hf_fetch( + *, hf_cfg, model: str, baseline_exp_dir: Path, capture_signature: str +) -> None: + if baseline_exp_dir.exists() and any(baseline_exp_dir.glob("*.pt")): + return + try: + src = _hfs.fetch_latest_baseline( + config=hf_cfg, + model=model, + target_tensors_dir=baseline_exp_dir, + capture_signature=capture_signature, + ) + if src is not None: + print(f"[hf-store] restored baseline for {model} from {src}", flush=True) + except Exception as e: + msg = f"[hf-store] fetch failed for {model}: {e}" + if os.environ.get("GITHUB_RUN_ID"): + raise RuntimeError(msg) from e + warnings.warn(msg) + + +def _maybe_hf_push( + *, + hf_cfg, + model: str, + model_setup: ModelLaunchSettings, + tensors_dir: Path, + pass_label: str, + diff_threshold: float, + dump_cfg: dict[str, Any], + comparator_report: Optional[Path] = None, + comparator_stats: Optional[dict[str, Any]] = None, +) -> None: + # Under CI a push failure raises rather than warns, so a misconfigured + # store can't quietly mask the regression-detection guarantee. + pt_files = list(tensors_dir.glob("*.pt")) + if not pt_files: + return + try: + meta: dict[str, Any] = { + "schema_version": SCHEMA_VERSION, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "model": model, + "sglang_commit": _get_git_commit(), + "tp_size": model_setup.tp_size, + "prompt": PROMPT, + "max_tokens": dump_cfg["max_tokens"], + "ignore_eos": dump_cfg["ignore_eos"], + "temperature": 0, + "diff_threshold": diff_threshold, + "dumper_filter": dump_cfg["dumper_filter"], + "num_hidden_layers": dump_cfg.get("num_hidden_layers"), + "capture_layers": dump_cfg.get("capture_layers"), + "capture_signature": dump_cfg.get("capture_signature"), + "fusion_backend": dump_cfg.get("fusion_backend"), + "num_tensor_files": len(pt_files), + "pass_label": pass_label, + "source": "test_nightly_precision_regression.py", + } + meta.update(_collect_runtime_context()) + meta.update(_collect_ci_context()) + if comparator_stats: + meta.update(comparator_stats) + run_path = _hfs.push_run( + config=hf_cfg, + model=model, + sglang_commit=meta["sglang_commit"], + today_tensors_dir=tensors_dir, + meta=meta, + comparator_report=comparator_report, + ) + print( + f"[hf-store] {pass_label} {len(pt_files)} tensors for {model} -> {run_path}", + flush=True, + ) + except Exception as e: + msg = f"[hf-store] push failed for {model}: {e}" + if os.environ.get("GITHUB_RUN_ID"): + raise RuntimeError(msg) from e + warnings.warn(msg) + + +def _run_server_and_dump( + *, + model_setup: ModelLaunchSettings, + dump_dir: Path, + base_url: str, + dumper_filter: str, + max_tokens: int, + ignore_eos: bool, +): + env: dict[str, str] = { + **os.environ, + "DUMPER_DIR": str(dump_dir), + "DUMPER_EXP_NAME": EXP_NAME, + "DUMPER_SERVER_PORT": "reuse", + "DUMPER_NON_INTRUSIVE_MODE": "all", + } + + server_args: list[str] = list(model_setup.extra_args or []) + [ + # Below the scheduler's decode-token reservation (default 512) the KV + # pool clamps max_new_tokens to 0, so decode never runs and max_tokens>1 + # has no effect. Keep it well above that. + "--max-total-tokens", + "4096", + "--mem-fraction-static", + "0.9", + "--disable-cuda-graph", + "--disable-piecewise-cuda-graph", + "--disable-radix-cache", + # Explicit `trtllm`, not `auto` (which resolves to mnnvl on SM90). + "--flashinfer-allreduce-fusion-backend", + PRECISION_FUSION_BACKEND, + ] + + proc = popen_launch_server( + model_setup.model_path, + base_url, + timeout=NIGHTLY_PRECISION_SERVER_TIMEOUT, + other_args=server_args, + env=env, + ) + try: + requests.post( + f"{base_url}/dumper/configure", + json={ + "enable": True, + "filter": dumper_filter, + "cleanup_previous": True, + }, + timeout=60, + ).raise_for_status() + + resp = requests.post( + f"{base_url}/v1/chat/completions", + json={ + "model": model_setup.model_path, + "messages": [{"role": "user", "content": PROMPT}], + "max_tokens": max_tokens, + "temperature": 0, + # Without this the model may EOS on the first token and never + # enter the decode loop, leaving the decode path uncaptured. + "ignore_eos": ignore_eos, + }, + timeout=600, + ) + if resp.status_code != 200: + raise RuntimeError(f"Chat completions failed: {resp.text}") + finally: + kill_process_tree(proc.pid) + + +def _run_comparator( + *, baseline: Path, target: Path, threshold: float +) -> subprocess.CompletedProcess[str]: + cmd: list[str] = [ + sys.executable, + "-m", + "sglang.srt.debug_utils.comparator", + "--baseline-path", + str(baseline), + "--target-path", + str(target), + "--diff-threshold", + str(threshold), + "--output-format", + "json", + "--allow-skipped-pattern", + "input_ids|positions|seq_lens|req_pool_indices|rids", + # inputs.1 is hidden_states entering the layer (inputs.0 = positions). + # LayerCommunicator defers the cross-layer allreduce, so layer N sees + # per-tp partial sums; bs h[tp:partial] sums across tp on the h axis + # before diffing. + "--override-dims", + r"^non_intrusive__model\.layers\.\d+\.inputs\.1$:bs h[tp:partial]", + ] + return subprocess.run(cmd, capture_output=True, text=True, timeout=300) + + +def _update_baseline(model_baseline_dir: Path, today_exp_dir: Path): + final_dir = model_baseline_dir / EXP_NAME + staging_dir = model_baseline_dir / "_staging" + old_dir = model_baseline_dir / "_old_baseline" + + if staging_dir.exists(): + shutil.rmtree(staging_dir) + shutil.copytree(today_exp_dir, staging_dir) + + meta = { + "timestamp": datetime.now(timezone.utc).isoformat(), + "commit": _get_git_commit(), + } + (staging_dir.parent / "baseline_meta.json").write_text( + json.dumps(meta, indent=2), encoding="utf-8" + ) + + if final_dir.exists(): + if old_dir.exists(): + shutil.rmtree(old_dir) + final_dir.rename(old_dir) + + staging_dir.rename(final_dir) + + if old_dir.exists(): + shutil.rmtree(old_dir) + + +def _extract_diff_summary(stdout: str) -> str: + for line in stdout.strip().splitlines(): + try: + record = json.loads(line) + except json.JSONDecodeError: + continue + if record.get("type") != "comparison_tensor": + continue + if record.get("errors"): + name = record.get("name", "unknown") + return f"tensor={name} errored" + diff = record.get("diff") or {} + if diff and not diff.get("passed", True): + name = record.get("name", "unknown") + rel_diff = diff.get("rel_diff", "N/A") + return f"tensor={name} rel_diff={rel_diff}" + bad_replicated = next( + ( + c + for c in record.get("replicated_checks", []) + if not c.get("passed", True) + ), + None, + ) + if bad_replicated is not None: + name = record.get("name", "unknown") + axis = bad_replicated.get("axis", "?") + return f"tensor={name} replicated_check_failed axis={axis}" + return stdout[-200:] if stdout else "no output" + + +def _save_comparator_output(*, stdout: str, stderr: str, prefix: str) -> Path: + fd, path_str = tempfile.mkstemp( + prefix=f"nightly_precision_{prefix}_", suffix=".log", dir="/tmp" + ) + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write("=== STDOUT ===\n") + f.write(stdout) + f.write("\n=== STDERR ===\n") + f.write(stderr) + return Path(path_str) + + +def _report_summary(results): + lines = ["\n" + "=" * 60] + lines.append("Nightly Precision Regression Summary") + lines.append("=" * 60) + lines.append(f"{'Model':<45} {'Status':<25} Details") + lines.append("-" * 60) + + for model, status, details in results: + lines.append(f"{model:<45} {status:<25} {details[:80]}") + + lines.append("=" * 60) + summary = "\n".join(lines) + print(summary, flush=True) + + if is_in_ci(): + md = "## Nightly Precision Regression\n\n" + md += "| Model | Status | Details |\n" + md += "|-------|--------|--------|\n" + for model, status, details in results: + md += f"| {model} | {status} | {details[:100]} |\n" + write_github_step_summary(md) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/test_schedule_simulator.py b/asian_ai/performance/SGLang/test/registered/debug_utils/test_schedule_simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..e98f7765d51e71ce066745cefb6771e7289d54f6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/test_schedule_simulator.py @@ -0,0 +1,842 @@ +import json +import subprocess +import sys +import tempfile +import unittest + +from sglang.srt.debug_utils.schedule_simulator import ( + AttentionComputeBalancednessRecorder, + BatchSizeBalancednessRecorder, + FIFOScheduler, + GPUState, + RandomRouter, + RoundRobinRouter, + SimRequest, + SimulationResult, + Simulator, + StepRecord, + StickyRouter, + create_arg_parser, + generate_gsp_requests, + generate_random_requests, + load_from_request_logger, + main, +) +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=120, suite="base-a-test-cpu", nightly=True) +register_cpu_ci(est_time=338, suite="base-c-test-cpu") + +# ==================== Non-E2E Tests ==================== + + +class TestSimRequest(CustomTestCase): + def test_basic(self): + req = SimRequest(request_id="r1", input_len=100, output_len=50) + self.assertEqual(req.decoded_tokens, 0) + self.assertEqual(req.seq_len(), 100) + self.assertFalse(req.is_finished()) + + def test_seq_len_with_decoded(self): + req = SimRequest( + request_id="r1", input_len=100, output_len=50, decoded_tokens=10 + ) + self.assertEqual(req.seq_len(), 110) + + def test_is_finished(self): + req = SimRequest( + request_id="r1", input_len=100, output_len=50, decoded_tokens=50 + ) + self.assertTrue(req.is_finished()) + + +class TestGPUState(CustomTestCase): + def test_batch_size(self): + gpu = GPUState(gpu_id=0, max_total_tokens=10000) + self.assertEqual(gpu.batch_size(), 0) + gpu.running_requests = [ + SimRequest(request_id="r1", input_len=100, output_len=50), + SimRequest(request_id="r2", input_len=200, output_len=100), + ] + self.assertEqual(gpu.batch_size(), 2) + + def test_total_seq_len(self): + gpu = GPUState(gpu_id=0, max_total_tokens=10000) + gpu.running_requests = [ + SimRequest(request_id="r1", input_len=100, output_len=50), + SimRequest( + request_id="r2", input_len=200, output_len=100, decoded_tokens=10 + ), + ] + self.assertEqual(gpu.total_seq_len(), 100 + 210) + + def test_total_seq_len_shared_prefix(self): + gpu = GPUState(gpu_id=0, max_total_tokens=10000) + gpu.running_requests = [ + SimRequest( + request_id="r1", + input_len=150, + output_len=50, + group_id="g0", + prefix_len=100, + ), + SimRequest( + request_id="r2", + input_len=150, + output_len=50, + group_id="g0", + prefix_len=100, + ), + ] + self.assertEqual(gpu.total_seq_len(), 150 + 50) + + def test_total_seq_len_shared_prefix_with_decoded(self): + gpu = GPUState(gpu_id=0, max_total_tokens=10000) + gpu.running_requests = [ + SimRequest( + request_id="r1", + input_len=150, + output_len=50, + decoded_tokens=10, + group_id="g0", + prefix_len=100, + ), + SimRequest( + request_id="r2", + input_len=150, + output_len=50, + decoded_tokens=5, + group_id="g0", + prefix_len=100, + ), + ] + self.assertEqual(gpu.total_seq_len(), 160 + 55) + + def test_total_seq_len_multiple_groups(self): + gpu = GPUState(gpu_id=0, max_total_tokens=10000) + gpu.running_requests = [ + SimRequest( + request_id="r1", + input_len=150, + output_len=50, + group_id="g0", + prefix_len=100, + ), + SimRequest( + request_id="r2", + input_len=150, + output_len=50, + group_id="g0", + prefix_len=100, + ), + SimRequest( + request_id="r3", + input_len=200, + output_len=50, + group_id="g1", + prefix_len=150, + ), + SimRequest(request_id="r4", input_len=80, output_len=20), + ] + self.assertEqual(gpu.total_seq_len(), 150 + 50 + 200 + 80) + + +class TestRouters(CustomTestCase): + def test_round_robin(self): + router = RoundRobinRouter(num_gpus=4) + req = SimRequest(request_id="r1", input_len=100, output_len=50) + results = [router.route(req) for _ in range(8)] + self.assertEqual(results, [0, 1, 2, 3, 0, 1, 2, 3]) + + def test_random_router(self): + router = RandomRouter(num_gpus=4) + req = SimRequest(request_id="r1", input_len=100, output_len=50) + results = [router.route(req) for _ in range(100)] + self.assertTrue(all(0 <= r < 4 for r in results)) + + def test_sticky_router_same_group_same_gpu(self): + router = StickyRouter(num_gpus=4) + reqs = [ + SimRequest(request_id=f"r{i}", input_len=100, output_len=50, group_id="g0") + for i in range(10) + ] + results = [router.route(req) for req in reqs] + self.assertEqual(len(set(results)), 1) + + def test_sticky_router_no_group_fallback(self): + router = StickyRouter(num_gpus=4) + reqs = [ + SimRequest(request_id=f"r{i}", input_len=100, output_len=50) + for i in range(100) + ] + results = [router.route(req) for req in reqs] + self.assertTrue(all(0 <= r < 4 for r in results)) + + def test_sticky_router_multiple_groups(self): + router = StickyRouter(num_gpus=4) + for group_id in ["g0", "g1", "g2"]: + reqs = [ + SimRequest( + request_id=f"{group_id}_r{i}", + input_len=100, + output_len=50, + group_id=group_id, + ) + for i in range(5) + ] + results = [router.route(req) for req in reqs] + self.assertEqual(len(set(results)), 1) + + +class TestFIFOScheduler(CustomTestCase): + def test_runs_pending_requests(self): + scheduler = FIFOScheduler() + gpu = GPUState(gpu_id=0, max_total_tokens=10000) + gpu.pending_requests = [ + SimRequest(request_id=f"r{i}", input_len=100, output_len=50) + for i in range(3) + ] + scheduler.schedule(gpu) + self.assertEqual(len(gpu.running_requests), 3) + self.assertEqual(len(gpu.pending_requests), 0) + + def test_respects_token_limit(self): + scheduler = FIFOScheduler() + gpu = GPUState(gpu_id=0, max_total_tokens=250) + gpu.pending_requests = [ + SimRequest(request_id=f"r{i}", input_len=100, output_len=50) + for i in range(5) + ] + scheduler.schedule(gpu) + self.assertEqual(len(gpu.running_requests), 2) + self.assertEqual(len(gpu.pending_requests), 3) + + def test_evicts_lifo_when_over_budget(self): + scheduler = FIFOScheduler() + gpu = GPUState(gpu_id=0, max_total_tokens=250) + gpu.running_requests = [ + SimRequest(request_id=f"r{i}", input_len=100, output_len=50) + for i in range(3) + ] # 300 tokens total + scheduler.schedule(gpu) + self.assertEqual(len(gpu.running_requests), 2) + self.assertEqual(len(gpu.pending_requests), 1) + self.assertEqual(gpu.pending_requests[0].request_id, "r2") + + +class TestMetrics(CustomTestCase): + def test_batch_size_balancedness(self): + recorder = BatchSizeBalancednessRecorder() + gpu_states = [GPUState(gpu_id=i, max_total_tokens=10000) for i in range(2)] + gpu_states[0].running_requests = [ + SimRequest(request_id="r1", input_len=100, output_len=50) + ] + gpu_states[1].running_requests = [ + SimRequest(request_id="r2", input_len=100, output_len=50), + SimRequest(request_id="r3", input_len=100, output_len=50), + ] + recorder.on_step_end(0, gpu_states) + self.assertAlmostEqual( + recorder.get_summary()["batch_size_balancedness_mean"], 0.75 + ) + + def test_attention_compute_balancedness(self): + recorder = AttentionComputeBalancednessRecorder() + gpu_states = [GPUState(gpu_id=i, max_total_tokens=10000) for i in range(2)] + gpu_states[0].running_requests = [ + SimRequest(request_id="r1", input_len=100, output_len=50) + ] + gpu_states[1].running_requests = [ + SimRequest(request_id="r2", input_len=200, output_len=50) + ] + recorder.on_step_end(0, gpu_states) + self.assertAlmostEqual( + recorder.get_summary()["attention_compute_balancedness_mean"], 0.75 + ) + + def test_empty_history(self): + recorder = BatchSizeBalancednessRecorder() + self.assertEqual(recorder.get_summary()["batch_size_balancedness_mean"], 0.0) + + def test_all_zero_batch_size(self): + recorder = BatchSizeBalancednessRecorder() + gpu_states = [GPUState(gpu_id=i, max_total_tokens=10000) for i in range(2)] + recorder.on_step_end(0, gpu_states) + self.assertAlmostEqual( + recorder.get_summary()["batch_size_balancedness_mean"], 1.0 + ) + + +class TestDataLoader(CustomTestCase): + def test_load_from_request_logger(self): + log_data = [ + {"event": "request.received", "rid": "r1", "obj": {"text": "hello"}}, + { + "event": "request.finished", + "rid": "r1", + "out": {"meta_info": {"prompt_tokens": 100, "completion_tokens": 50}}, + }, + { + "event": "request.finished", + "rid": "r2", + "out": {"meta_info": {"prompt_tokens": 200, "completion_tokens": 100}}, + }, + ] + with tempfile.NamedTemporaryFile(mode="w", suffix=".log", delete=False) as f: + for item in log_data: + f.write(json.dumps(item) + "\n") + f.flush() + requests = load_from_request_logger(f.name) + + self.assertEqual(len(requests), 2) + self.assertEqual(requests[0].request_id, "r1") + self.assertEqual(requests[0].input_len, 100) + self.assertEqual(requests[1].input_len, 200) + + def test_empty_file(self): + with tempfile.NamedTemporaryFile(mode="w", suffix=".log", delete=False) as f: + f.write("") + f.flush() + self.assertEqual(len(load_from_request_logger(f.name)), 0) + + +class TestDataSynthesis(CustomTestCase): + def test_generate_basic(self): + requests = generate_random_requests( + num_requests=10, input_len=100, output_len=50 + ) + self.assertEqual(len(requests), 10) + for req in requests: + self.assertEqual(req.input_len, 100) + self.assertEqual(req.output_len, 50) + + def test_generate_with_range_ratio(self): + requests = generate_random_requests( + num_requests=100, input_len=100, output_len=50, range_ratio=0.5, seed=42 + ) + for req in requests: + self.assertGreaterEqual(req.input_len, 50) + self.assertLessEqual(req.input_len, 100) + + def test_generate_with_seed(self): + r1 = generate_random_requests( + num_requests=10, input_len=100, output_len=50, range_ratio=0.5, seed=42 + ) + r2 = generate_random_requests( + num_requests=10, input_len=100, output_len=50, range_ratio=0.5, seed=42 + ) + for a, b in zip(r1, r2): + self.assertEqual(a.input_len, b.input_len) + + def test_generate_gsp_basic(self): + requests = generate_gsp_requests( + num_groups=4, + prompts_per_group=3, + system_prompt_len=100, + question_len=50, + output_len=25, + seed=42, + ) + self.assertEqual(len(requests), 12) + for req in requests: + self.assertIsNotNone(req.group_id) + self.assertEqual(req.prefix_len, 100) + self.assertEqual(req.input_len, 150) + self.assertEqual(req.output_len, 25) + + def test_generate_gsp_group_assignment(self): + requests = generate_gsp_requests( + num_groups=3, + prompts_per_group=2, + system_prompt_len=100, + question_len=50, + output_len=25, + seed=42, + ) + group_counts = {} + for req in requests: + group_counts[req.group_id] = group_counts.get(req.group_id, 0) + 1 + self.assertEqual(len(group_counts), 3) + for count in group_counts.values(): + self.assertEqual(count, 2) + + def test_generate_gsp_with_range_ratio(self): + requests = generate_gsp_requests( + num_groups=4, + prompts_per_group=5, + system_prompt_len=100, + question_len=50, + output_len=25, + range_ratio=0.5, + seed=42, + ) + for req in requests: + self.assertGreaterEqual(req.prefix_len, 50) + self.assertLessEqual(req.prefix_len, 100) + self.assertGreaterEqual(req.input_len - req.prefix_len, 25) + self.assertLessEqual(req.input_len - req.prefix_len, 50) + + def test_generate_gsp_shuffled(self): + requests = generate_gsp_requests( + num_groups=4, + prompts_per_group=10, + system_prompt_len=100, + question_len=50, + output_len=25, + seed=42, + ) + group_ids = [req.group_id for req in requests] + is_sorted = all( + group_ids[i] <= group_ids[i + 1] for i in range(len(group_ids) - 1) + ) + self.assertFalse(is_sorted) + + +class TestSimulator(CustomTestCase): + def test_basic_run(self): + requests = [ + SimRequest(request_id=f"r{i}", input_len=10, output_len=5) + for i in range(10) + ] + sim = Simulator( + num_gpus_per_engine=2, + router=RoundRobinRouter(num_gpus=2), + scheduler=FIFOScheduler(), + recorders=[ + BatchSizeBalancednessRecorder(), + AttentionComputeBalancednessRecorder(), + ], + max_total_tokens=100, + ) + result = sim.run(requests) + self.assertIsInstance(result, SimulationResult) + self.assertIn("batch_size_balancedness_mean", result.summary) + self.assertGreater(len(result.step_records), 0) + + def test_all_requests_complete(self): + requests = [ + SimRequest(request_id=f"r{i}", input_len=10, output_len=3) for i in range(4) + ] + sim = Simulator( + num_gpus_per_engine=2, + router=RoundRobinRouter(num_gpus=2), + scheduler=FIFOScheduler(), + max_total_tokens=10000, + ) + sim.run(requests) + for gpu in sim.gpu_states: + self.assertEqual(len(gpu.pending_requests), 0) + self.assertEqual(len(gpu.running_requests), 0) + + def test_empty_requests(self): + sim = Simulator( + num_gpus_per_engine=2, + router=RoundRobinRouter(num_gpus=2), + scheduler=FIFOScheduler(), + ) + result = sim.run([]) + self.assertEqual(result.summary, {}) + self.assertEqual(len(result.step_records), 0) + + def test_step_records(self): + requests = [ + SimRequest(request_id=f"r{i}", input_len=10, output_len=3) for i in range(4) + ] + sim = Simulator( + num_gpus_per_engine=2, + router=RoundRobinRouter(num_gpus=2), + scheduler=FIFOScheduler(), + max_total_tokens=10000, + ) + result = sim.run(requests) + self.assertGreater(len(result.step_records), 0) + for record in result.step_records: + self.assertIsInstance(record, StepRecord) + self.assertIn(record.gpu_id, [0, 1]) + self.assertEqual(len([r for r in result.step_records if r.step == 0]), 2) + + def test_preemption_due_to_token_growth(self): + requests = [ + SimRequest(request_id="r0", input_len=50, output_len=10), + SimRequest(request_id="r1", input_len=50, output_len=10), + ] + sim = Simulator( + num_gpus_per_engine=1, + router=RoundRobinRouter(num_gpus=1), + scheduler=FIFOScheduler(), + max_total_tokens=110, + ) + result = sim.run(requests) + + found_preemption = False + for record in result.step_records: + if record.running_count == 1 and record.pending_count == 1: + found_preemption = True + break + self.assertTrue( + found_preemption, "Expected preemption to occur due to token growth" + ) + + +# ==================== E2E Tests ==================== + + +class TestCLI(CustomTestCase): + def _run_cli(self, *args): + return subprocess.run( + [sys.executable, "-m", "sglang.srt.debug_utils.schedule_simulator", *args], + capture_output=True, + text=True, + ) + + def _assert_output_contains(self, output: str, expected_lines: str): + for line in expected_lines.strip().split("\n"): + self.assertIn(line, output) + + def test_cli_basic(self): + log_data = [ + { + "event": "request.finished", + "rid": "r1", + "out": {"meta_info": {"prompt_tokens": 100, "completion_tokens": 50}}, + }, + { + "event": "request.finished", + "rid": "r2", + "out": {"meta_info": {"prompt_tokens": 200, "completion_tokens": 100}}, + }, + ] + with tempfile.NamedTemporaryFile(mode="w", suffix=".log", delete=False) as f: + for item in log_data: + f.write(json.dumps(item) + "\n") + input_file = f.name + with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f: + output_file = f.name + + result = self._run_cli( + "--input", input_file, "--num-gpus-per-engine", "2", "--output", output_file + ) + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + self.assertIn("Loaded 2 requests", result.stdout) + with open(output_file) as f: + self.assertIn("batch_size_balancedness_mean", json.load(f)) + + def test_cli_random_router(self): + log_data = [ + { + "event": "request.finished", + "rid": "r1", + "out": {"meta_info": {"prompt_tokens": 100, "completion_tokens": 50}}, + } + ] + with tempfile.NamedTemporaryFile(mode="w", suffix=".log", delete=False) as f: + for item in log_data: + f.write(json.dumps(item) + "\n") + input_file = f.name + + result = self._run_cli("--input", input_file, "--router", "random") + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + self.assertIn("router=random", result.stdout) + + def test_e2e_sticky_router_group_locality(self): + result = self._run_cli( + "--synth-gsp", + "--synth-gsp-num-groups", + "1", + "--synth-gsp-prompts-per-group", + "4", + "--synth-gsp-system-prompt-len", + "10", + "--synth-gsp-question-len", + "10", + "--synth-gsp-output-len", + "2", + "--synth-seed", + "42", + "--num-gpus-per-engine", + "2", + "--router", + "sticky", + "--max-total-tokens", + "1000", + "--log-level", + "2", + ) + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + self.assertIn("R=4:", result.stdout) + self.assertIn("R=0:-", result.stdout) + + def test_cli_synthetic(self): + result = self._run_cli( + "--synthetic", + "--synth-random-num-requests", + "100", + "--synth-random-input-len", + "512", + "--synth-random-output-len", + "128", + "--synth-random-range-ratio", + "0.5", + "--num-gpus-per-engine", + "4", + ) + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + self.assertIn("Generated 100 random requests", result.stdout) + + def test_cli_log_level(self): + result = self._run_cli( + "--synthetic", + "--synth-random-num-requests", + "10", + "--synth-random-output-len", + "5", + "--num-gpus-per-engine", + "2", + "--log-level", + "1", + ) + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + self.assertIn("step=", result.stdout) + + def test_e2e_simple_no_queuing(self): + result = self._run_cli( + "--synthetic", + "--synth-random-num-requests", + "4", + "--synth-random-input-len", + "10", + "--synth-random-output-len", + "2", + "--synth-random-range-ratio", + "1.0", + "--synth-seed", + "42", + "--num-gpus-per-engine", + "2", + "--max-total-tokens", + "10000", + "--log-level", + "2", + ) + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + self.assertIn( + "step=0 | GPU0[R=2:syn0,syn2 Q=0:-] | GPU1[R=2:syn1,syn3 Q=0:-]", + result.stdout, + ) + self.assertIn( + "step=1 | GPU0[R=0:- Q=0:-] | GPU1[R=0:- Q=0:-]", result.stdout + ) + self.assertIn("batch_size_balancedness_mean: 1.0000", result.stdout) + + def test_e2e_queuing_due_to_token_limit(self): + result = self._run_cli( + "--synthetic", + "--synth-random-num-requests", + "4", + "--synth-random-input-len", + "100", + "--synth-random-output-len", + "3", + "--synth-random-range-ratio", + "1.0", + "--synth-seed", + "42", + "--num-gpus-per-engine", + "1", + "--max-total-tokens", + "210", + "--log-level", + "2", + ) + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + self._assert_output_contains( + result.stdout, + """ +step=0 | GPU0[R=2:syn0,syn1 Q=2:syn2,syn3] +step=1 | GPU0[R=2:syn0,syn1 Q=2:syn2,syn3] +step=2 | GPU0[R=0:- Q=2:syn2,syn3] +step=3 | GPU0[R=2:syn2,syn3 Q=0:-] +step=4 | GPU0[R=2:syn2,syn3 Q=0:-] +step=5 | GPU0[R=0:- Q=0:-]""", + ) + + def test_e2e_retraction_due_to_token_growth(self): + result = self._run_cli( + "--synthetic", + "--synth-random-num-requests", + "2", + "--synth-random-input-len", + "50", + "--synth-random-output-len", + "10", + "--synth-random-range-ratio", + "1.0", + "--synth-seed", + "42", + "--num-gpus-per-engine", + "1", + "--max-total-tokens", + "110", + "--log-level", + "2", + ) + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + self._assert_output_contains( + result.stdout, + """ +step=0 | GPU0[R=2:syn0,syn1 Q=0:-] +step=5 | GPU0[R=2:syn0,syn1 Q=0:-] +step=6 | GPU0[R=1:syn0 Q=1:syn1] +step=9 | GPU0[R=0:- Q=1:syn1] +step=10 | GPU0[R=1:syn1 Q=0:-] +step=13 | GPU0[R=0:- Q=0:-]""", + ) + + def test_cli_gsp_basic(self): + result = self._run_cli( + "--synth-gsp", + "--synth-gsp-num-groups", + "4", + "--synth-gsp-prompts-per-group", + "8", + "--synth-gsp-system-prompt-len", + "100", + "--synth-gsp-question-len", + "50", + "--synth-gsp-output-len", + "10", + "--synth-seed", + "42", + "--num-gpus-per-engine", + "2", + ) + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + self.assertIn("Generated 32 GSP requests", result.stdout) + self.assertIn("4 groups x 8 prompts", result.stdout) + + def test_e2e_gsp_shared_prefix_enables_batching(self): + for has_long_prefix in [True, False]: + prefix_len, question_len = (50, 10) if has_long_prefix else (10, 50) + result = self._run_cli( + "--synth-gsp", + "--synth-gsp-num-groups", + "1", + "--synth-gsp-prompts-per-group", + "2", + "--synth-gsp-system-prompt-len", + str(prefix_len), + "--synth-gsp-question-len", + str(question_len), + "--synth-gsp-output-len", + "2", + "--synth-seed", + "42", + "--num-gpus-per-engine", + "1", + "--max-total-tokens", + "80", + "--log-level", + "2", + ) + self.assertEqual(result.returncode, 0, f"CLI failed: {result.stderr}") + if has_long_prefix: + self.assertIn("R=2:", result.stdout) + else: + self.assertNotIn("R=2:", result.stdout) + + +class TestLargerScale(CustomTestCase): + def _run_main(self, *cli_args) -> SimulationResult: + parser = create_arg_parser() + args = parser.parse_args(cli_args) + return main(args) + + def _assert_in_range(self, value, lo, hi, name): + self.assertGreaterEqual(value, lo, f"{name}={value} < {lo}") + self.assertLessEqual(value, hi, f"{name}={value} > {hi}") + + def test_vanilla_workload_random_policy(self): + result = self._run_main( + "--synthetic", + "--synth-random-num-requests", + "500000", + "--synth-random-input-len", + "32000", + "--synth-random-output-len", + "2000", + "--synth-seed", + "42", + "--num-gpus-per-engine", + "8", + "--num-engines", + "250", + "--router", + "random", + "--max-total-tokens", + "2000000", + "--stop-criteria", + "exist_no_pending", + "--max-steps", + "1500", + ) + self._assert_in_range( + result.summary["attention_compute_balancedness_mean"], 0.95, 1.0, "attn" + ) + self._assert_in_range( + result.summary["batch_size_balancedness_mean"], 0.90, 0.98, "bs" + ) + self._assert_in_range(result.summary["avg_batch_size"], 127, 141, "avg_bs") + + def _run_gsp_workload(self, router: str) -> SimulationResult: + return self._run_main( + "--synth-gsp", + "--synth-gsp-num-groups", + "50000", + "--synth-gsp-prompts-per-group", + "100", + "--synth-gsp-system-prompt-len", + "31000", + "--synth-gsp-question-len", + "1000", + "--synth-gsp-output-len", + "8000", + "--synth-seed", + "42", + "--num-gpus-per-engine", + "8", + "--num-engines", + "250", + "--router", + router, + "--max-total-tokens", + "500000", + "--stop-criteria", + "exist_no_pending", + "--max-steps", + "1500", + ) + + def test_gsp_workload_random_policy(self): + result = self._run_gsp_workload("random") + self._assert_in_range( + result.summary["attention_compute_balancedness_mean"], 0.90, 0.97, "attn" + ) + self._assert_in_range( + result.summary["batch_size_balancedness_mean"], 0.90, 0.97, "bs" + ) + self._assert_in_range(result.summary["avg_batch_size"], 14, 17, "avg_bs") + + def test_gsp_workload_sticky_policy(self): + result = self._run_gsp_workload("sticky") + self._assert_in_range( + result.summary["attention_compute_balancedness_mean"], 0.64, 0.71, "attn" + ) + self._assert_in_range( + result.summary["batch_size_balancedness_mean"], 0.64, 0.71, "bs" + ) + self._assert_in_range(result.summary["avg_batch_size"], 31, 36, "avg_bs") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/test_soft_watchdog.py b/asian_ai/performance/SGLang/test/registered/debug_utils/test_soft_watchdog.py new file mode 100644 index 0000000000000000000000000000000000000000..a0e81965fc8789367cc12c1443f42e47ee90fa97 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/test_soft_watchdog.py @@ -0,0 +1,88 @@ +import io +import unittest + +import requests + +from sglang.srt.environ import envs +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import ( + register_amd_ci, + register_cpu_ci, + register_cuda_ci, +) +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=120, suite="nightly-1-gpu", nightly=True) +register_amd_ci(est_time=120, suite="nightly-amd-1-gpu", nightly=True) +register_cpu_ci(est_time=622, suite="base-c-test-cpu") + + +class BaseTestSoftWatchdog: + env_override = None + expected_message = None + + @classmethod + def setUpClass(cls): + cls.stdout = io.StringIO() + cls.stderr = io.StringIO() + + with cls.env_override(): + cls.process = popen_launch_server( + "Qwen/Qwen3-0.6B", + DEFAULT_URL_FOR_TEST, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--soft-watchdog-timeout", + "20", + "--skip-server-warmup", + ], + return_stdout_stderr=(cls.stdout, cls.stderr), + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + cls.stdout.close() + cls.stderr.close() + + def test_watchdog_triggers(self): + print("Start call /generate API", flush=True) + try: + requests.post( + DEFAULT_URL_FOR_TEST + "/generate", + json={ + "text": "Hello, please repeat this sentence for 1000 times.", + "sampling_params": {"max_new_tokens": 100, "temperature": 0}, + }, + timeout=30, + ) + except requests.exceptions.ReadTimeout as e: + print(f"requests.post timeout (but expected): {e}") + print("End call /generate API", flush=True) + + combined_output = self.stdout.getvalue() + self.stderr.getvalue() + self.assertIn(self.expected_message, combined_output) + + +class TestSoftWatchdogDetokenizer(BaseTestSoftWatchdog, CustomTestCase): + env_override = lambda: envs.SGLANG_TEST_STUCK_DETOKENIZER.override(30) + expected_message = "DetokenizerManager watchdog timeout" + + +class TestSoftWatchdogTokenizer(BaseTestSoftWatchdog, CustomTestCase): + env_override = lambda: envs.SGLANG_TEST_STUCK_TOKENIZER.override(30) + expected_message = "TokenizerManager watchdog timeout" + + +class TestSoftWatchdogSchedulerInit(BaseTestSoftWatchdog, CustomTestCase): + env_override = lambda: envs.SGLANG_TEST_STUCK_SCHEDULER_INIT.override(30) + expected_message = "Scheduler watchdog timeout" + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/debug_utils/test_tensor_dump_forward_hook.py b/asian_ai/performance/SGLang/test/registered/debug_utils/test_tensor_dump_forward_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..9d88eadf2d17e56d147f68914c98ecc4f14b9327 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/debug_utils/test_tensor_dump_forward_hook.py @@ -0,0 +1,108 @@ +import unittest + +import torch +from torch import nn + +from sglang.srt.debug_utils.tensor_dump_forward_hook import ( + register_forward_hook_for_model, +) +from sglang.srt.distributed.parallel_state import ( + init_distributed_environment, + initialize_model_parallel, +) +from sglang.srt.layers.layernorm import RMSNorm +from sglang.srt.layers.linear import LinearBase +from sglang.srt.models.qwen2 import Qwen2MLP +from sglang.srt.server_args import ServerArgs, set_global_server_args_for_scheduler +from sglang.srt.utils import add_prefix +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci( + est_time=9, + stage="base-b", + runner_config="1-gpu-small", + disabled="Test uses pytest-style function without TestCase class - see #17145", +) +register_amd_ci( + est_time=15, + suite="stage-b-test-1-gpu-small-amd", + disabled="Test uses pytest-style function without TestCase class - see #17145", +) + +TEST_HIDDEN_SIZE = 32 + + +class SimpleModel(nn.Module): + + def __init__(self) -> None: + super().__init__() + self.hidden_size = TEST_HIDDEN_SIZE + self.rms_norm_eps = 1e-5 + self.mlp = Qwen2MLP( + hidden_size=self.hidden_size, + intermediate_size=self.hidden_size, + hidden_act="silu", + quant_config=None, + prefix=add_prefix("mlp", ""), + ) + self.layernorm = RMSNorm(self.hidden_size, eps=self.rms_norm_eps) + + @torch.no_grad() + def forward( + self, + hidden_states: torch.Tensor, + ) -> torch.Tensor: + hidden_states = self.layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + return hidden_states + + +class MockCausalLM(nn.Module): + def __init__(self) -> None: + super().__init__() + self.model = SimpleModel() + + @torch.no_grad() + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + return self.model(hidden_states) + + +def init_weights(module): + if isinstance(module, LinearBase): + torch.nn.init.uniform_(module.weight) + if module.bias is not None: + torch.nn.init.zeros_(module.bias) + elif isinstance(module, RMSNorm): + torch.nn.init.ones_(module.weight) + + +def test_model_forward_dump(tmp_path): + set_global_server_args_for_scheduler(ServerArgs(model_path="dummy")) + init_distributed_environment( + backend="nccl", + world_size=1, + rank=0, + local_rank=0, + distributed_init_method="tcp://127.0.0.1:2646", + ) + initialize_model_parallel() + model = MockCausalLM() + model.apply(init_weights) + model = model.cuda().bfloat16() + dumper = register_forward_hook_for_model( + model, tmp_path / "sglang_dump", [0], 0, 0, 0 + ) + + dir_path = dumper.get_dump_dir() + inp = torch.randn(4, TEST_HIDDEN_SIZE, dtype=torch.bfloat16) * 0.01 + result = model(inp.cuda()) + data = torch.load(f"{dir_path}/Pass00000.pt") + assert "model.layernorm" in data + assert "model.mlp.down_proj" in data + assert torch.allclose( + data["model.mlp.down_proj"], result.cpu(), rtol=1e-5, atol=1e-5 + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_aarch64.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_aarch64.py new file mode 100644 index 0000000000000000000000000000000000000000..9898ebb76c0c372a74f58e92532f08aae7d95bd2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_aarch64.py @@ -0,0 +1,101 @@ +import os +import unittest +from types import SimpleNamespace + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + popen_launch_pd_server, +) + +QWEN3_8B_MODEL_PATH = "Qwen/Qwen3-8B" + +register_cuda_ci(est_time=300, stage="base-c", runner_config="4-gpu-gb300") + + +class TestDisaggregationMooncakeAARCH64Accuracy(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + os.environ["SGLANG_MOONCAKE_CUSTOM_MEM_POOL"] = "true" + os.environ["MC_FORCE_MNNVL"] = "true" + cls.model = QWEN3_8B_MODEL_PATH + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def tearDownClass(cls): + os.environ.pop("SGLANG_MOONCAKE_CUSTOM_MEM_POOL") + os.environ.pop("MC_FORCE_MNNVL") + super().tearDownClass() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + "--base-gpu-id", + "2", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.62) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_basic.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..ef7fa96b8b5fa507cbd5deb8cf573b58721c531c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_basic.py @@ -0,0 +1,552 @@ +import asyncio +import json +import os +import threading +import time +import unittest +import uuid +from types import SimpleNamespace +from typing import Any + +import aiohttp +import openai +import requests +from transformers import AutoTokenizer + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.json_constrained_kit import JSONConstrainedMixin +from sglang.test.kits.pause_generation_kit import PauseResumeInPlaceMixin +from sglang.test.kits.spec_server_kits import SpecGrammarKit +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_DRAFT_MODEL_EAGLE3, + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TARGET_MODEL_EAGLE3, +) + +register_cuda_ci(est_time=730, stage="base-b", runner_config="2-gpu-large") + + +class TestDisaggregationAccuracy(PauseResumeInPlaceMixin, PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.pause_generate_url = cls.lb_url + cls.pause_target_urls = [cls.prefill_url, cls.decode_url] + cls.launch_all() + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=f"http://{self.base_host}:{self.lb_port}", + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.62) + + def test_logprob(self): + prompt = "The capital of france is " + response = requests.post( + self.lb_url + "/generate", + json={ + "text": prompt, + "sampling_params": {"temperature": 0}, + "return_logprob": True, + "return_input_logprob": True, + "logprob_start_len": 0, + }, + ) + + j = response.json() + completion_tokens = j["meta_info"]["completion_tokens"] + input_logprobs = j["meta_info"]["input_token_logprobs"] + output_logprobs = j["meta_info"]["output_token_logprobs"] + + assert ( + len(output_logprobs) == completion_tokens + ), f"output_logprobs and completion_tokens should have the same length, but got {len(output_logprobs)} and {completion_tokens}" + assert ( + len(input_logprobs) > 0 + ), f"input_logprobs should have at least one token, but got {len(input_logprobs)}" + + def test_chat_completion_top_logprobs(self): + client = openai.Client(api_key="empty", base_url=f"{self.lb_url}/v1") + response = client.chat.completions.create( + model="dummy", + messages=[ + {"role": "system", "content": "You are a helpful AI assistant."}, + {"role": "user", "content": "What is the capital of France?"}, + ], + temperature=0, + max_tokens=8, + logprobs=True, + top_logprobs=5, + ) + + self.assertIsNotNone(response.choices[0].logprobs) + content_logprobs = response.choices[0].logprobs.content + self.assertGreater(len(content_logprobs), 0) + + first_top_logprobs = next( + (item.top_logprobs for item in content_logprobs if item.top_logprobs), + None, + ) + self.assertIsNotNone(first_top_logprobs) + self.assertEqual(len(first_top_logprobs), 5) + self.assertIsInstance(first_top_logprobs[0].token, str) + self.assertIsInstance(first_top_logprobs[0].logprob, float) + + def test_structured_output(self): + json_schema = json.dumps( + { + "type": "object", + "properties": { + "name": {"type": "string", "pattern": "^[\\w]+$"}, + "population": {"type": "integer"}, + }, + "required": ["name", "population"], + } + ) + + # JSON + response = requests.post( + f"{self.lb_url}/generate", + json={ + "text": "Here is the information of the capital of France in the JSON format.\n", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 64, + "json_schema": json_schema, + }, + }, + ) + output = response.json()["text"] + # ensure the output is a valid JSON + json.loads(output) + + def test_first_token_finish(self): + client = openai.Client(api_key="empty", base_url=f"{self.lb_url}/v1") + tokenizer = AutoTokenizer.from_pretrained(self.model) + eos_token = tokenizer.eos_token_id + prompt = "The best programming language for AI is" + + # First token EOS + res = client.completions.create( + model="dummy", prompt=prompt, logit_bias={eos_token: 42} + ).model_dump() + print(f"{res=}") + + assert res["usage"]["completion_tokens"] == 1, ( + "Expected completion_tokens to be 1 when first token is EOS, " + f"but got {res['usage']['completion_tokens']}" + ) + + # First token EOS with ignore_eos + res = client.completions.create( + model="dummy", + prompt=prompt, + logit_bias={eos_token: 42}, + extra_body={"ignore_eos": True}, + ).model_dump() + print(f"{res=}") + + assert res["usage"]["completion_tokens"] > 1, ( + "Expected completion_tokens to be greater than 1 when ignore_eos is True, " + f"but got {res['usage']['completion_tokens']}" + ) + + # First token with specified stop token + stop_token_id = tokenizer.encode(" hello", add_special_tokens=False)[0] + res = client.completions.create( + model="dummy", + prompt=prompt, + logit_bias={stop_token_id: 42}, + stop=[" hello"], + ).model_dump() + print(f"{res=}") + + assert res["usage"]["completion_tokens"] == 1, ( + "Expected completion_tokens to be 1 when first token is stop token, " + f"but got {res['usage']['completion_tokens']}" + ) + + +class TestDisaggregationMooncakeFailure(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + # set DISAGGREGATION_TEST_FAILURE_PROB to simulate failure + os.environ["DISAGGREGATION_TEST_FAILURE_PROB"] = "0.05" + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.launch_all() + + @classmethod + def tearDownClass(cls): + os.environ.pop("DISAGGREGATION_TEST_FAILURE_PROB") + super().tearDownClass() + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=f"http://{self.base_host}:{self.lb_port}", + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + + # Expect lots of failure but the server cannot crash + try: + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + except Exception as e: + print(f"Test encountered expected errors: {e}") + # Check if servers are still healthy + try: + response = requests.get(self.prefill_url + "/health_generate") + assert response.status_code == 200 + response = requests.get(self.decode_url + "/health_generate") + assert response.status_code == 200 + except Exception as health_check_error: + # If health check fails, re-raise the original exception + raise e from health_check_error + + +class TestDisaggregationMooncakeSpec( + JSONConstrainedMixin, SpecGrammarKit, PDDisaggregationServerBase +): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = DEFAULT_TARGET_MODEL_EAGLE3 + spec_args = [ + "--speculative-algorithm", + "EAGLE", + "--speculative-draft-model-path", + DEFAULT_DRAFT_MODEL_EAGLE3, + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "16", + "--cuda-graph-max-bs-decode", + "8", + "--dtype=float16", + ] + cls.extra_prefill_args = spec_args + cls.extra_decode_args = spec_args + cls.launch_all() + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=f"http://{self.base_host}:{self.lb_port}", + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.74) + + +class TestDisaggregationSimulatedRetract(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + os.environ["SGLANG_TEST_RETRACT"] = "true" + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.launch_all() + + @classmethod + def tearDownClass(cls): + os.environ.pop("SGLANG_TEST_RETRACT") + super().tearDownClass() + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=f"http://{self.base_host}:{self.lb_port}", + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.62) + + +class TestDisaggregationPauseResumePrefillLeak(PDDisaggregationServerBase): + """Regression test: pause_generation must not leak prefill requests into + running_batch. With a small --max-running-requests the leak fills the + scheduling budget and blocks all subsequent prefills.""" + + MAX_RUNNING = 4 + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.extra_prefill_args = [ + "--max-running-requests", + str(cls.MAX_RUNNING), + "--enable-metrics", + ] + cls.launch_all() + + def test_retract_pause_no_leak_on_prefill(self): + """Retract-mode pause on a disagg prefill node must not leak prefill + requests into running_batch. Without the fix, each retract pause merges + last_batch into running_batch, but the prefill event loop never cleans + them up via update_running_batch. After enough cycles the + max-running-requests budget is exhausted and all new prefills hang.""" + asyncio.run(self._run_pause_resume_leak_test("retract")) + + def test_retract_pause_empty_running_batch(self): + """Retract-mode pause must not crash when running_batch is empty. + Regression test for issue #20272.""" + asyncio.run(self._run_pause_on_idle("retract")) + + async def _run_pause_on_idle(self, mode): + """Pause/resume on an idle prefill node (no in-flight requests).""" + async with aiohttp.ClientSession() as session: + async with session.post( + self.prefill_url + "/pause_generation", + json={"mode": mode}, + timeout=aiohttp.ClientTimeout(total=10), + ) as resp: + resp.raise_for_status() + async with session.post( + self.prefill_url + "/continue_generation", + json={}, + timeout=aiohttp.ClientTimeout(total=10), + ) as resp: + resp.raise_for_status() + + # Verify the engine still works after pause/resume + async with session.post( + self.lb_url + "/generate", + json={ + "text": "What is 1+1?", + "sampling_params": {"temperature": 0, "max_new_tokens": 1}, + }, + timeout=aiohttp.ClientTimeout(total=10), + ) as resp: + resp.raise_for_status() + body = await resp.json() + self.assertIn("text", body) + self.assertGreater(len(body["text"]), 0) + + async def _get_num_running_reqs(self, session): + """Query sglang:num_running_reqs from prefill node's /metrics.""" + async with session.get( + self.prefill_url + "/metrics", + timeout=aiohttp.ClientTimeout(total=5), + ) as resp: + resp.raise_for_status() + text = await resp.text() + for line in text.splitlines(): + # Match the gauge line, skip HELP/TYPE comments and + # per-priority breakdowns (which have priority="") + if ( + line.startswith("sglang:num_running_reqs{") + and "priority=" not in line + ): + return int(float(line.split()[-1])) + return 0 + + async def _run_pause_resume_leak_test(self, mode): + NUM_WORKERS = 64 + NUM_PAUSE_RESUME_CYCLES = self.MAX_RUNNING * 4 + MAX_NEW_TOKENS = 1 + LONG_PROMPT = "Tell me a story. " * 200 + + async def _background_worker(session, worker_id, cancel_event): + """Send requests sequentially until cancelled.""" + seq = 0 + while not cancel_event.is_set(): + try: + async with session.post( + self.lb_url + "/generate", + json={ + "text": f"[w{worker_id}-{seq}] {LONG_PROMPT}", + "sampling_params": { + "temperature": 0, + "max_new_tokens": MAX_NEW_TOKENS, + }, + }, + timeout=aiohttp.ClientTimeout(total=30), + ) as resp: + await resp.read() + except Exception: + pass + seq += 1 + + async def _post(session, url, json_data): + async with session.post( + url, + json=json_data, + timeout=aiohttp.ClientTimeout(total=30), + ) as resp: + resp.raise_for_status() + + cancel_event = asyncio.Event() + + async with aiohttp.ClientSession() as session: + workers = [ + asyncio.create_task(_background_worker(session, i, cancel_event)) + for i in range(NUM_WORKERS) + ] + + for _ in range(NUM_PAUSE_RESUME_CYCLES): + await _post( + session, + self.prefill_url + "/pause_generation", + {"mode": mode}, + ) + await _post( + session, + self.prefill_url + "/continue_generation", + {}, + ) + await asyncio.sleep(0.1) + + # Stop workers and abort all in-flight requests + cancel_event.set() + await _post( + session, self.prefill_url + "/abort_request", {"abort_all": True} + ) + await _post( + session, self.decode_url + "/abort_request", {"abort_all": True} + ) + await asyncio.gather(*workers, return_exceptions=True) + + # Wait for abort cleanup, then check for leaked phantom requests. + # With the bug, running_batch accumulates phantom prefill requests + # that are never cleaned up. + await asyncio.sleep(2) + num_running = await self._get_num_running_reqs(session) + self.assertEqual( + num_running, + 0, + f"Prefill node has {num_running} phantom running requests " + f"after abort — pause_generation is leaking into running_batch", + ) + + +PD_CHUNKED_ABORT_EXTRA_ARGS = [ + "--max-running-requests", + "4", + "--chunked-prefill-size", + "64", +] +_CHUNKED_ABORT_LONG_PROMPT = ( + "The quick brown fox jumps over the lazy dog. " + "Pack my box with five dozen liquor jugs. " + "Sphinx of black quartz, judge my vow. " +) * 900 + + +def _decode_response(response: requests.Response) -> Any: + try: + return response.json() + except ValueError: + return response.text + + +def _is_abort_result(status_code: int, body: Any) -> bool: + if status_code == 200: + reason = ( + body.get("meta_info", {}).get("finish_reason", {}) + if isinstance(body, dict) + else {} + ) + return isinstance(reason, dict) and reason.get("type") == "abort" + + if status_code not in (500, 503): + return False + + text = body if isinstance(body, str) else str(body) + return "abort" in text.lower() + + +class TestDisaggChunkedPrefillAbort(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + cls.extra_prefill_args = PD_CHUNKED_ABORT_EXTRA_ARGS + cls.extra_decode_args = PD_CHUNKED_ABORT_EXTRA_ARGS + cls.launch_all() + + def _post_abort(self, rid: str): + for url in (self.prefill_url, self.decode_url): + requests.post( + url + "/abort_request", + json={"rid": rid, "abort_all": False}, + timeout=10, + ) + + def test_abort_mid_chunked_prefill_by_rid(self): + rid = f"pd-chunked-prefill-abort-{uuid.uuid4().hex}" + result: dict[str, Any] = {} + + def run_generate(): + try: + response = requests.post( + self.lb_url + "/generate", + json={ + "rid": rid, + "text": f"{rid}\n{_CHUNKED_ABORT_LONG_PROMPT}", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 4096, + "ignore_eos": True, + }, + }, + timeout=180, + ) + result["status_code"] = response.status_code + result["body"] = _decode_response(response) + except requests.RequestException as exc: + result["exception"] = repr(exc) + + thread = threading.Thread(target=run_generate) + thread.start() + + time.sleep(1.0) + abort_deadline = time.monotonic() + 8 + while thread.is_alive() and time.monotonic() < abort_deadline: + self._post_abort(rid) + time.sleep(0.2) + + thread.join(timeout=60) + self.assertFalse(thread.is_alive(), "Chunked-prefill abort request hung") + self.assertNotIn("exception", result, result.get("exception")) + self.assertTrue( + _is_abort_result(result["status_code"], result["body"]), + f"Expected chunked-prefill request to abort, got {result}", + ) + + for url in (self.lb_url, self.prefill_url, self.decode_url): + health = requests.get(url + "/health", timeout=10) + self.assertEqual(health.status_code, 200, health.text) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_decode_offload.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_decode_offload.py new file mode 100644 index 0000000000000000000000000000000000000000..b683071894570c8b31cfae3c1e715ce2c31dbdda --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_decode_offload.py @@ -0,0 +1,177 @@ +import os +import shutil +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + popen_launch_pd_server, +) + +# Registering the test for CUDA CI with appropriate parameters +# Increasing estimated time since we run evaluation twice +register_cuda_ci( + est_time=600, + stage="base-b", + runner_config="2-gpu-large", +) + + +class TestDisaggregationDecodeOffload(PDDisaggregationServerBase): + """ + Test class for verifying KV cache offloading on the decode side in a + prefill-decode disaggregation setup. + """ + + @classmethod + def setUpClass(cls): + # Set environment variable to make offloading more frequent for testing purposes + cls.old_stride = os.environ.get("SGLANG_HICACHE_DECODE_OFFLOAD_STRIDE") + cls.hicache_dir = "/tmp/hicache_test" + os.environ["SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIR"] = cls.hicache_dir + os.environ["SGLANG_HICACHE_DECODE_OFFLOAD_STRIDE"] = "16" + + # Ensure a clean cache directory + if os.path.exists(cls.hicache_dir): + shutil.rmtree(cls.hicache_dir) + os.makedirs(cls.hicache_dir, exist_ok=True) + + super().setUpClass() + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + + # Non-blocking start of prefill and decode servers + cls.start_prefill() + cls.start_decode() + + # Wait for both servers to be ready before proceeding + cls.wait_server_ready(cls.prefill_url + "/health") + cls.wait_server_ready(cls.decode_url + "/health") + + cls.launch_lb() + + @classmethod + def tearDownClass(cls): + # Restore the original environment variable state + super().tearDownClass() + if cls.old_stride is not None: + os.environ["SGLANG_HICACHE_DECODE_OFFLOAD_STRIDE"] = cls.old_stride + else: + os.environ.pop("SGLANG_HICACHE_DECODE_OFFLOAD_STRIDE", None) + + os.environ.pop("SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIR", None) + + # Clean up the cache directory + if os.path.exists(cls.hicache_dir): + shutil.rmtree(cls.hicache_dir) + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--page-size", + "16", + "--enable-hierarchical-cache", + "--hicache-storage-backend", + "file", + "--hicache-ratio", + "2", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "1", + "--disaggregation-decode-enable-offload-kvcache", + "--num-reserved-decode-tokens", + "128", + "--hicache-ratio", + "2", + "--page-size", + "16", + "--hicache-storage-backend", + "file", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_mmlu_double_eval(self): + """ + Run two rounds of MMLU evaluation: + 1. First round: Decode node offloads KV cache back to disk (HiCache). + 2. Restart All Nodes to clear memory cache. + 3. Second round: Prefill node loads KV cache from disk (HiCache). + Verify that both rounds produce consistent scores. + """ + args = SimpleNamespace( + base_url=f"http://{self.base_host}:{self.lb_port}", + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics1 = run_eval(args) + + # Ensure all offloads are committed to disk + import time + + time.sleep(10) + + kill_process_tree(self.process_prefill.pid) + kill_process_tree(self.process_decode.pid) + kill_process_tree(self.process_lb.pid) + self.process_prefill.wait() + self.process_decode.wait() + self.process_lb.wait() + + self.start_prefill() + self.start_decode() + self.launch_lb() + self.wait_server_ready(self.prefill_url + "/health") + self.wait_server_ready(self.decode_url + "/health") + + metrics2 = run_eval(args) + + # Assert score is above a minimum threshold for both rounds + self.assertGreater(metrics1["score"], 0.65) + self.assertGreater(metrics2["score"], 0.65) + + # Score should be consistent: round 2 should be >= round 1, or at least within a 0.05 margin if slightly lower + self.assertGreaterEqual(metrics2["score"], metrics1["score"] - 0.05) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_decode_radix_cache.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_decode_radix_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..11ff4fbf1bf18c5f9a4efa9b7b558d0187bd799a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_decode_radix_cache.py @@ -0,0 +1,269 @@ +import asyncio +import os +import shutil +import tempfile +import time +import unittest +from types import SimpleNamespace + +import requests + +from sglang.benchmark.datasets.random import sample_random_requests +from sglang.benchmark.utils import get_tokenizer +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.cache_hit_kit import ( + async_request_sglang_generate, + gen_payload, + run_multiturn_cache_hit_test, +) +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + is_in_ci, + try_cached_model, +) + +register_cuda_ci(est_time=300, stage="base-c", runner_config="8-gpu-h20") + + +def _has_nixl(): + try: + import nixl._api # noqa: F401 + except ImportError: + return False + return True + + +def _has_mooncake(): + try: + import mooncake.engine # noqa: F401 + except ImportError: + return False + return True + + +class DisaggregationDecodeRadixCacheTestMixin: + extra_decode_args = ["--disaggregation-decode-enable-radix-cache"] + transfer_backend_name = None + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST) + cls.transfer_backend = [ + "--disaggregation-transfer-backend", + cls.transfer_backend_name, + ] + cls.launch_all() + + def _assert_process_healthy(self, name, process, url): + self.assertIsNotNone(process, f"{name} process was not started") + self.assertIsNone( + process.poll(), + f"{name} exited unexpectedly with code {process.returncode}", + ) + response = requests.get(f"{url}/health", timeout=10) + response.raise_for_status() + + def test_decode_radix_cache_hits_and_workers_stay_alive(self): + decode_info = requests.get(f"{self.decode_url}/server_info", timeout=10).json() + self.assertFalse( + decode_info.get("disable_radix_cache", True), + "decode server did not enable radix cache", + ) + + result = run_multiturn_cache_hit_test( + base_url=self.base_url, + model_path=self.model, + num_clients=4, + num_rounds=3, + request_length=384, + output_length=64, + max_parallel=4, + ) + self.assertGreater( + result["overall"]["total_cached_tokens"], + 0, + "expected decode radix cache to reuse at least some tokens", + ) + + # Give the schedulers a short idle window so any post-request leak/crash + # paths have a chance to surface before the liveness checks below. + time.sleep(5) + + self._assert_process_healthy("load balancer", self.process_lb, self.lb_url) + self._assert_process_healthy("prefill", self.process_prefill, self.prefill_url) + self._assert_process_healthy("decode", self.process_decode, self.decode_url) + + def test_gsm8k_accuracy_two_passes(self): + """Run GSM8K twice to verify decode radix cache does not degrade accuracy.""" + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=500, + num_threads=100, + num_shots=6, + ) + + metrics_first = run_eval(args) + print(f"First run metrics: {metrics_first}") + + metrics_second = run_eval(args) + print(f"Second run metrics: {metrics_second}") + + self.assertGreater(metrics_first["score"], 0.80) + self.assertGreater(metrics_second["score"], 0.80) + + accuracy_drop = metrics_first["score"] - metrics_second["score"] + self.assertLessEqual( + accuracy_drop, + 0.03, + f"Second run accuracy dropped by {accuracy_drop:.4f} " + f"(first={metrics_first['score']:.4f}, second={metrics_second['score']:.4f}), " + f"exceeds 3% threshold", + ) + + +@unittest.skipUnless( + is_in_ci() or _has_nixl(), + "NIXL is required for decode radix cache disaggregation coverage.", +) +class TestDisaggregationDecodeRadixCacheNixl( + DisaggregationDecodeRadixCacheTestMixin, PDDisaggregationServerBase +): + transfer_backend_name = "nixl" + + +@unittest.skipUnless( + is_in_ci() or _has_mooncake(), + "Mooncake is required for decode radix cache disaggregation coverage.", +) +class TestDisaggregationDecodeRadixCacheMooncake( + DisaggregationDecodeRadixCacheTestMixin, PDDisaggregationServerBase +): + transfer_backend_name = "mooncake" + + +@unittest.skipUnless( + is_in_ci() or _has_mooncake(), + "Mooncake is required for decode radix cache disaggregation coverage.", +) +class TestDisaggregationDecodeRadixHiCacheFileBackend(PDDisaggregationServerBase): + extra_prefill_args = [ + "--enable-hierarchical-cache", + "--hicache-ratio", + "1.2", + "--hicache-write-policy", + "write_through", + "--hicache-storage-backend", + "file", + "--hicache-storage-prefetch-policy", + "wait_complete", + "--hicache-io-backend", + "kernel", + "--hicache-mem-layout", + "page_first", + "--page-size", + "64", + ] + extra_decode_args = [ + "--disaggregation-decode-enable-radix-cache", + *extra_prefill_args, + ] + transfer_backend_name = "mooncake" + + @classmethod + def setUpClass(cls): + cls.hicache_dir = tempfile.mkdtemp(prefix="sglang-hicache-") + os.environ["SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIR"] = cls.hicache_dir + + super().setUpClass() + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST) + cls.transfer_backend = [ + "--disaggregation-transfer-backend", + cls.transfer_backend_name, + ] + cls.launch_all() + + @classmethod + def tearDownClass(cls): + super().tearDownClass() + os.environ.pop("SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIR", None) + shutil.rmtree(cls.hicache_dir, ignore_errors=True) + + def _post_ok(self, url): + response = requests.post(url, timeout=60) + response.raise_for_status() + + def _flush_memory_cache(self): + self._post_ok(f"{self.prefill_url}/flush_cache?timeout=30") + self._post_ok(f"{self.decode_url}/flush_cache?timeout=30") + + def _generate(self, input_ids, output_len): + output = asyncio.run( + async_request_sglang_generate( + gen_payload(input_ids, output_len), + f"{self.base_url}/generate", + ) + ) + self.assertTrue(output.success, output.error) + return output + + def _sample_token_ids(self, input_len, output_len, num_prompts=1): + tokenizer = get_tokenizer(self.model) + return [ + list(request.prompt) + for request in sample_random_requests( + input_len=input_len, + output_len=output_len, + num_prompts=num_prompts, + range_ratio=1.0, + tokenizer=tokenizer, + dataset_path="", + return_text=False, + ) + ] + + def test_decode_hicache_file_backend_l3_reuses_decode_output_after_flush(self): + self._post_ok(f"{self.decode_url}/hicache/storage-backend/clear") + self._flush_memory_cache() + + num_rounds = 5 + output_len = 64 + history = self._sample_token_ids( + input_len=256, output_len=output_len, num_prompts=1 + )[0] + suffixes = self._sample_token_ids( + input_len=64, output_len=output_len, num_prompts=num_rounds - 1 + ) + + prev_prompt_len = 0 + prev_output_len = 0 + for round_idx in range(num_rounds): + output = self._generate(history, output_len) + if round_idx == 0: + self.assertEqual(output.cached_tokens, 0) + else: + self.assertGreaterEqual( + output.cached_tokens, + prev_prompt_len + prev_output_len, + ) + + history.extend(output.output_ids) + prev_prompt_len = output.prompt_len + prev_output_len = len(output.output_ids) + + if round_idx < num_rounds - 1: + history.extend(suffixes[round_idx]) + time.sleep(1) + self._flush_memory_cache() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_different_tp.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_different_tp.py new file mode 100644 index 0000000000000000000000000000000000000000..ed670e2c98035a576e591e2bfcb42b210fec2681 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_different_tp.py @@ -0,0 +1,508 @@ +import os +import unittest +from types import SimpleNamespace + +from sglang.srt.environ import envs +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_MODEL_NAME_FOR_TEST_MLA, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + popen_launch_pd_server, + try_cached_model, +) + +register_cuda_ci(est_time=375, stage="base-c", runner_config="8-gpu-h20") + + +class TestDisaggregationMooncakePrefillLargerTP(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + # Temporarily disable JIT DeepGEMM + envs.SGLANG_ENABLE_JIT_DEEPGEMM.set(False) + + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST_MLA) + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + "--base-gpu-id", + "4", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.60) + + +class TestDisaggregationMooncakeDecodeLargerTP(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + # Temporarily disable JIT DeepGEMM + envs.SGLANG_ENABLE_JIT_DEEPGEMM.set(False) + + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST_MLA) + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--base-gpu-id", + "4", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.60) + + +class TestDisaggregationMooncakeMHAPrefillLargerTP(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + # Temporarily disable JIT DeepGEMM + envs.SGLANG_ENABLE_JIT_DEEPGEMM.set(False) + + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST) + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + "--base-gpu-id", + "4", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.60) + + +class TestDisaggregationMooncakeMHADecodeLargerTP(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + # Temporarily disable JIT DeepGEMM + envs.SGLANG_ENABLE_JIT_DEEPGEMM.set(False) + + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST) + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--base-gpu-id", + "4", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.60) + + +STAGING_ENV = { + "SGLANG_DISAGG_STAGING_BUFFER": "1", + "SGLANG_DISAGG_STAGING_BUFFER_SIZE_MB": "64", + "SGLANG_DISAGG_STAGING_POOL_SIZE_MB": "1024", +} + + +class TestDisaggregationStagingPrefillLargerTP(PDDisaggregationServerBase): + """Prefill TP=4 -> Decode TP=2 with staging buffer enabled (MHA model).""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + envs.SGLANG_ENABLE_JIT_DEEPGEMM.set(False) + + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST) + + cls.start_prefill() + cls.start_decode() + + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + env = {**os.environ, **STAGING_ENV} + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + env=env, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + "--base-gpu-id", + "4", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + env = {**os.environ, **STAGING_ENV} + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + env=env, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"[Staging PrefillLargerTP] Evaluation metrics: {metrics}") + self.assertGreater(metrics["score"], 0.60) + + +class TestDisaggregationStagingDecodeLargerTP(PDDisaggregationServerBase): + """Prefill TP=2 -> Decode TP=4 with staging buffer enabled (MHA model).""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + envs.SGLANG_ENABLE_JIT_DEEPGEMM.set(False) + + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST) + + cls.start_prefill() + cls.start_decode() + + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + env = {**os.environ, **STAGING_ENV} + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + env=env, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--base-gpu-id", + "4", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + env = {**os.environ, **STAGING_ENV} + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + env=env, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"[Staging DecodeLargerTP] Evaluation metrics: {metrics}") + self.assertGreater(metrics["score"], 0.60) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_dp_attention.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_dp_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..996210b93fb296cd4d9a34c0d20d4a1475660466 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_dp_attention.py @@ -0,0 +1,134 @@ +import unittest +from types import SimpleNamespace + +from sglang.benchmark.serving import run_benchmark +from sglang.srt.environ import envs +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST_MLA, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + get_benchmark_args, + popen_launch_pd_server, + try_cached_model, +) + +register_cuda_ci(est_time=443, stage="base-c", runner_config="8-gpu-h20") + + +class TestDisaggregationDPAttention(PDDisaggregationServerBase): + """PD-disagg + DP-attention e2e on `total_tokens` LB — the most complex + dispatch (token accounting + tie-break + estimated_tokens). Simpler + algorithms are unit-tested in + test/registered/unit/managers/test_data_parallel_controller.py. + """ + + PREFILL_DP_SIZE = 4 + DECODE_DP_SIZE = 4 + LOAD_BALANCE_METHOD = "total_tokens" + + @classmethod + def setUpClass(cls): + super().setUpClass() + # Temporarily disable JIT DeepGEMM + envs.SGLANG_ENABLE_JIT_DEEPGEMM.set(False) + + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST_MLA) + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + str(cls.PREFILL_DP_SIZE), + "--dp", + str(cls.PREFILL_DP_SIZE), + "--enable-dp-attention", + "--load-balance-method", + cls.LOAD_BALANCE_METHOD, + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + str(cls.DECODE_DP_SIZE), + "--dp", + str(cls.DECODE_DP_SIZE), + "--enable-dp-attention", + "--base-gpu-id", + str(cls.PREFILL_DP_SIZE), + "--load-balance-method", + cls.LOAD_BALANCE_METHOD, + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=1400, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.60) + + def test_bench_serving(self): + args = get_benchmark_args( + base_url=f"http://{self.base_host}:{self.lb_port}", + dataset_name="random", + tokenizer=self.model, + num_prompts=1000, + random_input_len=4096, + random_output_len=1024, + request_rate=float("inf"), + max_concurrency=256, + ) + result = run_benchmark(args) + + self.assertLess(result["mean_tpot_ms"], 20) + self.assertEqual(result["completed"], 1000) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_dsv4.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_dsv4.py new file mode 100644 index 0000000000000000000000000000000000000000..4bbb072f8cb7946d7802d95bb2c7fb7d24eb51d6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_dsv4.py @@ -0,0 +1,129 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + popen_launch_pd_server, + try_cached_model, +) + +register_cuda_ci(est_time=500, stage="base-c", runner_config="deepep-8-gpu-h200") + +DSV4_FLASH_MODEL = "sgl-project/DeepSeek-V4-Flash-FP8" + +DEEPEP_CONFIG = '{"normal_dispatch":{"num_sms":96},"normal_combine":{"num_sms":96}}' + +DSV4_FLASH_ENV = { + "SGLANG_DSV4_FP4_EXPERTS": "0", + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "256", +} + +_EAGLE_SPEC_ARGS = [ + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", +] + + +class TestDisaggregationDSV4(SpecDecodingMixin, PDDisaggregationServerBase, GSM8KMixin): + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 1.8 + bs_1_speed_thres = 140 + + @classmethod + def setUpClass(cls): + super().setUpClass() + + cls.model = try_cached_model(DSV4_FLASH_MODEL) + + cls.start_prefill() + cls.start_decode() + + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + 4, + "--dp", + 4, + "--enable-dp-attention", + "--moe-a2a-backend", + "deepep", + "--deepep-config", + DEEPEP_CONFIG, + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "128", + *_EAGLE_SPEC_ARGS, + "--watchdog-timeout", + "900", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + env=DSV4_FLASH_ENV, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + 4, + "--dp", + 4, + "--enable-dp-attention", + "--base-gpu-id", + 4, + "--moe-a2a-backend", + "deepep", + "--deepep-config", + DEEPEP_CONFIG, + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "128", + *_EAGLE_SPEC_ARGS, + "--watchdog-timeout", + "900", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + env=DSV4_FLASH_ENV, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_hisparse.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_hisparse.py new file mode 100644 index 0000000000000000000000000000000000000000..e4b124808871e4c955556821c8efecb66568bd81 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_hisparse.py @@ -0,0 +1,162 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + is_in_ci, + popen_launch_pd_server, + try_cached_model, +) + +register_cuda_ci(est_time=1000, stage="extra-b", runner_config="deepep-8-gpu-h200") + +DSV4_FLASH_MODEL = "sgl-project/DeepSeek-V4-Flash-FP8" +DSV4_FLASH_LOADER_CONFIG = '{"enable_multithread_load": true, "num_threads": 64}' +DSV4_HISPARSE_CONFIG = ( + '{"top_k":512,"device_buffer_size":4096,"host_to_device_ratio":2}' +) + +DSV4_FLASH_ENV = { + "SGLANG_DSV4_FP4_EXPERTS": "0", + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "256", +} +DSV4_NIXL_SERVER_LAUNCH_TIMEOUT = 1800 + + +def _has_nixl(): + try: + import nixl._api # noqa: F401 + except Exception: + return False + return True + + +class TestDisaggregationDSV4HiSparseBase(PDDisaggregationServerBase, GSM8KMixin): + gsm8k_accuracy_thres = 0.93 + gsm8k_num_questions = 200 + gsm8k_num_shots = 20 + + @classmethod + def setUpClass(cls): + super().setUpClass() + + cls.model = try_cached_model(DSV4_FLASH_MODEL) + cls.start_prefill() + cls.start_decode() + + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + 4, + "--page-size", + 256, + "--chunked-prefill-size", + 8192, + "--max-running-requests", + 16, + "--mem-fraction-static", + 0.9, + "--skip-server-warmup", + "--reasoning-parser", + "deepseek-v4", + "--tool-call-parser", + "deepseekv4", + "--model-loader-extra-config", + DSV4_FLASH_LOADER_CONFIG, + "--watchdog-timeout", + "900", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + env=DSV4_FLASH_ENV, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + 4, + "--base-gpu-id", + 4, + "--page-size", + 256, + "--chunked-prefill-size", + 8192, + "--max-running-requests", + 16, + "--mem-fraction-static", + 0.9, + "--skip-server-warmup", + "--reasoning-parser", + "deepseek-v4", + "--tool-call-parser", + "deepseekv4", + "--model-loader-extra-config", + DSV4_FLASH_LOADER_CONFIG, + "--enable-hisparse", + "--hisparse-config", + DSV4_HISPARSE_CONFIG, + "--watchdog-timeout", + "900", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + env=DSV4_FLASH_ENV, + ) + + +@unittest.skipIf(is_in_ci(), "Flaky in CI — skip until stabilized.") +class TestDisaggregationDSV4HiSparseNixl(TestDisaggregationDSV4HiSparseBase): + @classmethod + def setUpClass(cls): + PDDisaggregationServerBase.setUpClass.__func__(cls) + + cls.transfer_backend = ["--disaggregation-transfer-backend", "nixl"] + cls.model = try_cached_model(DSV4_FLASH_MODEL) + + cls.start_prefill() + cls.start_decode() + + cls.wait_server_ready( + cls.prefill_url + "/health", + timeout=DSV4_NIXL_SERVER_LAUNCH_TIMEOUT, + process=cls.process_prefill, + ) + cls.wait_server_ready( + cls.decode_url + "/health", + timeout=DSV4_NIXL_SERVER_LAUNCH_TIMEOUT, + process=cls.process_decode, + ) + + cls.launch_lb() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_hybrid_attention.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_hybrid_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..6962a5d1c3db039cfbbdf760c9154e2f95d85ad0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_hybrid_attention.py @@ -0,0 +1,396 @@ +import unittest +from types import SimpleNamespace + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + is_in_ci, + popen_launch_pd_server, +) + +register_cuda_ci(est_time=310, stage="extra-b", runner_config="8-gpu-h200") + + +@unittest.skipIf(is_in_ci(), "Temporarily disable the flaky test.") +class TestDisaggregationHybridAttentionGDN(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = "Qwen/Qwen3-Next-80B-A3B-Instruct" + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--base-gpu-id", + "4", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.93) + + +class TestDisaggregationHybridAttentionGDNExtraBuffer(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = "Qwen/Qwen3-Next-80B-A3B-Instruct" + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--mamba-scheduler-strategy", + "extra_buffer", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--base-gpu-id", + "4", + "--mamba-scheduler-strategy", + "extra_buffer", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + # TODO: Fix PD disaggregation accuracy issue (https://github.com/sgl-project/sglang/issues/21744) and increase the threshold back to 0.93. + self.assertGreater(metrics["score"], 0.90) + + +class TestDisaggregationHybridAttentionGDNDPDecode(PDDisaggregationServerBase): + """Test with prefill tp=2 and decode tp=2/dp=2 with dp-attention enabled.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = "Qwen/Qwen3-Next-80B-A3B-Instruct" + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "2", + "--dp", + "2", + "--enable-dp-attention", + "--enable-dp-lm-head", + "--base-gpu-id", + "2", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + # TODO: Fix PD disaggregation accuracy issue (https://github.com/sgl-project/sglang/issues/21744) and increase the threshold back to 0.93. + self.assertGreater(metrics["score"], 0.90) + + +class TestDisaggregationHybridAttentionMamba(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = "nvidia/NVIDIA-Nemotron-Nano-9B-v2" + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--base-gpu-id", + "4", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.87) + + +class TestDisaggregationHybridAttentionMambaExtraBuffer(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = "nvidia/NVIDIA-Nemotron-Nano-9B-v2" + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--mamba-scheduler-strategy", + "extra_buffer", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "4", + "--base-gpu-id", + "4", + "--mamba-scheduler-strategy", + "extra_buffer", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"Evaluation metrics: {metrics}") + + self.assertGreater(metrics["score"], 0.87) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_optimistic_prefill.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_optimistic_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..63e27f96f27f51fa343bd7da55b2d9298d2a8c0a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_optimistic_prefill.py @@ -0,0 +1,202 @@ +import time +import unittest +import uuid +from concurrent.futures import ThreadPoolExecutor, as_completed +from types import SimpleNamespace + +import requests +from prometheus_client.parser import text_string_to_metric_families + +from sglang.srt.disaggregation.prefill import should_force_retry +from sglang.srt.environ import envs +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import DEFAULT_MODEL_NAME_FOR_TEST + +register_cuda_ci(est_time=120, stage="base-b", runner_config="2-gpu-large") + + +FORCE_RETRY_PROB = 0.1 + + +def rid_that_forces_retry(prefix: str) -> str: + """Return a rid that the test retry sampler will select.""" + for _ in range(1000): + rid = f"{prefix}{uuid.uuid4().hex}" + req = SimpleNamespace( + rid=rid, + is_retracted=False, + time_stats=SimpleNamespace(prefill_retry_count=0), + ) + if should_force_retry(req): + return rid + raise RuntimeError("Failed to sample an optimistic prefill retry rid") + + +class OptimisticPrefillRetryCounterMixin: + def _get_retry_counter(self) -> float: + response = requests.get(f"{self.prefill_url}/metrics") + response.raise_for_status() + total = 0.0 + for family in text_string_to_metric_families(response.text): + if family.name != "sglang:num_prefill_retries": + continue + for sample in family.samples: + if sample.name == "sglang:num_prefill_retries_total": + total += sample.value + return total + + def assert_retry_counter_increases(self, fn): + before_retries = self._get_retry_counter() + result = fn() + after_retries = self._get_retry_counter() + self.assertGreater(after_retries, before_retries) + return result + + +class TestOptimisticPrefill( + OptimisticPrefillRetryCounterMixin, PDDisaggregationServerBase +): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls._force_retry_prob_was_set = ( + envs.SGLANG_TEST_FORCE_OPTIMISTIC_PREFILL_RETRY_PROB.is_set() + ) + cls._force_retry_prob_value = ( + envs.SGLANG_TEST_FORCE_OPTIMISTIC_PREFILL_RETRY_PROB.get() + ) + envs.SGLANG_TEST_FORCE_OPTIMISTIC_PREFILL_RETRY_PROB.set(FORCE_RETRY_PROB) + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.extra_prefill_args = [ + "--optimistic-prefill-retries", + "3", + "--chunked-prefill-size", + "128", + "--enable-metrics", + "--enable-request-time-stats-logging", + ] + cls.launch_all() + + @classmethod + def tearDownClass(cls): + try: + super().tearDownClass() + finally: + if getattr(cls, "_force_retry_prob_was_set", False): + envs.SGLANG_TEST_FORCE_OPTIMISTIC_PREFILL_RETRY_PROB.set( + cls._force_retry_prob_value + ) + else: + envs.SGLANG_TEST_FORCE_OPTIMISTIC_PREFILL_RETRY_PROB.clear() + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=f"http://{self.base_host}:{self.lb_port}", + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = self.assert_retry_counter_increases(lambda: run_eval(args)) + print(f"Evaluation metrics: {metrics}") + self.assertGreater(metrics["score"], 0.62) + time.sleep(1) # trigger memory check + + def test_logprob(self): + request_id = rid_that_forces_retry("logprob-retry-") + prompt = f"{request_id}: " + "The capital of France is Paris. " * 900 + j = self.assert_retry_counter_increases( + lambda: requests.post( + self.lb_url + "/generate", + json={ + "rid": request_id, + "text": prompt, + "sampling_params": {"temperature": 0, "max_new_tokens": 8}, + "return_logprob": True, + "return_input_logprob": True, + "logprob_start_len": 0, + }, + ).json() + ) + completion_tokens = j["meta_info"]["completion_tokens"] + input_logprobs = j["meta_info"]["input_token_logprobs"] + output_logprobs = j["meta_info"]["output_token_logprobs"] + + self.assertGreater(j["meta_info"]["prompt_tokens"], 512) + assert len(output_logprobs) == completion_tokens + assert len(input_logprobs) > 0 + + +class TestOptimisticPrefillFailure(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + # enable optimistic prefill retry sampling and disagg failure prob + cls._force_retry_ctx = ( + envs.SGLANG_TEST_FORCE_OPTIMISTIC_PREFILL_RETRY_PROB.override( + FORCE_RETRY_PROB + ) + ) + cls._force_retry_ctx.__enter__() + cls._disagg_failure_ctx = envs.SGLANG_TEST_DISAGG_FAILURE_PROB.override( + FORCE_RETRY_PROB + ) + cls._disagg_failure_ctx.__enter__() + + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.extra_prefill_args = [ + "--optimistic-prefill-retries", + "3", + "--chunked-prefill-size", + "128", + "--enable-metrics", + "--enable-request-time-stats-logging", + "--load-format", + "dummy", + ] + cls.launch_all() + + @classmethod + def tearDownClass(cls): + try: + super().tearDownClass() + finally: + if getattr(cls, "_force_retry_ctx", None): + cls._force_retry_ctx.__exit__(None, None, None) + if getattr(cls, "_disagg_failure_ctx", None): + cls._disagg_failure_ctx.__exit__(None, None, None) + + def test_survive_requests(self): + # send many small requests to ensure the engine survives injected failures + n = 100 + with ThreadPoolExecutor(max_workers=32) as executor: + futures = [] + for i in range(n): + rid = f"survive-{i}-{uuid.uuid4().hex}" + futures.append( + executor.submit( + requests.post, + self.lb_url + "/generate", + json={ + "rid": rid, + "text": "Hello world", + "sampling_params": {"temperature": 0, "max_new_tokens": 4}, + }, + timeout=30, + ) + ) + for future in as_completed(futures): + try: + _ = future.result() + except Exception: + pass + time.sleep(1) # trigger memory check + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_pp.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_pp.py new file mode 100644 index 0000000000000000000000000000000000000000..aab493056997bdf573f66e6b418d899fbb20a072 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_pp.py @@ -0,0 +1,255 @@ +import time +import unittest +from types import SimpleNamespace + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + popen_launch_pd_server, + try_cached_model, +) + +register_cuda_ci(est_time=216, stage="base-c", runner_config="8-gpu-h20") + + +class TestDisaggregationPrefillPPAccuracy(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST) + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp-size", + "2", + "--pp-size", + "2", + "--disable-overlap-schedule", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp-size", + "2", + "--base-gpu-id", + "4", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + + self.assertGreater(metrics["score"], 0.24) + # Wait a little bit so that the memory check happens. + time.sleep(5) + + +class TestDisaggregationPrefillPPDynamicChunkAccuracy(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST) + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp-size", + "2", + "--pp-size", + "2", + "--disable-overlap-schedule", + "--enable-dynamic-chunking", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp-size", + "2", + "--base-gpu-id", + "4", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + + self.assertGreater(metrics["score"], 0.24) + # Wait a little bit so that the memory check happens. + time.sleep(5) + + +class TestDisaggregationDecodePPAccuracy(PDDisaggregationServerBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = try_cached_model(DEFAULT_MODEL_NAME_FOR_TEST) + + # Non blocking start servers + cls.start_prefill() + cls.start_decode() + + # Block until both + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp-size", + "2", + "--pp-size", + "2", + "--disable-overlap-schedule", + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_pd_server( + cls.model, + cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp-size", + "2", + "--pp-size", + "2", + "--base-gpu-id", + "4", + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_pd_server( + cls.model, + cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + + self.assertGreater(metrics["score"], 0.24) + # Wait a little bit so that the memory check happens. + time.sleep(5) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_xpu.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_xpu.py new file mode 100644 index 0000000000000000000000000000000000000000..9802ab9df15eb469d3370980397d144d8a54e9fb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_disaggregation_xpu.py @@ -0,0 +1,93 @@ +""" +Disaggregation integration test for the NIXL transfer backend on Intel XPU. + +Launches a prefill server, a decode server, and a load-balancer using the +NIXL KV-transfer backend, then verifies that basic text completion works +end-to-end. This exercises the np.uint64 pointer-arithmetic fix in +python/sglang/srt/disaggregation/nixl/conn.py, which is required on +Intel XPU where device addresses have bit 63 set (e.g. 0xffff81ab54e01000) +and would overflow np.int64. + +Usage: + python3 -m pytest test/registered/disaggregation/test_disaggregation_xpu.py -v +""" + +import subprocess +import unittest + +import requests +import torch + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST_QWEN + +register_cuda_ci( + est_time=300, + stage="base-a", + runner_config="1-gpu-small", + disabled="Intel XPU only — not available in standard CUDA CI", +) + +_XPU_AVAILABLE = torch.xpu.is_available() + + +@unittest.skipUnless( + _XPU_AVAILABLE, "Intel XPU not available (torch.xpu.is_available() returned False)" +) +class TestDisaggregationNixlBasic(PDDisaggregationServerBase): + """Smoke-test the NIXL disaggregation backend with a small completion.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST_QWEN + # Force the NIXL backend and XPU device. + cls.transfer_backend = ["--disaggregation-transfer-backend", "nixl"] + cls.rdma_devices = [] + cls.extra_prefill_args = ["--device", "xpu"] + cls.extra_decode_args = ["--device", "xpu"] + subprocess.check_call( + ["pip", "install", "sglang-router"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + cls.launch_all() + + def test_completion_returns_text(self): + """A simple completion must succeed and return non-empty generated text.""" + response = requests.post( + self.lb_url + "/generate", + json={ + "text": "The capital of France is", + "sampling_params": {"temperature": 0, "max_new_tokens": 16}, + }, + ) + self.assertEqual(response.status_code, 200, response.text) + data = response.json() + self.assertIn("text", data, f"Unexpected response shape: {data}") + self.assertGreater( + len(data["text"]), + 0, + "Generated text should not be empty", + ) + + def test_completion_correct_output(self): + """Disaggregated NIXL output must produce the expected token for a deterministic prompt.""" + response = requests.post( + self.lb_url + "/generate", + json={ + "text": "1 + 1 =", + "sampling_params": {"temperature": 0, "max_new_tokens": 4}, + }, + ) + self.assertEqual(response.status_code, 200, response.text) + generated = response.json()["text"] + # The model should produce "2" somewhere in the first few tokens. + self.assertIn("2", generated, f"Expected '2' in output, got: {generated!r}") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_epd_disaggregation.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_epd_disaggregation.py new file mode 100644 index 0000000000000000000000000000000000000000..55188cc814ccdc90e876d1c96ae3bd26c469af79 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_epd_disaggregation.py @@ -0,0 +1,1515 @@ +import io +import os +import re +import subprocess +import threading +import time +import unittest + +import grpc +import openai +import zmq +from grpc_health.v1 import health_pb2, health_pb2_grpc + +from sglang.srt.utils import kill_process_tree +from sglang.srt.utils.network import get_zmq_socket_on_host +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.mmmu_vlm_kit import MMMUMixin +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) +from sglang.test.test_utils import ( + DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + is_in_ci, + popen_launch_server, +) +from sglang.test.vlm_utils import ( + AUDIO_TRUMP_SPEECH_URL, + IMAGE_MAN_IRONING_URL, + IMAGE_SGL_LOGO_URL, + VIDEO_JOBS_URL, +) + +# Omni model for local testing; override via env var EPD_OMNI_MODEL +DEFAULT_OMNI_MODEL = "Qwen/Qwen3-Omni-30B-A3B-Instruct" +QWEN35_27B_MODEL = "Qwen/Qwen3.5-27B" + + +register_cuda_ci(est_time=97, stage="base-c", runner_config="4-gpu-h100") + + +@unittest.skipIf( + is_in_ci(), + "Omni model EPD test with image, video, and audio modalities, running locally only", +) +class TestEPDDisaggregationOmni(PDDisaggregationServerBase): + """ + EPD disaggregation test for omni models (e.g. Qwen3-Omni). Covers image, video, + and audio when server_type=http (encoder_transfer_backend: mooncake/zmq_to_scheduler/zmq_to_tokenizer). + When server_type=grpc, only image is tested (gRPC encode is image-only). + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = os.environ.get("EPD_OMNI_MODEL", DEFAULT_OMNI_MODEL) + cls.server_type = os.environ.get("EPD_ENCODE_SERVER_TYPE", "http") + assert cls.server_type in ( + "grpc", + "http", + ), f"Invalid EPD_ENCODE_SERVER_TYPE: {cls.server_type}" + cls.encoder_transfer_backend = os.environ.get( + "EPD_ENCODER_TRANSFER_BACKEND", "zmq_to_scheduler" + ) + assert cls.encoder_transfer_backend in ( + "mooncake", + "zmq_to_scheduler", + "zmq_to_tokenizer", + ), f"Invalid EPD_ENCODER_TRANSFER_BACKEND: {cls.encoder_transfer_backend}" + cls.enable_global_cache = ( + os.environ.get("MOONCAKE_MASTER") is not None + or os.environ.get("MOONCAKE_CLIENT") is not None + ) + if cls.server_type == "grpc": + cls.encode_port = f"{int(cls.lb_port) + 305}" + cls.encode_url = f"grpc://{cls.base_host}:{cls.encode_port}" + else: + cls.encode_port = f"{int(cls.lb_port) + 300}" + cls.encode_url = f"http://{cls.base_host}:{cls.encode_port}" + + cls.image_man_ironing = IMAGE_MAN_IRONING_URL + cls.image_sgl_logo = IMAGE_SGL_LOGO_URL + cls.video_jobs = VIDEO_JOBS_URL + cls.audio_trump = AUDIO_TRUMP_SPEECH_URL + + print( + f"Setting up EPD Omni: model={cls.model}, encode={cls.encode_port}, " + f"prefill={cls.prefill_port}, decode={cls.decode_port}, " + f"server_type={cls.server_type}, backend={cls.encoder_transfer_backend}, " + f"global_cache={cls.enable_global_cache}" + ) + print(f"Data URLs: image={cls.image_man_ironing}, audio={cls.audio_trump}") + + cls.start_encode() + prefill_thread = threading.Thread(target=cls.start_prefill) + decode_thread = threading.Thread(target=cls.start_decode) + prefill_thread.start() + decode_thread.start() + prefill_thread.join() + decode_thread.join() + + if cls.server_type == "grpc": + cls._wait_grpc_ready(cls.base_host, cls.encode_port, cls.process_encode) + else: + cls.wait_server_ready( + cls.encode_url + "/health", process=cls.process_encode + ) + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + cls.api_key = "sk-123456" + os.environ["OPENAI_API_KEY"] = cls.api_key + os.environ["OPENAI_API_BASE"] = f"{cls.lb_url}/v1" + + @classmethod + def start_encode(cls): + if cls.server_type == "grpc": + cls.encode_stdout = io.StringIO() + cls.encode_stderr = io.StringIO() + cls.process_encode = subprocess.Popen( + [ + "python3", + "-m", + "sglang.launch_server", + "--model-path", + cls.model, + "--host", + cls.base_host, + "--port", + cls.encode_port, + "--trust-remote-code", + "--encoder-only", + "--grpc-mode", + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--tp", + "1", + ] + ) + else: + encode_args = [ + "--trust-remote-code", + "--encoder-only", + "--encoder-transfer-backend", + cls.encoder_transfer_backend, + "--tp", + "1", + "--port", + cls.encode_port, + ] + if cls.enable_global_cache: + encode_args.append("--enable-mm-global-cache") + cls.encode_stdout = io.StringIO() + cls.encode_stderr = io.StringIO() + cls.process_encode = popen_launch_server( + cls.model, + base_url=cls.encode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=encode_args, + return_stdout_stderr=(cls.encode_stdout, cls.encode_stderr), + ) + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--language-only", + "--encoder-urls", + cls.encode_url, + "--encoder-transfer-backend", + ( + "zmq_to_scheduler" + if cls.server_type == "grpc" + else cls.encoder_transfer_backend + ), + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "1", + "--port", + cls.prefill_port, + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + prefill_env = os.environ.copy() + if cls.server_type == "grpc": + prefill_env["SGLANG_ENCODER_MM_RECEIVER_MODE"] = "grpc" + cls.process_prefill = popen_launch_server( + cls.model, + base_url=cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + env=prefill_env, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "2", + "--port", + cls.decode_port, + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_server( + cls.model, + base_url=cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + @classmethod + def tearDownClass(cls): + for process in [ + cls.process_lb, + cls.process_decode, + cls.process_prefill, + cls.process_encode, + ]: + if process: + try: + kill_process_tree(process.pid) + except Exception as e: + print(f"Error killing process: {e}") + + @staticmethod + def _wait_grpc_ready( + host, port, process, timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH + ): + deadline = time.time() + timeout + channel = grpc.insecure_channel(f"{host}:{port}") + stub = health_pb2_grpc.HealthStub(channel) + try: + while time.time() < deadline: + if process.poll() is not None: + raise RuntimeError( + f"gRPC encoder exited with code {process.returncode}" + ) + try: + response = stub.Check( + health_pb2.HealthCheckRequest(service=""), timeout=2 + ) + if response.status == health_pb2.HealthCheckResponse.SERVING: + return + except grpc.RpcError: + pass + time.sleep(1) + finally: + channel.close() + raise RuntimeError(f"gRPC encoder not ready at {host}:{port} within {timeout}s") + + # ---- helpers ---- + + def _client(self): + return openai.Client(api_key=self.api_key, base_url=f"{self.lb_url}/v1") + + def _skip_if_grpc(self, msg="gRPC encode is image-only"): + """Skip this test when encode server is gRPC (image-only).""" + if self.server_type == "grpc": + self.skipTest(msg) + + def _parse_cache_log(self): + """Parse encode server logs and return list of (local_hits, global_hits, misses) + tuples from '=== Multi-Level Cache Check ===' lines.""" + log = self.encode_stdout.getvalue() + self.encode_stderr.getvalue() + pattern = re.compile( + r"Multi-Level Cache Check.*?" + r"Local Hits:\s*(\d+).*?" + r"Global Hits:\s*(\d+).*?" + r"Misses.*?:\s*(\d+)" + ) + return [(int(m[1]), int(m[2]), int(m[3])) for m in pattern.finditer(log)] + + # ---- image ---- + def test_image(self): + client = self._client() + response = client.chat.completions.create( + model="default", + messages=[ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": {"url": self.image_man_ironing}, + }, + { + "type": "text", + "text": "Describe this image in a sentence.", + }, + ], + }, + ], + temperature=0, + max_tokens=256, + ) + text = response.choices[0].message.content + print(f"[Omni EPD] Image response:\n{text}") + self.assertIsNotNone(text) + self.assertGreater(len(text), 0) + + text_lower = text.lower() + self.assertTrue( + any(w in text_lower for w in ("man", "person", "driver")), + f"Image response should mention a person: {text}", + ) + self.assertTrue( + any(w in text_lower for w in ("iron", "cloth", "hang", "holding")), + f"Image response should mention ironing/clothes: {text}", + ) + + def test_image_cache_hit(self): + """Send the same image twice; the second request should hit the global-mm-cache.""" + self._skip_if_grpc("gRPC encode is image-only; cache test uses HTTP path") + if not self.enable_global_cache: + self.skipTest("global-mm-cache not enabled (MOONCAKE_MASTER not set)") + client = self._client() + baseline = len(self._parse_cache_log()) + for i in range(2): + response = client.chat.completions.create( + model="default", + messages=[ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": {"url": self.image_sgl_logo}, + }, + { + "type": "text", + "text": "What is shown in this image?", + }, + ], + }, + ], + temperature=0, + max_tokens=128, + ) + text = response.choices[0].message.content + print(f"[Omni EPD] Image cache-hit round {i}: {text}") + self.assertIsNotNone(text) + self.assertGreater(len(text), 0) + time.sleep(1) + + entries = self._parse_cache_log()[baseline:] + print(f"[Omni EPD] Image cache log entries: {entries}") + self.assertGreaterEqual( + len(entries), 2, "Expected at least 2 cache-check log entries" + ) + local_hits, global_hits, _ = entries[-1] + self.assertGreater( + local_hits + global_hits, + 0, + f"Second image request should have cache hits, got: {entries[-1]}", + ) + + # ---- video ---- + def test_video(self): + self._skip_if_grpc() + client = self._client() + response = client.chat.completions.create( + model="default", + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": "Describe the video."}, + { + "type": "video_url", + "video_url": {"url": self.video_jobs}, + }, + ], + }, + ], + max_tokens=8192, + stream=False, + ) + text = response.choices[0].message.content + print(f"[Omni EPD] Video response:\n{text}") + self.assertIsNotNone(text) + self.assertGreater(len(text), 0) + + text_lower = text.lower() + self.assertTrue( + any( + w in text_lower + for w in ("ipod", "device", "microphone", "smartphone", "phone") + ), + f"Video response should mention a device: {text}", + ) + self.assertTrue( + any( + w in text_lower + for w in ( + "man", + "person", + "individual", + "speaker", + "presenter", + "steve", + "hand", + "hands", + ) + ), + f"Video response should mention a person: {text}", + ) + self.assertTrue( + any( + w in text_lower + for w in ( + "present", + "presenting", + "examine", + "examining", + "display", + "displaying", + "hold", + "holding", + "gestur", + "speak", + "speaking", + ) + ), + f"Video response should mention an action: {text}", + ) + + def test_video_cache_hit(self): + """Send the same video twice; the second request should hit the global-mm-cache.""" + self._skip_if_grpc() + if not self.enable_global_cache: + self.skipTest("global-mm-cache not enabled (MOONCAKE_MASTER not set)") + client = self._client() + baseline = len(self._parse_cache_log()) + for i in range(2): + response = client.chat.completions.create( + model="default", + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": "Describe the video."}, + { + "type": "video_url", + "video_url": {"url": self.video_jobs}, + }, + ], + }, + ], + max_tokens=256, + stream=False, + ) + text = response.choices[0].message.content + print(f"[Omni EPD] Video cache-hit round {i}: {text}") + self.assertIsNotNone(text) + self.assertGreater(len(text), 0) + time.sleep(1) + + entries = self._parse_cache_log()[baseline:] + print(f"[Omni EPD] Video cache log entries: {entries}") + self.assertGreaterEqual( + len(entries), 2, "Expected at least 2 cache-check log entries" + ) + local_hits, global_hits, _ = entries[-1] + self.assertGreater( + local_hits + global_hits, + 0, + f"Second video request should have cache hits, got: {entries[-1]}", + ) + + # ---- audio ---- + + def test_audio(self): + self._skip_if_grpc() + client = self._client() + response = client.chat.completions.create( + model="default", + messages=[ + { + "role": "user", + "content": [ + { + "type": "audio_url", + "audio_url": {"url": self.audio_trump}, + }, + { + "type": "text", + "text": "Listen to this audio and write down the audio transcription in English.", + }, + ], + }, + ], + temperature=0, + max_tokens=256, + stream=False, + ) + text = response.choices[0].message.content + print(f"[Omni EPD] Audio response:\n{text}") + self.assertIsNotNone(text) + self.assertGreater(len(text), 0) + + text_lower = text.lower() + for keyword in ("thank you", "leader"): + self.assertIn( + keyword, + text_lower, + f"Audio response should contain '{keyword}': {text}", + ) + + def test_audio_cache_hit(self): + """Send the same audio twice; the second request should hit the global-mm-cache.""" + self._skip_if_grpc() + if not self.enable_global_cache: + self.skipTest("global-mm-cache not enabled (MOONCAKE_MASTER not set)") + client = self._client() + baseline = len(self._parse_cache_log()) + for i in range(2): + response = client.chat.completions.create( + model="default", + messages=[ + { + "role": "user", + "content": [ + { + "type": "audio_url", + "audio_url": {"url": self.audio_trump}, + }, + { + "type": "text", + "text": "What is this audio about?", + }, + ], + }, + ], + temperature=0, + max_tokens=128, + stream=False, + ) + text = response.choices[0].message.content + print(f"[Omni EPD] Audio cache-hit round {i}: {text}") + self.assertIsNotNone(text) + self.assertGreater(len(text), 0) + time.sleep(1) + + entries = self._parse_cache_log()[baseline:] + print(f"[Omni EPD] Audio cache log entries: {entries}") + self.assertGreaterEqual( + len(entries), 2, "Expected at least 2 cache-check log entries" + ) + local_hits, global_hits, _ = entries[-1] + self.assertGreater( + local_hits + global_hits, + 0, + f"Second audio request should have cache hits, got: {entries[-1]}", + ) + + # ---- mixed modality ---- + + def test_mixed_image_audio_video(self): + """Image + audio + video in one request to test multi-modal routing.""" + self._skip_if_grpc() + client = self._client() + response = client.chat.completions.create( + model="default", + messages=[ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": {"url": self.image_man_ironing}, + }, + { + "type": "audio_url", + "audio_url": {"url": self.audio_trump}, + }, + { + "type": "video_url", + "video_url": {"url": self.video_jobs}, + }, + { + "type": "text", + "text": ( + "I have an image, an audio clip, and a video, which are not related at all. " + "Please: 1. Describe the image in a sentence, " + "2. Summarize the audio content briefly, " + "3. Describe what happens in the video." + ), + }, + ], + }, + ], + temperature=0, + max_tokens=512, + stream=False, + ) + text = response.choices[0].message.content + print(f"[Omni EPD] Mixed image+audio+video response:\n{text}") + self.assertIsNotNone(text) + self.assertGreater(len(text), 0) + + text_lower = text.lower() + self.assertTrue( + any(w in text_lower for w in ("man", "person", "iron", "cloth")), + f"Mixed response should describe the image: {text}", + ) + + +@unittest.skipIf(is_in_ci(), "Skipping in CI to reduce multi-GPU runtime") +class TestEPDDisaggregationOneEncoder(MMMUMixin, PDDisaggregationServerBase): + """Test EPD disaggregation with single encode server""" + + # Qwen2.5-VL-3B-Instruct scores ~0.40 on the 50-sample MMMU subset. + accuracy = 0.40 + mmmu_args = ["--limit", "50"] + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST + cls.base_url = cls.lb_url # MMMUMixin reads this for OPENAI_API_BASE + cls.encode_port = f"{int(cls.lb_port) + 300}" + cls.encode_url = f"http://{cls.base_host}:{cls.encode_port}" + + print( + f"Setting up EPD (one encoder): encode={cls.encode_port}, " + f"prefill={cls.prefill_port}, decode={cls.decode_port}" + ) + + # Start servers in order: encode -> prefill/decode + cls.start_encode() + prefill_thread = threading.Thread(target=cls.start_prefill) + decode_thread = threading.Thread(target=cls.start_decode) + prefill_thread.start() + decode_thread.start() + prefill_thread.join() + decode_thread.join() + + # Wait for all servers to be ready + cls.wait_server_ready(cls.encode_url + "/health", process=cls.process_encode) + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + # Set OpenAI API key and base URL environment variables. Needed for lmms-eval to work. + cls.api_key = "sk-123456" + os.environ["OPENAI_API_KEY"] = cls.api_key + os.environ["OPENAI_API_BASE"] = f"{cls.lb_url}/v1" + + @classmethod + def start_encode(cls): + """Start encode server for multimodal processing""" + encode_args = [ + "--trust-remote-code", + "--encoder-only", + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--tp", + "1", + "--port", + cls.encode_port, + "--enable-prefix-mm-cache", + ] + cls.process_encode = popen_launch_server( + cls.model, + base_url=cls.encode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=encode_args, + ) + + @classmethod + def start_prefill(cls): + """Start prefill server with language model only""" + prefill_args = [ + "--trust-remote-code", + "--language-only", + "--encoder-urls", + cls.encode_url, + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "1", + "--port", + cls.prefill_port, + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_server( + cls.model, + base_url=cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + """Start decode server""" + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "2", + "--port", + cls.decode_port, + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_server( + cls.model, + base_url=cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + @classmethod + def tearDownClass(cls): + """Clean up all processes""" + for process in [ + cls.process_lb, + cls.process_decode, + cls.process_prefill, + cls.process_encode, + ]: + if process: + try: + kill_process_tree(process.pid) + except Exception as e: + print(f"Error killing process: {e}") + + +@unittest.skipIf( + is_in_ci(), + "Qwen3.5 EPD image/video test runs locally only", +) +class TestEPDDisaggregationQwen35(PDDisaggregationServerBase): + """EPD disaggregation test for Qwen3.5 image and video requests.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.process_encode = None + cls.model = QWEN35_27B_MODEL + cls.encode_port = f"{int(cls.lb_port) + 300}" + cls.encode_url = f"http://{cls.base_host}:{cls.encode_port}" + cls.language_url = cls.prefill_url + cls.image_man_ironing = IMAGE_MAN_IRONING_URL + cls.video_jobs = VIDEO_JOBS_URL + + print( + f"Setting up Qwen3.5 encoder disaggregation: model={cls.model}, " + f"encode={cls.encode_port}, language={cls.prefill_port}" + ) + + cls.start_encode() + cls.start_prefill() + + cls.wait_server_ready(cls.encode_url + "/health", process=cls.process_encode) + cls.wait_server_ready(cls.language_url + "/health", process=cls.process_prefill) + + cls.api_key = "sk-123456" + + @classmethod + def start_encode(cls): + encode_args = [ + "--trust-remote-code", + "--encoder-only", + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--tp", + "1", + "--port", + cls.encode_port, + "--reasoning-parser", + "qwen3", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', + ] + cls.process_encode = popen_launch_server( + cls.model, + base_url=cls.encode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=encode_args, + ) + + @classmethod + def start_prefill(cls): + language_args = [ + "--trust-remote-code", + "--language-only", + "--encoder-urls", + cls.encode_url, + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--tp", + "1", + "--base-gpu-id", + "1", + "--port", + cls.prefill_port, + "--reasoning-parser", + "qwen3", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', + ] + cls.process_prefill = popen_launch_server( + cls.model, + base_url=cls.language_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=language_args, + ) + + @classmethod + def tearDownClass(cls): + if cls.process_lb: + kill_process_tree(cls.process_lb.pid) + if cls.process_decode: + kill_process_tree(cls.process_decode.pid) + if cls.process_prefill: + kill_process_tree(cls.process_prefill.pid) + if cls.process_encode: + kill_process_tree(cls.process_encode.pid) + + def _client(self): + return openai.Client(api_key=self.api_key, base_url=f"{self.language_url}/v1") + + def test_image(self): + client = self._client() + response = client.chat.completions.create( + model="default", + messages=[ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": {"url": self.image_man_ironing}, + }, + { + "type": "text", + "text": "Describe this image in a sentence.", + }, + ], + }, + ], + temperature=0, + max_tokens=256, + extra_body={"reasoning_effort": "none"}, + ) + text = response.choices[0].message.content + print(f"[Qwen3.5 EPD] Image response:\n{text}") + self.assertIsNotNone(text) + self.assertGreater(len(text), 0) + + text_lower = text.lower() + self.assertTrue( + any(w in text_lower for w in ("man", "person", "driver")), + f"Image response should mention a person: {text}", + ) + self.assertTrue( + any(w in text_lower for w in ("iron", "cloth", "hang", "holding")), + f"Image response should mention ironing/clothes: {text}", + ) + + def test_video(self): + client = self._client() + response = client.chat.completions.create( + model="default", + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": "Describe the video."}, + { + "type": "video_url", + "video_url": {"url": self.video_jobs}, + }, + ], + }, + ], + max_tokens=1024, + stream=False, + ) + text = response.choices[0].message.content + print(f"[Qwen3.5 EPD] Video response:\n{text}") + self.assertIsNotNone(text) + self.assertGreater(len(text), 0) + + text_lower = text.lower() + self.assertTrue( + any( + w in text_lower + for w in ("ipod", "device", "microphone", "smartphone", "phone") + ), + f"Video response should mention a device: {text}", + ) + self.assertTrue( + any( + w in text_lower + for w in ( + "man", + "person", + "individual", + "speaker", + "presenter", + "steve", + "hand", + "hands", + ) + ), + f"Video response should mention a person: {text}", + ) + + +class TestEPDDisaggregationMultiEncoders(MMMUMixin, PDDisaggregationServerBase): + """ + Test EPD disaggregation with multiple encode servers for load balancing. + Both encode servers run on GPU 0 (different ports) for testing load distribution. + """ + + # Qwen2.5-VL-3B-Instruct scores ~0.40 on the 50-sample MMMU subset. + accuracy = 0.40 + mmmu_args = ["--limit", "50"] + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST + cls.base_url = cls.lb_url # MMMUMixin reads this for OPENAI_API_BASE + cls.encode_port1 = f"{int(cls.lb_port) + 300}" + cls.encode_port2 = f"{int(cls.lb_port) + 301}" + cls.encode_url1 = f"http://{cls.base_host}:{cls.encode_port1}" + cls.encode_url2 = f"http://{cls.base_host}:{cls.encode_port2}" + + print( + f"Setting up EPD (multiple encoders): encode1={cls.encode_port1}, " + f"encode2={cls.encode_port2}, prefill={cls.prefill_port}, decode={cls.decode_port}" + ) + + # Start two encode servers on GPU 0/1 + encode1_thread = threading.Thread( + target=cls.start_encode_server, args=(cls.encode_port1, 0) + ) + encode2_thread = threading.Thread( + target=cls.start_encode_server, args=(cls.encode_port2, 1) + ) + encode1_thread.start() + encode2_thread.start() + encode1_thread.join() + encode2_thread.join() + + prefill_thread = threading.Thread(target=cls.start_prefill) + decode_thread = threading.Thread(target=cls.start_decode) + prefill_thread.start() + decode_thread.start() + prefill_thread.join() + decode_thread.join() + + cls.wait_server_ready(cls.encode_url1 + "/health", process=cls.process_encode1) + cls.wait_server_ready(cls.encode_url2 + "/health", process=cls.process_encode2) + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + # Set OpenAI API key and base URL environment variables. Needed for lmms-eval to work. + cls.api_key = "sk-123456" + os.environ["OPENAI_API_KEY"] = cls.api_key + os.environ["OPENAI_API_BASE"] = f"{cls.lb_url}/v1" + + @classmethod + def start_encode_server(cls, port, gpu_id): + """Start an encode server on specific port and GPU""" + encode_args = [ + "--trust-remote-code", + "--encoder-only", + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--tp", + "1", + "--port", + port, + "--enable-prefix-mm-cache", + ] + # Only set base-gpu-id if not using GPU 0 + if gpu_id != 0: + encode_args.extend(["--base-gpu-id", str(gpu_id)]) + + process = popen_launch_server( + cls.model, + base_url=f"http://{cls.base_host}:{port}", + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=encode_args, + ) + if port == cls.encode_port1: + cls.process_encode1 = process + else: + cls.process_encode2 = process + + @classmethod + def start_prefill(cls): + """Start prefill server with multiple encode URLs""" + prefill_args = [ + "--trust-remote-code", + "--language-only", + "--encoder-urls", + cls.encode_url1, + cls.encode_url2, + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "2", + "--port", + cls.prefill_port, + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_server( + cls.model, + base_url=cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + """Start decode server""" + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "3", + "--port", + cls.decode_port, + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_server( + cls.model, + base_url=cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + @classmethod + def tearDownClass(cls): + """Clean up all processes""" + for process in [ + cls.process_lb, + cls.process_decode, + cls.process_prefill, + cls.process_encode1, + cls.process_encode2, + ]: + if process: + try: + kill_process_tree(process.pid) + except Exception as e: + print(f"Error killing process: {e}") + + +@unittest.skipIf(is_in_ci(), "Skipping in CI to reduce multi-GPU runtime") +class TestEPDDisaggregationGrpcEncoderMMMU(MMMUMixin, PDDisaggregationServerBase): + """Test MMMU evaluation with gRPC encoder in EPD mode.""" + + # Qwen2.5-VL-3B-Instruct scores ~0.40 on the 50-sample MMMU subset. + accuracy = 0.40 + mmmu_args = ["--limit", "50"] + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST + cls.base_url = cls.lb_url # MMMUMixin reads this for OPENAI_API_BASE + cls.encode_port = f"{int(cls.lb_port) + 304}" + cls.encode_url = f"grpc://{cls.base_host}:{cls.encode_port}" + + print( + f"Setting up gRPC EPD (one encoder): encode={cls.encode_port}, " + f"prefill={cls.prefill_port}, decode={cls.decode_port}" + ) + + cls.start_encode() + prefill_thread = threading.Thread(target=cls.start_prefill) + decode_thread = threading.Thread(target=cls.start_decode) + prefill_thread.start() + decode_thread.start() + prefill_thread.join() + decode_thread.join() + + cls.wait_grpc_ready(cls.base_host, cls.encode_port, cls.process_encode) + cls.wait_server_ready(cls.prefill_url + "/health") + cls.wait_server_ready(cls.decode_url + "/health") + + cls.launch_lb() + + cls.api_key = "sk-123456" + os.environ["OPENAI_API_KEY"] = cls.api_key + os.environ["OPENAI_API_BASE"] = f"{cls.lb_url}/v1" + + @classmethod + def start_encode(cls): + encode_command = [ + "python3", + "-m", + "sglang.launch_server", + "--model-path", + cls.model, + "--host", + cls.base_host, + "--port", + cls.encode_port, + "--trust-remote-code", + "--encoder-only", + "--grpc-mode", + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--tp", + "1", + "--base-gpu-id", + "0", + "--enable-prefix-mm-cache", + ] + cls.process_encode = subprocess.Popen(encode_command) + + @classmethod + def start_prefill(cls): + prefill_args = [ + "--trust-remote-code", + "--language-only", + "--encoder-urls", + cls.encode_url, + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "1", + "--port", + cls.prefill_port, + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + prefill_env = os.environ.copy() + prefill_env["SGLANG_ENCODER_MM_RECEIVER_MODE"] = "grpc" + cls.process_prefill = popen_launch_server( + cls.model, + base_url=cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + env=prefill_env, + ) + + @classmethod + def start_decode(cls): + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "2", + "--port", + cls.decode_port, + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_server( + cls.model, + base_url=cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + @staticmethod + def wait_grpc_ready(host, port, process, timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH): + deadline = time.time() + timeout + channel = grpc.insecure_channel(f"{host}:{port}") + stub = health_pb2_grpc.HealthStub(channel) + try: + while time.time() < deadline: + if process.poll() is not None: + raise RuntimeError( + f"gRPC encoder server exited with code {process.returncode}" + ) + try: + response = stub.Check( + health_pb2.HealthCheckRequest(service=""), timeout=2 + ) + if response.status == health_pb2.HealthCheckResponse.SERVING: + return + except grpc.RpcError: + pass + time.sleep(1) + finally: + channel.close() + + raise RuntimeError( + f"gRPC encoder server not ready at {host}:{port} within {timeout}s" + ) + + @classmethod + def tearDownClass(cls): + os.environ.pop("SGLANG_ENCODER_MM_RECEIVER_MODE", None) + os.environ.pop("OPENAI_API_KEY", None) + os.environ.pop("OPENAI_API_BASE", None) + for process in [ + cls.process_lb, + cls.process_decode, + cls.process_prefill, + cls.process_encode, + ]: + if process: + try: + kill_process_tree(process.pid) + except Exception as e: + print(f"Error killing process: {e}") + + +@unittest.skipIf(is_in_ci(), "Skipping in CI to reduce multi-GPU runtime") +class TestEPDDisaggregationGrpcEncoderOnly(PDDisaggregationServerBase): + """Test gRPC encoder server integration with zmq_to_scheduler transfers.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + os.environ["SGLANG_ENCODER_MM_RECEIVER_MODE"] = "grpc" + cls.model = DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST + cls.encode_port = f"{int(cls.lb_port) + 302}" + + print(f"Setting up gRPC EPD encoder: encode={cls.encode_port}") + + cls.start_encode() + cls.wait_grpc_ready(cls.base_host, cls.encode_port, cls.process_encode) + + @classmethod + def start_encode(cls): + encode_command = [ + "python3", + "-m", + "sglang.launch_server", + "--model-path", + cls.model, + "--host", + cls.base_host, + "--port", + cls.encode_port, + "--trust-remote-code", + "--encoder-only", + "--grpc-mode", + "--encoder-transfer-backend", + "zmq_to_scheduler", + "--tp", + "1", + "--base-gpu-id", + "0", + "--enable-prefix-mm-cache", + ] + cls.process_encode = subprocess.Popen(encode_command) + + @staticmethod + def wait_grpc_ready(host, port, process, timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH): + deadline = time.time() + timeout + channel = grpc.insecure_channel(f"{host}:{port}") + stub = health_pb2_grpc.HealthStub(channel) + try: + while time.time() < deadline: + if process.poll() is not None: + raise RuntimeError( + f"gRPC encoder server exited with code {process.returncode}" + ) + try: + response = stub.Check( + health_pb2.HealthCheckRequest(service=""), timeout=2 + ) + if response.status == health_pb2.HealthCheckResponse.SERVING: + return + except grpc.RpcError: + pass + time.sleep(1) + finally: + channel.close() + + raise RuntimeError( + f"gRPC encoder server not ready at {host}:{port} within {timeout}s" + ) + + @classmethod + def tearDownClass(cls): + os.environ.pop("SGLANG_ENCODER_MM_RECEIVER_MODE", None) + if cls.process_encode: + try: + kill_process_tree(cls.process_encode.pid) + except Exception as e: + print(f"Error killing process: {e}") + super().tearDownClass() + + def test_grpc_encoder_zmq_to_scheduler(self): + from smg_grpc_proto import sglang_encoder_pb2, sglang_encoder_pb2_grpc + + context = zmq.Context() + recv_port, recv_socket = get_zmq_socket_on_host( + context, zmq.PULL, host=self.base_host + ) + channel = grpc.insecure_channel(f"{self.base_host}:{self.encode_port}") + stub = sglang_encoder_pb2_grpc.SglangEncoderStub(channel) + req_id = f"grpc-epd-{int(time.time() * 1000)}" + image_path = os.path.abspath("examples/assets/example_image.png") + + try: + stub.SchedulerReceiveUrl( + sglang_encoder_pb2.SchedulerReceiveUrlRequest( + req_id=req_id, + receive_url=f"{self.base_host}:{recv_port}", + receive_count=1, + ), + timeout=60, + ) + stub.Encode( + sglang_encoder_pb2.EncodeRequest( + mm_items=[image_path], + req_id=req_id, + num_parts=1, + part_idx=0, + ), + timeout=300, + ) + + poller = zmq.Poller() + poller.register(recv_socket, zmq.POLLIN) + socks = dict(poller.poll(60000)) + self.assertIn( + recv_socket, + socks, + "No embedding payload received from gRPC encoder server", + ) + parts = recv_socket.recv_multipart() + self.assertTrue(parts, "Empty embedding payload from gRPC encoder server") + finally: + recv_socket.close() + context.term() + channel.close() + + +@unittest.skipIf( + is_in_ci(), + "TestEPDDisaggregationMooncake test requires RDMA hardware, skipping in CI", +) +class TestEPDDisaggregationMooncake(MMMUMixin, PDDisaggregationServerBase): + """Test EPD disaggregation with mooncake GPU→GPU transfer. + + Validates the async VIT forward + GPU buffer pre-allocation + + GPU-to-GPU mooncake transfer pipeline using MMMU eval (multi-image). + """ + + # Qwen2.5-VL-3B-Instruct scores ~0.40 on the 50-sample MMMU subset. + accuracy = 0.40 + mmmu_args = ["--limit", "50"] + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.model = DEFAULT_SMALL_VLM_MODEL_NAME_FOR_TEST + cls.base_url = cls.lb_url # MMMUMixin reads this for OPENAI_API_BASE + cls.encode_port = f"{int(cls.lb_port) + 306}" + cls.encode_url = f"http://{cls.base_host}:{cls.encode_port}" + + print( + f"Setting up EPD Mooncake RDMA: encode={cls.encode_port}, " + f"prefill={cls.prefill_port}, decode={cls.decode_port}" + ) + + # Start servers in order: encode -> prefill/decode + cls.start_encode() + prefill_thread = threading.Thread(target=cls.start_prefill) + decode_thread = threading.Thread(target=cls.start_decode) + prefill_thread.start() + decode_thread.start() + prefill_thread.join() + decode_thread.join() + + # Wait for all servers to be ready + cls.wait_server_ready(cls.encode_url + "/health", process=cls.process_encode) + cls.wait_server_ready(cls.prefill_url + "/health", process=cls.process_prefill) + cls.wait_server_ready(cls.decode_url + "/health", process=cls.process_decode) + + cls.launch_lb() + + @classmethod + def start_encode(cls): + """Start encode server with mooncake transfer backend""" + encode_args = [ + "--trust-remote-code", + "--encoder-only", + "--encoder-transfer-backend", + "mooncake", + "--tp", + "1", + "--port", + cls.encode_port, + "--enable-prefix-mm-cache", + ] + cls.process_encode = popen_launch_server( + cls.model, + base_url=cls.encode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=encode_args, + ) + + @classmethod + def start_prefill(cls): + """Start prefill server with mooncake transfer backend""" + prefill_args = [ + "--trust-remote-code", + "--language-only", + "--encoder-urls", + cls.encode_url, + "--encoder-transfer-backend", + "mooncake", + "--disaggregation-mode", + "prefill", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "1", + "--port", + cls.prefill_port, + ] + prefill_args += cls.transfer_backend + cls.rdma_devices + cls.process_prefill = popen_launch_server( + cls.model, + base_url=cls.prefill_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=prefill_args, + ) + + @classmethod + def start_decode(cls): + """Start decode server""" + decode_args = [ + "--trust-remote-code", + "--disaggregation-mode", + "decode", + "--disaggregation-bootstrap-port", + cls.bootstrap_port, + "--tp", + "1", + "--base-gpu-id", + "2", + "--port", + cls.decode_port, + ] + decode_args += cls.transfer_backend + cls.rdma_devices + cls.process_decode = popen_launch_server( + cls.model, + base_url=cls.decode_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=decode_args, + ) + + @classmethod + def tearDownClass(cls): + """Clean up all processes""" + for process in [ + cls.process_lb, + cls.process_decode, + cls.process_prefill, + cls.process_encode, + ]: + if process: + try: + kill_process_tree(process.pid) + except Exception as e: + print(f"Error killing process: {e}") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/disaggregation/test_specv2_kvcache_offloading.py b/asian_ai/performance/SGLang/test/registered/disaggregation/test_specv2_kvcache_offloading.py new file mode 100644 index 0000000000000000000000000000000000000000..581004bbd0ce3881e33191c27c241379b4754c59 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/disaggregation/test_specv2_kvcache_offloading.py @@ -0,0 +1,417 @@ +""" +Unit tests for _release_finished_req in DecodeKVCacheOffloadManager. + +Verifies that over-allocated KV cache slots (from speculative decoding v2) +are correctly freed when a request finishes, preventing GPU memory leaks. + +Requires: torch, sglang (run in an environment with sglang installed) +""" + +import unittest +from unittest.mock import MagicMock + +import torch + +from sglang.srt.disaggregation.decode_kvcache_offload_manager import ( + DecodeKVCacheOffloadManager, +) +from sglang.srt.disaggregation.kv_events import OffloadedState +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=8, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=8, suite="stage-b-test-1-gpu-small-amd") + + +def _make_mock_req( + req_pool_idx: int, + kv_committed_len: int, + kv_allocated_len: int, + prefix_indices_len: int = 0, + rid: int = 0, +): + """Create a mock Req with the KV cache state needed for testing.""" + req = MagicMock() + req.rid = rid + req.req_pool_idx = req_pool_idx + req.kv_committed_len = kv_committed_len + req.kv_allocated_len = kv_allocated_len + req.kv_committed_freed = False + req.kv_overallocated_freed = False + req.prefix_indices = list(range(prefix_indices_len)) + + def pop_committed(): + assert not req.kv_committed_freed + req.kv_committed_freed = True + return req.kv_committed_len + + def pop_overallocated(): + assert not req.kv_overallocated_freed + req.kv_overallocated_freed = True + return req.kv_committed_len, req.kv_allocated_len + + req.pop_committed_kv_cache = pop_committed + req.pop_overallocated_kv_cache = pop_overallocated + return req + + +def _make_manager(pool_size: int, page_size: int = 1): + """Create a DecodeKVCacheOffloadManager with mock pools for testing.""" + # Build a real req_to_token tensor so indexing works + req_to_token = torch.arange(pool_size, dtype=torch.int64).unsqueeze(0) + + req_to_token_pool = MagicMock() + req_to_token_pool.req_to_token = req_to_token + + freed_indices = [] + + allocator = MagicMock() + allocator.free = MagicMock( + side_effect=lambda idx: freed_indices.append(idx.clone()) + ) + + tree_cache = MagicMock() + tree_cache.protected_size_ = 0 + + # Bypass __init__ entirely and set attributes directly + manager = object.__new__(DecodeKVCacheOffloadManager) + manager.req_to_token_pool = req_to_token_pool + manager.token_to_kv_pool_allocator = allocator + manager.page_size = page_size + manager.tree_cache = tree_cache + manager.offloaded_state = {} + manager.ongoing_offload = {} + manager.ongoing_backup = {} + manager.offload_inflight = {} + + return manager, freed_indices + + +class _FinishedEvent: + def synchronize(self): + pass + + +class TestReleaseFinishedReq(unittest.TestCase): + """Tests for _release_finished_req overallocation cleanup.""" + + def test_no_overallocation(self): + """Without spec v2, kv_committed == kv_allocated; no extra free.""" + manager, freed = _make_manager(pool_size=32) + req = _make_mock_req( + req_pool_idx=0, + kv_committed_len=20, + kv_allocated_len=20, # no overallocation + ) + prefill_offloaded_len = 8 + + manager._release_finished_req(req, prefill_offloaded_len) + + # Only one free call: the committed range [8:20] + self.assertEqual(len(freed), 1) + expected = torch.arange(8, 20, dtype=torch.int64) + self.assertTrue(torch.equal(freed[0], expected)) + manager.req_to_token_pool.free.assert_called_once_with(req) + + def test_with_overallocation(self): + """With spec v2, overallocated slots [committed:allocated] must be freed.""" + manager, freed = _make_manager(pool_size=32) + req = _make_mock_req( + req_pool_idx=0, + kv_committed_len=20, + kv_allocated_len=28, # 8 over-allocated slots + ) + prefill_offloaded_len = 8 + + manager._release_finished_req(req, prefill_offloaded_len) + + # Two free calls: committed [8:20] and overallocated [20:28] + self.assertEqual(len(freed), 2) + expected_committed = torch.arange(8, 20, dtype=torch.int64) + expected_overalloc = torch.arange(20, 28, dtype=torch.int64) + self.assertTrue(torch.equal(freed[0], expected_committed)) + self.assertTrue(torch.equal(freed[1], expected_overalloc)) + manager.req_to_token_pool.free.assert_called_once_with(req) + + def test_overallocation_with_page_alignment(self): + """With page_size > 1, start of overallocated range is ceil-aligned.""" + page_size = 4 + manager, freed = _make_manager(pool_size=32, page_size=page_size) + req = _make_mock_req( + req_pool_idx=0, + kv_committed_len=10, # not page-aligned + kv_allocated_len=28, + ) + prefill_offloaded_len = 4 + + manager._release_finished_req(req, prefill_offloaded_len) + + # Committed range [4:10] + # Overallocated: start_p = ceil_align(10, 4) = 12, end_p = 28 => [12:28] + self.assertEqual(len(freed), 2) + expected_committed = torch.arange(4, 10, dtype=torch.int64) + expected_overalloc = torch.arange(12, 28, dtype=torch.int64) + self.assertTrue(torch.equal(freed[0], expected_committed)) + self.assertTrue(torch.equal(freed[1], expected_overalloc)) + + def test_overallocation_page_aligned_noop(self): + """When ceil_align(committed, page_size) >= allocated, no overalloc free.""" + page_size = 4 + manager, freed = _make_manager(pool_size=32, page_size=page_size) + req = _make_mock_req( + req_pool_idx=0, + kv_committed_len=10, # ceil_align(10, 4) = 12 + kv_allocated_len=12, # same as aligned start + ) + prefill_offloaded_len = 4 + + manager._release_finished_req(req, prefill_offloaded_len) + + # Only committed [4:10], no overalloc because start_p == end_p + self.assertEqual(len(freed), 1) + expected_committed = torch.arange(4, 10, dtype=torch.int64) + self.assertTrue(torch.equal(freed[0], expected_committed)) + + def test_prefix_indices_decremented(self): + """protected_size_ is decremented by len(req.prefix_indices).""" + manager, _ = _make_manager(pool_size=32) + manager.tree_cache.protected_size_ = 10 + req = _make_mock_req( + req_pool_idx=0, + kv_committed_len=20, + kv_allocated_len=20, + prefix_indices_len=5, + ) + + manager._release_finished_req(req, start_offset=0) + + self.assertEqual(manager.tree_cache.protected_size_, 5) + + def test_release_finished_req_frees_prefill_when_state_present(self): + """ + When offloaded_state[rid].prefill_len > 0, _release_finished_req must + free the prefill-aligned slots in addition to the committed range. + + This is the consolidated free path that replaces the eager free that + previously happened in offload_kv_cache (which raced with concurrent + admission and produced cross-pollinated KV reads). + """ + manager, freed = _make_manager(pool_size=32) + rid = "req-prefill-present" + req = _make_mock_req( + req_pool_idx=0, + kv_committed_len=20, + kv_allocated_len=20, + rid=rid, + ) + manager.offloaded_state[rid] = OffloadedState( + prefill_len=8, inc_len=0, last_hash=None + ) + + manager._release_finished_req(req, start_offset=8) + + # Two frees in order: prefill [0:8] then committed [8:20]. + self.assertEqual(len(freed), 2) + expected_prefill = torch.arange(0, 8, dtype=torch.int64) + expected_committed = torch.arange(8, 20, dtype=torch.int64) + self.assertTrue(torch.equal(freed[0], expected_prefill)) + self.assertTrue(torch.equal(freed[1], expected_committed)) + # State entry is removed at the end of _release_finished_req. + self.assertNotIn(rid, manager.offloaded_state) + + def test_release_finished_req_skips_prefill_free_when_prefill_len_zero(self): + """ + When state exists but prefill_len == 0 (request shorter than page_size, + so no prefill chunk was ever offloaded), no prefill-aligned free is + emitted. + """ + manager, freed = _make_manager(pool_size=32) + rid = "req-prefill-zero" + req = _make_mock_req( + req_pool_idx=0, + kv_committed_len=10, + kv_allocated_len=10, + rid=rid, + ) + manager.offloaded_state[rid] = OffloadedState( + prefill_len=0, inc_len=0, last_hash=None + ) + + manager._release_finished_req(req, start_offset=0) + + # Only the committed range [0:10] is freed. + self.assertEqual(len(freed), 1) + expected_committed = torch.arange(0, 10, dtype=torch.int64) + self.assertTrue(torch.equal(freed[0], expected_committed)) + + def test_finalize_release_creates_state_so_prefill_is_freed(self): + """ + finalize_release_on_finish handles the case where no incremental + offload ever ran (offloaded_state is empty). It must materialize an + OffloadedState with the correct prefill_len so that the consolidated + free site in _release_finished_req can locate and free those slots. + """ + page_size = 4 + manager, freed = _make_manager(pool_size=32, page_size=page_size) + rid = "req-finalize-no-state" + req = _make_mock_req( + req_pool_idx=0, + kv_committed_len=13, + kv_allocated_len=13, + rid=rid, + ) + # 12 input tokens => prefill_len = 12 // 4 * 4 = 12 + req.origin_input_ids = list(range(12)) + + manager.finalize_release_on_finish(req) + + # finalize creates state, then _release_finished_req frees: + # prefill [0:12] then committed [12:13]. + self.assertEqual(len(freed), 2) + expected_prefill = torch.arange(0, 12, dtype=torch.int64) + expected_committed = torch.arange(12, 13, dtype=torch.int64) + self.assertTrue(torch.equal(freed[0], expected_prefill)) + self.assertTrue(torch.equal(freed[1], expected_committed)) + # State is deleted by _release_finished_req on the way out. + self.assertNotIn(rid, manager.offloaded_state) + + def test_unfinished_offload_ack_does_not_free_incremental_slots(self): + manager, freed = _make_manager(pool_size=32) + req = _make_mock_req( + req_pool_idx=0, kv_committed_len=20, kv_allocated_len=20, rid=1 + ) + req.finished.return_value = False + manager.offloaded_state[req.rid] = OffloadedState( + prefill_len=4, inc_len=4, last_hash=None + ) + manager.offload_inflight[req.rid] = 1 + manager.ongoing_offload[7] = ( + req, + torch.arange(4, 8, dtype=torch.int64), + [10, 11, 12, 13], + 0.0, + 4, + 8, + ) + manager.cache_controller = MagicMock() + manager.cache_controller.ack_write_queue = [(None, _FinishedEvent(), [7])] + manager._trigger_backup = MagicMock(return_value="last_hash") + + manager._check_offload_progress(1) + + self.assertEqual(freed, []) + manager.req_to_token_pool.free.assert_not_called() + self.assertNotIn(req.rid, manager.offload_inflight) + + def test_offload_kv_cache_tracks_inflight_write_until_ack(self): + manager, freed = _make_manager(pool_size=32, page_size=4) + manager.cache_controller = MagicMock() + manager.cache_controller.get_hash_str = MagicMock(return_value="prefill_hash") + manager.cache_controller.write = MagicMock( + return_value=torch.arange(4, 8, dtype=torch.int64) + ) + manager.decode_host_mem_pool = MagicMock() + manager.request_counter = 0 + manager.offload_stride = 4 + + req = _make_mock_req( + req_pool_idx=0, kv_committed_len=20, kv_allocated_len=20, rid=5 + ) + req.origin_input_ids = [0, 1, 2, 3] + req.output_ids = [4, 5, 6, 7, 8] + req.finished.return_value = False + + did_offload = manager.offload_kv_cache(req) + + self.assertTrue(did_offload) + self.assertEqual(manager.offload_inflight[req.rid], 1) + self.assertEqual(manager.offloaded_state[req.rid].inc_len, 4) + manager.cache_controller.write.assert_called_once() + + manager.cache_controller.ack_write_queue = [(None, _FinishedEvent(), [1])] + manager._trigger_backup = MagicMock(return_value="last_hash") + + manager._check_offload_progress(1) + + self.assertEqual(freed, []) + self.assertNotIn(req.rid, manager.offload_inflight) + + def test_finalize_release_defers_while_offload_is_in_flight(self): + manager, freed = _make_manager(pool_size=32) + req = _make_mock_req( + req_pool_idx=0, kv_committed_len=20, kv_allocated_len=20, rid=2 + ) + manager.offloaded_state[req.rid] = OffloadedState( + prefill_len=4, inc_len=8, last_hash=None + ) + manager.offload_inflight[req.rid] = 1 + + manager.finalize_release_on_finish(req) + + self.assertEqual(freed, []) + manager.req_to_token_pool.free.assert_not_called() + self.assertIn(req.rid, manager.offloaded_state) + + def test_finished_offload_ack_waits_for_other_inflight_writes(self): + manager, freed = _make_manager(pool_size=32) + req = _make_mock_req( + req_pool_idx=0, kv_committed_len=20, kv_allocated_len=20, rid=3 + ) + req.finished.return_value = True + manager.offloaded_state[req.rid] = OffloadedState( + prefill_len=4, inc_len=8, last_hash=None + ) + manager.offload_inflight[req.rid] = 2 + manager.ongoing_offload[8] = ( + req, + torch.arange(4, 8, dtype=torch.int64), + [10, 11, 12, 13], + 0.0, + 4, + 8, + ) + manager.cache_controller = MagicMock() + manager.cache_controller.ack_write_queue = [(None, _FinishedEvent(), [8])] + manager._trigger_backup = MagicMock(return_value="last_hash") + + manager._check_offload_progress(1) + + self.assertEqual(freed, []) + manager.req_to_token_pool.free.assert_not_called() + self.assertEqual(manager.offload_inflight[req.rid], 1) + + def test_finished_request_releases_all_committed_slots_after_last_offload_ack( + self, + ): + manager, freed = _make_manager(pool_size=32) + req = _make_mock_req( + req_pool_idx=0, kv_committed_len=20, kv_allocated_len=20, rid=4 + ) + req.finished.return_value = True + manager.offloaded_state[req.rid] = OffloadedState( + prefill_len=4, inc_len=8, last_hash=None + ) + manager.offload_inflight[req.rid] = 1 + manager.ongoing_offload[9] = ( + req, + torch.arange(8, 12, dtype=torch.int64), + [14, 15, 16, 17], + 0.0, + 8, + 12, + ) + manager.cache_controller = MagicMock() + manager.cache_controller.ack_write_queue = [(None, _FinishedEvent(), [9])] + manager._trigger_backup = MagicMock(return_value="last_hash") + + manager._check_offload_progress(1) + + self.assertEqual(len(freed), 2) + self.assertTrue(torch.equal(freed[0], torch.arange(0, 4, dtype=torch.int64))) + self.assertTrue(torch.equal(freed[1], torch.arange(4, 20, dtype=torch.int64))) + manager.req_to_token_pool.free.assert_called_once_with(req) + self.assertNotIn(req.rid, manager.offloaded_state) + self.assertNotIn(req.rid, manager.offload_inflight) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/dllm/test_llada2_mini.py b/asian_ai/performance/SGLang/test/registered/dllm/test_llada2_mini.py new file mode 100644 index 0000000000000000000000000000000000000000..d729c7d77497912ed4ea8bc7dc332ae061d99144 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/dllm/test_llada2_mini.py @@ -0,0 +1,96 @@ +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=139, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=330, suite="stage-b-test-1-gpu-small-amd") + +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.run_eval import run_eval +from sglang.test.send_one import BenchArgs, send_one_prompt +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_amd_ci, + is_in_ci, + popen_launch_server, + write_github_step_summary, +) + + +class TestLLaDA2Mini(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "inclusionAI/LLaDA2.0-mini" + cls.base_url = DEFAULT_URL_FOR_TEST + + other_args = [ + "--trust-remote-code", + "--tp-size", + "1", + "--mem-fraction-static", + "0.9", + "--max-running-requests", + "4", + "--attention-backend", + "flashinfer", + "--dllm-algorithm", + "LowConfidence", + "--cuda-graph-bs", + "1", + "2", + "3", + "4", + ] + + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + + self.assertGreater(metrics["score"], 0.88) + if is_in_amd_ci(): + self.assertGreater(metrics["output_throughput"], 80) + else: + self.assertGreater(metrics["output_throughput"], 350) + + def test_bs_1_speed(self): + args = BenchArgs(port=int(self.base_url.split(":")[-1]), max_new_tokens=2048) + acc_length, speed = send_one_prompt(args) + + print(f"{speed=:.2f}") + + if is_in_ci(): + write_github_step_summary( + f"### test_bs_1_speed (llada2-mini) with tp1\n" + f"{speed=:.2f} token/s\n" + ) + if is_in_amd_ci(): + self.assertGreater(speed, 10) + else: + self.assertGreater(speed, 250) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/dllm/test_llada2_mini_amd.py b/asian_ai/performance/SGLang/test/registered/dllm/test_llada2_mini_amd.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea1145e2d339a68d5f92c0ee10dbf656ff657f5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/dllm/test_llada2_mini_amd.py @@ -0,0 +1,88 @@ +""" +Test LLaDA2 (Diffusion Language Model) on AMD GPUs. + +This test verifies that DLLM works on AMD with triton attention backend. +""" + +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci +from sglang.test.run_eval import run_eval +from sglang.test.send_one import BenchArgs, send_one_prompt +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, + write_github_step_summary, +) + +register_amd_ci(est_time=1000, suite="stage-b-test-1-gpu-small-amd") + + +class TestLLaDA2MiniAMD(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "inclusionAI/LLaDA2.0-mini" + cls.base_url = DEFAULT_URL_FOR_TEST + + other_args = [ + "--trust-remote-code", + "--mem-fraction-static", + "0.9", + "--max-running-requests", + "1", + "--attention-backend", + "triton", # Use triton for AMD instead of flashinfer + "--dllm-algorithm", + "LowConfidence", + ] + + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + """Test GSM8K accuracy with DLLM on AMD.""" + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + + # Relaxed thresholds for AMD - may need adjustment + self.assertGreater(metrics["score"], 0.80) + self.assertGreater(metrics["output_throughput"], 50) + + def test_bs_1_speed(self): + """Test single batch inference speed.""" + args = BenchArgs(port=int(self.base_url.split(":")[-1]), max_new_tokens=2048) + acc_length, speed = send_one_prompt(args) + + print(f"{speed=:.2f}") + + if is_in_ci(): + write_github_step_summary( + f"### test_bs_1_speed (llada2-mini AMD) with tp1\n" + f"{speed=:.2f} token/s\n" + ) + # Relaxed threshold for AMD + self.assertGreater(speed, 10) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/dp_attn/test_dp_attention.py b/asian_ai/performance/SGLang/test/registered/dp_attn/test_dp_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..b26acff7dd6e4e4ea4255dad8afb53e60e6ded45 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/dp_attn/test_dp_attention.py @@ -0,0 +1,228 @@ +import unittest + +import requests + +from sglang.lang.chat_template import get_chat_template_by_model_path +from sglang.srt.environ import envs +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.ebnf_constrained_kit import EBNFConstrainedMixin +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.json_constrained_kit import JSONConstrainedMixin +from sglang.test.kits.radix_cache_server_kit import run_radix_attention_test +from sglang.test.kits.regex_constrained_kit import RegexConstrainedMixin +from sglang.test.test_utils import ( + DEFAULT_IMAGE_URL, + DEFAULT_MLA_MODEL_NAME_FOR_TEST, + DEFAULT_MODEL_NAME_FOR_TEST_MLA, + DEFAULT_TARGET_MODEL_EAGLE_DP_ATTN, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_amd_ci, + popen_launch_server, +) + +register_cuda_ci(est_time=420, stage="base-b", runner_config="2-gpu-large") +register_amd_ci(est_time=500, suite="stage-b-test-2-gpu-large-amd") + + +@unittest.skipIf(is_in_amd_ci(), "This test case cannot run on ROCm.") +class TestDPAttentionDP2TP2( + CustomTestCase, + GSM8KMixin, + JSONConstrainedMixin, + EBNFConstrainedMixin, + RegexConstrainedMixin, +): + gsm8k_accuracy_thres = 0.6 + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls._env_override = envs.SGLANG_DISABLE_CONSECUTIVE_PREFILL_OVERLAP.override( + True + ) + cls._env_override.__enter__() + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "2", + "--enable-dp-attention", + "--dp", + "2", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + cls._env_override.__exit__(None, None, None) + + +class TestDPAttentionGatherv( + CustomTestCase, + GSM8KMixin, +): + """Exercise the variable-length all_gatherv + reduce_scatterv DP-MoE path + (SGLANG_DP_USE_GATHERV=1). The path only activates for the + attn_tp_size == 1, tp_size == dp_size layout, which tp2 + dp2 satisfies. + Without this test the gatherv/reduce_scatterv code is never exercised by CI + (it is gated behind the env var, default off). gsm8k must stay correct since + the change is a pure communication reorg, not a numerics change.""" + + gsm8k_accuracy_thres = 0.6 + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_TARGET_MODEL_EAGLE_DP_ATTN + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env={"SGLANG_DP_USE_GATHERV": "1"}, + other_args=[ + "--trust-remote-code", + "--tp", + "2", + "--enable-dp-attention", + "--dp", + "2", + "--chunked-prefill-size", + "256", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + +@unittest.skipIf(is_in_amd_ci(), "This test case cannot run on ROCm.") +class TestDPAttentionMixedChunk( + CustomTestCase, + GSM8KMixin, +): + gsm8k_accuracy_thres = 0.6 + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "2", + "--enable-dp-attention", + "--dp", + "2", + "--enable-mixed-chunk", + "--chunked-prefill-size", + "256", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + +@unittest.skipIf(is_in_amd_ci(), "This test case cannot run on ROCm.") +class TestDPRetract( + CustomTestCase, + JSONConstrainedMixin, + EBNFConstrainedMixin, + RegexConstrainedMixin, +): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "2", + "--enable-dp-attention", + "--dp", + "2", + "--max-total-tokens", + "4500", + "--max-running-requests", + "128", + "--chunked-prefill-size", + "256", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_radix_attention(self): + with envs.SGLANG_TEST_RETRACT.override(True): + run_radix_attention_test(self.base_url) + self.assertIsNone(self.process.poll()) + + +@unittest.skipIf(is_in_amd_ci(), "This test case cannot run on ROCm.") +class TestDPAttentionDP2TP2VLM(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "moonshotai/Kimi-VL-A3B-Instruct" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.image_url = DEFAULT_IMAGE_URL + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "2", + "--enable-dp-attention", + "--dp", + "2", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_vlm_generate(self): + chat_template = get_chat_template_by_model_path(self.model) + prompt = f"{chat_template.image_token}What is in this image?" + response = requests.post( + self.base_url + "/generate", + json={ + "text": prompt, + "image_data": [self.image_url], + "sampling_params": { + "temperature": 0, + "max_new_tokens": 16, + }, + }, + ) + response.raise_for_status() + response_json = response.json() + print(response_json) + self.assertIn("output_ids", response_json) + self.assertGreater(len(response_json["output_ids"]), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/dp_engine/test_data_parallelism.py b/asian_ai/performance/SGLang/test/registered/dp_engine/test_data_parallelism.py new file mode 100644 index 0000000000000000000000000000000000000000..1c601b9d29ff161817398f80be074678348ec331 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/dp_engine/test_data_parallelism.py @@ -0,0 +1,71 @@ +import time +import unittest + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=91, stage="base-b", runner_config="2-gpu-large") +register_amd_ci(est_time=73, suite="stage-b-test-2-gpu-large-amd") + + +class TestDataParallelism(CustomTestCase, GSM8KMixin): + gsm8k_accuracy_thres = 0.7 + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=["--dp", 2], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_update_weight(self): + response = requests.post( + self.base_url + "/update_weights_from_disk", + json={"model_path": DEFAULT_MODEL_NAME_FOR_TEST}, + ) + + # check if the response is 200 + assert response.status_code == 200 + + # pause a few seconds then send again + time.sleep(1) + + response = requests.post( + self.base_url + "/update_weights_from_disk", + json={"model_path": DEFAULT_MODEL_NAME_FOR_TEST}, + ) + + # check if the response is 200 + assert response.status_code == 200 + + def test_get_memory_pool_size(self): + # use `server_info` instead since `get_memory_pool_size` is merged into `server_info` + response = requests.get(self.base_url + "/server_info") + assert response.status_code == 200 + + time.sleep(1) + + response = requests.get(self.base_url + "/server_info") + assert response.status_code == 200 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ep/test_deepep_large.py b/asian_ai/performance/SGLang/test/registered/ep/test_deepep_large.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2ff36ed2dd367595f71cd2ade4ba1db1aeb864 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ep/test_deepep_large.py @@ -0,0 +1,219 @@ +import unittest +from types import SimpleNamespace + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.send_one import BenchArgs, send_one_prompt +from sglang.test.test_utils import ( + DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=528, stage="extra-b", runner_config="deepep-8-gpu-h200") + +DEEPSEEK_V32_MODEL_PATH = "deepseek-ai/DeepSeek-V3.2" + + +@unittest.skip("Skip for saving ci time") +class TestDeepseek(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--moe-runner-backend", + "deep_gemm", + "--enable-two-batch-overlap", + "--ep-num-redundant-experts", + "32", + "--ep-dispatch-algorithm", + "dynamic", + "--eplb-algorithm", + "deepseek", + "--cuda-graph-bs", + "256", + "--max-running-requests", + "2048", + "--disable-radix-cache", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=1200, + num_threads=1200, + ) + metrics = run_eval(args) + print(f"Eval accuracy of GSM8K: {metrics=}") + + self.assertGreater(metrics["score"], 0.92) + + +class TestDeepseekMTP(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--disable-overlap-schedule", + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--moe-runner-backend", + "deep_gemm", + "--enable-two-batch-overlap", + "--ep-num-redundant-experts", + "32", + "--ep-dispatch-algorithm", + "dynamic", + "--eplb-algorithm", + "deepseek", + "--cuda-graph-bs", + "64", # TODO: increase it to 128 when TBO is supported in draft_extend + "--max-running-requests", + "512", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", + "--disable-radix-cache", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=1200, + num_threads=1200, + ) + metrics = run_eval(args) + print(f"Eval accuracy of GSM8K: {metrics=}") + + self.assertGreater(metrics["score"], 0.92) + + server_info = requests.get(self.base_url + "/server_info") + avg_spec_accept_length = server_info.json()["internal_states"][0][ + "avg_spec_accept_length" + ] + print( + f"###test_gsm8k:\n" + f"accuracy={metrics['score']=:.3f}\n" + f"{avg_spec_accept_length=:.3f}\n" + ) + self.assertGreater(avg_spec_accept_length, 1.85) + + +class TestDeepseekV32TBO(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEEPSEEK_V32_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--trust-remote-code", + "--tp", + "8", + "--dp", + "8", + "--enable-dp-attention", + "--enable-two-batch-overlap", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "256", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_a_gsm8k( + self, + ): # Append an "a" to make this test run first (alphabetically) to warm up the server + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=1200, + num_threads=1200, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.92) + + def test_bs_1_speed(self): + args = BenchArgs(port=int(self.base_url.split(":")[-1]), max_new_tokens=2048) + acc_length, speed = send_one_prompt(args) + + print(f"{speed=:.2f}") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ep/test_deepep_small.py b/asian_ai/performance/SGLang/test/registered/ep/test_deepep_small.py new file mode 100644 index 0000000000000000000000000000000000000000..76912aec93fc91fac58b661198fd742a505d814c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ep/test_deepep_small.py @@ -0,0 +1,578 @@ +import os +import unittest +from types import SimpleNamespace + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST_MLA, + DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=478, stage="base-c", runner_config="deepep-4-gpu-h100") + + +class TestPureDP(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--enable-dp-attention", + "--dp", + "4", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "512", + "--mem-fraction-static", + "0.5", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +class TestHybridDPTP(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--enable-dp-attention", + "--dp", + "2", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "256", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +class TestTP(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +@unittest.skip("covered in test_deepep_large.py") +class TestNoGatherdBuffer(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "512", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +class TestTBO(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--moe-a2a-backend", + "deepep", + "--enable-two-batch-overlap", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "512", + ], + env={ + **os.environ, + "SGLANG_TBO_DEBUG": "1", + }, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +class TestTBOWithTPAttn(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--moe-a2a-backend", + "deepep", + "--enable-two-batch-overlap", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "512", + "--mem-fraction-static", # temp fix as DeepEP buffer is too large. + "0.7", + ], + env={ + **os.environ, + "SGLANG_TBO_DEBUG": "1", + }, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +# There exists bug when using MTP + TBO + attn_tp_size > 1, currently skip that case. +# @unittest.skip("covered in TestMTPWithTPAttnAndTBO") +class TestTBOWithTPAttnAndDenseDP(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--moe-dense-tp-size", + "1", + "--moe-a2a-backend", + "deepep", + "--enable-two-batch-overlap", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "512", + "--mem-fraction-static", # temp fix as DeepEP buffer is too large. + "0.7", + ], + env={ + **os.environ, + "SGLANG_TBO_DEBUG": "1", + }, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +@unittest.skip("covered in TestMTPWithTBO") +class TestMTP(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--enable-dp-attention", + "--dp", + "2", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN, + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "3", + "--speculative-num-draft-tokens", + "3", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "64", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + server_info = requests.get(self.base_url + "/server_info") + avg_spec_accept_length = server_info.json()["internal_states"][0][ + "avg_spec_accept_length" + ] + print( + f"###test_gsm8k (deepseek-v3 mtp + dp + tbo):\n" + f"accuracy={metrics['score']=:.3f}\n" + f"{avg_spec_accept_length=:.3f}\n" + ) + self.assertGreater(avg_spec_accept_length, 2.1) + + +class TestMTPWithTBO(CustomTestCase): + @classmethod + def setUpClass(cls): + + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "4", + "--enable-dp-attention", + "--dp-size", + "4", + "--enable-two-batch-overlap", + "--moe-a2a-backend", + "deepep", + "--trust-remote-code", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "3", + "--speculative-num-draft-tokens", + "3", + "--speculative-draft-model-path", + DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN, + "--chunked-prefill-size", + "256", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "128", + ], + env={ + **os.environ, + "SGLANG_TBO_DEBUG": "1", + }, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + server_info = requests.get(self.base_url + "/server_info") + avg_spec_accept_length = server_info.json()["internal_states"][0][ + "avg_spec_accept_length" + ] + print( + f"###test_gsm8k (deepseek-v3 mtp + dp + tbo):\n" + f"accuracy={metrics['score']=:.3f}\n" + f"{avg_spec_accept_length=:.3f}\n" + ) + self.assertGreater(avg_spec_accept_length, 2.1) + + +@unittest.skip("skipped due to bug when using MTP & TBO & attn_tp_size > 1") +class TestMTPWithTPAttnAndTBO(CustomTestCase): + @classmethod + def setUpClass(cls): + + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "4", + "--moe-dense-tp-size", + "1", + "--enable-two-batch-overlap", + "--moe-a2a-backend", + "deepep", + "--trust-remote-code", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "3", + "--speculative-num-draft-tokens", + "3", + "--speculative-draft-model-path", + DEFAULT_MODEL_NAME_FOR_TEST_MLA_NEXTN, + "--chunked-prefill-size", + "256", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "128", + "--mem-fraction-static", # temp fix as DeepEP buffer is too large. + "0.7", + ], + env={ + **os.environ, + "SGLANG_TBO_DEBUG": "1", + }, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + server_info = requests.get(self.base_url + "/server_info") + avg_spec_accept_length = server_info.json()["internal_states"][0][ + "avg_spec_accept_length" + ] + print( + f"###test_gsm8k (deepseek-v3 mtp + dp + tbo):\n" + f"accuracy={metrics['score']=:.3f}\n" + f"{avg_spec_accept_length=:.3f}\n" + ) + self.assertGreater(avg_spec_accept_length, 2.1) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ep/test_flashinfer_a2a.py b/asian_ai/performance/SGLang/test/registered/ep/test_flashinfer_a2a.py new file mode 100644 index 0000000000000000000000000000000000000000..549da84f27faacb0f94413e5a7c1e81986455949 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ep/test_flashinfer_a2a.py @@ -0,0 +1,125 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=500, stage="base-c", runner_config="4-gpu-gb300") + +DEEPSEEK_V3_FP4_MODEL = "nvidia/DeepSeek-V3-0324-FP4" +QWEN3_FP8_MODEL = "Qwen/Qwen3-Next-80B-A3B-Instruct-FP8" +SERVER_LAUNCH_TIMEOUT = 1000 + + +class TestFlashinferA2ATrtllmRoutedFP4(CustomTestCase): + """flashinfer A2A + flashinfer_trtllm_routed with modelopt_fp4 (DeepSeek V3).""" + + @classmethod + def setUpClass(cls): + cls.model = DEEPSEEK_V3_FP4_MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--tp", + "4", + "--ep", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "flashinfer", + "--moe-runner-backend", + "flashinfer_trtllm_routed", + "--quantization", + "modelopt_fp4", + "--disable-flashinfer-autotune", + "--model-loader-extra-config", + '{"enable_multithread_load": true}', + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.90) + + +class TestFlashinferA2ATrtllmRoutedFP8(CustomTestCase): + """flashinfer A2A + flashinfer_trtllm_routed with fp8 (Qwen3-Next).""" + + @classmethod + def setUpClass(cls): + cls.model = QWEN3_FP8_MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--tp", + "4", + "--ep", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "flashinfer", + "--moe-runner-backend", + "flashinfer_trtllm_routed", + "--attention-backend", + "triton", + "--mem-fraction-static", + "0.7", + "--mamba-ssm-dtype", + "bfloat16", + "--disable-flashinfer-autotune", + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.93) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ep/test_mooncake_ep_small.py b/asian_ai/performance/SGLang/test/registered/ep/test_mooncake_ep_small.py new file mode 100644 index 0000000000000000000000000000000000000000..561403739321b848908897b771ba33acb3a5963a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ep/test_mooncake_ep_small.py @@ -0,0 +1,126 @@ +import os +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.server_fixtures.disaggregation_fixture import get_rdma_devices_args +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST_MLA, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, +) + +register_cuda_ci(est_time=82, stage="base-c", runner_config="deepep-4-gpu-h100") + +ib_devices = get_rdma_devices_args() + + +class TestTP(CustomTestCase): + extra_args = [] + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--elastic-ep-backend", + "mooncake", + "--mooncake-ib-device", + ib_devices, + "--moe-a2a-backend", + "mooncake", + "--deepep-mode", + "low_latency", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--enable-two-batch-overlap", + "--disable-custom-all-reduce", + "--enable-eplb", + "--ep-num-redundant-experts", + "72", + "--chunked-prefill-size", + "512", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "512", + "--mem-fraction-static", + "0.5", + *cls.extra_args, + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +@unittest.skipIf(is_in_ci(), "Skip since mooncake-ep fault-tolerant test is flaky.") +class TestPureDP(TestTP): + extra_args = [ + "--enable-dp-attention", + "--dp", + "4", + ] + + pkill_process_1 = "sglang::scheduler_DP1_TP1_EP1" + pkill_process_2 = "sglang::scheduler_DP3_TP3_EP3" + + def test_gsm8k_fault_1(self): + """ + Kill one rank and the system should remain operational. + """ + os.system(f"pkill -f {self.pkill_process_1}") + super().test_gsm8k() + + @unittest.skipIf(is_in_ci(), "To reduce the CI execution time.") + def test_gsm8k_fault_2(self): + """ + Kill another rank and the system should remain operational. + """ + os.system(f"pkill -f {self.pkill_process_2}") + super().test_gsm8k() + + +@unittest.skipIf(is_in_ci(), "To reduce the CI execution time.") +class TestHybridDPTP(TestPureDP): + extra_args = [ + "--enable-dp-attention", + "--dp", + "2", + ] + + pkill_process_1 = "sglang::scheduler_DP1_TP2_EP2" + pkill_process_2 = "sglang::scheduler_DP1_TP3_EP3" + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/ep/test_tbo_shared_experts_fusion.py b/asian_ai/performance/SGLang/test/registered/ep/test_tbo_shared_experts_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..1d93ff76d3650b62befeb1cb69506239c06ce031 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/ep/test_tbo_shared_experts_fusion.py @@ -0,0 +1,73 @@ +import os +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=900, stage="extra-b", runner_config="deepep-8-gpu-h200") + +DEEPSEEK_V3_MODEL_PATH = "deepseek-ai/DeepSeek-V3-0324" + + +class TestTBOWithSharedExpertsFusion(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEEPSEEK_V3_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--moe-a2a-backend", + "deepep", + "--enable-two-batch-overlap", + "--enforce-shared-experts-fusion", + "--disable-cuda-graph", + "--max-running-requests", + "512", + ], + env={ + **os.environ, + "SGLANG_TBO_DEBUG": "1", + }, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/eplb/test_lplb_distributed.py b/asian_ai/performance/SGLang/test/registered/eplb/test_lplb_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1f0b355aae3780ef7ece87c34092a3b85c607b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/eplb/test_lplb_distributed.py @@ -0,0 +1,446 @@ +"""Real-CUDA multi-rank distributed test for LPLBSolver. + +Supplements the CPU-only `test_lplb.py` checks: this test spawns 2 +CUDA-bound ranks on a single node via `torch.multiprocessing.spawn` and +exercises the actual code paths the production LP server uses, including +the EP all-reduce and the DP-attention "empty rank" case (rank with zero +tokens for a given forward). + +Critical invariants this test catches that the CPU tests cannot: + 1. The all-reduce inside `LPLBSolver.solve()` actually completes when + one rank has empty `topk_ids` (i.e., the empty-rank deadlock fix is + in effect — without it, the empty rank would skip `solver.solve()` + and hang the collective). + 2. Both ranks receive the **same** counts post-all-reduce and produce + identical outputs. + 3. The output equals the torch-IPM oracle computed from the ORACLE + summed counts (this is the discriminator that tells "all-reduce + happened" apart from "rank silently used local-only counts and + coincidentally produced a finite tensor"). + 4. The fused-only contract holds end-to-end: a fused-kernel failure + must surface as an exception (no silent torch fallback exists). + 5. Post-rebalance reinit produces solvers tied to the new metadata — + outputs change when `phy2log` changes. + +Pattern follows `test/registered/layers/mamba/test_mamba2_mixer.py` — +`torch.multiprocessing.spawn` is required because `torch.distributed` +plays poorly with arbitrary subprocess launchers. +""" + +import pytest +import torch + +from sglang.srt.distributed.device_communicators.custom_all_reduce_utils import ( + update_environment_variables, +) +from sglang.srt.distributed.parallel_state import ( + init_distributed_environment, + initialize_model_parallel, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=120, stage="base-b", runner_config="2-gpu-large") + +NUM_GPUS = 2 +TOPK = 2 + +# Smallest replicated-metadata config that still exercises a non-trivial LP: +# num_gpus = 2 +# num_logical = 4 (3 single-copy + 1 replicated) +# num_phy = 6 (4 + 2 redundant copies of expert 0) +# → NC = 1 + 2 = 3, NV = 2 + 2 + 2 = 6 (well within H20 shmem budget) +NUM_LOGICAL = 4 +NUM_PHY = 6 + + +def _make_metadata(rebalanced: bool = False): + """Build (phy2log, log2phy, num_valid) for the test config. + + When `rebalanced=True`, swap the redundant logical from expert 0 to + expert 1 — same shapes, different mapping, so a stale solver would + produce wrong outputs. + """ + replicated_logical = 1 if rebalanced else 0 + phy2log = torch.tensor( + [0, 1, 2, 3, replicated_logical, replicated_logical], dtype=torch.int64 + ) + log2phy = torch.full((NUM_LOGICAL, 3), -1, dtype=torch.int64) + for i in range(NUM_LOGICAL): + log2phy[i, 0] = i + log2phy[replicated_logical, 1] = 4 + log2phy[replicated_logical, 2] = 5 + num_valid = torch.ones(NUM_LOGICAL, dtype=torch.int64) + num_valid[replicated_logical] = 3 + return phy2log, log2phy, num_valid + + +@pytest.mark.skipif( + not torch.cuda.is_available(), + reason="This test requires CUDA", +) +def test_dispatch_probability_matches_torch_reference(): + """The fused CUDA `dispatch_probability` and the pure-torch reference + must produce identical outputs for the same ``random_vals``. Single-rank, + runs on any CUDA GPU.""" + from sglang.jit_kernel.lplb.cuda_solver import ( + dispatch_probability, + dispatch_probability_torch_reference, + ) + + torch.manual_seed(0) + device = torch.device("cuda:0") + num_logical, max_copies, num_tokens, topk = 8, 3, 64, 4 + + # Random LP-style probabilities (some rows zeroed to exercise the fallback). + log2phy_prob = torch.rand(num_logical, max_copies, device=device) + log2phy_prob[0] = 0 # force fallback row + log2phy_map = torch.full( + (num_logical, max_copies), -1, dtype=torch.int32, device=device + ) + for i in range(num_logical): + log2phy_map[i, 0] = i # primary replica + log2phy_map[i, 1] = num_logical + (i % 4) # one redundant + # leave last slot at -1 to exercise the masked-replica path + + topk_ids = torch.randint( + 0, num_logical, (num_tokens, topk), dtype=torch.int32, device=device + ) + random_vals = torch.rand(num_tokens * topk, device=device, dtype=torch.float32) + + cuda_out = dispatch_probability(topk_ids, log2phy_prob, log2phy_map, random_vals) + torch_out = dispatch_probability_torch_reference( + topk_ids, log2phy_prob, log2phy_map, random_vals + ) + + assert torch.equal(cuda_out, torch_out), ( + f"dispatch_probability disagrees with torch reference: " + f"{(cuda_out != torch_out).sum().item()}/{cuda_out.numel()} mismatches" + ) + + +@pytest.mark.skipif( + not torch.cuda.is_available(), + reason="This test requires CUDA", +) +def test_solve_ipm_matches_torch_reference(): + """The fused CUDA IPM kernel and the pure-torch reference should agree to + a small tolerance on a *real* LPLB LP. They are NOT bit-equivalent — the + kernel factors the KKT system with a hand-written block Cholesky while the + reference uses torch.linalg.solve (LU) — so we compare with allclose and + print the max abs difference (the numerical-difference number the review + asked about). + + The LP is built the way LPLBSolver does (Big-M column + normalized + counts), because an arbitrary random Ax=b never satisfies the solver's + convergence test (the Big-M slack must reach ~0) and both backends would + just return the 0.5 non-convergence sentinel — agreeing trivially without + exercising the solve. Single-rank, any CUDA GPU.""" + from sglang.jit_kernel.lplb.cuda_solver import solve_ipm as cuda_solve_ipm + from sglang.jit_kernel.lplb.torch_solver import solve_ipm_torch_reference + from sglang.srt.eplb.lplb_solver import LPLBSolver + + torch.manual_seed(0) + device = torch.device("cuda:0") + phy2log, log2phy, num_valid = _make_metadata() + solver = LPLBSolver( + phy2log=phy2log.to(device), + log2phy=log2phy.to(device), + num_gpus=NUM_GPUS, + ep_group=None, + logical_to_all_physical_map_num_valid=num_valid.to(device), + ) + + # Realistic counts: the replicated expert (logical 0) carries heavy load + # to distribute across its 3 physical copies; the rest are moderate. This + # gives the barrier method a well-posed instance that converges in 5 iters. + global_counts = torch.tensor( + [120.0, 30.0, 25.0, 20.0], dtype=torch.float32, device=device + ) + + # Reconstruct the LP exactly as LPLBSolver._solve builds it. + counts_norm = global_counts / global_counts.sum().clamp(min=1.0) + t1 = counts_norm[solver.log_single] + b1 = counts_norm[solver.log_replicated] + b2 = -(solver.B1 @ t1).flatten() + b = torch.cat([b1, b2]) + big_M_col = b - solver._A_base_row_sum + A_full = torch.hstack([solver.A_base, big_M_col.unsqueeze(1)]) + + cuda_x = cuda_solve_ipm(A_full, b, solver.c_vec) + torch_x = solve_ipm_torch_reference(A_full, b, solver.c_vec) + + converged = not torch.allclose(cuda_x, torch.full_like(cuda_x, 0.5)) + max_diff = (cuda_x - torch_x).abs().max().item() + print( + f"\n[ipm-compare] converged={converged} max|cuda-torch|={max_diff:.3e} " + f"cuda={[round(v,4) for v in cuda_x.tolist()]} " + f"torch={[round(v,4) for v in torch_x.tolist()]}" + ) + assert converged, ( + "IPM returned the 0.5 non-convergence sentinel — the comparison would " + "be trivial. Adjust the LP instance so it converges." + ) + assert torch.allclose( + cuda_x, torch_x, atol=1e-2, rtol=1e-2 + ), f"fused IPM diverges from torch reference: max abs diff {max_diff:.3e}" + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.device_count() < NUM_GPUS, + reason=f"This test requires at least {NUM_GPUS} CUDA devices", +) +def test_lplb_distributed_two_rank(): + """Driver: spawn `NUM_GPUS` worker processes that each run the + distributed-LPLB invariant suite.""" + torch.multiprocessing.spawn( + _worker_main, + args=(NUM_GPUS,), + nprocs=NUM_GPUS, + ) + + +def _worker_main(local_rank: int, world_size: int): + """Per-rank entry point under torch.multiprocessing.spawn.""" + # Inject minimal ServerArgs before any LPLB module reads the global state. + # Silent fallbacks no longer exist — the fused CUDA path is the only LP + # path, so this test relies on hard failures, not gating flags. + from sglang.srt.server_args import ( + ServerArgs, + set_global_server_args_for_scheduler, + ) + + set_global_server_args_for_scheduler( + ServerArgs( + model_path="dummy", + ) + ) + + device = torch.device(f"cuda:{local_rank}") + torch.cuda.set_device(device) + torch.set_default_device(device) + + update_environment_variables( + { + "RANK": str(local_rank), + "LOCAL_RANK": str(local_rank), + "WORLD_SIZE": str(world_size), + "MASTER_ADDR": "localhost", + "MASTER_PORT": "12347", # Distinct from other tests' ports. + } + ) + init_distributed_environment( + world_size=world_size, rank=local_rank, local_rank=local_rank + ) + initialize_model_parallel( + tensor_model_parallel_size=world_size, + expert_model_parallel_size=world_size, + ) + + from sglang.srt.eplb.lplb_solver import clear_global_lplb_solvers + + try: + # Clear the global solver registry between subtests so a stale solver + # can't shadow a freshly-built one. + clear_global_lplb_solvers() + _check_solver_with_empty_rank(local_rank, world_size, device) + clear_global_lplb_solvers() + _check_all_ranks_empty(local_rank, world_size, device) + clear_global_lplb_solvers() + _check_solver_determinism(local_rank, world_size, device) + clear_global_lplb_solvers() + _check_post_rebalance_reinit(local_rank, world_size, device) + finally: + # Use parallel_state's destroy helpers rather than raw + # `dist.destroy_process_group()` so we don't leave _WORLD/_MOE_EP/_TP + # globals stale for later tests. + from sglang.srt.distributed.parallel_state import ( + destroy_distributed_environment, + destroy_model_parallel, + ) + + clear_global_lplb_solvers() + destroy_model_parallel() + destroy_distributed_environment() + + +def _build_solver(): + """Construct an LPLBSolver bound to the live moe_ep_group.""" + from sglang.srt.distributed.parallel_state import get_moe_ep_group + from sglang.srt.eplb.lplb_solver import LPLBSolver + + phy2log, log2phy, num_valid = _make_metadata(rebalanced=False) + return ( + LPLBSolver( + phy2log=phy2log.cuda(), + log2phy=log2phy.cuda(), + num_gpus=NUM_GPUS, + ep_group=get_moe_ep_group(), + logical_to_all_physical_map_num_valid=num_valid.cuda(), + ), + phy2log, + log2phy, + num_valid, + ) + + +def _expected_output(solver, expected_global_counts: torch.Tensor) -> torch.Tensor: + """Oracle: what `solver.solve(*)` should produce given known global + counts. Uses the solver's own `_solve` so we match implementation + quirks (regularization, on-device clamp normalization, etc.). + """ + return solver._solve(expected_global_counts.float().cuda()) + + +def _check_solver_with_empty_rank(rank: int, world_size: int, device: torch.device): + """Rank 0 has real `topk_ids`; rank 1 has `(0, topk)` empty. + + The all-reduce inside `solve()` must complete on both ranks, and both + must produce output equal to the oracle solver-output for the SUMMED + global counts (rank 0's bincount + rank 1's zero contribution). + """ + solver, _, _, _ = _build_solver() + + # Rank 0 owns these tokens; rank 1 is idle (DP-attention empty case). + rank0_topk = torch.tensor( + [[0, 1], [0, 2], [3, 0], [0, 1]], dtype=torch.int32, device=device + ) + if rank == 0: + topk_ids = rank0_topk + else: + topk_ids = torch.empty((0, TOPK), dtype=torch.int32, device=device) + + # Compute the oracle: the global counts are exactly the bincount of + # rank 0's tokens (rank 1 contributes zero). + flat = rank0_topk.flatten().long() + expected_counts = torch.bincount(flat, minlength=NUM_LOGICAL) + expected = _expected_output(solver, expected_counts) + + # Run the actual collective. + actual = solver.solve(topk_ids) + + # Shape + finiteness sanity. + assert actual.shape == ( + NUM_LOGICAL, + solver.max_copies, + ), f"rank {rank}: bad output shape {actual.shape}" + assert torch.isfinite(actual).all(), f"rank {rank}: non-finite values in output" + assert (actual >= 0).all(), f"rank {rank}: negative probabilities" + + # The strong invariant: output matches the summed-count oracle. + # If the all-reduce silently failed, rank 1 would feed all-zero local + # counts to its solver, the oracle wouldn't match, and this assertion + # would catch it. + assert torch.allclose(actual, expected, atol=1e-4, rtol=1e-3), ( + f"rank {rank}: solve() output disagrees with summed-count oracle " + f"(max abs diff {(actual - expected).abs().max().item():.2e}). " + "This usually indicates the EP all-reduce inside solve() was " + "skipped on the empty rank, or rank 1 used local counts only." + ) + + # 0.5-uniform sentinel detection: torch IPM's failure path returns a + # vector of all-0.5. If we see that, the IPM diverged silently. + is_uniform_half = torch.allclose( + actual, + torch.full_like(actual, 0.5), + atol=1e-6, + ) + assert not is_uniform_half, ( + f"rank {rank}: output is the 0.5-uniform fallback, indicating " + "torch IPM convergence failure" + ) + + +def _check_all_ranks_empty(rank: int, world_size: int, device: torch.device): + """Both ranks have empty topk_ids (idle batch). The collective must + still complete; the output should be the all-zero-counts oracle.""" + solver, _, _, _ = _build_solver() + + empty = torch.empty((0, TOPK), dtype=torch.int32, device=device) + expected_counts = torch.zeros(NUM_LOGICAL, dtype=torch.int64) + expected = _expected_output(solver, expected_counts) + + actual = solver.solve(empty) + + assert torch.isfinite(actual).all(), f"rank {rank}: non-finite for empty-batch" + assert (actual >= 0).all(), f"rank {rank}: negative for empty-batch" + assert torch.allclose( + actual, expected, atol=1e-4, rtol=1e-3 + ), f"rank {rank}: empty-batch output disagrees with all-zero oracle" + + +def _check_solver_determinism(rank: int, world_size: int, device: torch.device): + """Same input, two `solve()` calls in a row → identical output.""" + solver, _, _, _ = _build_solver() + if rank == 0: + topk_ids = torch.tensor([[0, 1], [3, 0]], dtype=torch.int32, device=device) + else: + topk_ids = torch.empty((0, TOPK), dtype=torch.int32, device=device) + + out1 = solver.solve(topk_ids) + out2 = solver.solve(topk_ids) + assert torch.equal(out1, out2), ( + f"rank {rank}: solve() not deterministic across calls " + f"(max diff {(out1 - out2).abs().max().item():.2e})" + ) + + +def _check_post_rebalance_reinit(rank: int, world_size: int, device: torch.device): + """Build a NEW solver with different `phy2log` (the redundant logical + moves from expert 0 to expert 1). Same input → DIFFERENT output, since + the LP problem changed.""" + from sglang.srt.distributed.parallel_state import get_moe_ep_group + from sglang.srt.eplb.lplb_solver import LPLBSolver + + solver_old, _, _, _ = _build_solver() + phy2log_new, log2phy_new, num_valid_new = _make_metadata(rebalanced=True) + solver_new = LPLBSolver( + phy2log=phy2log_new.cuda(), + log2phy=log2phy_new.cuda(), + num_gpus=NUM_GPUS, + ep_group=get_moe_ep_group(), + logical_to_all_physical_map_num_valid=num_valid_new.cuda(), + ) + + # An input that hits the replicated logical in BOTH configs (so the + # LP solution is sensitive to which logical is the replicated one). + rank0_topk = torch.tensor( + [[0, 1], [0, 1], [0, 1], [2, 3]], dtype=torch.int32, device=device + ) + if rank == 0: + topk_ids = rank0_topk + else: + topk_ids = torch.empty((0, TOPK), dtype=torch.int32, device=device) + + out_old = solver_old.solve(topk_ids) + out_new = solver_new.solve(topk_ids) + + # The two outputs should differ — same `topk_ids`, different metadata + # ⇒ different LP solution. If they're identical, one of the solvers + # used stale state. + assert not torch.equal(out_old, out_new), ( + f"rank {rank}: post-rebalance solver produced same output as " + "pre-rebalance solver despite different phy2log mappings — " + "stale solver state likely" + ) + + # Positive oracle: each output should match its OWN solver's + # `_solve` of the SUMMED global counts (rank 0's bincount; rank 1 + # contributes zero). Both ranks compare against the same global oracle + # since solve() all-reduces the counts. + expected_counts = torch.bincount(rank0_topk.flatten().long(), minlength=NUM_LOGICAL) + expected_old = _expected_output(solver_old, expected_counts) + expected_new = _expected_output(solver_new, expected_counts) + assert torch.allclose(out_old, expected_old, atol=1e-4, rtol=1e-3), ( + f"rank {rank}: pre-rebalance output disagrees with own oracle " + f"(diff {(out_old - expected_old).abs().max().item():.2e})" + ) + assert torch.allclose(out_new, expected_new, atol=1e-4, rtol=1e-3), ( + f"rank {rank}: post-rebalance output disagrees with own oracle " + f"(diff {(out_new - expected_new).abs().max().item():.2e})" + ) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/eval/test_text_models_gsm8k_eval.py b/asian_ai/performance/SGLang/test/registered/eval/test_text_models_gsm8k_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..98cd5b6db1d3292f9070ae21ea34ebbe776e6f38 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/eval/test_text_models_gsm8k_eval.py @@ -0,0 +1,138 @@ +import json +import unittest +import warnings +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_FP8_TP1, + DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_FP8_TP2, + DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_TP1, + DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_TP2, + DEFAULT_URL_FOR_TEST, + ModelLaunchSettings, + check_evaluation_test_results, + parse_models, + popen_launch_server, + write_results_to_json, +) + +# Nightly eval tests run large models (up to 70B+ params) that may need +# downloading on cache miss. Use a longer timeout than the default 600s. +NIGHTLY_EVAL_SERVER_TIMEOUT = 1800 + +register_cuda_ci(est_time=3600, suite="nightly-eval-text-2-gpu", nightly=True) + +MODEL_SCORE_THRESHOLDS = { + # Thresholds set at 5% below reported GSM8K (5-shot/CoT) scores + "meta-llama/Llama-3.1-8B-Instruct": 0.80, # 84.5% - 5% + "mistralai/Mistral-7B-Instruct-v0.3": 0.47, # 52.1% - 5% + "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct": 0.81, # 86.4% - 5% + "google/gemma-2-27b-it": 0.81, # 85.5% measured - 5% + "meta-llama/Llama-3.1-70B-Instruct": 0.89, # 94.1% - 5% + "mistralai/Mixtral-8x7B-Instruct-v0.1": 0.69, # 74.4% - 5% + "Qwen/Qwen2-57B-A14B-Instruct": 0.76, # 80.7% - 5% (official A14B score; 88.2% was the 72B) + "neuralmagic/Meta-Llama-3.1-8B-Instruct-FP8": 0.80, # 84.5% - 5% + "neuralmagic/Mistral-7B-Instruct-v0.3-FP8": 0.47, # 52.1% - 5% + "neuralmagic/DeepSeek-Coder-V2-Lite-Instruct-FP8": 0.81, # 86.4% - 5% + "zai-org/GLM-4.5-Air-FP8": 0.80, # ~85% - 5% + "neuralmagic/gemma-2-2b-it-FP8": 0.53, # 58.4% measured - 5% + "neuralmagic/Meta-Llama-3.1-70B-Instruct-FP8": 0.89, # 94.1% - 5% + "neuralmagic/Mixtral-8x7B-Instruct-v0.1-FP8": 0.69, # 74.4% - 5% + "neuralmagic/Qwen2-72B-Instruct-FP8": 0.86, # 91.1% - 5% + "neuralmagic/Qwen2-57B-A14B-Instruct-FP8": 0.76, # 80.7% - 5% (official A14B score) +} + + +# Do not use `CustomTestCase` since `test_gsm8k_all_models` does not want retry +class TestNightlyGsm8KEval(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.models = [] + models_tp1 = parse_models( + DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_TP1 + ) + parse_models(DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_FP8_TP1) + for model_path in models_tp1: + cls.models.append(ModelLaunchSettings(model_path, tp_size=1)) + + models_tp2 = parse_models( + DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_TP2 + ) + parse_models(DEFAULT_MODEL_NAME_FOR_NIGHTLY_EVAL_FP8_TP2) + for model_path in models_tp2: + cls.models.append(ModelLaunchSettings(model_path, tp_size=2)) + + cls.base_url = DEFAULT_URL_FOR_TEST + + def test_gsm8k_all_models(self): + warnings.filterwarnings( + "ignore", category=ResourceWarning, message="unclosed.*socket" + ) + is_first = True + all_results = [] + for model_setup in self.models: + with self.subTest(model=model_setup.model_path): + other_args = list(model_setup.extra_args) + process = None + + if model_setup.model_path == "meta-llama/Llama-3.1-70B-Instruct": + other_args.extend(["--mem-fraction-static", "0.9"]) + + try: + process = popen_launch_server( + model=model_setup.model_path, + other_args=other_args, + base_url=self.base_url, + timeout=NIGHTLY_EVAL_SERVER_TIMEOUT, + ) + + args = SimpleNamespace( + base_url=self.base_url, + model=model_setup.model_path, + eval_name="gsm8k", + num_examples=None, + num_threads=1024, + ) + + metrics = run_eval(args) + print( + f"{'=' * 42}\n{model_setup.model_path} - metrics={metrics} score={metrics['score']}\n{'=' * 42}\n" + ) + + write_results_to_json( + model_setup.model_path, metrics, "w" if is_first else "a" + ) + is_first = False + + all_results.append( + (model_setup.model_path, metrics["score"], 0.0, None) + ) + except Exception as e: + error_message = str(e) + all_results.append( + (model_setup.model_path, None, None, error_message) + ) + print(f"Error evaluating {model_setup.model_path}: {error_message}") + finally: + if process is not None: + kill_process_tree(process.pid) + + try: + with open("results.json", "r") as f: + print("\nFinal Results from results.json:") + print(json.dumps(json.load(f), indent=2)) + except Exception as e: + print(f"Error reading results.json: {e}") + + # Check all scores after collecting all results + check_evaluation_test_results( + all_results, + self.__class__.__name__, + model_accuracy_thresholds=MODEL_SCORE_THRESHOLDS, + model_count=len(self.models), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/eval/test_vlms_mmmu_eval.py b/asian_ai/performance/SGLang/test/registered/eval/test_vlms_mmmu_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..d731ec43aaf37dd3bddae9a3bcd3fe8df2acb53a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/eval/test_vlms_mmmu_eval.py @@ -0,0 +1,154 @@ +import json +import unittest +import warnings +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + ModelEvalMetrics, + ModelLaunchSettings, + check_evaluation_test_results, + popen_launch_server, + write_results_to_json, +) + +# Nightly eval tests run large models that may need downloading on cache miss. +# Use a longer timeout than the default 600s. +NIGHTLY_EVAL_SERVER_TIMEOUT = 1800 + +register_cuda_ci(est_time=7200, suite="nightly-eval-vlm-2-gpu", nightly=True) + +MODEL_THRESHOLDS = { + # Conservative thresholds on 100 MMMU samples, especially for latency thresholds + ModelLaunchSettings("deepseek-ai/deepseek-vl2-small"): ModelEvalMetrics( + 0.320, 56.1 + ), + ModelLaunchSettings("deepseek-ai/Janus-Pro-7B"): ModelEvalMetrics(0.285, 40.3), + ModelLaunchSettings("Efficient-Large-Model/NVILA-8B-hf"): ModelEvalMetrics( + 0.270, 56.7 + ), + ModelLaunchSettings("Efficient-Large-Model/NVILA-Lite-2B-hf"): ModelEvalMetrics( + 0.270, 23.8 + ), + ModelLaunchSettings("google/gemma-4-E4B-it"): ModelEvalMetrics(0.26, 15.0), + ModelLaunchSettings( + "google/gemma-4-26B-A4B-it", extra_args=["--tp=2"] + ): ModelEvalMetrics(0.27, 22.3), + ModelLaunchSettings( + "google/gemma-4-31B-it", extra_args=["--tp=2"] + ): ModelEvalMetrics(0.28, 25.5), + ModelLaunchSettings("mistral-community/pixtral-12b"): ModelEvalMetrics(0.360, 16.6), + ModelLaunchSettings("moonshotai/Kimi-VL-A3B-Instruct"): ModelEvalMetrics( + 0.330, 23.5 + ), + # temporarily disabled: NaN in next_token_logits + # ModelLaunchSettings("openbmb/MiniCPM-o-2_6"): ModelEvalMetrics(0.330, 29.5), + # ModelLaunchSettings("openbmb/MiniCPM-v-2_6"): ModelEvalMetrics(0.259, 36.3), + ModelLaunchSettings("OpenGVLab/InternVL2_5-2B"): ModelEvalMetrics(0.300, 18.0), + ModelLaunchSettings("Qwen/Qwen2-VL-7B-Instruct"): ModelEvalMetrics(0.310, 83.3), + ModelLaunchSettings("Qwen/Qwen2.5-VL-7B-Instruct"): ModelEvalMetrics(0.330, 31.9), + ModelLaunchSettings( + "Qwen/Qwen3-VL-30B-A3B-Instruct", extra_args=["--tp=2"] + ): ModelEvalMetrics(0.29, 37.0), + ModelLaunchSettings( + "unsloth/Mistral-Small-3.1-24B-Instruct-2503" + ): ModelEvalMetrics(0.30, 16.7), + ModelLaunchSettings("XiaomiMiMo/MiMo-VL-7B-RL"): ModelEvalMetrics(0.28, 40.0), + ModelLaunchSettings("zai-org/GLM-4.1V-9B-Thinking"): ModelEvalMetrics(0.280, 30.4), + ModelLaunchSettings( + "zai-org/GLM-4.5V-FP8", extra_args=["--tp=2"] + ): ModelEvalMetrics(0.26, 34.0), +} + + +class TestNightlyVLMMmmuEval(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.models = list(MODEL_THRESHOLDS.keys()) + cls.base_url = DEFAULT_URL_FOR_TEST + + def test_mmmu_vlm_models(self): + warnings.filterwarnings( + "ignore", category=ResourceWarning, message="unclosed.*socket" + ) + is_first = True + all_results = [] + + for model in self.models: + model_path = model.model_path + with self.subTest(model=model_path): + process = None + try: + process = popen_launch_server( + model=model_path, + base_url=self.base_url, + other_args=model.extra_args, + timeout=NIGHTLY_EVAL_SERVER_TIMEOUT, + ) + + args = SimpleNamespace( + base_url=self.base_url, + model=model_path, + eval_name="mmmu", + num_examples=100, + num_threads=64, + max_tokens=1024, + ) + + args.return_latency = True + + metrics, latency = run_eval(args) + + metrics["score"] = round(metrics["score"], 4) + metrics["latency"] = round(latency, 4) + print( + f"{'=' * 42}\n{model_path} - metrics={metrics} score={metrics['score']}\n{'=' * 42}\n" + ) + + write_results_to_json(model_path, metrics, "w" if is_first else "a") + is_first = False + + all_results.append( + ( + model_path, + metrics["score"], + metrics["latency"], + None, + ) + ) + except Exception as e: + error_message = str(e) + all_results.append((model_path, None, None, error_message)) + print(f"Error evaluating {model_path}: {error_message}") + finally: + if process is not None: + kill_process_tree(process.pid) + + try: + with open("results.json", "r") as f: + print("\nFinal Results from results.json:") + print(json.dumps(json.load(f), indent=2)) + except Exception as e: + print(f"Error reading results: {e}") + + model_accuracy_thresholds = { + model.model_path: threshold.accuracy + for model, threshold in MODEL_THRESHOLDS.items() + } + model_latency_thresholds = { + model.model_path: threshold.eval_time + for model, threshold in MODEL_THRESHOLDS.items() + } + check_evaluation_test_results( + all_results, + self.__class__.__name__, + model_accuracy_thresholds=model_accuracy_thresholds, + model_latency_thresholds=model_latency_thresholds, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/function_call/test_kimik2_detector.py b/asian_ai/performance/SGLang/test/registered/function_call/test_kimik2_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..27f39d69793ed4673e36a0aadfcb5df73f2e3e52 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/function_call/test_kimik2_detector.py @@ -0,0 +1,1398 @@ +import json +import unittest + +from sglang.srt.entrypoints.openai.protocol import Function, Tool +from sglang.srt.function_call.kimik2_detector import ( + KimiK2Detector as KimiK2FuncDetector, +) +from sglang.srt.function_call.kimik2_detector import ( + _strip_special_tokens, +) +from sglang.srt.parser.reasoning_parser import KimiK2Detector as KimiK2ReasoningDetector +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(5, "base-a-test-cpu") +register_cpu_ci(est_time=7, suite="base-c-test-cpu") + + +def _make_tool(name, parameters=None): + """Helper to create a Tool with less boilerplate.""" + return Tool( + type="function", + function=Function( + name=name, + description=f"{name} tool", + parameters=parameters + or { + "type": "object", + "properties": { + "path": {"type": "string", "description": "File path"}, + }, + "required": ["path"], + }, + ), + ) + + +def _collect_streaming_tool_calls(detector, chunks, tools): + """Run streaming chunks through a detector and collect assembled tool calls.""" + tool_calls = [] + all_normal_text = "" + for chunk in chunks: + result = detector.parse_streaming_increment(chunk, tools) + all_normal_text += result.normal_text + for tc_chunk in result.calls: + if tc_chunk.tool_index is not None: + while len(tool_calls) <= tc_chunk.tool_index: + tool_calls.append({"name": "", "parameters": ""}) + tc = tool_calls[tc_chunk.tool_index] + if tc_chunk.name: + tc["name"] = tc_chunk.name + if tc_chunk.parameters: + tc["parameters"] += tc_chunk.parameters + return tool_calls, all_normal_text + + +# ============================================================ +# Part 1: KimiK2Detector (function call parsing) tests +# ============================================================ + + +class TestKimiK2DetectorBasic(unittest.TestCase): + """Basic non-streaming parsing tests for KimiK2Detector.""" + + def setUp(self): + self.tools = [ + _make_tool("ReadFile"), + _make_tool( + "get_weather", + { + "type": "object", + "properties": { + "city": {"type": "string"}, + "unit": {"type": "string"}, + }, + "required": ["city"], + }, + ), + ] + self.detector = KimiK2FuncDetector() + + def test_single_tool_call(self): + """Parse a single complete tool call.""" + text = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/test.py"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = self.detector.detect_and_parse(text, self.tools) + self.assertEqual(len(result.calls), 1) + self.assertEqual(result.calls[0].name, "ReadFile") + self.assertEqual(result.calls[0].parameters, '{"path": "/test.py"}') + self.assertEqual(result.normal_text, "") + + def test_multiple_tool_calls(self): + """Parse two consecutive tool calls.""" + text = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/a.py"}' + "<|tool_call_end|>" + "<|tool_call_begin|>functions.get_weather:1" + '<|tool_call_argument_begin|>{"city": "Tokyo"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = self.detector.detect_and_parse(text, self.tools) + self.assertEqual(len(result.calls), 2) + self.assertEqual(result.calls[0].name, "ReadFile") + self.assertEqual(result.calls[1].name, "get_weather") + self.assertEqual(result.calls[1].parameters, '{"city": "Tokyo"}') + + def test_non_streaming_tool_index_is_local(self): + """tool_index is the per-response 0-based position, not the model's :N suffix. + + The model may emit conversation-level ``:N`` counters (e.g. ``:5``, ``:6``) + in a multi-turn conversation. The non-streaming parser must enumerate + parsed calls locally (0, 1, ...) so that + ``serving_chat._process_tool_call_id()`` can offset them by + ``history_tool_calls_cnt`` without double-counting. + """ + text = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:5" + '<|tool_call_argument_begin|>{"path": "/a.py"}' + "<|tool_call_end|>" + "<|tool_call_begin|>functions.get_weather:6" + '<|tool_call_argument_begin|>{"city": "Tokyo"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = self.detector.detect_and_parse(text, self.tools) + self.assertEqual(len(result.calls), 2) + self.assertEqual(result.calls[0].tool_index, 0) + self.assertEqual(result.calls[0].name, "ReadFile") + self.assertEqual(result.calls[1].tool_index, 1) + self.assertEqual(result.calls[1].name, "get_weather") + + def test_normal_text_before_tool_call(self): + """Normal text before tool call markers is preserved.""" + text = ( + "Let me check the file." + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/test.py"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = self.detector.detect_and_parse(text, self.tools) + self.assertEqual(len(result.calls), 1) + self.assertEqual(result.normal_text, "Let me check the file.") + + def test_no_tool_call(self): + """Text without tool call markers returns as normal text.""" + text = "Just a normal response." + result = self.detector.detect_and_parse(text, self.tools) + self.assertEqual(len(result.calls), 0) + self.assertEqual(result.normal_text, text) + + def test_has_tool_call(self): + """has_tool_call correctly detects the presence of tool call markers.""" + self.assertTrue( + self.detector.has_tool_call("<|tool_calls_section_begin|>stuff") + ) + self.assertFalse(self.detector.has_tool_call("no markers here")) + + +class TestKimiK2DetectorHyphenatedNames(unittest.TestCase): + """Test support for hyphenated function names (common in MCP tools).""" + + def setUp(self): + self.tools = [ + _make_tool("mcp__portal__search-documents"), + _make_tool("list-files"), + ] + self.detector = KimiK2FuncDetector() + + def test_hyphenated_name_non_streaming(self): + """Parse tool call with hyphenated function name.""" + text = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.mcp__portal__search-documents:0" + '<|tool_call_argument_begin|>{"path": "/docs"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = self.detector.detect_and_parse(text, self.tools) + self.assertEqual(len(result.calls), 1) + self.assertEqual(result.calls[0].name, "mcp__portal__search-documents") + + def test_hyphenated_name_streaming(self): + """Stream tool call with hyphenated function name.""" + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.list-files:0" + '<|tool_call_argument_begin|>{"path', + '": "/home"}', + "<|tool_call_end|>", + "<|tool_calls_section_end|>", + ] + tool_calls, _ = _collect_streaming_tool_calls(self.detector, chunks, self.tools) + self.assertEqual(len(tool_calls), 1) + self.assertEqual(tool_calls[0]["name"], "list-files") + params = json.loads(tool_calls[0]["parameters"]) + self.assertEqual(params["path"], "/home") + + +class TestKimiK2DetectorStreaming(unittest.TestCase): + """Streaming incremental parsing tests for KimiK2Detector.""" + + def test_streaming_trailing_literal_left_angle_is_not_dropped(self): + """A final literal '<' must remain in normal_text instead of being buffered away.""" + detector = KimiK2FuncDetector() + + result = detector.parse_streaming_increment("normal text <", []) + + self.assertEqual(result.normal_text, "normal text <") + self.assertEqual(detector._buffer, "") + + def setUp(self): + self.tools = [ + _make_tool("ReadFile"), + _make_tool( + "get_weather", + { + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + }, + ), + ] + + def test_streaming_single_tool_call(self): + """Stream a single tool call across multiple chunks.""" + detector = KimiK2FuncDetector() + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + "<|tool_call_argument_begin|>{", + '"path": "/test.py"', + "}", + "<|tool_call_end|><|tool_calls_section_end|>", + ] + tool_calls, _ = _collect_streaming_tool_calls(detector, chunks, self.tools) + self.assertEqual(len(tool_calls), 1) + self.assertEqual(tool_calls[0]["name"], "ReadFile") + self.assertEqual(tool_calls[0]["parameters"], '{"path": "/test.py"}') + + def test_streaming_multiple_tool_calls(self): + """Stream two tool calls sequentially.""" + detector = KimiK2FuncDetector() + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/a.py"}', + "<|tool_call_end|>", + "<|tool_call_begin|>functions.get_weather:1" + '<|tool_call_argument_begin|>{"city": "Paris"}', + "<|tool_call_end|>", + "<|tool_calls_section_end|>", + ] + tool_calls, _ = _collect_streaming_tool_calls(detector, chunks, self.tools) + self.assertEqual(len(tool_calls), 2) + self.assertEqual(tool_calls[0]["name"], "ReadFile") + self.assertEqual(tool_calls[1]["name"], "get_weather") + self.assertEqual(json.loads(tool_calls[1]["parameters"]), {"city": "Paris"}) + + def test_streaming_state_reset_after_completion(self): + """Buffer and state reset after tool call completes.""" + detector = KimiK2FuncDetector() + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/x"}', + "<|tool_call_end|>", + "<|tool_calls_section_end|>", + ] + for chunk in chunks: + detector.parse_streaming_increment(chunk, self.tools) + + self.assertEqual(detector._buffer, "") + self.assertEqual(detector.current_tool_id, 1) + + +class TestKimiK2DetectorSpecialTokenLeakage(unittest.TestCase): + """Verify special tokens are never leaked into normal_text output.""" + + def setUp(self): + self.tools = [_make_tool("ReadFile")] + + def test_no_leak_in_non_tool_text(self): + """End tokens appearing without start tokens are stripped from output.""" + detector = KimiK2FuncDetector() + result = detector.parse_streaming_increment( + "normal text<|tool_calls_section_end|>", self.tools + ) + self.assertNotIn("<|tool_calls_section_end|>", result.normal_text) + self.assertIn("normal text", result.normal_text) + + def test_no_leak_of_argument_begin_token(self): + """Argument begin token is stripped when leaked.""" + detector = KimiK2FuncDetector() + result = detector.parse_streaming_increment( + "text<|tool_call_argument_begin|>more", self.tools + ) + self.assertNotIn("<|tool_call_argument_begin|>", result.normal_text) + + def test_no_leak_on_error_fallback(self): + """On parse errors, normal_text fallback has tokens stripped.""" + cleaned = _strip_special_tokens( + "leaked<|tool_calls_section_begin|>" "<|tool_call_end|>content" + ) + self.assertEqual(cleaned, "leakedcontent") + + def test_strip_special_tokens_all_tokens(self): + """All 5 known special tokens are stripped.""" + dirty = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>" + "<|tool_call_argument_begin|>" + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + self.assertEqual(_strip_special_tokens(dirty), "") + + def test_strip_preserves_normal_text(self): + """Stripping doesn't affect normal text content.""" + text = "Hello world, this is normal text." + self.assertEqual(_strip_special_tokens(text), text) + + +# ============================================================ +# Part 2: KimiK2ReasoningDetector tests +# ============================================================ + + +class TestKimiK2ReasoningDetectorNonStreaming(unittest.TestCase): + """Non-streaming tests for KimiK2ReasoningDetector.""" + + def test_normal_reasoning_with_think_end(self): + """Standard case: ... followed by tool call markers.""" + det = KimiK2ReasoningDetector() + text = ( + "I need to check the file." + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/test.py"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = det.detect_and_parse(text) + self.assertEqual(result.reasoning_text, "I need to check the file.") + self.assertIn("<|tool_calls_section_begin|>", result.normal_text) + + def test_tool_call_inside_think_without_close_tag(self): + """ + BUG FIX: Model outputs tool call markers inside without . + + This is the primary scenario that caused special token leakage. + The model decides to call a tool while reasoning and directly outputs + <|tool_calls_section_begin|> without first closing with . + """ + det = KimiK2ReasoningDetector() + text = ( + "Let me read this file..." + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/test.py"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = det.detect_and_parse(text) + + # Reasoning content must NOT contain tool call tokens + self.assertNotIn("<|tool_calls_section_begin|>", result.reasoning_text) + self.assertNotIn("<|tool_call_begin|>", result.reasoning_text) + self.assertIn("Let me read this file...", result.reasoning_text) + self.assertNotIn("", result.reasoning_text) + + # Tool call markers must be in normal_text for downstream parsing + self.assertIn("<|tool_calls_section_begin|>", result.normal_text) + self.assertIn("<|tool_call_begin|>", result.normal_text) + + def test_no_reasoning_just_tool_call(self): + """No block, just tool call markers — pass through as normal_text.""" + det = KimiK2ReasoningDetector() + text = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/x"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = det.detect_and_parse(text) + self.assertEqual(result.reasoning_text, "") + self.assertIn("<|tool_calls_section_begin|>", result.normal_text) + + def test_normal_text_without_reasoning(self): + """Plain text without reasoning or tool calls.""" + det = KimiK2ReasoningDetector() + result = det.detect_and_parse("Hello, how can I help?") + self.assertEqual(result.normal_text, "Hello, how can I help?") + self.assertEqual(result.reasoning_text, "") + + +class TestKimiK2ReasoningDetectorStreaming(unittest.TestCase): + """Streaming tests for KimiK2ReasoningDetector.""" + + def _run_streaming(self, chunks, **kwargs): + """Helper: run chunks through streaming detector, collect reasoning and normal text.""" + det = KimiK2ReasoningDetector(**kwargs) + all_reasoning = "" + all_normal = "" + for chunk in chunks: + r = det.parse_streaming_increment(chunk) + all_reasoning += r.reasoning_text + all_normal += r.normal_text + return all_reasoning, all_normal + + def test_streaming_normal_think_then_tool_call(self): + """Standard streaming: ... then tool call markers.""" + reasoning, normal = self._run_streaming( + [ + "", + "Analyzing the request...", + "", + "<|tool_calls_section_begin|>", + "<|tool_call_begin|>functions.ReadFile:0", + ] + ) + self.assertIn("Analyzing the request...", reasoning) + self.assertIn("<|tool_calls_section_begin|>", normal) + self.assertNotIn("<|tool_calls_section_begin|>", reasoning) + + def test_streaming_tool_call_inside_think(self): + """ + BUG FIX (streaming): Tool call markers inside without . + + This is the streaming equivalent of the primary bug. The model streams + reasoning content, then directly outputs tool call markers without . + """ + reasoning, normal = self._run_streaming( + [ + "", + "I need to", + " read the file.", + "<|tool_calls_section_begin|>", + "<|tool_call_begin|>functions.ReadFile:5", + "<|tool_call_argument_begin|>", + '{"path": "/Users/user/project/file.ts"}', + "<|tool_call_end|>", + "<|tool_calls_section_end|>", + ] + ) + + # Reasoning is clean + self.assertIn("I need to read the file.", reasoning) + self.assertNotIn("<|tool_calls_section_begin|>", reasoning) + self.assertNotIn("<|tool_call_begin|>", reasoning) + self.assertNotIn("", reasoning) + + # Tool call markers are in normal_text + self.assertIn("<|tool_calls_section_begin|>", normal) + self.assertIn("functions.ReadFile:5", normal) + + def test_streaming_tool_call_marker_in_single_chunk(self): + """Tool call marker arrives in a single chunk while in reasoning mode.""" + reasoning, normal = self._run_streaming( + [ + "thinking...", + '<|tool_calls_section_begin|><|tool_call_begin|>functions.ReadFile:0<|tool_call_argument_begin|>{"path": "/x"}', + ] + ) + self.assertIn("thinking...", reasoning) + self.assertIn("<|tool_calls_section_begin|>", normal) + + def test_streaming_partial_marker_buffering(self): + """ + Partial tool call marker at end of chunk is buffered to prevent + premature streaming of marker characters as reasoning content. + """ + det = KimiK2ReasoningDetector(stream_reasoning=True) + + # First chunk: reasoning + partial marker "<|tool_calls" + det._in_reasoning = True + det.stripped_think_start = True + + r1 = det.parse_streaming_increment("some reasoning") + self.assertEqual(r1.reasoning_text, "some reasoning") + + # Chunk that ends with start of marker + r2 = det.parse_streaming_increment("<|tool") + # Partial marker should be buffered, not streamed + self.assertNotIn("<|tool", r2.reasoning_text) + + # Complete the marker + r3 = det.parse_streaming_increment("_calls_section_begin|>rest") + # Now it should force-exit reasoning + self.assertIn("<|tool_calls_section_begin|>", r3.normal_text) + + def test_streaming_no_reasoning_mode(self): + """Normal text without reasoning passes through as normal_text.""" + reasoning, normal = self._run_streaming( + [ + "Hello, I can help with that.", + " What do you need?", + ] + ) + self.assertEqual(reasoning, "") + self.assertIn("Hello, I can help with that.", normal) + self.assertIn(" What do you need?", normal) + + def test_streaming_force_reasoning(self): + """With force_reasoning, content before is reasoning.""" + reasoning, normal = self._run_streaming( + [ + "I should analyze this...", + "", + "Here is the answer.", + ], + force_reasoning=True, + ) + self.assertIn("I should analyze this...", reasoning) + self.assertIn("Here is the answer.", normal) + + +# ============================================================ +# Part 3: End-to-end integration tests +# ============================================================ + + +class TestKimiK2EndToEnd(unittest.TestCase): + """ + End-to-end tests simulating the full flow: + reasoning parser -> tool call parser. + + These test the exact bug scenario from the issue: Kimi-K2.5 outputs + tool call markers inside blocks, which must be correctly + split between reasoning and tool call parsers. + """ + + def setUp(self): + self.tools = [ + _make_tool("ReadFile"), + _make_tool( + "get_weather", + { + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + }, + ), + ] + + def test_e2e_streaming_reasoning_to_tool_call(self): + """ + Full pipeline: streaming reasoning parser feeds into streaming tool call parser. + + Simulates the exact path through serving_chat.py: + 1. Model outputs reasoning...<|tool_calls_section_begin|>... + 2. ReasoningParser splits: reasoning_text + normal_text + 3. FunctionCallParser receives normal_text and extracts tool calls + """ + reasoning_det = KimiK2ReasoningDetector(stream_reasoning=True) + tc_det = KimiK2FuncDetector() + + streaming_chunks = [ + "", + "I need to read the file", + " to understand the code.", + "<|tool_calls_section_begin|>", + "<|tool_call_begin|>functions.ReadFile:0", + "<|tool_call_argument_begin|>", + '{"path": "/Users/user/project/file.ts"}', + "<|tool_call_end|>", + "<|tool_calls_section_end|>", + ] + + all_reasoning = "" + all_tc_calls = [] + + for chunk in streaming_chunks: + # Step 1: reasoning parser + r = reasoning_det.parse_streaming_increment(chunk) + all_reasoning += r.reasoning_text + + # Step 2: feed normal_text into tool call parser (like serving_chat.py does) + if r.normal_text: + tc_result = tc_det.parse_streaming_increment(r.normal_text, self.tools) + all_tc_calls.extend(tc_result.calls) + + # Verify reasoning content + self.assertIn("I need to read the file to understand the code.", all_reasoning) + self.assertNotIn("<|", all_reasoning) + + # Verify tool calls were extracted + name_calls = [c for c in all_tc_calls if c.name] + self.assertEqual(len(name_calls), 1) + self.assertEqual(name_calls[0].name, "ReadFile") + + param_calls = [c for c in all_tc_calls if c.parameters] + full_params = "".join(c.parameters for c in param_calls) + self.assertIn("/Users/user/project/file.ts", full_params) + + def test_e2e_non_streaming_reasoning_to_tool_call(self): + """Non-streaming pipeline: reason parser then tool call parser.""" + reasoning_det = KimiK2ReasoningDetector() + tc_det = KimiK2FuncDetector() + + text = ( + "Let me check this file." + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/src/main.py"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + + # Step 1: reasoning parser + r = reasoning_det.detect_and_parse(text) + self.assertIn("Let me check this file.", r.reasoning_text) + self.assertNotIn("<|", r.reasoning_text) + + # Step 2: tool call parser on normal_text + tc_result = tc_det.detect_and_parse(r.normal_text, self.tools) + self.assertEqual(len(tc_result.calls), 1) + self.assertEqual(tc_result.calls[0].name, "ReadFile") + self.assertEqual( + json.loads(tc_result.calls[0].parameters), + {"path": "/src/main.py"}, + ) + + def test_e2e_normal_think_close_then_tool_call(self): + """Standard case with — should also work correctly.""" + reasoning_det = KimiK2ReasoningDetector(stream_reasoning=True) + tc_det = KimiK2FuncDetector() + + chunks = [ + "", + "Thinking about it...", + "", + "<|tool_calls_section_begin|>", + "<|tool_call_begin|>functions.get_weather:0", + '<|tool_call_argument_begin|>{"city": "London"}', + "<|tool_call_end|>", + "<|tool_calls_section_end|>", + ] + + all_reasoning = "" + all_tc_calls = [] + + for chunk in chunks: + r = reasoning_det.parse_streaming_increment(chunk) + all_reasoning += r.reasoning_text + if r.normal_text: + tc_result = tc_det.parse_streaming_increment(r.normal_text, self.tools) + all_tc_calls.extend(tc_result.calls) + + self.assertIn("Thinking about it...", all_reasoning) + name_calls = [c for c in all_tc_calls if c.name] + self.assertEqual(len(name_calls), 1) + self.assertEqual(name_calls[0].name, "get_weather") + + def test_e2e_normal_think_close_then_content_overlap_tool_call(self): + """Trailing content between ```` and the tool-call markers + (e.g. ``"This is a content:"``) must be surfaced as ``normal_text`` + by the tool-call parser and not stripped — this is the exact bug the + PR fixes. + """ + reasoning_det = KimiK2ReasoningDetector(stream_reasoning=True) + tc_det = KimiK2FuncDetector() + + chunks = [ + "", + "Thinking about it...", + "This is a ", + "content:<|tool_calls_section_begin|>", + "<|tool_call_begin|>functions.get_weather:0", + '<|tool_call_argument_begin|>{"city": "London"}', + "<|tool_call_end|>", + "<|tool_calls_section_end|>", + ] + + all_reasoning = "" + all_content = "" + + toolcall_chunks = [] + for chunk in chunks: + r = reasoning_det.parse_streaming_increment(chunk) + all_reasoning += r.reasoning_text + if r.normal_text: + toolcall_chunks.append(r.normal_text) + + tool_calls, all_content = _collect_streaming_tool_calls( + tc_det, toolcall_chunks, self.tools + ) + + self.assertEqual("Thinking about it...", all_reasoning) + self.assertEqual("This is a content:", all_content) + self.assertEqual(len(tool_calls), 1) + first_call = tool_calls.pop() + self.assertEqual(first_call["name"], "get_weather") + self.assertEqual(first_call["parameters"], '{"city": "London"}') + + def test_e2e_normal_think_close_then_content_overlap_tool_call_multi_token(self): + """Speculative decoding: a single chunk may contain normal text followed + by tool-call markers and even the tool_call_begin/id. The normal-text + prefix must still be emitted (not stripped) by the tool-call parser. + """ + reasoning_det = KimiK2ReasoningDetector(stream_reasoning=True) + tc_det = KimiK2FuncDetector() + + chunks = [ + "", + "Thinking about it...", + "This is a ", + "content:<|tool_calls_section_begin|><|tool_call_begin|>functions.get_weather:0" + '<|tool_call_argument_begin|>{"city": "London"}<|tool_call_end|><|tool_calls_section_end|>', + ] + + all_reasoning = "" + all_content = "" + toolcall_chunks = [] + + for chunk in chunks: + r = reasoning_det.parse_streaming_increment(chunk) + all_reasoning += r.reasoning_text + if r.normal_text: + toolcall_chunks.append(r.normal_text) + + tool_calls, all_content = _collect_streaming_tool_calls( + tc_det, toolcall_chunks, self.tools + ) + + self.assertEqual("Thinking about it...", all_reasoning) + self.assertEqual("This is a content:", all_content) + self.assertEqual(len(tool_calls), 1) + first_call = tool_calls.pop() + self.assertEqual(first_call["name"], "get_weather") + self.assertEqual(first_call["parameters"], '{"city": "London"}') + + def test_e2e_normal_think_close_then_content_overlap_tool_call_multi_token_multi_calls( + self, + ): + """Speculative decoding: a single chunk may contain normal text followed + by tool-call markers and even the tool_call_begin/id. Additionally, this + single chunk packs two complete tool-call sections back-to-back, which + exercises the ``while True:`` drain loop introduced by this PR — both + calls must be emitted from one ``parse_streaming_increment`` invocation. + """ + reasoning_det = KimiK2ReasoningDetector(stream_reasoning=True) + tc_det = KimiK2FuncDetector() + + chunks = [ + "", + "Thinking about it...", + "This is a ", + 'content:<|tool_calls_section_begin|><|tool_call_begin|>functions.get_weather:0<|tool_call_argument_begin|>{"city": "London"}<|tool_call_end|><|tool_calls_section_end|><|tool_calls_section_begin|><|tool_call_begin|>functions.get_weather:1<|tool_call_argument_begin|>' + '{"city": "Delhi"}<|tool_call_end|><|tool_calls_section_end|>', + ] + + all_reasoning = "" + all_content = "" + toolcall_chunks = [] + + for chunk in chunks: + r = reasoning_det.parse_streaming_increment(chunk) + all_reasoning += r.reasoning_text + if r.normal_text: + toolcall_chunks.append(r.normal_text) + + tool_calls, all_content = _collect_streaming_tool_calls( + tc_det, toolcall_chunks, self.tools + ) + + self.assertEqual("Thinking about it...", all_reasoning) + self.assertEqual("This is a content:", all_content) + self.assertEqual(len(tool_calls), 2) + first_call = tool_calls.pop(0) + self.assertEqual(first_call["name"], "get_weather") + self.assertEqual(first_call["parameters"], '{"city": "London"}') + second_call = tool_calls.pop(0) + self.assertEqual(second_call["name"], "get_weather") + self.assertEqual(second_call["parameters"], '{"city": "Delhi"}') + + def test_e2e_chunk_split_invariance(self): + """The detector must produce identical results across a few realistic + chunking variants. Special tokens (e.g. ``<|tool_calls_section_begin|>``) + are atomic and never split, so cuts only fall on token boundaries or + inside JSON args. + """ + prefix = "Thinking about it...This is a content:" + call1 = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:0" + '<|tool_call_argument_begin|>{"city": "London"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + call2 = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:1" + '<|tool_call_argument_begin|>{"city": "Delhi"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + + expected_reasoning = "Thinking about it..." + expected_content = "This is a content:" + expected_calls = [ + {"name": "get_weather", "parameters": '{"city": "London"}'}, + {"name": "get_weather", "parameters": '{"city": "Delhi"}'}, + ] + + variants = { + # One complete tool call per chunk. + "first_complete_then_second_complete": [prefix + call1, call2], + # Both tool calls arrive in a single chunk. + "both_in_one_chunk": [prefix + call1 + call2], + # First call complete + second call partial (cut inside JSON args), + # then the rest of the second call. + "first_complete_second_partial_then_rest": [ + prefix + + call1 + + "<|tool_calls_section_begin|>" + + "<|tool_call_begin|>functions.get_weather:1" + + '<|tool_call_argument_begin|>{"city": "De', + 'lhi"}<|tool_call_end|><|tool_calls_section_end|>', + ], + # First call partial (cut inside JSON args), then rest of first + + # full second call. + "first_partial_then_first_complete_second_complete": [ + prefix + + "<|tool_calls_section_begin|>" + + "<|tool_call_begin|>functions.get_weather:0" + + '<|tool_call_argument_begin|>{"city": "Lon', + 'don"}<|tool_call_end|><|tool_calls_section_end|>' + call2, + ], + } + + for name, chunks in variants.items(): + with self.subTest(variant=name): + reasoning_det = KimiK2ReasoningDetector(stream_reasoning=True) + tc_det = KimiK2FuncDetector() + all_reasoning = "" + toolcall_chunks = [] + for chunk in chunks: + r = reasoning_det.parse_streaming_increment(chunk) + all_reasoning += r.reasoning_text + if r.normal_text: + toolcall_chunks.append(r.normal_text) + tool_calls, all_content = _collect_streaming_tool_calls( + tc_det, toolcall_chunks, self.tools + ) + self.assertEqual(all_reasoning, expected_reasoning) + self.assertEqual(all_content, expected_content) + self.assertEqual(tool_calls, expected_calls) + + def test_e2e_normal_text_between_two_tool_calls(self): + """Normal text appearing BETWEEN two tool-call sections must be + surfaced as ``normal_text``. + """ + tc_det = KimiK2FuncDetector() + chunks = [ + "Prefix text:" + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:0" + '<|tool_call_argument_begin|>{"city": "London"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + " Now calling next: " + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:1" + "<|tool_call_argument_begin|>" + '{"city":' + ' "Delhi"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ] + + tool_calls, all_content = _collect_streaming_tool_calls( + tc_det, chunks, self.tools + ) + + self.assertIn("Prefix text:", all_content) + self.assertIn("Now calling next:", all_content) + self.assertEqual(len(tool_calls), 2) + self.assertEqual(tool_calls[0]["name"], "get_weather") + self.assertEqual(tool_calls[0]["parameters"], '{"city": "London"}') + self.assertEqual(tool_calls[1]["name"], "get_weather") + self.assertEqual(tool_calls[1]["parameters"], '{"city": "Delhi"}') + + def test_e2e_unparsable_tool_id_does_not_wedge_stream(self): + """A tool_call header with an unparsable ID must not wedge the + streaming parser. + """ + tc_det = KimiK2FuncDetector() + + # ``weird@id`` matches the broad ``[^\\s<|]+`` capture in + # ``stream_tool_call_portion_regex`` but fails both the standard + # ``name:idx`` form and the bare-counter form, so + # ``_parse_tool_call_id`` returns ``(None, 0)``. + chunks = [ + "normal text before", + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>weird@id" + '<|tool_call_argument_begin|>{"city"' + ': "London"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>", + # A valid follow-up call: must still be parsed. + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:0" + '<|tool_call_argument_begin|>{"city": "Delhi"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>", + ] + + tool_calls, all_content = _collect_streaming_tool_calls( + tc_det, chunks, self.tools + ) + + # The bad call may be skipped/logged, but the follow-up MUST be + # emitted. The stream must not be wedged on the bad header. + valid = [c for c in tool_calls if c.get("name") == "get_weather"] + self.assertEqual(len(valid), 1) + self.assertEqual(valid[0]["parameters"], '{"city": "Delhi"}') + self.assertIn("normal text before", all_content) + + def test_e2e_malformed_json_args_passes_through_to_client(self): + """A tool call with malformed JSON args (e.g. unclosed brace, + spelling mistake) is the **client's** problem to + validate/repair — the parser's job is to locate boundaries and + hand back the raw argument string. This mirrors the + ``detect_and_parse`` (non-streaming) contract. + + Required behavior: + + 1. The malformed call is emitted unchanged (raw bytes + preserved, name + index intact) so the client can decide + how to handle it (reject, repair, replay-prompt, etc). + 2. The stream is not wedged — the trailing valid call must + still parse. + 3. ``current_tool_id`` advances normally — the trailing valid + call sits at index 2, not 1 or 3. + + Asserts the SAME outcome under three chunk layouts: + + * **single-chunk / MTP path** — all three sections in one + forward step (mimics speculative / multi-token-prediction). + * **per-call split path** — one section per chunk. + * **bad section split mid-payload** — the malformed section + itself is fragmented across three chunks (header + partial + args; more args; end-token + trailing valid call). Verifies + the atomic-section buffer correctly defers emission until + ``<|tool_call_end|>`` arrives. + """ + good_args_0 = '{"city": "London"}' + # JSON keyword (the model misspelled ``false``). + bad_args = '{"city": "Bad", "valid": fasle' + good_args_1 = '{"city": "Delhi"}' + + good_section_0 = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:0" + f"<|tool_call_argument_begin|>{good_args_0}" + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + bad_section = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:1" + f"<|tool_call_argument_begin|>{bad_args}" + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + good_section_1 = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:2" + f"<|tool_call_argument_begin|>{good_args_1}" + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + + layouts = { + "mtp_single_chunk": [good_section_0 + bad_section + good_section_1], + "per_call_chunks": [good_section_0, bad_section, good_section_1], + "bad_section_split_mid_payload": [ + good_section_0, + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:1" + f'<|tool_call_argument_begin|>{{"city":', + ' "Bad", "valid": fasle', + "<|tool_call_end|>" "<|tool_calls_section_end|>" + good_section_1, + ], + } + + for layout_name, chunks in layouts.items(): + with self.subTest(layout=layout_name): + tc_det = KimiK2FuncDetector() + tool_calls, _ = _collect_streaming_tool_calls( + tc_det, chunks, self.tools + ) + + # Three contiguous tool calls (good, bad-passthrough, good). + self.assertEqual( + len(tool_calls), + 3, + f"[{layout_name}] expected 3 calls, got: {tool_calls!r}", + ) + self.assertEqual(tool_calls[0]["name"], "get_weather") + self.assertEqual(tool_calls[1]["name"], "get_weather") + self.assertEqual(tool_calls[2]["name"], "get_weather") + self.assertEqual(tool_calls[0]["parameters"], good_args_0) + # Bad payload preserved byte-for-byte for the client. + self.assertEqual(tool_calls[1]["parameters"], bad_args) + self.assertEqual(tool_calls[2]["parameters"], good_args_1) + + def test_e2e_exception_mid_drain_preserves_accumulated_calls(self): + """An exception raised mid-drain must not discard tool calls already + finalized in the same ``parse_streaming_increment`` invocation. + """ + import unittest.mock as mock + + tc_det = KimiK2FuncDetector() + + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:0" + '<|tool_call_argument_begin|>{"city": "London"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:1" + '<|tool_call_argument_begin|>{"city": "Delhi"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ] + + # Force an exception on the SECOND resolution step by making + # ``_resolve_function_name`` raise the second time it is invoked. + call_count = {"n": 0} + real_resolve = tc_det._resolve_function_name + + def flaky_resolve(function_id, tools, function_args=None): + call_count["n"] += 1 + if call_count["n"] >= 2: + raise RuntimeError("forced mid-drain failure") + return real_resolve(function_id, tools, function_args) + + with mock.patch.object( + tc_det, "_resolve_function_name", side_effect=flaky_resolve + ): + tool_calls, all_content = _collect_streaming_tool_calls( + tc_det, chunks, self.tools + ) + + # First call must survive the mid-drain exception. + named = [c for c in tool_calls if c.get("name")] + self.assertGreaterEqual(len(named), 1) + self.assertEqual(named[0]["name"], "get_weather") + self.assertEqual(named[0]["parameters"], '{"city": "London"}') + # Already-finalized call payload must NOT leak into normal_text. + self.assertNotIn('{"city": "London"}', all_content) + self.assertNotIn("<|tool_call_begin|>", all_content) + + def test_e2e_multiple_tool_calls_without_think_close(self): + """Multiple tool calls inside without .""" + reasoning_det = KimiK2ReasoningDetector(stream_reasoning=True) + tc_det = KimiK2FuncDetector() + + chunks = [ + "", + "Let me check both files.", + "<|tool_calls_section_begin|>", + "<|tool_call_begin|>functions.ReadFile:0" + '<|tool_call_argument_begin|>{"path": "/a.py"}', + "<|tool_call_end|>", + "<|tool_call_begin|>functions.ReadFile:1" + '<|tool_call_argument_begin|>{"path": "/b.py"}', + "<|tool_call_end|>", + "<|tool_calls_section_end|>", + ] + + all_reasoning = "" + all_tc_calls = [] + + for chunk in chunks: + r = reasoning_det.parse_streaming_increment(chunk) + all_reasoning += r.reasoning_text + if r.normal_text: + tc_result = tc_det.parse_streaming_increment(r.normal_text, self.tools) + all_tc_calls.extend(tc_result.calls) + + self.assertIn("Let me check both files.", all_reasoning) + self.assertNotIn("<|", all_reasoning) + + name_calls = [c for c in all_tc_calls if c.name] + self.assertEqual(len(name_calls), 2) + self.assertEqual(name_calls[0].name, "ReadFile") + self.assertEqual(name_calls[1].name, "ReadFile") + + +# ============================================================ +# Part 2b: OpenAI streaming-spec compliance for ``tool_index`` +# ============================================================ + + +class TestKimiK2DetectorOpenAIIndexCompliance(unittest.TestCase): + """The detector must emit ``tool_index`` as a dense, 0-based position + within the *current response* (per the OpenAI streaming spec), regardless + of the value of the model's conversation-level ``:N`` counter in the + tool_call header. The serving layer is responsible for adding any + history offset back when synthesizing the public ``id`` field. + + These tests pin the detector contract so multi-turn conversations + (where the model continues an auto-incrementing counter across turns) + can never produce sparse / non-zero-based ``index`` values in the + streamed delta. + """ + + def setUp(self): + self.tools = [ + _make_tool( + "get_weather", + { + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + }, + ), + ] + + def _run(self, chunks): + det = KimiK2FuncDetector() + events = [] + for chunk in chunks: + r = det.parse_streaming_increment(chunk, self.tools) + events.extend(r.calls) + return events + + def test_single_call_with_nonzero_model_counter_starts_at_index_0(self): + """Model continues a conversation-level counter (``:5``) across turns. + The detector must still emit ``tool_index=0`` for the first call in + this response — the model's ``:N`` suffix MUST NOT leak into ``index``. + """ + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:5" + '<|tool_call_argument_begin|>{"city":', + ' "Paris"}<|tool_call_end|><|tool_calls_section_end|>', + ] + events = self._run(chunks) + + self.assertGreaterEqual(len(events), 1) + # Every emitted delta (name event + arg deltas) must use index 0. + for ev in events: + self.assertEqual( + ev.tool_index, + 0, + f"tool_index must be 0-based per response, got {ev.tool_index}", + ) + first = events[0] + self.assertEqual(first.name, "get_weather") + + def test_multi_call_response_uses_dense_0_based_indices(self): + """Two calls in one response, model emits ``:7`` then ``:8``. The + detector must emit ``tool_index=0`` then ``tool_index=1`` (dense, + 0-based), independent of the model's counter. + """ + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:7" + '<|tool_call_argument_begin|>{"city": "London"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:8" + '<|tool_call_argument_begin|>{"city": "Berlin"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ] + events = self._run(chunks) + + name_events = [e for e in events if e.name] + self.assertEqual(len(name_events), 2) + self.assertEqual(name_events[0].tool_index, 0) + self.assertEqual(name_events[1].tool_index, 1) + + # Every delta for call N must carry tool_index == N. + for ev in events: + self.assertIn(ev.tool_index, (0, 1)) + + def test_continuation_chunks_keep_same_tool_index(self): + """Per OpenAI spec, all argument-delta chunks for a given call + must share the same ``index``. Split the args across multiple + chunks and verify ``tool_index`` stays at 0 throughout. + """ + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>functions.get_weather:10" + '<|tool_call_argument_begin|>{"city":', + ' "Pa', + 'ris"}', + "<|tool_call_end|><|tool_calls_section_end|>", + ] + events = self._run(chunks) + + self.assertGreater(len(events), 1, "expected name event + arg deltas") + for ev in events: + self.assertEqual(ev.tool_index, 0) + + # Reassembled args must round-trip. + joined = "".join(ev.parameters or "" for ev in events) + self.assertEqual(joined, '{"city": "Paris"}') + + def test_three_calls_with_nonzero_model_counter_indices_are_dense(self): + """Multi-turn worst case: model continues at ``:10`` and emits three + calls in this response. Indices must be 0, 1, 2 — not 10, 11, 12. + """ + sections = [] + for offset, city in enumerate(("Paris", "Berlin", "Madrid")): + sections.append( + "<|tool_calls_section_begin|>" + f"<|tool_call_begin|>functions.get_weather:{10 + offset}" + f'<|tool_call_argument_begin|>{{"city": "{city}"}}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + events = self._run(["".join(sections)]) + + name_events = [e for e in events if e.name] + self.assertEqual([e.tool_index for e in name_events], [0, 1, 2]) + + def test_bare_counter_id_also_starts_at_index_0(self): + """Same invariant for the bare-counter ID form (model omits function + name and emits just a numeric counter, e.g. ``:5``). + """ + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>5" + '<|tool_call_argument_begin|>{"city": "Paris"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ] + events = self._run(chunks) + + self.assertGreaterEqual(len(events), 1) + for ev in events: + self.assertEqual(ev.tool_index, 0) + + +# ============================================================ +# Part 3: Bare-counter tool call ID parsing +# ============================================================ + + +class TestKimiK2BareCounterParsing(unittest.TestCase): + """Tests for bare numeric tool_call_id format (e.g., '3' instead of 'functions.ReadFile:0').""" + + def setUp(self): + self.detector = KimiK2FuncDetector() + self.tools = [ + _make_tool("ReadFile"), + _make_tool( + "get_weather", + { + "type": "object", + "properties": { + "city": {"type": "string"}, + "unit": {"type": "string"}, + }, + "required": ["city"], + }, + ), + ] + + # --- _parse_tool_call_id --- + + def test_standard_format_with_functions_prefix(self): + name, idx = self.detector._parse_tool_call_id( + "functions.ReadFile:0", self.tools + ) + self.assertEqual(name, "ReadFile") + self.assertEqual(idx, 0) + + def test_standard_format_without_functions_prefix(self): + name, idx = self.detector._parse_tool_call_id("ReadFile:1", self.tools) + self.assertEqual(name, "ReadFile") + self.assertEqual(idx, 1) + + def test_bare_counter_single_tool(self): + single_tool = [_make_tool("search")] + name, idx = self.detector._parse_tool_call_id( + "3", single_tool, '{"query": "test"}' + ) + self.assertEqual(name, "search") + self.assertEqual(idx, 3) + + def test_bare_counter_infers_by_args(self): + name, idx = self.detector._parse_tool_call_id( + "0", self.tools, '{"city": "Tokyo"}' + ) + self.assertEqual(name, "get_weather") + self.assertEqual(idx, 0) + + def test_bare_counter_no_tools_returns_none(self): + name, idx = self.detector._parse_tool_call_id("5", [], '{"x": 1}') + self.assertIsNone(name) + self.assertEqual(idx, 5) + + def test_bare_counter_no_args_multiple_tools_returns_none(self): + name, idx = self.detector._parse_tool_call_id("2", self.tools, None) + self.assertIsNone(name) + self.assertEqual(idx, 2) + + def test_unexpected_format_returns_none(self): + name, idx = self.detector._parse_tool_call_id("some_garbage", self.tools) + self.assertIsNone(name) + self.assertEqual(idx, 0) + + # --- _infer_tool_name --- + + def test_infer_no_tools(self): + self.assertIsNone(self.detector._infer_tool_name([], '{"x": 1}')) + + def test_infer_single_tool(self): + result = self.detector._infer_tool_name([_make_tool("only_one")], '{"x": 1}') + self.assertEqual(result, "only_one") + + def test_infer_by_argument_overlap(self): + result = self.detector._infer_tool_name( + self.tools, '{"city": "Paris", "unit": "celsius"}' + ) + self.assertEqual(result, "get_weather") + + def test_infer_malformed_json_returns_none(self): + result = self.detector._infer_tool_name(self.tools, '{"city": "Par') + self.assertIsNone(result) + + def test_infer_empty_args_returns_none(self): + self.assertIsNone(self.detector._infer_tool_name(self.tools, None)) + self.assertIsNone(self.detector._infer_tool_name(self.tools, "")) + + def test_infer_no_matching_props_returns_none(self): + tools_no_props = [ + _make_tool("a", {"type": "object"}), + _make_tool("b", {"type": "object"}), + ] + result = self.detector._infer_tool_name(tools_no_props, '{"x": 1}') + self.assertIsNone(result) + + # --- detect_and_parse with bare counter (end-to-end) --- + + def test_detect_and_parse_bare_counter(self): + text = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>0" + '<|tool_call_argument_begin|>{"city": "Tokyo"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = self.detector.detect_and_parse(text, self.tools) + self.assertEqual(len(result.calls), 1) + self.assertEqual(result.calls[0].name, "get_weather") + self.assertEqual(result.calls[0].parameters, '{"city": "Tokyo"}') + + def test_detect_and_parse_bare_counter_skips_unknown(self): + text = ( + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>0" + '<|tool_call_argument_begin|>{"unknown_key": "value"}' + "<|tool_call_end|>" + "<|tool_calls_section_end|>" + ) + result = self.detector.detect_and_parse(text, self.tools) + # No tool props match, _infer_tool_name returns None, call is skipped + self.assertEqual(len(result.calls), 0) + + def test_streaming_bare_counter_single_tool(self): + detector = KimiK2FuncDetector() + single_tool = [_make_tool("search")] + chunks = [ + "<|tool_calls_section_begin|>" + "<|tool_call_begin|>0" + '<|tool_call_argument_begin|>{"path', + '": "/test"}', + "<|tool_call_end|>", + "<|tool_calls_section_end|>", + ] + tool_calls, _ = _collect_streaming_tool_calls(detector, chunks, single_tool) + self.assertEqual(len(tool_calls), 1) + self.assertEqual(tool_calls[0]["name"], "search") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/gb300/test_deepseek_v4_pro_fp4.py b/asian_ai/performance/SGLang/test/registered/gb300/test_deepseek_v4_pro_fp4.py new file mode 100644 index 0000000000000000000000000000000000000000..eed0e92d1a3ea7e7eb0aefd10d7018ac52cfab0e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/gb300/test_deepseek_v4_pro_fp4.py @@ -0,0 +1,152 @@ +import unittest + +from sglang.test.accuracy_test_runner import AccuracyTestParams +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.performance_test_runner import PerformanceTestParams +from sglang.test.run_combined_tests import run_combined_tests +from sglang.test.test_utils import ModelLaunchSettings + +register_cuda_ci( + est_time=7200, suite="nightly-4-gpu-gb300-deepseek-v4-pro-fp4", nightly=True +) + +MODEL_PATH = "deepseek-ai/DeepSeek-V4-Pro" +SERVER_LAUNCH_TIMEOUT = 3600 + +DEEPEP_CONFIG = '{"normal_dispatch":{"num_sms":96},"normal_combine":{"num_sms":96}}' + +LOW_LATENCY_ARGS = [ + "--trust-remote-code", + "--moe-runner-backend", + "flashinfer_mxfp4", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--chunked-prefill-size", + "8192", + "--disable-flashinfer-autotune", + "--swa-full-tokens-ratio", + "0.1", + "--mem-fraction-static", + "0.85", +] + +BALANCED_ARGS = [ + "--trust-remote-code", + "--dp", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "deepep", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", + "--mem-fraction-static", + "0.85", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "256", + "--deepep-config", + DEEPEP_CONFIG, +] + +HIGH_THROUGHPUT_ARGS = [ + "--trust-remote-code", + "--dp", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "megamoe", + "--mem-fraction-static", + "0.9", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "256", +] + +BALANCED_ENV = { + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "256", +} + +HIGH_THROUGHPUT_ENV = { + "SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK": "8320", +} + +PERFORMANCE_BATCH_SIZES = { + "low-latency": [1, 4, 16], + "balanced": [64], + "high-throughput": [128], +} + + +class TestDeepSeekV4ProFp4(unittest.TestCase): + """DeepSeek-V4-Pro FP4 on GB300 (4x B200 NVL4, tp=4).""" + + def test_deepseek_v4_pro_fp4(self): + variants = [ + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=LOW_LATENCY_ARGS, + variant="low-latency", + launch_timeout=SERVER_LAUNCH_TIMEOUT, + ), + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=BALANCED_ARGS, + env=BALANCED_ENV, + variant="balanced", + launch_timeout=SERVER_LAUNCH_TIMEOUT, + ), + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=HIGH_THROUGHPUT_ARGS, + env=HIGH_THROUGHPUT_ENV, + variant="high-throughput", + launch_timeout=SERVER_LAUNCH_TIMEOUT, + ), + ] + + failures = [] + accuracy_params = AccuracyTestParams( + dataset="gsm8k", + baseline_accuracy=0.935, + temperature=1.0, + top_p=1.0, + ) + for variant in variants: + try: + run_combined_tests( + models=[variant], + test_name=f"DeepSeek-V4-Pro-FP4 ({variant.variant})", + accuracy_params=accuracy_params, + performance_params=PerformanceTestParams( + batch_sizes=PERFORMANCE_BATCH_SIZES[variant.variant], + profile_dir="performance_profiles_gb300", + ), + ) + except AssertionError as e: + failures.append(f"{variant.variant}: {e}") + + if failures: + raise AssertionError( + "DeepSeek-V4-Pro-FP4 failures:\n" + "\n".join(failures) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/gb300/test_glm52_nvfp4.py b/asian_ai/performance/SGLang/test/registered/gb300/test_glm52_nvfp4.py new file mode 100644 index 0000000000000000000000000000000000000000..767f8799da2d5c34710e62e40721ae5b1d925b47 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/gb300/test_glm52_nvfp4.py @@ -0,0 +1,70 @@ +import unittest + +from sglang.test.accuracy_test_runner import AccuracyTestParams +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.performance_test_runner import PerformanceTestParams +from sglang.test.run_combined_tests import run_combined_tests +from sglang.test.test_utils import ModelLaunchSettings + +register_cuda_ci(est_time=7200, suite="nightly-4-gpu-gb300-glm5-nvfp4", nightly=True) + +MODEL_PATH = "nvidia/GLM-5.2-NVFP4" + +COMMON_ARGS = [ + "--trust-remote-code", + "--reasoning-parser=glm45", + "--tool-call-parser=glm47", + "--quantization=modelopt_fp4", + "--moe-runner-backend=flashinfer_trtllm", + "--mem-fraction-static=0.9", + "--enable-metrics", +] + +TP_MTP_ARGS = [ + "--speculative-algorithm=EAGLE", + "--speculative-num-steps=3", + "--speculative-eagle-topk=1", + "--speculative-num-draft-tokens=4", +] + +DP_MTP_ARGS = [ + "--speculative-algorithm=EAGLE", + "--speculative-num-steps=1", + "--speculative-eagle-topk=1", + "--speculative-num-draft-tokens=2", +] + + +class TestGlm52Nvfp4(unittest.TestCase): + """GLM-5.2 NVFP4 on GB300 (4x GB300 NVL4, tp=4).""" + + def test_glm52_nvfp4(self): + variants = [ + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS + TP_MTP_ARGS, + variant="TP4+MTP", + ), + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS + + ["--dp-size=4", "--enable-dp-attention"] + + DP_MTP_ARGS, + variant="TP4+DP4+DPA+MTP", + ), + ] + + run_combined_tests( + models=variants, + test_name="GLM-5.2-NVFP4", + accuracy_params=AccuracyTestParams(dataset="gsm8k", baseline_accuracy=0.92), + performance_params=PerformanceTestParams( + profile_dir="performance_profiles_gb300", + ), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/gb300/test_kimi_k25.py b/asian_ai/performance/SGLang/test/registered/gb300/test_kimi_k25.py new file mode 100644 index 0000000000000000000000000000000000000000..10af4d4cf52c260cf8f709ffcca5dfb057843871 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/gb300/test_kimi_k25.py @@ -0,0 +1,63 @@ +import unittest + +from sglang.test.accuracy_test_runner import AccuracyTestParams +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.performance_test_runner import PerformanceTestParams +from sglang.test.run_combined_tests import run_combined_tests +from sglang.test.test_utils import ModelLaunchSettings + +register_cuda_ci( + est_time=7200, + suite="nightly-4-gpu-gb300-kimi-k25", + nightly=True, + disabled="not needed", +) + +MODEL_PATH = "moonshotai/Kimi-K2.5" + +COMMON_ARGS = [ + "--trust-remote-code", + "--reasoning-parser=kimi_k2", + "--tool-call-parser=kimi_k2", + "--mem-fraction-static=0.8", + "--enable-multimodal", + "--enable-metrics", +] + + +class TestKimiK25(unittest.TestCase): + """Kimi-K2.5 (native INT4) on GB300 (4x GB300 NVL4, tp=4). + + No EAGLE/MTP support for Kimi-K2.5 — only TP and TP+DP+DPA variants. + """ + + def test_kimi_k25(self): + variants = [ + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS, + variant="TP4", + ), + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS + ["--dp-size=4", "--enable-dp-attention"], + variant="TP4+DP4+DPA", + ), + ] + + run_combined_tests( + models=variants, + test_name="Kimi-K2.5", + accuracy_params=AccuracyTestParams( + dataset="mmmu-pro", baseline_accuracy=0.69, repeat=1, max_tokens=32768 + ), + performance_params=PerformanceTestParams( + profile_dir="performance_profiles_gb300", + ), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/gb300/test_kimi_k25_nvfp4.py b/asian_ai/performance/SGLang/test/registered/gb300/test_kimi_k25_nvfp4.py new file mode 100644 index 0000000000000000000000000000000000000000..22ab08af50fbbe94327b5c944a966284a688ffa5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/gb300/test_kimi_k25_nvfp4.py @@ -0,0 +1,78 @@ +import unittest + +from sglang.test.accuracy_test_runner import AccuracyTestParams +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.performance_test_runner import PerformanceTestParams +from sglang.test.run_combined_tests import run_combined_tests +from sglang.test.test_utils import ModelLaunchSettings + +register_cuda_ci( + est_time=7200, suite="nightly-4-gpu-gb300-kimi-k25-nvfp4", nightly=True +) + +MODEL_PATH = "nvidia/Kimi-K2.5-NVFP4" +DRAFT_MODEL_PATH = "lightseekorg/kimi-k2.5-eagle3-mla" + +COMMON_ARGS = [ + "--trust-remote-code", + "--reasoning-parser=kimi_k2", + "--tool-call-parser=kimi_k2", + "--quantization=modelopt_fp4", + "--attention-backend=tokenspeed_mla", + "--kv-cache-dtype=fp8_e4m3", + "--moe-runner-backend=flashinfer_trtllm", + "--mem-fraction-static=0.8", + "--enable-metrics", + "--speculative-algorithm=EAGLE3", + f"--speculative-draft-model-path={DRAFT_MODEL_PATH}", + "--speculative-draft-model-quantization=unquant", +] + +TP_EAGLE_ARGS = [ + "--speculative-num-steps=3", + "--speculative-eagle-topk=1", + "--speculative-num-draft-tokens=4", +] + +DP_EAGLE_ARGS = [ + "--speculative-num-steps=1", + "--speculative-eagle-topk=1", + "--speculative-num-draft-tokens=2", +] + + +class TestKimiK25Nvfp4(unittest.TestCase): + """Kimi-K2.5 NVFP4 + EAGLE3 on GB300 (4x GB300 NVL4, tp=4).""" + + def test_kimi_k25_nvfp4(self): + variants = [ + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS + TP_EAGLE_ARGS, + variant="TP4+EAGLE3", + ), + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS + + ["--dp-size=4", "--enable-dp-attention"] + + DP_EAGLE_ARGS, + variant="TP4+DP4+DPA+EAGLE3", + ), + ] + + run_combined_tests( + models=variants, + test_name="Kimi-K2.5-NVFP4", + accuracy_params=AccuracyTestParams( + dataset="mmmu-pro", baseline_accuracy=0.69, repeat=1, max_tokens=32768 + ), + performance_params=PerformanceTestParams( + profile_dir="performance_profiles_gb300", + ), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/gb300/test_qwen35_fp8.py b/asian_ai/performance/SGLang/test/registered/gb300/test_qwen35_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..8e27e997d5d663f878c88e0388ca1d15316e1ba2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/gb300/test_qwen35_fp8.py @@ -0,0 +1,74 @@ +import unittest + +from sglang.test.accuracy_test_runner import AccuracyTestParams +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.performance_test_runner import PerformanceTestParams +from sglang.test.run_combined_tests import run_combined_tests +from sglang.test.test_utils import ModelLaunchSettings + +register_cuda_ci(est_time=7200, suite="nightly-4-gpu-gb300-qwen35-fp8", nightly=True) + +MODEL_PATH = "Qwen/Qwen3.5-397B-A17B-FP8" + +COMMON_ARGS = [ + "--trust-remote-code", + "--reasoning-parser=qwen3", + "--tool-call-parser=qwen3_coder", + "--enable-flashinfer-allreduce-fusion", + "--attention-backend=trtllm_mha", + "--mem-fraction-static=0.8", + "--mamba-scheduler-strategy=extra_buffer", + "--enable-multimodal", + "--enable-metrics", +] + +TP_MTP_ARGS = [ + "--speculative-algorithm=EAGLE", + "--speculative-num-steps=3", + "--speculative-eagle-topk=1", + "--speculative-num-draft-tokens=4", +] + +DP_MTP_ARGS = [ + "--speculative-algorithm=EAGLE", + "--speculative-num-steps=1", + "--speculative-eagle-topk=1", + "--speculative-num-draft-tokens=2", +] + + +class TestQwen35Fp8(unittest.TestCase): + """Qwen3.5-397B FP8 on GB300 (4x GB300 NVL4, tp=4).""" + + def test_qwen35_fp8(self): + variants = [ + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS + TP_MTP_ARGS, + variant="TP4+MTP", + ), + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS + + ["--dp-size=4", "--enable-dp-attention"] + + DP_MTP_ARGS, + variant="TP4+DP4+DPA+MTP", + ), + ] + + run_combined_tests( + models=variants, + test_name="Qwen3.5-397B-FP8", + accuracy_params=AccuracyTestParams( + dataset="mmmu-pro", baseline_accuracy=0.76, repeat=1, max_tokens=32768 + ), + performance_params=PerformanceTestParams( + profile_dir="performance_profiles_gb300", + ), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/gb300/test_qwen35_nvfp4.py b/asian_ai/performance/SGLang/test/registered/gb300/test_qwen35_nvfp4.py new file mode 100644 index 0000000000000000000000000000000000000000..d2facb88d04e786ad5454288935835994f6bbcad --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/gb300/test_qwen35_nvfp4.py @@ -0,0 +1,83 @@ +import unittest + +from sglang.test.accuracy_test_runner import AccuracyTestParams +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.performance_test_runner import PerformanceTestParams +from sglang.test.run_combined_tests import run_combined_tests +from sglang.test.test_utils import ModelLaunchSettings + +register_cuda_ci( + est_time=7200, + suite="nightly-4-gpu-gb300-qwen35-nvfp4", + nightly=True, + disabled="not needed", +) + +MODEL_PATH = "nvidia/Qwen3.5-397B-A17B-NVFP4" + +COMMON_ARGS = [ + "--trust-remote-code", + "--reasoning-parser=qwen3", + "--tool-call-parser=qwen3_coder", + "--quantization=modelopt_fp4", + "--fp4-gemm-backend=flashinfer_cutlass", + "--moe-runner-backend=flashinfer_trtllm", + "--kv-cache-dtype=fp8_e4m3", + "--enable-flashinfer-allreduce-fusion", + "--attention-backend=trtllm_mha", + "--mem-fraction-static=0.8", + "--enable-multimodal", + "--enable-metrics", +] + +MTP_ARGS = [ + "--speculative-algorithm=EAGLE", + "--speculative-num-steps=3", + "--speculative-eagle-topk=1", + "--speculative-num-draft-tokens=4", + "--mamba-scheduler-strategy=extra_buffer", + "--page-size=64", +] + + +class TestQwen35Nvfp4(unittest.TestCase): + """Qwen3.5-397B NVFP4 on GB300 (4x GB300 NVL4, tp=4).""" + + def test_qwen35_nvfp4(self): + variants = [ + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS, + variant="TP4", + ), + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS + ["--dp-size=4", "--enable-dp-attention"], + variant="TP4+DP4+DPA", + ), + ModelLaunchSettings( + MODEL_PATH, + tp_size=4, + extra_args=COMMON_ARGS + + ["--dp-size=4", "--enable-dp-attention"] + + MTP_ARGS, + variant="TP4+DP4+DPA+MTP", + ), + ] + + run_combined_tests( + models=variants, + test_name="Qwen3.5-397B-NVFP4", + accuracy_params=AccuracyTestParams( + dataset="mmmu-pro", baseline_accuracy=0.76, repeat=1, max_tokens=32768 + ), + performance_params=PerformanceTestParams( + profile_dir="performance_profiles_gb300", + ), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_spec_file_storage.py b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_spec_file_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad0e8c3d9848586423171fa9b6d3975af4649d6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_spec_file_storage.py @@ -0,0 +1,89 @@ +""" +E2E test for HiCache file storage with EAGLE3 speculative decoding. + +Usage: + python3 -m pytest test/registered/hicache/test_hicache_spec_file_storage.py -v +""" + +import os +import shutil +import tempfile +import time +import unittest + +from sglang.srt.mem_cache.hicache_storage import PoolName +from sglang.srt.utils import is_hip +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.hicache_spec_storage_common import HiCacheSpecStorageMixin +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=200, stage="extra-a", runner_config="1-gpu-large") + + +@unittest.skipIf(is_hip(), "HiCache + EAGLE3 file-storage loadback e2e is CUDA-only.") +class TestHiCacheSpecFileStorage(HiCacheSpecStorageMixin, CustomTestCase): + storage_backend = "file" + expected_storage_backend = "HiCacheFile" + storage_wait_timeout = 30 + + @classmethod + def setUpClass(cls): + cls.temp_dir = tempfile.mkdtemp() + cls.process = None + cls._launch_spec_server() + + @classmethod + def _get_spec_server_env(cls): + return {"SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIR": cls.temp_dir} + + @classmethod + def _count_file_storage_pages(cls): + try: + filenames = os.listdir(cls.temp_dir) + except FileNotFoundError: + return 0, 0 + + target_pages = 0 + draft_pages = 0 + for filename in filenames: + if not filename.endswith(".bin"): + continue + if f".{PoolName.DRAFT}" in filename: + draft_pages += 1 + else: + target_pages += 1 + return target_pages, draft_pages + + @classmethod + def _wait_for_file_storage_pages(cls): + min_pages = (cls.input_token_len - 2 * cls.page_size) // cls.page_size + deadline = time.monotonic() + cls.storage_wait_timeout + target_pages = draft_pages = 0 + + while time.monotonic() < deadline: + target_pages, draft_pages = cls._count_file_storage_pages() + if target_pages >= min_pages and draft_pages >= min_pages: + return target_pages, draft_pages + time.sleep(0.2) + + raise AssertionError( + "Timed out waiting for HiCache file storage pages before restart: " + f"{target_pages=}, {draft_pages=}, {min_pages=}" + ) + + @classmethod + def tearDownClass(cls): + cls._stop_spec_server() + if hasattr(cls, "temp_dir"): + shutil.rmtree(cls.temp_dir, ignore_errors=True) + + def _wait_for_storage_before_restart(self): + target_pages, draft_pages = self._wait_for_file_storage_pages() + print(f"file_storage_before_restart: {target_pages=}, {draft_pages=}") + + def test_file_storage_loadback_keeps_spec_accept_length(self): + self._run_storage_loadback_keeps_spec_accept_length() + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_spec_mooncake_storage.py b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_spec_mooncake_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..329acf979a2c422d3f234655fe897dc51b551faa --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_spec_mooncake_storage.py @@ -0,0 +1,187 @@ +""" +E2E test for HiCache mooncake storage with EAGLE3 speculative decoding. + +Verifies that after a server restart, both target and draft KV cache for a +long deterministic prompt are reloaded from the mooncake_master process and +the spec accept length does not regress. + +Mooncake_master + http metadata server lifecycle is reused from +``test_hicache_storage_mooncake_backend.HiCacheStorageMooncakeBackendBaseMixin``; +this file only overrides the SGLang-side setup for EAGLE3 + spec loadback. + +Usage: + python3 -m pytest test/registered/hicache/test_hicache_spec_mooncake_storage.py -v +""" + +import os +import signal +import socket +import subprocess +import time +import unittest + +from test_hicache_storage_mooncake_backend import ( + HiCacheStorageMooncakeBackendBaseMixin, +) + +from sglang.srt.utils import is_hip +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.hicache_spec_storage_common import HiCacheSpecStorageMixin +from sglang.test.test_utils import CustomTestCase, find_available_port + +register_cuda_ci(est_time=240, stage="extra-a", runner_config="2-gpu-large") + + +@unittest.skipIf( + is_hip(), "HiCache + EAGLE3 mooncake-storage loadback e2e is CUDA-only." +) +class TestHiCacheSpecMooncakeStorage( + HiCacheSpecStorageMixin, HiCacheStorageMooncakeBackendBaseMixin, CustomTestCase +): + """EAGLE3 + mooncake L3 loadback. After a server restart the long + deterministic prompt's target+draft KV must be reloaded from + mooncake_master and the spec accept length must not regress.""" + + storage_backend = "mooncake" + expected_storage_backend = "MooncakeStore" + # Mooncake exposes no external page count; wait this long after the + # first prompt for HiCacheController's backup queue to drain into the + # mooncake_master before restart. + mooncake_backup_drain_seconds = 15 + mooncake_store_port_base = 50052 + mooncake_store_http_port_base = 8081 + + # The inherited test from HiCacheStorageBaseMixin assumes a basic-storage + # setup; it is already covered by test_hicache_storage_mooncake_backend.py. + @unittest.skip("Covered by test_hicache_storage_mooncake_backend.py") + def test_basic_backup_and_prefetch(self): # noqa: D401 + pass + + @classmethod + def setUpClass(cls): + # Bypass the parent chain's basic-storage server bootstrap; only + # reuse the inherited mooncake_master / metadata-server lifecycle. + cls.mooncake_master_port = find_available_port(cls.mooncake_master_port_base) + cls.mooncake_metadata_port = find_available_port( + cls.mooncake_metadata_port_base + ) + cls.mooncake_store_port = find_available_port(cls.mooncake_store_port_base) + cls.mooncake_store_http_port = find_available_port( + cls.mooncake_store_http_port_base + ) + cls._start_mooncake_services() + try: + cls._start_mooncake_store_service() + cls._launch_spec_server() + except Exception: + cls._stop_mooncake_store_service() + cls._stop_mooncake_services() + raise + + @classmethod + def tearDownClass(cls): + try: + cls._stop_spec_server() + finally: + cls._stop_mooncake_store_service() + cls._stop_mooncake_services() + + # ---- server side ---- + + @classmethod + def _start_mooncake_store_service(cls): + print( + f"Starting Mooncake store service on rpc port {cls.mooncake_store_port}, " + f"http port {cls.mooncake_store_http_port}..." + ) + cls.store_service_process = subprocess.Popen( + [ + "mooncake_client", + "--host=127.0.0.1", + f"--port={cls.mooncake_store_port}", + f"--master_server_address=127.0.0.1:{cls.mooncake_master_port}", + f"--metadata_server=http://127.0.0.1:{cls.mooncake_metadata_port}/metadata", + "--protocol=tcp", + "--device_names=", + "--global_segment_size=4294967296", + "--enable_http_server=true", + f"--http_port={cls.mooncake_store_http_port}", + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + preexec_fn=os.setsid, + ) + cls._wait_for_mooncake_store_service_ready() + + @classmethod + def _wait_for_mooncake_store_service_ready(cls, timeout: int = 90): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + process = getattr(cls, "store_service_process", None) + if process is not None and process.poll() is not None: + raise RuntimeError( + f"Mooncake store service exited with code {process.returncode}" + ) + try: + with socket.create_connection( + ("127.0.0.1", cls.mooncake_store_port), timeout=2 + ): + pass + print("Mooncake store service is ready") + return + except OSError: + pass + time.sleep(1) + raise TimeoutError("Timed out waiting for Mooncake store service readiness.") + + @classmethod + def _stop_mooncake_store_service(cls): + process = getattr(cls, "store_service_process", None) + if process is None: + return + print("Stopping Mooncake store service...") + try: + os.killpg(os.getpgid(process.pid), signal.SIGTERM) + process.wait(timeout=15) + print("Mooncake store service stopped") + except (ProcessLookupError, subprocess.TimeoutExpired, OSError): + try: + os.killpg(os.getpgid(process.pid), signal.SIGKILL) + process.wait(timeout=5) + except (ProcessLookupError, subprocess.TimeoutExpired, OSError) as e: + print(f"Warning: Could not stop Mooncake store service: {e}") + finally: + cls.store_service_process = None + + @classmethod + def _get_spec_server_env(cls): + return { + "MOONCAKE_MASTER": f"127.0.0.1:{cls.mooncake_master_port}", + "MOONCAKE_PROTOCOL": "tcp", + "MC_MS_AUTO_DISC": "0", + "MOONCAKE_DEVICE": "", + "MOONCAKE_TE_META_DATA_SERVER": ( + f"http://127.0.0.1:{cls.mooncake_metadata_port}/metadata" + ), + # Keep storage capacity in the external mooncake_client so cached + # pages survive SGLang server restart. + "MOONCAKE_GLOBAL_SEGMENT_SIZE": "0", + } + + # ---- prompt / IO helpers ---- + + def _wait_for_storage_before_restart(self): + print( + f"[mooncake] draining backup queue " + f"({self.mooncake_backup_drain_seconds}s)..." + ) + time.sleep(self.mooncake_backup_drain_seconds) + + # ---- the test ---- + + def test_mooncake_storage_loadback_keeps_spec_accept_length(self): + self._run_storage_loadback_keeps_spec_accept_length() + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage.py b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..a4475de3b2fe23a4db067403fd2e8e760be66de4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage.py @@ -0,0 +1,55 @@ +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=99, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=300, suite="stage-b-test-1-gpu-small-amd") + +import time +import unittest + +from sglang.srt.utils import is_hip, kill_process_tree +from sglang.test.kits.eval_accuracy_kit import MMLUMixin +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +_is_hip = is_hip() + + +class TestHiCache(CustomTestCase, MMLUMixin): + mmlu_score_threshold = 0.65 + mmlu_num_examples = 64 + mmlu_num_threads = 32 + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--enable-hierarchical-cache", + "--mem-fraction-static", + 0.7, + "--hicache-size", + 100 if not _is_hip else 200, + "--page-size", + "64", + "--hicache-storage-backend", + "file", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + time.sleep(5) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_3fs_backend.py b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_3fs_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb6520e594d8d9028743d656fbb54eac6eef231 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_3fs_backend.py @@ -0,0 +1,92 @@ +""" +Benchmark tests for HiCache Storage with 3FS backend. +Usage: + python3 -m pytest test/registered/hicache/test_hicache_storage_3fs_backend.py -v +""" + +import json +import os +import unittest + +from test_hicache_storage_file_backend import HiCacheStorageBaseMixin + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=300, stage="base-c", runner_config="4-gpu-h100") +register_amd_ci(est_time=300, suite="base-b-test-2-gpu-large") + + +class HiCacheStorage3FSBackendBaseMixin(HiCacheStorageBaseMixin): + """Base mixin class with common setup and utilities""" + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + # Create a temporary JSON config file for HF3FS + hf3fs_config = { + "file_path_prefix": os.path.join(cls.temp_dir, "hicache"), + "file_size": 1024 * 1024 * 1024 * 2, + "numjobs": 2, + "entries": 8, + "use_mock_hf3fs_client": True, + "hicache_storage_pass_prefix_keys": True, + } + + # Write config to temporary file + config_file = os.path.join(cls.temp_dir, "hf3fs_config.json") + with open(config_file, "w") as f: + json.dump(hf3fs_config, f, indent=2) + + server_args = { + "--tp-size": 1, + "--hicache-ratio": 1.2, + "--hicache-storage-backend": "hf3fs", + "--hicache-storage-backend-extra-config": json.dumps(hf3fs_config), + } + + # Set the environment variable to point to our config file + env_vars = { + "SGLANG_HICACHE_HF3FS_CONFIG_PATH": config_file, + } + + return server_args, env_vars + + +class TestHf3fsBackendLayerFirstLayout( + HiCacheStorage3FSBackendBaseMixin, CustomTestCase +): + """Layer first layout tests for HiCache-Hf3fs backend""" + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args, env_vars = super()._get_additional_server_args_and_env() + server_args["--hicache-mem-layout"] = "layer_first" + server_args["--hicache-io-backend"] = "direct" + server_args["--tp-size"] = 2 + return server_args, env_vars + + +class TestHf3fsBackendAccuracy(HiCacheStorage3FSBackendBaseMixin, CustomTestCase): + """Accuracy tests for HiCache-Hf3fs backend""" + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args, env_vars = super()._get_additional_server_args_and_env() + server_args["--hicache-ratio"] = 1.5 + server_args["--tp-size"] = 2 + server_args["--hicache-mem-layout"] = "page_first_direct" + server_args["--hicache-io-backend"] = "direct" + return server_args, env_vars + + def test_eval_accuracy(self): + """Test eval accuracy with cache persistence across cache flushes""" + from test_hicache_storage_file_backend import run_eval_accuracy_test + + run_eval_accuracy_test(self) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_file_backend.py b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_file_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb12ae8c3e4800d0bd8f0fa958788cbad3162a2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_file_backend.py @@ -0,0 +1,335 @@ +""" +E2E tests for HiCache Storage functionality. +Usage: + python3 -m pytest test/registered/hicache/test_hicache_storage_file_backend.py -v +""" + +import json +import os +import random +import tempfile +import time +import unittest +from types import SimpleNamespace +from typing import Dict +from urllib.parse import urlparse + +import requests + +from sglang.benchmark.utils import get_tokenizer +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_MLA_MODEL_NAME_FOR_TEST, + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, +) +from sglang.utils import wait_for_http_ready + +register_cuda_ci(est_time=148, stage="base-b", runner_config="2-gpu-large") +register_amd_ci(est_time=526, suite="stage-b-test-2-gpu-large-amd") + + +class HiCacheStorageBaseMixin: + """Base mixin class with common setup and utilities""" + + @classmethod + def setUpClass(cls): + """Set up test environment and launch server once for all tests""" + cls.temp_dir = tempfile.mkdtemp() + cls.model = cls._get_model_name() + cls.base_url = DEFAULT_URL_FOR_TEST + + parsed_url = urlparse(cls.base_url) + cls.base_host = parsed_url.hostname + cls.base_port = str(parsed_url.port) + + # Prepare tokenizer for prompt generation + cls.tokenizer = get_tokenizer(cls.model) + + # Launch server with HiCache enabled and cache report + cls.process = cls._launch_server_with_hicache() + cls._wait_for_server_ready(process=cls.process) + + print(f"Test server launched successfully at {cls.base_url}") + print(f"Cache directory: {cls.temp_dir}") + + @classmethod + def tearDownClass(cls): + """Clean up test environment""" + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + import shutil + + if hasattr(cls, "temp_dir"): + shutil.rmtree(cls.temp_dir, ignore_errors=True) + + @classmethod + def _get_model_name(cls): + """Get model name for the test configuration - override in subclasses""" + return DEFAULT_MODEL_NAME_FOR_TEST + + @classmethod + def _get_base_server_args(cls): + """Get base server arguments - can be extended in subclasses""" + extra_config = { + "hicache_storage_pass_prefix_keys": True, + } + return { + "--enable-hierarchical-cache": True, + "--mem-fraction-static": 0.6, + "--hicache-ratio": 1.2, + "--page-size": 64, + "--enable-cache-report": True, + "--hicache-storage-prefetch-policy": "wait_complete", + "--hicache-storage-backend": "file", + "--hicache-storage-backend-extra-config": json.dumps(extra_config), + } + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + return {}, {"SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIR": cls.temp_dir} + + @classmethod + def _launch_server_with_hicache(cls): + """Launch server with HiCache enabled""" + + additional_server_args, env_vars = cls._get_additional_server_args_and_env() + env_vars["SGLANG_ENABLE_DETERMINISTIC_INFERENCE"] = "1" + server_args = cls._get_base_server_args() + if additional_server_args: + server_args.update(additional_server_args) + + final_server_args = [] + for k, v in server_args.items(): + if isinstance(v, bool): + final_server_args.append(str(k)) + else: + final_server_args.append(str(k)) + final_server_args.append(str(v)) + + print(f"final_server_args: {final_server_args}") + + env_vars = { + **os.environ, + **env_vars, + } + + return popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=final_server_args, + env=env_vars, + ) + + @classmethod + def _wait_for_server_ready(cls, timeout: int = 60, process=None) -> bool: + """Wait for server to be ready""" + wait_for_http_ready( + url=f"{cls.base_url}/health", + timeout=timeout, + process=process, + ) + return True + + def send_request( + self, prompt: str, max_tokens: int = 100, temperature: float = 0.0 + ) -> Dict: + """Send a generate request and return response""" + response = requests.post( + f"{self.base_url}/generate", + json={ + "text": prompt, + "sampling_params": { + "temperature": temperature, + "max_new_tokens": max_tokens, + "ignore_eos": True, + }, + }, + timeout=60, + ) + + self.assertEqual( + response.status_code, + 200, + f"Request failed: {response.status_code} - {response.text}", + ) + return response.json() + + def get_cached_tokens(self, response_json: Dict) -> int: + """Extract cached tokens count from /generate response""" + meta = response_json.get("meta_info", {}) + return int(meta.get("cached_tokens", 0)) + + def flush_cache(self): + """Flush device cache to force remote storage access.""" + res = requests.post( + f"{self.base_url}/flush_cache", + params={"timeout": 30}, + timeout=40, + ) + res.raise_for_status() + + def gen_prompt(self, token_num: int) -> str: + """Generate a random prompt of specified token length using tokenizer vocabulary.""" + all_available_tokens = list(self.tokenizer.get_vocab().values()) + selected_tokens = random.choices(all_available_tokens, k=token_num) + return self.tokenizer.decode(selected_tokens) + + def trigger_offloading_and_flush(self): + """Helper method to trigger offloading and flush cache""" + # Trigger offloading + self.send_request(self.gen_prompt(1), max_tokens=150) + + # Flush device cache to force remote storage access + self.flush_cache() + + def test_basic_backup_and_prefetch(self): + """Test storage and retrieval of large context through remote cache""" + print("\n=== Testing Large Context Cache Storage & Retrieval ===") + + # Generate substantial context that will be cached + base_prompt = self.gen_prompt(768) + + # First request - populate cache + print("Step 1: Populating cache with large context...") + response1 = self.send_request(base_prompt, max_tokens=150) + self.assertIsNotNone(response1) + + # Flush device cache to force remote storage access + self.trigger_offloading_and_flush() + + # Second request with extended prompt - should hit remote cache + print("Step 2: Testing cache hit from remote storage...") + + start_time = time.time() + response2 = self.send_request(base_prompt, max_tokens=150) + retrieval_time = time.time() - start_time + + cached_tokens = self.get_cached_tokens(response2) + print( + f"Remote cache retrieval time: {retrieval_time:.3f}s, cached_tokens={cached_tokens}" + ) + + # Assert cached tokens indicate a remote hit + self.assertGreater( + cached_tokens, 700, "Expected significant cached tokens for remote hit" + ) + + +@unittest.skipIf(is_in_ci(), "To reduce the CI execution time.") +class TestHiCacheStoragePageFirstLayout(HiCacheStorageBaseMixin, CustomTestCase): + """Page first layout tests for HiCache Storage functionality""" + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args = {"--hicache-mem-layout": "page_first"} + return server_args, {} + + +@unittest.skipIf(is_in_ci(), "To reduce the CI execution time.") +class TestHiCacheStorageMLA(HiCacheStorageBaseMixin, CustomTestCase): + """MLA Model tests for HiCache Storage functionality""" + + @classmethod + def _get_model_name(cls): + """Use MLA model for testing""" + return DEFAULT_MLA_MODEL_NAME_FOR_TEST + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args = {"--tp-size": 2} + return server_args, {} + + +class TestHiCacheStoragePageFirstDirectIO(HiCacheStorageBaseMixin, CustomTestCase): + """Page first direct tests for HiCache Storage functionality""" + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args = { + "--hicache-mem-layout": "page_first_direct", + "--hicache-io-backend": "direct", + "--tp-size": 2, + } + return server_args, {} + + +class TestHiCacheStorageAccuracy(HiCacheStorageBaseMixin, CustomTestCase): + """Accuracy tests for HiCache Storage functionality""" + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args = { + "--tp-size": 2, + "--hicache-ratio": 1.5, + } + + return server_args, {} + + @unittest.skipIf(is_in_ci(), "To skip flaky test") + def test_eval_accuracy(self): + """Test eval accuracy with cache persistence across cache flushes""" + run_eval_accuracy_test(self) + + +def run_eval_accuracy_test(test_instance, accuracy_threshold: float = 0.03): + """Generic eval accuracy test with configurable accuracy threshold + + Args: + test_instance: The test class instance that provides base_host, base_port, flush_cache, and assert methods + """ + print("\n=== Testing Eval Accuracy with Cache Persistence ===") + + # First evaluation - populate cache + print("Phase 1: Running initial GSM8K evaluation to populate cache...") + args_initial = SimpleNamespace( + base_url=f"http://{test_instance.base_host}:{test_instance.base_port}", + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=64, + ) + metrics_initial = run_eval(args_initial) + + # Flush cache to force remote storage access + print("Phase 2: Flushing device cache...") + test_instance.flush_cache() + + # Second evaluation - should use remote cache + print("Phase 3: Running second GSM8K evaluation using remote cache...") + metrics_cached = run_eval(args_initial) + + # Verify accuracy consistency + accuracy_diff = abs(metrics_initial["score"] - metrics_cached["score"]) + print(f"Accuracy difference: {accuracy_diff:.4f}") + + # Assertions + test_instance.assertGreater( + metrics_initial["score"], 0.6, "Initial accuracy should be reasonable" + ) + test_instance.assertGreater( + metrics_cached["score"], 0.6, "Cached accuracy should be reasonable" + ) + test_instance.assertLess( + accuracy_diff, + accuracy_threshold, + "Accuracy should be consistent between cache states", + ) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_mooncake_backend.py b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_mooncake_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..44ee7ad6313493a93a06c0e3b51d08baec609111 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_mooncake_backend.py @@ -0,0 +1,320 @@ +""" +Benchmark tests for HiCache Storage with Mooncake backend. +Usage: + python3.10 -m pytest test/registered/hicache/test_hicache_storage_mooncake_backend.py -v +""" + +import os +import subprocess +import time +import unittest + +import requests +from test_hicache_storage_file_backend import HiCacheStorageBaseMixin + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_MLA_MODEL_NAME_FOR_TEST, + CustomTestCase, + find_available_port, + get_gpu_count, + is_in_ci, +) + +register_cuda_ci(est_time=236, stage="base-b", runner_config="2-gpu-large") + + +class HiCacheStorageMooncakeBackendBaseMixin(HiCacheStorageBaseMixin): + """Base mixin class with common setup and utilities""" + + # Default port ranges for Mooncake services - can be overridden in subclasses + mooncake_master_port_base = 50051 + mooncake_metadata_port_base = 8080 + + @classmethod + def setUpClass(cls): + """Set up test environment and launch Mooncake services before server setup""" + # Find available ports for Mooncake services to avoid conflicts + cls.mooncake_master_port = find_available_port( + HiCacheStorageMooncakeBackendBaseMixin.mooncake_master_port_base + ) + cls.mooncake_metadata_port = find_available_port( + HiCacheStorageMooncakeBackendBaseMixin.mooncake_metadata_port_base + ) + + # Start Mooncake services first + cls._start_mooncake_services() + + # Call parent setup + super().setUpClass() + + @classmethod + def tearDownClass(cls): + """Clean up Mooncake services after server teardown""" + # Call parent teardown first + super().tearDownClass() + + # Stop Mooncake services + cls._stop_mooncake_services() + + @classmethod + def _start_mooncake_services(cls): + """Start Mooncake metadata and master services with configurable ports and readiness detection""" + print("Starting Mooncake services...") + print( + f"Using master port: {cls.mooncake_master_port}, metadata port: {cls.mooncake_metadata_port}" + ) + + # Start metadata service with configurable port + try: + # Start metadata server with port configuration + cls.metadata_service_process = subprocess.Popen( + [ + "python3", + "-m", + "mooncake.http_metadata_server", + "--port", + str(cls.mooncake_metadata_port), + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + preexec_fn=os.setsid, # Create new process group + ) + print( + f"Mooncake metadata service started on port {cls.mooncake_metadata_port}" + ) + except (FileNotFoundError, subprocess.SubprocessError) as e: + print(f"Warning: Could not start Mooncake metadata service: {e}") + cls.metadata_service_process = None + + # Start master service with configurable port + try: + # Start master server with port configuration + cls.master_service_process = subprocess.Popen( + ["mooncake_master", "--port", str(cls.mooncake_master_port)], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + preexec_fn=os.setsid, # Create new process group + ) + print(f"Mooncake master service started on port {cls.mooncake_master_port}") + except (FileNotFoundError, subprocess.SubprocessError) as e: + print(f"Warning: Could not start Mooncake master service: {e}") + cls.master_service_process = None + + # Wait for services to be ready instead of fixed sleep + cls._wait_for_mooncake_services_ready() + + @classmethod + def _wait_for_mooncake_services_ready(cls, timeout: int = 30) -> bool: + """Wait for Mooncake services to be ready by checking their endpoints""" + print("Waiting for Mooncake services to be ready...") + + start_time = time.time() + services_ready = False + + while time.time() - start_time < timeout: + try: + # Check metadata service + metadata_ready = False + if ( + cls.metadata_service_process + and cls.metadata_service_process.poll() is None + ): + try: + # Try to connect to the metadata service + metadata_url = ( + f"http://127.0.0.1:{cls.mooncake_metadata_port}/metadata" + ) + response = requests.get(metadata_url, timeout=2) + if response.status_code == 200: + metadata_ready = True + print("Mooncake metadata service is ready") + except (requests.RequestException, ConnectionError): + # Service might not be fully started yet + pass + + # Check master service (if it has a health endpoint) + master_ready = False + if ( + cls.master_service_process + and cls.master_service_process.poll() is None + ): + # For now, we'll assume master service is ready if process is running + # and it's been a few seconds since startup + if ( + time.time() - start_time > 5 + ): # Give master service time to initialize + master_ready = True + print("Mooncake master service is ready") + + # Both services should be ready + if metadata_ready and master_ready: + services_ready = True + print("All Mooncake services are ready") + break + + except Exception as e: + print(f"Error checking service readiness: {e}") + + time.sleep(2) + + if not services_ready: + print( + "Warning: Mooncake services may not be fully ready, continuing anyway..." + ) + + return services_ready + + @classmethod + def _stop_mooncake_services(cls): + """Stop Mooncake services""" + print("Stopping Mooncake services...") + + # Stop metadata service + if hasattr(cls, "metadata_service_process") and cls.metadata_service_process: + try: + os.killpg(os.getpgid(cls.metadata_service_process.pid), 9) + cls.metadata_service_process.wait(timeout=5) + print("Mooncake metadata service stopped") + except (ProcessLookupError, subprocess.TimeoutExpired, OSError) as e: + print(f"Warning: Could not stop Mooncake metadata service: {e}") + + # Stop master service + if hasattr(cls, "master_service_process") and cls.master_service_process: + try: + os.killpg(os.getpgid(cls.master_service_process.pid), 9) + cls.master_service_process.wait(timeout=5) + print("Mooncake master service stopped") + except (ProcessLookupError, subprocess.TimeoutExpired, OSError) as e: + print(f"Warning: Could not stop Mooncake master service: {e}") + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + + server_args = { + "--tp-size": 2, + "--hicache-ratio": 2, + "--hicache-storage-backend": "mooncake", + } + + # Set the environment variables for Mooncake using dynamic ports + env_vars = { + "MOONCAKE_MASTER": f"127.0.0.1:{cls.mooncake_master_port}", + "MOONCAKE_PROTOCOL": "tcp", + "MC_MS_AUTO_DISC": "0", + "MOONCAKE_DEVICE": "", + "MOONCAKE_TE_META_DATA_SERVER": f"http://127.0.0.1:{cls.mooncake_metadata_port}/metadata", + "MOONCAKE_GLOBAL_SEGMENT_SIZE": "4294967296", # 4 GiB + } + + return server_args, env_vars + + +''' +# Same as #10131, layer first layout test TODO(mateng): will make it work +class TestMooncakeBackendLayerFirstLayout( + HiCacheStorageMooncakeBackendBaseMixin, CustomTestCase +): + """Layer first layout tests for HiCache-Mooncake backend""" + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args, env_vars = super()._get_additional_server_args_and_env() + server_args["--hicache-mem-layout"] = "layer_first" + server_args["--hicache-io-backend"] = "direct" + return server_args, env_vars +''' + + +@unittest.skipIf(is_in_ci(), "To reduce the CI execution time.") +class TestMooncakeBackendPageFirstLayout( + HiCacheStorageMooncakeBackendBaseMixin, CustomTestCase +): + """Page first layout tests for HiCache-Mooncake backend""" + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args, env_vars = super()._get_additional_server_args_and_env() + server_args["--hicache-mem-layout"] = "page_first" + return server_args, env_vars + + +class TestMooncakeBackendMLAModel( + HiCacheStorageMooncakeBackendBaseMixin, CustomTestCase +): + """MLA Model tests for HiCache-Mooncake backend""" + + @classmethod + def _get_model_name(cls): + """Use MLA model for testing""" + return DEFAULT_MLA_MODEL_NAME_FOR_TEST + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args, env_vars = super()._get_additional_server_args_and_env() + server_args["--hicache-mem-layout"] = "page_first" + server_args["--tp-size"] = 2 + return server_args, env_vars + + +@unittest.skipUnless(get_gpu_count() >= 2, "Requires at least 2 CUDA GPUs for TP2+CP2") +class TestMooncakeBackendQwen330BCP2( + HiCacheStorageMooncakeBackendBaseMixin, CustomTestCase +): + """Qwen3-30B with Mooncake HiCache storage, CP2, and TP2.""" + + @classmethod + def _get_model_name(cls): + return "Qwen/Qwen3-30B-A3B-FP8" + + @classmethod + def _get_additional_server_args_and_env(cls): + server_args, env_vars = super()._get_additional_server_args_and_env() + server_args.update( + { + "--tp-size": 2, + "--moe-dp-size": 2, + "--attn-cp-size": 2, + "--enable-prefill-context-parallel": True, + "--trust-remote-code": True, + "--cuda-graph-max-bs-decode": 32, + "--max-running-requests": 32, + "--max-total-tokens": 8192, + "--model-loader-extra-config": ( + '{"enable_multithread_load": true, "num_threads": 64}' + ), + "--hicache-mem-layout": "page_first_direct", + "--hicache-io-backend": "direct", + } + ) + return server_args, env_vars + + +class TestMooncakeBackendAccuracy( + HiCacheStorageMooncakeBackendBaseMixin, CustomTestCase +): + """Accuracy tests for HiCache-Mooncake backend""" + + @classmethod + def _get_additional_server_args_and_env(cls): + """Get additional server arguments specific to configuration - override in subclasses""" + server_args, env_vars = super()._get_additional_server_args_and_env() + server_args["--hicache-ratio"] = 1.5 + server_args["--tp-size"] = 2 + server_args["--hicache-mem-layout"] = "page_first_direct" + server_args["--hicache-io-backend"] = "direct" + return server_args, env_vars + + def test_eval_accuracy(self): + """Test eval accuracy with cache persistence across cache flushes""" + from test_hicache_storage_file_backend import run_eval_accuracy_test + + run_eval_accuracy_test(self) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_runtime_attach_detach.py b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_runtime_attach_detach.py new file mode 100644 index 0000000000000000000000000000000000000000..a85de2b599ace7f61da18fe18a7e8f94767fd0d6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_storage_runtime_attach_detach.py @@ -0,0 +1,367 @@ +""" +E2E check for HiCache storage runtime attach/detach. + +This test launches an SGLang server with hierarchical cache enabled but WITHOUT +any storage backend at startup, then attaches/detaches a storage backend via the +HTTP endpoints. + +Usage: + python3 -m pytest test/registered/hicache/test_hicache_storage_runtime_attach_detach.py -v +""" + +import json +import os +import tempfile +import time +import unittest +from urllib import error, request + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + find_available_port, + popen_launch_server, +) +from sglang.utils import wait_for_http_ready + +register_cuda_ci(est_time=139, stage="base-b", runner_config="2-gpu-large") + + +class TestHiCacheStorageRuntimeAttachDetach(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.temp_dir = tempfile.mkdtemp() + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + # Use a per-test-class available port to reduce flakiness / conflicts. + default_port = int(DEFAULT_URL_FOR_TEST.rsplit(":", 1)[1]) + cls.base_url = f"http://127.0.0.1:{find_available_port(default_port)}" + + cls.other_args = [ + "--enable-hierarchical-cache", + "--mem-fraction-static", + "0.6", + "--hicache-ratio", + "1.2", + "--hicache-size", + "100", + "--page-size", + "64", + "--enable-cache-report", + # NOTE: do NOT pass --hicache-storage-backend* here + ] + + cls.env = { + **os.environ, + # File backend uses this env var to decide where to store cache pages. + "SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIR": cls.temp_dir, + # Make runs less flaky for CI/dev. + "SGLANG_ENABLE_DETERMINISTIC_INFERENCE": "1", + } + + @classmethod + def tearDownClass(cls): + import shutil + + shutil.rmtree(cls.temp_dir, ignore_errors=True) + + @classmethod + def _wait_for_server_ready( + cls, base_url: str, timeout: int = 60, process=None + ) -> bool: + wait_for_http_ready( + url=f"{base_url}/health", + timeout=timeout, + process=process, + ) + return True + + @staticmethod + def _http_get(url: str, timeout: int = 10, headers: dict | None = None): + try: + req = request.Request(url, headers=headers or {}, method="GET") + with request.urlopen(req, timeout=timeout) as resp: + return resp.getcode(), resp.read().decode("utf-8", errors="replace") + except error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + return e.code, body + + @staticmethod + def _http_post_json(url: str, payload: dict | None = None, timeout: int = 30): + data = None + headers = {} + if payload is not None: + data = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + req = request.Request(url, data=data, headers=headers, method="POST") + try: + with request.urlopen(req, timeout=timeout) as resp: + return resp.getcode(), resp.read().decode("utf-8", errors="replace") + except error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + return e.code, body + + @staticmethod + def _http_post_json_with_headers( + url: str, + payload: dict | None = None, + timeout: int = 30, + headers: dict | None = None, + ): + data = None + all_headers = dict(headers or {}) + if payload is not None: + data = json.dumps(payload).encode("utf-8") + all_headers["Content-Type"] = "application/json" + req = request.Request(url, data=data, headers=all_headers, method="POST") + try: + with request.urlopen(req, timeout=timeout) as resp: + return resp.getcode(), resp.read().decode("utf-8", errors="replace") + except error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + return e.code, body + + @staticmethod + def _http_put_json_with_headers( + url: str, + payload: dict | None = None, + timeout: int = 30, + headers: dict | None = None, + ): + data = None + all_headers = dict(headers or {}) + if payload is not None: + data = json.dumps(payload).encode("utf-8") + all_headers["Content-Type"] = "application/json" + req = request.Request(url, data=data, headers=all_headers, method="PUT") + try: + with request.urlopen(req, timeout=timeout) as resp: + return resp.getcode(), resp.read().decode("utf-8", errors="replace") + except error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + return e.code, body + + @staticmethod + def _http_delete_with_headers( + url: str, timeout: int = 30, headers: dict | None = None + ): + all_headers = dict(headers or {}) + req = request.Request(url, headers=all_headers, method="DELETE") + try: + with request.urlopen(req, timeout=timeout) as resp: + return resp.getcode(), resp.read().decode("utf-8", errors="replace") + except error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + return e.code, body + + def _get_backend_status(self, base_url: str, headers: dict | None = None): + code, body = self._http_get( + f"{base_url}/hicache/storage-backend", timeout=10, headers=headers + ) + self.assertEqual(code, 200, body) + return json.loads(body) + + def _attach_backend( + self, + base_url: str, + backend: str, + extra_cfg: dict, + prefetch_policy: str = "timeout", + write_policy: str = "write_through", + headers: dict | None = None, + ): + payload = { + "hicache_storage_backend": backend, + "hicache_storage_backend_extra_config_json": json.dumps(extra_cfg), + "hicache_storage_prefetch_policy": prefetch_policy, + "hicache_write_policy": write_policy, + } + return self._http_put_json_with_headers( + f"{base_url}/hicache/storage-backend", + payload, + timeout=30, + headers=headers, + ) + + def _detach_backend(self, base_url: str, headers: dict | None = None): + return self._http_delete_with_headers( + f"{base_url}/hicache/storage-backend", + timeout=30, + headers=headers, + ) + + def test_runtime_attach_detach(self): + # Phase A: WITHOUT --admin-api-key, ADMIN_FORCE endpoints must be forbidden (403). + process1 = popen_launch_server( + self.model, + self.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=self.other_args, + env=self.env, + ) + try: + self._wait_for_server_ready(self.base_url, process=process1) + + code_info, _body_info = self._http_get( + f"{self.base_url}/hicache/storage-backend", timeout=10 + ) + self.assertEqual(code_info, 400) + code_attach_no_admin, _body_attach_no_admin = self._attach_backend( + base_url=self.base_url, backend="file", extra_cfg={} + ) + self.assertEqual(code_attach_no_admin, 400) + code_detach_no_admin, _body_detach_no_admin = self._detach_backend( + self.base_url + ) + self.assertEqual(code_detach_no_admin, 400) + finally: + kill_process_tree(process1.pid) + time.sleep(2) + + # Phase B: WITH --admin-api-key, must provide Authorization: Bearer . + admin_key = "sglang-test-admin-key" + base_url2 = f"http://127.0.0.1:{find_available_port(int(self.base_url.rsplit(':', 1)[1]) + 1)}" + other_args2 = list(self.other_args) + ["--admin-api-key", admin_key] + process2 = popen_launch_server( + self.model, + base_url2, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args2, + env=self.env, + ) + try: + self._wait_for_server_ready(base_url2, process=process2) + + # 1) Initially disabled (but unauthorized without admin key) + code_info2_unauth, _ = self._http_get( + f"{base_url2}/hicache/storage-backend", timeout=10 + ) + self.assertEqual(code_info2_unauth, 401) + + admin_headers = {"Authorization": f"Bearer {admin_key}"} + status0 = self._get_backend_status(base_url2, headers=admin_headers) + self.assertIsNone(status0.get("hicache_storage_backend")) + + # 2) Attach should succeed when idle + extra_cfg = { + "hicache_storage_pass_prefix_keys": True, + # keep knobs small and stable + "prefetch_threshold": 256, + "prefetch_timeout_base": 3, + "prefetch_timeout_per_ki_token": 0.01, + } + + # Unauthorized attach must fail. + code_attach_unauth, _ = self._attach_backend( + base_url=base_url2, backend="file", extra_cfg=extra_cfg + ) + self.assertEqual(code_attach_unauth, 401) + + code_attach, body_attach = self._attach_backend( + base_url=base_url2, + backend="file", + extra_cfg=extra_cfg, + prefetch_policy="timeout", + write_policy="write_back", + headers=admin_headers, + ) + self.assertEqual(code_attach, 200, f"{code_attach} - {body_attach}") + + status1 = self._get_backend_status(base_url2, headers=admin_headers) + self.assertEqual(status1.get("hicache_storage_backend"), "file") + self.assertEqual( + status1.get("hicache_storage_backend_extra_config"), + json.dumps(extra_cfg), + ) + self.assertEqual(status1.get("hicache_storage_prefetch_policy"), "timeout") + self.assertEqual(status1.get("hicache_write_policy"), "write_back") + + # 3) Attach again succeeds with policies updated + code_attach_again, body_attach_again = self._attach_backend( + base_url=base_url2, + backend="file", + extra_cfg=extra_cfg, + prefetch_policy="wait_complete", + write_policy="write_through_selective", + headers=admin_headers, + ) + self.assertEqual( + code_attach_again, 200, f"{code_attach_again} - {body_attach_again}" + ) + + status2 = self._get_backend_status(base_url2, headers=admin_headers) + self.assertEqual( + status2.get("hicache_storage_backend_extra_config"), + json.dumps(extra_cfg), + ) + self.assertEqual( + status2.get("hicache_storage_prefetch_policy"), "wait_complete" + ) + self.assertEqual( + status2.get("hicache_write_policy"), "write_through_selective" + ) + + # 4) Attach again with different backend should be rejected + code_attach_again, body_attach_again = self._attach_backend( + base_url=base_url2, + backend="mooncake", + extra_cfg=extra_cfg, + headers=admin_headers, + ) + self.assertNotEqual(code_attach_again, 200, body_attach_again) + + # 5) Detach should succeed and be idempotent + code_detach, body_detach = self._detach_backend( + base_url2, headers=admin_headers + ) + self.assertEqual(code_detach, 200, f"{code_detach} - {body_detach}") + status3 = self._get_backend_status(base_url2, headers=admin_headers) + self.assertIsNone(status3.get("hicache_storage_backend")) + self.assertEqual( + status3.get("hicache_storage_prefetch_policy"), "wait_complete" + ) + self.assertEqual( + status3.get("hicache_write_policy"), "write_through_selective" + ) + + code_detach_again, body_detach_again = self._detach_backend( + base_url2, headers=admin_headers + ) + self.assertEqual( + code_detach_again, + 200, + f"{code_detach_again} - {body_detach_again}", + ) + + # 6) Re-attach after detach should succeed + code_attach2, body_attach2 = self._attach_backend( + base_url=base_url2, + backend="file", + extra_cfg=extra_cfg, + headers=admin_headers, + ) + self.assertEqual(code_attach2, 200, f"{code_attach2} - {body_attach2}") + status4 = self._get_backend_status(base_url2, headers=admin_headers) + self.assertEqual(status4.get("hicache_storage_backend"), "file") + self.assertEqual( + status4.get("hicache_storage_backend_extra_config"), + json.dumps(extra_cfg), + ) + self.assertEqual(status4.get("hicache_storage_prefetch_policy"), "timeout") + self.assertEqual(status4.get("hicache_write_policy"), "write_through") + + # Cleanup: detach for test isolation + code_detach2, body_detach2 = self._detach_backend( + base_url2, headers=admin_headers + ) + self.assertEqual(code_detach2, 200, f"{code_detach2} - {body_detach2}") + finally: + kill_process_tree(process2.pid) + time.sleep(2) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_variants.py b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_variants.py new file mode 100644 index 0000000000000000000000000000000000000000..be0ec21a95a389a292fc926e1f3906a390a6d910 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/hicache/test_hicache_variants.py @@ -0,0 +1,136 @@ +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=450, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=524, suite="stage-b-test-1-gpu-small-amd") +""" +Consolidated HiCache variant tests. +Tests HiCache with different configurations: standard, MLA, EAGLE, and page size variants. +""" + +import unittest + +from sglang.benchmark.utils import get_tokenizer +from sglang.srt.utils import is_hip, kill_process_tree +from sglang.test.kits.eval_accuracy_kit import MGSMEnMixin, MMLUMixin +from sglang.test.test_utils import ( + DEFAULT_DRAFT_MODEL_EAGLE3, + DEFAULT_MLA_MODEL_NAME_FOR_TEST, + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TARGET_MODEL_EAGLE3, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +_is_hip = is_hip() + + +class HiCacheBaseServer(CustomTestCase): + """Base class for HiCache tests with configurable server setup""" + + model_name = DEFAULT_MODEL_NAME_FOR_TEST + hicache_args = [] + + @classmethod + def setUpClass(cls): + cls.model = cls.model_name + cls.base_url = DEFAULT_URL_FOR_TEST + + # Setup tokenizer if needed by subclass + if hasattr(cls, "needs_tokenizer") and cls.needs_tokenizer: + cls.tokenizer = get_tokenizer(cls.model) + + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=cls.hicache_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + +class TestHiCacheStandard(HiCacheBaseServer, MMLUMixin): + """Standard HiCache configuration tests""" + + model_name = DEFAULT_MODEL_NAME_FOR_TEST + hicache_args = [ + "--enable-hierarchical-cache", + "--mem-fraction-static", + 0.7, + "--hicache-size", + 100 if not _is_hip else 200, + ] + mmlu_score_threshold = 0.65 + mmlu_num_examples = 64 + mmlu_num_threads = 32 + + +class TestHiCacheMLA(HiCacheBaseServer, MMLUMixin, MGSMEnMixin): + """HiCache with MLA model tests""" + + model_name = DEFAULT_MLA_MODEL_NAME_FOR_TEST + hicache_args = [ + "--trust-remote-code", + "--enable-hierarchical-cache", + ] + (["--hicache-size", 200] if _is_hip else ["--hicache-ratio", 2]) + mmlu_score_threshold = 0.5 + mmlu_num_examples = 64 + mmlu_num_threads = 32 + mgsm_en_score_threshold = 0.8 + + +@unittest.skipIf(is_hip(), "Disabled for AMD-aiter") +class TestHiCacheEagle(HiCacheBaseServer, MMLUMixin): + """HiCache with EAGLE speculative decoding tests""" + + model_name = DEFAULT_TARGET_MODEL_EAGLE3 + needs_tokenizer = True + hicache_args = [ + "--enable-hierarchical-cache", + "--hicache-ratio", + 1.2, + "--mem-fraction-static", + 0.7, + "--speculative-algorithm", + "EAGLE3", + "--speculative-draft-model-path", + DEFAULT_DRAFT_MODEL_EAGLE3, + "--speculative-num-steps", + 2, + "--speculative-eagle-topk", + 1, + "--speculative-num-draft-tokens", + 3, + "--dtype", + "float16", + "--chunked-prefill-size", + 1024, + ] + mmlu_score_threshold = 0.72 + mmlu_num_examples = 64 + mmlu_num_threads = 32 + mmlu_accept_length_thres = 2.26 + + +class TestHiCachePage(HiCacheBaseServer, MMLUMixin): + """HiCache with custom page size tests""" + + model_name = DEFAULT_MODEL_NAME_FOR_TEST + hicache_args = [ + "--enable-hierarchical-cache", + "--page-size", + 32, + "--hicache-write-policy", + "write_back", + ] + mmlu_score_threshold = 0.65 + mmlu_num_examples = 64 + mmlu_num_threads = 32 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/hicache/test_qwen35_hicache.py b/asian_ai/performance/SGLang/test/registered/hicache/test_qwen35_hicache.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1d62de6efed2bf07ffcdb2a417ae49c92f68b8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/hicache/test_qwen35_hicache.py @@ -0,0 +1,174 @@ +import shutil +import tempfile +import time +import unittest +from types import SimpleNamespace + +import requests +import zmq +from msgspec.msgpack import Decoder + +from sglang.srt.disaggregation.kv_events import BlockStored, KVEventBatch +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci + +# This eval harness applies the chat_template, which is critical for qwen3.5 +# to get good accuracy on gsm8k +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=540, stage="extra-b", runner_config="4-gpu-h100") + +QWEN35_27B_MODEL = "Qwen/Qwen3.5-27B" +ACC_THRESHOLDS = {QWEN35_27B_MODEL: {"gsm8k": 0.8}} + + +class TestQwen35WithHiCache(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = QWEN35_27B_MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.storage_dir = tempfile.mkdtemp(prefix="qwen35-hicache-") + env = { + "SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIR": cls.storage_dir, + } + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + env=env, + other_args=[ + "--tp-size", + "4", + "--max-mamba-cache-size", + "500", + "--max-total-tokens", + "120000", + "--chunked-prefill-size", + "2048", + "--mamba-scheduler-strategy", + "extra_buffer", + "--mamba-track-interval", + "128", + "--mamba-ssm-dtype", + "bfloat16", + "--max-running-requests", + "128", + "--reasoning-parser", + "qwen3", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', + "--hicache-mem-layout", + "page_first_direct", + "--hicache-io-backend", + "direct", + "--enable-hierarchical-cache", + "--hicache-ratio", + "2", + "--hicache-size", + "0", + "--hicache-write-policy", + "write_through", + "--hicache-storage-backend", + "file", + "--hicache-storage-prefetch-policy", + "wait_complete", + "--kv-events-config", + '{"publisher": "zmq", "topic": "kv-events"}', + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + shutil.rmtree(cls.storage_dir, ignore_errors=True) + + def _run_gsm8k(self): + args = SimpleNamespace( + model=self.model, + eval_name="gsm8k", + num_shots=5, + num_examples=100, + max_tokens=16000, + num_threads=50, + repeat=1, + temperature=0.6, + top_p=0.95, + top_k=20, + base_url=self.base_url, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + return run_eval(args) + + def test_gsm8k(self): + first_metrics = self._run_gsm8k() + print(f"first_metrics={first_metrics}") + self.assertGreaterEqual( + first_metrics["score"], ACC_THRESHOLDS[self.model]["gsm8k"] + ) + + print(f"flush cache") + res = requests.post( + f"{self.base_url}/flush_cache", + params={"timeout": 30}, + timeout=40, + ) + res.raise_for_status() + + second_metrics = self._run_gsm8k() + print(f"second_metrics={second_metrics}") + self.assertGreaterEqual( + second_metrics["score"], ACC_THRESHOLDS[self.model]["gsm8k"] + ) + self.assertLessEqual( + abs(second_metrics["score"] - first_metrics["score"]), + 0.05, + f"HiCache prefetch accuracy drift too large: " + f"first={first_metrics['score']}, second={second_metrics['score']}", + ) + + def test_kv_events_smoke(self): + decoder = Decoder(type=KVEventBatch) + context = zmq.Context() + sub = context.socket(zmq.SUB) + sub.connect("tcp://localhost:5557") + sub.setsockopt_string(zmq.SUBSCRIBE, "kv-events") + + try: + time.sleep(1.0) + res = requests.post( + f"{self.base_url}/generate", + json={ + "text": "HiCache KV event compatibility check. " * 64, + "sampling_params": {"temperature": 0, "max_new_tokens": 1}, + }, + timeout=120, + ) + res.raise_for_status() + + events = [] + deadline = time.time() + 10 + while time.time() < deadline and not any( + isinstance(event, BlockStored) for event in events + ): + if sub.poll(timeout=100): + _, _, payload = sub.recv_multipart() + events.extend(decoder.decode(payload).events) + + self.assertTrue( + any(isinstance(event, BlockStored) for event in events), + "Expected at least one BlockStored event from Qwen3.5 HiCache server", + ) + finally: + sub.close() + context.term() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/input_embedding/test_input_embeddings.py b/asian_ai/performance/SGLang/test/registered/input_embedding/test_input_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..047fad3d71ac08f90289ede0db3e4fc2bf64dc46 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/input_embedding/test_input_embeddings.py @@ -0,0 +1,155 @@ +import json +import os +import tempfile +import unittest + +import requests +from transformers import AutoModelForCausalLM, AutoTokenizer + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=42, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=38, suite="stage-b-test-1-gpu-small-amd") + + +class TestInputEmbeds(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model) + cls.ref_model = AutoModelForCausalLM.from_pretrained(cls.model) + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=["--disable-radix", "--cuda-graph-max-bs-decode", 4], + ) + cls.texts = [ + "The capital of France is", + "What is the best time of year to visit Japan for cherry blossoms?", + ] + + def generate_input_embeddings(self, text): + """Generate input embeddings for a given text.""" + input_ids = self.tokenizer(text, return_tensors="pt")["input_ids"] + embeddings = self.ref_model.get_input_embeddings()(input_ids) + return embeddings.squeeze().tolist() # Convert tensor to a list for API use + + def send_request(self, payload): + """Send a POST request to the /generate endpoint and return the response.""" + response = requests.post( + self.base_url + "/generate", + json=payload, + timeout=30, # Set a reasonable timeout for the API request + ) + if response.status_code == 200: + return response.json() + return { + "error": f"Request failed with status {response.status_code}: {response.text}" + } + + def send_file_request(self, file_path): + """Send a POST request to the /generate_from_file endpoint with a file.""" + with open(file_path, "rb") as f: + response = requests.post( + self.base_url + "/generate_from_file", + files={"file": f}, + timeout=30, # Set a reasonable timeout for the API request + ) + if response.status_code == 200: + return response.json() + return { + "error": f"Request failed with status {response.status_code}: {response.text}" + } + + def test_text_based_response(self): + """Test and print API responses using text-based input.""" + for text in self.texts: + payload = { + "model": self.model, + "text": text, + "sampling_params": {"temperature": 0, "max_new_tokens": 50}, + } + response = self.send_request(payload) + print( + f"Text Input: {text}\nResponse: {json.dumps(response, indent=2)}\n{'-' * 80}" + ) + + def test_embedding_based_response(self): + """Test and print API responses using input embeddings.""" + for text in self.texts: + embeddings = self.generate_input_embeddings(text) + payload = { + "model": self.model, + "input_embeds": embeddings, + "sampling_params": {"temperature": 0, "max_new_tokens": 50}, + } + response = self.send_request(payload) + print( + f"Embeddings Input (for text '{text}'):\nResponse: {json.dumps(response, indent=2)}\n{'-' * 80}" + ) + + def test_compare_text_vs_embedding(self): + """Test and compare responses for text-based and embedding-based inputs.""" + for text in self.texts: + # Text-based payload + text_payload = { + "model": self.model, + "text": text, + "sampling_params": {"temperature": 0, "max_new_tokens": 50}, + } + # Embedding-based payload + embeddings = self.generate_input_embeddings(text) + embed_payload = { + "model": self.model, + "input_embeds": embeddings, + "sampling_params": {"temperature": 0, "max_new_tokens": 50}, + } + # Get responses + text_response = self.send_request(text_payload) + embed_response = self.send_request(embed_payload) + # Print responses + print( + f"Text Input: {text}\nText-Based Response: {json.dumps(text_response, indent=2)}\n" + ) + print( + f"Embeddings Input (for text '{text}'):\nEmbedding-Based Response: {json.dumps(embed_response, indent=2)}\n{'-' * 80}" + ) + # This is flaky, so we skip this temporarily + # self.assertEqual(text_response["text"], embed_response["text"]) + + def test_generate_from_file(self): + """Test the /generate_from_file endpoint using tokenized embeddings.""" + for text in self.texts: + embeddings = self.generate_input_embeddings(text) + with tempfile.NamedTemporaryFile( + mode="w", suffix=".json", delete=False + ) as tmp_file: + json.dump(embeddings, tmp_file) + tmp_file_path = tmp_file.name + + try: + response = self.send_file_request(tmp_file_path) + print( + f"Text Input: {text}\nResponse from /generate_from_file: {json.dumps(response, indent=2)}\n{'-' * 80}" + ) + finally: + # Ensure the temporary file is deleted + os.remove(tmp_file_path) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/input_embedding/test_input_embeds_chunked.py b/asian_ai/performance/SGLang/test/registered/input_embedding/test_input_embeds_chunked.py new file mode 100644 index 0000000000000000000000000000000000000000..b865092bc595f834d8a902791af850e55863a251 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/input_embedding/test_input_embeds_chunked.py @@ -0,0 +1,189 @@ +"""Regression tests for input_embeds shape-mismatch bugs. + +Covers two bugs with the same crash signature +(RuntimeError: shape mismatch in set_kv_buffer) but opposite polarity: + +- Chunked prefill truncation (#20376): PrefillAdder shrinks fill_len and + extend_input_len on chunk overflow but not input_embeds, so the full array + flows through while out_cache_loc is sized for the truncated length. + Polarity: cache_k > loc. + +- Retraction with output_ids (#14110): after retraction, get_fill_ids() + includes accumulated output_ids but input_embeds only covers + origin_input_ids. Polarity: cache_k < loc. +""" + +import unittest + +import requests +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +from sglang.srt.environ import envs +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=43, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=43, suite="stage-b-test-1-gpu-small-amd") + +CHUNKED_PREFILL_SIZE = 256 + +# Shared reference model — loaded once per process, not per test class. +_MODEL = DEFAULT_SMALL_MODEL_NAME_FOR_TEST +_tokenizer = None +_ref_model = None + + +def _load_ref(): + global _tokenizer, _ref_model + if _tokenizer is None: + _tokenizer = AutoTokenizer.from_pretrained(_MODEL) + _ref_model = AutoModelForCausalLM.from_pretrained(_MODEL) + + +def _embeds_for(text: str) -> list[list[float]]: + _load_ref() + ids = _tokenizer(text, return_tensors="pt")["input_ids"] + embeds = _ref_model.get_input_embeddings()(ids) + return embeds.squeeze(0).to(torch.float32).tolist() + + +def _generate(base_url, input_embeds, max_new_tokens, ignore_eos=False, timeout=120): + resp = requests.post( + f"{base_url}/generate", + json={ + "input_embeds": input_embeds, + "sampling_params": { + "temperature": 0, + "max_new_tokens": max_new_tokens, + "ignore_eos": ignore_eos, + }, + }, + timeout=timeout, + ) + return resp + + +class TestInputEmbedsChunkedAndRetract(CustomTestCase): + """Single server launch covering both bugs. + + Both tests require --disable-radix-cache (for input_embeds). The chunked + prefill test needs a small --chunked-prefill-size. The retraction test + uses SGLANG_TEST_RETRACT to deterministically force retraction every few + scheduler iterations regardless of KV pressure. + """ + + @classmethod + def setUpClass(cls): + cls.base_url = DEFAULT_URL_FOR_TEST + # SGLANG_TEST_RETRACT forces retraction periodically; this is + # deterministic and doesn't require guessing KV budgets. + with envs.SGLANG_TEST_RETRACT.override(True): + cls.process = popen_launch_server( + _MODEL, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--disable-radix-cache", + "--chunked-prefill-size", + str(CHUNKED_PREFILL_SIZE), + "--cuda-graph-max-bs-decode", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def _assert_server_alive(self): + self.assertIsNone(self.process.poll(), "server process crashed") + + def test_chunked_prefill_truncation_and_continuation(self): + """Regression test for #20376. + + A single request longer than chunked_prefill_size deterministically + exercises both (a) first-chunk truncation and (b) chunk continuation, + without any concurrent-timing dependency. Pre-fix this crashes in + set_kv_buffer on both chunks. + """ + # ~80 tokens each repetition; 6 repetitions exceeds CHUNKED_PREFILL_SIZE + # comfortably. Token count is model-dependent so assert it. + text = "The quick brown fox jumps over the lazy dog. " * 40 + embeds = _embeds_for(text) + self.assertGreater( + len(embeds), + CHUNKED_PREFILL_SIZE, + f"prompt must exceed chunked_prefill_size={CHUNKED_PREFILL_SIZE} " + f"to trigger chunking; got {len(embeds)} tokens", + ) + + resp = _generate(self.base_url, embeds, max_new_tokens=8) + self.assertEqual(resp.status_code, 200, resp.text[:300]) + body = resp.json() + self.assertIn("text", body) + self.assertIsInstance(body["text"], str) + self._assert_server_alive() + + def test_chunked_prefill_batch_truncation(self): + """Regression test for #20376 — multi-request batch case. + + A batch POST with total tokens > chunked_prefill_size goes through a + single ZMQ send, so all requests land in the same scheduler iteration + and the PrefillAdder is forced to truncate at least one. This matches + the original thundering-herd trigger without HTTP timing races. + """ + text = "The quick brown fox jumps over the lazy dog. " * 8 + embeds = _embeds_for(text) + seq_len = len(embeds) + + # Enough batched requests to overflow the chunk budget. + n = max(4, CHUNKED_PREFILL_SIZE // seq_len + 2) + self.assertGreater(n * seq_len, CHUNKED_PREFILL_SIZE) + + resp = _generate(self.base_url, [embeds] * n, max_new_tokens=8) + self.assertEqual(resp.status_code, 200, resp.text[:300]) + results = resp.json() + self.assertEqual(len(results), n) + for r in results: + self.assertIn("text", r) + self._assert_server_alive() + + def test_retraction_with_output_ids(self): + """Regression test for #14110. + + SGLANG_TEST_RETRACT forces retraction every few scheduler iterations. + Combined with ignore_eos and a reasonable max_new_tokens, at least one + request is retracted mid-decode with non-empty output_ids, then + re-prefilled. Pre-#14110 this crashes (cache_k < loc) because the + filled token sequence includes output_ids but input_embeds does not. + """ + text = "The quick brown fox jumps over the lazy dog. " * 4 + embeds = _embeds_for(text) + + # Batch of requests with enough decode steps that SGLANG_TEST_RETRACT + # (interval=3 by default) fires mid-decode. + n = 4 + resp = _generate( + self.base_url, + [embeds] * n, + max_new_tokens=32, + ignore_eos=True, + ) + self.assertEqual(resp.status_code, 200, resp.text[:300]) + results = resp.json() + self.assertEqual(len(results), n) + for r in results: + self.assertIn("text", r) + self._assert_server_alive() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_activation.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_activation.py new file mode 100644 index 0000000000000000000000000000000000000000..011540f524cab8c9e4e7bbbc467d83ad5085c0a0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_activation.py @@ -0,0 +1,110 @@ +import torch +import torch.nn.functional as F +from sgl_kernel import gelu_and_mul as gelu_and_mul_aot +from sgl_kernel import gelu_tanh_and_mul as gelu_tanh_and_mul_aot +from sgl_kernel import silu_and_mul as silu_and_mul_aot + +from sglang.jit_kernel.activation import gelu_and_mul as gelu_and_mul_jit +from sglang.jit_kernel.activation import gelu_tanh_and_mul as gelu_tanh_and_mul_jit +from sglang.jit_kernel.activation import relu2 as relu2_jit +from sglang.jit_kernel.activation import silu_and_mul as silu_and_mul_jit +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.benchmark.utils import create_random +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=30, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +@torch.compile +def silu_and_mul(input: torch.Tensor) -> torch.Tensor: + lhs, rhs = input.split(input.shape[-1] // 2, dim=-1) + return F.silu(lhs) * rhs + + +@torch.compile +def gelu_and_mul(input: torch.Tensor) -> torch.Tensor: + lhs, rhs = input.split(input.shape[-1] // 2, dim=-1) + return F.gelu(lhs, approximate="none") * rhs + + +@torch.compile +def gelu_tanh_and_mul(input: torch.Tensor) -> torch.Tensor: + lhs, rhs = input.split(input.shape[-1] // 2, dim=-1) + return F.gelu(lhs, approximate="tanh") * rhs + + +OPS = { + "silu": (silu_and_mul_aot, silu_and_mul_jit, silu_and_mul), + "gelu": (gelu_and_mul_aot, gelu_and_mul_jit, gelu_and_mul), + "gelu_tanh": (gelu_tanh_and_mul_aot, gelu_tanh_and_mul_jit, gelu_tanh_and_mul), +} + + +@marker.parametrize("op_name", ["silu", "gelu", "gelu_tanh"]) +@marker.parametrize("dim", [1024, 4096, 6144, 8192], [4096]) +@marker.parametrize("batch_size", [2**x for x in range(0, 15)], [8, 512]) +@marker.benchmark("impl", ["aot", "jit", "torch"]) +def benchmark(op_name: str, dim: int, batch_size: int, impl: str): + x = create_random(batch_size, dim * 2) + aot_op, jit_op, torch_op = OPS[op_name] + fn = {"aot": aot_op, "jit": jit_op, "torch": torch_op}[impl] + return marker.do_bench(fn, input_args=(x,)) + + +def _make_expert_ids(num_tokens: int, skip_ratio: float) -> torch.Tensor: + expert_ids = torch.randint(low=0, high=8, size=(num_tokens,), dtype=torch.int32) + if skip_ratio > 0: + skip = torch.rand(num_tokens) < skip_ratio + expert_ids[skip] = -1 + return expert_ids + + +@marker.parametrize("op_name", ["silu", "gelu"]) +@marker.parametrize("dim", [1024, 4096, 8192], [4096]) +@marker.parametrize("batch_size", [64, 256, 1024, 4096, 16384], [1024]) +@marker.parametrize("skip_ratio", [0.0, 0.25, 0.5], [0.25]) +@marker.benchmark("impl", ["unfiltered", "filtered"]) +def benchmark_filter( + op_name: str, dim: int, batch_size: int, skip_ratio: float, impl: str +): + torch.random.manual_seed(42) + x = create_random(batch_size, dim * 2) + jit_fn = silu_and_mul_jit if op_name == "silu" else gelu_and_mul_jit + extra_kwargs = {} + expert_ids = _make_expert_ids(batch_size, skip_ratio) + if impl == "filtered": + extra_kwargs = {"expert_ids": expert_ids.to(x.device), "expert_step": 1} + + # NOTE: get the unmasked part from `experts_ids` + real_skip_ratio = (expert_ids == -1).sum().item() / batch_size + effective_bytes = int(x.nbytes * (1 - real_skip_ratio) * 1.5) + return marker.do_bench( + jit_fn, + input_args=(x,), + input_kwargs=extra_kwargs, + memory_args=None, # x is dynamic (counted in extra_memory_footprint) + memory_output=None, # same, output is dynamic + extra_memory_footprint=effective_bytes, + ) + + +@torch.compile +def relu2_torch(input: torch.Tensor) -> torch.Tensor: + return F.relu(input).pow(2) + + +@marker.parametrize("dim", [1024, 4096, 6144, 8192], [4096]) +@marker.parametrize("batch_size", [2**x for x in range(0, 15)], [8, 512]) +@marker.benchmark("impl", ["jit", "torch"]) +def benchmark_unary(dim: int, batch_size: int, impl: str): + x = create_random(batch_size, dim) + fn = {"jit": relu2_jit, "torch": relu2_torch}[impl] + return marker.do_bench(fn, input_args=(x,)) + + +if __name__ == "__main__": + benchmark.run() + benchmark_filter.run() + benchmark_unary.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_add_constant.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_add_constant.py new file mode 100644 index 0000000000000000000000000000000000000000..54e86b93ff7b3ed278f46f1324780ba260aa41a4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_add_constant.py @@ -0,0 +1,61 @@ +import torch +import triton +import triton.testing + +from sglang.jit_kernel.add_constant import _jit_add_constant_module, add_constant +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark_no_cudagraph, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=15, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +CONSTANT = 7 +SIZE_LIST = get_benchmark_range( + full_range=[128, 1024, 1025, 4096, 4097, 65536, 2**20, 2**22, 2**24], + ci_range=[4096, 2**20], +) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["size"], + x_vals=SIZE_LIST, + line_arg="provider", + line_vals=["jit_module", "jit_wrapper", "torch"], + line_names=["JIT module", "JIT wrapper", "PyTorch"], + styles=[("blue", "-"), ("orange", "-"), ("green", "--")], + ylabel="us", + plot_name="add-constant-performance", + args={}, + ) +) +def benchmark(size: int, provider: str): + src = torch.arange(size, dtype=torch.int32, device=DEFAULT_DEVICE) + + if provider == "jit_module": + dst = torch.empty_like(src) + module = _jit_add_constant_module(CONSTANT) + + def fn(): + module.add_constant(dst, src) + + elif provider == "jit_wrapper": + + def fn(): + add_constant(src, CONSTANT) + + else: + + def fn(): + src + CONSTANT + + return run_benchmark_no_cudagraph(fn) + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_awq_dequantize.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_awq_dequantize.py new file mode 100644 index 0000000000000000000000000000000000000000..7ba5e6831366e5cf7618727987c34f0e48fb922d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_awq_dequantize.py @@ -0,0 +1,124 @@ +import itertools + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.awq_dequantize import awq_dequantize as jit_awq_dequantize +from sglang.jit_kernel.benchmark.utils import run_benchmark +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +try: + from sgl_kernel import awq_dequantize as aot_awq_dequantize + + AOT_AVAILABLE = True +except ImportError: + AOT_AVAILABLE = False + +IS_CI = is_in_ci() + +if IS_CI: + qweight_row_range = [128] + qweight_cols_range = [16] +else: + qweight_row_range = [128, 256, 512, 1024, 3584] + qweight_cols_range = [16, 32, 64, 128, 448] + +configs = list(itertools.product(qweight_row_range, qweight_cols_range)) + + +def check_correctness(): + if not AOT_AVAILABLE: + print("sgl_kernel AOT not available, skipping correctness check") + return + + qweight_row, qweight_col = 128, 16 + device = torch.device("cuda") + qweight = torch.randint( + 0, + torch.iinfo(torch.int32).max, + (qweight_row, qweight_col), + dtype=torch.int32, + device=device, + ) + group_size = qweight_row + scales_row = qweight_row // group_size + scales_col = qweight_col * 8 + scales = torch.rand(scales_row, scales_col, dtype=torch.float16, device=device) + qzeros = torch.randint( + 0, + torch.iinfo(torch.int32).max, + (scales_row, qweight_col), + dtype=torch.int32, + device=device, + ) + + jit_out = jit_awq_dequantize(qweight, scales, qzeros) + aot_out = aot_awq_dequantize(qweight, scales, qzeros) + torch.cuda.synchronize() + torch.testing.assert_close(jit_out, aot_out, rtol=0, atol=0) + print("Correctness check passed (JIT vs AOT)") + + +if AOT_AVAILABLE: + line_vals = ["jit", "aot"] + line_names = ["JIT Kernel", "AOT Kernel"] + styles = [("blue", "-"), ("green", "-")] +else: + line_vals = ["jit"] + line_names = ["JIT Kernel"] + styles = [("blue", "-")] + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["qweight_row", "qweight_col"], + x_vals=configs, + line_arg="provider", + line_vals=line_vals, + line_names=line_names, + styles=styles, + ylabel="us", + plot_name="awq-dequantize-jit-vs-aot", + args={}, + ) +) +def benchmark(qweight_row, qweight_col, provider): + device = torch.device("cuda") + qweight = torch.randint( + 0, + torch.iinfo(torch.int32).max, + (qweight_row, qweight_col), + dtype=torch.int32, + device=device, + ) + group_size = qweight_row + scales_row = qweight_row // group_size + scales_col = qweight_col * 8 + scales = torch.rand(scales_row, scales_col, dtype=torch.float16, device=device) + qzeros = torch.randint( + 0, + torch.iinfo(torch.int32).max, + (scales_row, qweight_col), + dtype=torch.int32, + device=device, + ) + + if provider == "jit": + fn = lambda: jit_awq_dequantize(qweight, scales, qzeros) + elif provider == "aot": + fn = lambda: aot_awq_dequantize(qweight, scales, qzeros) + else: + raise ValueError(f"Unknown provider: {provider}") + + return run_benchmark(fn) + + +if __name__ == "__main__": + check_correctness() + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_clamp_position.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_clamp_position.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c95b37f50db8d459797909b1cf23ba4330d863 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_clamp_position.py @@ -0,0 +1,67 @@ +import itertools + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark, +) +from sglang.jit_kernel.clamp_position import clamp_position_cuda +from sglang.srt.utils import get_compiler_backend +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci( + est_time=13, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) +register_amd_ci(est_time=16, stage="jit-kernel-unit", runner_config="amd") + +SIZE_LIST = get_benchmark_range( + full_range=[2**n for n in range(4, 16)], + ci_range=[256, 4096], +) + +configs = list(itertools.product(SIZE_LIST)) + + +def _torch_clamp_position(seq_lens): + return torch.clamp(seq_lens - 1, min=0).to(torch.int64) + + +_compiled_clamp_position = torch.compile( + _torch_clamp_position, dynamic=True, backend=get_compiler_backend() +) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["size"], + x_vals=configs, + line_arg="provider", + line_vals=["jit", "torch_compile", "torch"], + line_names=["SGL JIT Kernel", "torch.compile", "PyTorch"], + styles=[("blue", "-"), ("green", "-."), ("red", "--")], + ylabel="us", + plot_name="clamp-position-performance", + args={}, + ) +) +def benchmark(size: int, provider: str): + seq_lens = torch.randint( + 0, 10000, (size,), dtype=torch.int64, device=DEFAULT_DEVICE + ) + + if provider == "jit": + fn = lambda: clamp_position_cuda(seq_lens) + elif provider == "torch_compile": + fn = lambda: _compiled_clamp_position(seq_lens) + else: + fn = lambda: _torch_clamp_position(seq_lens) + + return run_benchmark(fn) + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_concat_mla.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_concat_mla.py new file mode 100644 index 0000000000000000000000000000000000000000..fc023cd1ca8b932dc2e0c48677102458d2bb7a22 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_concat_mla.py @@ -0,0 +1,164 @@ +import itertools + +import torch +import triton +import triton.testing +from sgl_kernel import concat_mla_absorb_q as aot_absorb_q +from sgl_kernel import concat_mla_k as aot_k + +from sglang.jit_kernel.benchmark.utils import run_benchmark +from sglang.jit_kernel.concat_mla import concat_mla_absorb_q as jit_absorb_q +from sglang.jit_kernel.concat_mla import concat_mla_k as jit_k +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=6, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +IS_CI = is_in_ci() + +NUM_LOCAL_HEADS = 128 +QK_NOPE_HEAD_DIM = 128 +QK_ROPE_HEAD_DIM = 64 +K_HEAD_DIM = QK_NOPE_HEAD_DIM + QK_ROPE_HEAD_DIM + +A_LAST_DIM = 512 +B_LAST_DIM = 64 + +DTYPE = torch.bfloat16 +DEVICE = "cuda" + + +def aot_concat_mla_k(k, k_nope, k_rope): + aot_k(k, k_nope, k_rope) + + +def jit_concat_mla_k(k, k_nope, k_rope): + jit_k(k, k_nope, k_rope) + + +def torch_concat_mla_k(k, k_nope, k_rope): + nope_head_dim = k_nope.shape[-1] + k[:, :, :nope_head_dim] = k_nope + k[:, :, nope_head_dim:] = k_rope.expand(-1, k.shape[1], -1) + + +def aot_concat_mla_absorb_q(a, b): + return aot_absorb_q(a, b) + + +def jit_concat_mla_absorb_q(a, b): + return jit_absorb_q(a, b) + + +def torch_concat_mla_absorb_q(a, b, out): + a_last_dim = a.shape[-1] + out[:, :, :a_last_dim] = a + out[:, :, a_last_dim:] = b + + +if IS_CI: + NUM_TOKENS_VALS = [256, 1024] +else: + NUM_TOKENS_VALS = [256, 512, 1024, 2048, 4096, 8192, 16384, 32768] + +K_LINE_VALS = ["aot", "jit", "torch"] +K_LINE_NAMES = ["SGL AOT Kernel", "SGL JIT Kernel", "PyTorch"] +K_STYLES = [("orange", "-"), ("blue", "--"), ("green", "-.")] + + +def _create_concat_mla_k_data(num_tokens): + """Allocate oversized containers and slice to produce non-contiguous tensors.""" + k_nope_container = torch.randn( + (num_tokens, NUM_LOCAL_HEADS, QK_NOPE_HEAD_DIM + 128), + dtype=DTYPE, + device=DEVICE, + ) + k_nope = k_nope_container[:, :, :QK_NOPE_HEAD_DIM] + + k_rope_container = torch.randn( + (num_tokens, 1, 128 + QK_ROPE_HEAD_DIM), + dtype=DTYPE, + device=DEVICE, + ) + k_rope = k_rope_container[:, :, -QK_ROPE_HEAD_DIM:] + + k = torch.empty( + (num_tokens, NUM_LOCAL_HEADS, K_HEAD_DIM), + dtype=DTYPE, + device=DEVICE, + ) + return k, k_nope, k_rope + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["num_tokens"], + x_vals=NUM_TOKENS_VALS, + line_arg="provider", + line_vals=K_LINE_VALS, + line_names=K_LINE_NAMES, + styles=K_STYLES, + ylabel="us", + plot_name="concat-mla-k-performance", + args={}, + ) +) +def bench_concat_mla_k(num_tokens: int, provider: str): + k, k_nope, k_rope = _create_concat_mla_k_data(num_tokens) + + FN_MAP = { + "aot": aot_concat_mla_k, + "jit": jit_concat_mla_k, + "torch": torch_concat_mla_k, + } + fn = lambda: FN_MAP[provider](k, k_nope, k_rope) + return run_benchmark(fn) + + +if IS_CI: + ABSORB_Q_VALS = list(itertools.product([4, 16], [16])) +else: + ABSORB_Q_VALS = list(itertools.product([1, 4, 8, 16, 32], [1, 8, 32, 128])) + +Q_LINE_VALS = ["aot", "jit", "torch"] +Q_LINE_NAMES = ["SGL AOT Kernel", "SGL JIT Kernel", "PyTorch"] +Q_STYLES = [("orange", "-"), ("blue", "--"), ("green", "-.")] + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["dim_0", "dim_1"], + x_vals=ABSORB_Q_VALS, + line_arg="provider", + line_vals=Q_LINE_VALS, + line_names=Q_LINE_NAMES, + styles=Q_STYLES, + ylabel="us", + plot_name="concat-mla-absorb-q-performance", + args={}, + ) +) +def bench_concat_mla_absorb_q(dim_0: int, dim_1: int, provider: str): + a = torch.randn(dim_0, dim_1, A_LAST_DIM, dtype=DTYPE, device=DEVICE) + b = torch.randn(dim_0, dim_1, B_LAST_DIM, dtype=DTYPE, device=DEVICE) + + if provider == "torch": + out = torch.empty( + dim_0, dim_1, A_LAST_DIM + B_LAST_DIM, dtype=DTYPE, device=DEVICE + ) + fn = lambda: torch_concat_mla_absorb_q(a, b, out) + else: + FN_MAP = { + "aot": aot_concat_mla_absorb_q, + "jit": jit_concat_mla_absorb_q, + } + fn = lambda: FN_MAP[provider](a, b) + + return run_benchmark(fn) + + +if __name__ == "__main__": + bench_concat_mla_k.run(print_data=True) + bench_concat_mla_absorb_q.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_custom_all_reduce.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_custom_all_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..44b8067cedc194594e01147243d3295470d8ed74 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_custom_all_reduce.py @@ -0,0 +1,295 @@ +"""Benchmark JIT custom all-reduce (v2) vs NCCL, AOT custom-AR (v1), and +FlashInfer trtllm allreduce_fusion. + +Usage:: + + # Benchmark on every supported world size (2..8 GPUs): + python benchmark/bench_custom_all_reduce.py + # Pick a specific world size (or comma-separated list): + python benchmark/bench_custom_all_reduce.py --num-gpu 4 + python benchmark/bench_custom_all_reduce.py --num-gpu 2,4,8 + +The script self-relaunches under ``torchrun --nproc_per_node=N`` for each N in +``num_gpus``; results are printed on rank 0 of every run. +""" + +from __future__ import annotations + +import atexit +import contextlib +import logging +import os +from typing import Optional + +import torch +import torch.distributed as dist + +import sglang.srt.distributed.parallel_state as ps +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.benchmark.utils import get_benchmark_range, multigpu_bench_main +from sglang.jit_kernel.mp import register_comm_cleanup +from sglang.jit_kernel.utils import cache_once, is_arch_support_pdl +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=120, + stage="base-b-kernel-benchmark", + runner_config="1-gpu-large", + disabled="requires multi-GPU, self-skips in CI", +) + + +# --------------------------------------------------------------------------- +# Sweep parameters +# --------------------------------------------------------------------------- + +DTYPE = torch.bfloat16 +# torch.dtype.itemsize exists only on newer torch; element_size() is portable. +DTYPE_ITEMSIZE = torch.tensor([], dtype=DTYPE).element_size() +MESSAGE_SIZES_BYTES = [ + 4 * 1024, # 4K + 16 * 1024, # 16K + 64 * 1024, # 64K + 128 * 1024, # 128K + 3 * 64 * 1024, # 192K + 4 * 64 * 1024, # 256K + 3 * 128 * 1024, # 384K + 4 * 128 * 1024, # 512K + 5 * 128 * 1024, # 640K + 6 * 128 * 1024, # 768K + 7 * 128 * 1024, # 896K + 1 * 1024 * 1024, # 1M + 2 * 1024 * 1024, # 2M + 3 * 1024 * 1024, # 3M + 4 * 1024 * 1024, # 4M + 8 * 1024 * 1024, # 8M + 16 * 1024 * 1024, # 16M + 32 * 1024 * 1024, # 32M +] +WORLD_SIZES = list(range(2, 9)) +MAX_BYTES = max(MESSAGE_SIZES_BYTES) +# trtllm allreduce_fusion only supports these world sizes. +FI_SUPPORTED_WORLD_SIZES = (2, 4, 8) +# AOT custom_all_reduce (v1) only supports these world sizes. +AOT_SUPPORTED_WORLD_SIZES = (2, 4, 6, 8) +PROVIDERS = ["nccl", "aot", "jit", "fi"] +WORLD_SIZES = get_benchmark_range(WORLD_SIZES, [2, 4, 8]) + +# --------------------------------------------------------------------------- +# Per-rank distributed init (run once per torchrun worker) +# --------------------------------------------------------------------------- + + +@cache_once +def _init_cpu_group() -> dist.ProcessGroup: + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + torch.cuda.set_device(local_rank) + dist.init_process_group(backend="gloo") + ps._WORLD = coord = ps.init_world_group( + ranks=list(range(world_size)), + local_rank=local_rank, + backend="nccl", + ) + atexit.register(dist.destroy_process_group) + # Quieter benchmark output. + logging.disable(logging.INFO) + torch.cuda.set_stream(torch.cuda.Stream()) + return coord.cpu_group + + +@cache_once +def _init_nccl_group() -> dist.ProcessGroup: + _init_cpu_group() + coord = ps._WORLD + assert coord is not None and coord.device_group is not None + return coord.device_group + + +# --------------------------------------------------------------------------- +# Backend wrappers - each exposes: +# .all_reduce(tensor) -> Tensor +# .graph_context() -> context manager wrapping cuda-graph capture +# (nullcontext when capture is not required) +# --------------------------------------------------------------------------- + + +class NCCLAllReduceBackend: + def __init__(self) -> None: + self.group = _init_nccl_group() + + def graph_context(self): + return contextlib.nullcontext() + + def all_reduce(self, tensor: torch.Tensor) -> torch.Tensor: + dist.all_reduce(tensor, group=self.group) + return tensor + + +class JITAllReduceBackend: + def __init__(self) -> None: + from sglang.srt.distributed.device_communicators.custom_all_reduce_v2 import ( + CustomAllReduceV2, + ) + + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + self.comm = CustomAllReduceV2( + _init_cpu_group(), device, max_pull_size=MAX_BYTES + ) + if self.comm.disabled: + raise RuntimeError("JIT CustomAllReduceV2 is disabled on this system") + register_comm_cleanup(self.comm) + + def graph_context(self): + return self.comm.capture() + + def all_reduce(self, tensor: torch.Tensor) -> Optional[torch.Tensor]: + assert self.comm.should_custom_ar(tensor), str(tensor.shape) + return self.comm.custom_all_reduce(tensor) + + +class AOTAllReduceBackend: + def __init__(self) -> None: + from sglang.srt.distributed.device_communicators.custom_all_reduce import ( + CustomAllreduce, + ) + + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + self.comm = CustomAllreduce(_init_cpu_group(), device, max_size=MAX_BYTES) + if self.comm.disabled: + raise RuntimeError("AOT CustomAllreduce is disabled on this system") + register_comm_cleanup(self.comm) + + def graph_context(self): + return self.comm.capture() + + def all_reduce(self, tensor: torch.Tensor) -> Optional[torch.Tensor]: + assert self.comm.should_custom_ar(tensor), str(tensor.shape) + return self.comm.custom_all_reduce(tensor) + + +class FlashInferAllReduceBackend: + def __init__(self) -> None: + import flashinfer.comm as comm + + group = _init_cpu_group() + rank = dist.get_rank(group=group) + world_size = dist.get_world_size(group=group) + # Use the smallest message size as the inner hidden dim, so any + # message in the sweep is an integer multiple of it. + hidden_dim = min(MESSAGE_SIZES_BYTES) // DTYPE_ITEMSIZE + num_tokens = MAX_BYTES // (hidden_dim * DTYPE_ITEMSIZE) + self._comm = comm + self._hidden_dim = hidden_dim + self._workspace = comm.create_allreduce_fusion_workspace( + backend="trtllm", + world_size=world_size, + rank=rank, + max_token_num=num_tokens, + hidden_dim=hidden_dim, + dtype=DTYPE, + ) + + def graph_context(self): + return contextlib.nullcontext() + + def all_reduce(self, tensor: torch.Tensor) -> torch.Tensor: + return self._comm.allreduce_fusion( + input=tensor.view(-1, self._hidden_dim), + workspace=self._workspace, + pattern=self._comm.AllReduceFusionPattern.kAllReduce, + launch_with_pdl=is_arch_support_pdl(), + fp32_acc=True, + ) + + +@cache_once +def _init_nccl_backend() -> NCCLAllReduceBackend: + return NCCLAllReduceBackend() + + +@cache_once +def _init_jit_backend() -> JITAllReduceBackend: + return JITAllReduceBackend() + + +@cache_once +def _init_aot_backend() -> AOTAllReduceBackend: + return AOTAllReduceBackend() + + +@cache_once +def _init_fi_backend() -> FlashInferAllReduceBackend: + return FlashInferAllReduceBackend() + + +BACKEND_FACTORY = { + "nccl": _init_nccl_backend, + "jit": _init_jit_backend, + "aot": _init_aot_backend, + "fi": _init_fi_backend, +} + + +@cache_once +def _init_all_backends() -> None: + """Pre-build every supported backend before any timed iteration so JIT + compilation / IPC setup don't bleed into the first measured size. + """ + world_size = dist.get_world_size(_init_cpu_group()) + factories = dict(BACKEND_FACTORY) + if world_size not in AOT_SUPPORTED_WORLD_SIZES: + factories.pop("aot") + if world_size not in FI_SUPPORTED_WORLD_SIZES: + factories.pop("fi") + for fn in factories.values(): + fn() + + +# --------------------------------------------------------------------------- +# Benchmark +# --------------------------------------------------------------------------- + + +@marker.parametrize("message_bytes", MESSAGE_SIZES_BYTES) +@marker.benchmark("provider", PROVIDERS) +def benchmark(message_bytes: int, provider: str): + cpu_group = _init_cpu_group() + gpu_group = _init_nccl_group() + world_size = dist.get_world_size(cpu_group) + if provider == "fi" and world_size not in FI_SUPPORTED_WORLD_SIZES: + marker.skip( + f"flashinfer trtllm allreduce_fusion needs world_size in " + f"{FI_SUPPORTED_WORLD_SIZES}" + ) + if provider == "aot" and world_size not in AOT_SUPPORTED_WORLD_SIZES: + marker.skip( + f"AOT custom_all_reduce needs world_size in " f"{AOT_SUPPORTED_WORLD_SIZES}" + ) + _init_all_backends() + backend = BACKEND_FACTORY[provider]() + numel = message_bytes // DTYPE_ITEMSIZE + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + x = torch.randn(numel, dtype=DTYPE, device=device) + # Bandwidth-equivalent bytes moved by a ring all-reduce per rank. + effective_bytes = int(x.nbytes * 2 * (world_size - 1) / world_size) + return marker.do_bench( + backend.all_reduce, + input_args=(x,), + graph_context_fn=backend.graph_context, + sync_multigpu_fn=lambda: dist.barrier(gpu_group), + # all-reduce is in-place w.r.t. its argument; explicit footprint + # captures the cross-GPU traffic instead. + memory_args=None, + memory_output=None, + extra_memory_footprint=effective_bytes, + ) + + +if __name__ == "__main__": + multigpu_bench_main( + name=__name__, + file=__file__, + num_gpus=WORLD_SIZES, + main_fn=benchmark.run, + ) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_dsv3_fused_a_gemm.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_dsv3_fused_a_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..2eb78dfc892fffd9a8e53986ab4b6b8be8122217 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_dsv3_fused_a_gemm.py @@ -0,0 +1,96 @@ +"""Benchmark for DeepSeek V3 fused QKV-A GEMM: CuTe DSL vs CUDA JIT vs +sgl_kernel AOT vs torch. + +Run on SM90+ (Hopper or later): + python test/registered/jit/benchmark/bench_dsv3_fused_a_gemm.py +""" + +import torch +import torch.nn.functional as F +import triton.testing +from sgl_kernel import dsv3_fused_a_gemm as sgl_kernel_dsv3_fused_a_gemm + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.cutedsl_dsv3_fused_a_gemm import ( + dsv3_fused_a_gemm as cutedsl_dsv3_fused_a_gemm, +) +from sglang.jit_kernel.dsv3_fused_a_gemm import dsv3_fused_a_gemm +from sglang.jit_kernel.utils import get_jit_cuda_arch, is_hip_runtime +from sglang.srt.utils.common import is_sm120_supported +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=12, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +IS_CI = is_in_ci() + +DTYPE = torch.bfloat16 +DEVICE = "cuda" +HD_OUT = 2112 +HD_IN_LIST = [6144, 7168] + +AOT_HD_IN = 7168 +HAS_AOT = not is_sm120_supported() + +NUM_TOKENS_LIST = [1, 8, 16] if IS_CI else list(range(1, 17)) + +LINE_VALS = ["cutedsl", "jit", "sgl_kernel", "torch"] +LINE_NAMES = ["CuTe DSL", "CUDA JIT", "sgl_kernel AOT", "torch F.linear"] +STYLES = [("blue", "-"), ("orange", "--"), ("red", ":"), ("green", "-.")] + + +def _median_us(fn, *args) -> float: + result = marker.do_bench( + fn, + input_args=args, + use_cuda_graph=True, + metrics=(0.5,), + disable_log_bandwidth=True, + ) + return result.times[0] * 1e6 + + +def _bench(num_tokens, provider, hd_in): + if provider == "sgl_kernel" and not (HAS_AOT and hd_in == AOT_HD_IN): + return float("nan") + + mat_a = torch.randn((num_tokens, hd_in), dtype=DTYPE, device=DEVICE) + mat_b = torch.randn((HD_OUT, hd_in), dtype=DTYPE, device=DEVICE).transpose(0, 1) + fn_map = { + "cutedsl": cutedsl_dsv3_fused_a_gemm, + "jit": dsv3_fused_a_gemm, + "sgl_kernel": sgl_kernel_dsv3_fused_a_gemm, + "torch": lambda a, b: F.linear(a, b.T), + } + return _median_us(fn_map[provider], mat_a, mat_b) + + +@triton.testing.perf_report( + [ + triton.testing.Benchmark( + x_names=["num_tokens"], + x_vals=NUM_TOKENS_LIST, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name=f"dsv3-fused-a-gemm-bf16-K{hd_in}-N{HD_OUT}", + args={"hd_in": hd_in}, + ) + for hd_in in HD_IN_LIST + ] +) +def benchmark(num_tokens, provider, hd_in): + return _bench(num_tokens, provider, hd_in) + + +if __name__ == "__main__": + if is_hip_runtime() or get_jit_cuda_arch().major < 9: + print( + "dsv3_fused_a_gemm JIT kernel requires SM90+ (Hopper). Skipping benchmark." + ) + else: + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_dsv3_router_gemm.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_dsv3_router_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..8394054706be09facb8ba2f0f818def439d21f87 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_dsv3_router_gemm.py @@ -0,0 +1,66 @@ +"""Benchmark for DeepSeek V3 router GEMM (JIT kernel vs sgl_kernel AOT vs torch). + +Run on a Hopper (SM90+) GPU: + python -m sglang.jit_kernel.benchmark.bench_dsv3_router_gemm +""" + +import torch +import torch.nn.functional as F + +try: + from sgl_kernel import dsv3_router_gemm as sgl_kernel_dsv3_router_gemm +except ImportError: + sgl_kernel_dsv3_router_gemm = None + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.benchmark.utils import create_random +from sglang.jit_kernel.dsv3_router_gemm import dsv3_router_gemm +from sglang.jit_kernel.utils import get_jit_cuda_arch, is_hip_runtime +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +# sgl_kernel AOT kernel is specialized for hidden_dim=7168 only. +SGL_KERNEL_HIDDEN_DIM = 7168 + + +def _torch(mat_a, mat_b, out_dtype): + return F.linear(mat_a, mat_b).to(out_dtype) + + +FN_MAP = { + "jit": dsv3_router_gemm, + "sgl_kernel": sgl_kernel_dsv3_router_gemm, + "torch": _torch, +} + + +@marker.parametrize("num_experts", [256, 384], [256]) +@marker.parametrize("hidden_dim", [6144, 7168], [7168]) +@marker.parametrize("num_tokens", list(range(1, 17)), [1, 8, 16]) +@marker.parametrize("out_dtype", [torch.bfloat16, torch.float32]) +@marker.benchmark("provider", ["jit", "sgl_kernel", "torch"]) +def benchmark(num_experts, hidden_dim, num_tokens, out_dtype, provider): + if provider == "sgl_kernel": + if sgl_kernel_dsv3_router_gemm is None: + marker.skip("sgl_kernel dsv3_router_gemm not available in this build") + if hidden_dim != SGL_KERNEL_HIDDEN_DIM: + marker.skip("sgl_kernel AOT only supports hidden_dim=7168") + mat_a = create_random(num_tokens, hidden_dim) + mat_b = create_random(num_experts, hidden_dim) + return marker.do_bench( + FN_MAP[provider], + input_args=(mat_a, mat_b), + input_kwargs={"out_dtype": out_dtype}, + ) + + +if __name__ == "__main__": + if is_hip_runtime() or get_jit_cuda_arch().major < 9: + print( + "dsv3_router_gemm JIT kernel requires SM90+ (Hopper). Skipping benchmark." + ) + else: + benchmark.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_dsv4_fp4_indexer.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_dsv4_fp4_indexer.py new file mode 100644 index 0000000000000000000000000000000000000000..1e547cf70f5b539332f62f83f20ee436794d8e1c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_dsv4_fp4_indexer.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +import sys + +import torch +import triton + +from sglang.benchmark.bench_utils import run_bench +from sglang.jit_kernel.benchmark.utils import get_benchmark_range +from sglang.srt.utils import is_sm100_supported +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +try: + import deep_gemm + from deep_gemm.utils import per_token_cast_to_fp4 +except Exception: + deep_gemm = None + per_token_cast_to_fp4 = None + +HEAD_DIM = 128 +NUM_HEADS = 64 +BLOCK_KV = 64 +NEXT_N = 1 + +shape_range = get_benchmark_range( + full_range=[(256, 8192), (256, 32768)], + ci_range=[(256, 8192)], +) + + +def _pack_fp8_cache(k: torch.Tensor, *, num_blocks: int) -> torch.Tensor: + k = k.view(num_blocks, BLOCK_KV, 1, HEAD_DIM) + scale = k.abs().float().amax(dim=3, keepdim=True).clamp(1.0e-4) / 448.0 + k_fp8 = (k * (1.0 / scale)).to(torch.float8_e4m3fn) + buf = torch.empty( + (num_blocks, BLOCK_KV * (HEAD_DIM + 4)), dtype=torch.uint8, device="cuda" + ) + buf[:, : BLOCK_KV * HEAD_DIM].copy_( + k_fp8.view(num_blocks, BLOCK_KV * HEAD_DIM).view(torch.uint8) + ) + buf[:, BLOCK_KV * HEAD_DIM :].copy_( + scale.view(num_blocks, BLOCK_KV).view(torch.uint8) + ) + return buf.view(num_blocks, BLOCK_KV, 1, HEAD_DIM + 4) + + +def _pack_fp4_cache( + k_fp4: torch.Tensor, + k_sf: torch.Tensor, + *, + num_blocks: int, +) -> torch.Tensor: + buf = torch.empty((num_blocks, BLOCK_KV * 68), dtype=torch.uint8, device="cuda") + buf[:, : BLOCK_KV * 64].view(num_blocks, BLOCK_KV, 64).copy_( + k_fp4.view(torch.uint8).view(num_blocks, BLOCK_KV, 64) + ) + buf[:, BLOCK_KV * 64 :].view(num_blocks, BLOCK_KV, 4).copy_( + k_sf.contiguous().view(torch.uint8).view(num_blocks, BLOCK_KV, 4) + ) + return buf.view(num_blocks, BLOCK_KV, 1, 68) + + +def _make_case(batch: int, seq_len_kv: int): + if deep_gemm is None or per_token_cast_to_fp4 is None: + raise RuntimeError("DeepGEMM is required for this benchmark.") + + blocks_per_seq = triton.cdiv(seq_len_kv, BLOCK_KV) + padded_len = blocks_per_seq * BLOCK_KV + num_blocks = batch * blocks_per_seq + num_cache_tokens = num_blocks * BLOCK_KV + page_table = torch.arange(num_blocks, dtype=torch.int32, device="cuda").view( + batch, blocks_per_seq + ) + context_lens = torch.full( + (batch, NEXT_N), seq_len_kv, dtype=torch.int32, device="cuda" + ) + schedule = deep_gemm.get_paged_mqa_logits_metadata( + context_lens, BLOCK_KV, deep_gemm.get_num_sms(), indices=None + ) + + q = torch.randn( + batch, NEXT_N, NUM_HEADS, HEAD_DIM, device="cuda", dtype=torch.bfloat16 + ) + k = torch.randn(num_cache_tokens, HEAD_DIM, device="cuda", dtype=torch.bfloat16) + weights = torch.randn(batch * NEXT_N, NUM_HEADS, device="cuda", dtype=torch.float32) + + q_scale = q.abs().float().amax(dim=-1, keepdim=True).clamp(1.0e-4) / 448.0 + q_fp8 = (q.float() / q_scale).clamp(-448.0, 448.0).to(torch.float8_e4m3fn) + weights_fp8 = ( + weights.view(batch, NEXT_N, NUM_HEADS)[:, :, :, None] * q_scale + ).view(batch * NEXT_N, NUM_HEADS) + k_cache_fp8 = _pack_fp8_cache(k, num_blocks=num_blocks) + + q_fp4_flat, q_sf_flat = per_token_cast_to_fp4( + q.view(-1, HEAD_DIM), use_ue8m0=True, gran_k=32, use_packed_ue8m0=True + ) + q_fp4 = q_fp4_flat.view(batch, NEXT_N, NUM_HEADS, HEAD_DIM // 2) + q_sf = q_sf_flat.view(batch, NEXT_N, NUM_HEADS) + k_fp4, k_sf = per_token_cast_to_fp4( + k, use_ue8m0=True, gran_k=32, use_packed_ue8m0=True + ) + k_cache_fp4 = _pack_fp4_cache(k_fp4, k_sf, num_blocks=num_blocks) + + return { + "padded_len": padded_len, + "page_table": page_table, + "context_lens": context_lens, + "schedule": schedule, + "q_fp8": q_fp8, + "weights_fp8": weights_fp8, + "k_cache_fp8": k_cache_fp8, + "q_fp4": q_fp4, + "q_sf": q_sf, + "weights": weights, + "k_cache_fp4": k_cache_fp4, + } + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch", "seq_len_kv"], + x_vals=shape_range, + x_log=False, + line_arg="provider", + line_vals=["fp8", "fp4"], + line_names=["Default FP8 indexer", "FP4 indexer"], + styles=[("blue", "-"), ("green", "-")], + ylabel="us", + plot_name="dsv4-fp4-indexer-performance", + args={}, + ) +) +def benchmark(batch: int, seq_len_kv: int, provider: str): + case = _make_case(batch, seq_len_kv) + if provider == "fp8": + fn = lambda: deep_gemm.fp8_paged_mqa_logits( + case["q_fp8"], + case["k_cache_fp8"], + case["weights_fp8"], + case["context_lens"], + case["page_table"], + case["schedule"], + case["padded_len"], + clean_logits=False, + indices=None, + ) + elif provider == "fp4": + fn = lambda: deep_gemm.fp8_fp4_paged_mqa_logits( + (case["q_fp4"], case["q_sf"]), + case["k_cache_fp4"], + case["weights"], + case["context_lens"], + case["page_table"], + case["schedule"], + case["padded_len"], + clean_logits=False, + logits_dtype=torch.float32, + indices=None, + ) + else: + raise ValueError(f"Unknown provider: {provider}") + return tuple(t * 1000 for t in run_bench(fn, use_cuda_graph=False)) + + +if __name__ == "__main__": + if not is_sm100_supported(): + print("[skip] DeepSeek V4 FP4 indexer benchmark requires SM100 CUDA.") + sys.exit(0) + if deep_gemm is None or per_token_cast_to_fp4 is None: + print("[skip] DeepGEMM is unavailable.") + sys.exit(0) + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_fused_eh_norm.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_fused_eh_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..f6a7519788f583faf01335534f6545cf7ffab30a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_fused_eh_norm.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import torch + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.fused_eh_norm import fused_eh_norm +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=6, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +EPS = 1e-6 + + +def reference( + x: torch.Tensor, + prev: torch.Tensor, + ew: torch.Tensor, + hw: torch.Tensor, + eps: float, +) -> torch.Tensor: + xf = x.float() + pf = prev.float() + x_var = xf.pow(2).mean(dim=-1, keepdim=True) + p_var = pf.pow(2).mean(dim=-1, keepdim=True) + return torch.cat( + ( + (xf * torch.rsqrt(x_var + eps) * ew.float()).to(x.dtype), + (pf * torch.rsqrt(p_var + eps) * hw.float()).to(prev.dtype), + ), + dim=-1, + ) + + +FN_MAP = { + "jit": fused_eh_norm, + "torch": reference, +} + + +@marker.parametrize("dtype", [torch.bfloat16, torch.float16], [torch.bfloat16]) +@marker.parametrize("hidden_size", [6144, 7168], [7168]) +@marker.parametrize("num_tokens", [1, 4, 6, 8, 16, 32, 128, 512], [1, 6]) +@marker.benchmark("impl", ["jit", "torch"]) +def benchmark(num_tokens: int, hidden_size: int, dtype: torch.dtype, impl: str): + x = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) + prev = torch.randn_like(x) + ew = torch.randn(hidden_size, device="cuda", dtype=dtype) + hw = torch.randn(hidden_size, device="cuda", dtype=dtype) + + expected = reference(x, prev, ew, hw, EPS) + actual = fused_eh_norm(x, prev, ew, hw, EPS) + torch.testing.assert_close(actual.float(), expected.float(), rtol=1e-2, atol=1e-2) + + return marker.do_bench( + FN_MAP[impl], + input_args=(x, prev, ew, hw, EPS), + memory_args=(x, prev, ew, hw), + memory_output="out", + ) + + +if __name__ == "__main__": + benchmark.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_fused_qknorm_rope.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_fused_qknorm_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..ce357ee092f92f054e61ee122c0392183bfe78f2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_fused_qknorm_rope.py @@ -0,0 +1,269 @@ +""" +Benchmark: fused_qknorm_rope JIT vs AOT (sgl_kernel) + +Measures throughput (µs) for fused_qk_norm_rope across typical +LLM configurations (head_dim × num_heads × num_tokens). + +Run: + python test/registered/jit/benchmark/bench_fused_qknorm_rope.py +""" + +import itertools + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import get_benchmark_range, run_benchmark +from sglang.jit_kernel.fused_qknorm_rope import ( + fused_qk_norm_rope as fused_qk_norm_rope_jit, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=6, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +try: + from sgl_kernel import fused_qk_norm_rope as fused_qk_norm_rope_aot + + AOT_AVAILABLE = True +except ImportError: + fused_qk_norm_rope_aot = None + AOT_AVAILABLE = False + +# --------------------------------------------------------------------------- +# Benchmark configuration +# --------------------------------------------------------------------------- + +NUM_TOKENS_RANGE = get_benchmark_range( + full_range=[1, 64, 256, 1024, 4096], + ci_range=[64, 512], +) + +# (head_dim, num_heads_q, num_heads_k, num_heads_v) — typical MoE/dense configs +MODEL_CONFIGS = get_benchmark_range( + full_range=[ + (64, 32, 8, 8), # small + (128, 32, 8, 8), # typical (e.g. Qwen3-8B) + (256, 16, 4, 4), # large head_dim + ], + ci_range=[(128, 32, 8, 8)], +) + +# Real production shapes (self-attention; num_heads_k == num_heads_v == num_heads_q). +# Format: (name, num_tokens, num_heads_q, num_heads_k, num_heads_v, head_dim, rotary_dim) +PRODUCTION_SHAPES = [ + ("flux_1024", 4096, 24, 24, 24, 128, 128), + ("qwen_image_1024", 4096, 32, 32, 32, 128, 128), + ("qwen_image_partial", 4096, 32, 32, 32, 128, 64), + ("zimage_1024", 4096, 30, 30, 30, 128, 128), + ("batch2_medium", 4096, 24, 24, 24, 128, 128), # B=2, T=2048 +] + +LINE_VALS = ["jit", "aot"] if AOT_AVAILABLE else ["jit"] +LINE_NAMES = ["JIT (new)", "AOT sgl_kernel"] if AOT_AVAILABLE else ["JIT (new)"] +STYLES = [("blue", "--"), ("orange", "-")] if AOT_AVAILABLE else [("blue", "--")] + + +# --------------------------------------------------------------------------- +# Benchmark: fused_qk_norm_rope (interleave style, no YaRN) +# --------------------------------------------------------------------------- + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["num_tokens", "head_dim", "num_heads_q", "num_heads_k", "num_heads_v"], + x_vals=[ + (nt, hd, nq, nk, nv) + for nt, (hd, nq, nk, nv) in itertools.product( + NUM_TOKENS_RANGE, MODEL_CONFIGS + ) + ], + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="fused-qknorm-rope-performance", + args={}, + ) +) +def bench_fused_qknorm_rope( + num_tokens: int, + head_dim: int, + num_heads_q: int, + num_heads_k: int, + num_heads_v: int, + provider: str, +): + device = "cuda" + total_heads = num_heads_q + num_heads_k + num_heads_v + + qkv = torch.randn( + (num_tokens, total_heads * head_dim), dtype=torch.bfloat16, device=device + ) + q_weight = torch.ones(head_dim, dtype=torch.bfloat16, device=device) + k_weight = torch.ones(head_dim, dtype=torch.bfloat16, device=device) + position_ids = torch.arange(num_tokens, dtype=torch.int32, device=device) + + common_kwargs = dict( + num_heads_q=num_heads_q, + num_heads_k=num_heads_k, + num_heads_v=num_heads_v, + head_dim=head_dim, + eps=1e-5, + q_weight=q_weight, + k_weight=k_weight, + base=10000.0, + is_neox=False, + position_ids=position_ids, + factor=1.0, + low=1.0, + high=32.0, + attention_factor=1.0, + rotary_dim=head_dim, + ) + + if provider == "jit": + fn = lambda: fused_qk_norm_rope_jit(qkv.clone(), **common_kwargs) + elif provider == "aot": + fn = lambda: fused_qk_norm_rope_aot(qkv.clone(), **common_kwargs) + else: + raise ValueError(f"Unknown provider: {provider}") + + return run_benchmark(fn) + + +# --------------------------------------------------------------------------- +# Benchmark: fused_qk_norm_rope — real production shapes (with speedup column) +# --------------------------------------------------------------------------- + + +def bench_fused_qknorm_rope_production(): + device = "cuda" + header = f"{'name':<22} {'tokens':>6} {'nq':>4} {'nk':>4} {'nv':>4} {'hd':>4} {'rdim':>5} {'JIT(us)':>9} {'AOT(us)':>9} {'speedup':>8}" + sep = "-" * len(header) + print("\nfused-qknorm-rope-production-shapes:") + print(sep) + print(header) + print(sep) + + for ( + name, + num_tokens, + num_heads_q, + num_heads_k, + num_heads_v, + head_dim, + rotary_dim, + ) in PRODUCTION_SHAPES: + total_heads = num_heads_q + num_heads_k + num_heads_v + qkv = torch.randn( + (num_tokens, total_heads * head_dim), dtype=torch.bfloat16, device=device + ) + q_weight = torch.ones(head_dim, dtype=torch.bfloat16, device=device) + k_weight = torch.ones(head_dim, dtype=torch.bfloat16, device=device) + position_ids = torch.arange(num_tokens, dtype=torch.int32, device=device) + + common_kwargs = dict( + num_heads_q=num_heads_q, + num_heads_k=num_heads_k, + num_heads_v=num_heads_v, + head_dim=head_dim, + eps=1e-5, + q_weight=q_weight, + k_weight=k_weight, + base=10000.0, + is_neox=False, + position_ids=position_ids, + factor=1.0, + low=1.0, + high=32.0, + attention_factor=1.0, + rotary_dim=rotary_dim, + ) + + jit_us, _, _ = run_benchmark( + lambda: fused_qk_norm_rope_jit(qkv.clone(), **common_kwargs) + ) + if AOT_AVAILABLE: + aot_us, _, _ = run_benchmark( + lambda: fused_qk_norm_rope_aot(qkv.clone(), **common_kwargs) + ) + speedup = f"{aot_us / jit_us:.2f}x" + aot_str = f"{aot_us:9.3f}" + else: + aot_str = f"{'N/A':>9}" + speedup = "N/A" + + print( + f"{name:<22} {num_tokens:>6} {num_heads_q:>4} {num_heads_k:>4} {num_heads_v:>4}" + f" {head_dim:>4} {rotary_dim:>5} {jit_us:9.3f} {aot_str} {speedup:>8}" + ) + print(sep) + + +# --------------------------------------------------------------------------- +# Quick correctness diff +# --------------------------------------------------------------------------- + + +def calculate_diff(): + if not AOT_AVAILABLE: + print("sgl_kernel not available — skipping AOT diff check") + return + + device = "cuda" + print("Correctness diff (JIT vs AOT):") + + for head_dim, is_neox in [(64, False), (128, False), (128, True), (256, False)]: + num_tokens = 32 + num_heads_q, num_heads_k, num_heads_v = 4, 2, 2 + total_heads = num_heads_q + num_heads_k + num_heads_v + + qkv = torch.randn( + (num_tokens, total_heads * head_dim), dtype=torch.bfloat16, device=device + ) + q_weight = torch.ones(head_dim, dtype=torch.bfloat16, device=device) + k_weight = torch.ones(head_dim, dtype=torch.bfloat16, device=device) + position_ids = torch.arange(num_tokens, dtype=torch.int32, device=device) + + common = dict( + num_heads_q=num_heads_q, + num_heads_k=num_heads_k, + num_heads_v=num_heads_v, + head_dim=head_dim, + eps=1e-5, + q_weight=q_weight, + k_weight=k_weight, + base=10000.0, + is_neox=is_neox, + position_ids=position_ids, + factor=1.0, + low=1.0, + high=32.0, + attention_factor=1.0, + rotary_dim=head_dim, + ) + + qkv_jit = qkv.clone() + fused_qk_norm_rope_jit(qkv_jit, **common) + qkv_aot = qkv.clone() + fused_qk_norm_rope_aot(qkv_aot, **common) + + match = torch.allclose(qkv_jit.float(), qkv_aot.float(), atol=1e-2, rtol=1e-2) + status = "OK" if match else "MISMATCH" + max_err = (qkv_jit.float() - qkv_aot.float()).abs().max().item() + print( + f" head_dim={head_dim:3d} is_neox={str(is_neox):5s} " + f"max_err={max_err:.2e} [{status}]" + ) + + +if __name__ == "__main__": + calculate_diff() + print() + bench_fused_qknorm_rope.run(print_data=True) + print() + bench_fused_qknorm_rope_production() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_hadamard.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_hadamard.py new file mode 100644 index 0000000000000000000000000000000000000000..bf1d6e712b3a789fc415f48aba84aaf64cadd71f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_hadamard.py @@ -0,0 +1,121 @@ +import itertools +import math +from typing import Tuple + +import torch +import torch.nn.functional as F +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + DEFAULT_DTYPE, + get_benchmark_range, + run_benchmark, +) +from sglang.jit_kernel.hadamard import hadamard_transform +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +# AOT kernel: might not be available in all environments. +# This is used for performance baseline comparison. +try: + from sgl_kernel import hadamard_transform as hadamard_transform_aot + + AOT_AVAILABLE = True +except Exception: + AOT_AVAILABLE = False + +# Naive reference implementation using scipy hadamard matrix. +try: + from scipy.linalg import hadamard + + SCIPY_AVAILABLE = True +except ImportError: + SCIPY_AVAILABLE = False + +# CI environment uses simplified parameters +batch_sizes = get_benchmark_range( + full_range=[1, 16, 64, 256], + ci_range=[16], +) +dim_range = get_benchmark_range( + full_range=[64, 256, 1024, 4096, 8192, 16384, 32768], + ci_range=[1024], +) + + +# Naive reference implementation using precomputed scipy hadamard matrix. +def torch_hadamard_transform(x, scale, H, dim, dim_padded): + flat = x.reshape(-1, dim) + if dim != dim_padded: + flat = F.pad(flat, (0, dim_padded - dim)) + out = F.linear(flat, H) * scale + return out[..., :dim].reshape(x.shape) + + +available_providers = ["jit_kernel"] +available_names = ["JIT Kernel"] +available_styles = [("red", "-")] + +if AOT_AVAILABLE: + available_providers.insert(0, "aot_kernel") + available_names.insert(0, "AOT Kernel") + available_styles.insert(0, ("green", "-")) + +if SCIPY_AVAILABLE: + available_providers.append("naive") + available_names.append("Naive (scipy)") + available_styles.append(("blue", "-")) + +configs = list(itertools.product(batch_sizes, dim_range)) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch_size", "dim"], + x_vals=[list(c) for c in configs], + line_arg="provider", + line_vals=available_providers, + line_names=available_names, + styles=available_styles, + ylabel="us", + plot_name="hadamard-transform-performance", + args={}, + ) +) +def benchmark(batch_size: int, dim: int, provider: str) -> Tuple[float, float, float]: + scale = 1.0 / math.sqrt(dim) + x = torch.randn(batch_size, dim, device=DEFAULT_DEVICE, dtype=DEFAULT_DTYPE) + + FN_MAP = { + "jit_kernel": lambda: hadamard_transform(x.clone(), scale=scale), + } + if AOT_AVAILABLE: + FN_MAP["aot_kernel"] = lambda: hadamard_transform_aot(x.clone(), scale=scale) + if SCIPY_AVAILABLE: + # Precompute Hadamard matrix on GPU to avoid CPU-GPU transfer + # during CUDA graph capture. + log_dim = math.ceil(math.log2(dim)) if dim > 0 else 0 + dim_padded = 2**log_dim if dim > 0 else 1 + H = torch.tensor( + hadamard(dim_padded, dtype=float), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + FN_MAP["naive"] = lambda: torch_hadamard_transform( + x.clone(), scale, H, dim, dim_padded + ) + + fn = FN_MAP[provider] + return run_benchmark(fn) + + +if __name__ == "__main__": + print("=" * 80) + print("Benchmarking Fast Hadamard Transform") + print("=" * 80) + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_hicache.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_hicache.py new file mode 100644 index 0000000000000000000000000000000000000000..11d271ce68a9bb73fcf4db63e9449e046e8fad30 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_hicache.py @@ -0,0 +1,423 @@ +"""Benchmark for HiCache JIT kernel performance. + +This benchmark tests the performance of KV cache transfer operations +between GPU and CPU (host pinned memory), comparing: +- SGL AOT Kernel: Pre-compiled transfer_kv kernels from sgl_kernel +- SGL JIT Kernel: JIT-compiled hicache kernels +- PyTorch Indexing: Plain PyTorch index copy +- PyTorch 2 Stream: PyTorch implementation using 2 CUDA streams + +Tests cover: +- One Layer: CPU->GPU +- All Layer: GPU->CPU + +Note: Uses do_bench instead of do_bench_cudagraph since CUDA graph +capture doesn't support CPU-GPU memory transfers. +""" + +import itertools +import os +from dataclasses import dataclass +from typing import Tuple + +import torch +import triton +import triton.testing +from sgl_kernel import transfer_kv_all_layer, transfer_kv_per_layer + +from sglang.jit_kernel.benchmark.utils import DEFAULT_QUANTILES, get_benchmark_range +from sglang.jit_kernel.hicache import ( + can_use_hicache_jit_kernel, + transfer_hicache_all_layer, + transfer_hicache_one_layer, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=29, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +DISABLE_TORCH = os.environ.get("DISABLE_TORCH", "0") == "1" +PAGE_SIZE = 1 +ENABLE_SORT = True +GPU_CACHE_SIZE = 256 * 1024 # 256K tokens on GPU +HOST_CACHE_SIZE = 512 * 1024 # 512K tokens on CPU +NUM_LAYERS = 8 + + +@dataclass(frozen=True) +class HiCacheCache: + k_cache_cuda: torch.Tensor + v_cache_cuda: torch.Tensor + k_cache_host: torch.Tensor + v_cache_host: torch.Tensor + + def get_slice(self, num_layers: int, element_size: int) -> "HiCacheCache": + def slice_cuda(t: torch.Tensor) -> torch.Tensor: + needed_cuda = num_layers * GPU_CACHE_SIZE + return t.view(-1, element_size)[:needed_cuda].unflatten(0, (num_layers, -1)) + + def slice_host(t: torch.Tensor) -> torch.Tensor: + needed_host = num_layers * HOST_CACHE_SIZE + return t.view(-1, element_size)[:needed_host].unflatten(0, (num_layers, -1)) + + return HiCacheCache( + k_cache_cuda=slice_cuda(self.k_cache_cuda), + v_cache_cuda=slice_cuda(self.v_cache_cuda), + k_cache_host=slice_host(self.k_cache_host), + v_cache_host=slice_host(self.v_cache_host), + ) + + +def gen_indices( + size: int, max_size: int, *, page_size: int = PAGE_SIZE +) -> torch.Tensor: + def align(x: int) -> int: + return (x + page_size - 1) // page_size + + assert size <= max_size and max_size % page_size == 0 + indices = torch.randperm(align(max_size))[: align(size)] + offsets = torch.arange(page_size) + return (indices[:, None] * page_size + offsets).flatten().cuda()[:size] + + +def sglang_aot_transfer_one( + k_cache_dst: torch.Tensor, + v_cache_dst: torch.Tensor, + indices_dst: torch.Tensor, + k_cache_src: torch.Tensor, + v_cache_src: torch.Tensor, + indices_src: torch.Tensor, + item_size: int, +) -> None: + """SGL AOT Kernel for single layer transfer.""" + transfer_kv_per_layer( + k_cache_src, + k_cache_dst, + v_cache_src, + v_cache_dst, + indices_src, + indices_dst, + item_size, + ) + + +def sglang_jit_transfer_one( + k_cache_dst: torch.Tensor, + v_cache_dst: torch.Tensor, + indices_dst: torch.Tensor, + k_cache_src: torch.Tensor, + v_cache_src: torch.Tensor, + indices_src: torch.Tensor, + element_dim: int, +) -> None: + """SGL JIT Kernel for single layer transfer.""" + transfer_hicache_one_layer( + k_cache_dst, + v_cache_dst, + indices_dst, + k_cache_src, + v_cache_src, + indices_src, + element_dim=element_dim, + ) + + +def sglang_aot_transfer_all( + k_ptrs_dst: torch.Tensor, + v_ptrs_dst: torch.Tensor, + indices_dst: torch.Tensor, + k_ptrs_src: torch.Tensor, + v_ptrs_src: torch.Tensor, + indices_src: torch.Tensor, + item_size: int, + num_layers: int, +) -> None: + """SGL AOT Kernel for all layer transfer.""" + transfer_kv_all_layer( + k_ptrs_src, + k_ptrs_dst, + v_ptrs_src, + v_ptrs_dst, + indices_src, + indices_dst, + item_size, + num_layers, + ) + + +def sglang_jit_transfer_all( + k_ptrs_dst: torch.Tensor, + v_ptrs_dst: torch.Tensor, + indices_dst: torch.Tensor, + k_ptrs_src: torch.Tensor, + v_ptrs_src: torch.Tensor, + indices_src: torch.Tensor, + stride_bytes: int, + element_size: int, +) -> None: + """SGL JIT Kernel for all layer transfer.""" + transfer_hicache_all_layer( + k_ptrs_dst, + v_ptrs_dst, + indices_dst, + k_ptrs_src, + v_ptrs_src, + indices_src, + kv_cache_src_stride_bytes=stride_bytes, + kv_cache_dst_stride_bytes=stride_bytes, + element_size=element_size, + ) + + +def pytorch_transfer( + k_cache_dst: torch.Tensor, + v_cache_dst: torch.Tensor, + indices_dst_on_dst: torch.Tensor, + k_cache_src: torch.Tensor, + v_cache_src: torch.Tensor, + indices_src_on_src: torch.Tensor, +) -> None: + """PyTorch indexing baseline.""" + dst_device = k_cache_dst.device + k_cache_dst[indices_dst_on_dst] = k_cache_src[indices_src_on_src].to(dst_device) + v_cache_dst[indices_dst_on_dst] = v_cache_src[indices_src_on_src].to(dst_device) + + +# Benchmark configuration + +BS_RANGE = get_benchmark_range( + full_range=[2**n for n in range(0, 16)], + ci_range=[16], +) +ELEMENT_SIZE_RANGE = get_benchmark_range( + full_range=[64, 128, 256, 512, 1024], + ci_range=[1024], +) + +LINE_VALS = ["aot", "jit", "torch"] +LINE_NAMES = ["SGL AOT Kernel", "SGL JIT Kernel", "PyTorch"] +STYLES = [("orange", "-"), ("blue", "--"), ("red", ":")] + +CONFIGS = list(itertools.product(ELEMENT_SIZE_RANGE, BS_RANGE)) + + +# ============================================================================= +# One Layer Benchmarks +# ============================================================================= + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["element_size", "batch_size"], + x_vals=CONFIGS, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="hicache-one-layer-h2d", + args={}, + ) +) +def benchmark_one_layer_h2d( + element_size: int, batch_size: int, provider: str +) -> Tuple[float, float, float]: + """One Layer: Host (CPU) -> Device (GPU).""" + global cache + cache_local = cache.get_slice(num_layers=NUM_LAYERS, element_size=element_size) + k_cache_src = cache_local.k_cache_host + v_cache_src = cache_local.v_cache_host + k_cache_dst = cache_local.k_cache_cuda + v_cache_dst = cache_local.v_cache_cuda + torch.manual_seed(batch_size * 65536 + element_size) + indices_src_gpu = gen_indices(batch_size, HOST_CACHE_SIZE) + indices_dst_gpu = gen_indices(batch_size, GPU_CACHE_SIZE) + + if ENABLE_SORT: + indices_src_gpu, mapping = indices_src_gpu.sort() + indices_dst_gpu = indices_dst_gpu[mapping] + indices_src_cpu = indices_src_gpu.cpu() + torch.cuda.synchronize() + + element_bytes = element_size * k_cache_src.element_size() + + FN_MAP = { + "aot": lambda: [ + sglang_aot_transfer_one( + k_cache_dst[i], + v_cache_dst[i], + indices_dst_gpu, + k_cache_src[i], + v_cache_src[i], + indices_src_gpu, + element_bytes, + ) + for i in range(NUM_LAYERS) + ], + "jit": lambda: [ + sglang_jit_transfer_one( + k_cache_dst[i], + v_cache_dst[i], + indices_dst_gpu, + k_cache_src[i], + v_cache_src[i], + indices_src_gpu, + element_size, + ) + for i in range(NUM_LAYERS) + ], + "torch": lambda: [ + pytorch_transfer( + k_cache_dst[i], + v_cache_dst[i], + indices_dst_gpu, + k_cache_src[i], + v_cache_src[i], + indices_src_cpu, + ) + for i in range(NUM_LAYERS) + ], + } + + if provider == "jit" and not can_use_hicache_jit_kernel(element_size=element_bytes): + return (float("nan"), float("nan"), float("nan")) + + if DISABLE_TORCH and provider in ["torch"]: + return (float("nan"), float("nan"), float("nan")) + + ms, min_ms, max_ms = triton.testing.do_bench( # type: ignore + FN_MAP[provider], quantiles=DEFAULT_QUANTILES, warmup=5, rep=25 + ) + return ( + 1000 * ms / NUM_LAYERS, + 1000 * max_ms / NUM_LAYERS, + 1000 * min_ms / NUM_LAYERS, + ) + + +# ============================================================================= +# All Layer Benchmarks +# ============================================================================= + + +def _create_ptr_tensor(tensors, device="cuda"): + """Create a tensor of data pointers.""" + return torch.tensor( + [t.data_ptr() for t in tensors], + dtype=torch.uint64, + device=device, + ) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["element_size", "batch_size"], + x_vals=CONFIGS, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="hicache-all-layer-d2h", + args={}, + ) +) +def benchmark_all_layer_d2h( + element_size: int, batch_size: int, provider: str +) -> Tuple[float, float, float]: + """All Layer: Device (GPU) -> Host (CPU).""" + global cache + cache_local = cache.get_slice(num_layers=NUM_LAYERS, element_size=element_size) + k_caches_src = cache_local.k_cache_cuda + v_caches_src = cache_local.v_cache_cuda + k_caches_dst = cache_local.k_cache_host + v_caches_dst = cache_local.v_cache_host + torch.manual_seed(batch_size * 65536 + element_size) + + indices_src_gpu = gen_indices(batch_size, GPU_CACHE_SIZE) + indices_dst_gpu = gen_indices(batch_size, HOST_CACHE_SIZE) + if ENABLE_SORT: + indices_dst_gpu, mapping = indices_dst_gpu.sort() + indices_src_gpu = indices_src_gpu[mapping] + indices_dst_cpu = indices_dst_gpu.cpu() + torch.cuda.synchronize() + + element_bytes = element_size * k_caches_src.element_size() + + k_ptrs_src = _create_ptr_tensor([k_caches_src[i] for i in range(NUM_LAYERS)]) + v_ptrs_src = _create_ptr_tensor([v_caches_src[i] for i in range(NUM_LAYERS)]) + k_ptrs_dst = _create_ptr_tensor([k_caches_dst[i] for i in range(NUM_LAYERS)]) + v_ptrs_dst = _create_ptr_tensor([v_caches_dst[i] for i in range(NUM_LAYERS)]) + + FN_MAP = { + "aot": lambda: sglang_aot_transfer_all( + k_ptrs_dst, + v_ptrs_dst, + indices_dst_gpu, + k_ptrs_src, + v_ptrs_src, + indices_src_gpu, + element_bytes, + NUM_LAYERS, + ), + "jit": lambda: sglang_jit_transfer_all( + k_ptrs_dst, + v_ptrs_dst, + indices_dst_gpu, + k_ptrs_src, + v_ptrs_src, + indices_src_gpu, + element_bytes, + element_bytes, + ), + "torch": lambda: [ + pytorch_transfer( + k_caches_dst[i], + v_caches_dst[i], + indices_dst_cpu, + k_caches_src[i], + v_caches_src[i], + indices_src_gpu, + ) + for i in range(NUM_LAYERS) + ], + } + + if provider == "jit" and not can_use_hicache_jit_kernel(element_size=element_bytes): + return (float("nan"), float("nan"), float("nan")) + + if DISABLE_TORCH and provider in ["torch"]: + return (float("nan"), float("nan"), float("nan")) + + ms, min_ms, max_ms = triton.testing.do_bench( # type: ignore + FN_MAP[provider], quantiles=DEFAULT_QUANTILES, warmup=5, rep=25 + ) + return ( + 1000 * ms / NUM_LAYERS, + 1000 * max_ms / NUM_LAYERS, + 1000 * min_ms / NUM_LAYERS, + ) + + +if __name__ == "__main__": + MAX_SIZE = max(ELEMENT_SIZE_RANGE) + DEVICE_SHAPE = (NUM_LAYERS * GPU_CACHE_SIZE, MAX_SIZE) + HOST_SHAPE = (NUM_LAYERS * HOST_CACHE_SIZE, MAX_SIZE) + + cache = HiCacheCache( + k_cache_cuda=torch.empty(DEVICE_SHAPE, dtype=torch.bfloat16, device="cuda"), + v_cache_cuda=torch.empty(DEVICE_SHAPE, dtype=torch.bfloat16, device="cuda"), + k_cache_host=torch.empty(HOST_SHAPE, dtype=torch.bfloat16, pin_memory=True), + v_cache_host=torch.empty(HOST_SHAPE, dtype=torch.bfloat16, pin_memory=True), + ) + + print("=" * 60) + print("One Layer: Host -> Device (CPU -> GPU)") + print("=" * 60) + benchmark_one_layer_h2d.run(print_data=True) + + print("\n" + "=" * 60) + print("All Layer: Device -> Host (GPU -> CPU) [per-layer avg]") + print("=" * 60) + benchmark_all_layer_d2h.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_hisparse.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_hisparse.py new file mode 100644 index 0000000000000000000000000000000000000000..889b9f5c576355611e320c00a60b9f37e22cd05e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_hisparse.py @@ -0,0 +1,192 @@ +import itertools +from typing import Dict, Tuple + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import DEFAULT_DEVICE, DEFAULT_DTYPE +from sglang.jit_kernel.hisparse import load_cache_to_device_buffer_mla +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=12, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +DEVICE = DEFAULT_DEVICE +DTYPE = DEFAULT_DTYPE +TOP_K = 2048 +ITEM_SIZE_BYTES = 512 +MISS_RATES = [0.2, 0.001] +ROUNDS = 5 +WARMUP_ROUNDS = 5 +BATCH_SIZES = [1, 10, 100] +HOT_BUFFER_SIZES = [4096, 8192] +CONFIGS = [ + ( + batch_size, + hot_buffer_size, + miss_rate, + batch_size * round(TOP_K * miss_rate), + ) + for batch_size, hot_buffer_size, miss_rate in itertools.product( + BATCH_SIZES, HOT_BUFFER_SIZES, MISS_RATES + ) +] + +LINE_VALS = ["jit"] +LINE_NAMES = ["SGL JIT Kernel"] +STYLES = [("blue", "--")] + + +def _make_top_k_tokens( + num_hits: int, num_misses: int, hot_buffer_size: int +) -> torch.Tensor: + hit_tokens = torch.arange(num_hits, dtype=torch.int32, device=DEVICE) + miss_tokens = hot_buffer_size + torch.arange( + num_misses, dtype=torch.int32, device=DEVICE + ) + return torch.cat([hit_tokens, miss_tokens]) + + +def _miss_tokens_per_req(miss_rate: float) -> int: + return round(TOP_K * miss_rate) + + +def _build_inputs( + batch_size: int, hot_buffer_size: int, miss_rate: float +) -> Dict[str, torch.Tensor | int]: + dtype_bytes = torch.empty((), dtype=DTYPE).element_size() + kv_dim = ITEM_SIZE_BYTES // dtype_bytes + padded_buffer_size = hot_buffer_size + 1 + seq_len = hot_buffer_size + TOP_K + 1 + num_misses = _miss_tokens_per_req(miss_rate) + num_hits = TOP_K - num_misses + + top_k_row = _make_top_k_tokens(num_hits, num_misses, hot_buffer_size) + top_k_tokens = top_k_row.view(1, -1).repeat(batch_size, 1).contiguous() + + host_stride = seq_len + total_host_tokens = batch_size * host_stride + host_cache = torch.empty( + (total_host_tokens, 1, kv_dim), dtype=DTYPE, device="cpu", pin_memory=True + ) + host_cache.copy_(torch.randn_like(host_cache)) + + total_device_tokens = batch_size * padded_buffer_size + device_buffer = torch.empty( + (total_device_tokens, 1, kv_dim), dtype=DTYPE, device=DEVICE + ) + device_buffer.normal_() + + device_buffer_locs = torch.arange( + total_device_tokens, dtype=torch.int32, device=DEVICE + ).view(batch_size, padded_buffer_size) + device_buffer_tokens = torch.full( + (batch_size, padded_buffer_size), -1, dtype=torch.int32, device=DEVICE + ) + device_buffer_tokens[:, :hot_buffer_size] = torch.arange( + hot_buffer_size, dtype=torch.int32, device=DEVICE + ) + + lru_slots = ( + torch.arange(hot_buffer_size, dtype=torch.int16, device=DEVICE) + .view(1, -1) + .repeat(batch_size, 1) + ) + + return { + "top_k_tokens": top_k_tokens, + "device_buffer_tokens": device_buffer_tokens, + "initial_device_buffer_tokens": device_buffer_tokens.clone(), + "host_cache_locs": torch.arange( + total_host_tokens, dtype=torch.int64, device=DEVICE + ).view(batch_size, host_stride), + "device_buffer_locs": device_buffer_locs, + "host_cache": host_cache, + "device_buffer": device_buffer, + "top_k_device_locs": torch.empty( + (batch_size, TOP_K), dtype=torch.int32, device=DEVICE + ), + "req_pool_indices": torch.arange(batch_size, dtype=torch.int64, device=DEVICE), + "seq_lens": torch.full( + (batch_size,), seq_len, dtype=torch.int32, device=DEVICE + ), + "lru_slots": lru_slots, + "initial_lru_slots": lru_slots.clone(), + "num_real_reqs": torch.tensor([batch_size], dtype=torch.int32, device=DEVICE), + } + + +def _time_kernel(batch_size: int, hot_buffer_size: int, miss_rate: float) -> float: + state = _build_inputs(batch_size, hot_buffer_size, miss_rate) + + def run_once(): + state["device_buffer_tokens"].copy_(state["initial_device_buffer_tokens"]) + state["lru_slots"].copy_(state["initial_lru_slots"]) + state["top_k_device_locs"].fill_(-1) + load_cache_to_device_buffer_mla( + top_k_tokens=state["top_k_tokens"], + device_buffer_tokens=state["device_buffer_tokens"], + host_cache_locs=state["host_cache_locs"], + device_buffer_locs=state["device_buffer_locs"], + host_cache=state["host_cache"], + device_buffer=state["device_buffer"], + top_k_device_locs=state["top_k_device_locs"], + req_pool_indices=state["req_pool_indices"], + seq_lens=state["seq_lens"], + lru_slots=state["lru_slots"], + item_size_bytes=ITEM_SIZE_BYTES, + num_top_k=TOP_K, + hot_buffer_size=hot_buffer_size, + block_size=1024, + num_real_reqs=state["num_real_reqs"], + ) + + run_once() + torch.cuda.synchronize() + for _ in range(WARMUP_ROUNDS): + run_once() + torch.cuda.synchronize() + + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + start.record() + for _ in range(ROUNDS): + run_once() + end.record() + torch.cuda.synchronize() + return start.elapsed_time(end) * 1000.0 / ROUNDS + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch_size", "hot_buffer_size", "miss_rate", "miss_tokens_cnt"], + x_vals=CONFIGS, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="hisparse-latency", + args={}, + ) +) +def benchmark_latency( + batch_size: int, + hot_buffer_size: int, + miss_rate: float, + miss_tokens_cnt: int, + provider: str, +) -> Tuple[float, float, float]: + assert provider == "jit" + batch_size = int(batch_size) + hot_buffer_size = int(hot_buffer_size) + miss_rate = float(miss_rate) + assert miss_tokens_cnt == batch_size * _miss_tokens_per_req(miss_rate) + avg_us = _time_kernel(batch_size, hot_buffer_size, miss_rate) + return avg_us, avg_us, avg_us + + +if __name__ == "__main__": + benchmark_latency.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_mla_kv_pack_quantize_fp8.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_mla_kv_pack_quantize_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..e60ba7740e2a7e6571418b94415296f77fbee1dd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_mla_kv_pack_quantize_fp8.py @@ -0,0 +1,216 @@ +"""Bench the hybrid ``mla_kv_pack_quantize_fp8`` against an inlined naive Triton baseline.""" + +import itertools +from typing import Tuple + +import torch +import triton +import triton.language as tl +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + DEFAULT_DTYPE, + DEFAULT_QUANTILES, + get_benchmark_range, +) +from sglang.jit_kernel.mla_kv_pack_quantize_fp8 import ( + mla_kv_pack_quantize_fp8 as hybrid_pack, +) +from sglang.jit_kernel.utils import is_arch_support_pdl +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=15, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +@triton.jit +def _triton_mla_kv_pack_quantize_fp8_kernel( + k_nope_ptr, + k_pe_ptr, + v_ptr, + k_out_ptr, + v_out_ptr, + k_scale_inv, + v_scale_inv, + s_total, + k_nope_stride_t, + k_nope_stride_h, + k_pe_stride_t, + v_stride_t, + v_stride_h, + k_out_stride_t, + k_out_stride_h, + v_out_stride_t, + v_out_stride_h, + QK_NOPE: tl.constexpr, + QK_ROPE: tl.constexpr, + V_HEAD: tl.constexpr, + FP8_DTYPE: tl.constexpr, + BLOCK_S: tl.constexpr, + ENABLE_PDL: tl.constexpr, +): + pid_s = tl.program_id(0) + pid_h = tl.program_id(1) + t_idx = pid_s * BLOCK_S + tl.arange(0, BLOCK_S) + t_mask = t_idx < s_total + nope_idx = tl.arange(0, QK_NOPE) + rope_idx = tl.arange(0, QK_ROPE) + v_idx = tl.arange(0, V_HEAD) + if ENABLE_PDL: + tl.extra.cuda.gdc_wait() + nope_off = ( + t_idx[:, None] * k_nope_stride_t + pid_h * k_nope_stride_h + nope_idx[None, :] + ) + k_nope = tl.load(k_nope_ptr + nope_off, mask=t_mask[:, None]) + pe_off = t_idx[:, None] * k_pe_stride_t + rope_idx[None, :] + k_pe = tl.load(k_pe_ptr + pe_off, mask=t_mask[:, None]) + v_off = t_idx[:, None] * v_stride_t + pid_h * v_stride_h + v_idx[None, :] + v = tl.load(v_ptr + v_off, mask=t_mask[:, None]) + k_nope_fp8 = (k_nope.to(tl.float32) * k_scale_inv).to(FP8_DTYPE) + k_pe_fp8 = (k_pe.to(tl.float32) * k_scale_inv).to(FP8_DTYPE) + v_fp8 = (v.to(tl.float32) * v_scale_inv).to(FP8_DTYPE) + k_out_base = t_idx[:, None] * k_out_stride_t + pid_h * k_out_stride_h + tl.store( + k_out_ptr + k_out_base + nope_idx[None, :], k_nope_fp8, mask=t_mask[:, None] + ) + tl.store( + k_out_ptr + k_out_base + QK_NOPE + rope_idx[None, :], + k_pe_fp8, + mask=t_mask[:, None], + ) + v_out_off = ( + t_idx[:, None] * v_out_stride_t + pid_h * v_out_stride_h + v_idx[None, :] + ) + tl.store(v_out_ptr + v_out_off, v_fp8, mask=t_mask[:, None]) + if ENABLE_PDL: + tl.extra.cuda.gdc_launch_dependents() + + +def _triton_pack(k_nope, k_pe, v, k_out, v_out): + s, num_heads, qk_nope = k_nope.shape + qk_rope = k_pe.shape[-1] + v_head = v.shape[-1] + k_pe_2d = k_pe.squeeze(1) if k_pe.dim() == 3 else k_pe + enable_pdl = is_arch_support_pdl() + if s < 512: + block_s, num_warps, num_stages = 1, 1, 2 + elif s < 2048: + block_s, num_warps, num_stages = 4, 2, 3 + else: + block_s, num_warps, num_stages = 16, 4, 3 + extra = {"launch_pdl": True} if enable_pdl else {} + grid = (triton.cdiv(s, block_s), num_heads) + _triton_mla_kv_pack_quantize_fp8_kernel[grid]( + k_nope, + k_pe_2d, + v, + k_out, + v_out, + 1.0, + 1.0, + s, + k_nope.stride(0), + k_nope.stride(1), + k_pe_2d.stride(0), + v.stride(0), + v.stride(1), + k_out.stride(0), + k_out.stride(1), + v_out.stride(0), + v_out.stride(1), + QK_NOPE=qk_nope, + QK_ROPE=qk_rope, + V_HEAD=v_head, + FP8_DTYPE=tl.float8e4nv, + BLOCK_S=block_s, + ENABLE_PDL=enable_pdl, + num_warps=num_warps, + num_stages=num_stages, + **extra, + ) + + +QK_NOPE = 128 +QK_ROPE = 64 +V_HEAD = 128 +NUM_HEADS = 32 +NUM_LAYERS = 8 + +BS_RANGE = get_benchmark_range( + full_range=[1, 4, 16, 64, 256, 1024, 4096, 8192, 16384], + ci_range=[1, 64, 1024, 4096, 16384], +) + +LINE_VALS = ["hybrid", "triton"] +LINE_NAMES = ["hybrid (v0+v1_flat)", "naive Triton"] +STYLES = [("green", "-"), ("red", "--")] +CONFIGS = list(itertools.product(BS_RANGE)) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch_size"], + x_vals=CONFIGS, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="mla-kv-pack-quantize-fp8-performance", + args={}, + ) +) +def benchmark(batch_size: int, provider: str) -> Tuple[float, float, float]: + k_nope = torch.randn( + (NUM_LAYERS, batch_size, NUM_HEADS, QK_NOPE), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + k_pe = torch.randn( + (NUM_LAYERS, batch_size, 1, QK_ROPE), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + v = torch.randn( + (NUM_LAYERS, batch_size, NUM_HEADS, V_HEAD), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + k_out = torch.empty( + (NUM_LAYERS, batch_size, NUM_HEADS, QK_NOPE + QK_ROPE), + dtype=torch.float8_e4m3fn, + device=DEFAULT_DEVICE, + ) + v_out = torch.empty( + (NUM_LAYERS, batch_size, NUM_HEADS, V_HEAD), + dtype=torch.float8_e4m3fn, + device=DEFAULT_DEVICE, + ) + torch.cuda.synchronize() + + if provider == "hybrid": + + def fn(): + for i in range(NUM_LAYERS): + hybrid_pack(k_nope[i], k_pe[i], v[i], k_out=k_out[i], v_out=v_out[i]) + + else: + + def fn(): + for i in range(NUM_LAYERS): + _triton_pack(k_nope[i], k_pe[i], v[i], k_out[i], v_out[i]) + + ms, min_ms, max_ms = triton.testing.do_bench_cudagraph( + fn, quantiles=DEFAULT_QUANTILES + ) + return ( + 1000 * ms / NUM_LAYERS, + 1000 * max_ms / NUM_LAYERS, + 1000 * min_ms / NUM_LAYERS, + ) + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_moe_fused_gate.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_moe_fused_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..d58a112d90aead39fdd2af5f2bf846a12828b9c0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_moe_fused_gate.py @@ -0,0 +1,98 @@ +import torch +from sgl_kernel import kimi_k2_moe_fused_gate as aot_kimi_k2_gate +from sgl_kernel import moe_fused_gate as aot_moe_fused_gate + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.benchmark.utils import create_random +from sglang.jit_kernel.moe_fused_gate import moe_fused_gate, moe_fused_gate_jit +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=20, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +TOPK = 8 +SCALE = 2.5 +# AOT moe_fused_gate requires experts_per_group <= 32, so split experts into +# groups of 32 and select every group (topk_group == num_expert_group) to get a +# flat top-k. The 384-expert (3x128) layout uses the dedicated Kimi-K2 kernel. +AOT_GROUP_SIZE = 32 + + +@torch.compile +def torch_router(scores, bias, topk, scoring_func): + """Reference PyTorch router: scoring + bias + top-k + renorm + scale.""" + if scoring_func == "sigmoid": + activated = scores.sigmoid() + else: + activated = torch.nn.functional.softplus(scores).sqrt() + biased = activated + bias.unsqueeze(0) + _, ids = torch.topk(biased, k=topk, dim=-1) + weights = activated.gather(1, ids) + weights = weights / weights.sum(dim=-1, keepdim=True) + return weights * SCALE, ids.to(torch.int32) + + +@marker.parametrize("scoring_func", ["sigmoid", "sqrtsoftplus"]) +@marker.parametrize("num_experts", [128, 256, 384, 512], [256, 384]) +@marker.parametrize("num_tokens", [1, 4, 16, 64, 512, 1024, 8192], [16, 1024]) +@marker.benchmark("provider", ["triton", "jit", "aot", "torch"]) +def benchmark(num_tokens: int, num_experts: int, scoring_func: str, provider: str): + torch.manual_seed(0) + scores = create_random(num_tokens, num_experts, dtype=torch.float32) + bias = create_random(num_experts, dtype=torch.float32) + + common = dict( + topk=TOPK, + scoring_func=scoring_func, + renormalize=True, + routed_scaling_factor=SCALE, + apply_routed_scaling_factor_on_output=True, + ) + if provider == "triton": + return marker.do_bench( + moe_fused_gate, input_args=(scores, bias), input_kwargs=common + ) + if provider == "jit": + return marker.do_bench( + moe_fused_gate_jit, input_args=(scores, bias), input_kwargs=common + ) + if provider == "torch": + return marker.do_bench( + torch_router, input_args=(scores, bias, TOPK, scoring_func) + ) + if provider == "aot": + # The AOT CUDA kernels only implement sigmoid scoring. + if scoring_func != "sigmoid": + marker.skip("AOT kernel supports sigmoid only") + if num_experts == 384: # 3 groups of 128 -> dedicated Kimi-K2 kernel + return marker.do_bench( + aot_kimi_k2_gate, + input_args=(scores, bias), + input_kwargs=dict( + topk=TOPK, + renormalize=True, + routed_scaling_factor=SCALE, + apply_routed_scaling_factor_on_output=True, + ), + ) + num_group = max(num_experts // AOT_GROUP_SIZE, 1) + return marker.do_bench( + aot_moe_fused_gate, + input_args=( + scores, + bias, + num_group, + num_group, + TOPK, + 0, # num_fused_shared_experts + SCALE, + True, # apply_routed_scaling_factor_on_output + ), + ) + raise ValueError(f"unknown provider: {provider}") + + +if __name__ == "__main__": + benchmark.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_mxfp8_moe.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_mxfp8_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc865790067dede4d1b856dec7fc428245f8bbc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_mxfp8_moe.py @@ -0,0 +1,292 @@ +from __future__ import annotations + +import sys +from typing import Any + +import torch +import triton + +from sglang.jit_kernel.benchmark.utils import get_benchmark_range, run_benchmark +from sglang.jit_kernel.mxfp8 import ( + es_sm100_mxfp8_blockscaled_grouped_quant, + es_sm100_mxfp8_blockscaled_moe_grouped_gemm, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +def is_sm100_supported(device=None) -> bool: + if not torch.cuda.is_available(): + return False + return (torch.cuda.get_device_capability(device)[0] == 10) and ( + torch.version.cuda >= "12.8" + ) + + +_SM100_SUPPORTED = is_sm100_supported() + + +def _probe_sgl_kernel_group_mm() -> tuple[bool, str]: + if not _SM100_SUPPORTED: + return False, "MXFP8 MoE benchmark requires sm100+ with CUDA 12.8+." + try: + import sgl_kernel # noqa: F401 + except Exception as e: + return False, f"import sgl_kernel failed: {e}" + if not hasattr(sgl_kernel, "es_sm100_mxfp8_blockscaled_grouped_mm"): + return False, "sgl_kernel.es_sm100_mxfp8_blockscaled_grouped_mm is missing." + try: + pass + + # We assume if it's imported, it works + except Exception as e: + return False, f"calling sgl-kernel grouped_mm op failed: {e}" + return True, "" + + +_SGL_KERNEL_AVAILABLE, _SGL_KERNEL_REASON = _probe_sgl_kernel_group_mm() + + +def align(val: int, alignment: int = 128) -> int: + return int((val + alignment - 1) // alignment * alignment) + + +def _prepare_case( + total_tokens: int, n_g: int, k_g: int, num_experts: int, dtype: torch.dtype +) -> dict[str, Any]: + device = torch.device("cuda") + base = total_tokens // num_experts + rem = total_tokens % num_experts + m_per_expert = [base + (1 if i < rem else 0) for i in range(num_experts)] + + expert_offset = 0 + expert_offsets = [] + aux_expert_offset = 0 + aux_expert_offsets = [] + a_blockscale_offset = 0 + a_blockscale_offsets = [] + b_blockscale_offset = 0 + b_blockscale_offsets = [] + tokens_per_expert_list = [] + expert_ranges = [] + problem_sizes = [] + + a_list = [] + b_list = [] + for g in range(num_experts): + m_g = m_per_expert[g] + tokens_per_expert_list.append(m_g) + expert_ranges.append((expert_offset, expert_offset + m_g)) + expert_offsets.append(expert_offset) + expert_offset += m_g + + aux_expert_offsets.append(aux_expert_offset) + aux_expert_offset += n_g + + a_blockscale_offsets.append(a_blockscale_offset) + a_blockscale_offset += align(m_g, 128) + + b_blockscale_offsets.append(b_blockscale_offset) + b_blockscale_offset += n_g # n_g already align to 128 in practice + + problem_sizes.append([m_g, n_g, k_g]) + + a = torch.randn((m_g, k_g), device=device, dtype=dtype) * 0.1 + b = torch.randn((n_g, k_g), device=device, dtype=dtype) * 0.1 + a_list.append(a) + b_list.append(b) + + a = torch.concat(a_list, dim=0) + b = torch.concat(b_list, dim=0) + + _expert_offsets = torch.tensor(expert_offsets).to(device=device, dtype=torch.int32) + _aux_expert_offsets = torch.tensor(aux_expert_offsets).to( + device=device, dtype=torch.int32 + ) + _a_blockscale_offsets = torch.tensor(a_blockscale_offsets).to( + device=device, dtype=torch.int32 + ) + _b_blockscale_offsets = torch.tensor(b_blockscale_offsets).to( + device=device, dtype=torch.int32 + ) + _tokens_per_expert = torch.tensor(tokens_per_expert_list).to( + device=device, dtype=torch.int32 + ) + _problem_sizes = torch.tensor(problem_sizes).to(device=device, dtype=torch.int32) + + a_quant = torch.zeros_like(a, dtype=torch.float8_e4m3fn, device=device) + a_scale_factor = torch.zeros( + (a_blockscale_offset, k_g // 32), dtype=torch.uint8, device=device + ) + + b_quant = torch.zeros_like(b, dtype=torch.float8_e4m3fn, device=device) + b_scale_factor = torch.zeros( + (num_experts * n_g, k_g // 32), dtype=torch.uint8, device=device + ) + + # Use a global workspace to avoid allocating 1GB every time + workspace = torch.empty((1024, 1024, 1024), dtype=torch.uint8, device=device) + + es_sm100_mxfp8_blockscaled_grouped_quant( + a, + _tokens_per_expert, + _expert_offsets, + _a_blockscale_offsets, + a_quant, + a_scale_factor, + ) + + es_sm100_mxfp8_blockscaled_grouped_quant( + b, + torch.ones_like(_tokens_per_expert) * n_g, + _aux_expert_offsets, + _b_blockscale_offsets, + b_quant, + b_scale_factor, + ) + + b_quant = b_quant.view(num_experts, n_g, k_g) + b_scale_factor = b_scale_factor.view(num_experts, n_g, k_g // 32) + + sgl_b_quant = b_quant.transpose(1, 2) + sgl_b_scale_factor = b_scale_factor.transpose(1, 2) + + return { + "a": a, + "b": b.view(num_experts, n_g, k_g), + "b_quant": b_quant, + "a_quant": a_quant, + "b_scale_factor": b_scale_factor, + "a_scale_factor": a_scale_factor, + "expert_offsets": _expert_offsets, + "a_blockscale_offsets": _a_blockscale_offsets, + "tokens_per_expert": _tokens_per_expert, + "problem_sizes": _problem_sizes, + "sgl_b_quant": sgl_b_quant, + "sgl_b_scale_factor": sgl_b_scale_factor, + "workspace": workspace, + "expert_ranges": expert_ranges, + "dtype": dtype, + } + + +def _sgl_kernel_group_mm(case: dict[str, Any]) -> torch.Tensor: + from sgl_kernel import es_sm100_mxfp8_blockscaled_grouped_mm + + a_quant = case["a_quant"] + sgl_b_quant = case["sgl_b_quant"] + a_scale_factor = case["a_scale_factor"] + sgl_b_scale_factor = case["sgl_b_scale_factor"] + problem_sizes = case["problem_sizes"] + expert_offsets = case["expert_offsets"] + a_blockscale_offsets = case["a_blockscale_offsets"] + dtype = case["dtype"] + + total_tokens = a_quant.shape[0] + n_g = sgl_b_quant.shape[2] + + # sgl-kernel takes output pre-allocated + d = torch.empty((total_tokens, n_g), device=a_quant.device, dtype=dtype) + es_sm100_mxfp8_blockscaled_grouped_mm( + d, + a_quant, + sgl_b_quant, + a_scale_factor, + sgl_b_scale_factor, + problem_sizes, + expert_offsets, + a_blockscale_offsets, + ) + return d + + +shape_range = get_benchmark_range( + full_range=[ + # (total_tokens, n_g, k_g, num_experts) + (1024, 4096, 4096, 64), + (2048, 4096, 4096, 64), + (4096, 4096, 4096, 64), + ] + + [ + (total_tokens, n_g, k_g, num_experts) + for total_tokens in [32 * (2**i) for i in range(9)] # 32 to 8192 + for n_g, k_g, num_experts in [ + # DeepSeek-V3/R1, gateup, TP = 1, EP = 8 + (4096, 7168, 32), + # DeepSeek-V3/R1, down, TP = 1, EP = 8 + (7168, 2048, 32), + ] + ], + ci_range=[(1024, 2048, 2048, 8)], +) + +line_vals = ["jit"] +line_names = ["JIT MXFP8 MoE GroupMM"] +styles = [("green", "-")] + +if _SGL_KERNEL_AVAILABLE: + line_vals.append("sgl_kernel") + line_names.append("sgl-kernel MXFP8 MoE GroupMM") + styles.append(("orange", "-")) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["total_tokens", "n_g", "k_g", "num_experts"], + x_vals=shape_range, + x_log=False, + line_arg="provider", + line_vals=line_vals, + line_names=line_names, + styles=styles, + ylabel="us", + plot_name="mxfp8-moe-groupmm-performance", + args={}, + ) +) +def benchmark(total_tokens, n_g, k_g, num_experts, provider): + case = _prepare_case(total_tokens, n_g, k_g, num_experts, torch.bfloat16) + + if provider == "jit": + fn = lambda: es_sm100_mxfp8_blockscaled_moe_grouped_gemm( + case["b_quant"], + case["a_quant"], + case["b_scale_factor"], + case["a_scale_factor"], + case["expert_offsets"], + case["a_blockscale_offsets"], + case["tokens_per_expert"], + case["workspace"], + case["dtype"], + ) + elif provider == "sgl_kernel": + fn = lambda: _sgl_kernel_group_mm(case) + else: + raise ValueError(f"Unknown provider: {provider}") + + # Warm up + fn() + + # Profile + if provider == "jit": + torch.cuda.nvtx.range_push("jit") + fn() + torch.cuda.nvtx.range_pop() + elif provider == "sgl_kernel": + torch.cuda.nvtx.range_push("sgl_kernel") + fn() + torch.cuda.nvtx.range_pop() + + return run_benchmark(fn) + + +if __name__ == "__main__": + if not _SM100_SUPPORTED: + print("[skip] MXFP8 MoE GroupMM benchmark requires sm100+ with CUDA 12.8+.") + sys.exit(0) + if not _SGL_KERNEL_AVAILABLE: + print(f"[info] sgl-kernel baseline unavailable: {_SGL_KERNEL_REASON}") + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_ngram_compute_decode.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_ngram_compute_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..a30298f153df733869e2ccb7f3d42e82c9cfcf7a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_ngram_compute_decode.py @@ -0,0 +1,123 @@ +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark_no_cudagraph, +) +from sglang.jit_kernel.ngram_embedding import ( + compute_n_gram_ids, + compute_n_gram_ids_decode, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=15, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +NE_N = 8 +NE_K = 2 +VOCAB_SIZE = 32000 +MAX_CONTEXT_LEN = 1024 +BATCH_SIZE_LIST = get_benchmark_range( + full_range=[1, 2, 8, 32, 128, 512, 1024, 2048, 4096], + ci_range=[32, 1024], +) + + +def _make_ngram_params(): + ne_weights = torch.zeros([NE_N - 1, NE_K, NE_N], dtype=torch.int32) + ne_mods = torch.zeros([NE_N - 1, NE_K], dtype=torch.int32) + exclusive_sums = torch.zeros([(NE_N - 1) * NE_K + 1], dtype=torch.int32) + + for n in range(2, NE_N + 1): + for k in range(NE_K): + config_id = (n - 2) * NE_K + k + mod = 65537 + 2 * config_id + ne_mods[n - 2][k] = mod + exclusive_sums[config_id + 1] = exclusive_sums[config_id] + mod + for delta in range(NE_N): + ne_weights[n - 2][k][delta] = pow(VOCAB_SIZE, delta, mod) + + return ( + ne_weights.to(DEFAULT_DEVICE), + ne_mods.to(DEFAULT_DEVICE), + exclusive_sums.to(DEFAULT_DEVICE), + ) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch_size"], + x_vals=BATCH_SIZE_LIST, + line_arg="provider", + line_vals=["general", "decode"], + line_names=["general compute_n_gram_ids", "decode fast path"], + styles=[("blue", "-"), ("orange", "-")], + ylabel="us", + plot_name="ngram-compute-decode", + args={}, + ) +) +def benchmark(batch_size: int, provider: str): + num_configs = (NE_N - 1) * NE_K + max_running_reqs = batch_size + 8 + ne_weights, ne_mods, exclusive_sums = _make_ngram_params() + ne_token_table = torch.randint( + 0, + VOCAB_SIZE, + (max_running_reqs, MAX_CONTEXT_LEN), + dtype=torch.int32, + device=DEFAULT_DEVICE, + ) + row_indices = torch.arange(batch_size, dtype=torch.int64, device=DEFAULT_DEVICE) + column_starts = torch.randint( + 0, MAX_CONTEXT_LEN, (batch_size,), dtype=torch.int32, device=DEFAULT_DEVICE + ) + n_gram_ids = torch.empty( + (batch_size, num_configs), dtype=torch.int32, device=DEFAULT_DEVICE + ) + + if provider == "general": + tokens = torch.empty(batch_size, dtype=torch.int32, device=DEFAULT_DEVICE) + exclusive_req_len_sums = torch.arange( + batch_size + 1, dtype=torch.int32, device=DEFAULT_DEVICE + ) + + def fn(): + compute_n_gram_ids( + NE_N, + NE_K, + ne_weights, + ne_mods, + exclusive_sums, + tokens, + exclusive_req_len_sums, + ne_token_table, + row_indices, + column_starts, + n_gram_ids, + ) + + else: + + def fn(): + compute_n_gram_ids_decode( + NE_N, + NE_K, + ne_weights, + ne_mods, + exclusive_sums, + ne_token_table, + row_indices, + column_starts, + n_gram_ids, + ) + + return run_benchmark_no_cudagraph(fn) + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_ngram_update_token_table.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_ngram_update_token_table.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe7e884fc4517b52b8558588fb071284cffea69 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_ngram_update_token_table.py @@ -0,0 +1,78 @@ +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark_no_cudagraph, +) +from sglang.jit_kernel.ngram_embedding import ( + update_token_table, + update_token_table_decode, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=15, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +MAX_CONTEXT_LEN = 4096 +BATCH_SIZE_LIST = get_benchmark_range( + full_range=[1, 2, 8, 32, 128, 512, 1024, 2048, 4096], + ci_range=[32, 1024], +) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch_size"], + x_vals=BATCH_SIZE_LIST, + line_arg="provider", + line_vals=["general", "decode"], + line_names=["general update_token_table", "decode fast path"], + styles=[("blue", "-"), ("orange", "-")], + ylabel="us", + plot_name="ngram-update-token-table", + args={}, + ) +) +def benchmark(batch_size: int, provider: str): + max_running_reqs = batch_size + 8 + tokens = torch.arange(batch_size, dtype=torch.int32, device=DEFAULT_DEVICE) + token_table = torch.empty( + (max_running_reqs, MAX_CONTEXT_LEN), dtype=torch.int32, device=DEFAULT_DEVICE + ) + row_indices = torch.arange(batch_size, dtype=torch.int64, device=DEFAULT_DEVICE) + column_starts = torch.randint( + 0, MAX_CONTEXT_LEN, (batch_size,), dtype=torch.int32, device=DEFAULT_DEVICE + ) + req_lens = torch.ones(batch_size, dtype=torch.int32, device=DEFAULT_DEVICE) + + if provider == "general": + + def fn(): + update_token_table( + tokens, + token_table, + row_indices, + column_starts, + req_lens, + None, + ) + + else: + + def fn(): + update_token_table_decode( + tokens, + token_table, + row_indices, + column_starts, + ) + + return run_benchmark_no_cudagraph(fn) + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_norm.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1dfd60f9e8e3b7b76dbb79efc779f06b0baa20 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_norm.py @@ -0,0 +1,102 @@ +import itertools + +import torch +import triton +import triton.testing +from flashinfer.norm import fused_add_rmsnorm as fi_fused_add_rmsnorm +from flashinfer.norm import rmsnorm as fi_rmsnorm + +from sglang.jit_kernel.benchmark.utils import get_benchmark_range, run_benchmark +from sglang.jit_kernel.norm import fused_add_rmsnorm as jit_fused_add_rmsnorm +from sglang.jit_kernel.norm import rmsnorm as jit_rmsnorm +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=30, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +DTYPE = torch.bfloat16 +DEVICE = "cuda" + +BS_LIST = get_benchmark_range( + full_range=[2**n for n in range(0, 14)], + ci_range=[16, 32], +) +HIDDEN_SIZE_LIST = get_benchmark_range( + full_range=sorted([1536, *range(1024, 8192 + 1, 1024)]), + ci_range=[512, 2048], +) + +LINE_VALS = ["flashinfer", "jit"] +LINE_NAMES = ["FlashInfer", "SGL JIT Kernel"] +STYLES = [("blue", "--"), ("green", "-.")] +NUM_LAYERS = 4 # avoid L2 effect + +configs_0 = list(itertools.product(HIDDEN_SIZE_LIST + [16384], BS_LIST)) +configs_1 = list(itertools.product(HIDDEN_SIZE_LIST, BS_LIST)) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["hidden_size", "batch_size"], + x_vals=configs_0, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="rmsnorm-performance", + args={}, + ) +) +def benchmark_rmsnorm(hidden_size: int, batch_size: int, provider: str): + input = torch.randn( + (NUM_LAYERS, batch_size, hidden_size), dtype=DTYPE, device=DEVICE + ) + weight = torch.randn((NUM_LAYERS, hidden_size), dtype=DTYPE, device=DEVICE) + FN_MAP = {"jit": jit_rmsnorm, "flashinfer": fi_rmsnorm} + + def f(): + fn = FN_MAP[provider] + for i in range(NUM_LAYERS): + fn(input[i], weight[i], out=input[i]) + + return run_benchmark(f, scale=NUM_LAYERS) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["hidden_size", "batch_size"], + x_vals=configs_1, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="fused-add-rmsnorm-performance", + args={}, + ) +) +def benchmark_fused_add_rmsnorm(hidden_size: int, batch_size: int, provider: str): + input = torch.randn( + (NUM_LAYERS, batch_size, hidden_size), dtype=DTYPE, device=DEVICE + ) + residual = torch.randn_like(input) + weight = torch.randn((NUM_LAYERS, hidden_size), dtype=DTYPE, device=DEVICE) + FN_MAP = {"jit": jit_fused_add_rmsnorm, "flashinfer": fi_fused_add_rmsnorm} + + def f(): + fn = FN_MAP[provider] + for i in range(NUM_LAYERS): + fn(input[i], residual[i], weight[i]) + + return run_benchmark(f, scale=NUM_LAYERS) + + +if __name__ == "__main__": + print("Benchmarking rmsnorm...") + benchmark_rmsnorm.run(print_data=True) + + print("Benchmarking fused_add_rmsnorm...") + benchmark_fused_add_rmsnorm.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_nvfp4_blockwise_moe.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_nvfp4_blockwise_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..7fea40f6e82517b1da15e1fafb74654f1dd4d86e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_nvfp4_blockwise_moe.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import sys +from typing import Any + +import torch +import triton + +from sglang.jit_kernel.benchmark.utils import get_benchmark_range, run_benchmark +from sglang.jit_kernel.nvfp4 import ( + cutlass_fp4_group_mm, + scaled_fp4_experts_quant, + scaled_fp4_quant, +) +from sglang.srt.utils import is_sm100_supported +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +FLOAT4_E2M1_MAX = 6.0 +FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max +_NVFP4_SUPPORTED = is_sm100_supported() + + +def _round_up(x: int, y: int) -> int: + return ((x + y - 1) // y) * y + + +def _expert_offsets(m_per_expert: list[int], device: torch.device) -> torch.Tensor: + offsets = [0] + for m in m_per_expert: + offsets.append(offsets[-1] + m) + return torch.tensor(offsets, dtype=torch.int32, device=device) + + +def _blockscale_offsets(m_per_expert: list[int], device: torch.device) -> torch.Tensor: + offsets = [0] + for m in m_per_expert: + offsets.append(offsets[-1] + _round_up(m, 128)) + return torch.tensor(offsets, dtype=torch.int32, device=device) + + +def _prepare_case( + total_tokens: int, n: int, k: int, num_experts: int, dtype: torch.dtype +) -> dict[str, Any]: + device = torch.device("cuda") + base = total_tokens // num_experts + rem = total_tokens % num_experts + m_per_expert = [base + (1 if i < rem else 0) for i in range(num_experts)] + + expert_offsets_full = _expert_offsets(m_per_expert, device) + blockscale_offsets_full = _blockscale_offsets(m_per_expert, device) + + a = torch.randn((total_tokens, k), device=device, dtype=dtype) * 0.1 + b = torch.randn((num_experts, n, k), device=device, dtype=dtype) * 0.1 + + a_global_scale = torch.empty((num_experts,), device=device, dtype=torch.float32) + for i in range(num_experts): + start = int(expert_offsets_full[i].item()) + end = int(expert_offsets_full[i + 1].item()) + a_global_scale[i] = ( + FLOAT8_E4M3_MAX + * FLOAT4_E2M1_MAX + / a[start:end].abs().max().to(torch.float32) + ) + + b_global_scale = torch.empty((num_experts,), device=device, dtype=torch.float32) + for i in range(num_experts): + b_global_scale[i] = ( + FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / b[i].abs().max().to(torch.float32) + ) + + a_fp4, a_blockscale = scaled_fp4_experts_quant( + a, + a_global_scale, + expert_offsets_full, + blockscale_offsets_full, + topk=1, + ) + + b_fp4 = torch.empty((num_experts, n, k // 2), device=device, dtype=torch.uint8) + b_blockscale = torch.empty( + (num_experts, _round_up(n, 128), _round_up(k // 16, 4)), + device=device, + dtype=torch.float8_e4m3fn, + ) + for i in range(num_experts): + b_fp4_i, b_scale_i = scaled_fp4_quant(b[i], b_global_scale[i]) + b_fp4[i].copy_(b_fp4_i) + b_blockscale[i].copy_(b_scale_i) + + alphas = (1.0 / (a_global_scale * b_global_scale)).to(torch.float32) + params = { + "ab_strides": torch.full((num_experts,), k, dtype=torch.int64, device=device), + "c_strides": torch.full((num_experts,), n, dtype=torch.int64, device=device), + "problem_sizes": torch.tensor( + [[m, n, k] for m in m_per_expert], dtype=torch.int32, device=device + ), + "expert_offsets": expert_offsets_full[:-1].contiguous(), + "blockscale_offsets": blockscale_offsets_full[:-1].contiguous(), + "a_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "b_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "out_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "a_scales_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "b_scales_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "alpha_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "layout_sfa": torch.empty((num_experts, 5), dtype=torch.int64, device=device), + "layout_sfb": torch.empty((num_experts, 5), dtype=torch.int64, device=device), + } + + expert_ranges: list[tuple[int, int]] = [] + start = 0 + for m in m_per_expert: + end = start + m + expert_ranges.append((start, end)) + start = end + + return { + "a": a, + "b": b, + "a_fp4": a_fp4, + "b_fp4": b_fp4, + "a_blockscale": a_blockscale, + "b_blockscale": b_blockscale, + "alphas": alphas, + "params": params, + "expert_offsets_full": expert_offsets_full, + "expert_ranges": expert_ranges, + "dtype": dtype, + } + + +def _torch_ref_group_mm(case: dict[str, Any]) -> torch.Tensor: + a = case["a"] + b = case["b"] + dtype = case["dtype"] + expert_ranges = case["expert_ranges"] + total_tokens = a.shape[0] + n = b.shape[1] + out = torch.empty((total_tokens, n), device=a.device, dtype=dtype) + for i, (start, end) in enumerate(expert_ranges): + out[start:end] = torch.matmul(a[start:end], b[i].t()) + return out + + +def _aot_cutlass_fp4_group_mm(case: dict[str, Any]) -> torch.Tensor: + a_fp4 = case["a_fp4"] + b_fp4 = case["b_fp4"] + a_blockscale = case["a_blockscale"] + b_blockscale = case["b_blockscale"] + alphas = case["alphas"] + params = case["params"] + out_dtype = case["dtype"] + + out = torch.empty( + (a_fp4.shape[0], b_fp4.shape[1]), device=a_fp4.device, dtype=out_dtype + ) + torch.ops.sgl_kernel.cutlass_fp4_group_mm.default( + out, + a_fp4, + b_fp4, + a_blockscale, + b_blockscale, + alphas, + params["ab_strides"], + params["c_strides"], + params["problem_sizes"], + params["expert_offsets"], + params["blockscale_offsets"], + ) + return out + + +def _probe_legacy_aot_group_mm() -> tuple[bool, str]: + if not torch.cuda.is_available(): + return False, "CUDA is not available." + if not _NVFP4_SUPPORTED: + return False, "NVFP4 benchmarks require sm100+ with CUDA 12.8+." + try: + import sgl_kernel # noqa: F401 + except Exception as e: + return False, f"import sgl_kernel failed: {e}" + if not hasattr(torch.ops, "sgl_kernel"): + return False, "torch.ops.sgl_kernel is not registered." + op = getattr(torch.ops.sgl_kernel, "cutlass_fp4_group_mm", None) + if op is None or not hasattr(op, "default"): + return False, "torch.ops.sgl_kernel.cutlass_fp4_group_mm.default is missing." + try: + case = _prepare_case(64, 256, 128, 4, torch.bfloat16) + _aot_cutlass_fp4_group_mm(case) + torch.cuda.synchronize() + except Exception as e: + return False, f"calling AOT grouped_mm op failed: {e}" + return True, "" + + +_AOT_GROUP_MM_AVAILABLE, _AOT_GROUP_MM_REASON = _probe_legacy_aot_group_mm() + +shape_range = get_benchmark_range( + full_range=[(128, 256, 128, 4), (256, 512, 128, 8), (512, 512, 256, 8)], + ci_range=[(128, 256, 128, 4)], +) + +line_vals = ["jit"] +line_names = ["JIT NVFP4 MoE GroupMM"] +styles = [("green", "-")] +if _AOT_GROUP_MM_AVAILABLE: + line_vals.append("aot_sgl_kernel") + line_names.append("AOT NVFP4 MoE GroupMM") + styles.append(("orange", "-")) +line_vals.append("torch_ref") +line_names.append("Torch Ref") +styles.append(("blue", "-")) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["total_tokens", "n", "k", "num_experts"], + x_vals=shape_range, + x_log=False, + line_arg="provider", + line_vals=line_vals, + line_names=line_names, + styles=styles, + ylabel="us", + plot_name="nvfp4-blockwise-moe-groupmm-performance", + args={}, + ) +) +def benchmark(total_tokens, n, k, num_experts, provider): + case = _prepare_case(total_tokens, n, k, num_experts, torch.bfloat16) + + if provider == "jit": + fn = lambda: cutlass_fp4_group_mm( + case["a_fp4"], + case["b_fp4"], + case["a_blockscale"], + case["b_blockscale"], + case["alphas"], + case["dtype"], + case["params"], + ) + elif provider == "aot_sgl_kernel": + fn = lambda: _aot_cutlass_fp4_group_mm(case) + elif provider == "torch_ref": + fn = lambda: _torch_ref_group_mm(case) + else: + raise ValueError(f"Unknown provider: {provider}") + + return run_benchmark(fn) + + +if __name__ == "__main__": + if not _NVFP4_SUPPORTED: + print("[skip] NVFP4 blockwise MoE benchmark requires sm100+ with CUDA 12.8+.") + sys.exit(0) + if not _AOT_GROUP_MM_AVAILABLE: + print( + f"[info] legacy AOT grouped_mm baseline unavailable: {_AOT_GROUP_MM_REASON}" + ) + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_nvfp4_quant.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_nvfp4_quant.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc87cecf238ca8240efd021635f7eacf453a622 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_nvfp4_quant.py @@ -0,0 +1,197 @@ +from __future__ import annotations + +import sys + +import torch +import triton + +from sglang.jit_kernel.benchmark.utils import get_benchmark_range, run_benchmark +from sglang.jit_kernel.nvfp4 import scaled_fp4_quant +from sglang.srt.utils import is_sm100_supported +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +FLOAT4_E2M1_MAX = 6.0 +FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max +BLOCK_SIZE = 16 +_NVFP4_SUPPORTED = is_sm100_supported() + +try: + from flashinfer import fp4_quantize as flashinfer_fp4_quantize +except Exception: + flashinfer_fp4_quantize = None + + +def _torch_ref_quant(input: torch.Tensor, input_global_scale: torch.Tensor): + m, n = input.shape + x = input.view(m, n // BLOCK_SIZE, BLOCK_SIZE) + vec_max = torch.max(torch.abs(x), dim=-1, keepdim=True)[0].to(torch.float32) + scale = input_global_scale * (vec_max / FLOAT4_E2M1_MAX) + scale = scale.to(torch.float8_e4m3fn).to(torch.float32) + output_scale = torch.where(scale == 0, torch.zeros_like(scale), 1.0 / scale) + + scaled_x = x.to(torch.float32) * output_scale + clipped = torch.clamp(scaled_x, -6.0, 6.0).reshape(m, n) + + rounded = clipped.clone() + rounded[(rounded >= 0.0) & (rounded <= 0.25)] = 0.0 + rounded[(rounded > 0.25) & (rounded < 0.75)] = 0.5 + rounded[(rounded >= 0.75) & (rounded <= 1.25)] = 1.0 + rounded[(rounded > 1.25) & (rounded < 1.75)] = 1.5 + rounded[(rounded >= 1.75) & (rounded <= 2.5)] = 2.0 + rounded[(rounded > 2.5) & (rounded < 3.5)] = 3.0 + rounded[(rounded >= 3.5) & (rounded <= 5.0)] = 4.0 + rounded[rounded > 5.0] = 6.0 + + # This baseline intentionally keeps work on GPU but does not pack to uint8. + return rounded, scale + + +def _aot_scaled_fp4_quant(input: torch.Tensor, input_global_scale: torch.Tensor): + m, n = input.shape + output = torch.empty((m, n // 2), device=input.device, dtype=torch.uint8) + rounded_m = ((m + 128 - 1) // 128) * 128 + scale_n = n // BLOCK_SIZE + rounded_n = ((scale_n + 4 - 1) // 4) * 4 + output_scale = torch.empty( + (rounded_m, rounded_n // 4), device=input.device, dtype=torch.int32 + ) + torch.ops.sgl_kernel.scaled_fp4_quant.default( + output, input, output_scale, input_global_scale + ) + return output, output_scale.view(torch.float8_e4m3fn) + + +def _probe_legacy_aot_quant() -> tuple[bool, str]: + if not torch.cuda.is_available(): + return False, "CUDA is not available." + if not _NVFP4_SUPPORTED: + return False, "NVFP4 benchmarks require sm100+ with CUDA 12.8+." + try: + import sgl_kernel # noqa: F401 + except Exception as e: + return False, f"import sgl_kernel failed: {e}" + if not hasattr(torch.ops, "sgl_kernel"): + return False, "torch.ops.sgl_kernel is not registered." + op = getattr(torch.ops.sgl_kernel, "scaled_fp4_quant", None) + if op is None or not hasattr(op, "default"): + return False, "torch.ops.sgl_kernel.scaled_fp4_quant.default is missing." + try: + x = torch.randn((16, 64), dtype=torch.bfloat16, device="cuda") + global_scale = ( + FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / torch.abs(x).max().to(torch.float32) + ) + _aot_scaled_fp4_quant(x, global_scale) + torch.cuda.synchronize() + except Exception as e: + return False, f"calling AOT quant op failed: {e}" + return True, "" + + +_AOT_QUANT_AVAILABLE, _AOT_QUANT_REASON = _probe_legacy_aot_quant() + + +def _probe_flashinfer_quant() -> tuple[bool, str]: + if flashinfer_fp4_quantize is None: + return False, "import flashinfer.fp4_quantize failed." + if not torch.cuda.is_available(): + return False, "CUDA is not available." + if not _NVFP4_SUPPORTED: + return False, "NVFP4 benchmarks require sm100+ with CUDA 12.8+." + try: + x = torch.randn((16, 64), dtype=torch.bfloat16, device="cuda") + global_scale = ( + FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / torch.abs(x).max().to(torch.float32) + ) + flashinfer_fp4_quantize( + x, + global_scale, + BLOCK_SIZE, # sf_vec_size + False, # use_ue8m0 + True, # is_sf_swizzled_layout + ) + torch.cuda.synchronize() + except Exception as e: + return False, f"calling flashinfer.fp4_quantize failed: {e}" + return True, "" + + +_FLASHINFER_QUANT_AVAILABLE, _FLASHINFER_QUANT_REASON = _probe_flashinfer_quant() + +shape_range = get_benchmark_range( + full_range=[(128, 2048), (512, 4096), (1024, 4096), (2048, 8192)], + ci_range=[(128, 2048)], +) + +line_vals = [] +line_names = [] +styles = [] +if _FLASHINFER_QUANT_AVAILABLE: + line_vals.append("flashinfer") + line_names.append("FlashInfer FP4 Quant") + styles.append(("purple", "-")) +line_vals.append("jit") +line_names.append("JIT NVFP4 Quant") +styles.append(("green", "-")) +if _AOT_QUANT_AVAILABLE: + line_vals.append("aot_sgl_kernel") + line_names.append("AOT NVFP4 Quant") + styles.append(("orange", "-")) +line_vals.append("torch_ref") +line_names.append("Torch Ref") +styles.append(("blue", "-")) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["m", "n"], + x_vals=shape_range, + x_log=False, + line_arg="provider", + line_vals=line_vals, + line_names=line_names, + styles=styles, + ylabel="us", + plot_name="nvfp4-quant-performance", + args={}, + ) +) +def benchmark(m, n, provider): + x = torch.randn((m, n), dtype=torch.bfloat16, device="cuda") + tensor_amax = torch.abs(x).max().to(torch.float32) + global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / tensor_amax + + if provider == "jit": + fn = lambda: scaled_fp4_quant(x, global_scale) + elif provider == "flashinfer": + fn = lambda: flashinfer_fp4_quantize( + x, + global_scale, + BLOCK_SIZE, # sf_vec_size + False, # use_ue8m0 + True, # is_sf_swizzled_layout + ) + elif provider == "aot_sgl_kernel": + fn = lambda: _aot_scaled_fp4_quant(x, global_scale) + elif provider == "torch_ref": + fn = lambda: _torch_ref_quant(x, global_scale) + else: + raise ValueError(f"Unknown provider: {provider}") + + return run_benchmark(fn) + + +if __name__ == "__main__": + if not _NVFP4_SUPPORTED: + print("[skip] NVFP4 quant benchmark requires sm100+ with CUDA 12.8+.") + sys.exit(0) + if not _FLASHINFER_QUANT_AVAILABLE: + print( + f"[info] flashinfer quant baseline unavailable: {_FLASHINFER_QUANT_REASON}" + ) + if not _AOT_QUANT_AVAILABLE: + print(f"[info] legacy AOT quant baseline unavailable: {_AOT_QUANT_REASON}") + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_nvfp4_scaled_mm.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_nvfp4_scaled_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..a2e4528bebcc7f84d8fd2c56601f3b4961935e18 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_nvfp4_scaled_mm.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +import sys + +import torch +import triton + +from sglang.jit_kernel.benchmark.utils import get_benchmark_range, run_benchmark +from sglang.jit_kernel.nvfp4 import cutlass_scaled_fp4_mm, scaled_fp4_quant +from sglang.srt.utils import is_sm100_supported, is_sm120_supported +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +FLOAT4_E2M1_MAX = 6.0 +FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max +BLOCK_SIZE = 16 +_NVFP4_SUPPORTED = is_sm100_supported() or is_sm120_supported() + +K_E2M1_TO_FLOAT = [ + 0.0, + 0.5, + 1.0, + 1.5, + 2.0, + 3.0, + 4.0, + 6.0, + 0.0, + -0.5, + -1.0, + -1.5, + -2.0, + -3.0, + -4.0, + -6.0, +] + + +def _dequantize_to_fp16( + tensor_fp4: torch.Tensor, tensor_sf: torch.Tensor, global_scale: torch.Tensor +): + m, packed_k = tensor_fp4.shape + k = packed_k * 2 + flat = tensor_fp4.flatten() + high = (flat & 0xF0) >> 4 + low = flat & 0x0F + f_h = torch.tensor([K_E2M1_TO_FLOAT[x] for x in high], device=tensor_fp4.device) + f_l = torch.tensor([K_E2M1_TO_FLOAT[x] for x in low], device=tensor_fp4.device) + val = torch.stack((f_l, f_h), dim=-1).reshape(m, k) + + rounded_m = ((m + 128 - 1) // 128) * 128 + scale_n = k // BLOCK_SIZE + rounded_n = ((scale_n + 4 - 1) // 4) * 4 + sf = tensor_sf.view(torch.float8_e4m3fn) + tmp = torch.reshape(sf, (1, rounded_m // 128, rounded_n // 4, 32, 4, 4)) + tmp = torch.permute(tmp, (0, 1, 4, 3, 2, 5)) + scale = torch.reshape(tmp, (rounded_m, rounded_n))[:m, :scale_n].to(torch.float32) + scale = scale / global_scale + + return (val.view(m, scale_n, BLOCK_SIZE) * scale.unsqueeze(-1)).reshape(m, k) + + +def _aot_cutlass_scaled_fp4_mm( + a: torch.Tensor, + b: torch.Tensor, + block_scale_a: torch.Tensor, + block_scale_b: torch.Tensor, + alpha: torch.Tensor, + out_dtype: torch.dtype, +) -> torch.Tensor: + out = torch.empty((a.shape[0], b.shape[0]), dtype=out_dtype, device=a.device) + torch.ops.sgl_kernel.cutlass_scaled_fp4_mm.default( + out, a, b, block_scale_a, block_scale_b, alpha + ) + return out + + +def _probe_legacy_aot_scaled_mm() -> tuple[bool, str]: + if not torch.cuda.is_available(): + return False, "CUDA is not available." + if not _NVFP4_SUPPORTED: + return False, "NVFP4 benchmarks require sm100+ with CUDA 12.8+." + try: + import sgl_kernel # noqa: F401 + except Exception as e: + return False, f"import sgl_kernel failed: {e}" + if not hasattr(torch.ops, "sgl_kernel"): + return False, "torch.ops.sgl_kernel is not registered." + op = getattr(torch.ops.sgl_kernel, "cutlass_scaled_fp4_mm", None) + if op is None or not hasattr(op, "default"): + return False, "torch.ops.sgl_kernel.cutlass_scaled_fp4_mm.default is missing." + try: + m, n, k = 16, 32, 64 + a = torch.randn((m, k), dtype=torch.bfloat16, device="cuda") + b = torch.randn((n, k), dtype=torch.bfloat16, device="cuda") + a_global_scale = ( + FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / torch.amax(a.flatten(), dim=-1) + ).to(torch.float32) + b_global_scale = ( + FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / torch.amax(b.flatten(), dim=-1) + ).to(torch.float32) + alpha = 1.0 / (a_global_scale * b_global_scale) + a_fp4, a_sf = scaled_fp4_quant(a, a_global_scale) + b_fp4, b_sf = scaled_fp4_quant(b, b_global_scale) + _aot_cutlass_scaled_fp4_mm(a_fp4, b_fp4, a_sf, b_sf, alpha, torch.bfloat16) + torch.cuda.synchronize() + except Exception as e: + return False, f"calling AOT scaled_mm op failed: {e}" + return True, "" + + +_AOT_SCALED_MM_AVAILABLE, _AOT_SCALED_MM_REASON = _probe_legacy_aot_scaled_mm() + +shape_range = get_benchmark_range( + full_range=[(128, 4096, 4096), (512, 4096, 4096), (1024, 8192, 4096)], + ci_range=[(128, 4096, 4096)], +) + +line_vals = ["jit"] +line_names = ["JIT NVFP4 GEMM"] +styles = [("green", "-")] +if _AOT_SCALED_MM_AVAILABLE: + line_vals.append("aot_sgl_kernel") + line_names.append("AOT NVFP4 GEMM") + styles.append(("orange", "-")) +line_vals.append("torch_ref") +line_names.append("Torch Ref") +styles.append(("blue", "-")) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["m", "n", "k"], + x_vals=shape_range, + x_log=False, + line_arg="provider", + line_vals=line_vals, + line_names=line_names, + styles=styles, + ylabel="us", + plot_name="nvfp4-scaled-mm-performance", + args={}, + ) +) +def benchmark(m, n, k, provider): + a = torch.randn((m, k), dtype=torch.bfloat16, device="cuda") + b = torch.randn((n, k), dtype=torch.bfloat16, device="cuda") + + a_global_scale = ( + FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / torch.amax(a.flatten(), dim=-1) + ).to(torch.float32) + b_global_scale = ( + FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / torch.amax(b.flatten(), dim=-1) + ).to(torch.float32) + alpha = 1.0 / (a_global_scale * b_global_scale) + + a_fp4, a_sf = scaled_fp4_quant(a, a_global_scale) + b_fp4, b_sf = scaled_fp4_quant(b, b_global_scale) + + if provider == "jit": + fn = lambda: cutlass_scaled_fp4_mm( + a_fp4, b_fp4, a_sf, b_sf, alpha, torch.bfloat16 + ) + elif provider == "aot_sgl_kernel": + fn = lambda: _aot_cutlass_scaled_fp4_mm( + a_fp4, b_fp4, a_sf, b_sf, alpha, torch.bfloat16 + ) + elif provider == "torch_ref": + a_ref = _dequantize_to_fp16(a_fp4, a_sf, a_global_scale) + b_ref = _dequantize_to_fp16(b_fp4, b_sf, b_global_scale) + fn = lambda: torch.matmul(a_ref, b_ref.t()) + else: + raise ValueError(f"Unknown provider: {provider}") + + return run_benchmark(fn) + + +if __name__ == "__main__": + if not _NVFP4_SUPPORTED: + print("[skip] NVFP4 scaled_mm benchmark requires sm100/sm120 with CUDA 12.8+.") + sys.exit(0) + if not _AOT_SCALED_MM_AVAILABLE: + print( + f"[info] legacy AOT scaled_mm baseline unavailable: {_AOT_SCALED_MM_REASON}" + ) + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_online_c128_mtp.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_online_c128_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..e55d5f998ba76a1367fb05705c45e1bf1a39c5bf --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_online_c128_mtp.py @@ -0,0 +1,162 @@ +"""Benchmark online c128 MTP write-prefix kernel.""" + +from __future__ import annotations + +import itertools +from dataclasses import dataclass + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark, + run_benchmark_no_cudagraph, +) +from sglang.jit_kernel.dsv4.online_c128_mtp import _jit_online_c128_mtp_module +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=10, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +HEAD_DIM = 512 +STATE_DIM = HEAD_DIM * 3 +SWA_PAGE_SIZE = 128 + +BATCH_SIZE_RANGE = get_benchmark_range( + full_range=[1, 2, 4, 8, 16, 32, 64, 128, 256], + ci_range=[8, 64], +) +NUM_VERIFY_TOKENS_RANGE = get_benchmark_range( + full_range=[1, 4, 8], + ci_range=[8], +) +BENCHMARK_CONFIGS = list(itertools.product(BATCH_SIZE_RANGE, NUM_VERIFY_TOKENS_RANGE)) + + +@dataclass +class BenchmarkCase: + kv_score_input: torch.Tensor + seq_lens: torch.Tensor + req_pool_indices: torch.Tensor + req_to_token: torch.Tensor + ape: torch.Tensor + state: torch.Tensor + layer_bs: int + num_verify_tokens: int + state_slot_stride: int + + +def round_up_div(x: int, y: int) -> int: + return (x + y - 1) // y + + +def make_seq_lens(batch_size: int, num_verify_tokens: int) -> torch.Tensor: + # Cover chunk positions around the interesting boundaries. This exercises + # both the has-partial path and the final_seq % 128 == 0 skip-write path. + offsets = torch.tensor([0, 1, 2, 63, 120, 126, 127], dtype=torch.int64) + seq_offsets = offsets[torch.arange(batch_size, dtype=torch.int64) % offsets.numel()] + base = 8 * SWA_PAGE_SIZE + seq_lens = base + seq_offsets + assert int(seq_lens.max()) + num_verify_tokens < base + 2 * SWA_PAGE_SIZE + return seq_lens.to(device=DEFAULT_DEVICE) + + +def make_req_to_token( + batch_size: int, max_seq_len: int, num_chunks: int +) -> torch.Tensor: + chunk_ids = torch.arange(max_seq_len, dtype=torch.int32) // SWA_PAGE_SIZE + req_offsets = torch.arange(batch_size, dtype=torch.int32).unsqueeze(1) * num_chunks + req_to_token = req_offsets + chunk_ids.unsqueeze(0) + return req_to_token.contiguous().to(device=DEFAULT_DEVICE) + + +def make_case(batch_size: int, num_verify_tokens: int) -> BenchmarkCase: + seq_lens = make_seq_lens(batch_size, num_verify_tokens) + req_pool_indices = torch.arange( + batch_size, dtype=torch.int64, device=DEFAULT_DEVICE + ) + + max_seq_len = int(seq_lens.max().item()) + num_verify_tokens + SWA_PAGE_SIZE + num_chunks = round_up_div(max_seq_len, SWA_PAGE_SIZE) + req_to_token = make_req_to_token(batch_size, max_seq_len, num_chunks) + + num_full_locs = batch_size * num_chunks + + state_slot_stride = num_full_locs + state = torch.empty( + (state_slot_stride * (1 + num_verify_tokens), STATE_DIM), + dtype=torch.float32, + device=DEFAULT_DEVICE, + ) + state.normal_(mean=0.0, std=0.01) + + kv_score_input = torch.randn( + batch_size * num_verify_tokens, + HEAD_DIM * 2, + dtype=torch.float32, + device=DEFAULT_DEVICE, + ) + ape = torch.randn(128, HEAD_DIM, dtype=torch.float32, device=DEFAULT_DEVICE) + + return BenchmarkCase( + kv_score_input=kv_score_input, + seq_lens=seq_lens, + req_pool_indices=req_pool_indices, + req_to_token=req_to_token, + ape=ape, + state=state, + layer_bs=batch_size, + num_verify_tokens=num_verify_tokens, + state_slot_stride=state_slot_stride, + ) + + +def call_write_prefix(module, case: BenchmarkCase) -> None: + module.write_prefix_states( + case.kv_score_input, + case.seq_lens, + case.req_pool_indices, + case.req_to_token, + case.ape, + case.state, + case.layer_bs, + case.num_verify_tokens, + case.state_slot_stride, + ) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch_size", "num_verify_tokens"], + x_vals=BENCHMARK_CONFIGS, + line_arg="launch_mode", + line_vals=["cuda_graph", "eager"], + line_names=["CUDA graph", "Eager launch"], + styles=[("blue", "-"), ("orange", "--")], + ylabel="us", + plot_name="online-c128-mtp-write-prefix-performance", + args={}, + ) +) +def benchmark( + batch_size: int, num_verify_tokens: int, launch_mode: str +) -> tuple[float, float, float]: + case = make_case(batch_size, num_verify_tokens) + module = _jit_online_c128_mtp_module( + HEAD_DIM, case.seq_lens.dtype, case.req_pool_indices.dtype + ) + fn = lambda: call_write_prefix(module, case) + + if launch_mode == "cuda_graph": + return run_benchmark(fn) + if launch_mode == "eager": + return run_benchmark_no_cudagraph(fn) + raise ValueError(f"Unknown launch_mode: {launch_mode}") + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_per_tensor_quant_fp8.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_per_tensor_quant_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..80fe52c49a310112dabe375d6d7edda8caf55e64 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_per_tensor_quant_fp8.py @@ -0,0 +1,122 @@ +from typing import Optional, Tuple + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import get_benchmark_range, run_benchmark +from sglang.jit_kernel.per_tensor_quant_fp8 import per_tensor_quant_fp8 +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +try: + from vllm import _custom_ops as ops + + VLLM_AVAILABLE = True +except ImportError: + ops = None + VLLM_AVAILABLE = False + +try: + from sglang.srt.utils import is_hip + + _is_hip = is_hip() +except ImportError: + _is_hip = False + +fp8_type_ = torch.float8_e4m3fnuz if _is_hip else torch.float8_e4m3fn + + +def vllm_scaled_fp8_quant( + input: torch.Tensor, + scale: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor]: + if not VLLM_AVAILABLE: + return sglang_scaled_fp8_quant(input, scale) + return ops.scaled_fp8_quant(input, scale) + + +def sglang_scaled_fp8_quant( + input: torch.Tensor, + scale: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor]: + fp8_type_: torch.dtype = torch.float8_e4m3fn + output = torch.empty_like(input, device=input.device, dtype=fp8_type_) + is_static = True + if scale is None: + scale = torch.zeros(1, device=input.device, dtype=torch.float32) + is_static = False + per_tensor_quant_fp8(input, output, scale, is_static) + + return output, scale + + +def calculate_diff(batch_size: int, seq_len: int): + device = torch.device("cuda") + x = torch.rand((batch_size, seq_len), dtype=torch.bfloat16, device=device) + + if not VLLM_AVAILABLE: + print("vLLM not available, skipping comparison") + return + + vllm_out, vllm_scale = vllm_scaled_fp8_quant(x) + sglang_out, sglang_scale = sglang_scaled_fp8_quant(x) + + vllm_out = vllm_out.to(torch.float32) + sglang_out = sglang_out.to(torch.float32) + + triton.testing.assert_close(vllm_out, sglang_out, rtol=1e-3, atol=1e-3) + triton.testing.assert_close(vllm_scale, sglang_scale, rtol=1e-3, atol=1e-3) + + +# Benchmark configuration +element_range = get_benchmark_range( + full_range=[2**n for n in range(10, 20)], + ci_range=[16384], +) + +if VLLM_AVAILABLE: + line_vals = ["vllm", "sglang"] + line_names = ["VLLM", "SGL Kernel"] + styles = [("blue", "-"), ("green", "-")] +else: + line_vals = ["sglang"] + line_names = ["SGL Kernel"] + styles = [("green", "-")] + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["element_count"], + x_vals=element_range, + line_arg="provider", + line_vals=line_vals, + line_names=line_names, + styles=styles, + ylabel="us", + plot_name="per-tensor-quant-fp8-performance", + args={}, + ) +) +def benchmark(element_count, provider): + dtype = torch.float16 + device = torch.device("cuda") + + x = torch.randn(element_count, 4096, device=device, dtype=dtype) + + if provider == "vllm": + fn = lambda: vllm_scaled_fp8_quant(x.clone()) + elif provider == "sglang": + fn = lambda: sglang_scaled_fp8_quant(x.clone()) + else: + raise ValueError(f"Unknown provider: {provider}") + + return run_benchmark(fn) + + +if __name__ == "__main__": + calculate_diff(batch_size=4, seq_len=4096) + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_per_token_group_quant_8bit.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_per_token_group_quant_8bit.py new file mode 100644 index 0000000000000000000000000000000000000000..6217bac1fffcae8d62ac0d1c2bcbbb84bb8da477 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_per_token_group_quant_8bit.py @@ -0,0 +1,289 @@ +import itertools +from typing import Any, Dict, List + +import torch +import triton +from sgl_kernel.test_utils import create_per_token_group_quant_test_data + +from sglang.jit_kernel.benchmark.utils import get_benchmark_range +from sglang.jit_kernel.per_token_group_quant_8bit import ( + per_token_group_quant_8bit as sglang_per_token_group_quant_8bit, +) +from sglang.srt.layers.quantization.fp8_kernel import ( + create_per_token_group_quant_fp8_output_scale, +) +from sglang.srt.layers.quantization.fp8_kernel import ( + per_token_group_quant_8bit as triton_per_token_group_quant_8bit, +) +from sglang.srt.utils import is_hip +from sglang.srt.utils.bench_utils import bench_kineto +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=13, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +IS_CI = is_in_ci() + +_is_hip = is_hip() +fp8_type_ = torch.float8_e4m3fnuz if _is_hip else torch.float8_e4m3fn + +NUM_TESTS = 30 if IS_CI else 300 + +GROUP_SIZE_RANGE = [128] +DST_DTYPE_RANGE = [fp8_type_] + +# ---- GEMM-like branch (num_ranks=None) ---- +NUM_TOKENS_RANGE_GEMM = get_benchmark_range( + full_range=[1, 4, 16, 64, 256, 768, 2048, 8192, 16384], + ci_range=[768], +) +HIDDEN_DIM_RANGE_GEMM = [1536, 7168, 16384] +NUM_RANKS_RANGE_GEMM = [None] + + +FLAGS_GEMM_FULL: List[Dict[str, Any]] = [ + dict( + column_major_scales=False, + scale_tma_aligned=False, + scale_ue8m0=False, + fuse_silu_and_mul=False, + masked_layout_mode=None, + ), + dict( + column_major_scales=True, + scale_tma_aligned=False, + scale_ue8m0=False, + fuse_silu_and_mul=False, + masked_layout_mode=None, + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=False, + fuse_silu_and_mul=False, + masked_layout_mode=None, + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=False, + masked_layout_mode=None, + ), +] +FLAGS_GEMM_CI: List[Dict[str, Any]] = [ + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=False, + masked_layout_mode=None, + ), +] +FLAGS_RANGE_GEMM = get_benchmark_range( + full_range=FLAGS_GEMM_FULL, ci_range=FLAGS_GEMM_CI +) + +CONFIGS_GEMM = list( + itertools.product( + NUM_TOKENS_RANGE_GEMM, + HIDDEN_DIM_RANGE_GEMM, + GROUP_SIZE_RANGE, + NUM_RANKS_RANGE_GEMM, + DST_DTYPE_RANGE, + FLAGS_RANGE_GEMM, + ) +) + +# ---- MoE-like / multi-rank branch (hidden_dim=2048, num_ranks in {8,16,32,48}) ---- +NUM_TOKENS_RANGE_MOE = get_benchmark_range( + full_range=[1 * 8, 4 * 8, 64 * 8, 256 * 8, 768 * 8], + ci_range=[768 * 8], +) +HIDDEN_DIM_RANGE_MOE = [2048] +NUM_RANKS_RANGE_MOE = get_benchmark_range( + full_range=[8, 16, 32, 48], + ci_range=[48], +) + +FLAGS_MOE: List[Dict[str, Any]] = [ + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=True, + masked_layout_mode=None, + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=True, + masked_layout_mode="balanced", + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=True, + masked_layout_mode="imbalanced", + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=True, + masked_layout_mode="extreme", + ), +] +FLAGS_RANGE_MOE = get_benchmark_range(full_range=FLAGS_MOE, ci_range=FLAGS_MOE) + +CONFIGS_MOE = list( + itertools.product( + NUM_TOKENS_RANGE_MOE, + HIDDEN_DIM_RANGE_MOE, + GROUP_SIZE_RANGE, + NUM_RANKS_RANGE_MOE, + DST_DTYPE_RANGE, + FLAGS_RANGE_MOE, + ) +) + +# ---- Final configs ---- +CONFIGS = CONFIGS_GEMM + CONFIGS_MOE + +LINE_VALS = ["triton", "sglang"] +LINE_NAMES = ["Triton (Inaccurate)", "SGL Kernel"] +STYLES = [("blue", "-"), ("green", "-")] + + +def _flatten_to_2d(t: torch.Tensor) -> torch.Tensor: + """Reshape a tensor with 3+ dims to 2D by merging all leading dims.""" + if t.ndim <= 2: + return t + return t.reshape(-1, t.shape[-1]) + + +def _make_sglang_bench_fn( + x: torch.Tensor, + group_size: int, + dst_dtype: torch.dtype, + flags: dict, +): + """ + Adapter that pre-allocates output tensors and returns a zero-arg callable + matching the JIT kernel's signature. + + The JIT kernel does not support fuse_silu_and_mul, so when enabled we + pre-compute silu+mul on the input. bench_kineto only times the kernel + matching the given name, so the pre-processing is not included. + + The JIT kernel expects 2D tensors, so any higher-dimensional inputs + (e.g. from masked_layout_mode) are flattened to 2D. + """ + fuse_silu_and_mul = flags.get("fuse_silu_and_mul", False) + column_major_scales = flags.get("column_major_scales", False) + scale_tma_aligned = flags.get("scale_tma_aligned", False) + scale_ue8m0 = flags.get("scale_ue8m0", False) + + # JIT kernel does not support fuse_silu_and_mul; pre-compute it + if fuse_silu_and_mul: + half = x.shape[-1] // 2 + x_input = torch.nn.functional.silu(x[..., :half]) * x[..., half:] + else: + x_input = x + + # JIT kernel expects 2D (num_tokens, hidden_dim); flatten if needed + x_input = _flatten_to_2d(x_input.contiguous()) + + out_shape = x_input.shape + output_q = torch.empty(out_shape, device=x.device, dtype=dst_dtype) + + fp8_max = torch.finfo(dst_dtype).max + fp8_min = -fp8_max + + output_s = create_per_token_group_quant_fp8_output_scale( + x_shape=out_shape, + device=x.device, + group_size=group_size, + column_major_scales=column_major_scales, + scale_tma_aligned=scale_tma_aligned, + scale_ue8m0=scale_ue8m0, + ) + + def _run(): + sglang_per_token_group_quant_8bit( + input=x_input, + output_q=output_q, + output_s=output_s, + group_size=group_size, + eps=1e-10, + fp8_min=fp8_min, + fp8_max=fp8_max, + scale_ue8m0=scale_ue8m0, + ) + + return _run + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=[ + "num_tokens", + "hidden_dim", + "group_size", + "num_ranks", + "dst_dtype", + "flags", + ], + x_vals=CONFIGS, + line_arg="provider", + line_vals=LINE_VALS, + # Triton has multi kernels and we only report the time for the core one + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="per-token-group-quant-8bit-performance", + args={}, + ) +) +def benchmark( + num_tokens, hidden_dim, group_size, num_ranks, dst_dtype, flags, provider +): + print( + f"Testing: {num_tokens=} {hidden_dim=} {group_size=} {num_ranks=} {dst_dtype=} {flags=} {provider=}" + ) + + x, masked_m = create_per_token_group_quant_test_data( + num_tokens=num_tokens, hidden_dim=hidden_dim, num_ranks=num_ranks, flags=flags + ) + + if provider == "triton": + fn = triton_per_token_group_quant_8bit + kernel_names = "_per_token_group_quant_8bit|_silu_and_mul_post_quant_kernel" + bench_fn = lambda: fn( + x=x, + masked_m=masked_m, + group_size=group_size, + dst_dtype=dst_dtype, + **{k: v for k, v in flags.items() if k not in ["masked_layout_mode"]}, + ) + elif provider == "sglang": + kernel_names = "per_token_group_quant_8bit_kernel" + bench_fn = _make_sglang_bench_fn( + x=x, + group_size=group_size, + dst_dtype=dst_dtype, + flags=flags, + ) + else: + raise ValueError(f"Unknown provider: {provider}") + + time_s = bench_kineto(bench_fn, kernel_names=kernel_names, num_tests=NUM_TESTS) + return time_s * 1e6 + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_per_token_group_quant_8bit_v2.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_per_token_group_quant_8bit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..0c490b9e6acc40cf2a26f60676503355c71fd4e2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_per_token_group_quant_8bit_v2.py @@ -0,0 +1,67 @@ +import torch +from sgl_kernel import sgl_per_token_group_quant_8bit + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.benchmark.utils import create_random +from sglang.jit_kernel.per_token_group_quant_8bit_v2 import ( + per_token_group_quant_8bit_v2, +) +from sglang.srt.layers.quantization.fp8_kernel import ( + create_per_token_group_quant_fp8_output_scale, + fp8_dtype, + fp8_max, + fp8_min, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=6, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +G = 128 +HIDDEN = 4096 + + +def _aot_v2(x, x_q, x_s): + # Low-level AOT op writing into the same preallocated x_q/x_s as the JIT + # path, so this is a kernel-vs-kernel comparison (no wrapper / no realloc). + sgl_per_token_group_quant_8bit( + x, + x_q, + x_s, + G, + 1e-10, + float(fp8_min), + float(fp8_max), + False, # scale_ue8m0 + False, # fuse_silu_and_mul + None, # masked_m + enable_v2=True, + ) + + +def _jit_v2(x, x_q, x_s): + per_token_group_quant_8bit_v2(x, x_q, x_s, G, 1e-10, float(fp8_min), float(fp8_max)) + + +FN = {"aot_v2": _aot_v2, "jit_v2": _jit_v2} + + +@marker.parametrize("num_tokens", [1, 8, 64, 512, 4096], ci_vals=[1, 512]) +@marker.benchmark("impl", ["aot_v2", "jit_v2"]) +def benchmark(num_tokens: int, impl: str): + x = create_random(num_tokens, HIDDEN) + x_q = torch.empty(num_tokens, HIDDEN, device="cuda", dtype=fp8_dtype) + x_s = create_per_token_group_quant_fp8_output_scale( + x_shape=(num_tokens, HIDDEN), + device="cuda", + group_size=G, + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=False, + ) + return marker.do_bench(FN[impl], input_args=(x, x_q, x_s), graph_clone_args=(0,)) + + +if __name__ == "__main__": + benchmark.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_qknorm.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_qknorm.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc11b7318cb54df754810c3eb57bb027636c48c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_qknorm.py @@ -0,0 +1,77 @@ +import torch + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.benchmark.utils import create_random +from sglang.jit_kernel.norm import fused_inplace_qknorm +from sglang.srt.utils import get_current_device_stream_fast +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=10, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +alt_stream = torch.cuda.Stream() + +torch._dynamo.config.recompile_limit = 100 + + +# NOTE: now aot fallback to flashinfer +def sglang_aot_qknorm( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, +) -> None: + from flashinfer import rmsnorm # lazy import to avoid crash + + current_stream = get_current_device_stream_fast() + alt_stream.wait_stream(current_stream) + rmsnorm(q, q_weight, out=q) + with torch.cuda.stream(alt_stream): + rmsnorm(k, k_weight, out=k) + current_stream.wait_stream(alt_stream) + + +@torch.compile() +def torch_impl_qknorm( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + eps: float = 1e-6, +) -> None: + q_mean = q.float().pow(2).mean(dim=-1, keepdim=True) + k_mean = k.float().pow(2).mean(dim=-1, keepdim=True) + q_norm = (q_mean + eps).rsqrt() + k_norm = (k_mean + eps).rsqrt() + q.copy_(q.float() * q_norm * q_weight.float()) + k.copy_(k.float() * k_norm * k_weight.float()) + + +FN_MAP = { + "aot": sglang_aot_qknorm, + "jit": fused_inplace_qknorm, + "torch": torch_impl_qknorm, +} + + +@marker.parametrize("head_dim", [128, 256, 512, 1024], [128]) +@marker.parametrize("GQA", [4, 8], [4]) +@marker.parametrize("num_kv_heads", [1, 2, 4, 8], [1]) +@marker.parametrize("batch_size", [2**n for n in range(0, 14)], [16]) +@marker.benchmark("impl", ["aot", "jit", "torch"]) +def benchmark(head_dim: int, GQA: int, num_kv_heads: int, batch_size: int, impl: str): + num_qo_heads = GQA * num_kv_heads + q = create_random(batch_size, num_qo_heads, head_dim) + k = create_random(batch_size, num_kv_heads, head_dim) + q_weight = create_random(head_dim) + k_weight = create_random(head_dim) + return marker.do_bench( + FN_MAP[impl], + input_args=(q, k, q_weight, k_weight), + memory_output=(q, k), # inplace write to q, k + ) + + +if __name__ == "__main__": + benchmark.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_qknorm_across_heads.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_qknorm_across_heads.py new file mode 100644 index 0000000000000000000000000000000000000000..9b96418be569ef507ae3643a2f468fbdc5044129 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_qknorm_across_heads.py @@ -0,0 +1,125 @@ +import itertools +from typing import Tuple + +import torch +import triton +import triton.testing +from sgl_kernel import rmsnorm + +from sglang.jit_kernel.benchmark.utils import run_benchmark +from sglang.jit_kernel.norm import fused_inplace_qknorm_across_heads +from sglang.srt.utils import get_current_device_stream_fast +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=12, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +IS_CI = is_in_ci() + +alt_stream = torch.cuda.Stream() + + +def sglang_jit_qknorm_across_heads( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, +) -> None: + + fused_inplace_qknorm_across_heads(q, k, q_weight, k_weight) + + +def sglang_aot_qknorm_across_heads( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, +) -> None: + + current_stream = get_current_device_stream_fast() + alt_stream.wait_stream(current_stream) + rmsnorm(q, q_weight, out=q) + with torch.cuda.stream(alt_stream): + rmsnorm(k, k_weight, out=k) + current_stream.wait_stream(alt_stream) + + +def flashinfer_qknorm_across_heads( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, +) -> None: + from flashinfer import rmsnorm + + rmsnorm(q, q_weight, out=q) + rmsnorm(k, k_weight, out=k) + + +@torch.compile() +def torch_impl_qknorm_across_heads( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + eps: float = 1e-6, +) -> None: + q_mean = q.float().pow(2).mean(dim=-1, keepdim=True) + k_mean = k.float().pow(2).mean(dim=-1, keepdim=True) + q_norm = (q_mean + eps).rsqrt() + k_norm = (k_mean + eps).rsqrt() + q.copy_(q.float() * q_norm * q_weight.float()) + k.copy_(k.float() * k_norm * k_weight.float()) + + +DTYPE = torch.bfloat16 +DEVICE = "cuda" + +if IS_CI: + BS_RANGE = [16] + HIDDEN_DIM_RANGE = [1024] +else: + BS_RANGE = [2**n for n in range(0, 14)] + HIDDEN_DIM_RANGE = [512, 1024, 2048, 4096, 8192] + +LINE_VALS = ["jit", "aot", "flashinfer", "torch"] +LINE_NAMES = ["SGL JIT Kernel", "SGL AOT Kernel", "FlashInfer", "PyTorch"] +STYLES = [("blue", "-"), ("orange", "--"), ("green", "-."), ("red", ":")] + +configs = list(itertools.product(BS_RANGE, HIDDEN_DIM_RANGE)) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch_size", "hidden_dim"], + x_vals=configs, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="qknorm-across-heads-performance", + args={}, + ) +) +def benchmark( + batch_size: int, hidden_dim: int, provider: str +) -> Tuple[float, float, float]: + q = torch.randn((batch_size, hidden_dim), dtype=DTYPE, device=DEVICE) + k = torch.randn((batch_size, hidden_dim), dtype=DTYPE, device=DEVICE) + q_weight = torch.randn(hidden_dim, dtype=DTYPE, device=DEVICE) + k_weight = torch.randn(hidden_dim, dtype=DTYPE, device=DEVICE) + FN_MAP = { + "jit": sglang_jit_qknorm_across_heads, + "aot": sglang_aot_qknorm_across_heads, + "flashinfer": flashinfer_qknorm_across_heads, + "torch": torch_impl_qknorm_across_heads, + } + fn = lambda: FN_MAP[provider](q, k, q_weight, k_weight) + return run_benchmark(fn) + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_renorm.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_renorm.py new file mode 100644 index 0000000000000000000000000000000000000000..d6df49085ebd907d7f8c7a69f16f41dc2e3ab781 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_renorm.py @@ -0,0 +1,241 @@ +import itertools + +import sgl_kernel +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import run_benchmark_no_cudagraph +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=5, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +def torch_top_k_renorm_probs(probs, top_k): + """Vectorized PyTorch implementation of top-k renormalization.""" + batch_size, vocab_size = probs.shape + + # Handle scalar or tensor k + if isinstance(top_k, int): + k_val = min(max(top_k, 1), vocab_size) + # Get top-k indices for all batches at once + _, topk_indices = torch.topk(probs, k_val, dim=1, largest=True) + + # Create mask: batch_size x vocab_size + mask = torch.zeros_like(probs) + mask.scatter_(1, topk_indices, 1.0) + + # Vectorized renormalization + masked_probs = probs * mask + renorm_probs = masked_probs / (masked_probs.sum(dim=1, keepdim=True) + 1e-10) + return renorm_probs + else: + # Variable k per batch - need to handle separately + renorm_probs = torch.zeros_like(probs) + for i in range(batch_size): + k_val = min(max(top_k[i].item(), 1), vocab_size) + _, topk_indices = torch.topk(probs[i], k_val, largest=True) + mask = torch.zeros_like(probs[i]) + mask[topk_indices] = 1.0 + masked_probs = probs[i] * mask + renorm_probs[i] = masked_probs / (masked_probs.sum() + 1e-10) + return renorm_probs + + +def torch_top_p_renorm_probs(probs, top_p, eps=1e-5): + """Vectorized PyTorch implementation of top-p renormalization.""" + batch_size, vocab_size = probs.shape + + # Handle scalar or tensor p + if isinstance(top_p, float): + p_val = top_p + # Vectorized implementation for uniform top_p + # Sort probs in descending order + sorted_probs, sorted_indices = torch.sort(probs, descending=True, dim=1) + cumsum_probs = torch.cumsum(sorted_probs, dim=1) + + # Find cutoff: where cumsum exceeds top_p + cutoff_mask = cumsum_probs <= p_val + # Keep at least one token (the highest prob) + cutoff_mask[:, 0] = True + + # Create mask in original order + mask = torch.zeros_like(probs) + mask.scatter_(1, sorted_indices, cutoff_mask.float()) + + # Vectorized renormalization + masked_probs = probs * mask + renorm_probs = masked_probs / (masked_probs.sum(dim=1, keepdim=True) + eps) + return renorm_probs + else: + # Variable p per batch - need to handle separately + renorm_probs = torch.zeros_like(probs) + for i in range(batch_size): + p_val = top_p[i].item() + sorted_prob, indices = torch.sort(probs[i], descending=False) + cdf = torch.cumsum(sorted_prob, dim=-1) + mask = torch.zeros(vocab_size, dtype=torch.float32, device=probs.device) + mask.scatter_(0, indices, (cdf >= (1 - p_val) - eps).float()) + masked_probs = probs[i] * mask + renorm_probs[i] = masked_probs / (masked_probs.sum() + eps) + return renorm_probs + + +def calculate_diff_top_k_renorm(batch_size, vocab_size, k): + """Compare Torch reference and SGLang kernel for top-k renorm correctness.""" + torch.manual_seed(42) + device = torch.device("cuda") + + pre_norm_prob = torch.rand(batch_size, vocab_size, device=device) + probs = pre_norm_prob / pre_norm_prob.sum(dim=-1, keepdim=True) + + top_k_tensor = torch.full((batch_size,), k, device=device, dtype=torch.int32) + + torch_output = torch_top_k_renorm_probs(probs, top_k_tensor) + sglang_output = sgl_kernel.top_k_renorm_prob(probs, top_k_tensor) + + torch.testing.assert_close(torch_output, sglang_output, rtol=1e-3, atol=1e-3) + + +def calculate_diff_top_p_renorm(batch_size, vocab_size, p): + """Compare Torch reference and SGLang kernel for top-p renorm correctness.""" + torch.manual_seed(42) + device = torch.device("cuda") + + pre_norm_prob = torch.rand(batch_size, vocab_size, device=device) + probs = pre_norm_prob / pre_norm_prob.sum(dim=-1, keepdim=True) + + top_p_tensor = torch.full((batch_size,), p, device=device, dtype=torch.float32) + + torch_output = torch_top_p_renorm_probs(probs, top_p_tensor) + sglang_output = sgl_kernel.top_p_renorm_prob(probs, top_p_tensor) + + torch.testing.assert_close(torch_output, sglang_output, rtol=1e-3, atol=1e-3) + + +# Parameter space - simplified for CI +if is_in_ci(): + batch_size_range = [16] + vocab_size_range = [111] + k_range = [10] + p_range = [0.5] +else: + batch_size_range = [16, 64, 128] + vocab_size_range = [111, 32000, 128256] + k_range = [10, 100, 500] + p_range = [0.1, 0.5, 0.9] + +configs_k = list(itertools.product(batch_size_range, vocab_size_range, k_range)) +configs_p = list(itertools.product(batch_size_range, vocab_size_range, p_range)) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch_size", "vocab_size", "k"], + x_vals=configs_k, + line_arg="provider", + line_vals=["torch", "sglang"], + line_names=["Torch Reference", "SGL Kernel"], + styles=[("red", "-"), ("green", "-")], + ylabel="us", + plot_name="top-k-renorm-probs-performance", + args={}, + ) +) +def benchmark_top_k_renorm(batch_size, vocab_size, k, provider): + # Skip invalid configurations + if k >= vocab_size: + return float("nan"), float("nan"), float("nan") + + torch.manual_seed(42) + device = torch.device("cuda") + + pre_norm_prob = torch.rand(batch_size, vocab_size, device=device) + probs = pre_norm_prob / pre_norm_prob.sum(dim=-1, keepdim=True) + top_k_tensor = torch.full((batch_size,), k, device=device, dtype=torch.int32) + + if provider == "torch": + fn = lambda: torch_top_k_renorm_probs(probs.clone(), top_k_tensor) + elif provider == "sglang": + fn = lambda: sgl_kernel.top_k_renorm_prob(probs.clone(), top_k_tensor) + + return run_benchmark_no_cudagraph(fn) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["batch_size", "vocab_size", "p"], + x_vals=configs_p, + line_arg="provider", + line_vals=["torch", "sglang"], + line_names=["Torch Reference", "SGL Kernel"], + styles=[("red", "-"), ("blue", "-")], + ylabel="us", + plot_name="top-p-renorm-probs-performance", + args={}, + ) +) +def benchmark_top_p_renorm(batch_size, vocab_size, p, provider): + torch.manual_seed(42) + device = torch.device("cuda") + + pre_norm_prob = torch.rand(batch_size, vocab_size, device=device) + probs = pre_norm_prob / pre_norm_prob.sum(dim=-1, keepdim=True) + top_p_tensor = torch.full((batch_size,), p, device=device, dtype=torch.float32) + + if provider == "torch": + fn = lambda: torch_top_p_renorm_probs(probs.clone(), top_p_tensor) + elif provider == "sglang": + fn = lambda: sgl_kernel.top_p_renorm_prob(probs.clone(), top_p_tensor) + + return run_benchmark_no_cudagraph(fn) + + +if __name__ == "__main__": + print("=" * 60) + print("Running correctness checks...") + print("=" * 60) + + # Correctness checks - simplified for CI + if is_in_ci(): + test_configs_k = [configs_k[0]] if configs_k else [(16, 111, 10)] + test_configs_p = [configs_p[0]] if configs_p else [(16, 111, 0.5)] + else: + test_configs_k = configs_k[:3] # Test first 3 configs + test_configs_p = configs_p[:3] + + print("\n1. Testing top_k_renorm_probs...") + for cfg in test_configs_k: + batch_size, vocab_size, k = cfg + if k < vocab_size: # Skip invalid configs + calculate_diff_top_k_renorm(batch_size, vocab_size, k) + print( + f" ✓ Passed: batch_size={batch_size}, vocab_size={vocab_size}, k={k}" + ) + + print("\n2. Testing top_p_renorm_probs...") + for cfg in test_configs_p: + calculate_diff_top_p_renorm(*cfg) + batch_size, vocab_size, p = cfg + print(f" ✓ Passed: batch_size={batch_size}, vocab_size={vocab_size}, p={p}") + + print("\n" + "=" * 60) + print("All correctness checks passed!") + print("=" * 60) + + print("\n" + "=" * 60) + print("Starting performance benchmarks...") + print("=" * 60) + + print("\n1. Benchmarking top_k_renorm_probs...") + benchmark_top_k_renorm.run(print_data=True) + + print("\n2. Benchmarking top_p_renorm_probs...") + benchmark_top_p_renorm.run(print_data=True) + + print("\n" + "=" * 60) + print("Benchmarking complete!") + print("=" * 60) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_resolve_future_token_ids.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_resolve_future_token_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..84a36d9349f7cb813ebd11aebbcb1655f52fc334 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_resolve_future_token_ids.py @@ -0,0 +1,75 @@ +import itertools + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark, +) +from sglang.jit_kernel.resolve_future_token_ids import resolve_future_token_ids_cuda +from sglang.srt.utils import get_compiler_backend +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci( + est_time=10, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) +register_amd_ci(est_time=10, stage="jit-kernel-unit", runner_config="amd") + +SIZE_LIST = get_benchmark_range( + full_range=[2**n for n in range(4, 16)], # 16 … 32K elements + ci_range=[256, 4096], +) + +configs = list(itertools.product(SIZE_LIST)) + + +def _torch_resolve(input_ids, future_map): + input_ids[:] = torch.where( + input_ids < 0, + future_map[torch.clamp(-input_ids, min=0)], + input_ids, + ) + + +_compiled_resolve = torch.compile( + _torch_resolve, dynamic=True, backend=get_compiler_backend() +) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["size"], + x_vals=configs, + line_arg="provider", + line_vals=["jit", "torch_compile", "torch"], + line_names=["SGL JIT Kernel", "torch.compile", "PyTorch"], + styles=[("blue", "-"), ("green", "-."), ("red", "--")], + ylabel="us", + plot_name="resolve-future-token-ids-performance", + args={}, + ) +) +def benchmark(size: int, provider: str): + map_size = 8192 + future_map = torch.randint( + 0, 50000, (map_size,), dtype=torch.int64, device=DEFAULT_DEVICE + ) + input_ids = torch.randint( + -map_size + 1, 50000, (size,), dtype=torch.int64, device=DEFAULT_DEVICE + ) + + if provider == "jit": + fn = lambda: resolve_future_token_ids_cuda(input_ids.clone(), future_map) + elif provider == "torch_compile": + fn = lambda: _compiled_resolve(input_ids.clone(), future_map) + else: + fn = lambda: _torch_resolve(input_ids.clone(), future_map) + + return run_benchmark(fn) + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_rope.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..63b61c3b174a7303def4089ea7e32d4220475cc3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_rope.py @@ -0,0 +1,310 @@ +import itertools + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + DEFAULT_DTYPE, + get_benchmark_range, + run_benchmark, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=6, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +MAX_SEQ_LEN = 131072 +ROPE_BASE = 10000.0 +ROPE_DIM = 128 +CACHE_SIZE = 1024 * 1024 + + +def create_cos_sin_cache( + rotary_dim: int = ROPE_DIM, + max_position: int = MAX_SEQ_LEN, + base: float = ROPE_BASE, +) -> torch.Tensor: + inv_freq = 1.0 / ( + base + ** ( + torch.arange(0, rotary_dim, 2, dtype=torch.float32, device=DEFAULT_DEVICE) + / rotary_dim + ) + ) + t = torch.arange(max_position, dtype=torch.float32, device=DEFAULT_DEVICE) + freqs = torch.einsum("i,j->ij", t, inv_freq) + cos = freqs.cos() + sin = freqs.sin() + return torch.cat((cos, sin), dim=-1) + + +# Pre-build the cache once +COS_SIN_CACHE = create_cos_sin_cache() + + +# --------------------------------------------------------------------------- +# RoPE-only provider implementations +# --------------------------------------------------------------------------- + + +def flashinfer_rope( + q: torch.Tensor, + k: torch.Tensor, + positions: torch.Tensor, + is_neox: bool, +) -> None: + from flashinfer.rope import apply_rope_with_cos_sin_cache_inplace + + head_size = q.shape[-1] + apply_rope_with_cos_sin_cache_inplace( + positions=positions, + query=q.view(q.shape[0], -1), + key=k.view(k.shape[0], -1), + head_size=head_size, + cos_sin_cache=COS_SIN_CACHE, + is_neox=is_neox, + ) + + +def sglang_pos_enc_rope( + q: torch.Tensor, + k: torch.Tensor, + positions: torch.Tensor, + is_neox: bool, +) -> None: + from sglang.jit_kernel.rope import rotary_embedding_with_key + + head_size = q.shape[-1] + rotary_embedding_with_key( + positions=positions, + query=q.view(q.shape[0], -1), + key=k.view(k.shape[0], -1), + head_size=head_size, + cos_sin_cache=COS_SIN_CACHE, + is_neox=is_neox, + ) + + +def sglang_fused_rope( + q: torch.Tensor, + k: torch.Tensor, + positions: torch.Tensor, + is_neox: bool, +) -> None: + from sglang.jit_kernel.rope import apply_rope_inplace + + apply_rope_inplace(q, k, COS_SIN_CACHE, positions, is_neox=is_neox) + + +# --------------------------------------------------------------------------- +# RoPE + KV cache store provider implementations +# --------------------------------------------------------------------------- + + +def jit_rope_then_store( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + positions: torch.Tensor, + out_loc: torch.Tensor, + is_neox: bool, +) -> None: + from sglang.jit_kernel.kvcache import store_cache + from sglang.jit_kernel.rope import apply_rope_inplace + + head_size = q.shape[-1] + row_dim = k.shape[-2] * head_size + apply_rope_inplace( + positions=positions, + q=q, + k=k, + rope_dim=head_size, + cos_sin_cache=COS_SIN_CACHE, + is_neox=is_neox, + ) + store_cache( + k.view(-1, row_dim), + v.view(-1, row_dim), + k_cache, + v_cache, + out_loc, + ) + + +def jit_fused_rope_store( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + positions: torch.Tensor, + out_loc: torch.Tensor, + is_neox: bool, +) -> None: + from sglang.jit_kernel.rope import apply_rope_inplace_with_kvcache + + apply_rope_inplace_with_kvcache( + q, k, v, k_cache, v_cache, COS_SIN_CACHE, positions, out_loc, is_neox=is_neox + ) + + +# --------------------------------------------------------------------------- +# Benchmark configuration (shared) +# --------------------------------------------------------------------------- + +BS_RANGE = get_benchmark_range( + full_range=[2**n for n in range(0, 16)], + ci_range=[16], +) +QK_HEAD_RANGE = get_benchmark_range( + full_range=[(8, 1), (16, 2), (32, 8)], + ci_range=[(16, 2)], +) +QK_HEAD_RANGE = [f"{q},{k}" for q, k in QK_HEAD_RANGE] +IS_NEOX_RANGE = get_benchmark_range( + full_range=[True, False], + ci_range=[True], +) + + +# --------------------------------------------------------------------------- +# Benchmark 1: RoPE only +# --------------------------------------------------------------------------- + +ROPE_LINE_VALS = ["flashinfer", "jit_pos_enc", "jit_fused_rope"] +ROPE_LINE_NAMES = [ + "FlashInfer", + "SGL JIT PosEnc", + "SGL JIT Fused RoPE", +] +ROPE_STYLES = [("green", "-."), ("red", "-"), ("blue", "--")] + +rope_configs = list(itertools.product(QK_HEAD_RANGE, IS_NEOX_RANGE, BS_RANGE)) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["num_q_k_heads", "is_neox", "batch_size"], + x_vals=rope_configs, + line_arg="provider", + line_vals=ROPE_LINE_VALS, + line_names=ROPE_LINE_NAMES, + styles=ROPE_STYLES, + ylabel="us", + plot_name="rope-performance", + args={}, + ) +) +def benchmark(batch_size: int, num_q_k_heads: str, is_neox: bool, provider: str): + qo, kv = num_q_k_heads.split(",") + num_qo_heads = int(qo) + num_kv_heads = int(kv) + q = torch.randn( + (batch_size, num_qo_heads, ROPE_DIM), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + k = torch.randn( + (batch_size, num_kv_heads, ROPE_DIM), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + seed = batch_size << 16 | num_qo_heads << 8 | num_kv_heads << 4 | is_neox + torch.random.manual_seed(seed) + positions = torch.randint( + MAX_SEQ_LEN, (batch_size,), device=DEFAULT_DEVICE, dtype=torch.int64 + ) + torch.cuda.synchronize() + + FN_MAP = { + "flashinfer": flashinfer_rope, + "jit_pos_enc": sglang_pos_enc_rope, + "jit_fused_rope": sglang_fused_rope, + } + fn = lambda: FN_MAP[provider](q, k, positions, is_neox) + return run_benchmark(fn) + + +# --------------------------------------------------------------------------- +# Benchmark 2: RoPE + KV cache store +# --------------------------------------------------------------------------- + +STORE_LINE_VALS = ["jit_rope_then_store", "jit_fused_store"] +STORE_LINE_NAMES = [ + "SGL JIT RoPE + Store", + "SGL JIT Fused RoPE + Store", +] +STORE_STYLES = [("red", "-"), ("blue", "--")] + +store_configs = list(itertools.product(QK_HEAD_RANGE, IS_NEOX_RANGE, BS_RANGE)) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["num_q_k_heads", "is_neox", "batch_size"], + x_vals=store_configs, + line_arg="provider", + line_vals=STORE_LINE_VALS, + line_names=STORE_LINE_NAMES, + styles=STORE_STYLES, + ylabel="us", + plot_name="rope-store-performance", + args={}, + ) +) +def benchmark_store(batch_size: int, num_q_k_heads: str, is_neox: bool, provider: str): + qo, kv = num_q_k_heads.split(",") + num_qo_heads = int(qo) + num_kv_heads = int(kv) + q = torch.randn( + (batch_size, num_qo_heads, ROPE_DIM), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + k = torch.randn( + (batch_size, num_kv_heads, ROPE_DIM), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + v = torch.randn( + (batch_size, num_kv_heads, ROPE_DIM), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + row_size = num_kv_heads * ROPE_DIM + k_cache = torch.zeros( + CACHE_SIZE, row_size, dtype=DEFAULT_DTYPE, device=DEFAULT_DEVICE + ) + v_cache = torch.zeros( + CACHE_SIZE, row_size, dtype=DEFAULT_DTYPE, device=DEFAULT_DEVICE + ) + out_loc = torch.randperm(CACHE_SIZE, device=DEFAULT_DEVICE, dtype=torch.int64)[ + :batch_size + ] + seed = batch_size << 16 | num_qo_heads << 8 | num_kv_heads << 4 | is_neox + torch.random.manual_seed(seed) + positions = torch.randint( + MAX_SEQ_LEN, (batch_size,), device=DEFAULT_DEVICE, dtype=torch.int64 + ) + torch.cuda.synchronize() + + FN_MAP = { + "jit_rope_then_store": jit_rope_then_store, + "jit_fused_store": jit_fused_rope_store, + } + fn = lambda: FN_MAP[provider]( + q, k, v, k_cache, v_cache, positions, out_loc, is_neox + ) + return run_benchmark(fn) + + +if __name__ == "__main__": + print("Running RoPE performance benchmark...") + benchmark.run(print_data=True) + print("\nRunning RoPE + KV cache store performance benchmark...") + benchmark_store.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_set_mla_kv_buffer.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_set_mla_kv_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..8d62f2a4a18eaac6ad5e7321903e547bedec3eb8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_set_mla_kv_buffer.py @@ -0,0 +1,131 @@ +"""Benchmark the set_mla_kv_buffer dispatcher. + +Compares three providers across a batch-size sweep: + - ``wrapper``: the high-level wrapper exposed by ``set_mla_kv_buffer_triton`` + (dispatches to TMA on SM90+, Triton fallback otherwise). + - ``jit_tma``: the JIT CUDA TMA bulk-store kernel directly. + - ``triton``: the BLOCK-tiled Triton kernel (SM<90 fallback path). +""" + +import itertools +from typing import Tuple + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + DEFAULT_DTYPE, + DEFAULT_QUANTILES, + get_benchmark_range, +) +from sglang.jit_kernel.set_mla_kv_buffer import set_mla_kv_buffer as jit_set +from sglang.jit_kernel.utils import is_arch_support_pdl +from sglang.srt.mem_cache.utils import set_mla_kv_buffer_kernel as sglang_triton_kernel +from sglang.srt.mem_cache.utils import set_mla_kv_buffer_triton as sglang_wrapper +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=9, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +def _triton_baseline(kv_buffer, loc, cache_k_nope, cache_k_rope): + nope_dim = cache_k_nope.shape[-1] + rope_dim = cache_k_rope.shape[-1] + total_dim = nope_dim + rope_dim + BLOCK = 128 + n_loc = loc.numel() + grid = (n_loc, triton.cdiv(total_dim, BLOCK)) + pdl_kwargs = {"USE_GDC": True, "launch_pdl": True} if is_arch_support_pdl() else {} + sglang_triton_kernel[grid]( + kv_buffer, + cache_k_nope, + cache_k_rope, + loc, + kv_buffer.stride(0), + cache_k_nope.stride(0), + cache_k_rope.stride(0), + nope_dim, + rope_dim, + BLOCK=BLOCK, + DCP_RANK=0, + DCP_WORLD_SIZE=1, + **pdl_kwargs, + ) + + +NUM_LAYERS = 8 +CACHE_SIZE = (2 * 1024 * 1024) // NUM_LAYERS + +NOPE_DIM = 512 +ROPE_DIM = 64 + +BS_RANGE = get_benchmark_range( + full_range=[1, 8, 32, 128, 512, 1024, 2048, 4096, 8192, 16384], + ci_range=[1, 128, 2048, 4096, 8192], +) + +LINE_VALS = ["wrapper", "jit_tma", "triton"] +LINE_NAMES = ["Wrapper (auto)", "JIT TMA bulk-store", "Triton (BLOCK=128 baseline)"] +STYLES = [("blue", "-"), ("green", "--"), ("red", "-.")] +X_NAMES = ["batch_size"] +CONFIGS = list(itertools.product(BS_RANGE)) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=X_NAMES, + x_vals=CONFIGS, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="set-mla-kv-buffer-performance", + args={}, + ) +) +def benchmark(batch_size: int, provider: str) -> Tuple[float, float, float]: + cache_k_nope = torch.randn( + (NUM_LAYERS, batch_size, 1, NOPE_DIM), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + cache_k_rope = torch.randn( + (NUM_LAYERS, batch_size, 1, ROPE_DIM), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + kv_buffer = torch.randn( + (NUM_LAYERS, CACHE_SIZE, 1, NOPE_DIM + ROPE_DIM), + dtype=DEFAULT_DTYPE, + device=DEFAULT_DEVICE, + ) + loc = torch.randperm(CACHE_SIZE, device=DEFAULT_DEVICE)[:batch_size] + torch.cuda.synchronize() + + FN_MAP = { + "wrapper": sglang_wrapper, + "jit_tma": lambda buf, loc, n, r: jit_set(buf, loc, n, r), + "triton": _triton_baseline, + } + + def fn(): + impl = FN_MAP[provider] + for i in range(NUM_LAYERS): + impl(kv_buffer[i], loc, cache_k_nope[i], cache_k_rope[i]) + + ms, min_ms, max_ms = triton.testing.do_bench_cudagraph( + fn, quantiles=DEFAULT_QUANTILES + ) + return ( + 1000 * ms / NUM_LAYERS, + 1000 * max_ms / NUM_LAYERS, + 1000 * min_ms / NUM_LAYERS, + ) + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_sparse_mla_q8kv8_prefill_sm90.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_sparse_mla_q8kv8_prefill_sm90.py new file mode 100644 index 0000000000000000000000000000000000000000..fa92549cd018c1b9f5f7f13a93d4a451c1c087ac --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_sparse_mla_q8kv8_prefill_sm90.py @@ -0,0 +1,152 @@ +from __future__ import annotations + +import math + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import run_benchmark_no_cudagraph +from sglang.jit_kernel.sparse_mla_q8kv8_prefill_sm90 import sparse_mla_q8kv8_prefill_fwd +from sglang.srt.utils import is_sm90_supported +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +try: + from sgl_kernel.flash_mla import flash_mla_sparse_fwd + + HAS_Q16_FLASHMLA = True +except ImportError: + flash_mla_sparse_fwd = None + HAS_Q16_FLASHMLA = False + +register_cuda_ci( + est_time=120, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +IS_CI = is_in_ci() +DTYPE_FP8 = torch.float8_e4m3fn +D_V = 512 +H_KV = 1 + +if IS_CI: + CASES = [ + (2, 1024, 64, 512, 128), + (2, 1024, 64, 576, 128), + ] +else: + CASES = [ + (4096, 8192, 128, 576, 2048), + (4096, 32768, 128, 576, 2048), + (4096, 65536, 128, 576, 2048), + (4096, 8192, 64, 512, 512), + (4096, 32768, 64, 512, 512), + ] + + # This official benchmark intentionally measures the no-sink path. Current + # DeepSeek NSA E2E does not pass a per-head attention sink into sparse MLA, so + # sink-enabled timings are kernel feature coverage rather than E2E proxy data. + +LINE_VALS = ["q8_fp8_jit"] +LINE_NAMES = ["Q8 FP8 JIT"] +STYLES = [("blue", "-")] +if HAS_Q16_FLASHMLA: + LINE_VALS.insert(0, "q16_bf16_flashmla") + LINE_NAMES.insert(0, "Q16 BF16 FlashMLA") + STYLES.insert(0, ("orange", "--")) + + +def _sm90_available() -> bool: + return is_sm90_supported() + + +def _make_indices(s_q: int, s_kv: int, topk: int, d_qk: int) -> torch.Tensor: + generator = torch.Generator(device="cuda") + generator.manual_seed(1000 + d_qk + topk) + return torch.randint( + 0, + s_kv, + (s_q, H_KV, topk), + dtype=torch.int32, + device="cuda", + generator=generator, + ) + + +def _make_q16_inputs(s_q: int, s_kv: int, h_q: int, d_qk: int, topk: int): + generator = torch.Generator(device="cuda") + generator.manual_seed(2000 + d_qk + s_kv) + q = torch.randn( + (s_q, h_q, d_qk), dtype=torch.bfloat16, device="cuda", generator=generator + ) + kv = torch.randn( + (s_kv + 1, H_KV, d_qk), dtype=torch.bfloat16, device="cuda", generator=generator + ) + indices = _make_indices(s_q, s_kv, topk, d_qk) + sm_scale = 1.0 / math.sqrt(d_qk) + return q, kv, indices, sm_scale + + +def _make_q8_inputs(s_q: int, s_kv: int, h_q: int, d_qk: int, topk: int): + generator = torch.Generator(device="cuda") + generator.manual_seed(3000 + d_qk + s_kv) + q = (torch.randn((s_q, h_q, d_qk), device="cuda", generator=generator) * 0.05).to( + DTYPE_FP8 + ) + kv = torch.zeros((s_kv + 1, H_KV, d_qk), dtype=DTYPE_FP8, device="cuda") + kv[:s_kv] = ( + torch.randn((s_kv, H_KV, d_qk), device="cuda", generator=generator) * 0.05 + ).to(DTYPE_FP8) + indices = _make_indices(s_q, s_kv, topk, d_qk) + q_scale = torch.ones(1, dtype=torch.float32, device="cuda") + kv_scale = torch.ones(1, dtype=torch.float32, device="cuda") + sm_scale = 1.0 / math.sqrt(d_qk) + return q, kv, indices, sm_scale, q_scale, kv_scale + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["s_q", "s_kv", "h_q", "d_qk", "topk"], + x_vals=CASES, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="sparse-mla-q8kv8-prefill-sm90-performance", + args={}, + ) +) +def bench_sparse_mla_q8kv8_prefill_sm90( + s_q: int, s_kv: int, h_q: int, d_qk: int, topk: int, provider: str +): + if provider == "q16_bf16_flashmla": + if not HAS_Q16_FLASHMLA: + raise RuntimeError( + "sgl_kernel.flash_mla.flash_mla_sparse_fwd is not available" + ) + q, kv, indices, sm_scale = _make_q16_inputs(s_q, s_kv, h_q, d_qk, topk) + + def fn(): + return flash_mla_sparse_fwd(q, kv, indices, sm_scale, D_V) + + elif provider == "q8_fp8_jit": + if not _sm90_available(): + raise RuntimeError("Q8KV8 sparse prefill benchmark requires SM90 CUDA") + q, kv, indices, sm_scale, q_scale, kv_scale = _make_q8_inputs( + s_q, s_kv, h_q, d_qk, topk + ) + + def fn(): + return sparse_mla_q8kv8_prefill_fwd( + q, kv, indices, sm_scale, q_scale, kv_scale, D_V + ) + + else: + raise ValueError(f"Unknown provider: {provider}") + + return run_benchmark_no_cudagraph(fn) + + +if __name__ == "__main__": + bench_sparse_mla_q8kv8_prefill_sm90.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_store_cache.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_store_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..b771dffcbc12fea413ed10e0e4d9b103fa9fbf13 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_store_cache.py @@ -0,0 +1,75 @@ +import torch + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + create_empty, + create_random, +) +from sglang.jit_kernel.kvcache import store_cache +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=9, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +@torch.compile() +def torch_compile_store_cache( + k: torch.Tensor, + v: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + indices: torch.Tensor, +) -> None: + k_cache[indices] = k + v_cache[indices] = v + + +alt_stream = torch.cuda.Stream() + + +def torch_streams_store_cache( + k: torch.Tensor, + v: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + indices: torch.Tensor, +) -> None: + current_stream = torch.cuda.current_stream() + alt_stream.wait_stream(current_stream) + k_cache[indices] = k + with torch.cuda.stream(alt_stream): + v_cache[indices] = v + current_stream.wait_stream(alt_stream) + + +CACHE_SIZE = 2 * 1024 * 1024 +FN_MAP = { + "jit": store_cache, + "torch_compile": torch_compile_store_cache, + "torch_streams": torch_streams_store_cache, +} + + +@marker.parametrize("item_size", [64, 128, 256, 512, 1024], [1024]) +@marker.parametrize("batch_size", [2**n for n in range(0, 15)], [16]) +@marker.benchmark("impl", ["jit", "torch_compile", "torch_streams"]) +def benchmark(batch_size: int, item_size: int, impl: str): + torch.manual_seed(42) + k = create_random(batch_size, item_size) + k_cache = create_empty(CACHE_SIZE, item_size) + v = create_random(batch_size, item_size) + v_cache = create_empty(CACHE_SIZE, item_size) + indices = torch.randperm(CACHE_SIZE, device=DEFAULT_DEVICE)[:batch_size] + return marker.do_bench( + FN_MAP[impl], + input_args=(k, v, k_cache, v_cache, indices), + graph_clone_args=(0, 1, 4), # not need to clone cache, which is large + memory_args=(k, v, indices), # k_cache / v_cache excluded + memory_output=(k, v), # inplace write, size = k + v + ) + + +if __name__ == "__main__": + benchmark.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_symm_mem_all_gather.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_symm_mem_all_gather.py new file mode 100644 index 0000000000000000000000000000000000000000..361db9ad0c2897ef81d37de00e427b569884103f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_symm_mem_all_gather.py @@ -0,0 +1,170 @@ +"""Benchmark the symmetric-memory multimem all-gather vs NCCL. + +Providers: +- ``nccl`` : ``all_gather_into_tensor`` + concat-along-hidden reshape + (what ``tensor_model_parallel_all_gather(dim=-1)`` does) +- ``mm_safe`` : multimem kernel, ``safe=True`` (clones the buffer view) +- ``mm`` : multimem kernel, ``safe=False`` (fc gather config) +- ``mm_skipsync`` : multimem kernel, ``safe=False, skip_entry_sync=True`` + (logits gather config) + +Usage:: + + # Benchmark on the default world sizes (2, 4, 8 GPUs): + python test/registered/jit/benchmark/bench_symm_mem_all_gather.py + # Pick a specific world size (or comma-separated list): + python test/registered/jit/benchmark/bench_symm_mem_all_gather.py --num-gpu 8 +""" + +from __future__ import annotations + +import atexit +import logging +import os + +import torch +import torch.distributed as dist + +import sglang.srt.distributed.parallel_state as ps +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.benchmark.utils import get_benchmark_range, multigpu_bench_main +from sglang.jit_kernel.utils import cache_once +from sglang.srt.distributed.device_communicators.triton_symm_mem_ag import ( + all_gather_inner, + create_state, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=120, + stage="base-b-kernel-benchmark", + runner_config="1-gpu-large", + disabled="requires multi-GPU, self-skips in CI", +) + +# --------------------------------------------------------------------------- +# Sweep parameters +# --------------------------------------------------------------------------- + +DTYPE = torch.bfloat16 +PROVIDERS = ["nccl", "mm_safe", "mm", "mm_skipsync"] +# Full gathered hidden width H (per-rank shard is H / world_size). +HIDDENS = [7168, 16384, 163840] +NUM_TOKENS = [1, 8, 16, 32, 64, 128] +WORLD_SIZES = list(range(2, 9)) + +HIDDENS = get_benchmark_range(HIDDENS, [7168, 163840]) +NUM_TOKENS = get_benchmark_range(NUM_TOKENS, [16, 64]) +WORLD_SIZES = get_benchmark_range(WORLD_SIZES, [2, 4, 8]) + +MAX_HIDDEN = max(HIDDENS) +MAX_TOKENS = max(NUM_TOKENS) + +# --------------------------------------------------------------------------- +# Per-rank distributed init (run once per torchrun worker) +# --------------------------------------------------------------------------- + + +@cache_once +def _init_cpu_group() -> dist.ProcessGroup: + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + torch.cuda.set_device(local_rank) + dist.init_process_group(backend="gloo") + ps._WORLD = ps.init_world_group( + ranks=list(range(world_size)), + local_rank=local_rank, + backend="nccl", + ) + atexit.register(dist.destroy_process_group) + logging.disable(logging.INFO) + torch.cuda.set_stream(torch.cuda.Stream()) + return ps._WORLD.cpu_group + + +@cache_once +def _init_nccl_group() -> dist.ProcessGroup: + _init_cpu_group() + coord = ps._WORLD + assert coord is not None and coord.device_group is not None + return coord.device_group + + +@cache_once +def _init_state(): + _init_cpu_group() + coord = ps._WORLD + return create_state( + group=coord.device_group, + rank_in_group=coord.rank_in_group, + max_tokens=MAX_TOKENS, + hidden_size=MAX_HIDDEN, + ) + + +# --------------------------------------------------------------------------- +# Benchmark +# --------------------------------------------------------------------------- + + +@marker.parametrize("hidden", HIDDENS) +@marker.parametrize("num_tokens", NUM_TOKENS) +@marker.benchmark("provider", PROVIDERS) +def benchmark(num_tokens: int, hidden: int, provider: str): + gpu_group = _init_nccl_group() + state = _init_state() + world_size = state.world_size + local_hidden = hidden // world_size + if hidden % world_size != 0 or local_hidden % 8 != 0: + marker.skip(f"hidden={hidden} incompatible with world_size={world_size}") + if provider != "nccl" and state.symm_mem_hdl.multicast_ptr == 0: + marker.skip(f"multimem multicast unavailable for world_size={world_size}") + + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + x = torch.randn(num_tokens, local_hidden, dtype=DTYPE, device=device) + + if provider == "nccl": + out_buf = torch.empty( + world_size * num_tokens, local_hidden, dtype=DTYPE, device=device + ) + + def fn(inp: torch.Tensor) -> torch.Tensor: + dist.all_gather_into_tensor(out_buf, inp, group=gpu_group) + return ( + out_buf.reshape(world_size, num_tokens, local_hidden) + .movedim(0, 1) + .reshape(num_tokens, hidden) + ) + + else: + safe = provider == "mm_safe" + skip_entry_sync = provider == "mm_skipsync" + + def fn(inp: torch.Tensor) -> torch.Tensor: + return all_gather_inner( + state, + inp, + tp_hidden_dim=hidden, + skip_entry_sync=skip_entry_sync, + safe=safe, + ) + + return marker.do_bench( + fn, + input_args=(x,), + graph_clone_args=(0,), + sync_multigpu_fn=lambda: dist.barrier(gpu_group), + # Footprint = the gathered output every rank ends up with. + memory_args=None, + memory_output=None, + extra_memory_footprint=num_tokens * hidden * x.element_size(), + ) + + +if __name__ == "__main__": + multigpu_bench_main( + name=__name__, + file=__file__, + num_gpus=WORLD_SIZES, + main_fn=benchmark.run, + ) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_tp_qknorm.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_tp_qknorm.py new file mode 100644 index 0000000000000000000000000000000000000000..75837245f323bb7e829df7d2016886d7b82f9f97 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/bench_tp_qknorm.py @@ -0,0 +1,235 @@ +"""Benchmark fused TP QKNorm (push-mode custom-AR + RMSNorm) vs the serial +baseline (RMS sum-sq -> pull-mode all-reduce -> RMS apply). + +Usage:: + + # Benchmark on every supported world size (2..8 GPUs): + python benchmark/bench_tp_qknorm.py + # Specific world sizes: + python benchmark/bench_tp_qknorm.py --num-gpu 4 + python benchmark/bench_tp_qknorm.py --num-gpu 2,4,8 +""" + +from __future__ import annotations + +import atexit +import logging +import multiprocessing +import os +from multiprocessing.context import SpawnProcess +from typing import List + +import torch +import torch.distributed as dist + +import sglang.srt.distributed.parallel_state as ps +from sglang.jit_kernel.all_reduce import ( + _jit_custom_all_reduce_pull_module, + _jit_custom_all_reduce_push_module, + _jit_fused_parallel_qknorm_module, + fused_parallel_qknorm, + get_fused_parallel_qknorm_max_occupancy, +) +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.benchmark.utils import multigpu_bench_main +from sglang.jit_kernel.mp import register_comm_cleanup +from sglang.jit_kernel.utils import cache_once, get_ci_test_range +from sglang.srt.distributed.device_communicators.custom_all_reduce_v2 import ( + CustomAllReduceV2, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=120, + stage="base-b-kernel-benchmark", + runner_config="1-gpu-large", + disabled="requires multi-GPU, self-skips in CI", +) + + +# --------------------------------------------------------------------------- +# Sweep parameters +# --------------------------------------------------------------------------- + +DTYPE = torch.bfloat16 +EPS = 1e-6 +Q_K_DIMS = [(6144, 1024)] +BATCH_SIZES = get_ci_test_range([2**i for i in range(15)], [1, 64, 1024]) +MAX_PUSH_SIZE = 8 * max(BATCH_SIZES) +PROVIDERS = ["fused", "baseline"] + + +# --------------------------------------------------------------------------- +# Parallel JIT precompile (outer process, before any torchrun child starts) +# --------------------------------------------------------------------------- + + +def _compile_one(world_size: int) -> None: + """Compile every kernel this bench touches for a single world_size. + + Top-level so it survives ``spawn`` pickling. Compiled artifacts are + cached on disk by ``tvm_ffi``; torchrun children will reuse them. + """ + # baseline path: sum-sq -> pull-mode all-reduce -> apply + _jit_custom_all_reduce_pull_module(DTYPE, world_size) + # fused path: push-mode all-reduce + _jit_custom_all_reduce_push_module(DTYPE, world_size) + # fused path: fused QKNorm kernel (one per (dtype, world_size, q_dim, k_dim)) + for q_dim, k_dim in Q_K_DIMS: + _jit_fused_parallel_qknorm_module(DTYPE, world_size, q_dim, k_dim) + + +def _precompile_kernels(num_gpus: List[int]) -> None: + ctx = multiprocessing.get_context("spawn") + procs: list[tuple[int, SpawnProcess]] = [] + for world_size in num_gpus: + p = ctx.Process(target=_compile_one, args=(world_size,)) + p.start() + procs.append((world_size, p)) + for world_size, p in procs: + p.join() + if p.exitcode != 0: + raise RuntimeError( + f"TP QKNorm precompile failed for {world_size=} " f"(exit {p.exitcode})" + ) + + +# --------------------------------------------------------------------------- +# Per-rank distributed init (run once per torchrun worker) +# --------------------------------------------------------------------------- + + +@cache_once +def _init_cpu_group() -> dist.ProcessGroup: + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + torch.cuda.set_device(local_rank) + dist.init_process_group(backend="gloo") + ps._WORLD = coord = ps.init_world_group( + ranks=list(range(world_size)), + local_rank=local_rank, + backend="nccl", + ) + atexit.register(dist.destroy_process_group) + logging.disable(logging.INFO) + torch.cuda.set_stream(torch.cuda.Stream()) + return coord.cpu_group + + +@cache_once +def _init_gpu_group() -> dist.ProcessGroup: + _init_cpu_group() + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + gpu_group = dist.new_group(backend="nccl", device_id=device) + assert isinstance(gpu_group, dist.ProcessGroup) + atexit.register(lambda: dist.destroy_process_group(gpu_group)) + return gpu_group + + +@cache_once +def _init_fused_comm() -> CustomAllReduceV2: + """Push-mode workspace sized for the fused-QKNorm bench.""" + cpu_group = _init_cpu_group() + world_size = dist.get_world_size(cpu_group) + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + q_dim, k_dim = Q_K_DIMS[0] + max_occupancy = get_fused_parallel_qknorm_max_occupancy( + DTYPE, world_size, q_dim, k_dim + ) + if dist.get_rank(cpu_group) == 0: + print(f"Max occupancy for fused_parallel_qknorm: {max_occupancy} blocks/SM") + props = torch.cuda.get_device_properties(device) + comm = CustomAllReduceV2( + cpu_group, + device, + max_pull_size=0, + max_push_size=MAX_PUSH_SIZE, + max_push_blocks=props.multi_processor_count * max_occupancy, + ) + if comm.disabled: + raise RuntimeError("JIT CustomAllReduceV2 is disabled on this system") + register_comm_cleanup(comm) + return comm + + +@cache_once +def _init_baseline_comm() -> CustomAllReduceV2: + """Default (pull-mode) workspace for the serial baseline.""" + cpu_group = _init_cpu_group() + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + comm = CustomAllReduceV2(cpu_group, device) + if comm.disabled: + raise RuntimeError("JIT CustomAllReduceV2 is disabled on this system") + register_comm_cleanup(comm) + return comm + + +# --------------------------------------------------------------------------- +# Implementations +# --------------------------------------------------------------------------- + + +def _rmsnorm_baseline( + comm: CustomAllReduceV2, + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + world_size: int, +) -> None: + from sglang.srt.models.minimax_m2 import rms_apply_serial, rms_sumsq_serial + + sum_sq = rms_sumsq_serial(q, k) + sum_sq = comm.custom_all_reduce(sum_sq) + rms_apply_serial(q, k, q_weight, k_weight, sum_sq, world_size, EPS) + + +# --------------------------------------------------------------------------- +# Benchmark +# --------------------------------------------------------------------------- + + +@marker.parametrize("q_dim,k_dim", Q_K_DIMS) +@marker.parametrize("batch_size", BATCH_SIZES) +@marker.benchmark("provider", PROVIDERS) +def benchmark(q_dim: int, k_dim: int, batch_size: int, provider: str): + cpu_group = _init_cpu_group() + gpu_group = _init_gpu_group() + world_size = dist.get_world_size(cpu_group) + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + local_q_dim = q_dim // world_size + local_k_dim = k_dim // world_size + + q = torch.randn(batch_size, local_q_dim, device=device, dtype=DTYPE) + k = torch.randn(batch_size, local_k_dim, device=device, dtype=DTYPE) + q_weight = torch.randn(local_q_dim, device=device, dtype=DTYPE) + k_weight = torch.randn(local_k_dim, device=device, dtype=DTYPE) + + if provider == "fused": + comm = _init_fused_comm() + + def fn(q, k, q_weight, k_weight): + fused_parallel_qknorm(comm.obj, q, k, q_weight, k_weight, EPS) + + else: + comm = _init_baseline_comm() + + def fn(q, k, q_weight, k_weight): + _rmsnorm_baseline(comm, q, k, q_weight, k_weight, world_size) + + return marker.do_bench( + fn, + input_args=(q, k, q_weight, k_weight), + sync_multigpu_fn=lambda: dist.barrier(gpu_group), + memory_output=(q, k), # NOTE: In-place updates on q, k; + ) + + +if __name__ == "__main__": + multigpu_bench_main( + name=__name__, + file=__file__, + num_gpus=[2, 4, 8], # NOTE: don't support other world size now + main_fn=benchmark.run, + pre_launch_fn=_precompile_kernels, + ) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_causal_conv3d_cat_pad.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_causal_conv3d_cat_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..5864494fbe04307282267c234290c4785bff7e56 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_causal_conv3d_cat_pad.py @@ -0,0 +1,94 @@ +from dataclasses import dataclass + +import torch + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.diffusion.causal_conv3d_cat_pad import ( + fused_causal_conv3d_cat_pad_cuda, +) +from sglang.jit_kernel.diffusion.triton.causal_conv3d_pad import ( + fused_causal_conv3d_cat_pad as fused_causal_conv3d_cat_pad_triton, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=20, + stage="base-b-kernel-benchmark", + runner_config="1-gpu-large", + disabled="standalone benchmark", +) + +DEVICE = "cuda" +DTYPE = torch.bfloat16 + + +@dataclass(frozen=True) +class Case: + name: str + channels: int + t_size: int + h_size: int + w_size: int + cache_t: int + trace_count: int + + +CASES = [ + Case("c1024_t1_h30_w52_cache1", 1024, 1, 30, 52, 1, 8), + Case("c1024_t1_h30_w52_cache2", 1024, 1, 30, 52, 2, 8), + Case("c1024_t2_h60_w104_cache1", 1024, 2, 60, 104, 1, 5), + Case("c1024_t2_h60_w104_cache2", 1024, 2, 60, 104, 2, 5), + Case("c512_t4_h120_w208_cache1", 512, 4, 120, 208, 1, 5), + Case("c512_t4_h120_w208_cache2", 512, 4, 120, 208, 2, 5), + Case("c256_t4_h240_w416_cache1", 256, 4, 240, 416, 1, 6), + Case("c256_t4_h240_w416_cache2", 256, 4, 240, 416, 2, 6), +] +CASE_BY_NAME = {case.name: case for case in CASES} +CASE_NAMES = [case.name for case in CASES] + + +def make_inputs(case: Case) -> tuple[torch.Tensor, torch.Tensor, tuple[int, ...]]: + generator = torch.Generator(device=DEVICE) + generator.manual_seed(case.channels * 1009 + case.t_size * 251 + case.cache_t) + x = torch.randn( + (1, case.channels, case.t_size, case.h_size, case.w_size), + device=DEVICE, + dtype=DTYPE, + generator=generator, + ) + cache_x = torch.randn( + (1, case.channels, case.cache_t, case.h_size, case.w_size), + device=DEVICE, + dtype=DTYPE, + generator=generator, + ) + padding = (1, 1, 1, 1, case.cache_t, 0) + return x, cache_x, padding + + +@marker.parametrize("case_name", CASE_NAMES, ci_vals=CASE_NAMES[:2]) +@marker.benchmark("provider", ["triton", "cuda"]) +def benchmark(case_name: str, provider: str) -> marker.BenchResult: + case = CASE_BY_NAME[case_name] + x, cache_x, padding = make_inputs(case) + fn = ( + fused_causal_conv3d_cat_pad_triton + if provider == "triton" + else fused_causal_conv3d_cat_pad_cuda + ) + actual = fused_causal_conv3d_cat_pad_cuda(x, cache_x, padding) + expected = fused_causal_conv3d_cat_pad_triton(x, cache_x, padding) + torch.testing.assert_close(actual, expected, atol=0, rtol=0) + return marker.do_bench( + fn, + input_args=(x, cache_x, padding), + use_cuda_graph=False, + replay_iters=200, + graph_clone_args=(0, 1), + memory_args=(x, cache_x), + memory_output="out", + ) + + +if __name__ == "__main__": + benchmark.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_diffusion_nvfp4_scaled_mm.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_diffusion_nvfp4_scaled_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..ccb7d4b82ea8326fa04f4944d3aadf9cfedfa0dc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_diffusion_nvfp4_scaled_mm.py @@ -0,0 +1,367 @@ +import argparse +import csv +import json +import os +import re +import statistics +from pathlib import Path +from typing import Any, Callable + +import flashinfer +import sgl_kernel +import torch + +from sglang.jit_kernel.benchmark.utils import DEFAULT_DTYPE +from sglang.jit_kernel.utils import KERNEL_PATH +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=120, + stage="base-b-kernel-benchmark", + runner_config="1-gpu-large", + disabled="standalone diffusion NVFP4 benchmark", +) + +SCRIPT_DIR = Path(__file__).resolve().parent +REPO_ROOT = ( + Path(os.environ["SGLANG_NVFP4_REPO_ROOT"]) + if os.environ.get("SGLANG_NVFP4_REPO_ROOT") + # Anchor on the installed jit_kernel package (python/sglang/jit_kernel) so + # this stays correct regardless of where the benchmark file lives. + else KERNEL_PATH.parents[2] +) +DEFAULT_OUTPUT_DIR = REPO_ROOT / "outputs" / "nvfp4_benchmarks" +DEFAULT_SHAPE_LIBRARY = SCRIPT_DIR / "diffusion_nvfp4_shapes.json" +DTYPE = DEFAULT_DTYPE +WARMUP = 8 +ITERS = 20 +FLOAT4_E2M1_MAX = 6.0 +FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max +METHODS = ("cutlass", "flashinfer_auto", "flashinfer_cudnn") + + +def benchmark_provider( + fn: Callable[[], torch.Tensor], + warmup: int = WARMUP, + iters: int = ITERS, +) -> tuple[float, float, float]: + for _ in range(warmup): + y = fn() + del y + torch.cuda.synchronize() + + times_ms: list[float] = [] + for _ in range(iters): + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + start.record() + y = fn() + end.record() + end.synchronize() + times_ms.append(start.elapsed_time(end)) + del y + return statistics.median(times_ms), max(times_ms), min(times_ms) + + +def make_global_scale(x: torch.Tensor) -> torch.Tensor: + max_abs = torch.amax(x.abs()).clamp_min_(1e-6) + return (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / max_abs).to(torch.float32) + + +def build_quantized_inputs( + m: int, + n: int, + k: int, + device: torch.device, + seed: int, +) -> dict[str, Any]: + assert k % 16 == 0, f"NVFP4 requires k % 16 == 0, got k={k}" + + gen = torch.Generator(device=device) + gen.manual_seed(seed) + x = torch.randn((m, k), device=device, dtype=DTYPE, generator=gen) + w = torch.randn((n, k), device=device, dtype=DTYPE, generator=gen) + + x_global_scale = make_global_scale(x) + w_global_scale = make_global_scale(w) + alpha = (1.0 / (x_global_scale * w_global_scale)).to(torch.float32) + + x_fp4, x_sf = flashinfer.fp4_quantize(x, x_global_scale) + w_fp4, w_sf = flashinfer.fp4_quantize(w, w_global_scale) + if x_sf.dtype == torch.uint8: + x_sf = x_sf.view(torch.float8_e4m3fn) + if w_sf.dtype == torch.uint8: + w_sf = w_sf.view(torch.float8_e4m3fn) + + return { + "x_fp4": x_fp4, + "w_fp4": w_fp4, + "x_sf": x_sf, + "w_sf": w_sf, + "alpha": alpha, + } + + +def make_shape_id( + model: str, shape_kind: str, prefix: str, m: int, n: int, k: int +) -> str: + prefix_slug = re.sub(r"[^a-zA-Z0-9]+", "_", prefix).strip("_") + return f"{model}_{shape_kind}_{prefix_slug}_{m}x{n}x{k}" + + +def load_shape_cases(shape_library: Path) -> list[dict[str, Any]]: + payload = json.loads(shape_library.read_text(encoding="utf-8")) + if not isinstance(payload, dict) or not payload: + raise RuntimeError( + f"Expected a non-empty model->shape list mapping in {shape_library}." + ) + + rows: list[dict[str, Any]] = [] + for model, shapes in payload.items(): + if not isinstance(shapes, list): + raise RuntimeError( + f"Expected {model} to map to a list of shapes in {shape_library}." + ) + for shape in shapes: + m, n, k = (int(x) for x in shape["shape"]) + count = int(shape["count"]) + shape_kind = str(shape.get("kind", "actual_runtime_linear")) + prefix = str(shape.get("prefix", "")) + rows.append( + { + "shape_id": make_shape_id(model, shape_kind, prefix, m, n, k), + "source_model": model, + "shape_kind": shape_kind, + "runtime_prefix": prefix, + "m": m, + "n": n, + "k": k, + "count": count, + "approx_flops": 2 * m * n * k * count, + } + ) + + if not rows: + raise RuntimeError(f"No shapes found in {shape_library}.") + return rows + + +def split_csv_arg(text: str | None) -> set[str]: + if text is None or not text.strip(): + return set() + return {item.strip() for item in text.split(",") if item.strip()} + + +def select_shape_cases( + rows: list[dict[str, Any]], + *, + models: set[str], + shape_kinds: set[str], + top_k: int, + rank_by: str, +) -> list[dict[str, Any]]: + filtered = [ + row + for row in rows + if (not models or row["source_model"] in models) + and (not shape_kinds or row["shape_kind"] in shape_kinds) + ] + key = "approx_flops" if rank_by == "flops" else "count" + return sorted(filtered, key=lambda row: int(row[key]), reverse=True)[:top_k] + + +def write_csv(rows: list[dict[str, Any]], output_path: Path) -> None: + with output_path.open("w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter( + f, + fieldnames=[ + "shape_id", + "source_model", + "shape_kind", + "runtime_prefix", + "m", + "n", + "k", + "count", + "approx_flops", + "method", + "median_ms", + "min_ms", + "max_ms", + "tflops", + ], + ) + writer.writeheader() + writer.writerows(rows) + + +def write_markdown(rows: list[dict[str, Any]], output_path: Path) -> None: + shape_rows = [] + seen_shape_ids = set() + for row in rows: + if row["shape_id"] in seen_shape_ids: + continue + seen_shape_ids.add(row["shape_id"]) + shape_rows.append(row) + + lines: list[str] = [] + lines.append("# Diffusion NVFP4 Scaled MM Benchmark") + lines.append("") + lines.append("## Shape Cases") + lines.append("") + lines.append("| Shape ID | Model | Shape Kind | Calls | Shape `(M,N,K)` | Prefix |") + lines.append("|---|---|---|---:|---|---|") + for row in shape_rows: + lines.append( + f"| {row['shape_id']} | {row['source_model']} | {row['shape_kind']} | {row['count']} | `({row['m']}, {row['n']}, {row['k']})` | `{row['runtime_prefix']}` |" + ) + lines.append("") + + for shape_row in shape_rows: + shape_id = shape_row["shape_id"] + scoped = [row for row in rows if row["shape_id"] == shape_id] + lines.append(f"## {shape_id}") + lines.append("") + lines.append("| Method | Median ms | TFLOPS |") + lines.append("|---|---:|---:|") + for row in sorted(scoped, key=lambda item: float(item["median_ms"])): + lines.append( + f"| {row['method']} | {float(row['median_ms']):.4f} | {float(row['tflops']):.1f} |" + ) + lines.append("") + + output_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def run_shape_suite(shape_cases: list[dict[str, Any]]) -> list[dict[str, Any]]: + device = torch.device("cuda") + rows: list[dict[str, Any]] = [] + for idx, shape in enumerate(shape_cases): + m = int(shape["m"]) + n = int(shape["n"]) + k = int(shape["k"]) + quantized = build_quantized_inputs(m, n, k, device, seed=idx) + + metadata = { + "shape_id": str(shape["shape_id"]), + "source_model": str(shape["source_model"]), + "shape_kind": str(shape["shape_kind"]), + "runtime_prefix": str(shape["runtime_prefix"]), + "m": m, + "n": n, + "k": k, + "count": int(shape["count"]), + "approx_flops": int(shape["approx_flops"]), + } + + providers: dict[str, Callable[[], torch.Tensor]] = { + "cutlass": lambda: sgl_kernel.cutlass_scaled_fp4_mm( + quantized["x_fp4"], + quantized["w_fp4"], + quantized["x_sf"], + quantized["w_sf"], + quantized["alpha"], + DTYPE, + ), + "flashinfer_auto": lambda: flashinfer.mm_fp4( + quantized["x_fp4"], + quantized["w_fp4"].T, + quantized["x_sf"], + quantized["w_sf"].T, + quantized["alpha"], + DTYPE, + backend="auto", + ), + "flashinfer_cudnn": lambda: flashinfer.mm_fp4( + quantized["x_fp4"], + quantized["w_fp4"].T, + quantized["x_sf"], + quantized["w_sf"].T, + quantized["alpha"], + DTYPE, + backend="cudnn", + ), + } + + for method in METHODS: + median_ms, max_ms, min_ms = benchmark_provider(providers[method]) + rows.append( + { + **metadata, + "method": method, + "median_ms": median_ms, + "min_ms": min_ms, + "max_ms": max_ms, + "tflops": (2 * m * n * k) / (median_ms / 1e3) / 1e12, + } + ) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Benchmark diffusion NVFP4 GEMM backends on the captured diffusion shape library." + ) + parser.add_argument( + "--models", + help="Comma-separated source_model filter. Default: all models in the JSON shape library.", + ) + parser.add_argument( + "--shape-kinds", + help="Comma-separated shape_kind filter. Default: benchmark every shape kind in the JSON shape library.", + ) + parser.add_argument( + "--top-k", + type=int, + default=64, + help="Benchmark the top-k shapes after filtering and ranking.", + ) + parser.add_argument( + "--rank-by", + choices=["flops", "count"], + default="flops", + help="How to rank shapes before selecting top-k.", + ) + parser.add_argument( + "--output-dir", + default=str(DEFAULT_OUTPUT_DIR), + help="Directory for CSV/Markdown outputs.", + ) + args = parser.parse_args() + + if is_in_ci(): + print("Skipping bench_diffusion_nvfp4_scaled_mm.py in CI") + return + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required for NVFP4 scaled mm benchmarks.") + if not DEFAULT_SHAPE_LIBRARY.exists(): + raise RuntimeError( + f"Shape library not found at {DEFAULT_SHAPE_LIBRARY}. " + "Commit or copy the generated diffusion_nvfp4_shapes.json first." + ) + + shape_cases = load_shape_cases(DEFAULT_SHAPE_LIBRARY) + selected_shapes = select_shape_cases( + shape_cases, + models=split_csv_arg(args.models), + shape_kinds=split_csv_arg(args.shape_kinds), + top_k=args.top_k, + rank_by=args.rank_by, + ) + if not selected_shapes: + raise RuntimeError("No shapes matched the requested filters.") + rows = run_shape_suite(selected_shapes) + + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + csv_path = output_dir / "diffusion_nvfp4_scaled_mm.csv" + md_path = output_dir / "diffusion_nvfp4_scaled_mm_summary.md" + write_csv(rows, csv_path) + write_markdown(rows, md_path) + print(f"Wrote {csv_path}") + print(f"Wrote {md_path}") + + +if __name__ == "__main__": + main() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_fused_norm_scale_shift.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_fused_norm_scale_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..32110e4fd36e4a5bf2639a07af54dbb4999ba4a3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_fused_norm_scale_shift.py @@ -0,0 +1,139 @@ +# Benchmarks SGLang fused layernorm/rmsnorm scale shift kernels +# 1. fused_norm_scale_shift +# 2. fused_scale_residual_norm_scale_shift +import itertools +from typing import Tuple + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import run_benchmark_no_cudagraph +from sglang.multimodal_gen.runtime.layers.layernorm import ( + LayerNormScaleShift, + RMSNormScaleShift, + ScaleResidualLayerNormScaleShift, + ScaleResidualRMSNormScaleShift, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=17, + stage="base-b-kernel-benchmark", + runner_config="1-gpu-large", + disabled="Temporarily skipped to unblock flashinfer upgrade. Ref: https://github.com/sgl-project/sglang/actions/runs/23735552939/job/69139238979?pr=21422", +) + +if is_in_ci(): + B_RANGE, S_RANGE, D_RANGE = [1], [128], [1024] +else: + B_RANGE, S_RANGE, D_RANGE = [1], [128, 1024, 4096], [1024, 3072, 4096] + +NORM_TYPE_RANGE = ["layer", "rms"] +AFFINE_RANGE = [True, False] +DTYPE = torch.bfloat16 +DEVICE = "cuda" +EPS = 1e-5 +LINE_VALS = ["native", "cuda"] +LINE_NAMES = ["SGLang Native", "SGLang Fused"] +STYLES = [("red", "-"), ("blue", "--")] +config = list( + itertools.product(B_RANGE, S_RANGE, D_RANGE, NORM_TYPE_RANGE, AFFINE_RANGE) +) + + +def preprocess_layer(layer, affine: bool, D: int, DTYPE: torch.dtype): + if affine: + weight = torch.randn(D, dtype=DTYPE, device=DEVICE) + bias = torch.randn(D, dtype=DTYPE, device=DEVICE) + with torch.no_grad(): + layer.norm.weight.copy_(weight) + if hasattr(layer.norm, "bias"): + layer.norm.bias.copy_(bias) + layer.requires_grad_(False) + return layer.to(DEVICE) + + +# ============================================================================ +# Benchmark 1: fused_norm_scale_shift +# ============================================================================ +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["B", "S", "D", "norm_type", "affine"], + x_vals=config, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="fused_norm_scale_shift", + args={}, + ) +) +def bench_fused_norm_scale_shift( + B: int, S: int, D: int, norm_type, affine: bool, provider: str +) -> Tuple[float, float, float]: + x = torch.randn(B, S, D, dtype=DTYPE, device=DEVICE) + scale = torch.randn(B, S, D, dtype=DTYPE, device=DEVICE) + shift = torch.randn(B, S, D, dtype=DTYPE, device=DEVICE) + if norm_type == "layer": + layer = LayerNormScaleShift(D, EPS, affine, dtype=DTYPE) + else: + layer = RMSNormScaleShift(D, EPS, affine, dtype=DTYPE) + layer = preprocess_layer(layer, affine, D, DTYPE) + if provider == "native": + fn = lambda: layer.forward_native(x, shift, scale) + else: + fn = lambda: layer.forward_cuda(x, shift, scale) + + return run_benchmark_no_cudagraph(fn) + + +# ============================================================================ +# Benchmark 2: fused_scale_residual_norm_scale_shift +# ============================================================================ +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["B", "S", "D", "norm_type", "affine"], + x_vals=config, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="fused_scale_residual_norm_scale_shift", + args={}, + ) +) +def bench_fused_scale_residual_norm_scale_shift( + B: int, S: int, D: int, norm_type, affine: bool, provider: str +) -> Tuple[float, float, float]: + residual = torch.randn(B, S, D, dtype=DTYPE, device=DEVICE) + x = torch.randn(B, S, D, dtype=DTYPE, device=DEVICE) + scale = torch.randn(B, S, D, dtype=DTYPE, device=DEVICE) + shift = torch.randn(B, S, D, dtype=DTYPE, device=DEVICE) + gate = torch.randn(B, 1, D, dtype=DTYPE, device=DEVICE) + if norm_type == "layer": + layer = ScaleResidualLayerNormScaleShift(D, EPS, affine, dtype=DTYPE).to(DEVICE) + else: + layer = ScaleResidualRMSNormScaleShift(D, EPS, affine, dtype=DTYPE).to(DEVICE) + layer = preprocess_layer(layer, affine, D, DTYPE) + if provider == "native": + fn = lambda: layer.forward_native(residual, x, gate, shift, scale) + else: + fn = lambda: layer.forward_cuda(residual, x, gate, shift, scale) + + return run_benchmark_no_cudagraph(fn) + + +if __name__ == "__main__": + print(f"\n{'='*80}") + print("Benchmark: fused_norm_scale_shift") + print(f"{'='*80}\n") + bench_fused_norm_scale_shift.run(print_data=True) + + print(f"\n{'='*80}") + print("Benchmark: fused_scale_residual_norm_scale_shift") + print(f"{'='*80}\n") + bench_fused_scale_residual_norm_scale_shift.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_group_norm_silu.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_group_norm_silu.py new file mode 100644 index 0000000000000000000000000000000000000000..acd09d834625cbf61173227114bf8c727479acda --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_group_norm_silu.py @@ -0,0 +1,314 @@ +import argparse +import csv +import statistics +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +import torch +import torch.nn.functional as F +import triton.testing + +from sglang.jit_kernel.diffusion.triton.group_norm_silu import triton_group_norm_silu +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=45, + stage="base-b-kernel-benchmark", + runner_config="1-gpu-large", + disabled="standalone benchmark", +) + +DEVICE = "cuda" +EPS = 1e-5 +QUANTILES = [0.5, 0.2, 0.8] + + +@dataclass(frozen=True) +class Case: + name: str + shape: tuple[int, ...] + num_groups: int + + +CASES = [ + Case("token_2d", (4, 128), 32), + Case("image_2d", (2, 64, 32, 32), 32), + Case("video_3d_small", (1, 64, 4, 16, 16), 32), + Case("threshold_3d", (1, 128, 1, 256, 256), 32), + Case("hunyuan_video_large", (1, 128, 20, 256, 256), 32), + # LTX-2 latent upsampler (`LatentUpsampler` + `ResBlock`) operates on + # `[B, mid_channels=512, F, H, W]` tensors with num_groups=32. The + # `small` and `pre_720p` cases stay in the default set; the larger + # `post_720p` case is opt-in via LARGE_CASES below. + Case("ltx2_upsampler_small", (1, 512, 8, 45, 80), 32), + Case("ltx2_upsampler_pre_720p", (1, 512, 16, 90, 160), 32), +] + +# Cases too large to fit comfortably alongside the native-path intermediates +# on consumer GPUs (e.g. 24 GB L4). Opt in with `--cases large` (large only), +# `--cases all-large` (default + large), or by name. +# +# `ltx2_upsampler_post_720p` is ~471M bf16 elements (~940 MB tensor) and the +# eager `silu(group_norm(x))` reference materializes mean / variance / +# normalized / silu intermediates -- working set lands around 5 GB. On +# H100 / H200 this is fine and surfaces the asymptotic ~14x kernel speedup; +# on a 24 GB GPU it can OOM, so it's gated out of `--cases all`. +LARGE_CASES = [ + Case("ltx2_upsampler_post_720p", (1, 512, 16, 180, 320), 32), +] + +CASE_BY_NAME = {case.name: case for case in CASES + LARGE_CASES} + + +def dtype_from_name(name: str) -> torch.dtype: + mapping = { + "bf16": torch.bfloat16, + "bfloat16": torch.bfloat16, + "fp16": torch.float16, + "float16": torch.float16, + "fp32": torch.float32, + "float32": torch.float32, + } + return mapping[name] + + +def dtype_name(dtype: torch.dtype) -> str: + mapping = { + torch.bfloat16: "bf16", + torch.float16: "fp16", + torch.float32: "fp32", + } + return mapping[dtype] + + +def parse_dtypes(text: str) -> list[torch.dtype]: + return [dtype_from_name(item.strip()) for item in text.split(",") if item.strip()] + + +def parse_cases(text: str) -> list[Case]: + if text == "all": + return CASES + if text == "large": + return LARGE_CASES + if text == "all-large": + return CASES + LARGE_CASES + names = [item.strip() for item in text.split(",") if item.strip()] + missing = sorted(set(names) - CASE_BY_NAME.keys()) + if missing: + raise ValueError(f"Unknown cases: {missing}") + return [CASE_BY_NAME[name] for name in names] + + +def tolerance(dtype: torch.dtype) -> tuple[float, float]: + if dtype == torch.float32: + return 1e-5, 1e-5 + if dtype == torch.bfloat16: + return 7e-2, 2e-2 + return 3e-3, 3e-3 + + +def native_group_norm_silu( + x: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor, + num_groups: int, +) -> torch.Tensor: + return F.silu(F.group_norm(x, num_groups, weight=weight, bias=bias, eps=EPS)) + + +def make_inputs(case: Case, dtype: torch.dtype) -> tuple[torch.Tensor, ...]: + generator = torch.Generator(device=DEVICE) + generator.manual_seed(len(case.shape) * 1009 + case.shape[1] * 17 + case.num_groups) + x = torch.randn(case.shape, device=DEVICE, dtype=dtype, generator=generator) + weight = torch.randn(case.shape[1], device=DEVICE, dtype=dtype, generator=generator) + bias = torch.randn(case.shape[1], device=DEVICE, dtype=dtype, generator=generator) + return x, weight, bias + + +def do_bench_us(fn: Callable[[], object], warmup: int, rep: int) -> tuple[float, ...]: + median_ms, p20_ms, p80_ms = triton.testing.do_bench( + fn, + quantiles=QUANTILES, + warmup=warmup, + rep=rep, + ) + return median_ms * 1000.0, p20_ms * 1000.0, p80_ms * 1000.0 + + +def summarize(values: list[float]) -> float: + return statistics.median(values) + + +def run_case( + case: Case, + dtype: torch.dtype, + rounds: int, + warmup: int, + rep: int, +) -> dict[str, object]: + x, weight, bias = make_inputs(case, dtype) + + with torch.inference_mode(): + actual = triton_group_norm_silu( + x, weight, bias, num_groups=case.num_groups, eps=EPS + ) + expected = native_group_norm_silu(x, weight, bias, case.num_groups) + atol, rtol = tolerance(dtype) + torch.testing.assert_close(actual, expected, atol=atol, rtol=rtol) + + native_stats = [] + fused_stats = [] + for _ in range(rounds): + native_stats.append( + do_bench_us( + lambda: native_group_norm_silu(x, weight, bias, case.num_groups), + warmup=warmup, + rep=rep, + ) + ) + fused_stats.append( + do_bench_us( + lambda: triton_group_norm_silu( + x, weight, bias, num_groups=case.num_groups, eps=EPS + ), + warmup=warmup, + rep=rep, + ) + ) + + native_median_us = summarize([stats[0] for stats in native_stats]) + fused_median_us = summarize([stats[0] for stats in fused_stats]) + torch.cuda.empty_cache() + return { + "case": case.name, + "shape": "x".join(str(dim) for dim in case.shape), + "groups": case.num_groups, + "dtype": dtype_name(dtype), + "native_median_us": native_median_us, + "native_p20_us": summarize([stats[1] for stats in native_stats]), + "native_p80_us": summarize([stats[2] for stats in native_stats]), + "fused_median_us": fused_median_us, + "fused_p20_us": summarize([stats[1] for stats in fused_stats]), + "fused_p80_us": summarize([stats[2] for stats in fused_stats]), + "speedup": native_median_us / fused_median_us, + "rounds": rounds, + "warmup": warmup, + "rep": rep, + } + + +def run_profile(case: Case, dtype: torch.dtype, provider: str, iters: int) -> None: + x, weight, bias = make_inputs(case, dtype) + + if provider == "native": + + def fn() -> torch.Tensor: + return native_group_norm_silu(x, weight, bias, case.num_groups) + + elif provider == "fused": + + def fn() -> torch.Tensor: + return triton_group_norm_silu( + x, weight, bias, num_groups=case.num_groups, eps=EPS + ) + + else: + raise ValueError(f"Unknown provider: {provider}") + + with torch.inference_mode(): + for _ in range(5): + fn() + torch.cuda.synchronize() + for _ in range(iters): + fn() + torch.cuda.synchronize() + + +def write_csv(rows: list[dict[str, object]], output_path: Path) -> None: + output_path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0].keys()) if rows else [] + with output_path.open("w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(rows) + + +def print_rows(rows: list[dict[str, object]]) -> None: + header = ( + "case", + "dtype", + "shape", + "native_us", + "fused_us", + "speedup", + ) + print("| " + " | ".join(header) + " |") + print("|---|---|---|---:|---:|---:|") + for row in rows: + print( + "| {case} | {dtype} | {shape} | {native:.2f} | {fused:.2f} | {speedup:.3f}x |".format( + case=row["case"], + dtype=row["dtype"], + shape=row["shape"], + native=row["native_median_us"], + fused=row["fused_median_us"], + speedup=row["speedup"], + ) + ) + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Benchmark fused GroupNorm+SiLU against PyTorch GroupNorm+SiLU." + ) + parser.add_argument( + "--cases", + default="all", + help=( + "Comma-separated case names, or one of: 'all' (default-sized " + "cases only), 'large' (high-memory cases only -- requires " + "H100/H200-class GPU), 'all-large' (both). See CASES + LARGE_CASES." + ), + ) + parser.add_argument("--dtypes", default="bf16,fp16") + parser.add_argument("--rounds", type=int, default=3) + parser.add_argument("--warmup", type=int, default=25) + parser.add_argument("--rep", type=int, default=100) + parser.add_argument("--output-csv", default="") + parser.add_argument("--profile-provider", choices=["native", "fused"], default="") + parser.add_argument("--profile-iters", type=int, default=20) + args = parser.parse_args() + + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required for this benchmark.") + + cases = parse_cases(args.cases) + dtypes = parse_dtypes(args.dtypes) + + if args.profile_provider: + if len(cases) != 1 or len(dtypes) != 1: + raise ValueError( + "--profile-provider requires exactly one case and one dtype" + ) + run_profile(cases[0], dtypes[0], args.profile_provider, args.profile_iters) + return + + rows = [] + for case in cases: + for dtype in dtypes: + rows.append(run_case(case, dtype, args.rounds, args.warmup, args.rep)) + + print_rows(rows) + if args.output_csv: + write_csv(rows, Path(args.output_csv)) + print(f"Wrote {args.output_csv}") + + +if __name__ == "__main__": + if is_in_ci(): + print("Skipping bench_group_norm_silu.py in CI") + sys.exit(0) + main() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_ltx2_qknorm_split_rope.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_ltx2_qknorm_split_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..3491569ea6fd2650fc89ac2a244a5b48ed582987 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_ltx2_qknorm_split_rope.py @@ -0,0 +1,209 @@ +import random +import sys +from dataclasses import dataclass + +import torch + +from sglang.jit_kernel.diffusion.ltx2_qknorm_split_rope import ( + ltx2_qknorm_split_rope_cuda, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=30, + stage="base-b-kernel-benchmark", + runner_config="1-gpu-large", + disabled="standalone benchmark", +) + + +@dataclass(frozen=True) +class Workload: + name: str + batch: int + q_seq: int + k_seq: int + num_heads: int + head_dim: int + + +FULL_WORKLOADS = [ + Workload("stage1_video_self_q1536_k1536_d4096", 2, 1536, 1536, 32, 128), + Workload("stage1_audio_self_q126_k126_d2048", 2, 126, 126, 32, 64), + Workload("stage1_audio_to_video_q1536_k126_d2048", 2, 1536, 126, 32, 64), + Workload("stage1_video_to_audio_q126_k1536_d2048", 2, 126, 1536, 32, 64), + Workload("stage2_video_self_q6144_k6144_d4096", 1, 6144, 6144, 32, 128), + Workload("stage2_audio_self_q126_k126_d2048", 1, 126, 126, 32, 64), + Workload("stage2_audio_to_video_q6144_k126_d2048", 1, 6144, 126, 32, 64), + Workload("stage2_video_to_audio_q126_k6144_d2048", 1, 126, 6144, 32, 64), + Workload("hq_stage1_video_self_q8160_k8160_d4096", 1, 8160, 8160, 32, 128), + Workload("hq_stage1_audio_to_video_q8160_k126_d2048", 1, 8160, 126, 32, 64), + Workload("hq_stage1_video_to_audio_q126_k8160_d2048", 1, 126, 8160, 32, 64), + Workload("hq_stage2_video_self_q32640_k32640_d4096", 1, 32640, 32640, 32, 128), + Workload("hq_stage2_audio_to_video_q32640_k126_d2048", 1, 32640, 126, 32, 64), + Workload("hq_stage2_video_to_audio_q126_k32640_d2048", 1, 126, 32640, 32, 64), +] +CI_WORKLOADS = [ + Workload("stage1_video_self_q16_k16_d4096", 1, 16, 16, 32, 128), + Workload("stage1_audio_to_video_q16_k8_d2048", 1, 16, 8, 32, 64), +] + + +def _make_cos_sin( + batch: int, seq_len: int, num_heads: int, head_dim: int +) -> tuple[torch.Tensor, torch.Tensor]: + half_dim = head_dim // 2 + cos = torch.randn( + batch, seq_len, num_heads, half_dim, device="cuda", dtype=torch.bfloat16 + ).transpose(1, 2) + sin = torch.randn( + batch, seq_len, num_heads, half_dim, device="cuda", dtype=torch.bfloat16 + ).transpose(1, 2) + return cos, sin + + +def _apply_split_rotary_ref( + x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor +) -> torch.Tensor: + x_dtype = x.dtype + batch = x.shape[0] + _, num_heads, seq_len, _ = cos.shape + x = x.reshape(batch, seq_len, num_heads, -1).swapaxes(1, 2) + last = x.shape[-1] + half = last // 2 + split_x = x.reshape(*x.shape[:-1], 2, half) + first_x = split_x[..., :1, :] + second_x = split_x[..., 1:, :] + cos_u = cos.unsqueeze(-2) + sin_u = sin.unsqueeze(-2) + out = split_x * cos_u + out[..., :1, :].addcmul_(-sin_u, second_x) + out[..., 1:, :].addcmul_(sin_u, first_x) + out = out.reshape(*out.shape[:-2], last) + return out.swapaxes(1, 2).reshape(batch, seq_len, -1).to(dtype=x_dtype) + + +def _reference_pair(inputs): + q, k, q_cos, q_sin, k_cos, k_sin, q_norm, k_norm = inputs + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + q_out = _apply_split_rotary_ref(q_norm(q), q_cos, q_sin) + k_out = _apply_split_rotary_ref(k_norm(k), k_cos, k_sin) + return q_out.to(dtype=torch.bfloat16), k_out.to(dtype=torch.bfloat16) + + +def cuda_event_us(fn, warmups: int, repeats: int, rounds: int) -> float: + for _ in range(warmups): + fn() + torch.cuda.synchronize() + + samples = [] + for _ in range(rounds): + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + start.record() + for _ in range(repeats): + fn() + end.record() + end.synchronize() + samples.append(start.elapsed_time(end) * 1000.0 / repeats) + samples.sort() + return samples[len(samples) // 2] + + +def benchmark() -> None: + if not torch.cuda.is_available(): + print("CUDA required") + return + + torch.manual_seed(20260630) + random.seed(20260630) + torch.cuda.set_device(0) + + workloads = CI_WORKLOADS if is_in_ci() else FULL_WORKLOADS + warmups = 3 if is_in_ci() else 10 + repeats = 3 if is_in_ci() else 10 + rounds = 3 if is_in_ci() else 7 + + print("| workload | torch us | cuda us | speedup |") + print("|---|---:|---:|---:|") + + for workload in workloads: + hidden = workload.num_heads * workload.head_dim + q = torch.randn( + workload.batch, + workload.q_seq, + hidden, + device="cuda", + dtype=torch.bfloat16, + ) + k = torch.randn( + workload.batch, + workload.k_seq, + hidden, + device="cuda", + dtype=torch.bfloat16, + ) + q_cos, q_sin = _make_cos_sin( + workload.batch, workload.q_seq, workload.num_heads, workload.head_dim + ) + k_cos, k_sin = _make_cos_sin( + workload.batch, workload.k_seq, workload.num_heads, workload.head_dim + ) + q_norm = torch.nn.RMSNorm(hidden, eps=1e-6, device="cuda").to( + dtype=torch.bfloat16 + ) + k_norm = torch.nn.RMSNorm(hidden, eps=1e-6, device="cuda").to( + dtype=torch.bfloat16 + ) + inputs = (q, k, q_cos, q_sin, k_cos, k_sin, q_norm, k_norm) + + q_ref, k_ref = _reference_pair(inputs) + q_out, k_out = ltx2_qknorm_split_rope_cuda( + q, + q_cos, + q_sin, + q_norm.weight, + k, + k_cos, + k_sin, + k_norm.weight, + eps=1e-6, + num_heads=workload.num_heads, + head_dim=workload.head_dim, + ) + torch.cuda.synchronize() + assert torch.equal(q_ref, q_out) + assert torch.equal(k_ref, k_out) + + fns = { + "torch": lambda: _reference_pair(inputs), + "cuda": lambda: ltx2_qknorm_split_rope_cuda( + q, + q_cos, + q_sin, + q_norm.weight, + k, + k_cos, + k_sin, + k_norm.weight, + eps=1e-6, + num_heads=workload.num_heads, + head_dim=workload.head_dim, + ), + } + order = ["torch", "cuda"] + random.shuffle(order) + times = { + name: cuda_event_us(fns[name], warmups, repeats, rounds) for name in order + } + print( + f"| {workload.name} | {times['torch']:.2f} | " + f"{times['cuda']:.2f} | {times['torch'] / times['cuda']:.3f}x |" + ) + torch.cuda.empty_cache() + + +if __name__ == "__main__": + benchmark() + sys.exit(0) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_norm_impls.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_norm_impls.py new file mode 100644 index 0000000000000000000000000000000000000000..a932ea0c6f3d1ba3412750fa83e332d91a7761f5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_norm_impls.py @@ -0,0 +1,754 @@ +import argparse +import csv +import functools +import importlib +import math +import os +import statistics +import subprocess +import sys +from pathlib import Path +from typing import Callable + +import torch +import torch.nn.functional as F + +from sglang.jit_kernel.benchmark.utils import DEFAULT_DEVICE +from sglang.jit_kernel.diffusion.triton.norm import norm_infer, rms_norm_fn +from sglang.jit_kernel.diffusion.triton.rmsnorm_onepass import triton_one_pass_rms_norm +from sglang.jit_kernel.norm import fused_add_rmsnorm as jit_fused_add_rmsnorm +from sglang.jit_kernel.norm import rmsnorm as jit_rmsnorm +from sglang.jit_kernel.utils import KERNEL_PATH +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=120, + stage="base-b-kernel-benchmark", + runner_config="1-gpu-large", + disabled="self-skips in CI, standalone tool", +) + +os.environ.setdefault("FLASHINFER_DISABLE_VERSION_CHECK", "1") + +REPO_ROOT = KERNEL_PATH.parents[2] +THIRD_PARTY_ROOT = REPO_ROOT / "third_party" + +FLAGGEMS_REPO = "https://github.com/flagos-ai/FlagGems.git" +QUACK_REPO = "https://github.com/Dao-AILab/quack.git" + +TORCH_LN = "torch.nn.LayerNorm" +SGL_RMS = "sglang.RMSNorm.forward_cuda" +SGL_FUSED = "sgl_kernel.fused_add_rmsnorm" +SGL_LN = "sglang.LayerNormScaleShift" +SGL_RES_LN = "sglang.ScaleResidualLayerNormScaleShift" +SGL_LN_PAIR = f"{SGL_LN} / {SGL_RES_LN}" +MOVA_LN_MIX = f"{TORCH_LN} / {SGL_LN_PAIR}" + +ACTUAL_DIFFUSION_GROUPS: list[ + tuple[str, str, list[tuple[str, str, tuple[int, ...], str]]] +] = [ + ( + "qwen", + "1 GPU", + [ + ("qwen_ln_4096x3072", "layernorm", (1, 4096, 3072), SGL_LN_PAIR), + ("qwen_ln_26x3072", "layernorm", (1, 26, 3072), SGL_LN_PAIR), + ("qwen_ln_6x3072", "layernorm", (1, 6, 3072), SGL_LN_PAIR), + ("qwen_rms_26x3584", "rmsnorm", (1, 26, 3584), SGL_RMS), + ("qwen_rms_6x3584", "rmsnorm", (1, 6, 3584), SGL_RMS), + ], + ), + ( + "qwen-edit", + "1 GPU", + [ + ("qwen_edit_ln_200x3072", "layernorm", (1, 200, 3072), SGL_LN_PAIR), + ("qwen_edit_ln_203x3072", "layernorm", (1, 203, 3072), SGL_LN_PAIR), + ("qwen_edit_ln_8308x3072", "layernorm", (1, 8308, 3072), TORCH_LN), + ("qwen_edit_rms_200x3584", "rmsnorm", (1, 200, 3584), SGL_RMS), + ("qwen_edit_rms_203x3584", "rmsnorm", (1, 203, 3584), SGL_RMS), + ], + ), + ( + "flux", + "1 GPU", + [ + ("flux_ln_77x768", "layernorm", (1, 77, 768), TORCH_LN), + ("flux_ln_512x3072", "layernorm", (1, 512, 3072), TORCH_LN), + ("flux_ln_4096x3072", "layernorm", (1, 4096, 3072), TORCH_LN), + ("flux_ln_4608x3072", "layernorm", (1, 4608, 3072), TORCH_LN), + ("flux_rms_512x4096", "rmsnorm", (1, 512, 4096), SGL_RMS), + ], + ), + ( + "flux2", + "1 GPU", + [ + ("flux2_ln_512x6144", "layernorm", (1, 512, 6144), TORCH_LN), + ("flux2_ln_4096x6144", "layernorm", (1, 4096, 6144), TORCH_LN), + ("flux2_ln_4608x6144", "layernorm", (1, 4608, 6144), TORCH_LN), + ("flux2_rms_4608x48x128", "rmsnorm", (1, 4608, 48, 128), SGL_RMS), + ], + ), + ( + "zimage", + "1 GPU", + [ + ("zimage_ln_4128x3840", "layernorm", (1, 4128, 3840), TORCH_LN), + ("zimage_rms_32x3840", "rmsnorm", (1, 32, 3840), SGL_RMS), + ("zimage_rms_4096x3840", "rmsnorm", (1, 4096, 3840), SGL_RMS), + ("zimage_rms_4128x3840", "rmsnorm", (1, 4128, 3840), SGL_RMS), + ("zimage_rms_32x2560", "rmsnorm", (32, 2560), SGL_RMS), + ], + ), + ( + "wan-ti2v", + "1 GPU", + [ + ("wan_ti2v_ln_17850x3072", "layernorm", (1, 17850, 3072), SGL_LN_PAIR), + ("wan_ti2v_rms_17850x3072", "rmsnorm", (1, 17850, 3072), SGL_RMS), + ("wan_ti2v_rms_512x3072", "rmsnorm", (1, 512, 3072), SGL_RMS), + ("wan_ti2v_rms_512x4096", "rmsnorm", (1, 512, 4096), SGL_RMS), + ], + ), + ( + "hunyuanvideo", + "1 GPU", + [ + ("hunyuan_ln_46x768", "layernorm", (1, 46, 768), TORCH_LN), + ("hunyuan_ln_45x3072", "layernorm", (1, 45, 3072), SGL_LN_PAIR), + ("hunyuan_ln_27030x3072", "layernorm", (1, 27030, 3072), SGL_LN_PAIR), + ("hunyuan_ln_27075x3072", "layernorm", (1, 27075, 3072), SGL_LN), + ("hunyuan_rms_140x4096", "rmsnorm", (1, 140, 4096), SGL_RMS), + ("hunyuan_rms_45x24x128", "rmsnorm", (1, 45, 24, 128), SGL_RMS), + ("hunyuan_rms_27030x24x128", "rmsnorm", (1, 27030, 24, 128), SGL_RMS), + ("hunyuan_rms_27075x24x128", "rmsnorm", (1, 27075, 24, 128), SGL_RMS), + ("hunyuan_fused_add_140x4096", "fused_add_rmsnorm", (140, 4096), SGL_FUSED), + ], + ), + ( + "mova-720p", + "4 GPU, ulysses=4, ring=1", + [ + ("mova_ln_101x1536", "layernorm", (1, 101, 1536), MOVA_LN_MIX), + ("mova_ln_403x1536", "layernorm", (1, 403, 1536), TORCH_LN), + ("mova_ln_44100x5120", "layernorm", (1, 44100, 5120), MOVA_LN_MIX), + ("mova_ln_176400x5120", "layernorm", (1, 176400, 5120), SGL_LN), + ("mova_rms_101x1536", "rmsnorm", (1, 101, 1536), SGL_RMS), + ("mova_rms_101x5120", "rmsnorm", (1, 101, 5120), SGL_RMS), + ("mova_rms_44100x1536", "rmsnorm", (1, 44100, 1536), SGL_RMS), + ("mova_rms_44100x5120", "rmsnorm", (1, 44100, 5120), SGL_RMS), + ("mova_rms_512x1536", "rmsnorm", (1, 512, 1536), SGL_RMS), + ("mova_rms_512x4096", "rmsnorm", (1, 512, 4096), SGL_RMS), + ("mova_rms_512x5120", "rmsnorm", (1, 512, 5120), SGL_RMS), + ], + ), +] + +ACTUAL_DIFFUSION_SHAPES: list[dict[str, object]] = [ + { + "shape_id": shape_id, + "model": model, + "gpu_config": gpu_config, + "op": op, + "input_shape": list(input_shape), + "source_impl": source_impl, + } + for model, gpu_config, cases in ACTUAL_DIFFUSION_GROUPS + for shape_id, op, input_shape, source_impl in cases +] + + +def effective_rows_from_shape(input_shape: list[int]) -> int: + rows = 1 + for dim in input_shape[:-1]: + rows *= dim + return rows + + +def ensure_repo(repo_name: str, repo_url: str) -> Path: + repo_path = THIRD_PARTY_ROOT / repo_name + if repo_path.exists(): + return repo_path + repo_path.parent.mkdir(parents=True, exist_ok=True) + subprocess.run( + ["git", "clone", "--depth", "1", repo_url, str(repo_path)], + check=True, + cwd=REPO_ROOT, + ) + return repo_path + + +def ensure_python_dep(module_name: str, package_name: str | None = None) -> None: + package_name = package_name or module_name + try: + importlib.import_module(module_name) + except ModuleNotFoundError: + subprocess.run( + [sys.executable, "-m", "pip", "install", package_name], + check=True, + ) + + +def dtype_from_name(name: str) -> torch.dtype: + mapping = { + "bf16": torch.bfloat16, + "bfloat16": torch.bfloat16, + "fp16": torch.float16, + "float16": torch.float16, + "fp32": torch.float32, + "float32": torch.float32, + } + return mapping[name] + + +def dtype_name(dtype: torch.dtype) -> str: + mapping = { + torch.bfloat16: "bf16", + torch.float16: "fp16", + torch.float32: "fp32", + } + return mapping[dtype] + + +def normalize_hidden_sizes(text: str) -> list[int]: + return [int(x) for x in text.split(",") if x] + + +def normalize_dtypes(text: str) -> list[torch.dtype]: + return [dtype_from_name(x.strip()) for x in text.split(",") if x.strip()] + + +def prewarm(fn: Callable[[], object], iters: int = 3) -> None: + for _ in range(iters): + fn() + torch.cuda.synchronize() + + +def benchmark_provider( + fn: Callable[[], object], + setup_fn: Callable[[], None] | None = None, + warmup: int = 10, + rep: int = 30, +) -> tuple[float, float, float]: + for _ in range(warmup): + if setup_fn is not None: + setup_fn() + fn() + torch.cuda.synchronize() + + start_event = torch.cuda.Event(enable_timing=True) + end_event = torch.cuda.Event(enable_timing=True) + times_us: list[float] = [] + for _ in range(rep): + if setup_fn is not None: + setup_fn() + start_event.record() + fn() + end_event.record() + end_event.synchronize() + times_us.append(start_event.elapsed_time(end_event) * 1000.0) + + return statistics.median(times_us), max(times_us), min(times_us) + + +def geometric_mean(values: list[float]) -> float: + if not values: + return float("nan") + return math.exp(sum(math.log(v) for v in values) / len(values)) + + +@functools.cache +def load_flaggems(): + ensure_python_dep("sqlalchemy") + ensure_repo("FlagGems", FLAGGEMS_REPO) + src_root = THIRD_PARTY_ROOT / "FlagGems" / "src" + if str(src_root) not in sys.path: + sys.path.insert(0, str(src_root)) + from flag_gems.fused.fused_add_rms_norm import fused_add_rms_norm + from flag_gems.ops.layernorm import layer_norm + from flag_gems.ops.rms_norm import rms_norm + + return rms_norm, layer_norm, fused_add_rms_norm + + +@functools.cache +def load_quack(): + repo_path = ensure_repo("quack", QUACK_REPO) + try: + quack_rmsnorm = importlib.import_module("quack.rmsnorm") + except ModuleNotFoundError: + subprocess.run( + [sys.executable, "-m", "pip", "install", "-e", str(repo_path)], + check=True, + ) + quack_rmsnorm = importlib.import_module("quack.rmsnorm") + + return quack_rmsnorm.rmsnorm_fwd, quack_rmsnorm.layernorm_fwd + + +def build_rmsnorm_providers(dtype: torch.dtype, batch_size: int, hidden_size: int): + import flashinfer.norm as flashinfer_norm + import sgl_kernel + + x = torch.randn((batch_size, hidden_size), device=DEFAULT_DEVICE, dtype=dtype) + weight = torch.randn(hidden_size, device=DEFAULT_DEVICE, dtype=dtype) + + jit_out = torch.empty_like(x) + sgl_out = torch.empty_like(x) + flashinfer_out = torch.empty_like(x) + + flaggems_rms_norm, _, _ = load_flaggems() + quack_rmsnorm_fwd, _ = load_quack() + + providers = { + "pytorch": lambda: F.rms_norm(x, (hidden_size,), weight, 1e-6), + "sgl_kernel": lambda: sgl_kernel.rmsnorm(x, weight, eps=1e-6, out=sgl_out), + "flashinfer": lambda: flashinfer_norm.rmsnorm( + x, weight, eps=1e-6, out=flashinfer_out + ), + "jit_rmsnorm": lambda: jit_rmsnorm(x, weight, jit_out, 1e-6), + "quack": lambda: quack_rmsnorm_fwd(x, weight, eps=1e-6), + "triton_rms_norm_fn": lambda: rms_norm_fn( + x, weight, bias=None, residual=None, eps=1e-6 + ), + "flaggems": lambda: flaggems_rms_norm(x, (hidden_size,), weight, 1e-6), + } + if hidden_size <= 128: + providers["triton_one_pass"] = lambda: triton_one_pass_rms_norm(x, weight, 1e-6) + return providers + + +def build_fused_add_rmsnorm_providers( + dtype: torch.dtype, batch_size: int, hidden_size: int +): + import flashinfer.norm as flashinfer_norm + import sgl_kernel + + base_x = torch.randn((batch_size, hidden_size), device=DEFAULT_DEVICE, dtype=dtype) + base_residual = torch.randn_like(base_x) + weight = torch.randn(hidden_size, device=DEFAULT_DEVICE, dtype=dtype) + + x = base_x.clone() + residual = base_residual.clone() + + def reset(): + x.copy_(base_x) + residual.copy_(base_residual) + + _, _, flaggems_fused_add_rms_norm = load_flaggems() + quack_rmsnorm_fwd, _ = load_quack() + + def pytorch_impl(): + out = x + residual + return F.rms_norm(out, (hidden_size,), weight, 1e-6) + + providers = { + "pytorch": (pytorch_impl, reset), + "sgl_kernel": ( + lambda: sgl_kernel.fused_add_rmsnorm(x, residual, weight, eps=1e-6), + reset, + ), + "flashinfer": ( + lambda: flashinfer_norm.fused_add_rmsnorm(x, residual, weight, eps=1e-6), + reset, + ), + "jit_fused_add_rmsnorm": ( + lambda: jit_fused_add_rmsnorm(x, residual, weight, 1e-6), + reset, + ), + "quack": ( + lambda: quack_rmsnorm_fwd(x, weight, residual=residual, eps=1e-6), + reset, + ), + "flaggems": ( + lambda: flaggems_fused_add_rms_norm( + x, residual, (hidden_size,), weight, 1e-6 + ), + reset, + ), + } + return providers + + +def build_layernorm_providers(dtype: torch.dtype, batch_size: int, hidden_size: int): + import flashinfer.norm as flashinfer_norm + + x = torch.randn((batch_size, hidden_size), device=DEFAULT_DEVICE, dtype=dtype) + weight = torch.randn(hidden_size, device=DEFAULT_DEVICE, dtype=dtype) + bias = torch.randn(hidden_size, device=DEFAULT_DEVICE, dtype=dtype) + flashinfer_weight = torch.randn( + hidden_size, device=DEFAULT_DEVICE, dtype=torch.float32 + ) + flashinfer_bias = torch.randn( + hidden_size, device=DEFAULT_DEVICE, dtype=torch.float32 + ) + + triton_out = torch.empty_like(x) + + _, flaggems_layer_norm, _ = load_flaggems() + _, quack_layernorm_fwd = load_quack() + + providers = { + "pytorch": lambda: F.layer_norm(x, (hidden_size,), weight, bias, 1e-6), + "triton_norm_infer": lambda: norm_infer( + x, weight, bias, eps=1e-6, is_rms_norm=False, out=triton_out + ), + "flashinfer": lambda: flashinfer_norm.layernorm( + x, flashinfer_weight, flashinfer_bias, 1e-6 + ), + "quack": lambda: quack_layernorm_fwd( + x, flashinfer_weight, flashinfer_bias, 1e-6 + ), + "flaggems": lambda: flaggems_layer_norm(x, (hidden_size,), weight, bias)[0], + } + return providers + + +def maybe_benchmark( + op_name: str, + provider_name: str, + fn: Callable[[], object], + rows: list[dict[str, object]], + dtype: torch.dtype, + batch_size: int, + hidden_size: int, + reset: Callable[[], None] | None = None, + metadata: dict[str, object] | None = None, +) -> None: + metadata = metadata or {} + try: + median_us, max_us, min_us = benchmark_provider(fn, reset) + rows.append( + { + "op": op_name, + "provider": provider_name, + "dtype": dtype_name(dtype), + "batch_size": batch_size, + "hidden_size": hidden_size, + "median_us": median_us, + "min_us": min_us, + "max_us": max_us, + "status": "ok", + "error": "", + **metadata, + } + ) + except Exception as exc: # pragma: no cover - benchmark failures are data + rows.append( + { + "op": op_name, + "provider": provider_name, + "dtype": dtype_name(dtype), + "batch_size": batch_size, + "hidden_size": hidden_size, + "median_us": "", + "min_us": "", + "max_us": "", + "status": "unsupported", + "error": str(exc), + **metadata, + } + ) + + +def write_csv(rows: list[dict[str, object]], output_path: Path) -> None: + output_path.parent.mkdir(parents=True, exist_ok=True) + with output_path.open("w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter( + f, + fieldnames=[ + "op", + "provider", + "dtype", + "batch_size", + "hidden_size", + "median_us", + "min_us", + "max_us", + "shape_id", + "source_model", + "source_gpu_config", + "source_input_shape", + "source_impl", + "status", + "error", + ], + ) + writer.writeheader() + writer.writerows(rows) + + +def write_markdown(rows: list[dict[str, object]], output_path: Path) -> None: + lines: list[str] = [] + lines.append("# Norm Benchmark Summary") + lines.append("") + actual_shape_rows = [row for row in rows if row.get("shape_id")] + if actual_shape_rows: + seen: set[tuple[str, str, str, str, str, str]] = set() + lines.append("## Diffusion Shape Cases") + lines.append("") + lines.append( + "| Shape ID | Op | Model | GPU Config | Input Shape | Source Impl |" + ) + lines.append("|---|---|---|---|---|---|") + for row in actual_shape_rows: + key = ( + str(row.get("shape_id", "")), + str(row.get("op", "")), + str(row.get("source_model", "")), + str(row.get("source_gpu_config", "")), + str(row.get("source_input_shape", "")), + str(row.get("source_impl", "")), + ) + if key in seen: + continue + seen.add(key) + lines.append( + f"| {key[0]} | {key[1]} | {key[2]} | {key[3]} | `{key[4]}` | {key[5]} |" + ) + lines.append("") + for op_name in ("rmsnorm", "fused_add_rmsnorm", "layernorm"): + for dtype in sorted({row["dtype"] for row in rows}): + scoped = [ + row + for row in rows + if row["op"] == op_name + and row["dtype"] == dtype + and row["status"] == "ok" + ] + if not scoped: + continue + provider_to_values: dict[str, list[float]] = {} + provider_to_speedups: dict[str, list[float]] = {} + by_shape: dict[tuple[str, int, int], dict[str, float]] = {} + for row in scoped: + provider = str(row["provider"]) + value = float(row["median_us"]) + provider_to_values.setdefault(provider, []).append(value) + shape = ( + str(row.get("shape_id", "")), + int(row["batch_size"]), + int(row["hidden_size"]), + ) + by_shape.setdefault(shape, {})[provider] = value + for shape, perf in by_shape.items(): + if "pytorch" not in perf: + continue + baseline = perf["pytorch"] + for provider, value in perf.items(): + provider_to_speedups.setdefault(provider, []).append( + baseline / value + ) + + lines.append(f"## {op_name} ({dtype})") + lines.append("") + lines.append( + "| Provider | Geomean Speedup vs PyTorch | Median Latency (us) | Win Count |" + ) + lines.append("|---|---:|---:|---:|") + wins: dict[str, int] = {} + for perf in by_shape.values(): + best_provider = min(perf, key=perf.get) + wins[best_provider] = wins.get(best_provider, 0) + 1 + for provider in sorted(provider_to_values): + geomean_speedup = geometric_mean(provider_to_speedups.get(provider, [])) + median_latency = statistics.median(provider_to_values[provider]) + win_count = wins.get(provider, 0) + lines.append( + f"| {provider} | {geomean_speedup:.3f}x | {median_latency:.2f} | {win_count} |" + ) + lines.append("") + output_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def run_suite( + hidden_sizes: list[int], + batch_sizes: list[int], + dtypes: list[torch.dtype], + ops: list[str], +) -> list[dict[str, object]]: + rows: list[dict[str, object]] = [] + for dtype in dtypes: + for batch_size in batch_sizes: + for hidden_size in hidden_sizes: + if "rmsnorm" in ops: + rms_providers = build_rmsnorm_providers( + dtype, batch_size, hidden_size + ) + for provider_name, fn in rms_providers.items(): + maybe_benchmark( + "rmsnorm", + provider_name, + fn, + rows, + dtype, + batch_size, + hidden_size, + ) + + if "fused_add_rmsnorm" in ops: + fused_providers = build_fused_add_rmsnorm_providers( + dtype, batch_size, hidden_size + ) + for provider_name, provider in fused_providers.items(): + fn, reset = provider + maybe_benchmark( + "fused_add_rmsnorm", + provider_name, + fn, + rows, + dtype, + batch_size, + hidden_size, + reset, + ) + + if "layernorm" in ops: + layernorm_providers = build_layernorm_providers( + dtype, batch_size, hidden_size + ) + for provider_name, fn in layernorm_providers.items(): + maybe_benchmark( + "layernorm", + provider_name, + fn, + rows, + dtype, + batch_size, + hidden_size, + ) + return rows + + +def run_shape_suite( + shape_cases: list[dict[str, object]], + dtypes: list[torch.dtype], +) -> list[dict[str, object]]: + rows: list[dict[str, object]] = [] + for case in shape_cases: + op_name = str(case["op"]) + input_shape = [int(x) for x in case["input_shape"]] + batch_size = effective_rows_from_shape(input_shape) + hidden_size = input_shape[-1] + metadata = { + "shape_id": str(case["shape_id"]), + "source_model": str(case["model"]), + "source_gpu_config": str(case["gpu_config"]), + "source_input_shape": str(input_shape), + "source_impl": str(case["source_impl"]), + } + for dtype in dtypes: + if op_name == "rmsnorm": + providers = build_rmsnorm_providers(dtype, batch_size, hidden_size) + for provider_name, fn in providers.items(): + maybe_benchmark( + op_name, + provider_name, + fn, + rows, + dtype, + batch_size, + hidden_size, + metadata=metadata, + ) + elif op_name == "fused_add_rmsnorm": + providers = build_fused_add_rmsnorm_providers( + dtype, batch_size, hidden_size + ) + for provider_name, provider in providers.items(): + fn, reset = provider + maybe_benchmark( + op_name, + provider_name, + fn, + rows, + dtype, + batch_size, + hidden_size, + reset, + metadata=metadata, + ) + elif op_name == "layernorm": + providers = build_layernorm_providers(dtype, batch_size, hidden_size) + for provider_name, fn in providers.items(): + maybe_benchmark( + op_name, + provider_name, + fn, + rows, + dtype, + batch_size, + hidden_size, + metadata=metadata, + ) + else: + raise ValueError(f"Unsupported op in shape preset: {op_name}") + return rows + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Benchmark RMSNorm/LayerNorm implementations across providers." + ) + parser.add_argument( + "--hidden-sizes", + default="64,128,256,512,1024,2048,4096,8192,16384", + help="Comma-separated hidden sizes.", + ) + parser.add_argument( + "--batch-sizes", + default="1,16,128,1024", + help="Comma-separated batch sizes.", + ) + parser.add_argument( + "--dtypes", + default="bf16,fp16", + help="Comma-separated dtypes: bf16, fp16, fp32.", + ) + parser.add_argument( + "--output-dir", + default=str(REPO_ROOT / "outputs" / "norm_benchmarks"), + help="Directory for CSV/Markdown outputs.", + ) + parser.add_argument( + "--ops", + default="rmsnorm,fused_add_rmsnorm,layernorm", + help="Comma-separated ops to benchmark.", + ) + parser.add_argument( + "--shape-preset", + choices=["grid", "diffusion-actual"], + default="grid", + help="Use the default grid sweep or the captured diffusion workload shapes.", + ) + args = parser.parse_args() + + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required for norm benchmarks.") + + hidden_sizes = normalize_hidden_sizes(args.hidden_sizes) + batch_sizes = normalize_hidden_sizes(args.batch_sizes) + dtypes = normalize_dtypes(args.dtypes) + ops = [op.strip() for op in args.ops.split(",") if op.strip()] + + if args.shape_preset == "diffusion-actual": + shape_cases = [case for case in ACTUAL_DIFFUSION_SHAPES if case["op"] in ops] + rows = run_shape_suite(shape_cases, dtypes) + else: + rows = run_suite(hidden_sizes, batch_sizes, dtypes, ops) + output_dir = Path(args.output_dir) + csv_path = output_dir / "norm_impls.csv" + md_path = output_dir / "norm_impls_summary.md" + write_csv(rows, csv_path) + write_markdown(rows, md_path) + print(f"Wrote {csv_path}") + print(f"Wrote {md_path}") + + +if __name__ == "__main__": + if is_in_ci(): + print("Skipping bench_norm_impls.py in CI") + sys.exit(0) + main() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_qknorm_rope.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_qknorm_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..799296d2af9c1d7015c810030e5e526775415cd9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_qknorm_rope.py @@ -0,0 +1,192 @@ +from dataclasses import dataclass +from typing import Tuple + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + DEFAULT_DTYPE, + get_benchmark_range, + run_benchmark_no_cudagraph, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=13, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +MAX_SEQ_LEN = 131072 +ROPE_BASE = 10000.0 + + +@dataclass(frozen=True) +class CaseSpec: + name: str + batch_size: int + num_tokens: int + num_heads: int + head_dim: int + rope_dim: int + is_neox: bool + + +BENCH_CASES = ( + CaseSpec("flux_1024", 1, 4096, 24, 128, 128, False), + CaseSpec("qwen_image_1024", 1, 4096, 32, 128, 128, False), + CaseSpec("qwen_image_partial", 1, 4096, 32, 128, 64, False), + # Z-Image-Turbo default 1024x1024 config: dim=3840, num_heads=30 -> head_dim=128. + CaseSpec("zimage_1024", 1, 4096, 30, 128, 128, False), + CaseSpec("batch2_medium", 2, 2048, 24, 128, 128, False), +) +CASE_BY_NAME = {case.name: case for case in BENCH_CASES} +CASE_NAMES = get_benchmark_range( + full_range=[case.name for case in BENCH_CASES], + ci_range=[case.name for case in BENCH_CASES], +) +LINE_VALS = ["split", "fused"] +LINE_NAMES = ["JIT QKNorm + FlashInfer RoPE", "SGL JIT Fused QKNorm+RoPE"] +STYLES = [("red", "-"), ("blue", "--")] + + +def create_cos_sin_cache( + rotary_dim: int, + max_position: int = MAX_SEQ_LEN, + base: float = ROPE_BASE, +) -> torch.Tensor: + inv_freq = 1.0 / ( + base + ** ( + torch.arange(0, rotary_dim, 2, dtype=torch.float32, device=DEFAULT_DEVICE) + / rotary_dim + ) + ) + t = torch.arange(max_position, dtype=torch.float32, device=DEFAULT_DEVICE) + freqs = torch.einsum("i,j->ij", t, inv_freq) + return torch.cat((freqs.cos(), freqs.sin()), dim=-1) + + +def make_inputs(case: CaseSpec) -> dict[str, torch.Tensor | bool]: + seed = ( + case.batch_size * 1_000_003 + + case.num_tokens * 8191 + + case.num_heads * 127 + + case.head_dim * 17 + + case.rope_dim + ) + generator = torch.Generator(device=DEFAULT_DEVICE) + generator.manual_seed(seed) + return { + "q": torch.randn( + case.batch_size * case.num_tokens, + case.num_heads, + case.head_dim, + device=DEFAULT_DEVICE, + dtype=DEFAULT_DTYPE, + generator=generator, + ), + "k": torch.randn( + case.batch_size * case.num_tokens, + case.num_heads, + case.head_dim, + device=DEFAULT_DEVICE, + dtype=DEFAULT_DTYPE, + generator=generator, + ), + "q_weight": torch.randn( + case.head_dim, + device=DEFAULT_DEVICE, + dtype=DEFAULT_DTYPE, + generator=generator, + ), + "k_weight": torch.randn( + case.head_dim, + device=DEFAULT_DEVICE, + dtype=DEFAULT_DTYPE, + generator=generator, + ), + "positions": torch.randint( + 0, + MAX_SEQ_LEN, + (case.batch_size * case.num_tokens,), + device=DEFAULT_DEVICE, + dtype=torch.int64, + generator=generator, + ), + "cos_sin_cache": create_cos_sin_cache(case.rope_dim), + "is_neox": case.is_neox, + } + + +def clone_inputs( + inputs: dict[str, torch.Tensor | bool], +) -> dict[str, torch.Tensor | bool]: + out: dict[str, torch.Tensor | bool] = {} + for key, value in inputs.items(): + out[key] = value.clone() if isinstance(value, torch.Tensor) else value + return out + + +def split_qknorm_rope(inputs: dict[str, torch.Tensor | bool]) -> None: + from flashinfer.rope import apply_rope_with_cos_sin_cache_inplace + + from sglang.jit_kernel.norm import fused_inplace_qknorm + + q = inputs["q"] + k = inputs["k"] + q_weight = inputs["q_weight"] + k_weight = inputs["k_weight"] + positions = inputs["positions"] + cos_sin_cache = inputs["cos_sin_cache"] + is_neox = bool(inputs["is_neox"]) + + fused_inplace_qknorm(q, k, q_weight, k_weight) + apply_rope_with_cos_sin_cache_inplace( + positions=positions, + query=q.view(q.shape[0], -1), + key=k.view(k.shape[0], -1), + head_size=q.shape[-1], + cos_sin_cache=cos_sin_cache, + is_neox=is_neox, + ) + + +def fused_qknorm_rope(inputs: dict[str, torch.Tensor | bool]) -> None: + from sglang.jit_kernel.diffusion.qknorm_rope import fused_inplace_qknorm_rope + + fused_inplace_qknorm_rope( + inputs["q"], + inputs["k"], + inputs["q_weight"], + inputs["k_weight"], + inputs["cos_sin_cache"], + inputs["positions"], + is_neox=bool(inputs["is_neox"]), + rope_dim=inputs["cos_sin_cache"].shape[-1], + ) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["case_name"], + x_vals=CASE_NAMES, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="diffusion-qknorm-rope-performance", + args={}, + ) +) +def benchmark(case_name: str, provider: str) -> Tuple[float, float, float]: + case = CASE_BY_NAME[case_name] + inputs = make_inputs(case) + fn = split_qknorm_rope if provider == "split" else fused_qknorm_rope + return run_benchmark_no_cudagraph(lambda: fn(inputs)) + + +if __name__ == "__main__": + print("Running diffusion qknorm + rope performance benchmark...") + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_qwen_image_modulation.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_qwen_image_modulation.py new file mode 100644 index 0000000000000000000000000000000000000000..667edd70b42186692c16e26706d2003499969e5f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_qwen_image_modulation.py @@ -0,0 +1,186 @@ +from typing import Tuple + +import torch +import triton.testing + +from sglang.jit_kernel.benchmark.utils import run_benchmark_no_cudagraph +from sglang.jit_kernel.diffusion.triton.norm import norm_infer +from sglang.jit_kernel.diffusion.triton.scale_shift import ( + fuse_layernorm_scale_shift_gate_select01_kernel, + fuse_residual_layernorm_scale_shift_gate_select01_kernel, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=13, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +if is_in_ci(): + B_RANGE, S_RANGE, D_RANGE = [1], [128], [3072] +else: + B_RANGE, S_RANGE, D_RANGE = [1, 2], [128, 512, 2048], [1024, 1536, 3072] + +DTYPE = torch.bfloat16 +DEVICE = "cuda" +EPS = 1e-6 +LINE_VALS = ["split", "fused"] +LINE_NAMES = ["Triton Norm + Torch Select", "Fused Triton"] +STYLES = [("red", "-"), ("blue", "--")] +CONFIG = [(b, s, d) for b in B_RANGE for s in S_RANGE for d in D_RANGE] + + +def _make_common_inputs(batch_size: int, seq_len: int, hidden_size: int): + x = torch.randn(batch_size, seq_len, hidden_size, dtype=DTYPE, device=DEVICE) + weight = torch.randn(hidden_size, dtype=DTYPE, device=DEVICE) + bias = torch.randn(hidden_size, dtype=DTYPE, device=DEVICE) + index = torch.randint(0, 2, (batch_size, seq_len), dtype=torch.int32, device=DEVICE) + scale0 = torch.randn(batch_size, hidden_size, dtype=DTYPE, device=DEVICE) + shift0 = torch.randn(batch_size, hidden_size, dtype=DTYPE, device=DEVICE) + gate0 = torch.randn(batch_size, hidden_size, dtype=DTYPE, device=DEVICE) + scale1 = torch.randn(batch_size, hidden_size, dtype=DTYPE, device=DEVICE) + shift1 = torch.randn(batch_size, hidden_size, dtype=DTYPE, device=DEVICE) + gate1 = torch.randn(batch_size, hidden_size, dtype=DTYPE, device=DEVICE) + return x, weight, bias, index, scale0, shift0, gate0, scale1, shift1, gate1 + + +def _apply_select01_modulation( + x: torch.Tensor, + scale0: torch.Tensor, + shift0: torch.Tensor, + gate0: torch.Tensor, + scale1: torch.Tensor, + shift1: torch.Tensor, + gate1: torch.Tensor, + index: torch.Tensor, +): + idx = index.bool().unsqueeze(-1) + scale = torch.where(idx, scale1.unsqueeze(1), scale0.unsqueeze(1)) + shift = torch.where(idx, shift1.unsqueeze(1), shift0.unsqueeze(1)) + gate = torch.where(idx, gate1.unsqueeze(1), gate0.unsqueeze(1)) + return x * (1 + scale) + shift, gate + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["B", "S", "D"], + x_vals=CONFIG, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="qwen_image_layernorm_scale_shift_gate_select01", + args={}, + ) +) +def bench_layernorm_scale_shift_gate_select01( + B: int, S: int, D: int, provider: str +) -> Tuple[float, float, float]: + x, weight, bias, index, scale0, shift0, gate0, scale1, shift1, gate1 = ( + _make_common_inputs(B, S, D) + ) + + if provider == "split": + + def fn(): + normalized = norm_infer( + x.view(-1, x.shape[-1]), + weight, + bias, + eps=EPS, + is_rms_norm=False, + ).view_as(x) + return _apply_select01_modulation( + normalized, scale0, shift0, gate0, scale1, shift1, gate1, index + ) + + else: + + def fn(): + return fuse_layernorm_scale_shift_gate_select01_kernel( + x, + weight=weight, + bias=bias, + scale0=scale0, + shift0=shift0, + gate0=gate0, + scale1=scale1, + shift1=shift1, + gate1=gate1, + index=index, + eps=EPS, + ) + + return run_benchmark_no_cudagraph(fn) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=["B", "S", "D"], + x_vals=CONFIG, + line_arg="provider", + line_vals=LINE_VALS, + line_names=LINE_NAMES, + styles=STYLES, + ylabel="us", + plot_name="qwen_image_residual_layernorm_scale_shift_gate_select01", + args={}, + ) +) +def bench_residual_layernorm_scale_shift_gate_select01( + B: int, S: int, D: int, provider: str +) -> Tuple[float, float, float]: + x, weight, bias, index, scale0, shift0, gate0, scale1, shift1, gate1 = ( + _make_common_inputs(B, S, D) + ) + residual = torch.randn_like(x) + residual_gate = torch.randn_like(x) + + if provider == "split": + + def fn(): + residual_out = residual + residual_gate * x + normalized = norm_infer( + residual_out.view(-1, residual_out.shape[-1]), + weight, + bias, + eps=EPS, + is_rms_norm=False, + ).view_as(residual_out) + return _apply_select01_modulation( + normalized, scale0, shift0, gate0, scale1, shift1, gate1, index + ) + + else: + + def fn(): + return fuse_residual_layernorm_scale_shift_gate_select01_kernel( + x, + residual=residual, + residual_gate=residual_gate, + weight=weight, + bias=bias, + scale0=scale0, + shift0=shift0, + gate0=gate0, + scale1=scale1, + shift1=shift1, + gate1=gate1, + index=index, + eps=EPS, + ) + + return run_benchmark_no_cudagraph(fn) + + +if __name__ == "__main__": + print(f"\n{'=' * 80}") + print("Benchmark: qwen_image layernorm + scale_shift_gate_select01") + print(f"{'=' * 80}\n") + bench_layernorm_scale_shift_gate_select01.run(print_data=True) + + print(f"\n{'=' * 80}") + print("Benchmark: qwen_image residual + layernorm + scale_shift_gate_select01") + print(f"{'=' * 80}\n") + bench_residual_layernorm_scale_shift_gate_select01.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_residual_gate_add.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_residual_gate_add.py new file mode 100644 index 0000000000000000000000000000000000000000..064e6fc9c5ea99fd0f14c086d745de539347296e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/bench_residual_gate_add.py @@ -0,0 +1,116 @@ +import random +import sys +from dataclasses import dataclass + +import torch + +from sglang.jit_kernel.diffusion.residual_gate_add import residual_gate_add_cuda +from sglang.jit_kernel.diffusion.triton.scale_shift import fuse_scale_shift_kernel +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci( + est_time=30, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +@dataclass(frozen=True) +class Workload: + name: str + residual_shape: tuple[int, ...] + gate_shape: tuple[int, ...] + + +FULL_WORKLOADS = [ + Workload("ltx2_bcast_s32640_c4096", (1, 32640, 4096), (1, 1, 4096)), + Workload("ltx2_full_s8160_c4096", (1, 8160, 4096), (1, 8160, 4096)), + Workload("ideogram4_bcast_s4096_c4608", (1, 4096, 4608), (1, 1, 4608)), + Workload("flux2_bcast_s4608_c3072", (1, 4608, 3072), (1, 1, 3072)), + Workload("flux2_bcast_s4096_c3072", (1, 4096, 3072), (1, 1, 3072)), + Workload("flux2_bcast_s512_c3072", (1, 512, 3072), (1, 1, 3072)), + Workload("ltx2_full_s126_c2048", (1, 126, 2048), (1, 126, 2048)), +] +CI_WORKLOADS = [ + Workload("ltx2_bcast_s1024_c4096", (1, 1024, 4096), (1, 1, 4096)), + Workload("ltx2_full_s512_c4096", (1, 512, 4096), (1, 512, 4096)), +] + + +def cuda_event_us(fn, warmups: int, repeats: int, rounds: int) -> float: + for _ in range(warmups): + fn() + torch.cuda.synchronize() + + samples = [] + for _ in range(rounds): + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + start.record() + for _ in range(repeats): + fn() + end.record() + end.synchronize() + samples.append(start.elapsed_time(end) * 1000.0 / repeats) + samples.sort() + return samples[len(samples) // 2] + + +def benchmark() -> None: + if not torch.cuda.is_available(): + print("CUDA required") + return + + torch.manual_seed(20260625) + random.seed(20260625) + torch.cuda.set_device(0) + + workloads = CI_WORKLOADS if is_in_ci() else FULL_WORKLOADS + warmups = 5 if is_in_ci() else 20 + repeats = 5 if is_in_ci() else 20 + rounds = 5 if is_in_ci() else 13 + + print("| workload | gate | torch us | triton us | cuda us | cuda/triton |") + print("|---|---|---:|---:|---:|---:|") + + for workload in workloads: + residual = torch.randn( + workload.residual_shape, device="cuda", dtype=torch.bfloat16 + ) + update = torch.randn_like(residual) + gate = torch.randn(workload.gate_shape, device="cuda", dtype=torch.bfloat16) + + ref = residual + update * gate + triton_out = fuse_scale_shift_kernel(update, gate, residual, scale_constant=0) + cuda_out = residual_gate_add_cuda(residual, update, gate) + torch.cuda.synchronize() + torch.testing.assert_close(triton_out, ref, atol=5e-2, rtol=5e-2) + torch.testing.assert_close(cuda_out, ref, atol=5e-2, rtol=5e-2) + + fns = { + "torch": lambda: residual + update * gate, + "triton": lambda: fuse_scale_shift_kernel( + update, gate, residual, scale_constant=0 + ), + "cuda": lambda: residual_gate_add_cuda(residual, update, gate), + } + order = ["torch", "triton", "cuda"] + random.shuffle(order) + times = { + name: cuda_event_us(fns[name], warmups, repeats, rounds) for name in order + } + + gate_kind = ( + "bcast" if workload.gate_shape != workload.residual_shape else "full" + ) + print( + f"| {workload.name} | {gate_kind} | {times['torch']:.2f} | " + f"{times['triton']:.2f} | {times['cuda']:.2f} | " + f"{times['triton'] / times['cuda']:.3f}x |" + ) + + torch.cuda.empty_cache() + + +if __name__ == "__main__": + benchmark() + sys.exit(0) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/diffusion_nvfp4_shapes.json b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/diffusion_nvfp4_shapes.json new file mode 100644 index 0000000000000000000000000000000000000000..71fc4dd88ca2713de4b8c045700ce7625c023989 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/diffusion/diffusion_nvfp4_shapes.json @@ -0,0 +1,2676 @@ +{ + "flux": [ + { + "shape": [ + 4608, + 3072, + 15360 + ], + "count": 38, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4608, + 12288, + 3072 + ], + "count": 38, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4608, + 3072, + 3072 + ], + "count": 114, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4096, + 3072, + 3072 + ], + "count": 57, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 10240, + 4096 + ], + "count": 48, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4096, + 3072, + 3072 + ], + "count": 19, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_out.*" + }, + { + "shape": [ + 512, + 12288, + 4096 + ], + "count": 24, + "kind": "runtime_fused_qkv", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.qkv_proj" + }, + { + "shape": [ + 512, + 4096, + 10240 + ], + "count": 24, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 3072, + 3072 + ], + "count": 57, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 4096, + 4096 + ], + "count": 24, + "kind": "actual_runtime_linear", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.o_proj" + }, + { + "shape": [ + 512, + 3072, + 3072 + ], + "count": 19, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_add_out" + }, + { + "shape": [ + 512, + 3072, + 4096 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 77, + 3072, + 768 + ], + "count": 12, + "kind": "actual_runtime_linear", + "prefix": "clip.layers.*.mlp.fc1" + }, + { + "shape": [ + 77, + 768, + 3072 + ], + "count": 12, + "kind": "actual_runtime_linear", + "prefix": "clip.layers.*.mlp.fc2" + }, + { + "shape": [ + 77, + 2304, + 768 + ], + "count": 12, + "kind": "runtime_fused_qkv", + "prefix": "clip.layers.*.self_attn.qkv_proj" + }, + { + "shape": [ + 4096, + 64, + 3072 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4096, + 3072, + 64 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 77, + 768, + 768 + ], + "count": 12, + "kind": "actual_runtime_linear", + "prefix": "clip.layers.*.self_attn.out_proj" + } + ], + "flux2": [ + { + "shape": [ + 4608, + 55296, + 6144 + ], + "count": 48, + "kind": "runtime_fused_qkv_mlp", + "prefix": "single_transformer_blocks.*.attn.to_qkv_mlp_proj" + }, + { + "shape": [ + 4608, + 6144, + 24576 + ], + "count": 48, + "kind": "actual_runtime_linear", + "prefix": "single_transformer_blocks.*.attn.to_out" + }, + { + "shape": [ + 4096, + 36864, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.ff.linear_in" + }, + { + "shape": [ + 4096, + 6144, + 18432 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.ff.linear_out" + }, + { + "shape": [ + 4096, + 18432, + 6144 + ], + "count": 8, + "kind": "synthetic_packed_qkv", + "prefix": "transformer_blocks.*.attn.packed_qkv" + }, + { + "shape": [ + 4096, + 12288, + 6144 + ], + "count": 8, + "kind": "synthetic_packed_kv", + "prefix": "transformer_blocks.*.attn.packed_kv" + }, + { + "shape": [ + 4096, + 6144, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_k" + }, + { + "shape": [ + 4096, + 6144, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_out.*" + }, + { + "shape": [ + 4096, + 6144, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_q" + }, + { + "shape": [ + 4096, + 6144, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_v" + }, + { + "shape": [ + 512, + 36864, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.ff_context.linear_in" + }, + { + "shape": [ + 512, + 6144, + 18432 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.ff_context.linear_out" + }, + { + "shape": [ + 512, + 18432, + 6144 + ], + "count": 8, + "kind": "synthetic_packed_added_qkv", + "prefix": "transformer_blocks.*.attn.packed_qkv" + }, + { + "shape": [ + 512, + 12288, + 6144 + ], + "count": 8, + "kind": "synthetic_packed_kv", + "prefix": "transformer_blocks.*.attn.packed_kv" + }, + { + "shape": [ + 512, + 6144, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.add_k_proj" + }, + { + "shape": [ + 512, + 6144, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.add_q_proj" + }, + { + "shape": [ + 512, + 6144, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.add_v_proj" + }, + { + "shape": [ + 512, + 6144, + 6144 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_add_out" + }, + { + "shape": [ + 512, + 6144, + 15360 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4096, + 6144, + 128 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4096, + 128, + 6144 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "proj_out" + }, + { + "shape": [ + 1, + 36864, + 6144 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 18432, + 6144 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + } + ], + "helios": [ + { + "shape": [ + 11040, + 5120, + 5120 + ], + "count": 240, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 11040, + 13824, + 5120 + ], + "count": 80, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 11040, + 5120, + 13824 + ], + "count": 80, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 11040, + 5120, + 5120 + ], + "count": 80, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 8640, + 5120, + 5120 + ], + "count": 80, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 8640, + 5120, + 5120 + ], + "count": 80, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 10240, + 4096 + ], + "count": 96, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 12288, + 4096 + ], + "count": 48, + "kind": "runtime_fused_qkv", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.qkv_proj" + }, + { + "shape": [ + 512, + 4096, + 10240 + ], + "count": 48, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 4096, + 4096 + ], + "count": 48, + "kind": "actual_runtime_linear", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.o_proj" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 512, + 5120, + 4096 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 8640, + 64, + 5120 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 30720, + 5120 + ], + "count": 4, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 5120, + 5120 + ], + "count": 4, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 1, + 5120, + 256 + ], + "count": 4, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + } + ], + "hunyuanvideo": [ + { + "shape": [ + 27085, + 21504, + 3072 + ], + "count": 40, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.single_blocks.*.linear1" + }, + { + "shape": [ + 27085, + 3072, + 15360 + ], + "count": 40, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.single_blocks.*.linear2" + }, + { + "shape": [ + 27030, + 3072, + 12288 + ], + "count": 20, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.double_blocks.*.img_mlp.*" + }, + { + "shape": [ + 27030, + 12288, + 3072 + ], + "count": 20, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.double_blocks.*.img_mlp.*.proj" + }, + { + "shape": [ + 27030, + 9216, + 3072 + ], + "count": 20, + "kind": "runtime_fused_qkv", + "prefix": "Hunyuan.double_blocks.*.img_attn_qkv" + }, + { + "shape": [ + 27030, + 3072, + 3072 + ], + "count": 20, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.double_blocks.*.img_attn_proj" + }, + { + "shape": [ + 150, + 28672, + 4096 + ], + "count": 32, + "kind": "actual_runtime_linear", + "prefix": "llama.layers.*.mlp.gate_up_proj" + }, + { + "shape": [ + 150, + 4096, + 14336 + ], + "count": 32, + "kind": "actual_runtime_linear", + "prefix": "llama.layers.*.mlp.down_proj" + }, + { + "shape": [ + 150, + 6144, + 4096 + ], + "count": 32, + "kind": "runtime_fused_qkv", + "prefix": "llama.layers.*.self_attn.qkv_proj" + }, + { + "shape": [ + 150, + 4096, + 4096 + ], + "count": 32, + "kind": "actual_runtime_linear", + "prefix": "llama.layers.*.self_attn.o_proj" + }, + { + "shape": [ + 55, + 12288, + 3072 + ], + "count": 20, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 55, + 3072, + 12288 + ], + "count": 20, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 55, + 9216, + 3072 + ], + "count": 20, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 55, + 3072, + 3072 + ], + "count": 20, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 27030, + 64, + 3072 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.final_layer.linear" + }, + { + "shape": [ + 55, + 3072, + 12288 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.txt_in.refiner_blocks.*.mlp.*" + }, + { + "shape": [ + 55, + 12288, + 3072 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.txt_in.refiner_blocks.*.mlp.*.proj" + }, + { + "shape": [ + 55, + 9216, + 3072 + ], + "count": 2, + "kind": "runtime_fused_qkv", + "prefix": "Hunyuan.txt_in.refiner_blocks.*.self_attn_qkv" + }, + { + "shape": [ + 1, + 18432, + 3072 + ], + "count": 40, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 46, + 3072, + 768 + ], + "count": 12, + "kind": "actual_runtime_linear", + "prefix": "clip.layers.*.mlp.fc1" + }, + { + "shape": [ + 46, + 768, + 3072 + ], + "count": 12, + "kind": "actual_runtime_linear", + "prefix": "clip.layers.*.mlp.fc2" + }, + { + "shape": [ + 1, + 9216, + 3072 + ], + "count": 40, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 55, + 3072, + 3072 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.txt_in.refiner_blocks.*.self_attn_proj" + }, + { + "shape": [ + 46, + 2304, + 768 + ], + "count": 12, + "kind": "runtime_fused_qkv", + "prefix": "clip.layers.*.self_attn.qkv_proj" + }, + { + "shape": [ + 55, + 3072, + 4096 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.txt_in.input_embedder" + }, + { + "shape": [ + 46, + 768, + 768 + ], + "count": 12, + "kind": "actual_runtime_linear", + "prefix": "clip.layers.*.self_attn.out_proj" + }, + { + "shape": [ + 1, + 6144, + 3072 + ], + "count": 3, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 3072, + 3072 + ], + "count": 3, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 1, + 3072, + 4096 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.txt_in.c_embedder.*.proj" + }, + { + "shape": [ + 1, + 3072, + 3072 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.txt_in.c_embedder.*" + }, + { + "shape": [ + 1, + 3072, + 3072 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.vector_in.*" + }, + { + "shape": [ + 1, + 3072, + 256 + ], + "count": 3, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 1, + 3072, + 768 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "Hunyuan.vector_in.*.proj" + } + ], + "ltx": [ + { + "shape": [ + 6144, + 4096, + 4096 + ], + "count": 384, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 6144, + 4096, + 16384 + ], + "count": 96, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 6144, + 16384, + 4096 + ], + "count": 96, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 6144, + 4096, + 4096 + ], + "count": 192, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 6144, + 2048, + 4096 + ], + "count": 288, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 6144, + 4096, + 2048 + ], + "count": 96, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1024, + 4096, + 4096 + ], + "count": 194, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1024, + 2048, + 2048 + ], + "count": 194, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 126, + 2048, + 2048 + ], + "count": 672, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 126, + 2048, + 8192 + ], + "count": 96, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 126, + 8192, + 2048 + ], + "count": 96, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 126, + 2048, + 2048 + ], + "count": 288, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1024, + 4096, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1024, + 2048, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 6144, + 128, + 4096 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 6144, + 4096, + 128 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 24576, + 4096 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 4096, + 4096 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 16384, + 4096 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 126, + 128, + 2048 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 126, + 2048, + 128 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 12288, + 2048 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 2048, + 2048 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 8192, + 2048 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 4096, + 256 + ], + "count": 6, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 2048, + 256 + ], + "count": 6, + "kind": "actual_runtime_linear", + "prefix": "" + } + ], + "mova-720p": [ + { + "shape": [ + 44100, + 5120, + 5120 + ], + "count": 3040, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 44100, + 5120, + 5120 + ], + "count": 1760, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 44100, + 13824, + 5120 + ], + "count": 640, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 44100, + 5120, + 13824 + ], + "count": 640, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 44100, + 1536, + 5120 + ], + "count": 960, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 1280, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 2560, + 4096 + ], + "count": 384, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 3072, + 4096 + ], + "count": 192, + "kind": "runtime_fused_qkv", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.qkv_proj" + }, + { + "shape": [ + 512, + 1536, + 1536 + ], + "count": 960, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 4096, + 2560 + ], + "count": 192, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 176400, + 64, + 5120 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 101, + 5120, + 1536 + ], + "count": 960, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 101, + 8960, + 1536 + ], + "count": 480, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 101, + 1536, + 8960 + ], + "count": 480, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 101, + 1536, + 1536 + ], + "count": 2400, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 4096, + 1024 + ], + "count": 192, + "kind": "actual_runtime_linear", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.o_proj" + }, + { + "shape": [ + 101, + 1536, + 1536 + ], + "count": 1440, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 512, + 5120, + 4096 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 512, + 1536, + 4096 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 512, + 1536, + 1536 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 1, + 30720, + 5120 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 403, + 128, + 1536 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 5120, + 5120 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 1, + 9216, + 1536 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 1536, + 1536 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 1, + 5120, + 256 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 1, + 1536, + 256 + ], + "count": 16, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + } + ], + "qwen": [ + { + "shape": [ + 4096, + 3072, + 3072 + ], + "count": 720, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4096, + 3072, + 3072 + ], + "count": 240, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_out.*" + }, + { + "shape": [ + 47, + 3072, + 3072 + ], + "count": 360, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 19, + 3072, + 3072 + ], + "count": 360, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 47, + 3072, + 3072 + ], + "count": 120, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_add_out" + }, + { + "shape": [ + 19, + 3072, + 3072 + ], + "count": 120, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_add_out" + }, + { + "shape": [ + 1, + 18432, + 3072 + ], + "count": 240, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.img_mod" + }, + { + "shape": [ + 1, + 18432, + 3072 + ], + "count": 240, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.txt_mod" + } + ], + "qwen-edit": [ + { + "shape": [ + 8308, + 3072, + 3072 + ], + "count": 720, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 8308, + 3072, + 3072 + ], + "count": 240, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_out.*" + }, + { + "shape": [ + 195, + 3072, + 3072 + ], + "count": 360, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 189, + 3072, + 3072 + ], + "count": 360, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 195, + 3072, + 3072 + ], + "count": 120, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_add_out" + }, + { + "shape": [ + 189, + 3072, + 3072 + ], + "count": 120, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.attn.to_add_out" + }, + { + "shape": [ + 2, + 18432, + 3072 + ], + "count": 240, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.img_mod" + }, + { + "shape": [ + 1, + 18432, + 3072 + ], + "count": 240, + "kind": "actual_runtime_linear", + "prefix": "transformer_blocks.*.txt_mod" + } + ], + "wan-i2v": [ + { + "shape": [ + 15792, + 15360, + 5120 + ], + "count": 320, + "kind": "synthetic_packed_qkv", + "prefix": "blocks.*.attn1.packed_qkv" + }, + { + "shape": [ + 15792, + 5120, + 13824 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.ffn.net.*" + }, + { + "shape": [ + 15792, + 13824, + 5120 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.ffn.net.*.proj" + }, + { + "shape": [ + 15792, + 10240, + 5120 + ], + "count": 320, + "kind": "synthetic_packed_kv", + "prefix": "blocks.*.attn1.packed_kv" + }, + { + "shape": [ + 15792, + 5120, + 5120 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_k" + }, + { + "shape": [ + 15792, + 5120, + 5120 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_out.*" + }, + { + "shape": [ + 15792, + 5120, + 5120 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_q" + }, + { + "shape": [ + 15792, + 5120, + 5120 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_v" + }, + { + "shape": [ + 15792, + 5120, + 5120 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_out.*" + }, + { + "shape": [ + 15792, + 5120, + 5120 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_q" + }, + { + "shape": [ + 512, + 10240, + 5120 + ], + "count": 320, + "kind": "synthetic_packed_kv", + "prefix": "blocks.*.attn2.packed_kv" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_k" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 320, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_v" + }, + { + "shape": [ + 512, + 5120, + 4096 + ], + "count": 384, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 6144, + 4096 + ], + "count": 192, + "kind": "runtime_fused_qkv", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.qkv_proj" + }, + { + "shape": [ + 512, + 4096, + 5120 + ], + "count": 192, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 4096, + 2048 + ], + "count": 192, + "kind": "actual_runtime_linear", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.o_proj" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 512, + 5120, + 4096 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 31584, + 64, + 5120 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "proj_out" + }, + { + "shape": [ + 1, + 30720, + 5120 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 5120, + 5120 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 1, + 5120, + 256 + ], + "count": 8, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + } + ], + "wan-t2v": [ + { + "shape": [ + 37800, + 15360, + 5120 + ], + "count": 160, + "kind": "synthetic_packed_qkv", + "prefix": "blocks.*.attn1.packed_qkv" + }, + { + "shape": [ + 37800, + 5120, + 13824 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.ffn.net.*" + }, + { + "shape": [ + 37800, + 13824, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.ffn.net.*.proj" + }, + { + "shape": [ + 37800, + 10240, + 5120 + ], + "count": 160, + "kind": "synthetic_packed_kv", + "prefix": "blocks.*.attn1.packed_kv" + }, + { + "shape": [ + 37800, + 5120, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_k" + }, + { + "shape": [ + 37800, + 5120, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_out.*" + }, + { + "shape": [ + 37800, + 5120, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_q" + }, + { + "shape": [ + 37800, + 5120, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_v" + }, + { + "shape": [ + 37800, + 5120, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_out.*" + }, + { + "shape": [ + 37800, + 5120, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_q" + }, + { + "shape": [ + 512, + 10240, + 5120 + ], + "count": 160, + "kind": "synthetic_packed_kv", + "prefix": "blocks.*.attn2.packed_kv" + }, + { + "shape": [ + 512, + 5120, + 4096 + ], + "count": 384, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 6144, + 4096 + ], + "count": 192, + "kind": "runtime_fused_qkv", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.qkv_proj" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_k" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 160, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_v" + }, + { + "shape": [ + 512, + 4096, + 5120 + ], + "count": 192, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 4096, + 2048 + ], + "count": 192, + "kind": "actual_runtime_linear", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.o_proj" + }, + { + "shape": [ + 75600, + 64, + 5120 + ], + "count": 4, + "kind": "actual_runtime_linear", + "prefix": "proj_out" + }, + { + "shape": [ + 512, + 5120, + 5120 + ], + "count": 4, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 512, + 5120, + 4096 + ], + "count": 4, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 1, + 30720, + 5120 + ], + "count": 4, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 5120, + 5120 + ], + "count": 4, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 1, + 5120, + 256 + ], + "count": 4, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + } + ], + "wan-ti2v": [ + { + "shape": [ + 18144, + 3072, + 14336 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.ffn.net.*" + }, + { + "shape": [ + 18144, + 14336, + 3072 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.ffn.net.*.proj" + }, + { + "shape": [ + 18144, + 9216, + 3072 + ], + "count": 60, + "kind": "synthetic_packed_qkv", + "prefix": "blocks.*.attn1.packed_qkv" + }, + { + "shape": [ + 18144, + 6144, + 3072 + ], + "count": 60, + "kind": "synthetic_packed_kv", + "prefix": "blocks.*.attn1.packed_kv" + }, + { + "shape": [ + 18144, + 3072, + 3072 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_k" + }, + { + "shape": [ + 18144, + 3072, + 3072 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_out.*" + }, + { + "shape": [ + 18144, + 3072, + 3072 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_q" + }, + { + "shape": [ + 18144, + 3072, + 3072 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn1.to_v" + }, + { + "shape": [ + 18144, + 3072, + 3072 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_out.*" + }, + { + "shape": [ + 18144, + 3072, + 3072 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_q" + }, + { + "shape": [ + 512, + 10240, + 4096 + ], + "count": 96, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 18144, + 18432, + 3072 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 12288, + 4096 + ], + "count": 48, + "kind": "runtime_fused_qkv", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.qkv_proj" + }, + { + "shape": [ + 512, + 4096, + 10240 + ], + "count": 48, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 6144, + 3072 + ], + "count": 60, + "kind": "synthetic_packed_kv", + "prefix": "blocks.*.attn2.packed_kv" + }, + { + "shape": [ + 512, + 4096, + 4096 + ], + "count": 48, + "kind": "actual_runtime_linear", + "prefix": ".encoder.blocks.*.self_attn.SelfAttention.o_proj" + }, + { + "shape": [ + 18144, + 3072, + 3072 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "2" + }, + { + "shape": [ + 512, + 3072, + 3072 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_k" + }, + { + "shape": [ + 512, + 3072, + 3072 + ], + "count": 60, + "kind": "actual_runtime_linear", + "prefix": "blocks.*.attn2.to_v" + }, + { + "shape": [ + 18144, + 3072, + 256 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 18144, + 192, + 3072 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "proj_out" + }, + { + "shape": [ + 512, + 3072, + 4096 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "0.proj" + }, + { + "shape": [ + 512, + 3072, + 3072 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "2" + } + ], + "zimage": [ + { + "shape": [ + 4128, + 20480, + 3840 + ], + "count": 30, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4128, + 11520, + 3840 + ], + "count": 30, + "kind": "synthetic_packed_qkv", + "prefix": "layers.*.attention.packed_qkv" + }, + { + "shape": [ + 4128, + 3840, + 10240 + ], + "count": 30, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4128, + 7680, + 3840 + ], + "count": 30, + "kind": "synthetic_packed_kv", + "prefix": "layers.*.attention.packed_kv" + }, + { + "shape": [ + 4128, + 3840, + 3840 + ], + "count": 30, + "kind": "actual_runtime_linear", + "prefix": "layers.*.attention.to_k" + }, + { + "shape": [ + 4128, + 3840, + 3840 + ], + "count": 30, + "kind": "actual_runtime_linear", + "prefix": "layers.*.attention.to_out.*" + }, + { + "shape": [ + 4128, + 3840, + 3840 + ], + "count": 30, + "kind": "actual_runtime_linear", + "prefix": "layers.*.attention.to_q" + }, + { + "shape": [ + 4128, + 3840, + 3840 + ], + "count": 30, + "kind": "actual_runtime_linear", + "prefix": "layers.*.attention.to_v" + }, + { + "shape": [ + 512, + 19456, + 2560 + ], + "count": 36, + "kind": "actual_runtime_linear", + "prefix": "qwen3.layers.*.mlp.gate_up_proj" + }, + { + "shape": [ + 4096, + 20480, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 2560, + 9728 + ], + "count": 36, + "kind": "actual_runtime_linear", + "prefix": "qwen3.layers.*.mlp.down_proj" + }, + { + "shape": [ + 4096, + 11520, + 3840 + ], + "count": 2, + "kind": "synthetic_packed_qkv", + "prefix": "noise_refiner.*.attention.packed_qkv" + }, + { + "shape": [ + 4096, + 3840, + 10240 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 512, + 6144, + 2560 + ], + "count": 36, + "kind": "runtime_fused_qkv", + "prefix": "qwen3.layers.*.self_attn.qkv_proj" + }, + { + "shape": [ + 4096, + 7680, + 3840 + ], + "count": 2, + "kind": "synthetic_packed_kv", + "prefix": "noise_refiner.*.attention.packed_kv" + }, + { + "shape": [ + 512, + 2560, + 4096 + ], + "count": 36, + "kind": "actual_runtime_linear", + "prefix": "qwen3.layers.*.self_attn.o_proj" + }, + { + "shape": [ + 4096, + 3840, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "noise_refiner.*.attention.to_k" + }, + { + "shape": [ + 4096, + 3840, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "noise_refiner.*.attention.to_out.*" + }, + { + "shape": [ + 4096, + 3840, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "noise_refiner.*.attention.to_q" + }, + { + "shape": [ + 4096, + 3840, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "noise_refiner.*.attention.to_v" + }, + { + "shape": [ + 32, + 20480, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 32, + 11520, + 3840 + ], + "count": 2, + "kind": "synthetic_packed_qkv", + "prefix": "context_refiner.*.attention.packed_qkv" + }, + { + "shape": [ + 32, + 3840, + 10240 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 32, + 7680, + 3840 + ], + "count": 2, + "kind": "synthetic_packed_kv", + "prefix": "context_refiner.*.attention.packed_kv" + }, + { + "shape": [ + 4128, + 64, + 3840 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 4096, + 3840, + 64 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 32, + 3840, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "context_refiner.*.attention.to_k" + }, + { + "shape": [ + 32, + 3840, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "context_refiner.*.attention.to_out.*" + }, + { + "shape": [ + 32, + 3840, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "context_refiner.*.attention.to_q" + }, + { + "shape": [ + 32, + 3840, + 3840 + ], + "count": 2, + "kind": "actual_runtime_linear", + "prefix": "context_refiner.*.attention.to_v" + }, + { + "shape": [ + 32, + 3840, + 2560 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 15360, + 256 + ], + "count": 32, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 3840, + 256 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 256, + 1024 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + }, + { + "shape": [ + 1, + 1024, + 256 + ], + "count": 1, + "kind": "actual_runtime_linear", + "prefix": "" + } + ] +} diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_plan.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..11b99895a6141dfcd4732b3db2a4a036ed9be11f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_plan.py @@ -0,0 +1,347 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional, Tuple + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.kv_canary.utils import ( + POOL_AXIS, + SWA_WINDOW, + BenchCase, + build_fast_matrix_cases, + build_full_matrix_cases, + naive_cumsum_fn, +) +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark, +) +from sglang.jit_kernel.kv_canary.plan import launch_canary_plan_kernels +from sglang.jit_kernel.kv_canary.verify import VerifyPlan +from sglang.jit_kernel.kv_canary.write import WritePlan +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=900, suite="nightly-kernel-1-gpu", nightly=True) +# AMD mirrors the CUDA nightly registration (nightly-only, no per-PR suite). +register_amd_ci(est_time=900, suite="nightly-amd-kernel-1-gpu", nightly=True) + + +_TOTAL_TOKENS_AXIS: list[int] = [256, 4096, 65536, 262144] +_TOTAL_TOKENS_BS_AXIS: list[int] = [1, 32, 256] + + +@dataclass(frozen=True, slots=True, kw_only=True) +class _TotalTokensBenchCase: + bs: int + total_tokens: int + pool_kind: str + + +def _build_total_tokens_cases() -> list[_TotalTokensBenchCase]: + cases: list[_TotalTokensBenchCase] = [] + for bs in _TOTAL_TOKENS_BS_AXIS: + for total_tokens in _TOTAL_TOKENS_AXIS: + if total_tokens < bs: + continue + for pool_kind in POOL_AXIS: + cases.append( + _TotalTokensBenchCase( + bs=bs, total_tokens=total_tokens, pool_kind=pool_kind + ) + ) + return cases + + +_POOL_CAPACITY_VERIFY_CAP_AXIS: list[int] = [16384, 262144, 1398028] +_POOL_CAPACITY_BS_AXIS: list[int] = [1, 4, 32] +_POOL_CAPACITY_PREFIX_LEN: int = 512 +_POOL_CAPACITY_BS_PADDED_AXIS: list[Optional[int]] = [None, 4096] + + +@dataclass(frozen=True, slots=True, kw_only=True) +class _PoolCapacityBenchCase: + """One pool-capacity bench point. + + Attributes: + bs: Number of active (non-padding) requests in the launch. + bs_padded: Total request-axis size of the input tensors. ``None`` means + no padding (``bs_padded == bs``); a concrete value pads ``req_pool_indices`` + with ``REQ_POOL_IDX_PADDING`` sentinels in rows ``[bs, bs_padded)``. + prefix_len: Per-active-request prefix length. + verify_capacity: Plan tensor row capacity. + pool_kind: "full". + """ + + bs: int + bs_padded: Optional[int] + prefix_len: int + verify_capacity: int + pool_kind: str + + +def _build_pool_capacity_cases() -> list[_PoolCapacityBenchCase]: + cases: list[_PoolCapacityBenchCase] = [] + for bs in _POOL_CAPACITY_BS_AXIS: + for verify_capacity in _POOL_CAPACITY_VERIFY_CAP_AXIS: + for bs_padded in _POOL_CAPACITY_BS_PADDED_AXIS: + if bs_padded is not None and bs_padded < bs: + continue + cases.append( + _PoolCapacityBenchCase( + bs=bs, + bs_padded=bs_padded, + prefix_len=_POOL_CAPACITY_PREFIX_LEN, + verify_capacity=verify_capacity, + pool_kind="full", + ) + ) + return cases + + +_X_NAMES_MATRIX = ["scenario", "bs", "prefix_len", "mode", "extend_len", "pool_kind"] + + +def _cases_to_matrix_x_vals( + cases: list[BenchCase], +) -> list[tuple[str, int, int, str, int, str]]: + return [ + (c.scenario, c.bs, c.prefix_len, c.mode, c.extend_len, c.pool_kind) + for c in cases + ] + + +_X_VALS_MATRIX = _cases_to_matrix_x_vals( + get_benchmark_range( + full_range=build_full_matrix_cases(), + ci_range=build_fast_matrix_cases(), + ) +) + +_X_NAMES_TT = ["bs", "total_tokens", "pool_kind"] +_X_VALS_TT = [(c.bs, c.total_tokens, c.pool_kind) for c in _build_total_tokens_cases()] + +_X_NAMES_PC = ["bs", "bs_padded", "prefix_len", "verify_capacity", "pool_kind"] +_X_VALS_PC = [ + ( + c.bs, + c.bs_padded if c.bs_padded is not None else c.bs, + c.prefix_len, + c.verify_capacity, + c.pool_kind, + ) + for c in _build_pool_capacity_cases() +] + + +def _build_plan_inputs( + *, + bs: int, + prefix_len: int, + extend_len: int, + pool_kind: str, + device: torch.device, + verify_capacity_override: Optional[int] = None, + bs_padded: Optional[int] = None, +) -> dict: + swa_window_size = SWA_WINDOW if pool_kind == "swa_window_128" else 0 + verify_per_req = min(prefix_len, SWA_WINDOW) if swa_window_size > 0 else prefix_len + if verify_capacity_override is not None: + verify_capacity = max(1, verify_capacity_override) + else: + verify_capacity = max(1, bs * verify_per_req) + + effective_bs = bs_padded if bs_padded is not None else bs + if effective_bs < bs: + raise ValueError(f"kv-canary bench: bs_padded={bs_padded} must be >= bs={bs}") + write_req_capacity = max(1, effective_bs) + + verify_plan = VerifyPlan.allocate(verify_capacity=verify_capacity, device=device) + write_plan = WritePlan.allocate( + write_req_capacity=write_req_capacity, device=device + ) + + req_pool_indices = torch.zeros(effective_bs, dtype=torch.int64, device=device) + req_pool_indices[:bs] = torch.arange(1, bs + 1, dtype=torch.int64, device=device) + prefix_lens = torch.zeros(effective_bs, dtype=torch.int64, device=device) + prefix_lens[:bs] = prefix_len + extend_seq_lens = torch.zeros(effective_bs, dtype=torch.int64, device=device) + extend_seq_lens[:bs] = extend_len + + max_seq_len = max(prefix_len + extend_len, 1) + req_to_token_rows = effective_bs + 1 + req_to_token = torch.zeros( + req_to_token_rows, + max_seq_len, + dtype=torch.int32, + device=device, + ) + if bs > 0: + row_idx = torch.arange(1, bs + 1, dtype=torch.int32, device=device).unsqueeze(1) + col_idx = torch.arange(max_seq_len, dtype=torch.int32, device=device).unsqueeze( + 0 + ) + req_to_token[1 : bs + 1] = (row_idx - 1) * max_seq_len + col_idx + + if swa_window_size > 0: + full_pool_size = effective_bs * max_seq_len + 1 + full_to_swa: Optional[torch.Tensor] = torch.arange( + full_pool_size + 1, dtype=torch.int64, device=device + ) + full_to_swa[-1] = -1 + else: + full_to_swa = None + + return dict( + verify_plan_out=verify_plan, + write_plan_out=write_plan, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=req_to_token, + swa_window_size=swa_window_size, + full_to_swa_index_mapping=full_to_swa, + verify_capacity=int(verify_plan.verify_slot_indices.shape[0]), + ) + + +def _make_plan_callable(inputs: dict): + def fn() -> None: + launch_canary_plan_kernels( + verify_plan_out=inputs["verify_plan_out"], + write_plan_out=inputs["write_plan_out"], + req_pool_indices=inputs["req_pool_indices"], + prefix_lens=inputs["prefix_lens"], + extend_seq_lens=inputs["extend_seq_lens"], + req_to_token=inputs["req_to_token"], + swa_window_size=inputs["swa_window_size"], + full_to_swa_index_mapping=inputs["full_to_swa_index_mapping"], + verify_capacity=inputs["verify_capacity"], + req_to_verify_expected_tokens=None, + req_to_verify_expected_tokens_valid_lens=None, + kv_token_id_vs_position_offset=0, + ) + + return fn + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=_X_NAMES_MATRIX, + x_vals=_X_VALS_MATRIX, + line_arg="provider", + line_vals=["canary", "naive"], + line_names=["canary_plan_step", "naive torch.cumsum"], + styles=[("blue", "-"), ("red", "--")], + ylabel="us", + plot_name="kv-canary-plan-matrix-perf", + args={}, + ) +) +def benchmark_matrix( + scenario: str, + bs: int, + prefix_len: int, + mode: str, + extend_len: int, + pool_kind: str, + provider: str, +) -> Tuple[float, float, float]: + del scenario + del mode + + device = torch.device(DEFAULT_DEVICE) + if provider == "canary": + inputs = _build_plan_inputs( + bs=bs, + prefix_len=prefix_len, + extend_len=extend_len, + pool_kind=pool_kind, + device=device, + ) + fn = _make_plan_callable(inputs) + else: + fn = naive_cumsum_fn(bs=bs, device=device) + return run_benchmark(fn) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=_X_NAMES_TT, + x_vals=_X_VALS_TT, + line_arg="provider", + line_vals=["canary", "naive"], + line_names=["canary_plan_step", "naive torch.cumsum"], + styles=[("blue", "-"), ("red", "--")], + ylabel="us", + plot_name="kv-canary-plan-total-tokens-perf", + args={}, + ) +) +def benchmark_total_tokens( + bs: int, + total_tokens: int, + pool_kind: str, + provider: str, +) -> Tuple[float, float, float]: + device = torch.device(DEFAULT_DEVICE) + per_req_prefix = max(1, total_tokens // max(bs, 1)) + if provider == "canary": + inputs = _build_plan_inputs( + bs=bs, + prefix_len=per_req_prefix, + extend_len=1, + pool_kind=pool_kind, + device=device, + ) + fn = _make_plan_callable(inputs) + else: + fn = naive_cumsum_fn(bs=bs, device=device) + return run_benchmark(fn) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=_X_NAMES_PC, + x_vals=_X_VALS_PC, + line_arg="provider", + line_vals=["canary", "naive"], + line_names=["canary_plan_step", "naive torch.cumsum"], + styles=[("blue", "-"), ("red", "--")], + ylabel="us", + plot_name="kv-canary-plan-pool-capacity-perf", + args={}, + ) +) +def benchmark_pool_capacity( + bs: int, + bs_padded: int, + prefix_len: int, + verify_capacity: int, + pool_kind: str, + provider: str, +) -> Tuple[float, float, float]: + device = torch.device(DEFAULT_DEVICE) + if provider == "canary": + inputs = _build_plan_inputs( + bs=bs, + prefix_len=prefix_len, + extend_len=1, + pool_kind=pool_kind, + device=device, + verify_capacity_override=verify_capacity, + bs_padded=bs_padded, + ) + fn = _make_plan_callable(inputs) + else: + fn = naive_cumsum_fn(bs=bs, device=device) + return run_benchmark(fn) + + +if __name__ == "__main__": + benchmark_matrix.run(print_data=True) + benchmark_total_tokens.run(print_data=True) + benchmark_pool_capacity.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_scatter_req_token_ids.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_scatter_req_token_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..f40253e10429f078c01a2fe4756b28b4a3b329ca --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_scatter_req_token_ids.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +from dataclasses import dataclass + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark_no_cudagraph, +) +from sglang.jit_kernel.kv_canary.scatter_req_token_ids import ( + launch_scatter_req_token_ids_kernel, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=180, suite="nightly-kernel-1-gpu", nightly=True) +# AMD mirrors the CUDA nightly registration (nightly-only, no per-PR suite). +# Note: amd_ci_exec.sh sets SGLANG_IS_IN_CI, so this runs the CI-reduced range +# (_BS_AXIS_CI/_SEQ_LEN_AXIS_CI via get_benchmark_range), same as CUDA nightly. +register_amd_ci(est_time=180, suite="nightly-amd-kernel-1-gpu", nightly=True) + + +_BS_AXIS_FULL: list[int] = [1, 8, 64, 256] +_SEQ_LEN_AXIS_FULL: list[int] = [128, 512, 2048, 8192] +_BS_AXIS_CI: list[int] = [1, 64] +_SEQ_LEN_AXIS_CI: list[int] = [512, 2048] + + +@dataclass(frozen=True, slots=True, kw_only=True) +class _BenchCase: + bs: int + seq_len: int + + +def _build_cases() -> list[_BenchCase]: + bs_axis = get_benchmark_range(full_range=_BS_AXIS_FULL, ci_range=_BS_AXIS_CI) + seq_axis = get_benchmark_range( + full_range=_SEQ_LEN_AXIS_FULL, ci_range=_SEQ_LEN_AXIS_CI + ) + return [ + _BenchCase(bs=bs, seq_len=seq_len) for bs in bs_axis for seq_len in seq_axis + ] + + +_X_NAMES = ["bs", "seq_len"] +_X_VALS = [(c.bs, c.seq_len) for c in _build_cases()] + + +def _build_inputs(*, bs: int, seq_len: int, device: torch.device) -> dict: + max_reqs = max(bs + 1, 4) + max_context_len = max(seq_len + 1, 1) + total_tokens = bs * seq_len + + flat = torch.randint( + low=0, + high=1 << 30, + size=(total_tokens,), + dtype=torch.int64, + device=device, + ) + lens = torch.full((bs,), seq_len, dtype=torch.int64, device=device) + offsets = torch.zeros(bs + 1, dtype=torch.int64, device=device) + offsets[1:] = torch.cumsum(lens, dim=0) + + req_pool_indices = torch.arange(1, bs + 1, dtype=torch.int64, device=device) + pool = torch.zeros((max_reqs, max_context_len), dtype=torch.int32, device=device) + return dict( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=pool, + ) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=_X_NAMES, + x_vals=_X_VALS, + line_arg="provider", + line_vals=["triton"], + line_names=["Triton"], + styles=[("blue", "-")], + ylabel="time (us)", + plot_name="kv-canary-scatter-req-token-ids", + args={}, + ) +) +def benchmark(bs: int, seq_len: int, provider: str) -> tuple[float, float, float]: + inputs = _build_inputs(bs=bs, seq_len=seq_len, device=torch.device(DEFAULT_DEVICE)) + return run_benchmark_no_cudagraph( + lambda: launch_scatter_req_token_ids_kernel(**inputs) + ) + + +if __name__ == "__main__": + benchmark.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_verify.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_verify.py new file mode 100644 index 0000000000000000000000000000000000000000..06cf7b42cc4a2128ff2a1a9b72ba3f0c887a3f11 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_verify.py @@ -0,0 +1,318 @@ +from __future__ import annotations + +from typing import Tuple + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.kv_canary.utils import ( + RING_CAPACITY, + SWA_WINDOW, + BenchCase, + build_fast_matrix_cases, + build_full_matrix_cases, + cases_to_x_vals, + make_real_kv_sources, + naive_slot_copy_fn, +) +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark, +) +from sglang.jit_kernel.kv_canary import consts +from sglang.jit_kernel.kv_canary.verify import ( + CANARY_SLOT_BYTES, + CanaryLaunchTag, + RealKvSource, + VerifyOrWriteContext, + VerifyPlan, + launch_canary_verify_kernel, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=900, suite="nightly-kernel-1-gpu", nightly=True) +# AMD mirrors the CUDA nightly registration (nightly-only, no per-PR suite). +# Note: amd_ci_exec.sh sets SGLANG_IS_IN_CI, so this runs the CI-reduced range +# (build_fast_matrix_cases via get_benchmark_range), same as CUDA nightly. +register_amd_ci(est_time=900, suite="nightly-amd-kernel-1-gpu", nightly=True) + + +_X_NAMES = [ + "scenario", + "bs", + "prefix_len", + "mode", + "extend_len", + "pool_kind", + "real_kv_kind", + "hash_mode", +] +_X_VALS = cases_to_x_vals( + get_benchmark_range( + full_range=build_full_matrix_cases(), + ci_range=build_fast_matrix_cases(), + ) +) + +_KERNEL_KIND_X_NAMES = ["kernel_kind_name"] +_KERNEL_KIND_X_VALS = [(tag.name,) for tag in CanaryLaunchTag] + + +def _verify_entry_count(case: BenchCase) -> int: + if case.pool_kind == "swa_window_128": + per_req = min(case.prefix_len, SWA_WINDOW) + else: + per_req = case.prefix_len + return case.bs * per_req + + +def _verify_num_slots(case: BenchCase) -> int: + if case.pool_kind == "swa_window_128": + per_req_slots = SWA_WINDOW + else: + per_req_slots = max(1, case.prefix_len) + return max(2, case.bs * per_req_slots + 1) + + +def _build_verify_inputs(case: BenchCase, *, device: torch.device) -> Tuple[ + torch.Tensor, + VerifyPlan, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + tuple[RealKvSource, ...], +]: + total_entries = _verify_entry_count(case) + capacity = max(1, total_entries) + num_slots = _verify_num_slots(case) + + canary_buf = torch.zeros( + num_slots, CANARY_SLOT_BYTES, dtype=torch.uint8, device=device + ) + + slot_indices = torch.empty(capacity, dtype=torch.int64, device=device) + positions = torch.empty(capacity, dtype=torch.int64, device=device) + prev_slots = torch.empty(capacity, dtype=torch.int64, device=device) + if total_entries > 0: + flat_idx = torch.arange(total_entries, device=device, dtype=torch.int64) + per_req = total_entries // case.bs if case.bs > 0 else 0 + slot_indices[:total_entries] = (flat_idx % max(num_slots - 1, 1)).to( + torch.int64 + ) + positions[:total_entries] = (flat_idx % max(per_req, 1)).to(torch.int64) + is_head = (flat_idx % max(per_req, 1)) == 0 + prev_seq = (flat_idx - 1) % max(num_slots - 1, 1) + prev_slots[:total_entries] = torch.where( + is_head, torch.full_like(flat_idx, -1), prev_seq + ).to(torch.int64) + if capacity > total_entries: + slot_indices[total_entries:] = 0 + positions[total_entries:] = 0 + prev_slots[total_entries:] = -1 + + num_valid = torch.tensor([total_entries], dtype=torch.int32, device=device) + enable = torch.ones(1, dtype=torch.int32, device=device) + expected_input_ids = torch.full((capacity,), -1, dtype=torch.int64, device=device) + plan = VerifyPlan( + verify_slot_indices=slot_indices, + verify_expected_tokens=expected_input_ids, + verify_expected_positions=positions, + verify_prev_slot_indices=prev_slots, + verify_num_valid=num_valid, + enable=enable, + ) + + violation_ring = torch.zeros( + RING_CAPACITY, consts.VIOLATION_FIELDS, dtype=torch.int64, device=device + ) + violation_write_index = torch.zeros(1, dtype=torch.int32, device=device) + slot_run_counter = torch.zeros(1, dtype=torch.int64, device=device) + kernel_run_counter = torch.zeros(1, dtype=torch.int64, device=device) + enable_chain_position_assert = torch.ones(1, dtype=torch.int32, device=device) + + real_kv_sources = make_real_kv_sources( + kind=case.real_kv_kind, num_slots=num_slots, device=device + ) + + return ( + canary_buf, + plan, + violation_ring, + violation_write_index, + slot_run_counter, + kernel_run_counter, + enable_chain_position_assert, + real_kv_sources, + ) + + +def _build_context( + *, + canary_buf: torch.Tensor, + violation_ring: torch.Tensor, + violation_write_index: torch.Tensor, + slot_run_counter: torch.Tensor, + kernel_run_counter: torch.Tensor, + enable_chain_position_assert: torch.Tensor, + real_kv_sources: tuple[RealKvSource, ...], + kernel_kind: CanaryLaunchTag, + hash_mode: consts.RealKvHashMode, +) -> VerifyOrWriteContext: + return VerifyOrWriteContext( + canary_buf=canary_buf, + kernel_kind=kernel_kind, + violation_ring=violation_ring, + violation_write_index=violation_write_index, + slot_run_counter=slot_run_counter, + kernel_run_counter=kernel_run_counter, + real_kv_sources=real_kv_sources, + real_kv_hash_mode=hash_mode, + enable_chain_position_assert=enable_chain_position_assert, + ) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=_X_NAMES, + x_vals=_X_VALS, + line_arg="provider", + line_vals=["canary", "naive"], + line_names=["canary_verify_step", "naive index_copy_"], + styles=[("blue", "-"), ("red", "--")], + ylabel="us", + plot_name="kv-canary-verify-perf", + args={}, + ) +) +def benchmark( + scenario: str, + bs: int, + prefix_len: int, + mode: str, + extend_len: int, + pool_kind: str, + real_kv_kind: str, + hash_mode: str, + provider: str, +) -> Tuple[float, float, float]: + case = BenchCase( + scenario=scenario, + bs=bs, + prefix_len=prefix_len, + mode=mode, + extend_len=extend_len, + pool_kind=pool_kind, + real_kv_kind=real_kv_kind, + hash_mode=hash_mode, + ) + device = torch.device(DEFAULT_DEVICE) + + if provider == "canary": + ( + canary_buf, + plan, + violation_ring, + violation_write_index, + slot_run_counter, + kernel_run_counter, + enable_chain_position_assert, + real_kv_sources, + ) = _build_verify_inputs(case, device=device) + hash_mode_enum = consts.RealKvHashMode[case.hash_mode.upper()] + context = _build_context( + canary_buf=canary_buf, + violation_ring=violation_ring, + violation_write_index=violation_write_index, + slot_run_counter=slot_run_counter, + kernel_run_counter=kernel_run_counter, + enable_chain_position_assert=enable_chain_position_assert, + real_kv_sources=real_kv_sources, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + hash_mode=hash_mode_enum, + ) + + def fn() -> None: + violation_write_index.zero_() + launch_canary_verify_kernel( + context=context, + plan=plan, + check_verify_expected_token=True, + ) + + else: + fn = naive_slot_copy_fn(total=_verify_entry_count(case), device=device) + + return run_benchmark(fn) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=_KERNEL_KIND_X_NAMES, + x_vals=_KERNEL_KIND_X_VALS, + line_arg="provider", + line_vals=["canary"], + line_names=["canary_verify_step"], + styles=[("blue", "-")], + ylabel="us", + plot_name="kv-canary-verify-kernel-kind-perf", + args={}, + ) +) +def benchmark_kernel_kind( + kernel_kind_name: str, + provider: str, +) -> Tuple[float, float, float]: + case = BenchCase( + scenario="kernel_kind", + bs=32, + prefix_len=4096, + mode="extend", + extend_len=128, + pool_kind="full", + real_kv_kind="none", + hash_mode="none", + ) + device = torch.device(DEFAULT_DEVICE) + + ( + canary_buf, + plan, + violation_ring, + violation_write_index, + slot_run_counter, + kernel_run_counter, + enable_chain_position_assert, + real_kv_sources, + ) = _build_verify_inputs(case, device=device) + kernel_kind = CanaryLaunchTag[kernel_kind_name] + hash_mode_enum = consts.RealKvHashMode[case.hash_mode.upper()] + context = _build_context( + canary_buf=canary_buf, + violation_ring=violation_ring, + violation_write_index=violation_write_index, + slot_run_counter=slot_run_counter, + kernel_run_counter=kernel_run_counter, + enable_chain_position_assert=enable_chain_position_assert, + real_kv_sources=real_kv_sources, + kernel_kind=kernel_kind, + hash_mode=hash_mode_enum, + ) + + def fn() -> None: + violation_write_index.zero_() + launch_canary_verify_kernel( + context=context, + plan=plan, + check_verify_expected_token=True, + ) + + return run_benchmark(fn) + + +if __name__ == "__main__": + benchmark.run(print_data=True) + benchmark_kernel_kind.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_write.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_write.py new file mode 100644 index 0000000000000000000000000000000000000000..471c4bd5db973fbd9a38d85ec700d690ba430faa --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/kv_canary/bench_write.py @@ -0,0 +1,314 @@ +from __future__ import annotations + +from typing import Tuple + +import torch +import triton +import triton.testing + +from sglang.jit_kernel.benchmark.kv_canary.utils import ( + RING_CAPACITY, + SWA_WINDOW, + BenchCase, + build_fast_matrix_cases, + build_full_matrix_cases, + cases_to_x_vals, + make_real_kv_sources, + naive_slot_copy_fn, +) +from sglang.jit_kernel.benchmark.utils import ( + DEFAULT_DEVICE, + get_benchmark_range, + run_benchmark, +) +from sglang.jit_kernel.kv_canary import consts +from sglang.jit_kernel.kv_canary.verify import ( + CANARY_SLOT_BYTES, + CanaryLaunchTag, + VerifyOrWriteContext, +) +from sglang.jit_kernel.kv_canary.write import WritePlan, launch_canary_write_kernel +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=900, suite="nightly-kernel-1-gpu", nightly=True) +# AMD mirrors the CUDA nightly registration (nightly-only, no per-PR suite). +# Note: amd_ci_exec.sh sets SGLANG_IS_IN_CI, so this runs the CI-reduced range +# (build_fast_matrix_cases via get_benchmark_range), same as CUDA nightly. +register_amd_ci(est_time=900, suite="nightly-amd-kernel-1-gpu", nightly=True) + + +_X_NAMES = [ + "scenario", + "bs", + "prefix_len", + "mode", + "extend_len", + "pool_kind", + "real_kv_kind", + "hash_mode", +] +_X_VALS = cases_to_x_vals( + get_benchmark_range( + full_range=build_full_matrix_cases(), + ci_range=build_fast_matrix_cases(), + ) +) + +_KERNEL_KIND_X_NAMES = ["kernel_kind_name", "enable_write_verify_inputs_name"] +_KERNEL_KIND_X_VALS = [ + (tag.name, str(enable)) for tag in CanaryLaunchTag for enable in (False, True) +] + + +def _write_entry_count(case: BenchCase) -> int: + return case.bs * case.extend_len + + +def _write_num_slots(case: BenchCase) -> int: + per_req_slots = max( + SWA_WINDOW if case.pool_kind == "swa_window_128" else 1, + case.prefix_len + case.extend_len, + ) + return max(2, case.bs * per_req_slots + 1) + + +def _build_write_inputs( + case: BenchCase, *, device: torch.device, mirror_expected_inputs: bool = False +) -> dict: + total_entries = _write_entry_count(case) + num_tokens_padded = max(1, total_entries) + + per_req_slots = max( + SWA_WINDOW if case.pool_kind == "swa_window_128" else 1, + case.prefix_len + case.extend_len, + ) + num_slots = _write_num_slots(case) + + canary_buf = torch.zeros( + num_slots, CANARY_SLOT_BYTES, dtype=torch.uint8, device=device + ) + + write_offsets = torch.zeros(case.bs + 1, dtype=torch.int64, device=device) + if case.bs > 0: + offsets_host = torch.arange(0, case.bs + 1, dtype=torch.int64) * case.extend_len + write_offsets.copy_(offsets_host.to(device)) + + write_seed_slots = torch.empty(case.bs, dtype=torch.int64, device=device) + if case.bs > 0: + if case.prefix_len == 0: + write_seed_slots.fill_(-1) + else: + per_req_stride = per_req_slots + seeds = ( + torch.arange(case.bs, dtype=torch.int32, device=device) * per_req_stride + + case.prefix_len + - 1 + ) + write_seed_slots.copy_(seeds.to(torch.int64)) + + write_num_valid_reqs = torch.tensor([case.bs], dtype=torch.int32, device=device) + + plan = WritePlan( + write_offsets=write_offsets, + write_seed_slot_indices=write_seed_slots, + write_num_valid_reqs=write_num_valid_reqs, + ) + + input_ids = torch.zeros(num_tokens_padded, dtype=torch.int64, device=device) + positions = torch.zeros(num_tokens_padded, dtype=torch.int64, device=device) + out_cache_loc = torch.zeros(num_tokens_padded, dtype=torch.int64, device=device) + if total_entries > 0: + flat_idx = torch.arange(total_entries, device=device, dtype=torch.int64) + per_req_idx = flat_idx % max(case.extend_len, 1) + req_idx = flat_idx // max(case.extend_len, 1) + per_req_stride = per_req_slots + slots = (req_idx * per_req_stride + case.prefix_len + per_req_idx) % max( + num_slots, 1 + ) + input_ids[:total_entries] = (flat_idx % 32768).to(torch.int64) + positions[:total_entries] = (case.prefix_len + per_req_idx).to(torch.int64) + out_cache_loc[:total_entries] = slots.to(torch.int64) + + if case.pool_kind == "swa_window_128": + full_to_swa = torch.arange(num_slots + 1, dtype=torch.int64, device=device) + full_to_swa[-1] = -1 + out_cache_loc = full_to_swa[out_cache_loc] + + if mirror_expected_inputs: + expected_input_tokens = input_ids.clone() + expected_input_positions = positions.clone() + else: + expected_input_tokens = None + expected_input_positions = None + + violation_ring = torch.zeros( + RING_CAPACITY, consts.VIOLATION_FIELDS, dtype=torch.int64, device=device + ) + violation_write_index = torch.zeros(1, dtype=torch.int32, device=device) + slot_run_counter = torch.zeros(1, dtype=torch.int64, device=device) + kernel_run_counter = torch.zeros(1, dtype=torch.int64, device=device) + enable_chain_position_assert = torch.ones(1, dtype=torch.int32, device=device) + + real_kv_sources = make_real_kv_sources( + kind=case.real_kv_kind, num_slots=num_slots, device=device + ) + + return dict( + canary_buf=canary_buf, + plan=plan, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + expected_input_tokens=expected_input_tokens, + expected_input_positions=expected_input_positions, + violation_ring=violation_ring, + violation_write_index=violation_write_index, + slot_run_counter=slot_run_counter, + kernel_run_counter=kernel_run_counter, + enable_chain_position_assert=enable_chain_position_assert, + real_kv_sources=real_kv_sources, + ) + + +def _build_context( + *, + inputs: dict, + kernel_kind: CanaryLaunchTag, + hash_mode: consts.RealKvHashMode, +) -> VerifyOrWriteContext: + return VerifyOrWriteContext( + canary_buf=inputs["canary_buf"], + kernel_kind=kernel_kind, + violation_ring=inputs["violation_ring"], + violation_write_index=inputs["violation_write_index"], + slot_run_counter=inputs["slot_run_counter"], + kernel_run_counter=inputs["kernel_run_counter"], + real_kv_sources=inputs["real_kv_sources"], + real_kv_hash_mode=hash_mode, + enable_chain_position_assert=inputs["enable_chain_position_assert"], + ) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=_X_NAMES, + x_vals=_X_VALS, + line_arg="provider", + line_vals=["canary", "naive"], + line_names=["canary_write_step", "naive index_copy_"], + styles=[("blue", "-"), ("red", "--")], + ylabel="us", + plot_name="kv-canary-write-perf", + args={}, + ) +) +def benchmark( + scenario: str, + bs: int, + prefix_len: int, + mode: str, + extend_len: int, + pool_kind: str, + real_kv_kind: str, + hash_mode: str, + provider: str, +) -> Tuple[float, float, float]: + case = BenchCase( + scenario=scenario, + bs=bs, + prefix_len=prefix_len, + mode=mode, + extend_len=extend_len, + pool_kind=pool_kind, + real_kv_kind=real_kv_kind, + hash_mode=hash_mode, + ) + device = torch.device(DEFAULT_DEVICE) + + if provider == "canary": + inputs = _build_write_inputs(case, device=device) + hash_mode_enum = consts.RealKvHashMode[case.hash_mode.upper()] + context = _build_context( + inputs=inputs, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + hash_mode=hash_mode_enum, + ) + + def fn() -> None: + launch_canary_write_kernel( + context=context, + plan=inputs["plan"], + input_ids=inputs["input_ids"], + positions=inputs["positions"], + out_cache_loc=inputs["out_cache_loc"], + enable_write_input_assert=False, + expected_input_tokens=inputs["expected_input_tokens"], + expected_input_positions=inputs["expected_input_positions"], + ) + + else: + fn = naive_slot_copy_fn(total=_write_entry_count(case), device=device) + + return run_benchmark(fn) + + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=_KERNEL_KIND_X_NAMES, + x_vals=_KERNEL_KIND_X_VALS, + line_arg="provider", + line_vals=["canary"], + line_names=["canary_write_step"], + styles=[("blue", "-")], + ylabel="us", + plot_name="kv-canary-write-kernel-kind-perf", + args={}, + ) +) +def benchmark_kernel_kind( + kernel_kind_name: str, + enable_write_verify_inputs_name: str, + provider: str, +) -> Tuple[float, float, float]: + case = BenchCase( + scenario="kernel_kind", + bs=32, + prefix_len=4096, + mode="extend", + extend_len=128, + pool_kind="full", + real_kv_kind="none", + hash_mode="none", + ) + device = torch.device(DEFAULT_DEVICE) + + enable_write_verify_inputs = enable_write_verify_inputs_name == "True" + inputs = _build_write_inputs( + case, device=device, mirror_expected_inputs=enable_write_verify_inputs + ) + kernel_kind = CanaryLaunchTag[kernel_kind_name] + hash_mode_enum = consts.RealKvHashMode[case.hash_mode.upper()] + context = _build_context( + inputs=inputs, + kernel_kind=kernel_kind, + hash_mode=hash_mode_enum, + ) + + def fn() -> None: + launch_canary_write_kernel( + context=context, + plan=inputs["plan"], + input_ids=inputs["input_ids"], + positions=inputs["positions"], + out_cache_loc=inputs["out_cache_loc"], + enable_write_input_assert=enable_write_verify_inputs, + expected_input_tokens=inputs["expected_input_tokens"], + expected_input_positions=inputs["expected_input_positions"], + ) + + return run_benchmark(fn) + + +if __name__ == "__main__": + benchmark.run(print_data=True) + benchmark_kernel_kind.run(print_data=True) diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/minimax/bench_minimax_decode_topk.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/minimax/bench_minimax_decode_topk.py new file mode 100644 index 0000000000000000000000000000000000000000..fe57381af7339823764eaa234b3745ce18fb7ffd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/minimax/bench_minimax_decode_topk.py @@ -0,0 +1,123 @@ +"""Benchmark: MiniMax-M3 single-stage radix-select decode topk (JIT CUDA) vs the +2-stage split-K Triton baseline (_topk_index_partial_kernel + _topk_index_merge_kernel). + +Both consume the decode score tensor [num_heads, batch, max_seqblock] and produce +topk_idx [num_heads, batch, topk]. The JIT kernel is one launch with no +intermediate buffers; the baseline is two launches with split-K partials. +""" + +import torch +import triton + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.minimax_decode_topk import minimax_decode_topk +from sglang.srt.layers.attention.minimax_sparse_ops.decode.flash_with_topk_idx import ( + _topk_index_merge_kernel, + _topk_index_partial_kernel, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=8, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +BLOCK_SIZE = 128 +TOPK = 16 +NUM_HEADS = 1 # per-rank index heads at TP>=4 + + +def _triton_2stage(score, seq_lens): + num_q_heads, batch_size, max_seqblock = score.shape + TOPK_TARGET_GRID = 64 + MAX_NUM_TOPK_CHUNKS = 16 + t = max( + 1, + min(MAX_NUM_TOPK_CHUNKS, TOPK_TARGET_GRID // max(1, batch_size * num_q_heads)), + ) + nchunks = 1 << (t.bit_length() - 1) + bt = triton.next_power_of_2(TOPK) + chunk_blocks = (max_seqblock + nchunks - 1) // nchunks + out = torch.empty( + (num_q_heads, batch_size, TOPK), device=score.device, dtype=torch.int32 + ) + tsp = torch.empty( + nchunks, num_q_heads, batch_size, bt, dtype=torch.float32, device=score.device + ) + tip = torch.empty( + nchunks, num_q_heads, batch_size, bt, dtype=torch.int32, device=score.device + ) + _topk_index_partial_kernel[(batch_size, num_q_heads, nchunks)]( + score, + tsp, + tip, + seq_lens, + BLOCK_SIZE, + TOPK, + chunk_blocks, + score.stride(0), + score.stride(1), + score.stride(2), + tsp.stride(0), + tsp.stride(1), + tsp.stride(2), + tsp.stride(3), + tip.stride(0), + tip.stride(1), + tip.stride(2), + tip.stride(3), + ) + _topk_index_merge_kernel[(batch_size, num_q_heads)]( + tsp, + tip, + out, + seq_lens, + BLOCK_SIZE, + TOPK, + tsp.stride(0), + tsp.stride(1), + tsp.stride(2), + tsp.stride(3), + tip.stride(0), + tip.stride(1), + tip.stride(2), + tip.stride(3), + out.stride(0), + out.stride(1), + out.stride(2), + NUM_TOPK_CHUNKS=nchunks, + ) + return out + + +def _jit(score, seq_lens): + return minimax_decode_topk(score, seq_lens, BLOCK_SIZE, TOPK) + + +FN_MAP = {"jit": _jit, "triton_2stage": _triton_2stage} + + +@marker.parametrize("ctx", [4096, 32768, 131072, 524288], [4096, 524288]) +@marker.parametrize("batch", [1, 4, 16, 64, 256], [1, 64]) +@marker.benchmark("impl", ["jit", "triton_2stage"]) +def benchmark(ctx: int, batch: int, impl: str): + max_seqblock = (524288 + BLOCK_SIZE - 1) // BLOCK_SIZE + nb = min((ctx + BLOCK_SIZE - 1) // BLOCK_SIZE, max_seqblock) + score = torch.full( + (NUM_HEADS, batch, max_seqblock), + float("-inf"), + dtype=torch.float32, + device="cuda", + ) + score[:, :, :nb] = torch.randn(NUM_HEADS, batch, nb, device="cuda") * 5.0 + score[:, :, nb - 1] = 1e29 # forced local block + seq_lens = torch.full((batch,), ctx, device="cuda", dtype=torch.int32) + return marker.do_bench( + FN_MAP[impl], + input_args=(score, seq_lens), + graph_clone_args=(0, 1), # both read-only inputs + memory_args=(score,), + ) + + +if __name__ == "__main__": + benchmark.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/minimax/bench_minimax_qknorm_rope.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/minimax/bench_minimax_qknorm_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..54cb56cfdc400219edb291d9d9ee303d4962d4d1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/minimax/bench_minimax_qknorm_rope.py @@ -0,0 +1,148 @@ +"""Benchmark: fused MiniMax-M3 Gemma-RMSNorm + partial NeoX RoPE (1 in-place +launch) vs the unfused path (GemmaRMSNorm(q) + GemmaRMSNorm(k) + rotary_emb, +3 launches + intermediates). Main attention branch, per-rank TP8 shape (nq=8, nk=1). +""" + +import torch + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.minimax_qknorm_rope import ( + minimax_qknorm_rope, + minimax_qknorm_rope_grouped, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=6, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +HEAD_DIM, ROTARY_DIM, BASE, EPS, MAXPOS = 128, 64, 5_000_000, 1e-6, 131072 +NQ, NK = 64, 4 + + +def _cache(): + inv_freq = 1.0 / ( + BASE + ** ( + torch.arange(0, ROTARY_DIM, 2, dtype=torch.float, device="cuda") + / ROTARY_DIM + ) + ) + t = torch.arange(MAXPOS, dtype=torch.float, device="cuda") + freqs = torch.outer(t, inv_freq) + return torch.cat([freqs.cos(), freqs.sin()], dim=-1).contiguous() + + +def _unfused(qkv, wq, wk, cache, positions): + # GemmaRMSNorm (1+w) on q,k head-wise + partial neox rope, in plain torch + # (representative of the separate norm + rope launches). + T = qkv.shape[0] + q, k, v = qkv.split([NQ * HEAD_DIM, NK * HEAD_DIM, NK * HEAD_DIM], dim=-1) + + def norm(x, w, nh): + x = x.reshape(T, nh, HEAD_DIM).float() + var = x.pow(2).mean(-1, keepdim=True) + return (x * torch.rsqrt(var + EPS) * (1.0 + w.float())).to(torch.bfloat16) + + qn, kn = norm(q, wq, NQ), norm(k, wk, NK) + cs = cache.index_select(0, positions).float() + cos, sin = cs[:, None, :32], cs[:, None, 32:] + + def rope(x): + x1, x2 = x[..., :32].float(), x[..., 32:64].float() + o1 = x1 * cos - x2 * sin + o2 = x2 * cos + x1 * sin + return torch.cat([o1, o2, x[..., 64:].float()], dim=-1).to(torch.bfloat16) + + return rope(qn), rope(kn) + + +def _fused(qkv, wq, wk, cache, positions): + minimax_qknorm_rope(qkv, wq, wk, cache, positions, NQ, NK, NK, EPS) + return qkv + + +FN_MAP = {"fused": _fused, "unfused_torch": _unfused} + + +@marker.parametrize("T", [1, 16, 64, 256, 1024, 8192], [64, 1024]) +@marker.benchmark("impl", ["fused", "unfused_torch"]) +def benchmark(T: int, impl: str): + cache = _cache() + wq = (torch.randn(HEAD_DIM, device="cuda") * 0.1).to(torch.bfloat16) + wk = (torch.randn(HEAD_DIM, device="cuda") * 0.1).to(torch.bfloat16) + qkv = torch.randn(T, (NQ + 2 * NK) * HEAD_DIM, dtype=torch.bfloat16, device="cuda") + positions = torch.randint(0, MAXPOS, (T,), device="cuda", dtype=torch.int64) + return marker.do_bench( + FN_MAP[impl], + input_args=(qkv, wq, wk, cache, positions), + graph_clone_args=(0,), + memory_args=None, + ) + + +# --- Combined main + index single launch (the fused qkv+index_qkv GEMM path) --- +# Per-rank TP8 sparse shape: main q=8/k=1/v=1 + index idx_q=1/idx_k=1 (value +# disabled). One grouped launch (q, k, idx_q, idx_k) vs two separate launches. +C_NQ, C_NKV, C_NIQ = 8, 1, 1 +C_OFF_Q = 0 +C_OFF_K = C_NQ +C_OFF_V = C_NQ + C_NKV +C_OFF_IQ = C_NQ + 2 * C_NKV +C_OFF_IK = C_OFF_IQ + C_NIQ +C_TOTAL_HEADS = C_OFF_IK + 1 + + +def _combined_one(args): + qkv, wq, wk, wiq, wik, cache, positions = args + minimax_qknorm_rope_grouped( + qkv, + [ + (wq, C_OFF_Q, C_NQ), + (wk, C_OFF_K, C_NKV), + (wiq, C_OFF_IQ, C_NIQ), + (wik, C_OFF_IK, 1), + ], + cache, + positions, + EPS, + ) + return qkv + + +def _combined_two(args): + # Two launches over the same buffer: main (q,k) then index (idx_q, idx_k). + qkv, wq, wk, wiq, wik, cache, positions = args + minimax_qknorm_rope_grouped( + qkv, [(wq, C_OFF_Q, C_NQ), (wk, C_OFF_K, C_NKV)], cache, positions, EPS + ) + minimax_qknorm_rope_grouped( + qkv, [(wiq, C_OFF_IQ, C_NIQ), (wik, C_OFF_IK, 1)], cache, positions, EPS + ) + return qkv + + +C_FN_MAP = {"combined_one_launch": _combined_one, "two_launches": _combined_two} + + +@marker.parametrize("T", [1, 16, 64, 256, 1024, 8192], [64, 1024]) +@marker.benchmark("impl", ["combined_one_launch", "two_launches"]) +def benchmark_combined(T: int, impl: str): + cache = _cache() + ws = [ + (torch.randn(HEAD_DIM, device="cuda") * 0.1).to(torch.bfloat16) + for _ in range(4) + ] + qkv = torch.randn(T, C_TOTAL_HEADS * HEAD_DIM, dtype=torch.bfloat16, device="cuda") + positions = torch.randint(0, MAXPOS, (T,), device="cuda", dtype=torch.int64) + return marker.do_bench( + C_FN_MAP[impl], + input_args=((qkv, *ws, cache, positions),), + graph_clone_args=(0,), + memory_args=None, + ) + + +if __name__ == "__main__": + benchmark.run() + benchmark_combined.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/benchmark/minimax/bench_minimax_store_kv_index.py b/asian_ai/performance/SGLang/test/registered/jit/benchmark/minimax/bench_minimax_store_kv_index.py new file mode 100644 index 0000000000000000000000000000000000000000..f63076f35bcc2ba73f78a14d52e99dc33b5eba60 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/benchmark/minimax/bench_minimax_store_kv_index.py @@ -0,0 +1,69 @@ +"""Benchmark: fused MiniMax-M3 KV + index cache store (1 launch) vs the separate +per-buffer index_put_ stores (main K, main V, index K, optional index V).""" + +import torch + +from sglang.jit_kernel.benchmark import marker +from sglang.jit_kernel.minimax_store_kv_index import store_kv_index +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=6, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + +HEAD_DIM = 128 +NUM_KV_HEADS = 1 +HAS_V = False +N = 1 << 20 +DTYPE = torch.bfloat16 + + +def _separate(k, v, kc, vc, ik, ikc, loc, **_): + kc[loc] = k + vc[loc] = v + ikc[loc] = ik + + +def _fused(k, v, kc, vc, ik, ikc, loc, *, num_kv_heads, head_bytes): + store_kv_index( + k, + v, + kc, + vc, + ik, + ikc, + None, + None, + loc, + num_kv_heads=num_kv_heads, + head_bytes=head_bytes, + ) + + +FN_MAP = {"fused": _fused, "separate": _separate} + + +@marker.parametrize("T", [16, 64, 256, 1024, 4096, 16384], [256, 4096]) +@marker.benchmark("impl", ["fused", "separate"]) +def benchmark(T: int, impl: str): + k = torch.randn(T, NUM_KV_HEADS * HEAD_DIM, dtype=DTYPE, device="cuda") + v = torch.randn_like(k) + ik = torch.randn(T, HEAD_DIM, dtype=DTYPE, device="cuda") + kc = torch.zeros(N, NUM_KV_HEADS * HEAD_DIM, dtype=DTYPE, device="cuda") + vc = torch.zeros_like(kc) + ikc = torch.zeros(N, HEAD_DIM, dtype=DTYPE, device="cuda") + loc = torch.randperm(N, device="cuda")[:T] + extra_kwargs = dict(num_kv_heads=NUM_KV_HEADS, head_bytes=HEAD_DIM * DTYPE.itemsize) + return marker.do_bench( + FN_MAP[impl], + input_args=(k, v, kc, vc, ik, ikc, loc), + input_kwargs=extra_kwargs if impl == "fused" else {}, + # Read inputs cloned per iter; caches are write targets (kept hot). + graph_clone_args=(0, 1, 4, 6), + memory_args=(k, v, ik, loc), + memory_output=(k, v, ik), + ) + + +if __name__ == "__main__": + benchmark.run() diff --git a/asian_ai/performance/SGLang/test/registered/jit/deepseek_v4/test_c128_v2.py b/asian_ai/performance/SGLang/test/registered/jit/deepseek_v4/test_c128_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..cbfb4e8c2235cdfbd970ce4b4357700ed503aaed --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/deepseek_v4/test_c128_v2.py @@ -0,0 +1,261 @@ +from __future__ import annotations + +import sys +from typing import Tuple, Union + +import pytest +import torch +import triton + +from sglang.jit_kernel.dsv4 import compress_forward +from sglang.jit_kernel.tests.deepseek_v4.common import ( + LegacyContext, + PagedContext, + make_legacy_context, + make_paged_context, + make_state_pool, + to_seq_extend, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=30, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=30, suite="nightly-amd-kernel-1-gpu", nightly=True) + +Context = Union[LegacyContext, PagedContext] + +# c128 input row layout: | kv | score | each [head_dim] +HEAD_DIM = 512 +RATIO = 128 +ATOL = 5e-3 +RTOL = 5e-3 + + +def _gt_compress( + kv_score_input_cpu: torch.Tensor, # [num_q, head_dim*2] + ape_cpu: torch.Tensor, # [128, head_dim] + P: int, + head_dim: int, +) -> torch.Tensor: + """fp64 reference for compress event at ragged position ``P`` (P % 128 == 127).""" + lo = P - (RATIO - 1) + kv = kv_score_input_cpu[lo : P + 1, :head_dim].double() + sc = kv_score_input_cpu[lo : P + 1, head_dim:].double() + return ((kv * (sc + ape_cpu.double()).softmax(dim=0)).sum(dim=0)).float() + + +def _make_inputs( + num_q: int, head_dim: int, seed: int +) -> Tuple[torch.Tensor, torch.Tensor]: + g = torch.Generator(device="cpu").manual_seed(seed) + kv_score_input_cpu = torch.randn( + num_q, head_dim * 2, generator=g, dtype=torch.float32 + ) + ape_cpu = torch.randn(RATIO, head_dim, generator=g, dtype=torch.float32) + return kv_score_input_cpu, ape_cpu + + +def _run_prefill( + ctx: Context, + pool: torch.Tensor, + kv_score_input: torch.Tensor, + ape: torch.Tensor, + seq_lens_cpu: torch.Tensor, + extend_lens_cpu: torch.Tensor, +) -> torch.Tensor: + num_q = int(extend_lens_cpu.sum().item()) + plan = ctx.make_prefill_plan(seq_lens_cpu, extend_lens_cpu, num_q) + return compress_forward( + pool, + kv_score_input, + ape, + plan, + head_dim=ctx.head_dim, + compress_ratio=RATIO, + ) + + +def _run_decode( + ctx: Context, + pool: torch.Tensor, + kv_score_input: torch.Tensor, + ape: torch.Tensor, + seq_lens_gpu: torch.Tensor, +) -> torch.Tensor: + plan = ctx.make_decode_plan(seq_lens_gpu) + return compress_forward( + pool, + kv_score_input, + ape, + plan, + head_dim=ctx.head_dim, + compress_ratio=RATIO, + ) + + +# ----------------------------------------------------------------------------- +# Tests +# ----------------------------------------------------------------------------- + + +@pytest.mark.parametrize("mode", ["legacy", "paged"]) +@pytest.mark.parametrize("seq_len", [128, 256, 512]) +def test_prefill_no_context(mode: str, seq_len: int) -> None: + """Single-shot prefill, no prefix. Every compress event must match fp64 GT.""" + if mode == "legacy": + ctx: Context = make_legacy_context( + bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM + ) + else: + ctx = make_paged_context(bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM) + + seq_lens_cpu, extend_lens_cpu, num_q = to_seq_extend([(seq_len, seq_len)]) + kv_in_cpu, ape_cpu = _make_inputs(num_q, ctx.head_dim, seed=seq_len) + + pool = make_state_pool(ctx.num_pages, RATIO, ctx.head_dim) + out = _run_prefill( + ctx, pool, kv_in_cpu.cuda(), ape_cpu.cuda(), seq_lens_cpu, extend_lens_cpu + ) + + # Compact prefill output: row per compress plan, in CPU-planner order. + for plan_id, P in enumerate(range(RATIO - 1, seq_len, RATIO)): + gt = _gt_compress(kv_in_cpu, ape_cpu, P=P, head_dim=ctx.head_dim) + triton.testing.assert_close(out[plan_id].cpu(), gt, atol=ATOL, rtol=RTOL) + + +@pytest.mark.parametrize("mode", ["legacy", "paged"]) +@pytest.mark.parametrize("prefix_len", [0, 128, 256]) +def test_prefill_then_decode(mode: str, prefix_len: int) -> None: + """Prefill ``prefix_len`` tokens, then decode through to the next 128 boundary.""" + seq_len = prefix_len + RATIO # one full compress chunk after prefix + + if mode == "legacy": + ctx: Context = make_legacy_context( + bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM + ) + else: + ctx = make_paged_context(bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM) + + kv_full_cpu, ape_cpu = _make_inputs( + seq_len, ctx.head_dim, seed=seq_len + prefix_len + ) + pool = make_state_pool(ctx.num_pages, RATIO, ctx.head_dim) + + if prefix_len > 0: + seq_lens_cpu, extend_lens_cpu, _ = to_seq_extend([(prefix_len, prefix_len)]) + _run_prefill( + ctx, + pool, + kv_full_cpu[:prefix_len].cuda(), + ape_cpu.cuda(), + seq_lens_cpu, + extend_lens_cpu, + ) + + final_out = None + for k in range(RATIO): + cur_seq_len = prefix_len + k + 1 + seq_lens_gpu = torch.tensor([cur_seq_len], dtype=torch.int64, device="cuda") + kv_step = kv_full_cpu[prefix_len + k : prefix_len + k + 1].cuda() + out = _run_decode(ctx, pool, kv_step, ape_cpu.cuda(), seq_lens_gpu) + if cur_seq_len % RATIO == 0: + final_out = out + + P = seq_len - 1 + gt = _gt_compress(kv_full_cpu, ape_cpu, P=P, head_dim=ctx.head_dim) + assert final_out is not None + triton.testing.assert_close(final_out[0].cpu(), gt, atol=ATOL, rtol=RTOL) + + +@pytest.mark.parametrize("mode", ["legacy", "paged"]) +@pytest.mark.parametrize("prefix_len", [128, 256]) +def test_prefill_then_extend(mode: str, prefix_len: int) -> None: + """Prefill once, then a second prefill that extends across one compress event. + + First prefill ends at a 128-boundary so the second prefill starts fresh. + """ + extend_len = RATIO + seq_len = prefix_len + extend_len + + if mode == "legacy": + ctx: Context = make_legacy_context( + bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM + ) + else: + ctx = make_paged_context(bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM) + + kv_full_cpu, ape_cpu = _make_inputs(seq_len, ctx.head_dim, seed=prefix_len) + pool = make_state_pool(ctx.num_pages, RATIO, ctx.head_dim) + + seq_lens_cpu, extend_lens_cpu, _ = to_seq_extend([(prefix_len, prefix_len)]) + _run_prefill( + ctx, + pool, + kv_full_cpu[:prefix_len].cuda(), + ape_cpu.cuda(), + seq_lens_cpu, + extend_lens_cpu, + ) + + seq_lens_cpu, extend_lens_cpu, _ = to_seq_extend([(seq_len, extend_len)]) + out = _run_prefill( + ctx, + pool, + kv_full_cpu[prefix_len:].cuda(), + ape_cpu.cuda(), + seq_lens_cpu, + extend_lens_cpu, + ) + + P = seq_len - 1 + gt = _gt_compress(kv_full_cpu, ape_cpu, P=P, head_dim=ctx.head_dim) + # Single compress event in this extend; compact plan_id 0. + triton.testing.assert_close(out[0].cpu(), gt, atol=ATOL, rtol=RTOL) + + +@pytest.mark.parametrize("mode", ["legacy", "paged"]) +def test_prefill_multibatch(mode: str) -> None: + """Multi-batch prefill, each batch ending at a different chunk count.""" + seq_extend = [(128, 128), (256, 256), (384, 384)] + bs = len(seq_extend) + if mode == "legacy": + ctx: Context = make_legacy_context( + bs=bs, compress_ratio=RATIO, head_dim=HEAD_DIM + ) + else: + ctx = make_paged_context(bs=bs, compress_ratio=RATIO, head_dim=HEAD_DIM) + + seq_lens_cpu, extend_lens_cpu, num_q = to_seq_extend(seq_extend) + kv_in_cpu, ape_cpu = _make_inputs(num_q, ctx.head_dim, seed=99) + pool = make_state_pool(ctx.num_pages, RATIO, ctx.head_dim) + out = _run_prefill( + ctx, pool, kv_in_cpu.cuda(), ape_cpu.cuda(), seq_lens_cpu, extend_lens_cpu + ) + + # Compact: walk batches in order, then positions in order; matches the + # CPU planner's emit order for plan_c. + base = 0 + plan_id = 0 + for b, (seq, ext) in enumerate(seq_extend): + for j in range(ext): + P = j # prefix=0 + if (P + 1) % RATIO != 0: + continue + gt = _gt_compress( + kv_in_cpu[base : base + ext], + ape_cpu, + P=P, + head_dim=ctx.head_dim, + ) + triton.testing.assert_close( + out[plan_id].cpu(), + gt, + atol=ATOL, + rtol=RTOL, + ) + plan_id += 1 + base += ext + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/deepseek_v4/test_c4_v2.py b/asian_ai/performance/SGLang/test/registered/jit/deepseek_v4/test_c4_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..327fb50cf87d8cbab8b224de2fcc613aa110433c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/deepseek_v4/test_c4_v2.py @@ -0,0 +1,338 @@ +from __future__ import annotations + +import sys +from typing import Tuple, Union + +import pytest +import torch +import triton + +from sglang.jit_kernel.dsv4 import compress_forward +from sglang.jit_kernel.tests.deepseek_v4.common import ( + LegacyContext, + PagedContext, + make_legacy_context, + make_paged_context, + make_state_pool, + to_seq_extend, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=30, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=30, suite="nightly-amd-kernel-1-gpu", nightly=True) + +Context = Union[LegacyContext, PagedContext] + +# c4 input row layout: | kv_overlap | kv | score_overlap | score | +HEAD_DIM = 512 +RATIO = 4 +WINDOW = 8 # = 2 * RATIO (overlap + current) +ATOL = 5e-3 +RTOL = 5e-3 + + +# ----------------------------------------------------------------------------- +# fp64 ground truth (single compress event over a 8-token window). +# ----------------------------------------------------------------------------- + + +def _gt_compress( + kv_score_input_cpu: torch.Tensor, # [num_q, head_dim*4] + ape_cpu: torch.Tensor, # [8, head_dim] + P: int, + head_dim: int, +) -> torch.Tensor: + """fp64 reference for compress event at ragged position ``P``. + + Tokens at positions [P-7..P-4] contribute their *overlap* halves, tokens + at [P-3..P] contribute their *fresh* halves. Bias[0..3] for overlap, + bias[4..7] for fresh. When P < 7, the overlap is masked (kv=0, score=-inf) + so the softmax sees only the 4 fresh tokens. + """ + if P < 7: + kv_ov = torch.zeros(4, head_dim, dtype=torch.float64) + sc_ov = torch.full((4, head_dim), float("-inf"), dtype=torch.float64) + else: + kv_ov = kv_score_input_cpu[P - 7 : P - 3, :head_dim].double() + sc_ov = kv_score_input_cpu[P - 7 : P - 3, 2 * head_dim : 3 * head_dim].double() + kv_fr = kv_score_input_cpu[P - 3 : P + 1, head_dim : 2 * head_dim].double() + sc_fr = kv_score_input_cpu[P - 3 : P + 1, 3 * head_dim :].double() + kv = torch.cat([kv_ov, kv_fr], dim=0) + sc = torch.cat([sc_ov, sc_fr], dim=0) + ape_cpu.double() + return ((kv * sc.softmax(dim=0)).sum(dim=0)).float() + + +# ----------------------------------------------------------------------------- +# Driver +# ----------------------------------------------------------------------------- + + +def _run_prefill( + ctx: Context, + pool: torch.Tensor, + kv_score_input: torch.Tensor, + ape: torch.Tensor, + seq_lens_cpu: torch.Tensor, + extend_lens_cpu: torch.Tensor, +) -> torch.Tensor: + num_q = int(extend_lens_cpu.sum().item()) + plan = ctx.make_prefill_plan(seq_lens_cpu, extend_lens_cpu, num_q) + return compress_forward( + pool, + kv_score_input, + ape, + plan, + head_dim=ctx.head_dim, + compress_ratio=RATIO, + ) + + +def _run_decode( + ctx: Context, + pool: torch.Tensor, + kv_score_input: torch.Tensor, + ape: torch.Tensor, + seq_lens_gpu: torch.Tensor, +) -> torch.Tensor: + plan = ctx.make_decode_plan(seq_lens_gpu) + return compress_forward( + pool, + kv_score_input, + ape, + plan, + head_dim=ctx.head_dim, + compress_ratio=RATIO, + ) + + +def _make_inputs( + num_q: int, head_dim: int, seed: int +) -> Tuple[torch.Tensor, torch.Tensor]: + g = torch.Generator(device="cpu").manual_seed(seed) + kv_score_input_cpu = torch.randn( + num_q, head_dim * 4, generator=g, dtype=torch.float32 + ) + ape_cpu = torch.randn(WINDOW, head_dim, generator=g, dtype=torch.float32) + return kv_score_input_cpu, ape_cpu + + +# ----------------------------------------------------------------------------- +# Tests +# ----------------------------------------------------------------------------- + + +@pytest.mark.parametrize("mode", ["legacy", "paged"]) +@pytest.mark.parametrize("seq_len", [4, 8, 32, 256, 1024]) +def test_prefill_no_context(mode: str, seq_len: int) -> None: + """Prefill once, no prefix. Every compress event must match fp64 GT.""" + if mode == "legacy": + ctx: Context = make_legacy_context( + bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM + ) + else: + ctx = make_paged_context(bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM) + + seq_lens_cpu, extend_lens_cpu, num_q = to_seq_extend([(seq_len, seq_len)]) + kv_in_cpu, ape_cpu = _make_inputs(num_q, ctx.head_dim, seed=seq_len) + + pool = make_state_pool(ctx.num_pages, RATIO, ctx.head_dim) + out = _run_prefill( + ctx, pool, kv_in_cpu.cuda(), ape_cpu.cuda(), seq_lens_cpu, extend_lens_cpu + ) + + # Compact prefill output: row per compress plan, in CPU-planner order + # (batch-major, position-ascending). + for plan_id, P in enumerate(range(RATIO - 1, seq_len, RATIO)): + gt = _gt_compress(kv_in_cpu, ape_cpu, P=P, head_dim=ctx.head_dim) + triton.testing.assert_close(out[plan_id].cpu(), gt, atol=ATOL, rtol=RTOL) + + +@pytest.mark.parametrize("mode", ["legacy", "paged"]) +@pytest.mark.parametrize("prefix_len", [4, 256]) +def test_prefill_then_decode(mode: str, prefix_len: int) -> None: + """Prefill once, then decode 4 more tokens through one compress boundary.""" + extend_decode = 4 + seq_len = prefix_len + extend_decode + + if mode == "legacy": + ctx: Context = make_legacy_context( + bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM + ) + else: + ctx = make_paged_context(bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM) + + kv_full_cpu, ape_cpu = _make_inputs( + seq_len, ctx.head_dim, seed=seq_len + prefix_len + ) + pool = make_state_pool(ctx.num_pages, RATIO, ctx.head_dim) + + # Prefill the prefix. + seq_lens_cpu, extend_lens_cpu, _ = to_seq_extend([(prefix_len, prefix_len)]) + _run_prefill( + ctx, + pool, + kv_full_cpu[:prefix_len].cuda(), + ape_cpu.cuda(), + seq_lens_cpu, + extend_lens_cpu, + ) + + # Decode `extend_decode` tokens one at a time. + final_out = None + for k in range(extend_decode): + cur_seq_len = prefix_len + k + 1 + seq_lens_gpu = torch.tensor([cur_seq_len], dtype=torch.int64, device="cuda") + kv_step = kv_full_cpu[prefix_len + k : prefix_len + k + 1].cuda() + out = _run_decode(ctx, pool, kv_step, ape_cpu.cuda(), seq_lens_gpu) + if cur_seq_len % RATIO == 0: + final_out = out + + # Check the trailing compress: position P = seq_len - 1 = prefix + 3. + P = seq_len - 1 + gt = _gt_compress(kv_full_cpu, ape_cpu, P=P, head_dim=ctx.head_dim) + assert final_out is not None + triton.testing.assert_close(final_out[0].cpu(), gt, atol=ATOL, rtol=RTOL) + + +@pytest.mark.parametrize("mode", ["legacy", "paged"]) +@pytest.mark.parametrize("prefix_len", [256, 512, 768]) +def test_prefill_then_extend(mode: str, prefix_len: int) -> None: + """Prefill once, then prefill an extend that crosses one compress event. + + The first prefill ends at a swa_page boundary (only relevant for paged), + so the second prefill's overlap must be read out of the buffer. + """ + extend_len = 4 + + if mode == "legacy": + ctx: Context = make_legacy_context( + bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM + ) + else: + ctx = make_paged_context(bs=1, compress_ratio=RATIO, head_dim=HEAD_DIM) + + seq_len = prefix_len + extend_len + kv_full_cpu, ape_cpu = _make_inputs(seq_len, ctx.head_dim, seed=prefix_len) + pool = make_state_pool(ctx.num_pages, RATIO, ctx.head_dim) + + # First prefill: seq=prefix, ext=prefix. + seq_lens_cpu, extend_lens_cpu, _ = to_seq_extend([(prefix_len, prefix_len)]) + _run_prefill( + ctx, + pool, + kv_full_cpu[:prefix_len].cuda(), + ape_cpu.cuda(), + seq_lens_cpu, + extend_lens_cpu, + ) + + # Second prefill: seq=prefix+extend, ext=extend, prefix=prefix_len. + seq_lens_cpu, extend_lens_cpu, num_q = to_seq_extend([(seq_len, extend_len)]) + out = _run_prefill( + ctx, + pool, + kv_full_cpu[prefix_len:].cuda(), + ape_cpu.cuda(), + seq_lens_cpu, + extend_lens_cpu, + ) + + P = seq_len - 1 + gt = _gt_compress(kv_full_cpu, ape_cpu, P=P, head_dim=ctx.head_dim) + # Single compress event in this extend; compact plan_id 0. + triton.testing.assert_close(out[0].cpu(), gt, atol=ATOL, rtol=RTOL) + + +def test_paged_buffer_intermediate() -> None: + """Paged-only: after a multi-page prefill, verify the trailing 4 tokens of + every swa_page sit in the correct state-pool slots. + + These slots are what radix-cache resume reads when prefix-matching from a + swa_page boundary, so they MUST match the original token data. + """ + ctx = make_paged_context( + bs=1, + compress_ratio=RATIO, + head_dim=HEAD_DIM, + swa_page_size=256, + ring_size=8, + num_swa_pages_per_req=8, + ) + seq_len = 1024 # 4 swa_pages + seq_lens_cpu, extend_lens_cpu, num_q = to_seq_extend([(seq_len, seq_len)]) + kv_in_cpu, ape_cpu = _make_inputs(num_q, ctx.head_dim, seed=42) + + pool = make_state_pool(ctx.num_pages, RATIO, ctx.head_dim) + _run_prefill( + ctx, pool, kv_in_cpu.cuda(), ape_cpu.cuda(), seq_lens_cpu, extend_lens_cpu + ) + + pool_cpu = pool.cpu() + # For each swa_page boundary, the trailing `RATIO` tokens must have been + # written. The state slot for token at position p is + # `state_loc(0, p) = (p // swa_page_size) * ring_size + p % ring_size`. + for swa_page_end in range(ctx.swa_page_size, seq_len + 1, ctx.swa_page_size): + for offset in range(RATIO): + p = swa_page_end - RATIO + offset + sl = ctx.state_loc(0, p) + page_idx = sl // RATIO + slot_idx = sl % RATIO + actual = pool_cpu[page_idx, slot_idx] + # Token-row layout: the c4 prefill write copies the full + # head_dim*4 row from kv_input verbatim into the state pool. + expected = kv_in_cpu[p] + triton.testing.assert_close( + actual, + expected, + atol=ATOL, + rtol=RTOL, + ) + + +@pytest.mark.parametrize("mode", ["legacy", "paged"]) +def test_prefill_multibatch(mode: str) -> None: + """Multi-batch prefill, both modes.""" + seq_extend = [(8, 8), (256, 256), (260, 260), (1023, 1023)] + bs = len(seq_extend) + if mode == "legacy": + ctx: Context = make_legacy_context( + bs=bs, compress_ratio=RATIO, head_dim=HEAD_DIM + ) + else: + ctx = make_paged_context(bs=bs, compress_ratio=RATIO, head_dim=HEAD_DIM) + + seq_lens_cpu, extend_lens_cpu, num_q = to_seq_extend(seq_extend) + kv_in_cpu, ape_cpu = _make_inputs(num_q, ctx.head_dim, seed=99) + pool = make_state_pool(ctx.num_pages, RATIO, ctx.head_dim) + out = _run_prefill( + ctx, pool, kv_in_cpu.cuda(), ape_cpu.cuda(), seq_lens_cpu, extend_lens_cpu + ) + + # Compact: walk batches in order, then positions in order; matches the + # CPU planner's emit order for plan_c. + base = 0 + plan_id = 0 + for b, (seq, ext) in enumerate(seq_extend): + for j in range(ext): + P = j # prefix=0 here + if (P + 1) % RATIO != 0: + continue + gt = _gt_compress( + kv_in_cpu[base : base + ext], + ape_cpu, + P=P, + head_dim=ctx.head_dim, + ) + triton.testing.assert_close( + out[plan_id].cpu(), + gt, + atol=ATOL, + rtol=RTOL, + ) + plan_id += 1 + base += ext + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/deepseek_v4/test_fp4_indexer.py b/asian_ai/performance/SGLang/test/registered/jit/deepseek_v4/test_fp4_indexer.py new file mode 100644 index 0000000000000000000000000000000000000000..a6851760dfde3bb630283cdb06ab7b8313dcecff --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/deepseek_v4/test_fp4_indexer.py @@ -0,0 +1,228 @@ +from __future__ import annotations + +import sys + +import pytest +import torch + +from sglang.jit_kernel.dsv4 import ( + CompressorDecodePlan, + compress_norm_rope_store, + fused_q_indexer_rope_hadamard_fp4_quant, +) +from sglang.jit_kernel.hadamard import hadamard_transform +from sglang.srt.layers.attention.dsv4.fp4_indexer import ( + quantize_fp4_indexer_tensor, + store_fp4_index_k_cache, +) +from sglang.srt.layers.deepseek_v4_rope import ( + apply_rotary_emb_triton, + precompute_freqs_cis, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=60, suite="nightly-kernel-1-gpu", nightly=True) + +HEAD_DIM = 128 +FP4_DIM = HEAD_DIM // 2 +GROUP_SIZE = 32 +SCALE_GROUPS = HEAD_DIM // GROUP_SIZE +SCALE_BYTES = 4 +PAGE_SIZE = 64 +E2M1_MAX = 6.0 + + +def _ceil_ue8m0_exp_ref(x: torch.Tensor) -> torch.Tensor: + bits = x.to(torch.float32).contiguous().view(torch.int32) + exp = (bits >> 23) & 0xFF + mantissa = bits & 0x7FFFFF + exp = exp + (mantissa != 0).to(torch.int32) + return exp.clamp(1, 254) + + +def _fp4_e2m1_code_ref(x: torch.Tensor) -> torch.Tensor: + ax = torch.minimum(x.abs(), torch.tensor(E2M1_MAX, device=x.device)) + idx = torch.zeros_like(ax, dtype=torch.uint8) + for threshold in (0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0): + idx += (ax > threshold).to(torch.uint8) + sign = ((x < 0) & (idx != 0)).to(torch.uint8) * 8 + return idx | sign + + +def _ref_quantize_fp4_indexer(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + x = x.contiguous().view(-1, HEAD_DIM).float() + groups = x.view(-1, SCALE_GROUPS, GROUP_SIZE) + scale_raw = (groups.abs().amax(dim=-1) / E2M1_MAX).clamp_min(1.0e-4) + scale_exp = _ceil_ue8m0_exp_ref(scale_raw) + scale = (scale_exp << 23).contiguous().view(torch.float32) + + scaled = (groups / scale.unsqueeze(-1)).view(-1, HEAD_DIM) + code = _fp4_e2m1_code_ref(scaled) + packed = (code[:, 0::2].to(torch.int16) | (code[:, 1::2].to(torch.int16) << 4)).to( + torch.uint8 + ) + + packed_sf = scale_exp[:, 0].clone() + for group_id in range(1, SCALE_GROUPS): + packed_sf |= scale_exp[:, group_id] << (8 * group_id) + return packed, packed_sf + + +def _ref_store_fp4_index_cache( + x_fp4: torch.Tensor, + x_sf: torch.Tensor, + loc: torch.Tensor, + num_pages: int, +) -> torch.Tensor: + expected = torch.zeros( + num_pages, + PAGE_SIZE * (FP4_DIM + SCALE_BYTES), + device=x_fp4.device, + dtype=torch.uint8, + ) + sf_shifts = torch.arange(0, 32, 8, device=x_fp4.device, dtype=torch.int32) + for token_id in range(x_fp4.shape[0]): + cache_loc = int(loc[token_id].item()) + page = cache_loc // PAGE_SIZE + offset = cache_loc % PAGE_SIZE + expected[page, offset * FP4_DIM : (offset + 1) * FP4_DIM] = x_fp4[token_id] + sf_start = PAGE_SIZE * FP4_DIM + offset * SCALE_BYTES + expected[page, sf_start : sf_start + SCALE_BYTES] = ( + (x_sf[token_id] >> sf_shifts) & 0xFF + ).to(torch.uint8) + return expected + + +@pytest.mark.parametrize("num_tokens", [1, 7, 96]) +def test_quantize_fp4_indexer_tensor(num_tokens: int) -> None: + torch.manual_seed(num_tokens) + x = torch.randn(num_tokens, HEAD_DIM, device="cuda", dtype=torch.bfloat16) + x[0, :8] = torch.tensor( + [-8.0, -6.0, -3.0, -1.5, 0.0, 0.5, 2.0, 8.0], + device="cuda", + dtype=torch.bfloat16, + ) + + x_fp4, x_sf = quantize_fp4_indexer_tensor(x) + ref_fp4, ref_sf = _ref_quantize_fp4_indexer(x) + + torch.testing.assert_close(x_fp4.view(torch.uint8), ref_fp4) + torch.testing.assert_close(x_sf, ref_sf) + + +@pytest.mark.parametrize("num_tokens", [1, 16, 96]) +def test_fp4_index_cache_store_layout(num_tokens: int) -> None: + torch.manual_seed(num_tokens) + num_pages = max(1, (num_tokens + PAGE_SIZE - 1) // PAGE_SIZE) + x = torch.randn(num_tokens, HEAD_DIM, device="cuda", dtype=torch.bfloat16) + loc = torch.randperm(num_pages * PAGE_SIZE, device="cuda")[:num_tokens].to( + torch.int64 + ) + cache = torch.zeros( + num_pages, + PAGE_SIZE * (FP4_DIM + SCALE_BYTES), + device="cuda", + dtype=torch.uint8, + ) + + store_fp4_index_k_cache(x, cache, loc, page_size=PAGE_SIZE) + + ref_fp4, ref_sf = _ref_quantize_fp4_indexer(x) + expected = _ref_store_fp4_index_cache(ref_fp4, ref_sf, loc, num_pages) + torch.testing.assert_close(cache, expected) + + +@pytest.mark.parametrize("num_tokens", [1, 16, 96]) +def test_fp4_fused_norm_rope_store_layout(num_tokens: int) -> None: + torch.manual_seed(num_tokens + 100) + num_pages = max(1, (num_tokens + PAGE_SIZE - 1) // PAGE_SIZE) + compress_ratio = 4 + kv = torch.randn(num_tokens, HEAD_DIM, device="cuda", dtype=torch.bfloat16) + norm_weight = torch.randn(HEAD_DIM, device="cuda", dtype=torch.bfloat16) + seq_lens = ( + torch.arange(1, num_tokens + 1, device="cuda", dtype=torch.int64) + * compress_ratio + ) + req_pool_indices = torch.arange(num_tokens, device="cuda", dtype=torch.int64) + plan = CompressorDecodePlan.generate_legacy( + compress_ratio, req_pool_indices, seq_lens + ) + loc = torch.arange(num_tokens, device="cuda", dtype=torch.int64) + freqs_cis = precompute_freqs_cis( + 64, int(seq_lens.max().item()) + 1, 0, 10000, 1, 32, 1 + ).to("cuda") + cache = torch.zeros( + num_pages, + PAGE_SIZE * (FP4_DIM + SCALE_BYTES), + device="cuda", + dtype=torch.uint8, + ) + + compress_norm_rope_store( + kv.clone(), + plan, + norm_weight=norm_weight, + norm_eps=1.0e-6, + freq_cis=freqs_cis, + out_loc=loc, + kvcache=cache, + page_size=PAGE_SIZE, + use_fp4=True, + ) + + ref = kv.float() + ref = ref * torch.rsqrt((ref * ref).sum(dim=-1, keepdim=True) / HEAD_DIM + 1.0e-6) + ref = ref * norm_weight.float() + freqs = torch.view_as_real(freqs_cis).flatten(-2)[ + (seq_lens - compress_ratio).long() + ] + rope = ref[:, 64:].reshape(num_tokens, 32, 2) + freqs = freqs.reshape(num_tokens, 32, 2) + rope_out = torch.empty_like(rope) + rope_out[..., 0] = rope[..., 0] * freqs[..., 0] - rope[..., 1] * freqs[..., 1] + rope_out[..., 1] = rope[..., 0] * freqs[..., 1] + rope[..., 1] * freqs[..., 0] + ref[:, 64:] = rope_out.reshape(num_tokens, 64) + ref = hadamard_transform(ref.contiguous(), scale=HEAD_DIM**-0.5) + ref_fp4, ref_sf = _ref_quantize_fp4_indexer(ref) + + expected = _ref_store_fp4_index_cache( + ref_fp4, + ref_sf, + loc.to(torch.int64), + num_pages, + ) + torch.testing.assert_close(cache, expected) + + +@pytest.mark.parametrize("batch_size", [1, 5, 17]) +def test_fp4_fused_q_indexer_rope_hadamard_quant(batch_size: int) -> None: + torch.manual_seed(batch_size + 200) + num_heads = 8 + rope_dim = 64 + weight_scale = HEAD_DIM**-0.5 * num_heads**-0.5 + q = torch.randn( + batch_size, num_heads, HEAD_DIM, device="cuda", dtype=torch.bfloat16 + ) + weight = torch.randn(batch_size, num_heads, device="cuda", dtype=torch.bfloat16) + positions = (torch.arange(batch_size, device="cuda", dtype=torch.int32) * 7) % 63 + freqs_cis = precompute_freqs_cis(rope_dim, 64, 0, 10000, 1, 32, 1).to("cuda") + + (q_fp4, q_sf), weights_out = fused_q_indexer_rope_hadamard_fp4_quant( + q, weight, weight_scale, freqs_cis, positions + ) + + ref = q.clone() + apply_rotary_emb_triton(ref[..., -rope_dim:], freqs_cis, positions=positions) + ref = hadamard_transform(ref.contiguous(), scale=HEAD_DIM**-0.5) + ref_fp4, ref_sf = _ref_quantize_fp4_indexer(ref.view(-1, HEAD_DIM)) + ref_fp4 = ref_fp4.view(batch_size, num_heads, FP4_DIM) + ref_sf = ref_sf.view(batch_size, num_heads) + + torch.testing.assert_close(q_fp4.view(torch.uint8), ref_fp4) + torch.testing.assert_close(q_sf, ref_sf) + torch.testing.assert_close(weights_out.squeeze(-1), weight.float() * weight_scale) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_causal_conv3d_cat_pad.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_causal_conv3d_cat_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..106de62cc3e60398e2f9ee2150b5b86d66957bb9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_causal_conv3d_cat_pad.py @@ -0,0 +1,89 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.diffusion.causal_conv3d_cat_pad import ( + fused_causal_conv3d_cat_pad_cuda, +) +from sglang.jit_kernel.diffusion.triton.causal_conv3d_pad import ( + fused_causal_conv3d_cat_pad as fused_causal_conv3d_cat_pad_triton, +) +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="4-gpu-b200") +register_amd_ci(est_time=10, stage="jit-kernel-unit", runner_config="amd") + +DEVICE = "cuda" +DTYPE = torch.bfloat16 + +COSMOS3_CASES = get_ci_test_range( + [ + (1024, 1, 30, 52, 1), + (1024, 1, 30, 52, 2), + (1024, 2, 60, 104, 1), + (1024, 2, 60, 104, 2), + (512, 4, 120, 208, 1), + (512, 4, 120, 208, 2), + (256, 4, 240, 416, 1), + (256, 4, 240, 416, 2), + ], + [(1024, 1, 30, 52, 1), (512, 4, 120, 208, 2)], +) + + +def _make_inputs( + channels: int, + t_size: int, + h_size: int, + w_size: int, + cache_t: int, +) -> tuple[torch.Tensor, torch.Tensor, tuple[int, ...]]: + generator = torch.Generator(device=DEVICE) + generator.manual_seed(channels * 1009 + t_size * 251 + h_size + cache_t) + x = torch.randn( + (1, channels, t_size, h_size, w_size), + device=DEVICE, + dtype=DTYPE, + generator=generator, + ) + cache_x = torch.randn( + (1, channels, cache_t, h_size, w_size), + device=DEVICE, + dtype=DTYPE, + generator=generator, + ) + padding = (1, 1, 1, 1, cache_t, 0) + return x, cache_x, padding + + +@pytest.mark.parametrize("channels,t_size,h_size,w_size,cache_t", COSMOS3_CASES) +def test_causal_conv3d_cat_pad( + channels: int, + t_size: int, + h_size: int, + w_size: int, + cache_t: int, +) -> None: + x, cache_x, padding = _make_inputs(channels, t_size, h_size, w_size, cache_t) + actual = fused_causal_conv3d_cat_pad_cuda(x, cache_x, padding) + expected = fused_causal_conv3d_cat_pad_triton(x, cache_x, padding) + torch.testing.assert_close(actual, expected, atol=0, rtol=0) + + +def test_causal_conv3d_cat_pad_torch_compile() -> None: + x, cache_x, padding = _make_inputs(1024, 1, 30, 52, 1) + + @torch.compile(fullgraph=True) + def fn(x: torch.Tensor, cache_x: torch.Tensor) -> torch.Tensor: + return fused_causal_conv3d_cat_pad_cuda(x, cache_x, padding) + + actual = fn(x, cache_x) + expected = fused_causal_conv3d_cat_pad_triton(x, cache_x, padding) + torch.testing.assert_close(actual, expected, atol=0, rtol=0) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_diffusion_modelopt_fp8_scaled_mm.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_diffusion_modelopt_fp8_scaled_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..173f530ee0c630d1ae59e95ded4b3ad4515f5913 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_diffusion_modelopt_fp8_scaled_mm.py @@ -0,0 +1,142 @@ +import sys + +import pytest +import torch + +from sglang.multimodal_gen.runtime.layers.quantization.modelopt_quant import ( + ModelOptFp8Config, + ModelOptFp8LinearMethod, +) +from sglang.srt.layers.quantization.fp8_kernel import static_quant_fp8 +from sglang.srt.layers.quantization.fp8_utils import ( + cutlass_fp8_supported, + input_to_float8, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=20, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=80, suite="nightly-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" +DTYPE = torch.bfloat16 +MAX_FP8_DIFF = 5e-4 +TEST_CASES = [ + pytest.param(19, 150, 80, id="misaligned_projection_shape"), + pytest.param(512, 3072, 4096, id="flux2_added_kv_projection_shape"), +] + + +def _modelopt_fp8_supported() -> bool: + return torch.cuda.is_available() and cutlass_fp8_supported() + + +def _calc_diff(x: torch.Tensor, y: torch.Tensor) -> float: + x, y = x.double(), y.double() + denominator = (x * x + y * y).sum() + if denominator == 0: + return 0.0 + sim = 2 * (x * y).sum() / denominator + return (1 - sim).item() + + +def _dequantize_fp8_input(qinput: torch.Tensor, x_scale: torch.Tensor) -> torch.Tensor: + return qinput.to(torch.float32) * x_scale.to(torch.float32) + + +def _dequantize_fp8_weight( + weight: torch.Tensor, weight_scale: torch.Tensor +) -> torch.Tensor: + if weight_scale.ndim == 0 or weight_scale.numel() == 1: + scale = weight_scale.to(torch.float32) + else: + scale = weight_scale.to(torch.float32).reshape(-1, 1).t() + return weight.to(torch.float32) * scale + + +def _build_layer( + weight_q: torch.Tensor, + weight_scale: torch.Tensor, + input_scale: torch.Tensor, +) -> tuple[torch.nn.Module, ModelOptFp8LinearMethod]: + output_size, input_size = weight_q.shape + method = ModelOptFp8LinearMethod( + ModelOptFp8Config(is_checkpoint_fp8_serialized=True) + ) + layer = torch.nn.Module() + method.create_weights( + layer=layer, + input_size_per_partition=input_size, + output_partition_sizes=[output_size], + input_size=input_size, + output_size=output_size, + params_dtype=DTYPE, + weight_loader=lambda *args, **kwargs: None, + ) + layer = layer.to(device=DEVICE) + + layer.weight.data.copy_(weight_q) + layer.weight_scale.data.copy_(weight_scale.reshape_as(layer.weight_scale)) + layer.input_scale.data.copy_(input_scale.reshape_as(layer.input_scale)) + method.process_weights_after_loading(layer) + return layer, method + + +@pytest.mark.skipif( + not _modelopt_fp8_supported(), + reason="Diffusion ModelOpt FP8 scaled mm correctness requires CUDA FP8 support", +) +@pytest.mark.parametrize("m,n,k", TEST_CASES) +def test_checkpoint_processing(m: int, n: int, k: int) -> None: + generator = torch.Generator(device=DEVICE) + generator.manual_seed(20260410 + m + n + k) + + weight = torch.randn((n, k), device=DEVICE, dtype=DTYPE, generator=generator) + weight_q, weight_scale = input_to_float8(weight) + input_scale = torch.tensor(1.0, device=DEVICE, dtype=torch.float32) + + layer, _ = _build_layer(weight_q, weight_scale, input_scale) + + assert tuple(layer.weight.shape) == (k, n) + assert tuple(layer.weight.stride()) == (1, k) + assert layer.weight.dtype == torch.float8_e4m3fn + assert layer.input_scale.ndim == 0 + assert tuple(layer.weight_scale.shape) == (n, 1) + + expected_weight = weight_q.t().to(torch.float32) * weight_scale.to(torch.float32) + actual_weight = _dequantize_fp8_weight(layer.weight, layer.weight_scale) + torch.testing.assert_close(actual_weight, expected_weight, atol=0.0, rtol=0.0) + + +@pytest.mark.skipif( + not _modelopt_fp8_supported(), + reason="Diffusion ModelOpt FP8 scaled mm correctness requires CUDA FP8 support", +) +@pytest.mark.parametrize("m,n,k", TEST_CASES) +def test_shape_correctness(m: int, n: int, k: int) -> None: + generator = torch.Generator(device=DEVICE) + generator.manual_seed(20260410 + m + n + k) + + x = torch.randn((m, k), device=DEVICE, dtype=DTYPE, generator=generator) + weight = torch.randn((n, k), device=DEVICE, dtype=DTYPE, generator=generator) + weight_q, weight_scale = input_to_float8(weight) + _, input_scale = input_to_float8(x) + + layer, method = _build_layer(weight_q, weight_scale, input_scale) + + qinput, x_scale = static_quant_fp8( + x.contiguous(), + layer.input_scale, + repeat_scale=method.cutlass_fp8_supported, + ) + expected = torch.matmul( + _dequantize_fp8_input(qinput, x_scale), + _dequantize_fp8_weight(layer.weight, layer.weight_scale), + ) + + actual = method.apply(layer, x) + diff = _calc_diff(actual, expected.to(dtype=DTYPE)) + assert diff < MAX_FP8_DIFF, f"{m=}, {n=}, {k=}, {diff=:.6f}" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_diffusion_nvfp4_scaled_mm.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_diffusion_nvfp4_scaled_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b9f728c2d8f700c7229fafc419b18684679785 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_diffusion_nvfp4_scaled_mm.py @@ -0,0 +1,460 @@ +import sys + +import flashinfer +import pytest +import torch + +from sglang.jit_kernel.nvfp4 import cutlass_scaled_fp4_mm, scaled_fp4_quant +from sglang.multimodal_gen.runtime.layers.quantization import ( + modelopt_quant as diffusion_modelopt_quant, +) +from sglang.multimodal_gen.runtime.layers.quantization.modelopt_quant import ( + ModelOptFp4Config, + ModelOptFp4LinearMethod, +) +from sglang.multimodal_gen.runtime.platforms import current_platform +from sglang.srt.layers.quantization.modelopt_quant import pad_nvfp4_weight +from sglang.test.ci.ci_register import register_cuda_ci + +# B200-only correctness coverage for diffusion NVFP4 scaled mm. +register_cuda_ci(est_time=15, stage="base-b-kernel-unit", runner_config="4-gpu-b200") + +DEVICE = "cuda" +DTYPE = torch.bfloat16 +BLOCK_SIZE = 16 +FLOAT4_E2M1_MAX = 6.0 +FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max +FP4_VALUE_LUT = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) +DEEPGEMM_FP4_MAX_DIFF = 0.02 +TEST_CASES = [ + pytest.param(19, 150, 80, id="padding_regression"), + pytest.param(512, 6144, 128, id="flux2_projection_shape"), +] +FLUX2_PROJECTION_SHAPE = (512, 6144, 128) + + +def _nvfp4_supported() -> bool: + return torch.cuda.is_available() and torch.cuda.get_device_capability() >= (10, 0) + + +def _make_global_scale(x: torch.Tensor) -> torch.Tensor: + max_abs = torch.amax(x.abs()).clamp_min_(1e-6) + return (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / max_abs).to(torch.float32) + + +def _calc_diff(x: torch.Tensor, y: torch.Tensor) -> float: + x, y = x.double(), y.double() + denominator = (x * x + y * y).sum() + if denominator == 0: + return 0.0 + sim = 2 * (x * y).sum() / denominator + return (1 - sim).item() + + +def _swap_fp4_nibbles(packed: torch.Tensor) -> torch.Tensor: + return ((packed >> 4) | (packed << 4)).contiguous() + + +def _fp4_lut(device: torch.device) -> torch.Tensor: + return torch.tensor(FP4_VALUE_LUT, dtype=torch.float32, device=device) + + +def _unpack_fp4_bytes(packed: torch.Tensor) -> torch.Tensor: + assert packed.dtype == torch.uint8 + lut = _fp4_lut(packed.device) + + def _decode(nibbles: torch.Tensor) -> torch.Tensor: + values = lut[(nibbles & 0x7).to(torch.long)] + return torch.where((nibbles & 0x8) != 0, -values, values) + + low = _decode(packed & 0x0F) + high = _decode((packed & 0xF0) >> 4) + return torch.stack((low, high), dim=-1).reshape( + packed.shape[0], packed.shape[1] * 2 + ) + + +def _swizzled_to_linear( + scales_swizzled: torch.Tensor, + rows: int, + cols: int, +) -> torch.Tensor: + scales_swizzled = scales_swizzled.view(torch.float8_e4m3fn) + row_tiles = (rows + 128 - 1) // 128 + tile_cols = BLOCK_SIZE * 4 + col_tiles = (cols + tile_cols - 1) // tile_cols + tmp = scales_swizzled.reshape(1, row_tiles, col_tiles, 32, 4, 4) + tmp = tmp.permute(0, 1, 4, 3, 2, 5) + linear = tmp.reshape(row_tiles * 128, col_tiles * tile_cols // BLOCK_SIZE) + return linear[:rows, : cols // BLOCK_SIZE] + + +def _dequantize_nvfp4( + packed: torch.Tensor, + scales_swizzled: torch.Tensor, + global_scale: torch.Tensor, +) -> torch.Tensor: + rows, packed_cols = packed.shape + cols = packed_cols * 2 + unpacked = _unpack_fp4_bytes(packed).reshape(rows, cols // BLOCK_SIZE, BLOCK_SIZE) + scales_linear = _swizzled_to_linear(scales_swizzled, rows, cols).to(torch.float32) + return (unpacked * (scales_linear / global_scale).unsqueeze(-1)).reshape(rows, cols) + + +def _quantize_weight_for_checkpoint( + weight: torch.Tensor, weight_global_scale: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor]: + weight_fp4, weight_scale_linear = flashinfer.fp4_quantize( + weight, + weight_global_scale, + is_sf_swizzled_layout=False, + ) + if weight_scale_linear.dtype == torch.uint8: + weight_scale_linear = weight_scale_linear.view(torch.float8_e4m3fn) + return weight_fp4, weight_scale_linear.contiguous() + + +def _set_diffusion_fp4_backend( + monkeypatch: pytest.MonkeyPatch, backend: str | None +) -> None: + if backend is None: + monkeypatch.delenv( + "SGLANG_DIFFUSION_FLASHINFER_FP4_GEMM_BACKEND", raising=False + ) + else: + monkeypatch.setenv("SGLANG_DIFFUSION_FLASHINFER_FP4_GEMM_BACKEND", backend) + + current_platform.__class__.get_modelopt_flashinfer_fp4_backend.cache_clear() + current_platform.__class__.get_modelopt_fp4_gemm_op.cache_clear() + diffusion_modelopt_quant._get_fp4_gemm_op.cache_clear() + + +def _build_layer( + weight_fp4: torch.Tensor, + weight_scale_linear: torch.Tensor, + input_global_scale: torch.Tensor, + weight_global_scale: torch.Tensor, + *, + weight_scale_device: torch.device | str | None = None, + checkpoint_weight_scale_layout: str = "linear", +) -> tuple[ModelOptFp4LinearMethod, torch.nn.Module]: + output_size, input_size_half = weight_fp4.shape + input_size = input_size_half * 2 + method = ModelOptFp4LinearMethod( + ModelOptFp4Config( + is_checkpoint_nvfp4_serialized=True, + group_size=BLOCK_SIZE, + swap_weight_nibbles=True, + checkpoint_weight_scale_layout=checkpoint_weight_scale_layout, + ) + ) + layer = torch.nn.Module() + method.create_weights( + layer, + input_size_per_partition=input_size, + output_partition_sizes=[output_size], + input_size=input_size, + output_size=output_size, + params_dtype=DTYPE, + weight_loader=lambda *args, **kwargs: None, + ) + layer = layer.to(device=DEVICE) + + checkpoint_weight = _swap_fp4_nibbles(weight_fp4) + layer.weight.data.copy_(checkpoint_weight) + layer.input_scale.data.copy_( + (1.0 / input_global_scale).reshape_as(layer.input_scale) + ) + layer.weight_scale_2.data.copy_( + (1.0 / weight_global_scale).reshape_as(layer.weight_scale_2) + ) + layer.weight_scale.data.copy_(weight_scale_linear) + if weight_scale_device is not None: + layer.weight_scale = torch.nn.Parameter( + layer.weight_scale.detach().to(weight_scale_device), requires_grad=False + ) + + method.process_weights_after_loading(layer) + + _, flashinfer_backend = current_platform.get_modelopt_fp4_gemm_op() + if flashinfer_backend == "trtllm": + expected_weight, _ = pad_nvfp4_weight( + weight_fp4, n_alignment=128, k_alignment=0 + ) + expected_scale = ( + _swizzled_to_linear(weight_scale_linear, output_size, input_size) + if checkpoint_weight_scale_layout == "swizzled" + else weight_scale_linear + ) + if expected_scale.shape[0] != expected_weight.shape[0]: + pad_n = expected_weight.shape[0] - expected_scale.shape[0] + expected_scale = torch.nn.functional.pad(expected_scale, (0, 0, 0, pad_n)) + + expected_padding_cols = 0 + if expected_scale.shape[1] % 4 != 0: + padded_scale_k = ((expected_scale.shape[1] + 4 - 1) // 4) * 4 + pad_scale_k = padded_scale_k - expected_scale.shape[1] + expected_scale = torch.nn.functional.pad( + expected_scale, (0, pad_scale_k, 0, 0) + ) + pad_weight_k = pad_scale_k * 8 + expected_weight = torch.nn.functional.pad( + expected_weight, (0, pad_weight_k, 0, 0) + ) + expected_padding_cols = pad_weight_k + + expected_weight = flashinfer.shuffle_matrix_a( + expected_weight.view(torch.uint8), 128 + ) + expected_scale = ( + flashinfer.shuffle_matrix_sf_a(expected_scale.view(torch.uint8), 128) + .reshape(expected_scale.shape) + .view(torch.float8_e4m3fn) + ) + + assert torch.equal(layer.weight, expected_weight) + assert torch.equal( + layer.weight_scale_interleaved.view(torch.uint8), + expected_scale.view(torch.uint8), + ) + assert layer.weights_padding_cols == expected_padding_cols + else: + expected_weight, expected_padding_cols = pad_nvfp4_weight(weight_fp4) + expected_scale_shape = ( + ((output_size + 128 - 1) // 128) * 128, + (((input_size // BLOCK_SIZE) + 4 - 1) // 4) * 4, + ) + + assert torch.equal(layer.weight, expected_weight) + assert layer.weight_scale_interleaved.shape == expected_scale_shape + assert layer.weight_scale_interleaved.dtype == torch.float8_e4m3fn + assert layer.weights_padding_cols == expected_padding_cols + torch.testing.assert_close( + layer.alpha, + (1.0 / (input_global_scale * weight_global_scale)).to(torch.float32), + ) + torch.testing.assert_close( + layer.input_scale_inv, + input_global_scale.to(torch.float32), + ) + return method, layer + + +def _resolve_mode(mode: str): + if mode == "jit_cutlass": + return scaled_fp4_quant, cutlass_scaled_fp4_mm, None + if mode == "flashinfer2": + return flashinfer.fp4_quantize, flashinfer.mm_fp4, "cudnn" + if mode == "flashinfer_trtllm": + return flashinfer.fp4_quantize, flashinfer.mm_fp4, "trtllm" + raise ValueError(f"Unknown mode: {mode}") + + +@pytest.mark.skipif( + not _nvfp4_supported(), + reason="Diffusion NVFP4 scaled mm correctness requires Blackwell GPUs", +) +@pytest.mark.parametrize( + "backend", [None, "flashinfer_trtllm"], ids=["default", "flashinfer_trtllm"] +) +@pytest.mark.parametrize("m,n,k", TEST_CASES) +def test_checkpoint_processing( + monkeypatch: pytest.MonkeyPatch, backend: str | None, m: int, n: int, k: int +) -> None: + _set_diffusion_fp4_backend(monkeypatch, backend) + generator = torch.Generator(device=DEVICE) + generator.manual_seed(20260404 + m + n + k) + + weight = torch.randn((n, k), device=DEVICE, dtype=DTYPE, generator=generator) + input_global_scale = torch.tensor(512.0, device=DEVICE, dtype=torch.float32) + weight_global_scale = _make_global_scale(weight) + weight_fp4, weight_scale_linear = _quantize_weight_for_checkpoint( + weight, weight_global_scale + ) + + _build_layer( + weight_fp4, weight_scale_linear, input_global_scale, weight_global_scale + ) + + +@pytest.mark.skipif( + not _nvfp4_supported(), + reason="Diffusion NVFP4 scaled mm correctness requires Blackwell GPUs", +) +@pytest.mark.parametrize("mode", ["jit_cutlass", "flashinfer2"]) +def test_flux2_shape_correctness(mode: str) -> None: + m, n, k = FLUX2_PROJECTION_SHAPE + quantize_op, gemm_op, gemm_backend = _resolve_mode(mode) + generator = torch.Generator(device=DEVICE) + generator.manual_seed(20260404 + m + n + k) + + x = torch.randn((m, k), device=DEVICE, dtype=DTYPE, generator=generator) + weight = torch.randn((n, k), device=DEVICE, dtype=DTYPE, generator=generator) + input_global_scale = _make_global_scale(x) + weight_global_scale = _make_global_scale(weight) + alpha = (1.0 / (input_global_scale * weight_global_scale)).to(torch.float32) + + x_fp4, x_scale_swizzled = quantize_op(x, input_global_scale) + weight_fp4, weight_scale_swizzled = quantize_op(weight, weight_global_scale) + if x_scale_swizzled.dtype == torch.uint8: + x_scale_swizzled = x_scale_swizzled.view(torch.float8_e4m3fn) + if weight_scale_swizzled.dtype == torch.uint8: + weight_scale_swizzled = weight_scale_swizzled.view(torch.float8_e4m3fn) + + expected = torch.matmul( + _dequantize_nvfp4(x_fp4, x_scale_swizzled, input_global_scale), + _dequantize_nvfp4(weight_fp4, weight_scale_swizzled, weight_global_scale).t(), + ) + + if gemm_backend is None: + actual = gemm_op( + x_fp4, + weight_fp4, + x_scale_swizzled, + weight_scale_swizzled, + alpha, + DTYPE, + ) + else: + actual = gemm_op( + x_fp4, + weight_fp4.t(), + x_scale_swizzled, + weight_scale_swizzled.t(), + alpha, + DTYPE, + backend=gemm_backend, + ) + + diff = _calc_diff(actual, expected.to(dtype=DTYPE)) + assert diff < DEEPGEMM_FP4_MAX_DIFF, f"{mode=}, {m=}, {n=}, {k=}, {diff=:.6f}" + + +@pytest.mark.skipif( + not _nvfp4_supported(), + reason="Diffusion NVFP4 scaled mm correctness requires Blackwell GPUs", +) +def test_flux2_shape_correctness_flashinfer_trtllm( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _set_diffusion_fp4_backend(monkeypatch, "flashinfer_trtllm") + + m, n, k = FLUX2_PROJECTION_SHAPE + generator = torch.Generator(device=DEVICE) + generator.manual_seed(20260404 + m + n + k + 17) + + x = torch.randn((m, k), device=DEVICE, dtype=DTYPE, generator=generator) + weight = torch.randn((n, k), device=DEVICE, dtype=DTYPE, generator=generator) + input_global_scale = _make_global_scale(x) + weight_global_scale = _make_global_scale(weight) + weight_fp4, weight_scale_linear = _quantize_weight_for_checkpoint( + weight, weight_global_scale + ) + + method, layer = _build_layer( + weight_fp4, weight_scale_linear, input_global_scale, weight_global_scale + ) + actual = method.apply(layer, x) + + x_fp4, x_scale_swizzled = flashinfer.fp4_quantize(x, input_global_scale) + weight_fp4_ref, weight_scale_swizzled = flashinfer.fp4_quantize( + weight, weight_global_scale + ) + if x_scale_swizzled.dtype == torch.uint8: + x_scale_swizzled = x_scale_swizzled.view(torch.float8_e4m3fn) + if weight_scale_swizzled.dtype == torch.uint8: + weight_scale_swizzled = weight_scale_swizzled.view(torch.float8_e4m3fn) + + expected = torch.matmul( + _dequantize_nvfp4(x_fp4, x_scale_swizzled, input_global_scale), + _dequantize_nvfp4( + weight_fp4_ref, weight_scale_swizzled, weight_global_scale + ).t(), + ) + + diff = _calc_diff(actual, expected.to(dtype=DTYPE)) + assert diff < DEEPGEMM_FP4_MAX_DIFF, f"{m=}, {n=}, {k=}, {diff=:.6f}" + + +@pytest.mark.skipif( + not _nvfp4_supported(), + reason="Diffusion NVFP4 scaled mm correctness requires Blackwell GPUs", +) +def test_flux2_swizzled_scale_checkpoint_flashinfer_trtllm_matches_cudnn( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _set_diffusion_fp4_backend(monkeypatch, "flashinfer_trtllm") + + m, n, k = FLUX2_PROJECTION_SHAPE + generator = torch.Generator(device=DEVICE) + generator.manual_seed(20260517 + m + n + k) + + x = torch.randn((m, k), device=DEVICE, dtype=DTYPE, generator=generator) + weight = torch.randn((n, k), device=DEVICE, dtype=DTYPE, generator=generator) + input_global_scale = _make_global_scale(x) + weight_global_scale = _make_global_scale(weight) + alpha = (1.0 / (input_global_scale * weight_global_scale)).to(torch.float32) + + x_fp4, x_scale_swizzled = flashinfer.fp4_quantize(x, input_global_scale) + weight_fp4, weight_scale_swizzled = flashinfer.fp4_quantize( + weight, weight_global_scale + ) + if x_scale_swizzled.dtype == torch.uint8: + x_scale_swizzled = x_scale_swizzled.view(torch.float8_e4m3fn) + if weight_scale_swizzled.dtype == torch.uint8: + weight_scale_swizzled = weight_scale_swizzled.view(torch.float8_e4m3fn) + + method, layer = _build_layer( + weight_fp4, + weight_scale_swizzled, + input_global_scale, + weight_global_scale, + checkpoint_weight_scale_layout="swizzled", + ) + actual = method.apply(layer, x) + + expected = flashinfer.mm_fp4( + x_fp4, + weight_fp4.t(), + x_scale_swizzled, + weight_scale_swizzled.t(), + alpha, + DTYPE, + backend="cudnn", + ) + + diff = _calc_diff(actual, expected) + assert diff < DEEPGEMM_FP4_MAX_DIFF, f"{m=}, {n=}, {k=}, {diff=:.6f}" + + +@pytest.mark.skipif( + not _nvfp4_supported(), + reason="Diffusion NVFP4 scaled mm correctness requires Blackwell GPUs", +) +def test_checkpoint_processing_flashinfer_trtllm_cpu_weight_scale( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _set_diffusion_fp4_backend(monkeypatch, "flashinfer_trtllm") + + m, n, k = FLUX2_PROJECTION_SHAPE + generator = torch.Generator(device=DEVICE) + generator.manual_seed(20260413 + m + n + k) + + weight = torch.randn((n, k), device=DEVICE, dtype=DTYPE, generator=generator) + input_global_scale = torch.tensor(512.0, device=DEVICE, dtype=torch.float32) + weight_global_scale = _make_global_scale(weight) + weight_fp4, weight_scale_linear = _quantize_weight_for_checkpoint( + weight, weight_global_scale + ) + + _build_layer( + weight_fp4, + weight_scale_linear, + input_global_scale, + weight_global_scale, + weight_scale_device="cpu", + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_flydsl_fused_norm.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_flydsl_fused_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..d9577d12f217e0fffd377679f8763b61c6e157ff --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_flydsl_fused_norm.py @@ -0,0 +1,133 @@ +import sys + +import pytest +import torch +import torch.nn.functional as F + +from sglang.test.ci.ci_register import register_amd_ci + +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + +DEVICE = "cuda" +D = 5120 +EPS = 1e-6 + + +def _ref_rms_norm(x_f32, weight, eps): + var = x_f32.pow(2).mean(-1, keepdim=True) + return x_f32 * torch.rsqrt(var + eps) + + +def _ref_fused_residual_norm_ss( + residual, x, gate, weight, bias, scale, shift, norm_type, eps +): + ref_res = residual.float() + x.float() * (gate.float() if gate is not None else 1) + ref_res_bf16 = ref_res.to(torch.bfloat16) + if norm_type == "layer": + normed = F.layer_norm(ref_res_bf16.float(), (D,), weight, bias, eps) + else: + normed = _ref_rms_norm(ref_res_bf16.float(), weight, eps) * weight.float() + y = (normed * (1.0 + scale.float()) + shift.float()).to(torch.bfloat16) + return y, ref_res_bf16 + + +def _ref_norm_ss(x, weight, bias, scale, shift, norm_type, eps): + if norm_type == "layer": + normed = F.layer_norm(x.float(), (D,), weight, bias, eps) + else: + normed = _ref_rms_norm(x.float(), weight, eps) * weight.float() + return (normed * (1.0 + scale.float()) + shift.float()).to(torch.bfloat16) + + +@pytest.fixture(autouse=True) +def cuda_setup(): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + if not hasattr(torch.version, "hip") or not torch.version.hip: + pytest.skip("ROCm/HIP required for FlyDSL kernels") + torch.manual_seed(42) + + +FUSED_CASES = [ + ("rms", 1, 16), + ("rms", 2, 16), + ("layer", 2, 16), + ("rms", 1, 90000), +] + + +@pytest.mark.parametrize("norm_type,B,L", FUSED_CASES) +def test_fused_residual_norm_scale_shift(norm_type, B, L): + from sglang.jit_kernel.diffusion.flydsl.fused_residual_norm import ( + flydsl_fused_residual_norm_scale_shift, + ) + + residual = torch.randn(B, L, D, device=DEVICE, dtype=torch.bfloat16) + x = torch.randn(B, L, D, device=DEVICE, dtype=torch.bfloat16) + gate = torch.randn(B, 1, D, device=DEVICE, dtype=torch.bfloat16) + weight = torch.randn(D, device=DEVICE, dtype=torch.float32) + bias = ( + torch.randn(D, device=DEVICE, dtype=torch.float32) + if norm_type == "layer" + else None + ) + scale = torch.randn(B, 1, D, device=DEVICE, dtype=torch.bfloat16) + shift = torch.randn(B, 1, D, device=DEVICE, dtype=torch.bfloat16) + + y, res_out = flydsl_fused_residual_norm_scale_shift( + residual, + x, + gate, + weight, + bias, + scale, + shift, + norm_type, + EPS, + ) + y_ref, res_ref = _ref_fused_residual_norm_ss( + residual, + x, + gate, + weight, + bias, + scale, + shift, + norm_type, + EPS, + ) + torch.testing.assert_close(res_out, res_ref, atol=5e-2, rtol=5e-2) + torch.testing.assert_close(y, y_ref, atol=1.0, rtol=5e-2) + + +NSS_CASES = [ + ("rms", 2, 16), + ("layer", 2, 16), + ("rms", 1, 90000), + ("layer", 1, 90000), +] + + +@pytest.mark.parametrize("norm_type,B,L", NSS_CASES) +def test_norm_scale_shift(norm_type, B, L): + from sglang.jit_kernel.diffusion.flydsl.fused_residual_norm import ( + flydsl_norm_scale_shift, + ) + + x = torch.randn(B, L, D, device=DEVICE, dtype=torch.bfloat16) + weight = torch.randn(D, device=DEVICE, dtype=torch.float32) + bias = ( + torch.randn(D, device=DEVICE, dtype=torch.float32) + if norm_type == "layer" + else None + ) + scale = torch.randn(B, 1, D, device=DEVICE, dtype=torch.bfloat16) + shift = torch.randn(B, 1, D, device=DEVICE, dtype=torch.bfloat16) + + y = flydsl_norm_scale_shift(x, weight, bias, scale, shift, norm_type, EPS) + y_ref = _ref_norm_ss(x, weight, bias, scale, shift, norm_type, EPS) + torch.testing.assert_close(y, y_ref, atol=1.0, rtol=5e-2) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_fused_norm_scale_shift.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_fused_norm_scale_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..28c4859314f9c1d6d88642111602c9d2b73481ff --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_fused_norm_scale_shift.py @@ -0,0 +1,252 @@ +import sys +from typing import Optional, Tuple + +import pytest +import torch +from einops import rearrange +from torch import Tensor + +from sglang.jit_kernel.diffusion.cutedsl.scale_residual_norm_scale_shift import ( + fused_norm_scale_shift, + fused_scale_residual_norm_scale_shift, + validate_scale_shift, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=28, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" +SHAPE_MAP = { + "1": lambda B, S, F, D: (1,), + "D": lambda B, S, F, D: (D,), + "1D": lambda B, S, F, D: (1, D), + "BD": lambda B, S, F, D: (B, D), + "11D": lambda B, S, F, D: (1, 1, D), + "B1D": lambda B, S, F, D: (B, 1, D), + "1SD": lambda B, S, F, D: (1, S, D), + "BSD": lambda B, S, F, D: (B, S, D), + "BF1D": lambda B, S, F, D: (B, F, 1, D), +} +SHAPES = [ + # (B, S, F, D) + (1, 115200, 1, 3072), # Hunyuan + (1, 32760, 1, 1536), # Wan + (1, 6, 1, 3072), # Qwen + (1, 1024, 8, 3072), + (4, 512, 16, 3072), +] +DTYPES = [torch.float16, torch.bfloat16, torch.float32] +NORM_TYPES = ["layer", "rms"] +AFFINE_MODES = ["D", "NAT"] +INDEX_MODES = ["BSD", "1", "1SD", "BD", "B1D", "D", "1D", "11D", "BF1D"] + + +def _tol(dtype: torch.dtype): + return 1e-5 if dtype == torch.float32 else 5e-2 + + +@pytest.fixture(autouse=True) +def cuda_setup(): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + torch.cuda.manual_seed(0) + + +def _apply_scale_shift(y: Tensor, scale: Tensor, shift: Tensor) -> Tensor: + if scale.ndim == 4: + num_frame = scale.shape[1] + return rearrange( + rearrange(y, "b (f l) d -> b f l d", f=num_frame) * (1 + scale) + shift, + "b f l d -> b (f l) d", + ) + else: + scale = rearrange(scale, "b d -> b 1 d") if scale.ndim == 2 else scale + shift = rearrange(shift, "b d -> b 1 d") if shift.ndim == 2 else shift + return y * (1 + scale) + shift + + +def fused_norm_scale_shift_ref( + x: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + scale: Tensor, + shift: Tensor, + norm_type: str, + eps: float, +) -> Tensor: + original_dtype = x.dtype + x, weight, bias, scale, shift = ( + v.float() if v is not None else v for v in [x, weight, bias, scale, shift] + ) + if norm_type == "layer": + norm = torch.layer_norm(x, x.shape[-1:], eps=eps, weight=weight, bias=bias) + else: + norm = torch.rms_norm(x, x.shape[-1:], eps=eps, weight=weight) + return _apply_scale_shift(norm, scale, shift).to(original_dtype) + + +def fused_scale_residual_norm_scale_shift_ref( + residual: Tensor, + x: Tensor, + gate: Optional[Tensor] | int, + weight: Optional[Tensor], + bias: Optional[Tensor], + scale: Tensor, + shift: Tensor, + norm_type: str, + eps: float, +): + original_dtype = x.dtype + residual, x, gate, weight, bias, scale, shift = ( + v.float() if isinstance(v, Tensor) else v + for v in [residual, x, gate, weight, bias, scale, shift] + ) + if isinstance(gate, int): + x = residual + gate * x + else: + if gate.ndim == 4: + num_frame = gate.shape[1] + x_fld = rearrange(x, "b (f l) d -> b f l d", f=num_frame) + x = residual + rearrange(x_fld * gate, "b f l d -> b (f l) d") + else: + gate = rearrange(gate, "b d -> b 1 d") if gate.ndim == 2 else gate + x = residual + gate * x + if norm_type == "layer": + norm = torch.layer_norm(x, x.shape[-1:], eps=eps, weight=weight, bias=bias) + else: + norm = torch.rms_norm(x, x.shape[-1:], eps=eps, weight=weight) + y_ref = _apply_scale_shift(norm, scale, shift) + return y_ref.to(original_dtype), x.to(original_dtype) + + +def _make_tensor(index_mode: str, shape: Tuple, dtype: torch.dtype): + if index_mode == "NAT": + return None + return torch.randn(*SHAPE_MAP[index_mode](*shape), device=DEVICE, dtype=dtype) + + +def test_validate_scale_shift_rejects_non_divisible_frames(): + with pytest.raises(ValueError, match=r"S\(10\) must be divisible by F\(4\)"): + validate_scale_shift( + torch.empty((1, 4, 1, 256), device=DEVICE, dtype=torch.float16), + 1, + 10, + 256, + ) + + +@torch.no_grad() +def run_norm_scale_shift( + shape=SHAPES[0], + dtype=DTYPES[0], + affine_dtype=DTYPES[0], + scale_dtype=DTYPES[0], + shift_dtype=DTYPES[0], + norm_type=NORM_TYPES[0], + affine_mode=AFFINE_MODES[0], + scale_mode="BSD", + shift_mode="BSD", + eps=1e-5, +): + x = _make_tensor("BSD", shape, dtype) + weight = _make_tensor(affine_mode, shape, affine_dtype) + bias = _make_tensor(affine_mode, shape, affine_dtype) + scale = _make_tensor(scale_mode, shape, scale_dtype) + shift = _make_tensor(shift_mode, shape, shift_dtype) + y_dev = fused_norm_scale_shift(x, weight, bias, scale, shift, norm_type, eps) + y_ref = fused_norm_scale_shift_ref(x, weight, bias, scale, shift, norm_type, eps) + torch.testing.assert_close(y_dev, y_ref, atol=_tol(dtype), rtol=_tol(dtype)) + + +@torch.no_grad() +def run_scale_resi_norm_scale_shift( + shape=SHAPES[0], + dtype=DTYPES[0], + affine_dtype=DTYPES[0], + scale_dtype=DTYPES[0], + shift_dtype=DTYPES[0], + norm_type=NORM_TYPES[0], + affine_mode=AFFINE_MODES[0], + gate_mode="B1D", + scale_mode="BSD", + shift_mode="BSD", + eps=1e-5, +): + residual = _make_tensor("BSD", shape, dtype) + x = _make_tensor("BSD", shape, dtype) + gate = _make_tensor(gate_mode, shape, dtype) + weight = _make_tensor(affine_mode, shape, affine_dtype) + bias = _make_tensor(affine_mode, shape, affine_dtype) + scale = _make_tensor(scale_mode, shape, scale_dtype) + shift = _make_tensor(shift_mode, shape, shift_dtype) + y_dev, res_dev = fused_scale_residual_norm_scale_shift( + residual, x, gate, weight, bias, scale, shift, norm_type, eps + ) + y_ref, res_ref = fused_scale_residual_norm_scale_shift_ref( + residual, x, gate, weight, bias, scale, shift, norm_type, eps + ) + torch.testing.assert_close(y_dev, y_ref, atol=_tol(dtype), rtol=_tol(dtype)) + torch.testing.assert_close(res_dev, res_ref, atol=_tol(dtype), rtol=_tol(dtype)) + + +@pytest.mark.parametrize("norm_type", NORM_TYPES) +class TestFusedNormScaleShift: + @pytest.mark.parametrize("shape", SHAPES) + @pytest.mark.parametrize("dtype", DTYPES) + def test_shape_dtype(self, shape, dtype, norm_type): + run_norm_scale_shift(shape=shape, dtype=dtype, norm_type=norm_type) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_dtype_0(self, dtype, norm_type): + run_norm_scale_shift(affine_dtype=dtype, norm_type=norm_type) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_dtype_1(self, dtype, norm_type): + run_norm_scale_shift(scale_dtype=dtype, shift_dtype=dtype, norm_type=norm_type) + + @pytest.mark.parametrize("affine_mode", AFFINE_MODES) + def test_normtype_affine(self, affine_mode, norm_type): + run_norm_scale_shift(affine_mode=affine_mode, norm_type=norm_type) + + @pytest.mark.parametrize("index_mode", INDEX_MODES) + def test_index_mode(self, index_mode, norm_type): + run_norm_scale_shift( + scale_mode=index_mode, shift_mode=index_mode, norm_type=norm_type + ) + + +@pytest.mark.parametrize("norm_type", NORM_TYPES) +class TestFusedScaleResidualNormScaleShift: + @pytest.mark.parametrize("shape", SHAPES) + @pytest.mark.parametrize("dtype", DTYPES) + def test_shape_dtype(self, shape, dtype, norm_type): + run_scale_resi_norm_scale_shift(shape=shape, dtype=dtype, norm_type=norm_type) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_dtype_0(self, dtype, norm_type): + run_scale_resi_norm_scale_shift(affine_dtype=dtype, norm_type=norm_type) + + @pytest.mark.parametrize("dtype", DTYPES) + def test_dtype_1(self, dtype, norm_type): + run_scale_resi_norm_scale_shift( + scale_dtype=dtype, shift_dtype=dtype, norm_type=norm_type + ) + + @pytest.mark.parametrize("affine_mode", AFFINE_MODES) + def test_normtype_affine(self, affine_mode, norm_type): + run_scale_resi_norm_scale_shift(affine_mode=affine_mode, norm_type=norm_type) + + @pytest.mark.parametrize("index_mode", INDEX_MODES) + def test_scale_shift_index_mode(self, index_mode, norm_type): + run_scale_resi_norm_scale_shift( + scale_mode=index_mode, shift_mode=index_mode, norm_type=norm_type + ) + + @pytest.mark.parametrize("index_mode", INDEX_MODES) + def test_gate_index_mode(self, index_mode, norm_type): + run_scale_resi_norm_scale_shift(gate_mode=index_mode, norm_type=norm_type) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_group_norm_silu.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_group_norm_silu.py new file mode 100644 index 0000000000000000000000000000000000000000..7d9f115248ee032d46a0e65f1c6052ad091ce6a6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_group_norm_silu.py @@ -0,0 +1,105 @@ +import sys + +import pytest +import torch +import torch.nn as nn +import torch.nn.functional as F + +from sglang.jit_kernel.diffusion.group_norm_silu import apply_group_norm_silu +from sglang.jit_kernel.diffusion.triton.group_norm_silu import triton_group_norm_silu +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=8, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=15, suite="nightly-amd-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" +DTYPES = [torch.float16, torch.bfloat16, torch.float32] +TEST_CASES = [ + pytest.param((2, 64, 32, 32), 32, id="image_2d"), + pytest.param((1, 64, 4, 16, 16), 32, id="video_3d"), + pytest.param((4, 128), 32, id="token_2d"), +] +LARGE_TILE_CASE = ((1, 128, 20, 256, 256), 32) + + +def _tol(dtype: torch.dtype) -> tuple[float, float]: + if dtype == torch.float32: + return 1e-5, 1e-5 + if dtype == torch.bfloat16: + return 7e-2, 2e-2 + return 3e-3, 3e-3 + + +@pytest.fixture(autouse=True) +def cuda_setup(): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + torch.cuda.manual_seed(0) + + +def _reference( + x: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor, + num_groups: int, + eps: float = 1e-5, +) -> torch.Tensor: + return F.silu(F.group_norm(x, num_groups, weight=weight, bias=bias, eps=eps)) + + +@torch.no_grad() +@pytest.mark.parametrize("shape,num_groups", TEST_CASES) +@pytest.mark.parametrize("dtype", DTYPES) +def test_triton_group_norm_silu( + shape: tuple[int, ...], num_groups: int, dtype: torch.dtype +) -> None: + channels = shape[1] + x = torch.randn(shape, device=DEVICE, dtype=dtype) + weight = torch.randn(channels, device=DEVICE, dtype=dtype) + bias = torch.randn(channels, device=DEVICE, dtype=dtype) + + actual = triton_group_norm_silu(x, weight, bias, num_groups=num_groups) + expected = _reference(x, weight, bias, num_groups) + + atol, rtol = _tol(dtype) + torch.testing.assert_close(actual, expected, atol=atol, rtol=rtol) + + +@torch.no_grad() +@pytest.mark.parametrize("shape,num_groups", TEST_CASES[:2]) +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_apply_group_norm_silu( + shape: tuple[int, ...], + num_groups: int, + dtype: torch.dtype, +) -> None: + norm = nn.GroupNorm(num_groups, shape[1], eps=1e-5, affine=True).to( + device=DEVICE, dtype=dtype + ) + activation = nn.SiLU() + hidden_states = torch.randn(shape, device=DEVICE, dtype=dtype) + + actual = apply_group_norm_silu(hidden_states, norm, activation) + expected = activation(norm(hidden_states)) + + atol, rtol = _tol(dtype) + torch.testing.assert_close(actual, expected, atol=atol, rtol=rtol) + + +@torch.no_grad() +def test_triton_group_norm_silu_large_tile_bf16() -> None: + shape, num_groups = LARGE_TILE_CASE + x = torch.randn(shape, device=DEVICE, dtype=torch.bfloat16) + weight = torch.randn(shape[1], device=DEVICE, dtype=torch.bfloat16) + bias = torch.randn(shape[1], device=DEVICE, dtype=torch.bfloat16) + + actual = triton_group_norm_silu(x, weight, bias, num_groups=num_groups) + expected = _reference(x, weight, bias, num_groups) + + atol, rtol = _tol(torch.bfloat16) + torch.testing.assert_close(actual, expected, atol=atol, rtol=rtol) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_ltx2_ada_values.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_ltx2_ada_values.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f21ef450dee03ec455c3a0ee3a41ad80427ad2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_ltx2_ada_values.py @@ -0,0 +1,70 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.diffusion.triton.ltx2_ada_values import ltx2_ada_values9 +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=8, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=8, suite="nightly-amd-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" + + +@pytest.fixture(autouse=True) +def cuda_setup(): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + torch.cuda.manual_seed(0) + + +def _reference( + scale_shift_table: torch.Tensor, + timestep: torch.Tensor, +) -> tuple[torch.Tensor, ...]: + batch, seq, _ = timestep.shape + hidden = scale_shift_table.shape[1] + return ( + scale_shift_table.to(device=timestep.device, dtype=timestep.dtype) + .view(1, 1, 9, hidden) + .add(timestep.reshape(batch, seq, 9, hidden)) + .unbind(dim=2) + ) + + +@torch.no_grad() +@pytest.mark.parametrize("batch,seq,hidden", [(1, 1, 4096), (2, 3, 2048)]) +@pytest.mark.parametrize("table_dtype", [torch.bfloat16, torch.float32]) +def test_ltx2_ada_values9( + batch: int, + seq: int, + hidden: int, + table_dtype: torch.dtype, +) -> None: + scale_shift_table = torch.randn( + 9, hidden, device=DEVICE, dtype=table_dtype + ).contiguous() + timestep = torch.randn( + batch, seq, 9 * hidden, device=DEVICE, dtype=torch.bfloat16 + ).contiguous() + + actual = ltx2_ada_values9(scale_shift_table, timestep) + expected = _reference(scale_shift_table, timestep) + + assert len(actual) == 9 + for actual_value, expected_value in zip(actual, expected): + torch.testing.assert_close(actual_value, expected_value, atol=0, rtol=0) + + +@torch.no_grad() +def test_ltx2_ada_values9_rejects_unsupported_shape() -> None: + scale_shift_table = torch.randn(8, 4096, device=DEVICE, dtype=torch.bfloat16) + timestep = torch.randn(1, 1, 9 * 4096, device=DEVICE, dtype=torch.bfloat16) + + with pytest.raises(ValueError, match="scale_shift_table"): + ltx2_ada_values9(scale_shift_table, timestep) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_ltx2_qknorm_split_rope.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_ltx2_qknorm_split_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..b1dfe4626dcacd09c5f926bd35246d6aa2f550be --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_ltx2_qknorm_split_rope.py @@ -0,0 +1,223 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.diffusion.ltx2_qknorm_split_rope import ( + can_use_ltx2_qknorm_split_rope_cuda, + ltx2_qknorm_split_rope_cuda, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="4-gpu-b200") + + +def _require_cuda_b200() -> None: + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + if torch.cuda.get_device_capability()[0] < 10: + pytest.skip("LTX2 QKNorm split-RoPE CUDA path is validated on B200") + + +@pytest.fixture(autouse=True) +def cuda_setup(): + _require_cuda_b200() + torch.cuda.manual_seed(20260630) + + +def _make_cos_sin( + batch: int, seq_len: int, num_heads: int, head_dim: int +) -> tuple[torch.Tensor, torch.Tensor]: + half_dim = head_dim // 2 + cos = torch.randn( + batch, seq_len, num_heads, half_dim, device="cuda", dtype=torch.bfloat16 + ).transpose(1, 2) + sin = torch.randn( + batch, seq_len, num_heads, half_dim, device="cuda", dtype=torch.bfloat16 + ).transpose(1, 2) + return cos, sin + + +def _apply_split_rotary_ref( + x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor +) -> torch.Tensor: + x_dtype = x.dtype + batch = x.shape[0] + _, num_heads, seq_len, _ = cos.shape + x = x.reshape(batch, seq_len, num_heads, -1).swapaxes(1, 2) + last = x.shape[-1] + half = last // 2 + + split_x = x.reshape(*x.shape[:-1], 2, half) + first_x = split_x[..., :1, :] + second_x = split_x[..., 1:, :] + cos_u = cos.unsqueeze(-2) + sin_u = sin.unsqueeze(-2) + + out = split_x * cos_u + out[..., :1, :].addcmul_(-sin_u, second_x) + out[..., 1:, :].addcmul_(sin_u, first_x) + out = out.reshape(*out.shape[:-2], last) + return out.swapaxes(1, 2).reshape(batch, seq_len, -1).to(dtype=x_dtype) + + +def _reference( + q: torch.Tensor, + k: torch.Tensor, + q_cos: torch.Tensor, + q_sin: torch.Tensor, + k_cos: torch.Tensor, + k_sin: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + eps: float, +) -> tuple[torch.Tensor, torch.Tensor]: + q_norm = torch.nn.RMSNorm(q.shape[-1], eps=eps, device="cuda").to( + dtype=torch.bfloat16 + ) + k_norm = torch.nn.RMSNorm(k.shape[-1], eps=eps, device="cuda").to( + dtype=torch.bfloat16 + ) + q_norm.weight.data.copy_(q_weight) + k_norm.weight.data.copy_(k_weight) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + q_ref = _apply_split_rotary_ref(q_norm(q), q_cos, q_sin) + k_ref = _apply_split_rotary_ref(k_norm(k), k_cos, k_sin) + return q_ref.to(dtype=torch.bfloat16), k_ref.to(dtype=torch.bfloat16) + + +@pytest.mark.parametrize( + "batch,q_seq,k_seq,num_heads,head_dim", + [ + (1, 3, 3, 32, 128), + (1, 5, 2, 32, 64), + (2, 4, 3, 32, 64), + ], +) +def test_ltx2_qknorm_split_rope_matches_torch_exactly( + batch: int, q_seq: int, k_seq: int, num_heads: int, head_dim: int +) -> None: + hidden = num_heads * head_dim + eps = 1e-6 + q = torch.randn(batch, q_seq, hidden, device="cuda", dtype=torch.bfloat16) + k = torch.randn(batch, k_seq, hidden, device="cuda", dtype=torch.bfloat16) + q_cos, q_sin = _make_cos_sin(batch, q_seq, num_heads, head_dim) + k_cos, k_sin = _make_cos_sin(batch, k_seq, num_heads, head_dim) + q_weight = torch.randn(hidden, device="cuda", dtype=torch.bfloat16) + k_weight = torch.randn(hidden, device="cuda", dtype=torch.bfloat16) + + assert can_use_ltx2_qknorm_split_rope_cuda( + q, + q_cos, + q_sin, + q_weight, + k, + k_cos, + k_sin, + k_weight, + num_heads=num_heads, + head_dim=head_dim, + ) + + q_ref, k_ref = _reference(q, k, q_cos, q_sin, k_cos, k_sin, q_weight, k_weight, eps) + q_out, k_out = ltx2_qknorm_split_rope_cuda( + q, + q_cos, + q_sin, + q_weight, + k, + k_cos, + k_sin, + k_weight, + eps=eps, + num_heads=num_heads, + head_dim=head_dim, + ) + torch.cuda.synchronize() + + assert torch.equal(q_ref, q_out) + assert torch.equal(k_ref, k_out) + + +def test_ltx2_qknorm_split_rope_rejects_unsupported_inputs() -> None: + q = torch.randn((1, 3, 4096), device="cuda", dtype=torch.bfloat16) + k = torch.randn_like(q) + q_cos, q_sin = _make_cos_sin(1, 3, 32, 128) + q_weight = torch.randn(4096, device="cuda", dtype=torch.bfloat16) + k_weight = torch.randn(4096, device="cuda", dtype=torch.bfloat16) + + assert can_use_ltx2_qknorm_split_rope_cuda( + q, + q_cos, + q_sin, + q_weight, + k, + q_cos, + q_sin, + k_weight, + num_heads=32, + head_dim=128, + ) + assert not can_use_ltx2_qknorm_split_rope_cuda( + q.float(), + q_cos, + q_sin, + q_weight, + k, + q_cos, + q_sin, + k_weight, + num_heads=32, + head_dim=128, + ) + assert not can_use_ltx2_qknorm_split_rope_cuda( + q, + q_cos, + q_sin, + q_weight, + k, + q_cos.transpose(-1, -2), + q_sin, + k_weight, + num_heads=32, + head_dim=128, + ) + + +def test_ltx2_qknorm_split_rope_custom_op_torch_compile_fullgraph() -> None: + batch, q_seq, k_seq, num_heads, head_dim = 1, 3, 2, 32, 64 + hidden = num_heads * head_dim + q = torch.randn(batch, q_seq, hidden, device="cuda", dtype=torch.bfloat16) + k = torch.randn(batch, k_seq, hidden, device="cuda", dtype=torch.bfloat16) + q_cos, q_sin = _make_cos_sin(batch, q_seq, num_heads, head_dim) + k_cos, k_sin = _make_cos_sin(batch, k_seq, num_heads, head_dim) + q_weight = torch.randn(hidden, device="cuda", dtype=torch.bfloat16) + k_weight = torch.randn(hidden, device="cuda", dtype=torch.bfloat16) + + def fn(q, k, q_cos, q_sin, k_cos, k_sin, q_weight, k_weight): + return ltx2_qknorm_split_rope_cuda( + q, + q_cos, + q_sin, + q_weight, + k, + k_cos, + k_sin, + k_weight, + eps=1e-6, + num_heads=num_heads, + head_dim=head_dim, + ) + + compiled = torch.compile(fn, fullgraph=True) + q_out, k_out = compiled(q, k, q_cos, q_sin, k_cos, k_sin, q_weight, k_weight) + q_ref, k_ref = _reference( + q, k, q_cos, q_sin, k_cos, k_sin, q_weight, k_weight, 1e-6 + ) + torch.cuda.synchronize() + assert torch.equal(q_ref, q_out) + assert torch.equal(k_ref, k_out) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_qknorm_rope.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_qknorm_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac14bd19aa02d2a00d89cf20437e58294d55a0c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_qknorm_rope.py @@ -0,0 +1,153 @@ +import itertools +import sys + +import pytest +import torch +import triton + +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=44, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=176, suite="nightly-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" +DTYPE = torch.bfloat16 +MAX_SEQ_LEN = 131072 +ROPE_BASE = 10000.0 +ATOL = 8e-2 +RTOL = 1e-2 + + +def create_cos_sin_cache( + rotary_dim: int, + max_position: int = MAX_SEQ_LEN, + base: float = ROPE_BASE, +) -> torch.Tensor: + inv_freq = 1.0 / ( + base + ** ( + torch.arange(0, rotary_dim, 2, dtype=torch.float32, device=DEVICE) + / rotary_dim + ) + ) + t = torch.arange(max_position, dtype=torch.float32, device=DEVICE) + freqs = torch.einsum("i,j->ij", t, inv_freq) + return torch.cat((freqs.cos(), freqs.sin()), dim=-1) + + +def split_qknorm_rope( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + is_neox: bool, +) -> None: + from flashinfer.rope import apply_rope_with_cos_sin_cache_inplace + + from sglang.jit_kernel.norm import fused_inplace_qknorm + + fused_inplace_qknorm(q, k, q_weight, k_weight) + apply_rope_with_cos_sin_cache_inplace( + positions=positions.long(), + query=q.view(q.shape[0], -1), + key=k.view(k.shape[0], -1), + head_size=q.shape[-1], + cos_sin_cache=cos_sin_cache, + is_neox=is_neox, + ) + + +def fused_qknorm_rope( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + is_neox: bool, +) -> None: + from sglang.jit_kernel.diffusion.qknorm_rope import fused_inplace_qknorm_rope + + fused_inplace_qknorm_rope( + q, + k, + q_weight, + k_weight, + cos_sin_cache, + positions, + is_neox=is_neox, + rope_dim=cos_sin_cache.shape[-1], + ) + + +BS_LIST = [2**n for n in range(13)] +BS_LIST += [x + 1 for x in BS_LIST] +BS_LIST = get_ci_test_range(BS_LIST, [1, 9, 129, 257, 2049, 4097]) +HEADS_LIST = get_ci_test_range([8, 16, 24, 32], [8, 24]) +HEAD_DIM_LIST = get_ci_test_range([64, 128, 256], [64, 128, 256]) +IS_NEOX_LIST = [False, True] +POSITION_DTYPES = [torch.int32, torch.int64] +ROPE_DIM_CHOICES = { + 64: [64], + 128: [64, 128], + 256: [64, 128, 256], +} + + +@pytest.mark.parametrize( + "batch_size,num_heads,head_dim,is_neox,position_dtype", + list( + itertools.product( + BS_LIST, + HEADS_LIST, + HEAD_DIM_LIST, + IS_NEOX_LIST, + POSITION_DTYPES, + ) + ), +) +def test_qknorm_rope( + batch_size: int, + num_heads: int, + head_dim: int, + is_neox: bool, + position_dtype: torch.dtype, +) -> None: + rope_dims = ROPE_DIM_CHOICES[head_dim] + for rope_dim in rope_dims: + if is_neox: + elems_per_thread = head_dim // 32 + rotary_lanes = rope_dim // elems_per_thread + if rotary_lanes < 2 or rotary_lanes & (rotary_lanes - 1): + continue + + q = torch.randn(batch_size, num_heads, head_dim, device=DEVICE, dtype=DTYPE) + k = torch.randn(batch_size, num_heads, head_dim, device=DEVICE, dtype=DTYPE) + q_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + k_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + positions = torch.randint( + 0, MAX_SEQ_LEN, (batch_size,), device=DEVICE, dtype=position_dtype + ) + cos_sin_cache = create_cos_sin_cache(rope_dim) + + q_ref, k_ref = q.clone(), k.clone() + q_fused, k_fused = q.clone(), k.clone() + + split_qknorm_rope( + q_ref, k_ref, q_weight, k_weight, cos_sin_cache, positions, is_neox + ) + fused_qknorm_rope( + q_fused, k_fused, q_weight, k_weight, cos_sin_cache, positions, is_neox + ) + + # The split baseline mixes a separate BF16 qknorm kernel with FlashInfer RoPE, + # which differs from the fused path by about one BF16 rounding step on H200. + triton.testing.assert_close(q_ref, q_fused, atol=ATOL, rtol=RTOL) + triton.testing.assert_close(k_ref, k_fused, atol=ATOL, rtol=RTOL) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_qwen_image_modulation.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_qwen_image_modulation.py new file mode 100644 index 0000000000000000000000000000000000000000..27f84c3dd2cf2bd3d4d859d41f2a3fcc0eaf680e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_qwen_image_modulation.py @@ -0,0 +1,227 @@ +import sys + +import pytest +import torch +import triton + +from sglang.jit_kernel.diffusion.triton.norm import norm_infer +from sglang.jit_kernel.diffusion.triton.scale_shift import ( + fuse_layernorm_scale_shift_gate_select01_kernel, + fuse_residual_layernorm_scale_shift_gate_select01_kernel, +) +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=15, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=30, suite="nightly-amd-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" +DTYPES = get_ci_test_range( + [torch.float16, torch.bfloat16, torch.float32], [torch.float16, torch.bfloat16] +) +BATCH_SIZES = get_ci_test_range([1, 2, 4], [1, 2]) +SEQ_LENS = get_ci_test_range([6, 33, 128, 257], [6, 128]) +HIDDEN_SIZES = get_ci_test_range([512, 1024, 1536, 3072], [512, 3072]) +EPS = 1e-6 + + +def _tol(dtype: torch.dtype) -> tuple[float, float]: + if dtype == torch.float32: + return 1e-5, 1e-5 + return 5e-2, 5e-2 + + +def _make_modulation_tensors(batch_size: int, hidden_size: int, dtype: torch.dtype): + scale0 = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=dtype) + shift0 = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=dtype) + gate0 = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=dtype) + scale1 = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=dtype) + shift1 = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=dtype) + gate1 = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=dtype) + return scale0, shift0, gate0, scale1, shift1, gate1 + + +def _baseline_select01_modulation( + x: torch.Tensor, + weight: torch.Tensor | None, + bias: torch.Tensor | None, + scale0: torch.Tensor, + shift0: torch.Tensor, + gate0: torch.Tensor, + scale1: torch.Tensor, + shift1: torch.Tensor, + gate1: torch.Tensor, + index: torch.Tensor, + eps: float, +): + normalized = norm_infer( + x.view(-1, x.shape[-1]), + weight, + bias, + eps=eps, + is_rms_norm=False, + ).view_as(x) + return _apply_select01_modulation( + normalized, scale0, shift0, gate0, scale1, shift1, gate1, index + ) + + +def _baseline_residual_select01_modulation( + x: torch.Tensor, + residual: torch.Tensor, + residual_gate: torch.Tensor, + weight: torch.Tensor | None, + bias: torch.Tensor | None, + scale0: torch.Tensor, + shift0: torch.Tensor, + gate0: torch.Tensor, + scale1: torch.Tensor, + shift1: torch.Tensor, + gate1: torch.Tensor, + index: torch.Tensor, + eps: float, +): + residual_out = residual + residual_gate * x + normalized = norm_infer( + residual_out.view(-1, residual_out.shape[-1]), + weight, + bias, + eps=eps, + is_rms_norm=False, + ).view_as(residual_out) + output, gate_out = _apply_select01_modulation( + normalized, scale0, shift0, gate0, scale1, shift1, gate1, index + ) + return output, residual_out, gate_out + + +def _apply_select01_modulation( + x: torch.Tensor, + scale0: torch.Tensor, + shift0: torch.Tensor, + gate0: torch.Tensor, + scale1: torch.Tensor, + shift1: torch.Tensor, + gate1: torch.Tensor, + index: torch.Tensor, +): + idx = index.bool().unsqueeze(-1) + scale = torch.where(idx, scale1.unsqueeze(1), scale0.unsqueeze(1)) + shift = torch.where(idx, shift1.unsqueeze(1), shift0.unsqueeze(1)) + gate = torch.where(idx, gate1.unsqueeze(1), gate0.unsqueeze(1)) + return x * (1 + scale) + shift, gate + + +@pytest.fixture(autouse=True) +def cuda_setup(): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + torch.cuda.manual_seed(0) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("batch_size", BATCH_SIZES) +@pytest.mark.parametrize("seq_len", SEQ_LENS) +@pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) +def test_fused_layernorm_scale_shift_gate_select01( + dtype, batch_size, seq_len, hidden_size +): + x = torch.randn(batch_size, seq_len, hidden_size, device=DEVICE, dtype=dtype) + weight = torch.randn(hidden_size, device=DEVICE, dtype=dtype) + bias = torch.randn(hidden_size, device=DEVICE, dtype=dtype) + index = torch.randint(0, 2, (batch_size, seq_len), device=DEVICE, dtype=torch.int32) + scale0, shift0, gate0, scale1, shift1, gate1 = _make_modulation_tensors( + batch_size, hidden_size, dtype + ) + + out_ref, gate_ref = _baseline_select01_modulation( + x, + weight, + bias, + scale0, + shift0, + gate0, + scale1, + shift1, + gate1, + index, + EPS, + ) + out_fused, gate_fused = fuse_layernorm_scale_shift_gate_select01_kernel( + x.contiguous(), + weight=weight, + bias=bias, + scale0=scale0, + shift0=shift0, + gate0=gate0, + scale1=scale1, + shift1=shift1, + gate1=gate1, + index=index, + eps=EPS, + ) + + atol, rtol = _tol(dtype) + triton.testing.assert_close(out_ref, out_fused, atol=atol, rtol=rtol) + triton.testing.assert_close(gate_ref, gate_fused, atol=atol, rtol=rtol) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("batch_size", BATCH_SIZES) +@pytest.mark.parametrize("seq_len", SEQ_LENS) +@pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) +def test_fused_residual_layernorm_scale_shift_gate_select01( + dtype, batch_size, seq_len, hidden_size +): + x = torch.randn(batch_size, seq_len, hidden_size, device=DEVICE, dtype=dtype) + residual = torch.randn_like(x) + residual_gate = torch.randn_like(x) + weight = torch.randn(hidden_size, device=DEVICE, dtype=dtype) + bias = torch.randn(hidden_size, device=DEVICE, dtype=dtype) + index = torch.randint(0, 2, (batch_size, seq_len), device=DEVICE, dtype=torch.int32) + scale0, shift0, gate0, scale1, shift1, gate1 = _make_modulation_tensors( + batch_size, hidden_size, dtype + ) + + out_ref, residual_ref, gate_ref = _baseline_residual_select01_modulation( + x, + residual, + residual_gate, + weight, + bias, + scale0, + shift0, + gate0, + scale1, + shift1, + gate1, + index, + EPS, + ) + out_fused, residual_fused, gate_fused = ( + fuse_residual_layernorm_scale_shift_gate_select01_kernel( + x.contiguous(), + residual=residual.contiguous(), + residual_gate=residual_gate.contiguous(), + weight=weight, + bias=bias, + scale0=scale0, + shift0=shift0, + gate0=gate0, + scale1=scale1, + shift1=shift1, + gate1=gate1, + index=index, + eps=EPS, + ) + ) + + atol, rtol = _tol(dtype) + triton.testing.assert_close(out_ref, out_fused, atol=atol, rtol=rtol) + triton.testing.assert_close(residual_ref, residual_fused, atol=atol, rtol=rtol) + triton.testing.assert_close(gate_ref, gate_fused, atol=atol, rtol=rtol) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_residual_gate_add.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_residual_gate_add.py new file mode 100644 index 0000000000000000000000000000000000000000..452534c3c34da8494ba68e9a9b8bd9cdf44e65d6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_residual_gate_add.py @@ -0,0 +1,101 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.diffusion.residual_gate_add import ( + can_use_residual_gate_add_cuda, + residual_gate_add_cuda, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="4-gpu-b200") + + +CASES = [ + ((1, 1024, 4096), (1, 1, 4096)), + ((1, 512, 4096), (1, 512, 4096)), + ((1, 17, 65), (1, 1, 65)), + ((1, 17, 65), (1, 17, 65)), +] + + +def _tol(dtype: torch.dtype) -> float: + return 1e-5 if dtype == torch.float32 else 5e-2 + + +def _assert_matches_torch(out: torch.Tensor, ref: torch.Tensor) -> None: + if ref.dtype == torch.float32: + torch.testing.assert_close(out, ref, atol=_tol(ref.dtype), rtol=_tol(ref.dtype)) + else: + torch.testing.assert_close(out, ref, atol=0, rtol=0) + + +@pytest.fixture(autouse=True) +def cuda_setup(): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + torch.cuda.manual_seed(0) + + +@pytest.mark.parametrize("residual_shape,gate_shape", CASES) +def test_residual_gate_add_matches_torch(residual_shape, gate_shape): + residual = torch.randn(residual_shape, device="cuda", dtype=torch.bfloat16) + update = torch.randn_like(residual) + gate = torch.randn(gate_shape, device="cuda", dtype=torch.bfloat16) + + out = residual_gate_add_cuda(residual, update, gate) + ref = residual + update * gate + _assert_matches_torch(out, ref) + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32]) +@pytest.mark.parametrize("gate_shape", [(1, 1, 64), (1, 9, 64)]) +def test_residual_gate_add_dtypes(dtype, gate_shape): + residual = torch.randn((1, 9, 64), device="cuda", dtype=dtype) + update = torch.randn_like(residual) + gate = torch.randn(gate_shape, device="cuda", dtype=dtype) + + out = residual_gate_add_cuda(residual, update, gate) + ref = residual + update * gate + _assert_matches_torch(out, ref) + + +def test_can_use_residual_gate_add_cuda_rejects_unsupported_inputs(): + residual = torch.randn((1, 8, 64), device="cuda", dtype=torch.bfloat16) + update = torch.randn_like(residual) + gate = torch.randn((1, 1, 64), device="cuda", dtype=torch.bfloat16) + + assert can_use_residual_gate_add_cuda(residual, update, gate) + assert not can_use_residual_gate_add_cuda(residual.cpu(), update, gate) + assert not can_use_residual_gate_add_cuda(residual, update.float(), gate) + assert not can_use_residual_gate_add_cuda(residual, update[:, ::2], gate) + assert not can_use_residual_gate_add_cuda(residual, update, gate[:, :, ::2]) + + # Only [1, ..., 1, D] row-broadcast gates are supported; a batched + # [B>1, 1, D] gate is not row-broadcast here and must fall back. + batched_residual = torch.randn((2, 8, 64), device="cuda", dtype=torch.bfloat16) + batched_update = torch.randn_like(batched_residual) + batched_gate = torch.randn((2, 1, 64), device="cuda", dtype=torch.bfloat16) + assert not can_use_residual_gate_add_cuda( + batched_residual, batched_update, batched_gate + ) + + +def test_residual_gate_add_custom_op_torch_compile_fullgraph(): + residual = torch.randn((1, 32, 128), device="cuda", dtype=torch.bfloat16) + update = torch.randn_like(residual) + gate = torch.randn((1, 1, 128), device="cuda", dtype=torch.bfloat16) + + def fn(residual, update, gate): + return residual_gate_add_cuda(residual, update, gate) + + compiled = torch.compile(fn, fullgraph=True) + out = compiled(residual, update, gate) + ref = residual + update * gate + _assert_matches_torch(out, ref) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_varlen_pack_pad.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_varlen_pack_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..03619c9e6a2405a1d0cb8ef26f11200831cb341b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_varlen_pack_pad.py @@ -0,0 +1,194 @@ +"""Numerical correctness for fused varlen pack/scatter Triton kernels. + +Bit-exact comparison against the equivalent PyTorch ops (index_select, +zeros + index_copy_) across bf16/fp16 and several shape/mask cases. +""" + +import pytest +import torch + +from sglang.jit_kernel.diffusion.triton.varlen_pack_pad import ( + build_inv_indices, + fused_pack_qkv, + fused_scatter_to_padded, +) +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=60, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=15, suite="nightly-amd-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" +DTYPES = get_ci_test_range([torch.bfloat16, torch.float16], [torch.bfloat16]) +# (bs, s_txt, s_img, num_heads, head_dim, valid_txt_lens) tuples +SHAPES = get_ci_test_range( + [ + # name, bs, s_txt, s_img, H, D, valid_txt_lens + ("small_c2", 2, 64, 128, 4, 64, [32, 48]), + ("prod_c2", 2, 256, 1024, 24, 128, [128, 200]), + ("all_valid_b1", 1, 64, 128, 4, 64, [64]), + ("all_valid_b4", 4, 64, 128, 4, 64, [64, 64, 64, 64]), + ("c8_prod", 8, 256, 4096, 24, 128, [128, 200, 256, 100, 50, 256, 256, 50]), + # one batch with zero valid text tokens (image side still valid) + ("zero_txt_one_batch", 2, 64, 128, 4, 64, [0, 32]), + # bs=1 with no text validity (only image rows packed) + ("bs1_zero_txt", 1, 64, 128, 4, 64, [0]), + ], + [ + ("small_c2", 2, 64, 128, 4, 64, [32, 48]), + ("prod_c2", 2, 256, 1024, 24, 128, [128, 200]), + ("all_valid_b4", 4, 64, 128, 4, 64, [64, 64, 64, 64]), + ], +) + + +def _build_mask(bs, s_txt, s_img, valid_txt_lens): + s = s_txt + s_img + mask = torch.zeros(bs, s, dtype=torch.bool, device=DEVICE) + for b, vt in enumerate(valid_txt_lens): + mask[b, :vt] = True + mask[b, s_txt:] = True + return mask + + +def _ref_pack(q, k, v, indices): + bs, seq = q.shape[:2] + flat = lambda t: t.reshape(bs * seq, *t.shape[2:]) + return ( + flat(q).index_select(0, indices), + flat(k).index_select(0, indices), + flat(v).index_select(0, indices), + ) + + +def _ref_scatter(out_unpad, indices, bs, seq): + n_valid = indices.shape[0] + _, num_heads, head_dim = out_unpad.shape + flat = torch.zeros( + bs * seq, num_heads, head_dim, dtype=out_unpad.dtype, device=DEVICE + ) + flat.index_copy_(0, indices, out_unpad) + return flat.view(bs, seq, num_heads, head_dim) + + +def _build_meta(mask): + bs, seq = mask.shape + indices = mask.reshape(-1).nonzero(as_tuple=False).flatten() + inv_indices = build_inv_indices(indices, bs * seq) + return indices, inv_indices + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize( + "shape", SHAPES, ids=lambda s: s[0] if isinstance(s, tuple) else str(s) +) +def test_pack_matches_index_select(dtype, shape): + _, bs, s_txt, s_img, num_heads, head_dim, valid_txt_lens = shape + torch.manual_seed(0) + s = s_txt + s_img + mask = _build_mask(bs, s_txt, s_img, valid_txt_lens) + indices, _ = _build_meta(mask) + + q = torch.randn(bs, s, num_heads, head_dim, dtype=dtype, device=DEVICE) + k = torch.randn(bs, s, num_heads, head_dim, dtype=dtype, device=DEVICE) + v = torch.randn(bs, s, num_heads, head_dim, dtype=dtype, device=DEVICE) + + q_ref, k_ref, v_ref = _ref_pack(q, k, v, indices) + q_fused, k_fused, v_fused = fused_pack_qkv(q, k, v, indices) + + # bit-exact: pack is pure gather, no math + assert torch.equal(q_ref, q_fused) + assert torch.equal(k_ref, k_fused) + assert torch.equal(v_ref, v_fused) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize( + "shape", SHAPES, ids=lambda s: s[0] if isinstance(s, tuple) else str(s) +) +def test_scatter_matches_index_copy(dtype, shape): + _, bs, s_txt, s_img, num_heads, head_dim, valid_txt_lens = shape + torch.manual_seed(1) + s = s_txt + s_img + mask = _build_mask(bs, s_txt, s_img, valid_txt_lens) + indices, inv_indices = _build_meta(mask) + n_valid = indices.shape[0] + + out_unpad = torch.randn(n_valid, num_heads, head_dim, dtype=dtype, device=DEVICE) + out_ref = _ref_scatter(out_unpad, indices, bs, s) + out_fused = fused_scatter_to_padded(out_unpad, inv_indices, bs, s) + + # bit-exact: scatter is pure copy + zero-fill + assert torch.equal(out_ref, out_fused) + # Padding rows must be exactly zero + invalid = ~mask + if invalid.any(): + assert out_fused[invalid].abs().max().item() == 0.0 + + +def test_pack_handles_non_contiguous_input(): + """Helper must accept non-contiguous Q/K/V (auto .contiguous() inside).""" + torch.manual_seed(2) + bs, s_txt, s_img, num_heads, head_dim = 2, 64, 128, 4, 64 + s = s_txt + s_img + mask = _build_mask(bs, s_txt, s_img, [32, 48]) + indices, _ = _build_meta(mask) + + # Build non-contiguous tensors via permute + qkv_pre = torch.randn( + bs, num_heads, s, head_dim, dtype=torch.bfloat16, device=DEVICE + ) + q = qkv_pre.permute(0, 2, 1, 3) + k = torch.randn_like(qkv_pre).permute(0, 2, 1, 3) + v = torch.randn_like(qkv_pre).permute(0, 2, 1, 3) + assert not q.is_contiguous() + + q_ref, k_ref, v_ref = _ref_pack( + q.contiguous(), k.contiguous(), v.contiguous(), indices + ) + q_fused, k_fused, v_fused = fused_pack_qkv(q, k, v, indices) + assert torch.equal(q_ref, q_fused) + assert torch.equal(k_ref, k_fused) + assert torch.equal(v_ref, v_fused) + + +def test_build_inv_indices_matches_manual(): + """build_inv_indices output should match the manual full+scatter form.""" + torch.manual_seed(3) + bs, s = 2, 32 + mask = torch.bernoulli(torch.full((bs, s), 0.6, device=DEVICE)).to(torch.bool) + indices = mask.reshape(-1).nonzero(as_tuple=False).flatten() + n_valid = indices.shape[0] + + manual = torch.full((bs * s,), -1, dtype=torch.int32, device=DEVICE) + if n_valid > 0: + manual[indices.long()] = torch.arange(n_valid, dtype=torch.int32, device=DEVICE) + + built = build_inv_indices(indices, bs * s) + assert torch.equal(built, manual) + + +def test_empty_valid_set_handled(): + """All-False mask: pack returns empty tensors; scatter writes all zeros.""" + bs, s, num_heads, head_dim = 2, 16, 4, 64 + mask = torch.zeros(bs, s, dtype=torch.bool, device=DEVICE) + indices = mask.reshape(-1).nonzero(as_tuple=False).flatten() + inv_indices = build_inv_indices(indices, bs * s) + assert indices.numel() == 0 + + q = torch.randn(bs, s, num_heads, head_dim, dtype=torch.bfloat16, device=DEVICE) + q_unpad, k_unpad, v_unpad = fused_pack_qkv(q, q.clone(), q.clone(), indices) + assert q_unpad.shape == (0, num_heads, head_dim) + assert k_unpad.shape == (0, num_heads, head_dim) + assert v_unpad.shape == (0, num_heads, head_dim) + + out_padded = fused_scatter_to_padded(q_unpad, inv_indices, bs, s) + assert out_padded.shape == (bs, s, num_heads, head_dim) + assert out_padded.abs().max().item() == 0.0 + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_varlen_uspattn_equivalence.py b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_varlen_uspattn_equivalence.py new file mode 100644 index 0000000000000000000000000000000000000000..d16fe32a9b37e645ed93b4ebdb526703e891d957 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/diffusion/test_varlen_uspattn_equivalence.py @@ -0,0 +1,156 @@ +"""End-to-end equivalence between USPAttention varlen path and SDPA reference. + +Compares the production varlen path (``build_varlen_mask_meta`` + +``fused_pack_qkv`` + ``flash_attn_varlen_func`` + ``fused_scatter_to_padded``) +against ``torch.nn.functional.scaled_dot_product_attention`` with a broadcast +key mask, for inputs the gating in ``USPAttention.forward`` would accept. + +Verifies the documented contract: + * Valid (non-masked) query rows match SDPA within FA-vs-SDPA tolerance. + * Masked query rows are exactly zero in the varlen path (differs from + SDPA, which produces deterministic attention output at those rows). +""" + +import pytest +import torch +import torch.nn.functional as F + +from sglang.jit_kernel.diffusion.triton.varlen_pack_pad import ( + fused_pack_qkv, + fused_scatter_to_padded, +) +from sglang.jit_kernel.flash_attention import flash_attn_varlen_func +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.multimodal_gen.runtime.layers.attention.backends import ( + flash_attn as _fa_backend, +) +from sglang.multimodal_gen.runtime.layers.attention.layer import ( + build_varlen_mask_meta, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=15, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=60, suite="nightly-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" +DTYPES = get_ci_test_range([torch.bfloat16, torch.float16], [torch.bfloat16]) +# (name, bs, s_txt, s_img, num_heads, head_dim, valid_txt_lens) +SHAPES = get_ci_test_range( + [ + ("small_c2", 2, 64, 128, 4, 64, [32, 48]), + ("prod_c2", 2, 256, 1024, 24, 128, [128, 200]), + ("all_valid_b1", 1, 64, 128, 4, 64, [64]), + ("zero_txt_one_batch", 2, 64, 128, 4, 64, [0, 32]), + ], + [ + ("small_c2", 2, 64, 128, 4, 64, [32, 48]), + ], +) + + +def _build_mask(bs, s_txt, s_img, valid_txt_lens): + s = s_txt + s_img + mask = torch.zeros(bs, s, dtype=torch.bool, device=DEVICE) + for b, vt in enumerate(valid_txt_lens): + mask[b, :vt] = True + mask[b, s_txt:] = True + return mask + + +def _sdpa_with_key_mask(q, k, v, key_mask, softmax_scale): + """Reference: SDPA with a ``[B, S]`` key mask broadcast to ``[B, 1, 1, S]``.""" + q_ = q.transpose(1, 2) + k_ = k.transpose(1, 2) + v_ = v.transpose(1, 2) + mask = key_mask.to(dtype=q.dtype)[:, None, None, :] + mask = (mask - 1.0) * torch.finfo(q.dtype).max + out = F.scaled_dot_product_attention( + q_, + k_, + v_, + attn_mask=mask, + dropout_p=0.0, + is_causal=False, + scale=softmax_scale, + ) + return out.transpose(1, 2) + + +def _varlen_path(q, k, v, key_mask, softmax_scale): + """Production varlen path matching USPAttention.forward masked branch.""" + bs, seq = q.shape[0], q.shape[1] + meta = build_varlen_mask_meta(key_mask) + indices = meta["indices"] + if indices.shape[0] == 0: + return torch.zeros_like(q) + q_unpad, k_unpad, v_unpad = fused_pack_qkv(q, k, v, indices) + out_unpad = flash_attn_varlen_func( + q=q_unpad, + k=k_unpad, + v=v_unpad, + cu_seqlens_q=meta["cu_seqlens"], + cu_seqlens_k=meta["cu_seqlens"], + max_seqlen_q=meta["max_seqlen"], + max_seqlen_k=meta["max_seqlen"], + softmax_scale=softmax_scale, + causal=False, + ver=_fa_backend.fa_ver, + ) + return fused_scatter_to_padded(out_unpad, meta["inv_indices"], bs, seq) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize( + "shape", SHAPES, ids=lambda s: s[0] if isinstance(s, tuple) else str(s) +) +def test_varlen_path_matches_sdpa_on_valid_rows(dtype, shape): + """Valid rows: varlen output ≈ SDPA output within FA tolerance.""" + _, bs, s_txt, s_img, num_heads, head_dim, valid_txt_lens = shape + torch.manual_seed(0) + s = s_txt + s_img + softmax_scale = head_dim**-0.5 + mask = _build_mask(bs, s_txt, s_img, valid_txt_lens) + q = torch.randn(bs, s, num_heads, head_dim, dtype=dtype, device=DEVICE) + k = torch.randn(bs, s, num_heads, head_dim, dtype=dtype, device=DEVICE) + v = torch.randn(bs, s, num_heads, head_dim, dtype=dtype, device=DEVICE) + + out_sdpa = _sdpa_with_key_mask(q, k, v, mask, softmax_scale) + out_varlen = _varlen_path(q, k, v, mask, softmax_scale) + + valid = mask[..., None, None].expand_as(out_sdpa) + rtol = 1e-2 if dtype == torch.bfloat16 else 5e-3 + atol = 5e-2 if dtype == torch.bfloat16 else 1e-2 + torch.testing.assert_close( + out_sdpa[valid], + out_varlen[valid], + rtol=rtol, + atol=atol, + ) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize( + "shape", SHAPES, ids=lambda s: s[0] if isinstance(s, tuple) else str(s) +) +def test_varlen_path_zeros_masked_rows(dtype, shape): + """Masked rows: varlen path produces exact zeros (documented contract).""" + _, bs, s_txt, s_img, num_heads, head_dim, valid_txt_lens = shape + torch.manual_seed(1) + s = s_txt + s_img + softmax_scale = head_dim**-0.5 + mask = _build_mask(bs, s_txt, s_img, valid_txt_lens) + q = torch.randn(bs, s, num_heads, head_dim, dtype=dtype, device=DEVICE) + k = torch.randn(bs, s, num_heads, head_dim, dtype=dtype, device=DEVICE) + v = torch.randn(bs, s, num_heads, head_dim, dtype=dtype, device=DEVICE) + + out_varlen = _varlen_path(q, k, v, mask, softmax_scale) + + invalid = ~mask + if invalid.any(): + assert (out_varlen[invalid] == 0).all(), "masked rows must be zero-filled" + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_const_sync.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_const_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..aae231913994572c1759c98b11eacdd26c05a165 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_const_sync.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import re +from pathlib import Path + +import sglang.jit_kernel +from sglang.jit_kernel.kv_canary import consts +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=5, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=5, stage="jit-kernel-unit", runner_config="amd") + + +# Resolve the kernel source against the installed jit_kernel package rather +# than this file's location, so the test stays correct wherever it lives. +_CONSTS_CUH: Path = ( + Path(sglang.jit_kernel.__file__).resolve().parent + / "csrc" + / "kv_canary" + / "consts.cuh" +) + + +def _camel_to_upper_snake(name: str) -> str: + return re.sub(r"([A-Z])", r"_\1", name).lstrip("_").upper() + + +def _decode(expr: str) -> int: + expr = expr.strip().rstrip("UuLl") + if "<<" in expr: + return 1 << int(expr.split("<<")[1].strip()) + return int(expr, 0) + + +def _parse_constexpr_ints(source: str) -> dict[str, int]: + pattern = re.compile(r"constexpr\s+(?:[\w:]+)\s+(k[A-Za-z]\w*)\s*=\s*([^;]+);") + return {name: _decode(rhs) for name, rhs in pattern.findall(source)} + + +def _parse_enum_class(source: str, enum_name: str) -> dict[str, int]: + pattern = re.compile( + r"enum\s+class\s+" + re.escape(enum_name) + r"\s*:\s*[^\{]+\{([^}]+)\}" + ) + body = pattern.search(source).group(1) + member_re = re.compile(r"(k[A-Za-z]\w*)\s*=\s*([^,]+)") + return {name: _decode(rhs) for name, rhs in member_re.findall(body)} + + +def test_int_consts_sync() -> None: + cpp = _parse_constexpr_ints(_CONSTS_CUH.read_text(encoding="utf-8")) + cpp_normalized = {_camel_to_upper_snake(n[1:]): v for n, v in cpp.items()} + py = { + n: v + for n, v in vars(consts).items() + if isinstance(v, int) and not isinstance(v, bool) and not n.startswith("_") + } + assert cpp_normalized == py + + +def test_enums_sync() -> None: + cuh = _CONSTS_CUH.read_text(encoding="utf-8") + for enum_name in ("RealKvHashMode", "FailReason"): + cpp_members = _parse_enum_class(cuh, enum_name) + py_enum = getattr(consts, enum_name) + cpp_normalized = { + _camel_to_upper_snake(n[1:]): v for n, v in cpp_members.items() + } + py_normalized = {m.name: int(m.value) for m in py_enum} + assert cpp_normalized == py_normalized + + +if __name__ == "__main__": + import sys + + import pytest + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_kernel_config.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_kernel_config.py new file mode 100644 index 0000000000000000000000000000000000000000..22359d56320e4d1003d2081594164df5766bf86b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_kernel_config.py @@ -0,0 +1,441 @@ +from __future__ import annotations + +import pytest +import torch + +from sglang.jit_kernel.kv_canary import consts +from sglang.jit_kernel.kv_canary.verify import ( + CanaryLaunchTag, + VerifyOrWriteContext, + VerifyPlan, + launch_canary_verify_kernel, +) +from sglang.jit_kernel.kv_canary.write import WritePlan +from sglang.jit_kernel.tests.kv_canary._canary_helpers import ( + FakeViolationLog, + assert_canary_buf_equal, + assert_canary_state_equal, + make_canary_buf, + make_canary_buf_pair, + make_log_pair, + make_verify_plan, + make_verify_plan_pair, + make_write_plan_pair, + stamp_clean_chain, +) +from sglang.jit_kernel.tests.kv_canary._differential import ( + _assert_plans_byte_equal, + _run_both_plan, + _run_both_verify, + _run_both_write, +) +from sglang.jit_kernel.tests.kv_canary._fixtures import ( + dummy_pseudo_tensors, + empty_extras, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=60, stage="jit-kernel-unit", runner_config="amd") + +_DEVICE = torch.device("cuda") + + +def _build_verify_plan_5_entries( + *, device: torch.device +) -> tuple[VerifyPlan, VerifyPlan]: + num_slots = 16 + cuda_buf, ref_buf = make_canary_buf_pair( + num_slots=num_slots, slot_stride_bytes=32, device=_DEVICE + ) + + plan_cuda, plan_ref = make_verify_plan_pair( + slot_indices=[0, 1, 2, 3, 4], + positions=[0, 1, 2, 3, 4], + prev_slot_indices=[-1, 0, 1, 2, 3], + capacity=8, + device=device, + ) + return plan_cuda, plan_ref + + +def _build_write_fixtures( + *, device: torch.device +) -> tuple[WritePlan, WritePlan, torch.Tensor, torch.Tensor, torch.Tensor]: + num_tokens = 5 + plan_cuda, plan_ref = make_write_plan_pair( + write_offsets=[0, num_tokens], + seed_slot_indices=[-1], + num_valid_reqs=1, + req_capacity=4, + device=device, + ) + input_ids = torch.tensor([10, 20, 30, 40, 50], dtype=torch.int64, device=device) + positions = torch.tensor([0, 1, 2, 3, 4], dtype=torch.int64, device=device) + out_cache_loc = torch.tensor([0, 1, 2, 3, 4], dtype=torch.int64, device=device) + return plan_cuda, plan_ref, input_ids, positions, out_cache_loc + + +def _build_plan_fixtures( + *, device: torch.device, int64_req_to_token: bool = False +) -> tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + bs = 3 + max_reqs = 4 + max_seq_len = 16 + req_pool_indices = torch.tensor([1, 2, 3], dtype=torch.int64, device=device) + prefix_lens = torch.tensor([0, 4, 8], dtype=torch.int64, device=device) + extend_seq_lens = torch.tensor([5, 1, 1], dtype=torch.int64, device=device) + rp_axis = torch.arange(max_reqs, device=device, dtype=torch.int32).unsqueeze(1) + pos_axis = torch.arange(max_seq_len, device=device, dtype=torch.int32).unsqueeze(0) + req_to_token_int32 = (rp_axis * max_seq_len + pos_axis).contiguous() + if int64_req_to_token: + req_to_token = req_to_token_int32.to(torch.int64) + else: + req_to_token = req_to_token_int32 + return req_pool_indices, prefix_lens, extend_seq_lens, req_to_token + + +def test_verify_byte_equal_across_repeated_launches_10x() -> None: + num_launches = 10 + plan_cuda, plan_ref = _build_verify_plan_5_entries(device=_DEVICE) + + snapshot_rings: list[torch.Tensor] = [] + snapshot_write_indices: list[torch.Tensor] = [] + snapshot_bufs: list[torch.Tensor] = [] + + for _ in range(num_launches): + cuda_buf, ref_buf = make_canary_buf_pair( + num_slots=16, slot_stride_bytes=32, device=_DEVICE + ) + cuda_log, ref_log = make_log_pair(capacity=64, device=_DEVICE) + + _run_both_verify( + cuda_canary_buf=cuda_buf, + ref_canary_buf=ref_buf, + plan_cuda=plan_cuda, + plan_ref=plan_ref, + cuda_log=cuda_log, + ref_log=ref_log, + real_kv_sources_cuda=(), + real_kv_sources_ref=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + ) + + assert_canary_buf_equal(buf_a=cuda_buf, buf_b=ref_buf) + assert_canary_state_equal(log_a=cuda_log, log_b=ref_log) + + snapshot_rings.append(cuda_log.ring.clone()) + snapshot_write_indices.append(cuda_log.write_index.clone()) + snapshot_bufs.append(cuda_buf.clone()) + + for i in range(1, num_launches): + assert torch.equal( + snapshot_rings[0], snapshot_rings[i] + ), f"violation_ring differs between launch 0 and {i}" + assert torch.equal( + snapshot_write_indices[0], snapshot_write_indices[i] + ), f"violation_write_index differs between launch 0 and {i}" + assert torch.equal( + snapshot_bufs[0], snapshot_bufs[i] + ), f"canary_buf differs between launch 0 and {i}" + + +def test_write_byte_equal_across_repeated_launches_10x() -> None: + num_launches = 10 + plan_cuda, plan_ref, input_ids, positions, out_cache_loc = _build_write_fixtures( + device=_DEVICE + ) + + snapshot_bufs: list[torch.Tensor] = [] + snapshot_rings: list[torch.Tensor] = [] + snapshot_counters: list[torch.Tensor] = [] + + for _ in range(num_launches): + cuda_buf, ref_buf = make_canary_buf_pair( + num_slots=16, slot_stride_bytes=32, device=_DEVICE + ) + cuda_log, ref_log = make_log_pair(capacity=64, device=_DEVICE) + pseudo_tok, pseudo_pos = dummy_pseudo_tensors(input_ids.shape[0]) + + _run_both_write( + cuda_canary_buf=cuda_buf, + ref_canary_buf=ref_buf, + plan_cuda=plan_cuda, + plan_ref=plan_ref, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + enable_write_verify_inputs=False, + expected_input_tokens=pseudo_tok, + expected_input_positions=pseudo_pos, + cuda_log=cuda_log, + ref_log=ref_log, + real_kv_sources_cuda=(), + real_kv_sources_ref=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + ) + + assert_canary_buf_equal(buf_a=cuda_buf, buf_b=ref_buf) + assert_canary_state_equal(log_a=cuda_log, log_b=ref_log) + + snapshot_bufs.append(cuda_buf.clone()) + snapshot_rings.append(cuda_log.ring.clone()) + snapshot_counters.append(cuda_log.slot_run_counter.clone()) + + for i in range(1, num_launches): + assert torch.equal( + snapshot_bufs[0], snapshot_bufs[i] + ), f"canary_buf differs between launch 0 and {i}" + assert torch.equal( + snapshot_rings[0], snapshot_rings[i] + ), f"violation_ring differs between launch 0 and {i}" + assert torch.equal( + snapshot_counters[0], snapshot_counters[i] + ), f"slot_run_counter differs between launch 0 and {i}" + + +def test_plan_byte_equal_across_repeated_launches_10x() -> None: + num_launches = 10 + req_pool_indices, prefix_lens, extend_seq_lens, req_to_token = _build_plan_fixtures( + device=_DEVICE + ) + + snapshot_slots: list[torch.Tensor] = [] + snapshot_positions: list[torch.Tensor] = [] + snapshot_prevs: list[torch.Tensor] = [] + snapshot_write_offsets: list[torch.Tensor] = [] + + for _ in range(num_launches): + triton_v = VerifyPlan.allocate( + verify_capacity=64, device=_DEVICE + ).zero_for_testing_() + triton_w = WritePlan.allocate( + write_req_capacity=8, device=_DEVICE + ).zero_for_testing_() + ref_v = VerifyPlan.allocate( + verify_capacity=64, device=_DEVICE + ).zero_for_testing_() + ref_w = WritePlan.allocate( + write_req_capacity=8, device=_DEVICE + ).zero_for_testing_() + + _run_both_plan( + triton_verify=triton_v, + triton_write=triton_w, + ref_verify=ref_v, + ref_write=ref_w, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=req_to_token, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + ) + + _assert_plans_byte_equal( + triton_verify=triton_v, + triton_write=triton_w, + ref_verify=ref_v, + ref_write=ref_w, + ) + + n_verify = int(triton_v.verify_num_valid[0].item()) + snapshot_slots.append(triton_v.verify_slot_indices[:n_verify].clone()) + snapshot_positions.append(triton_v.verify_expected_positions[:n_verify].clone()) + snapshot_prevs.append(triton_v.verify_prev_slot_indices[:n_verify].clone()) + snapshot_write_offsets.append(triton_w.write_offsets.clone()) + + for i in range(1, num_launches): + assert torch.equal( + snapshot_slots[0], snapshot_slots[i] + ), f"verify_slot_indices differs between launch 0 and {i}" + assert torch.equal( + snapshot_positions[0], snapshot_positions[i] + ), f"verify_expected_positions differs between launch 0 and {i}" + assert torch.equal( + snapshot_prevs[0], snapshot_prevs[i] + ), f"verify_prev_slot_indices differs between launch 0 and {i}" + assert torch.equal( + snapshot_write_offsets[0], snapshot_write_offsets[i] + ), f"write_offsets differs between launch 0 and {i}" + + +def test_verify_multi_launch_100x_counter_linear() -> None: + num_launches = 100 + + plan_cuda = make_verify_plan( + slot_indices=[0], + positions=[0], + prev_slot_indices=[-1], + capacity=4, + device=_DEVICE, + ) + + cuda_log = FakeViolationLog.allocate(capacity=64, device=_DEVICE) + + for _ in range(num_launches): + cuda_buf = make_canary_buf(num_slots=16, slot_stride_bytes=32, device=_DEVICE) + launch_canary_verify_kernel( + context=VerifyOrWriteContext( + canary_buf=cuda_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=cuda_log.ring, + violation_write_index=cuda_log.write_index, + slot_run_counter=cuda_log.slot_run_counter, + kernel_run_counter=cuda_log.kernel_run_counter, + enable_chain_position_assert=cuda_log.enable_chain_position_assert, + real_kv_sources=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ), + plan=plan_cuda, + check_verify_expected_token=True, + ) + + torch.cuda.synchronize() + + assert ( + int(cuda_log.kernel_run_counter[0].item()) == num_launches + ), f"kernel_run_counter expected {num_launches}, got {cuda_log.kernel_run_counter[0].item()}" + assert int(cuda_log.slot_run_counter[0].item()) == num_launches, ( + f"slot_run_counter expected {num_launches} (1 active entry x 100 launches), " + f"got {cuda_log.slot_run_counter[0].item()}" + ) + + +def test_verify_check_disabled_byte_equal() -> None: + """check_verify_expected_token True vs False produce equivalent violation logs on a clean plan.""" + plan_true_cuda, plan_true_ref = _build_verify_plan_5_entries(device=_DEVICE) + plan_false_cuda, plan_false_ref = _build_verify_plan_5_entries(device=_DEVICE) + + chain_slot_indices = [0, 1, 2, 3, 4] + chain_tokens = [10, 20, 30, 40, 50] + chain_positions = [0, 1, 2, 3, 4] + + cuda_buf_true, ref_buf_true = make_canary_buf_pair( + num_slots=16, slot_stride_bytes=32, device=_DEVICE + ) + stamp_clean_chain( + cuda_buf=cuda_buf_true, + ref_buf=ref_buf_true, + slot_indices=chain_slot_indices, + tokens=chain_tokens, + positions=chain_positions, + ) + cuda_buf_false, ref_buf_false = make_canary_buf_pair( + num_slots=16, slot_stride_bytes=32, device=_DEVICE + ) + stamp_clean_chain( + cuda_buf=cuda_buf_false, + ref_buf=ref_buf_false, + slot_indices=chain_slot_indices, + tokens=chain_tokens, + positions=chain_positions, + ) + cuda_log_true, ref_log_true = make_log_pair(capacity=64, device=_DEVICE) + cuda_log_false, ref_log_false = make_log_pair(capacity=64, device=_DEVICE) + + _run_both_verify( + cuda_canary_buf=cuda_buf_true, + ref_canary_buf=ref_buf_true, + plan_cuda=plan_true_cuda, + plan_ref=plan_true_ref, + cuda_log=cuda_log_true, + ref_log=ref_log_true, + real_kv_sources_cuda=(), + real_kv_sources_ref=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + check_verify_expected_token=True, + ) + _run_both_verify( + cuda_canary_buf=cuda_buf_false, + ref_canary_buf=ref_buf_false, + plan_cuda=plan_false_cuda, + plan_ref=plan_false_ref, + cuda_log=cuda_log_false, + ref_log=ref_log_false, + real_kv_sources_cuda=(), + real_kv_sources_ref=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + check_verify_expected_token=False, + ) + + assert int(cuda_log_true.write_index[0].item()) == 0 + assert int(cuda_log_false.write_index[0].item()) == 0 + assert torch.equal(cuda_log_true.ring, cuda_log_false.ring) + assert torch.equal(cuda_log_true.write_index, cuda_log_false.write_index) + assert torch.equal(cuda_log_true.slot_run_counter, cuda_log_false.slot_run_counter) + assert torch.equal( + cuda_log_true.kernel_run_counter, cuda_log_false.kernel_run_counter + ) + + +@pytest.mark.parametrize("per_req_present", [False, True]) +def test_plan_per_req_present_or_absent(per_req_present: bool) -> None: + max_reqs = 4 + max_seq_len = 16 + rp_axis = torch.arange(max_reqs, device=_DEVICE, dtype=torch.int32).unsqueeze(1) + pos_axis = torch.arange(max_seq_len, device=_DEVICE, dtype=torch.int32).unsqueeze(0) + req_to_token = (rp_axis * max_seq_len + pos_axis).contiguous() + + if per_req_present: + req_pool_indices = torch.tensor([1, 2], dtype=torch.int64, device=_DEVICE) + prefix_lens = torch.tensor([3, 5], dtype=torch.int64, device=_DEVICE) + extend_seq_lens = torch.tensor([1, 1], dtype=torch.int64, device=_DEVICE) + else: + req_pool_indices = torch.tensor([0], dtype=torch.int64, device=_DEVICE) + prefix_lens = torch.tensor([0], dtype=torch.int64, device=_DEVICE) + extend_seq_lens = torch.tensor([0], dtype=torch.int64, device=_DEVICE) + + triton_v = VerifyPlan.allocate( + verify_capacity=64, device=_DEVICE + ).zero_for_testing_() + triton_w = WritePlan.allocate( + write_req_capacity=8, device=_DEVICE + ).zero_for_testing_() + ref_v = VerifyPlan.allocate(verify_capacity=64, device=_DEVICE).zero_for_testing_() + ref_w = WritePlan.allocate(write_req_capacity=8, device=_DEVICE).zero_for_testing_() + + _run_both_plan( + triton_verify=triton_v, + triton_write=triton_w, + ref_verify=ref_v, + ref_write=ref_w, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=req_to_token, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + ) + + _assert_plans_byte_equal( + triton_verify=triton_v, + triton_write=triton_w, + ref_verify=ref_v, + ref_write=ref_w, + ) + + if not per_req_present: + assert int(triton_v.verify_num_valid[0].item()) == 0 + bs = int(req_pool_indices.shape[0]) + assert int(triton_w.write_offsets[bs].item()) == 0 + + if per_req_present: + assert int(triton_v.verify_num_valid[0].item()) == 8 + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_pipeline_e2e.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_pipeline_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..dbdc9d85ec3f8a52e518e170272702c42a255d91 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_pipeline_e2e.py @@ -0,0 +1,843 @@ +from __future__ import annotations + +from typing import Any, Optional + +import pytest +import torch + +from sglang.jit_kernel.kv_canary import consts +from sglang.jit_kernel.kv_canary.plan import launch_canary_plan_kernels +from sglang.jit_kernel.kv_canary.plan_ref import ( + launch_canary_plan_kernels_torch_reference, +) +from sglang.jit_kernel.kv_canary.verify import ( + CanaryLaunchTag, + RealKvSource, + VerifyOrWriteContext, + VerifyPlan, + launch_canary_verify_kernel, +) +from sglang.jit_kernel.kv_canary.verify_ref import ( + launch_canary_verify_kernel_torch_reference, +) +from sglang.jit_kernel.kv_canary.write import WritePlan, launch_canary_write_kernel +from sglang.jit_kernel.kv_canary.write_ref import ( + launch_canary_write_kernel_torch_reference, +) +from sglang.jit_kernel.tests.kv_canary._canary_helpers import ( + FakeViolationLog, + assert_canary_buf_equal, + assert_canary_state_equal, + make_canary_buf, + make_real_kv_sources, + stamp_clean_chain, + write_slot_fields, +) +from sglang.jit_kernel.tests.kv_canary._fixtures import ( + clone_real_kv_sources, + empty_extras, + make_req_to_token, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + + +_DEVICE = torch.device("cuda") + + +def _run_pipeline( + *, + real: bool, + req_pool_indices: torch.Tensor, + prefix_lens: torch.Tensor, + extend_seq_lens: torch.Tensor, + input_ids: torch.Tensor, + positions: torch.Tensor, + out_cache_loc: torch.Tensor, + req_to_token: torch.Tensor, + canary_buf: torch.Tensor, + log: FakeViolationLog, + extras: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], + swa_window_size: int, + full_to_swa_index_mapping: Optional[torch.Tensor], + kernel_kind: CanaryLaunchTag, + enable_write_verify_inputs: bool, + expected_input_tokens: torch.Tensor, + expected_input_positions: torch.Tensor, + real_kv_sources: tuple[RealKvSource, ...], + real_kv_hash_mode: consts.RealKvHashMode, + verify_capacity: int, + write_req_capacity: int, + req_to_verify_expected_tokens: Optional[torch.Tensor] = None, + req_to_verify_expected_tokens_valid_lens: Optional[torch.Tensor] = None, + kv_token_id_vs_position_offset: int = 0, + check_verify_expected_token: bool = True, +) -> tuple[VerifyPlan, WritePlan]: + _ = extras + plan_v = VerifyPlan.allocate(verify_capacity=verify_capacity, device=_DEVICE) + plan_w = WritePlan.allocate(write_req_capacity=write_req_capacity, device=_DEVICE) + + # Existing pipeline tests that supply a pool but no per-req lens want "bound by full + # row width" semantics. Synthesise that bound here so callers don't have to. + if ( + req_to_verify_expected_tokens is not None + and req_to_verify_expected_tokens_valid_lens is None + ): + req_to_verify_expected_tokens_valid_lens = torch.full( + (int(req_pool_indices.shape[0]),), + int(req_to_verify_expected_tokens.shape[1]), + dtype=torch.int64, + device=req_pool_indices.device, + ) + + plan_fn = ( + launch_canary_plan_kernels + if real + else launch_canary_plan_kernels_torch_reference + ) + plan_fn( + verify_plan_out=plan_v, + write_plan_out=plan_w, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=req_to_token, + swa_window_size=swa_window_size, + full_to_swa_index_mapping=full_to_swa_index_mapping, + verify_capacity=verify_capacity, + req_to_verify_expected_tokens=req_to_verify_expected_tokens, + req_to_verify_expected_tokens_valid_lens=req_to_verify_expected_tokens_valid_lens, + kv_token_id_vs_position_offset=kv_token_id_vs_position_offset, + ) + + if real: + context = VerifyOrWriteContext( + canary_buf=canary_buf, + kernel_kind=kernel_kind, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=real_kv_sources, + real_kv_hash_mode=real_kv_hash_mode, + ) + launch_canary_write_kernel( + context=context, + plan=plan_w, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + enable_write_input_assert=enable_write_verify_inputs, + expected_input_tokens=expected_input_tokens, + expected_input_positions=expected_input_positions, + ) + launch_canary_verify_kernel( + context=context, + plan=plan_v, + check_verify_expected_token=check_verify_expected_token, + ) + torch.cuda.synchronize() + else: + launch_canary_write_kernel_torch_reference( + context=VerifyOrWriteContext( + canary_buf=canary_buf, + kernel_kind=kernel_kind, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=real_kv_sources, + real_kv_hash_mode=real_kv_hash_mode, + ), + plan=plan_w, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + enable_write_input_assert=enable_write_verify_inputs, + expected_input_tokens=expected_input_tokens, + expected_input_positions=expected_input_positions, + ) + launch_canary_verify_kernel_torch_reference( + context=VerifyOrWriteContext( + canary_buf=canary_buf, + kernel_kind=kernel_kind, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=real_kv_sources, + real_kv_hash_mode=real_kv_hash_mode, + ), + plan=plan_v, + check_verify_expected_token=check_verify_expected_token, + ) + + return plan_v, plan_w + + +def _run_both_and_assert_pipeline_equal( + *, + req_pool_indices: torch.Tensor, + prefix_lens: torch.Tensor, + extend_seq_lens: torch.Tensor, + input_ids: torch.Tensor, + positions: torch.Tensor, + out_cache_loc: torch.Tensor, + req_to_token: torch.Tensor, + num_slots: int, + extras: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], + swa_window_size: int = 0, + full_to_swa_index_mapping: Optional[torch.Tensor] = None, + kernel_kind: CanaryLaunchTag = CanaryLaunchTag.HEAD_K_FULL, + enable_write_verify_inputs: bool = False, + expected_input_tokens: Optional[torch.Tensor] = None, + expected_input_positions: Optional[torch.Tensor] = None, + real_kv_sources_real: tuple[RealKvSource, ...] = (), + real_kv_sources_ref: tuple[RealKvSource, ...] = (), + real_kv_hash_mode: consts.RealKvHashMode = consts.RealKvHashMode.NONE, + ring_capacity: int = 64, + verify_capacity: int = 256, + write_req_capacity: int = 16, + assert_ring_equal: bool = True, + initial_canary_buf: Optional[torch.Tensor] = None, + req_to_verify_expected_tokens: Optional[torch.Tensor] = None, + kv_token_id_vs_position_offset: int = 0, + check_verify_expected_token: bool = True, +) -> tuple[ + torch.Tensor, + torch.Tensor, + FakeViolationLog, + FakeViolationLog, + VerifyPlan, + WritePlan, + VerifyPlan, + WritePlan, +]: + # The kernel rejects non-None expected_* tensors when enable_write_verify_inputs=False + # (sanity check to catch caller bugs), so only synthesise zero placeholders in the + # branch that will actually assert against them. + if enable_write_verify_inputs: + total_tokens = int(input_ids.shape[0]) + if expected_input_tokens is None: + expected_input_tokens = torch.zeros( + total_tokens, dtype=torch.int64, device=_DEVICE + ) + if expected_input_positions is None: + expected_input_positions = torch.zeros( + total_tokens, dtype=torch.int64, device=_DEVICE + ) + + if initial_canary_buf is None: + buf_real = make_canary_buf(num_slots=num_slots, device=_DEVICE) + else: + buf_real = initial_canary_buf.clone() + buf_ref = buf_real.clone() + log_real = FakeViolationLog.allocate(capacity=ring_capacity, device=_DEVICE) + log_ref = FakeViolationLog.allocate(capacity=ring_capacity, device=_DEVICE) + + shared: dict[str, Any] = dict( + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + req_to_token=req_to_token, + extras=extras, + swa_window_size=swa_window_size, + full_to_swa_index_mapping=full_to_swa_index_mapping, + kernel_kind=kernel_kind, + enable_write_verify_inputs=enable_write_verify_inputs, + expected_input_tokens=expected_input_tokens, + expected_input_positions=expected_input_positions, + real_kv_hash_mode=real_kv_hash_mode, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + req_to_verify_expected_tokens=req_to_verify_expected_tokens, + kv_token_id_vs_position_offset=kv_token_id_vs_position_offset, + check_verify_expected_token=check_verify_expected_token, + ) + + plan_v_real, plan_w_real = _run_pipeline( + real=True, + canary_buf=buf_real, + log=log_real, + real_kv_sources=real_kv_sources_real, + **shared, + ) + plan_v_ref, plan_w_ref = _run_pipeline( + real=False, + canary_buf=buf_ref, + log=log_ref, + real_kv_sources=real_kv_sources_ref, + **shared, + ) + + assert_canary_buf_equal(buf_a=buf_real, buf_b=buf_ref) + if assert_ring_equal: + assert_canary_state_equal(log_a=log_real, log_b=log_ref) + else: + assert torch.equal(log_real.write_index, log_ref.write_index) + assert torch.equal(log_real.slot_run_counter, log_ref.slot_run_counter) + assert torch.equal(log_real.kernel_run_counter, log_ref.kernel_run_counter) + + return ( + buf_real, + buf_ref, + log_real, + log_ref, + plan_v_real, + plan_w_real, + plan_v_ref, + plan_w_ref, + ) + + +def _t(values: list[int]) -> torch.Tensor: + return torch.tensor(values, dtype=torch.int64, device=_DEVICE) + + +def _linear_r2t(*, max_reqs: int = 4, max_seq_len: int = 16) -> torch.Tensor: + return make_req_to_token( + kind="linear", max_reqs=max_reqs, max_seq_len=max_seq_len, device=_DEVICE + ) + + +def _zero_no_write_inputs() -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """``(input_ids, positions, out_cache_loc)`` zero placeholders for extend_seq_lens=0 tests.""" + zeros = torch.zeros(1, dtype=torch.int64, device=_DEVICE) + return zeros.clone(), zeros.clone(), zeros.clone() + + +def _contiguous_out_cache_loc( + *, req_pool_idx: int, start: int, count: int, max_seq_len: int = 16 +) -> torch.Tensor: + return _t([req_pool_idx * max_seq_len + start + i for i in range(count)]) + + +def _stamp_linear_prefix( + *, + initial_buf: torch.Tensor, + initial_ref: torch.Tensor, + req_pool_idx: int, + prefix_len: int, + tokens: list[int], + max_seq_len: int = 16, +) -> None: + """Stamp clean chain for slots ``[rp*max_seq_len + 0 .. + prefix_len)`` at positions ``0..prefix_len``.""" + stamp_clean_chain( + cuda_buf=initial_buf, + ref_buf=initial_ref, + slot_indices=[req_pool_idx * max_seq_len + pos for pos in range(prefix_len)], + tokens=tokens, + positions=list(range(prefix_len)), + ) + + +def test_pipeline_basic_5_step_single_req() -> None: + """Single req, prefix_len=0, extend_seq_len=5: basic plan→write→verify byte-equal.""" + _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([0]), + extend_seq_lens=_t([5]), + input_ids=_t([10, 20, 30, 40, 50]), + positions=_t([0, 1, 2, 3, 4]), + out_cache_loc=_contiguous_out_cache_loc(req_pool_idx=1, start=0, count=5), + req_to_token=_linear_r2t(), + num_slots=64, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + ) + + +def test_pipeline_multi_req_mixed_extend_decode() -> None: + """bs=3: pure extend req, decode req (prefix+1 extend), and padding sentinel row.""" + max_seq_len = 16 + _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1, 2, 0]), + prefix_lens=_t([0, 5, 0]), + extend_seq_lens=_t([4, 1, 0]), + input_ids=_t([11, 12, 13, 14, 21]), + positions=_t([0, 1, 2, 3, 5]), + out_cache_loc=_t( + [ + 1 * max_seq_len + 0, + 1 * max_seq_len + 1, + 1 * max_seq_len + 2, + 1 * max_seq_len + 3, + 2 * max_seq_len + 5, + ] + ), + req_to_token=_linear_r2t(max_reqs=8, max_seq_len=max_seq_len), + num_slots=128, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + write_req_capacity=4, + ) + + +def test_pipeline_swa_window() -> None: + """SWA window=4, prefix_len=6: verify covers window [2,6), write covers extend tokens.""" + max_seq_len = 16 + max_reqs = 4 + full_to_swa_index_mapping = torch.arange( + max_reqs * max_seq_len + 1, dtype=torch.int64, device=_DEVICE + ) + + _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([6]), + extend_seq_lens=_t([2]), + input_ids=_t([100, 101]), + positions=_t([6, 7]), + out_cache_loc=_t( + [ + full_to_swa_index_mapping[1 * max_seq_len + 6].item(), + full_to_swa_index_mapping[1 * max_seq_len + 7].item(), + ] + ), + req_to_token=_linear_r2t(max_reqs=max_reqs, max_seq_len=max_seq_len), + num_slots=64, + extras=empty_extras(), + swa_window_size=4, + full_to_swa_index_mapping=full_to_swa_index_mapping, + ) + + +def test_pipeline_sweep_no_write() -> None: + """All extend_seq_lens=0: write_step is no-op, verify sweeps prefix, buf unchanged.""" + prefix_len = 4 + input_ids, positions, out_cache_loc = _zero_no_write_inputs() + + initial_buf = make_canary_buf(num_slots=64, device=_DEVICE) + initial_ref = initial_buf.clone() + _stamp_linear_prefix( + initial_buf=initial_buf, + initial_ref=initial_ref, + req_pool_idx=1, + prefix_len=prefix_len, + tokens=[100 + pos for pos in range(prefix_len)], + ) + + buf_real, buf_ref, log_real, log_ref, plan_v_real, plan_w_real, _, _ = ( + _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([prefix_len]), + extend_seq_lens=_t([0]), + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + req_to_token=_linear_r2t(), + num_slots=64, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + initial_canary_buf=initial_buf, + ) + ) + + assert int(plan_v_real.verify_num_valid[0].item()) == prefix_len + assert int(plan_w_real.write_num_valid_reqs[0].item()) == 1 + assert int(plan_w_real.write_offsets[1].item()) == 0 + assert torch.equal(buf_real, initial_buf) + assert torch.equal(buf_ref, initial_buf) + assert int(log_real.write_index[0].item()) == 0 + assert int(log_ref.write_index[0].item()) == 0 + assert int(log_real.slot_run_counter[0].item()) == prefix_len + assert int(log_ref.slot_run_counter[0].item()) == prefix_len + + +@pytest.mark.parametrize( + "real_kv_hash_mode", + [ + consts.RealKvHashMode.NONE, + consts.RealKvHashMode.PARTIAL, + consts.RealKvHashMode.ALL, + ], +) +def test_pipeline_real_kv_mode(real_kv_hash_mode: consts.RealKvHashMode) -> None: + """real_kv_hash_mode OFF/PARTIAL/ALL: real and ref use cloned sources to prevent ALL-mode hash aliasing.""" + sources_real = make_real_kv_sources(count=2, num_slots=64, device=_DEVICE) + sources_ref = clone_real_kv_sources(sources_real) + + _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([0]), + extend_seq_lens=_t([3]), + input_ids=_t([5, 6, 7]), + positions=_t([0, 1, 2]), + out_cache_loc=_contiguous_out_cache_loc(req_pool_idx=1, start=0, count=3), + req_to_token=_linear_r2t(), + num_slots=64, + extras=empty_extras(), + real_kv_sources_real=sources_real, + real_kv_sources_ref=sources_ref, + real_kv_hash_mode=real_kv_hash_mode, + ) + + +def test_pipeline_pseudo_mode_on_match() -> None: + """enable_write_verify_inputs=ON, expected==actual: zero violations, buf byte-equal.""" + input_ids = _t([1, 2, 3, 4]) + positions = _t([0, 1, 2, 3]) + + _, _, log_real, log_ref, _, _, _, _ = _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([0]), + extend_seq_lens=_t([4]), + input_ids=input_ids, + positions=positions, + out_cache_loc=_contiguous_out_cache_loc(req_pool_idx=1, start=0, count=4), + req_to_token=_linear_r2t(), + num_slots=64, + extras=empty_extras(), + enable_write_verify_inputs=True, + expected_input_tokens=input_ids.clone(), + expected_input_positions=positions.clone(), + ) + + assert int(log_real.write_index[0].item()) == 0 + assert int(log_ref.write_index[0].item()) == 0 + + +def test_pipeline_pseudo_mode_on_token_mismatch_then_verify_clean() -> None: + """enable_write_verify_inputs=ON, expected tokens all wrong: write records N violations.""" + n_tokens = 3 + positions = _t([0, 1, 2]) + + _, _, log_real, log_ref, _, _, _, _ = _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([0]), + extend_seq_lens=_t([3]), + input_ids=_t([10, 20, 30]), + positions=positions, + out_cache_loc=_contiguous_out_cache_loc(req_pool_idx=1, start=0, count=3), + req_to_token=_linear_r2t(), + num_slots=64, + extras=empty_extras(), + enable_write_verify_inputs=True, + expected_input_tokens=_t([99, 99, 99]), + expected_input_positions=positions.clone(), + ring_capacity=64, + ) + + write_violations = int(log_real.write_index[0].item()) + assert ( + write_violations == n_tokens + ), f"expected {n_tokens} write violations, got {write_violations}" + + +def test_pipeline_empty_batch() -> None: + """bs=1 with req_pool_idx=0 (padding): write and verify are no-op, kernel_run_counter == 2 (write+verify).""" + input_ids, positions, out_cache_loc = _zero_no_write_inputs() + + _, _, log_real, log_ref, _, _, _, _ = _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([0]), + prefix_lens=_t([0]), + extend_seq_lens=_t([0]), + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + req_to_token=_linear_r2t(), + num_slots=64, + extras=empty_extras(), + ) + + assert int(log_real.kernel_run_counter[0].item()) == 2 + assert int(log_ref.kernel_run_counter[0].item()) == 2 + assert int(log_real.write_index[0].item()) == 0 + + +def test_pipeline_negative_slot_swa_out_of_window() -> None: + """SWA: some out_cache_loc entries map to -1 (out-of-window); write_step skips them, buf unchanged.""" + max_seq_len = 16 + max_reqs = 4 + + full_to_swa_index_mapping = torch.arange( + max_reqs * max_seq_len + 1, dtype=torch.int64, device=_DEVICE + ) + full_to_swa_index_mapping[1 * max_seq_len + 6] = -1 + full_to_swa_index_mapping[1 * max_seq_len + 7] = -1 + + _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([6]), + extend_seq_lens=_t([4]), + input_ids=_t([100, 101, 102, 103]), + positions=_t([6, 7, 8, 9]), + out_cache_loc=_t([-1, -1, 1 * max_seq_len + 8, 1 * max_seq_len + 9]), + req_to_token=_linear_r2t(max_reqs=max_reqs, max_seq_len=max_seq_len), + num_slots=128, + extras=empty_extras(), + swa_window_size=4, + full_to_swa_index_mapping=full_to_swa_index_mapping, + ) + + +def test_pipeline_ring_overflow_via_real_plan() -> None: + """Verify detects >capacity violations when prev_hash is pre-corrupted; write_index byte-equal, ring relaxed.""" + max_seq_len = 16 + max_reqs = 4 + req_to_token = _linear_r2t(max_reqs=max_reqs, max_seq_len=max_seq_len) + n_slots = 8 + + req_pool_indices = _t([1]) + prefix_lens = _t([n_slots]) + extend_seq_lens = _t([0]) + input_ids, positions, out_cache_loc = _zero_no_write_inputs() + + num_slots = max_reqs * max_seq_len + + # Step 1: pre-pollute canary_buf slots [0..n_slots) with wrong prev_hash so verify fires n_slots violations. + buf_real = make_canary_buf(num_slots=num_slots, device=_DEVICE) + buf_ref = make_canary_buf(num_slots=num_slots, device=_DEVICE) + for slot_idx in range(n_slots): + full_slot = 1 * max_seq_len + slot_idx + for buf in (buf_real, buf_ref): + write_slot_fields( + canary_buf=buf, + slot_idx=full_slot, + token=slot_idx + 1, + position=slot_idx, + prev_hash=0x1234_DEAD_BEEF_0000 + slot_idx, + real_kv_hash=0, + ) + + # Step 2: run real pipeline (plan + no write + verify); overflow ring capacity=4 with all n_slots violations. + ring_capacity = 4 + log_real = FakeViolationLog.allocate(capacity=ring_capacity, device=_DEVICE) + log_ref = FakeViolationLog.allocate(capacity=ring_capacity, device=_DEVICE) + plan_v_real = VerifyPlan.allocate(verify_capacity=256, device=_DEVICE) + plan_w_real = WritePlan.allocate(write_req_capacity=4, device=_DEVICE) + plan_v_ref = VerifyPlan.allocate(verify_capacity=256, device=_DEVICE) + plan_w_ref = WritePlan.allocate(write_req_capacity=4, device=_DEVICE) + + launch_canary_plan_kernels( + verify_plan_out=plan_v_real, + write_plan_out=plan_w_real, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=req_to_token, + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=int(plan_v_real.verify_slot_indices.shape[0]), + req_to_verify_expected_tokens=None, + req_to_verify_expected_tokens_valid_lens=None, + kv_token_id_vs_position_offset=0, + ) + launch_canary_plan_kernels_torch_reference( + verify_plan_out=plan_v_ref, + write_plan_out=plan_w_ref, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=req_to_token, + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=int(plan_v_ref.verify_slot_indices.shape[0]), + req_to_verify_expected_tokens=None, + req_to_verify_expected_tokens_valid_lens=None, + kv_token_id_vs_position_offset=0, + ) + + launch_canary_verify_kernel( + context=VerifyOrWriteContext( + canary_buf=buf_real, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=log_real.ring, + violation_write_index=log_real.write_index, + slot_run_counter=log_real.slot_run_counter, + kernel_run_counter=log_real.kernel_run_counter, + enable_chain_position_assert=log_real.enable_chain_position_assert, + real_kv_sources=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ), + plan=plan_v_real, + check_verify_expected_token=True, + ) + torch.cuda.synchronize() + + launch_canary_verify_kernel_torch_reference( + context=VerifyOrWriteContext( + canary_buf=buf_ref, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=log_ref.ring, + violation_write_index=log_ref.write_index, + slot_run_counter=log_ref.slot_run_counter, + kernel_run_counter=log_ref.kernel_run_counter, + enable_chain_position_assert=log_ref.enable_chain_position_assert, + real_kv_sources=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ), + plan=plan_v_ref, + check_verify_expected_token=True, + ) + + # Step 3: write_index byte-equal; ring contents relaxed (atomic order not guaranteed under overflow). + assert torch.equal(log_real.write_index, log_ref.write_index) + assert int(log_real.write_index[0].item()) == n_slots + + +@pytest.mark.parametrize( + "kernel_kind", [CanaryLaunchTag.HEAD_K_FULL, CanaryLaunchTag.SWEEP_V_SWA] +) +def test_pipeline_kernel_kind_propagates(kernel_kind: CanaryLaunchTag) -> None: + """Different CanaryLaunchTag values: violation ring's kernel_kind field matches on both sides.""" + max_seq_len = 16 + input_ids, positions, out_cache_loc = _zero_no_write_inputs() + + initial_buf = make_canary_buf(num_slots=64, device=_DEVICE) + write_slot_fields( + canary_buf=initial_buf, + slot_idx=1 * max_seq_len, + token=7, + position=99, + prev_hash=0, + real_kv_hash=0, + ) + + _, _, log_real, log_ref, _, _, _, _ = _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([1]), + extend_seq_lens=_t([0]), + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + req_to_token=_linear_r2t(max_seq_len=max_seq_len), + num_slots=64, + extras=empty_extras(), + kernel_kind=kernel_kind, + initial_canary_buf=initial_buf, + ) + + assert int(log_real.write_index[0].item()) == 1 + assert int(log_ref.write_index[0].item()) == 1 + assert int(log_real.ring[0, consts.VIOLATION_FIELD_KERNEL_KIND].item()) == int( + kernel_kind + ) + assert int(log_ref.ring[0, consts.VIOLATION_FIELD_KERNEL_KIND].item()) == int( + kernel_kind + ) + + +def test_pipeline_token_mismatch_detected_via_pool() -> None: + """plan-pool gather + verify-token check: stamped wrong token id raises VERIFY_TOKEN_MISMATCH.""" + max_seq_len = 16 + max_reqs = 4 + prefix_len = 4 + input_ids, positions, out_cache_loc = _zero_no_write_inputs() + + expected_tokens = [1000 + pos for pos in range(prefix_len)] + pool = torch.full((max_reqs, max_seq_len), -999, dtype=torch.int32, device=_DEVICE) + for pos, token in enumerate(expected_tokens): + pool[1, pos] = token + + stored_tokens = [token + 1 for token in expected_tokens] + + initial_buf = make_canary_buf(num_slots=64, device=_DEVICE) + initial_ref = initial_buf.clone() + _stamp_linear_prefix( + initial_buf=initial_buf, + initial_ref=initial_ref, + req_pool_idx=1, + prefix_len=prefix_len, + tokens=stored_tokens, + max_seq_len=max_seq_len, + ) + + _, _, log_real, log_ref, _, _, _, _ = _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([prefix_len]), + extend_seq_lens=_t([0]), + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + req_to_token=_linear_r2t(max_reqs=max_reqs, max_seq_len=max_seq_len), + num_slots=64, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + initial_canary_buf=initial_buf, + req_to_verify_expected_tokens=pool, + kv_token_id_vs_position_offset=0, + check_verify_expected_token=True, + ) + + assert int(log_real.write_index[0].item()) == prefix_len + assert int(log_ref.write_index[0].item()) == prefix_len + # Ring rows may land in any order; collect stored/expected pairs and compare as sets. + observed_pairs: set[tuple[int, int]] = set() + for row_idx in range(prefix_len): + fail_bits = int( + log_real.ring[row_idx, consts.VIOLATION_FIELD_FAIL_REASON_BITS].item() + ) + assert fail_bits & int( + consts.FailReason.VERIFY_TOKEN_MISMATCH + ), f"row {row_idx}: VERIFY_TOKEN_MISMATCH bit missing in {fail_bits:#b}" + stored = int(log_real.ring[row_idx, consts.VIOLATION_FIELD_STORED_TOKEN].item()) + expected = int( + log_real.ring[row_idx, consts.VIOLATION_FIELD_EXPECTED_TOKEN].item() + ) + observed_pairs.add((stored, expected)) + expected_pairs = {(stored_tokens[i], expected_tokens[i]) for i in range(prefix_len)} + assert observed_pairs == expected_pairs + + +def test_pipeline_eagle_offset_plus_1_byte_equal() -> None: + """plan-pool + offset=+1 full pipeline: stamped tokens match pool[rp, pos+1], no violations CUDA vs ref byte-equal.""" + max_seq_len = 16 + max_reqs = 4 + prefix_len = 4 + input_ids, positions, out_cache_loc = _zero_no_write_inputs() + + stored_tokens = [2000 + pos for pos in range(prefix_len)] + pool = torch.full((max_reqs, max_seq_len), -999, dtype=torch.int32, device=_DEVICE) + for pos in range(prefix_len): + # offset=+1 means kernel gathers from pool[rp, pos + 1], so place stored_tokens[pos] there. + pool[1, pos + 1] = stored_tokens[pos] + + initial_buf = make_canary_buf(num_slots=64, device=_DEVICE) + initial_ref = initial_buf.clone() + _stamp_linear_prefix( + initial_buf=initial_buf, + initial_ref=initial_ref, + req_pool_idx=1, + prefix_len=prefix_len, + tokens=stored_tokens, + max_seq_len=max_seq_len, + ) + + _, _, log_real, log_ref, _, _, _, _ = _run_both_and_assert_pipeline_equal( + req_pool_indices=_t([1]), + prefix_lens=_t([prefix_len]), + extend_seq_lens=_t([0]), + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + req_to_token=_linear_r2t(max_reqs=max_reqs, max_seq_len=max_seq_len), + num_slots=64, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + initial_canary_buf=initial_buf, + req_to_verify_expected_tokens=pool, + kv_token_id_vs_position_offset=1, + check_verify_expected_token=True, + ) + + assert int(log_real.write_index[0].item()) == 0 + assert int(log_ref.write_index[0].item()) == 0 + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_plan_fuzz.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_plan_fuzz.py new file mode 100644 index 0000000000000000000000000000000000000000..2ef14542bd4925f0184958acba097381bf69e2d7 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_plan_fuzz.py @@ -0,0 +1,223 @@ +from __future__ import annotations + +import random +from dataclasses import dataclass +from typing import Optional + +import pytest +import torch + +from sglang.jit_kernel.tests.kv_canary._differential import _run_both_plan +from sglang.jit_kernel.tests.kv_canary._fixtures import ( + allocate_plan_pair, + derive_plan_capacity, + make_lut, + make_padding_mask, + make_req_to_token, +) +from sglang.jit_kernel.tests.kv_canary._fuzz_driver import ( + FUZZ_SEEDS_PR, + run_fuzz_combo, +) +from sglang.jit_kernel.tests.kv_canary._invariants import PlanInvariants +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + + +_DEVICE = torch.device("cuda") + +_FUZZ_ITER_PER_SEED = 50 + + +@dataclass(frozen=True, slots=True, kw_only=True) +class PlanFuzzInputs: + req_pool_indices: torch.Tensor + prefix_lens: torch.Tensor + extend_seq_lens: torch.Tensor + req_to_token: torch.Tensor + swa_window_size: int + full_to_swa_index_mapping: Optional[torch.Tensor] + verify_capacity: int + write_req_capacity: int + req_to_verify_expected_tokens: Optional[torch.Tensor] + kv_token_id_vs_position_offset: int + + +def _draw_random_plan_inputs(rng: random.Random) -> PlanFuzzInputs: + bs = rng.randint(1, 16) + max_seq_len = rng.choice([8, 16, 64, 128, 256]) + swa_enabled = rng.random() < 0.5 + swa_window_size = ( + rng.choice([4, 16, 64, max_seq_len, max(2, max_seq_len // 3)]) + if swa_enabled + else 0 + ) + swa_window_size = min(swa_window_size, max_seq_len) + lut_kind = ( + rng.choice(["identity", "shift", "permutation", "with_oob"]) + if swa_enabled + else None + ) + rtt_kind = rng.choice(["linear", "sparse_permuted"]) + padding_kind = rng.choice(["none", "trailing", "interleaved"]) + capacity_kind = rng.choice(["loose", "tight_match", "under_by_one"]) + + max_reqs = max(bs + 2, 4) + pool_size = max_reqs * max_seq_len + rtt = make_req_to_token( + kind=rtt_kind, + max_reqs=max_reqs, + max_seq_len=max_seq_len, + device=_DEVICE, + rng=rng, + ) + padding_mask = make_padding_mask(bs=bs, kind=padding_kind, rng=rng) + req_pool_indices_list: list[int] = [] + prefix_lens_list: list[int] = [] + extend_seq_lens_list: list[int] = [] + for r in range(bs): + if padding_mask[r]: + req_pool_indices_list.append(0) + prefix_lens_list.append(0) + extend_seq_lens_list.append(0) + else: + req_pool_indices_list.append(rng.randint(1, max_reqs - 1)) + prefix_lens_list.append(rng.randint(0, max_seq_len - 1)) + extend_seq_lens_list.append(rng.randint(1, max(1, max_seq_len // 4))) + req_pool_indices = torch.tensor( + req_pool_indices_list, dtype=torch.int64, device=_DEVICE + ) + prefix_lens = torch.tensor(prefix_lens_list, dtype=torch.int64, device=_DEVICE) + extend_seq_lens = torch.tensor( + extend_seq_lens_list, dtype=torch.int64, device=_DEVICE + ) + + total_verify = 0 + for rpi, pfx in zip(req_pool_indices_list, prefix_lens_list): + if rpi == 0: + continue + if swa_window_size > 0: + window_start = max(0, pfx - swa_window_size) + total_verify += max(0, pfx - window_start) + else: + total_verify += pfx + + verify_capacity, write_req_capacity = derive_plan_capacity( + kind=capacity_kind, + total_verify=total_verify, + extras_count=0, + bs=bs, + ) + + full_to_swa: Optional[torch.Tensor] + if swa_window_size > 0 and lut_kind is not None: + full_to_swa = make_lut( + kind=lut_kind, pool_size=pool_size, device=_DEVICE, rng=rng + ) + else: + full_to_swa = None + + expected_pool_present = rng.random() < 0.5 + kv_token_id_vs_position_offset = rng.choice([0, 1]) + expected_pool: Optional[torch.Tensor] + if expected_pool_present: + pool_max_context_len = rng.choice( + [ + max(1, max_seq_len // 4), + max(1, max_seq_len // 2), + max_seq_len, + ] + ) + expected_pool = torch.randint( + low=0, + high=50000, + size=(max_reqs, pool_max_context_len), + dtype=torch.int32, + device=_DEVICE, + ) + else: + expected_pool = None + + return PlanFuzzInputs( + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + swa_window_size=swa_window_size, + full_to_swa_index_mapping=full_to_swa, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + req_to_verify_expected_tokens=expected_pool, + kv_token_id_vs_position_offset=kv_token_id_vs_position_offset, + ) + + +def _run_one(inputs: PlanFuzzInputs) -> tuple: + triton_v, triton_w, ref_v, ref_w = allocate_plan_pair( + verify_capacity=inputs.verify_capacity, + write_req_capacity=inputs.write_req_capacity, + ) + _run_both_plan( + triton_verify=triton_v, + triton_write=triton_w, + ref_verify=ref_v, + ref_write=ref_w, + req_pool_indices=inputs.req_pool_indices, + prefix_lens=inputs.prefix_lens, + extend_seq_lens=inputs.extend_seq_lens, + req_to_token=inputs.req_to_token, + extras=( + torch.empty(0, dtype=torch.int64, device=_DEVICE), + torch.empty(0, dtype=torch.int64, device=_DEVICE), + torch.empty(0, dtype=torch.int64, device=_DEVICE), + torch.zeros(1, dtype=torch.int32, device=_DEVICE), + ), + swa_window_size=inputs.swa_window_size, + full_to_swa_index_mapping=inputs.full_to_swa_index_mapping, + req_to_verify_expected_tokens=inputs.req_to_verify_expected_tokens, + kv_token_id_vs_position_offset=inputs.kv_token_id_vs_position_offset, + ) + PlanInvariants.assert_all( + verify_plan=triton_v, + write_plan=triton_w, + req_pool_indices=inputs.req_pool_indices, + prefix_lens=inputs.prefix_lens, + extend_seq_lens=inputs.extend_seq_lens, + swa_window_size=inputs.swa_window_size, + extras_slot_indices=torch.empty(0, dtype=torch.int64, device=_DEVICE), + extras_positions=torch.empty(0, dtype=torch.int64, device=_DEVICE), + extras_prev_slot_indices=torch.empty(0, dtype=torch.int64, device=_DEVICE), + extras_count=0, + ) + return triton_v, triton_w + + +def _summarize(inputs: PlanFuzzInputs) -> str: + return ( + f"bs={int(inputs.req_pool_indices.shape[0])} " + f"swa={inputs.swa_window_size} " + f"verify_cap={inputs.verify_capacity} write_cap={inputs.write_req_capacity} " + f"has_lut={inputs.full_to_swa_index_mapping is not None} " + f"has_pool={inputs.req_to_verify_expected_tokens is not None} " + f"offset={inputs.kv_token_id_vs_position_offset}" + ) + + +@pytest.mark.parametrize("seed", FUZZ_SEEDS_PR) +def test_plan_fuzz_full_combo(seed: int) -> None: + """Multi-dim plan fuzzer: random LUT/rtt/padding/capacity/swa × N iters, byte-equal.""" + run_fuzz_combo( + seed, + draw_fn=_draw_random_plan_inputs, + run_one_fn=_run_one, + summarize_fn=_summarize, + n_iter=_FUZZ_ITER_PER_SEED, + ) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_plan_hand.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_plan_hand.py new file mode 100644 index 0000000000000000000000000000000000000000..8d94af2d15f9be9390d82196cdfa092b67065de8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_plan_hand.py @@ -0,0 +1,1372 @@ +from __future__ import annotations + +import random + +import pytest +import torch + +from sglang.jit_kernel.kv_canary.plan import launch_canary_plan_kernels +from sglang.jit_kernel.kv_canary.plan_ref import ( + launch_canary_plan_kernels_torch_reference, +) +from sglang.jit_kernel.kv_canary.verify import VerifyPlan +from sglang.jit_kernel.kv_canary.write import WritePlan +from sglang.jit_kernel.tests.kv_canary._differential import run_plan_diff +from sglang.jit_kernel.tests.kv_canary._fixtures import ( + allocate_plan_pair, + derive_plan_capacity, + empty_extras, + make_lut, + make_req_to_token, +) +from sglang.jit_kernel.tests.kv_canary._invariants import PlanInvariants +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + + +_DEVICE = torch.device("cuda") + + +def _tensor(values: list[int]) -> torch.Tensor: + return torch.tensor(values, dtype=torch.int64, device=_DEVICE) + + +def _plan_pair( + *, verify_capacity: int, write_req_capacity: int +) -> tuple[tuple[VerifyPlan, WritePlan], tuple[VerifyPlan, WritePlan]]: + triton_v, triton_w, ref_v, ref_w = allocate_plan_pair( + verify_capacity=verify_capacity, write_req_capacity=write_req_capacity + ) + return (triton_v, triton_w), (ref_v, ref_w) + + +def _alloc_for_inputs( + *, + req_pool_indices: torch.Tensor, + prefix_lens: torch.Tensor, + extend_seq_lens: torch.Tensor, + extras_count: int, + swa_window_size: int, +) -> tuple[int, int]: + bs = int(req_pool_indices.shape[0]) + rpi_cpu = req_pool_indices.detach().cpu().tolist() + pfx_cpu = prefix_lens.detach().cpu().tolist() + ext_cpu = extend_seq_lens.detach().cpu().tolist() + total_verify = 0 + for rpi, pfx in zip(rpi_cpu, pfx_cpu): + if rpi == 0: + continue + if swa_window_size > 0: + window_start = max(0, pfx - swa_window_size) + total_verify += max(0, pfx - window_start) + else: + total_verify += max(0, pfx) + return derive_plan_capacity( + kind="loose", total_verify=total_verify, extras_count=extras_count, bs=bs + ) + + +def _run_label( + *, + label: str, + req_pool_indices: torch.Tensor, + prefix_lens: torch.Tensor, + extend_seq_lens: torch.Tensor, + req_to_token: torch.Tensor, + extras: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], + swa_window_size: int, + full_to_swa_index_mapping: torch.Tensor | None, + verify_capacity: int, + write_req_capacity: int, +) -> tuple[VerifyPlan, WritePlan]: + _ = extras + verify_plan = VerifyPlan.allocate( + verify_capacity=verify_capacity, device=_DEVICE + ).zero_for_testing_() + write_plan = WritePlan.allocate( + write_req_capacity=write_req_capacity, device=_DEVICE + ).zero_for_testing_() + runner = ( + launch_canary_plan_kernels + if label == "real" + else launch_canary_plan_kernels_torch_reference + ) + runner( + verify_plan_out=verify_plan, + write_plan_out=write_plan, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=req_to_token, + swa_window_size=swa_window_size, + full_to_swa_index_mapping=full_to_swa_index_mapping, + verify_capacity=verify_capacity, + req_to_verify_expected_tokens=None, + req_to_verify_expected_tokens_valid_lens=None, + kv_token_id_vs_position_offset=0, + ) + torch.cuda.synchronize() + return verify_plan, write_plan + + +class TestBasicShape: + def test_single_req_extend_basic(self) -> None: + """bs=1, prefix=0, extend=5 → verify entries empty; write_offsets[0:2] = [0, 5]; seed = -1.""" + # Step 1: build a one-req batch with no prefix and 5 extend tokens. + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([3]), + prefix_lens=_tensor([0]), + extend_seq_lens=_tensor([5]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_v, triton_w = plans[0] + # Step 2: prefix=0 → no verify entries; seed = -1 because prefix==0. + assert int(triton_v.verify_num_valid[0].item()) == 0 + assert int(triton_w.write_num_valid_reqs[0].item()) == 1 + assert int(triton_w.write_offsets[0].item()) == 0 + assert int(triton_w.write_offsets[1].item()) == 5 + assert int(triton_w.write_seed_slot_indices[0].item()) == -1 + + def test_single_req_decode(self) -> None: + """extend=1, prefix=K → write_seed_slot = req_to_token[rp, K-1]; verify covers all K prefix tokens.""" + max_seq_len = 16 + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=max_seq_len, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([2]), + prefix_lens=_tensor([7]), + extend_seq_lens=_tensor([1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_v, triton_w = plans[0] + # Step: verify covers positions [0..7); seed slot for req rp=2 is at position 6 = rp * max_seq_len + 6. + assert int(triton_v.verify_num_valid[0].item()) == 7 + assert int(triton_w.write_seed_slot_indices[0].item()) == 2 * max_seq_len + 6 + + def test_multi_req_mixed_extend_decode(self) -> None: + """bs=3 mixed extend/decode → write_offsets cumsum is byte-equal across Triton + ref.""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=8) + # req0: prefill extend=8; req1: decode extend=1; req2: decode extend=1. + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 2, 3]), + prefix_lens=_tensor([0, 4, 10]), + extend_seq_lens=_tensor([8, 1, 1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_v, triton_w = plans[0] + # Step: write_offsets exclusive cumsum on extend_seq_lens. + expected_write_offsets = [0, 8, 9, 10] + for i, value in enumerate(expected_write_offsets): + assert int(triton_w.write_offsets[i].item()) == value + # Verify count = 0 + 4 + 10 = 14. + assert int(triton_v.verify_num_valid[0].item()) == 14 + + +class TestSeedSlot: + def test_prefix_zero_seed_is_minus_one(self) -> None: + """prefix=0 → seed_slot_idx = -1 (no predecessor to anchor on).""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([0]), + extend_seq_lens=_tensor([3]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + assert int(plans[0][1].write_seed_slot_indices[0].item()) == -1 + + def test_prev_slot_minus_one_at_chain_head(self) -> None: + """pos=0 entry → verify_prev_slot_indices == -1 (chain head).""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + extend_seq_lens=_tensor([1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + # First entry has pos=0 → prev_slot = -1. + assert int(plans[0][0].verify_prev_slot_indices[0].item()) == -1 + + def test_prev_slot_is_self_minus_one(self) -> None: + """pos>0 entry → prev = req_to_token[rp, pos-1] (SWA-translated when SWA enabled).""" + max_seq_len = 16 + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=max_seq_len, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([2]), + prefix_lens=_tensor([4]), + extend_seq_lens=_tensor([1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_v = plans[0][0] + # entry[1] is pos=1: prev_slot = req_to_token[2, 0] = 2 * max_seq_len + 0 = 32. + assert int(triton_v.verify_prev_slot_indices[1].item()) == 2 * max_seq_len + 0 + # entry[2] is pos=2: prev_slot = req_to_token[2, 1] = 2 * max_seq_len + 1 = 33. + assert int(triton_v.verify_prev_slot_indices[2].item()) == 2 * max_seq_len + 1 + + def test_seed_translated_through_permuted_lut(self) -> None: + """Permuted LUT: seed slot is the LUT-lookup of req_to_token[rp, prefix-1], NOT identity.""" + rng = random.Random(42) + max_seq_len = 16 + max_reqs = 4 + pool_size = max_reqs * max_seq_len + lut = make_lut(kind="permutation", pool_size=pool_size, device=_DEVICE, rng=rng) + rtt = make_req_to_token( + kind="linear", max_reqs=max_reqs, max_seq_len=max_seq_len, device=_DEVICE + ) + + rp = 2 + prefix = 5 + req_pool_indices = _tensor([rp]) + prefix_lens = _tensor([prefix]) + extend_seq_lens = _tensor([1]) + + full_seed_slot = rp * max_seq_len + (prefix - 1) + expected_seed = int(lut[full_seed_slot].item()) + + extras = empty_extras() + verify_capacity, write_req_capacity = _alloc_for_inputs( + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + extras_count=0, + swa_window_size=max_seq_len, + ) + for label in ("real", "ref"): + _, w_plan = _run_label( + label=label, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + extras=extras, + swa_window_size=max_seq_len, + full_to_swa_index_mapping=lut, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + ) + actual_seed = int(w_plan.write_seed_slot_indices[0].item()) + assert ( + actual_seed == expected_seed + ), f"[{label}] permuted-LUT seed expected {expected_seed} got {actual_seed}" + + def test_swa_window_head_prev_slot_is_real_predecessor(self) -> None: + """SWA window with non-zero window_start: head entry's prev_slot != -1; it is the real predecessor.""" + rng = random.Random(13) + max_seq_len = 256 + max_reqs = 2 + pool_size = max_reqs * max_seq_len + swa_window_size = 128 + prefix = 200 + rp = 1 + lut = make_lut(kind="permutation", pool_size=pool_size, device=_DEVICE, rng=rng) + rtt = make_req_to_token( + kind="linear", max_reqs=max_reqs, max_seq_len=max_seq_len, device=_DEVICE + ) + + req_pool_indices = _tensor([rp]) + prefix_lens = _tensor([prefix]) + extend_seq_lens = _tensor([1]) + extras = empty_extras() + + window_start = prefix - swa_window_size + full_prev_slot = int(rtt[rp, window_start - 1].item()) + expected_prev = int(lut[full_prev_slot].item()) + + verify_capacity, write_req_capacity = derive_plan_capacity( + kind="loose", total_verify=swa_window_size, extras_count=0, bs=1 + ) + + for label in ("real", "ref"): + v_plan, _ = _run_label( + label=label, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + extras=extras, + swa_window_size=swa_window_size, + full_to_swa_index_mapping=lut, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + ) + actual_prev = int(v_plan.verify_prev_slot_indices[0].item()) + assert ( + actual_prev != -1 + ), f"[{label}] SWA window head must have real predecessor, got -1" + assert ( + actual_prev == expected_prev + ), f"[{label}] expected prev={expected_prev} got {actual_prev}" + + +class TestPadding: + def test_padding_rows_contribute_zero(self) -> None: + """``req_pool_indices[r] == 0`` rows → no verify entry, no write entry, seed = -1.""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + # Step: bs=3 with row 1 marked as padding (rpi=0). + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 0, 2]), + prefix_lens=_tensor([5, 99, 3]), + extend_seq_lens=_tensor([1, 99, 1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_v, triton_w = plans[0] + # verify count = 5 (req0) + 0 (padding) + 3 (req2) = 8. + assert int(triton_v.verify_num_valid[0].item()) == 8 + # write_offsets cumsum: [0, 1, 1, 2] — padding row contributes 0. + expected_write_offsets = [0, 1, 1, 2] + for i, value in enumerate(expected_write_offsets): + assert int(triton_w.write_offsets[i].item()) == value + # Padding row's seed must be -1. + assert int(triton_w.write_seed_slot_indices[1].item()) == -1 + + def test_per_req_slot_when_req_to_token_is_sparse(self) -> None: + """sparse_permuted rtt: verify_slot_indices read directly from the constructed table.""" + rng = random.Random(7) + max_seq_len = 8 + max_reqs = 3 + rtt = make_req_to_token( + kind="sparse_permuted", + max_reqs=max_reqs, + max_seq_len=max_seq_len, + device=_DEVICE, + rng=rng, + ) + rp = 1 + prefix = 4 + req_pool_indices = _tensor([rp]) + prefix_lens = _tensor([prefix]) + extend_seq_lens = _tensor([1]) + extras = empty_extras() + verify_capacity, write_req_capacity = _alloc_for_inputs( + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + extras_count=0, + swa_window_size=0, + ) + + expected_slots = [int(rtt[rp, pos].item()) for pos in range(prefix)] + + for label in ("real", "ref"): + v_plan, _ = _run_label( + label=label, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + extras=extras, + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + ) + actual_slots = v_plan.verify_slot_indices[:prefix].detach().cpu().tolist() + assert ( + actual_slots == expected_slots + ), f"[{label}] sparse-rtt slots expected {expected_slots} got {actual_slots}" + + def test_padding_row_with_garbage_prefix_does_not_oob(self) -> None: + """rpi==0 padding row with absurd prefix_lens must not OOB-read req_to_token (row is skipped).""" + req_pool_indices = _tensor([1, 0, 2]) + prefix_lens = _tensor([5, 99999, 3]) + extend_seq_lens = _tensor([1, 99999, 1]) + rtt = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + extras = empty_extras() + verify_capacity, write_req_capacity = derive_plan_capacity( + kind="loose", total_verify=8, extras_count=0, bs=3 + ) + + for label in ("real", "ref"): + v_plan, w_plan = _run_label( + label=label, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + extras=extras, + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + ) + assert int(v_plan.verify_num_valid[0].item()) == 8, label + assert ( + int(w_plan.write_seed_slot_indices[1].item()) == -1 + ), f"[{label}] padding row seed must be -1" + PlanInvariants.assert_all( + verify_plan=v_plan, + write_plan=w_plan, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + swa_window_size=0, + extras_slot_indices=extras[0], + extras_positions=extras[1], + extras_prev_slot_indices=extras[2], + extras_count=0, + ) + + +class TestSwa: + def test_swa_window_clip_prefix_less_than_window(self) -> None: + """SWA: prefix=3 < window=128 → window_start=0, verify covers 3 entries (no clip).""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=512, device=_DEVICE + ) + # Identity LUT keeps slot indices unchanged after SWA translation. + full_pool_size = 4 * 512 + lut = torch.arange(full_pool_size + 1, dtype=torch.int64, device=_DEVICE) + plans = _plan_pair(verify_capacity=256, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + extend_seq_lens=_tensor([1]), + req_to_token=req_to_token, + extras=empty_extras(), + swa_window_size=128, + full_to_swa_index_mapping=lut, + ) + + assert int(plans[0][0].verify_num_valid[0].item()) == 3 + + def test_swa_window_clip_prefix_gt_window(self) -> None: + """SWA: prefix=200 > window=128 → window_start=72, verify covers 128 entries.""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=512, device=_DEVICE + ) + full_pool_size = 4 * 512 + lut = torch.arange(full_pool_size + 1, dtype=torch.int64, device=_DEVICE) + plans = _plan_pair(verify_capacity=512, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([200]), + extend_seq_lens=_tensor([1]), + req_to_token=req_to_token, + extras=empty_extras(), + swa_window_size=128, + full_to_swa_index_mapping=lut, + ) + + triton_v = plans[0][0] + assert int(triton_v.verify_num_valid[0].item()) == 128 + # First verify entry should be at position 72. + assert int(triton_v.verify_expected_positions[0].item()) == 72 + + def test_swa_lut_translates_verify_slots(self) -> None: + """FULL slot → SWA slot translation is performed inside the plan kernel for verify_slot_indices.""" + max_seq_len = 16 + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=max_seq_len, device=_DEVICE + ) + full_pool_size = 4 * max_seq_len + # Build a LUT that maps FULL slot S → SWA slot (S + 100) for every S; chosen so we can distinguish a + # translated value from a raw full slot. + lut = ( + torch.arange(full_pool_size + 1, dtype=torch.int64, device=_DEVICE) + 100 + ).contiguous() + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + extend_seq_lens=_tensor([1]), + req_to_token=req_to_token, + extras=empty_extras(), + swa_window_size=128, + full_to_swa_index_mapping=lut, + ) + + triton_v = plans[0][0] + # FULL slot for (rp=1, pos=0) = 1 * max_seq_len + 0 = 16; expected SWA slot = 16 + 100 = 116. + assert int(triton_v.verify_slot_indices[0].item()) == 1 * max_seq_len + 0 + 100 + assert int(triton_v.verify_slot_indices[1].item()) == 1 * max_seq_len + 1 + 100 + assert int(triton_v.verify_slot_indices[2].item()) == 1 * max_seq_len + 2 + 100 + + def test_swa_lut_translates_seed_slot(self) -> None: + """write_seed_slot_indices is also SWA-translated inside the plan kernel.""" + max_seq_len = 16 + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=max_seq_len, device=_DEVICE + ) + full_pool_size = 4 * max_seq_len + lut = ( + torch.arange(full_pool_size + 1, dtype=torch.int64, device=_DEVICE) + 100 + ).contiguous() + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + extend_seq_lens=_tensor([1]), + req_to_token=req_to_token, + extras=empty_extras(), + swa_window_size=128, + full_to_swa_index_mapping=lut, + ) + + triton_w = plans[0][1] + # FULL slot at (rp=1, pos=2) = 1 * max_seq_len + 2 = 18; expected SWA seed = 18 + 100 = 118. + assert ( + int(triton_w.write_seed_slot_indices[0].item()) == 1 * max_seq_len + 2 + 100 + ) + + def test_verify_covers_all_tokens_in_swa_window(self) -> None: + """SWA group with window=128 + bs=4 → verify_num_valid == Σ min(prefix_lens[r], 128).""" + window = 128 + prefix_values = [50, 128, 200, 1024] + max_seq_len = 2048 + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=max_seq_len, device=_DEVICE + ) + full_pool_size = 4 * max_seq_len + lut = torch.arange(full_pool_size + 1, dtype=torch.int64, device=_DEVICE) + plans = _plan_pair(verify_capacity=1024, write_req_capacity=8) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 2, 3, 1]), + prefix_lens=_tensor(prefix_values), + extend_seq_lens=_tensor([1, 1, 1, 1]), + req_to_token=req_to_token, + extras=empty_extras(), + swa_window_size=window, + full_to_swa_index_mapping=lut, + ) + + expected_total = sum(min(p, window) for p in prefix_values) + assert int(plans[0][0].verify_num_valid[0].item()) == expected_total + + +class TestNoExtras: + def test_plan_num_valid_counts_only_per_req_entries(self) -> None: + """Sweep extras are written directly into VerifyPlan; plan kernel does not append them.""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + extend_seq_lens=_tensor([1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_v = plans[0][0] + assert int(triton_v.verify_num_valid[0].item()) == 3 + + def test_zero_prefix_has_no_verify_entries(self) -> None: + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([0]), + extend_seq_lens=_tensor([5]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + assert int(plans[0][0].verify_num_valid[0].item()) == 0 + + def test_verify_capacity_just_fits_per_req_entries(self) -> None: + rp = 1 + prefix = 4 + req_pool_indices = _tensor([rp]) + prefix_lens = _tensor([prefix]) + extend_seq_lens = _tensor([1]) + rtt = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + + total_verify = prefix + verify_capacity, write_req_capacity = derive_plan_capacity( + kind="tight_match", + total_verify=total_verify, + extras_count=0, + bs=1, + ) + + for label in ("real", "ref"): + v_plan, _ = _run_label( + label=label, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + ) + n = int(v_plan.verify_num_valid[0].item()) + assert n == total_verify, f"[{label}] num_valid {n}" + assert int(v_plan.enable[0].item()) == 1 + + def test_verify_capacity_undershoot_by_one(self) -> None: + rp = 1 + prefix = 3 + req_pool_indices = _tensor([rp]) + prefix_lens = _tensor([prefix]) + extend_seq_lens = _tensor([1]) + rtt = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + + total_verify = prefix + verify_capacity, write_req_capacity = derive_plan_capacity( + kind="under_by_one", + total_verify=total_verify, + extras_count=0, + bs=1, + ) + + real_v, _ = _run_label( + label="real", + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + ) + ref_v, _ = _run_label( + label="ref", + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + extras=empty_extras(), + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + ) + n_real = int(real_v.verify_num_valid[0].item()) + n_ref = int(ref_v.verify_num_valid[0].item()) + assert n_real == n_ref, f"real {n_real} vs ref {n_ref} diverged under cap" + assert n_real == verify_capacity + assert int(real_v.enable[0].item()) == 0 + assert int(ref_v.enable[0].item()) == 0 + + +class TestMisc: + def test_zero_extend_writes_empty_write_plan(self) -> None: + """``extend_seq_lens`` all zero → write offsets stay zero; VerifyPlan still populated.""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 2]), + prefix_lens=_tensor([4, 6]), + extend_seq_lens=_tensor([0, 0]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_v, triton_w = plans[0] + # VerifyPlan covers 4+6 = 10 entries; write offsets are zero. + assert int(triton_v.verify_num_valid[0].item()) == 10 + # write_offsets cumsum of zeros stays zero across the active prefix. + assert int(triton_w.write_offsets[0].item()) == 0 + assert int(triton_w.write_offsets[1].item()) == 0 + assert int(triton_w.write_offsets[2].item()) == 0 + # Seeds for write-empty reqs must be -1 per plan semantics. + assert int(triton_w.write_seed_slot_indices[0].item()) == -1 + assert int(triton_w.write_seed_slot_indices[1].item()) == -1 + + def test_replay_same_inputs_yields_same_outputs(self) -> None: + """Two consecutive runs on identical inputs produce byte-equal plans (kernel is pure).""" + req_pool_indices = _tensor([1, 2, 3]) + prefix_lens = _tensor([4, 7, 2]) + extend_seq_lens = _tensor([2, 1, 3]) + rtt = make_req_to_token( + kind="linear", max_reqs=8, max_seq_len=16, device=_DEVICE + ) + extras = empty_extras() + verify_capacity, write_req_capacity = derive_plan_capacity( + kind="loose", total_verify=13, extras_count=0, bs=3 + ) + + for label in ("real", "ref"): + run1_v, run1_w = _run_label( + label=label, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + extras=extras, + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + ) + run2_v, run2_w = _run_label( + label=label, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=extend_seq_lens, + req_to_token=rtt, + extras=extras, + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=verify_capacity, + write_req_capacity=write_req_capacity, + ) + assert torch.equal( + run1_v.verify_slot_indices, run2_v.verify_slot_indices + ), label + assert torch.equal( + run1_v.verify_expected_positions, run2_v.verify_expected_positions + ), label + assert torch.equal( + run1_v.verify_prev_slot_indices, run2_v.verify_prev_slot_indices + ), label + assert torch.equal(run1_v.verify_num_valid, run2_v.verify_num_valid), label + assert torch.equal(run1_w.write_offsets, run2_w.write_offsets), label + assert torch.equal( + run1_w.write_seed_slot_indices, run2_w.write_seed_slot_indices + ), label + assert torch.equal( + run1_w.write_num_valid_reqs, run2_w.write_num_valid_reqs + ), label + + def test_shrink_bs_clears_stale_write_offsets(self) -> None: + """Reusing a WritePlan with smaller bs: write_offsets beyond new bs must be zeroed by the kernel.""" + rtt = make_req_to_token( + kind="linear", max_reqs=16, max_seq_len=16, device=_DEVICE + ) + verify_capacity, write_req_capacity = derive_plan_capacity( + kind="loose", total_verify=80, extras_count=0, bs=8 + ) + + for label in ("real", "ref"): + big_rpi = _tensor([1, 2, 3, 4, 5, 6, 7, 8]) + big_pfx = _tensor([10] * 8) + big_ext = _tensor([1] * 8) + small_rpi = _tensor([1, 2, 3]) + small_pfx = _tensor([5, 5, 5]) + small_ext = _tensor([1, 1, 1]) + + verify_plan = VerifyPlan.allocate( + verify_capacity=verify_capacity, device=_DEVICE + ).zero_for_testing_() + write_plan = WritePlan.allocate( + write_req_capacity=write_req_capacity, device=_DEVICE + ).zero_for_testing_() + runner = ( + launch_canary_plan_kernels + if label == "real" + else launch_canary_plan_kernels_torch_reference + ) + runner( + verify_plan_out=verify_plan, + write_plan_out=write_plan, + req_pool_indices=big_rpi, + prefix_lens=big_pfx, + extend_seq_lens=big_ext, + req_to_token=rtt, + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=verify_capacity, + req_to_verify_expected_tokens=None, + req_to_verify_expected_tokens_valid_lens=None, + kv_token_id_vs_position_offset=0, + ) + torch.cuda.synchronize() + runner( + verify_plan_out=verify_plan, + write_plan_out=write_plan, + req_pool_indices=small_rpi, + prefix_lens=small_pfx, + extend_seq_lens=small_ext, + req_to_token=rtt, + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=verify_capacity, + req_to_verify_expected_tokens=None, + req_to_verify_expected_tokens_valid_lens=None, + kv_token_id_vs_position_offset=0, + ) + torch.cuda.synchronize() + n_active = int(write_plan.write_num_valid_reqs[0].item()) + tail_offsets = ( + write_plan.write_offsets[n_active + 1 : 8].detach().cpu().tolist() + ) + assert all( + v == 0 for v in tail_offsets + ), f"[{label}] stale write_offsets tail not cleared: {tail_offsets}" + + +class TestVerifyContent: + def test_verify_num_valid_aggregate(self) -> None: + """``verify_num_valid == sum(per-req verify_count)``.""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 2, 3]), + prefix_lens=_tensor([2, 5, 4]), + extend_seq_lens=_tensor([1, 1, 1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + assert int(plans[0][0].verify_num_valid[0].item()) == 11 + + def test_verify_covers_all_tokens_no_skip(self) -> None: + """FULL group + bs=4 → verify_num_valid == Σ(prefix_lens) — every prefix token verified.""" + # Step: 4 reqs with mixed prefix and extend; FULL group means no SWA window clip. + prefix_values = [0, 3, 7, 12] + extend_values = [4, 1, 1, 1] + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=32, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=128, write_req_capacity=8) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 2, 3, 1]), + prefix_lens=_tensor(prefix_values), + extend_seq_lens=_tensor(extend_values), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + assert int(plans[0][0].verify_num_valid[0].item()) == sum(prefix_values) + + def test_plan_verify_expected_positions_strictly_increment_per_req(self) -> None: + """Per req, verify_expected_positions[verify_offsets[r]:verify_offsets[r+1]] == [window_start..prefix-1].""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=32, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 2]), + prefix_lens=_tensor([5, 8]), + extend_seq_lens=_tensor([1, 1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_v = plans[0][0] + # Req 0: positions [0..5); Req 1: positions [0..8). + req0_positions = triton_v.verify_expected_positions[:5].cpu().tolist() + req1_positions = triton_v.verify_expected_positions[5:13].cpu().tolist() + assert req0_positions == [0, 1, 2, 3, 4] + assert req1_positions == [0, 1, 2, 3, 4, 5, 6, 7] + + def test_write_num_valid_reqs_excludes_padding(self) -> None: + """Padding rows (rpi == 0) contribute zero to write_offsets so the write kernel does no work for them, but they ARE included in write_num_valid_reqs, which equals bs (the full batch size including padding).""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=16, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=8) + # bs=4, last two rows are padding. + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 2, 0, 0]), + prefix_lens=_tensor([3, 5, 99, 99]), + extend_seq_lens=_tensor([1, 1, 99, 99]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_w = plans[0][1] + # Padding rows must contribute 0 to write_offsets cumsum: [0, 1, 2, 2, 2]. + expected_write_offsets = [0, 1, 2, 2, 2] + for i, value in enumerate(expected_write_offsets): + assert int(triton_w.write_offsets[i].item()) == value + + +class TestByteEqual: + def test_byte_equal_python_reference(self) -> None: + """End-to-end Triton vs Python ref byte-equal across a representative bs=4 case (no SWA).""" + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=32, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=128, write_req_capacity=8) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 2, 3, 1]), + prefix_lens=_tensor([0, 3, 8, 15]), + extend_seq_lens=_tensor([4, 1, 1, 1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + def test_byte_equal_python_reference_hardcoded(self) -> None: + """bs=3, three prefix combinations → hand-computed verify_offsets / write_offsets / seed slots.""" + # Step 1: pin (prefix, extend) per req. + prefixes = [0, 4, 7] + extends = [3, 1, 1] + rps = [1, 2, 3] + max_seq_len = 16 + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=max_seq_len, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor(rps), + prefix_lens=_tensor(prefixes), + extend_seq_lens=_tensor(extends), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + triton_v, triton_w = plans[0] + # Step 2: hand-compute expected write_offsets (exclusive cumsum of extends) and verify_num_valid. + expected_write_offsets = [0, 3, 4, 5] + expected_verify_num_valid = sum(prefixes) + expected_seeds = [ + -1, # prefix=0 → no predecessor + rps[1] * max_seq_len + (prefixes[1] - 1), + rps[2] * max_seq_len + (prefixes[2] - 1), + ] + + for i, value in enumerate(expected_write_offsets): + assert ( + int(triton_w.write_offsets[i].item()) == value + ), f"write_offsets[{i}] expected {value} got {int(triton_w.write_offsets[i].item())}" + assert ( + int(triton_v.verify_num_valid[0].item()) == expected_verify_num_valid + ), f"verify_num_valid expected {expected_verify_num_valid}" + for i, expected_seed in enumerate(expected_seeds): + assert ( + int(triton_w.write_seed_slot_indices[i].item()) == expected_seed + ), f"write_seed_slot_indices[{i}] expected {expected_seed}" + + +class TestBoundarySweep: + @pytest.mark.parametrize("bs", [1, 31, 32, 33, 128]) + def test_bs_boundary_byte_equal_sweep(self, bs: int) -> None: + """Sweep bs boundary values around Triton block boundaries; assert Triton vs ref byte-equal.""" + req_pool_indices = list(range(1, bs + 1)) + prefix_lens = [10] * bs + extend_seq_lens = [1] * bs + max_seq_len = 32 + req_to_token = make_req_to_token( + kind="linear", max_reqs=bs + 1, max_seq_len=max_seq_len, device=_DEVICE + ) + + total_verify = sum(min(p, max_seq_len) for p in prefix_lens) + plans = _plan_pair( + verify_capacity=max(total_verify + 64, 256), write_req_capacity=bs + 4 + ) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor(req_pool_indices), + prefix_lens=_tensor(prefix_lens), + extend_seq_lens=_tensor(extend_seq_lens), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + @pytest.mark.parametrize("prefix_val", [0, 1, 127, 128, 129, 4096]) + def test_prefix_lens_boundary_byte_equal_sweep(self, prefix_val: int) -> None: + """Sweep prefix_lens boundary values; assert Triton vs ref byte-equal.""" + max_seq_len = max(prefix_val + 4, 256) + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=max_seq_len, device=_DEVICE + ) + total_verify = prefix_val + 10 + plans = _plan_pair( + verify_capacity=max(total_verify + 64, 256), write_req_capacity=8 + ) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1, 2]), + prefix_lens=_tensor([prefix_val, 10]), + extend_seq_lens=_tensor([1, 1]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + @pytest.mark.parametrize("extend_val", [1, 128, 4096]) + def test_extend_seq_lens_boundary_byte_equal_sweep(self, extend_val: int) -> None: + """Sweep extend_seq_lens boundary values; assert Triton vs ref byte-equal.""" + max_seq_len = max(extend_val + 4, 64) + req_to_token = make_req_to_token( + kind="linear", max_reqs=4, max_seq_len=max_seq_len, device=_DEVICE + ) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([0]), + extend_seq_lens=_tensor([extend_val]), + req_to_token=req_to_token, + extras=empty_extras(), + ) + + +class TestExpectedTokenPool: + """Cover the optional ``req_to_verify_expected_tokens`` pool input and + ``kv_token_id_vs_position_offset`` shift in the plan_entries kernel. + + Pool dtype is int32 with layout ``[max_reqs, pool_max_context_len]``. + For each verify entry the kernel gathers ``expected_input_id = + req_to_verify_expected_tokens[rp, position + offset]`` and writes ``-1`` as + a sentinel when the pool is absent or the gather index is out of range. + """ + + _MAX_SEQ_LEN = 16 + _MAX_REQS = 4 + _POOL_COLS = 16 + _DEFAULT = object() + + def setup_method(self) -> None: + self.req_to_token = make_req_to_token( + kind="linear", + max_reqs=self._MAX_REQS, + max_seq_len=self._MAX_SEQ_LEN, + device=_DEVICE, + ) + self.pool = self._make_pool(fill_fn=lambda rp, pos: rp * 1000 + pos) + + def _make_pool( + self, *, fill_fn, pool_max_context_len: int | None = None + ) -> torch.Tensor: + cols = self._POOL_COLS if pool_max_context_len is None else pool_max_context_len + pool = torch.full( + (self._MAX_REQS, cols), -999, dtype=torch.int32, device=_DEVICE + ) + for rp in range(self._MAX_REQS): + for pos in range(cols): + pool[rp, pos] = fill_fn(rp, pos) + return pool + + def _run( + self, + *, + req_pool_indices: torch.Tensor, + prefix_lens: torch.Tensor, + pool: object = _DEFAULT, + offset: int = 0, + swa_window_size: int = 0, + full_to_swa_index_mapping: torch.Tensor | None = None, + ) -> torch.Tensor: + """Run plan_diff with the per-class fixed inputs; return the expected_tokens slice up to verify_num_valid.""" + bs = int(req_pool_indices.shape[0]) + pool_arg = self.pool if pool is self._DEFAULT else pool + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=_tensor([1] * bs), + req_to_token=self.req_to_token, + extras=empty_extras(), + swa_window_size=swa_window_size, + full_to_swa_index_mapping=full_to_swa_index_mapping, + req_to_verify_expected_tokens=pool_arg, + kv_token_id_vs_position_offset=offset, + ) + triton_v = plans[0][0] + n_valid = int(triton_v.verify_num_valid[0].item()) + return triton_v.verify_expected_tokens[:n_valid] + + @staticmethod + def _expected(values: list[int]) -> torch.Tensor: + return torch.tensor(values, dtype=torch.int64, device=_DEVICE) + + def test_pool_disabled_writes_minus_one_sentinel(self) -> None: + """pool=None default path: every verify entry's expected_token slot is -1.""" + got = self._run( + req_pool_indices=_tensor([1, 2]), + prefix_lens=_tensor([3, 5]), + pool=None, + ) + assert got.shape[0] == 8 + assert torch.equal(got, self._expected([-1] * 8)) + + def test_pool_enabled_target_offset_0_byte_equal(self) -> None: + """offset=0 (target pool): expected_token[i] == pool[rp, position[i]].""" + got = self._run( + req_pool_indices=_tensor([1, 2]), + prefix_lens=_tensor([3, 5]), + ) + assert torch.equal( + got, + self._expected( + [ + rp * 1000 + pos + for rp, plen in [(1, 3), (2, 5)] + for pos in range(plen) + ] + ), + ) + + def test_pool_enabled_eagle_offset_plus_1_byte_equal(self) -> None: + """offset=+1 (EAGLE draft): expected_token[i] == pool[rp, position[i] + 1].""" + got = self._run( + req_pool_indices=_tensor([1, 2]), + prefix_lens=_tensor([3, 5]), + offset=1, + ) + assert torch.equal( + got, + self._expected( + [ + rp * 1000 + pos + 1 + for rp, plen in [(1, 3), (2, 5)] + for pos in range(plen) + ] + ), + ) + + def test_pool_oob_above_size0_writes_sentinel(self) -> None: + """positions whose ``position + offset`` exceed pool_max_context_len get -1; in-range slots stay correct.""" + pool_cols = 4 + small_pool = self._make_pool( + fill_fn=lambda rp, pos: rp * 1000 + pos, pool_max_context_len=pool_cols + ) + got = self._run( + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([6]), + pool=small_pool, + ) + assert torch.equal( + got, + self._expected([1000 + pos if pos < pool_cols else -1 for pos in range(6)]), + ) + + def test_pool_oob_offset_plus_1_byte_equal_triggers_sentinel(self) -> None: + """offset=+1 path that pushes the last entry past pool cols still byte-equals the ref (sentinel scatter).""" + pool_cols = 4 + small_pool = self._make_pool( + fill_fn=lambda rp, pos: rp * 1000 + pos, pool_max_context_len=pool_cols + ) + got = self._run( + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([4]), + pool=small_pool, + offset=1, + ) + assert torch.equal( + got, + self._expected( + [1000 + pos + 1 if pos + 1 < pool_cols else -1 for pos in range(4)] + ), + ) + + +class TestExpectedTokenPoolValidLens: + _MAX_SEQ_LEN = 16 + _MAX_REQS = 4 + _POOL_COLS = 16 + + def setup_method(self) -> None: + self.req_to_token = make_req_to_token( + kind="linear", + max_reqs=self._MAX_REQS, + max_seq_len=self._MAX_SEQ_LEN, + device=_DEVICE, + ) + self.pool = self._make_pool(fill_fn=lambda rp, pos: rp * 1000 + pos) + + def _make_pool(self, *, fill_fn) -> torch.Tensor: + pool = torch.full( + (self._MAX_REQS, self._POOL_COLS), -999, dtype=torch.int32, device=_DEVICE + ) + for rp in range(self._MAX_REQS): + for pos in range(self._POOL_COLS): + pool[rp, pos] = fill_fn(rp, pos) + return pool + + def _run( + self, + *, + req_pool_indices: torch.Tensor, + prefix_lens: torch.Tensor, + valid_lens: torch.Tensor, + pool: torch.Tensor | None = None, + offset: int = 0, + swa_window_size: int = 0, + full_to_swa_index_mapping: torch.Tensor | None = None, + ) -> torch.Tensor: + """Run plan_diff with the per-class fixed inputs; return the expected_tokens slice up to verify_num_valid.""" + bs = int(req_pool_indices.shape[0]) + plans = _plan_pair(verify_capacity=64, write_req_capacity=4) + run_plan_diff( + plan_pair=plans, + req_pool_indices=req_pool_indices, + prefix_lens=prefix_lens, + extend_seq_lens=_tensor([1] * bs), + req_to_token=self.req_to_token, + extras=empty_extras(), + swa_window_size=swa_window_size, + full_to_swa_index_mapping=full_to_swa_index_mapping, + req_to_verify_expected_tokens=self.pool if pool is None else pool, + req_to_verify_expected_tokens_valid_lens=valid_lens, + kv_token_id_vs_position_offset=offset, + ) + triton_v = plans[0][0] + n_valid = int(triton_v.verify_num_valid[0].item()) + return triton_v.verify_expected_tokens[:n_valid] + + @staticmethod + def _expected(values: list[int]) -> torch.Tensor: + return torch.tensor(values, dtype=torch.int64, device=_DEVICE) + + def test_valid_lens_boundary_emits_sentinel_at_limit(self) -> None: + """sot_pos == valid_lens[r] is OUT of range; the kernel must emit -1 even though the pool has a real value at that slot.""" + got = self._run( + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + valid_lens=_tensor([2]), + ) + assert torch.equal(got, self._expected([1000, 1001, -1])) + + def test_valid_lens_within_limit_reads_pool(self) -> None: + """sot_pos == valid_lens[r] - 1 is IN range; the kernel must gather the pool value, not -1.""" + got = self._run( + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + valid_lens=_tensor([3]), + ) + assert torch.equal(got, self._expected([1000, 1001, 1002])) + + def test_valid_lens_mixed_across_reqs(self) -> None: + """Per-req different valid_lens in one batch: each req's gather is bounded by its own lens, not the batch max.""" + got = self._run( + req_pool_indices=_tensor([1, 2]), + prefix_lens=_tensor([3, 3]), + valid_lens=_tensor([2, 4]), + ) + assert torch.equal(got, self._expected([1000, 1001, -1, 2000, 2001, 2002])) + + def test_valid_lens_zero_emits_all_sentinel_for_that_req(self) -> None: + """valid_lens[r] == 0 disables every gather for req r regardless of pool content.""" + got = self._run( + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + valid_lens=_tensor([0]), + ) + assert torch.equal(got, self._expected([-1, -1, -1])) + + def test_valid_lens_masks_stale_pool_data_above_bound(self) -> None: + """Pool has realistic-looking values past valid_lens (the recycled-slot motivation): kernel still emits -1 for them.""" + # Positions 2..15 carry a longer previous owner's leftover token; the bound must hide them. + stale_pool = self._make_pool( + fill_fn=lambda rp, pos: 7777 if pos >= 2 else (rp * 1000 + pos), + ) + got = self._run( + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([5]), + valid_lens=_tensor([2]), + pool=stale_pool, + ) + assert torch.equal(got, self._expected([1000, 1001, -1, -1, -1])) + + def test_valid_lens_with_offset_plus_1_bounds_after_shift(self) -> None: + """``sot_pos = position + offset`` is compared against valid_lens; the offset shifts before the bound check.""" + # sot_pos for positions 0,1,2 is 1,2,3. valid_lens=2 → only sot_pos=1 reads pool. + got = self._run( + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + valid_lens=_tensor([2]), + offset=1, + ) + assert torch.equal(got, self._expected([1001, -1, -1])) + + def test_valid_lens_applies_under_swa_window(self) -> None: + """SWA-windowed verify entries are bounded by valid_lens the same way as the FULL pool path.""" + # prefix=5, swa_window=3 → entries cover positions 2,3,4. valid_lens=4 admits pos 2,3 only. + got = self._run( + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([5]), + valid_lens=_tensor([4]), + swa_window_size=3, + full_to_swa_index_mapping=make_lut( + kind="identity", + pool_size=self._MAX_REQS * self._MAX_SEQ_LEN, + device=_DEVICE, + ), + ) + assert torch.equal(got, self._expected([1002, 1003, -1])) + + def test_pool_set_but_valid_lens_missing_raises(self) -> None: + """One-way contract: passing the pool without per-req valid_lens is rejected at the Python wrapper.""" + triton_v, triton_w = _plan_pair(verify_capacity=64, write_req_capacity=4)[0] + with pytest.raises( + ValueError, match="req_to_verify_expected_tokens_valid_lens" + ): + launch_canary_plan_kernels( + verify_plan_out=triton_v, + write_plan_out=triton_w, + req_pool_indices=_tensor([1]), + prefix_lens=_tensor([3]), + extend_seq_lens=_tensor([1]), + req_to_token=self.req_to_token, + swa_window_size=0, + full_to_swa_index_mapping=None, + verify_capacity=int(triton_v.verify_slot_indices.shape[0]), + req_to_verify_expected_tokens=self.pool, + req_to_verify_expected_tokens_valid_lens=None, + kv_token_id_vs_position_offset=0, + ) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_scatter_req_token_ids.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_scatter_req_token_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..ae7fc6353384e173537e7a5ab18a5f11dc9a7fae --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_scatter_req_token_ids.py @@ -0,0 +1,279 @@ +from __future__ import annotations + +import random +import unittest + +import torch + +from sglang.jit_kernel.kv_canary.scatter_req_token_ids import ( + _SCATTER_BATCH_BLOCK, + launch_scatter_req_token_ids_kernel, + scatter_req_token_ids_torch_reference, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=10, stage="jit-kernel-unit", runner_config="amd") + + +_DEVICE = torch.device("cuda") + + +def _build_pool(*, max_reqs: int, max_context_len: int) -> torch.Tensor: + return torch.zeros((max_reqs, max_context_len), dtype=torch.int32, device=_DEVICE) + + +def _build_offsets(lens: list[int]) -> torch.Tensor: + cumsum = [0] + for n in lens: + cumsum.append(cumsum[-1] + n) + return torch.tensor(cumsum, dtype=torch.int64, device=_DEVICE) + + +def _build_flat(seqs: list[list[int]]) -> torch.Tensor: + flat: list[int] = [] + for s in seqs: + flat.extend(s) + return torch.tensor(flat, dtype=torch.int64, device=_DEVICE) + + +class TestScatterReqTokenIds(CustomTestCase): + def test_scatter_byte_equal_basic(self) -> None: + """Triton output matches the PyTorch reference for a small mixed batch.""" + seqs = [[10, 20, 30], [40, 50], [60, 70, 80, 90]] + lens = [len(s) for s in seqs] + rp = [3, 1, 5] + + flat = _build_flat(seqs) + offsets = _build_offsets(lens) + req_pool_indices = torch.tensor(rp, dtype=torch.int64, device=_DEVICE) + triton_pool = _build_pool(max_reqs=8, max_context_len=16) + ref_pool = _build_pool(max_reqs=8, max_context_len=16) + + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=triton_pool, + ) + scatter_req_token_ids_torch_reference( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=ref_pool, + ) + torch.cuda.synchronize() + + self.assertTrue(torch.equal(triton_pool, ref_pool)) + # Spot-check: req in slot 3 holds [10,20,30,0,0,...] etc. + self.assertEqual(triton_pool[3, :3].tolist(), [10, 20, 30]) + self.assertEqual(triton_pool[1, :2].tolist(), [40, 50]) + self.assertEqual(triton_pool[5, :4].tolist(), [60, 70, 80, 90]) + + def test_scatter_empty_batch_no_op(self) -> None: + """Empty input (num_tokens == 0) returns without touching the pool.""" + flat = torch.empty(0, dtype=torch.int64, device=_DEVICE) + offsets = torch.zeros(1, dtype=torch.int64, device=_DEVICE) + req_pool_indices = torch.empty(0, dtype=torch.int64, device=_DEVICE) + pool = _build_pool(max_reqs=8, max_context_len=16) + pool_before = pool.clone() + + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=pool, + ) + torch.cuda.synchronize() + self.assertTrue(torch.equal(pool, pool_before)) + + def test_scatter_single_req(self) -> None: + """One req with a full row of tokens writes byte-equal to the reference.""" + seqs = [list(range(10))] + lens = [10] + rp = [2] + + flat = _build_flat(seqs) + offsets = _build_offsets(lens) + req_pool_indices = torch.tensor(rp, dtype=torch.int64, device=_DEVICE) + triton_pool = _build_pool(max_reqs=4, max_context_len=16) + ref_pool = _build_pool(max_reqs=4, max_context_len=16) + + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=triton_pool, + ) + scatter_req_token_ids_torch_reference( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=ref_pool, + ) + torch.cuda.synchronize() + self.assertTrue(torch.equal(triton_pool, ref_pool)) + + def test_scatter_truncates_at_max_context_len(self) -> None: + """Tokens past the pool's max_context_len are silently dropped (no row spill).""" + # Two reqs; first req longer than max_context_len. Second req must remain + # uncorrupted. + seqs = [list(range(20)), [777, 888, 999]] + lens = [len(s) for s in seqs] + rp = [1, 2] + max_context_len = 8 + + flat = _build_flat(seqs) + offsets = _build_offsets(lens) + req_pool_indices = torch.tensor(rp, dtype=torch.int64, device=_DEVICE) + pool = _build_pool(max_reqs=4, max_context_len=max_context_len) + + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=pool, + ) + torch.cuda.synchronize() + + self.assertEqual( + pool[1, :max_context_len].tolist(), list(range(max_context_len)) + ) + self.assertEqual(pool[2, :3].tolist(), [777, 888, 999]) + + def test_scatter_mixed_empty_and_nonempty_reqs(self) -> None: + """Middle req has length 0 between two non-empty reqs: pool rows are byte-equal and untouched rows stay zero.""" + seqs = [[1, 2], [], [3, 4, 5]] + lens = [len(s) for s in seqs] + rp = [2, 4, 6] + + flat = _build_flat(seqs) + offsets = _build_offsets(lens) + req_pool_indices = torch.tensor(rp, dtype=torch.int64, device=_DEVICE) + triton_pool = _build_pool(max_reqs=8, max_context_len=8) + ref_pool = _build_pool(max_reqs=8, max_context_len=8) + + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=triton_pool, + ) + scatter_req_token_ids_torch_reference( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=ref_pool, + ) + torch.cuda.synchronize() + + self.assertTrue(torch.equal(triton_pool, ref_pool)) + # Middle req contributes nothing; its pool row stays zero. + zero_row = torch.zeros(8, dtype=torch.int32, device=_DEVICE) + self.assertTrue(torch.equal(triton_pool[4], zero_row)) + # First and third reqs are written to their respective rows. + self.assertEqual(triton_pool[2, :2].tolist(), [1, 2]) + self.assertEqual(triton_pool[6, :3].tolist(), [3, 4, 5]) + + def test_scatter_random_byte_equal(self) -> None: + """Randomized fuzz across bs, seq lengths, and req pool indices.""" + rng = random.Random(0) + max_reqs = 64 + max_context_len = 32 + + for _ in range(8): + bs = rng.randint(1, 16) + lens = [rng.randint(0, max_context_len) for _ in range(bs)] + # All distinct req pool indices in [1, max_reqs) + rp = rng.sample(range(1, max_reqs), k=bs) + seqs = [[rng.randint(0, 1 << 30) for _ in range(n)] for n in lens] + + flat = _build_flat(seqs) + offsets = _build_offsets(lens) + req_pool_indices = torch.tensor(rp, dtype=torch.int64, device=_DEVICE) + triton_pool = _build_pool( + max_reqs=max_reqs, max_context_len=max_context_len + ) + ref_pool = _build_pool(max_reqs=max_reqs, max_context_len=max_context_len) + + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=triton_pool, + ) + scatter_req_token_ids_torch_reference( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=ref_pool, + ) + torch.cuda.synchronize() + self.assertTrue(torch.equal(triton_pool, ref_pool)) + + +class TestScatterInputValidation(CustomTestCase): + """Cover the strict input checks in launch_scatter_req_token_ids_kernel.""" + + def test_raises_on_2d_flat_in(self) -> None: + """A 2-D flat_in tensor triggers a ValueError before any kernel launch.""" + flat = torch.zeros((2, 2), dtype=torch.int64, device=_DEVICE) + offsets = torch.tensor([0, 1, 2], dtype=torch.int64, device=_DEVICE) + req_pool_indices = torch.tensor([1, 2], dtype=torch.int64, device=_DEVICE) + pool = _build_pool(max_reqs=4, max_context_len=4) + with self.assertRaises(ValueError): + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=pool, + ) + + def test_raises_on_wrong_dtype_pool(self) -> None: + """A pool_out with non-int32 dtype triggers a TypeError.""" + flat = torch.tensor([10, 20], dtype=torch.int64, device=_DEVICE) + offsets = torch.tensor([0, 2], dtype=torch.int64, device=_DEVICE) + req_pool_indices = torch.tensor([1], dtype=torch.int64, device=_DEVICE) + pool = torch.zeros((4, 4), dtype=torch.int64, device=_DEVICE) + with self.assertRaises(TypeError): + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=pool, + ) + + def test_raises_on_offsets_len_mismatch(self) -> None: + """offsets.shape[0] must equal bs + 1; mismatch triggers a ValueError.""" + flat = torch.tensor([10, 20], dtype=torch.int64, device=_DEVICE) + # bs = 2 but offsets has length 2 instead of 3. + offsets = torch.tensor([0, 2], dtype=torch.int64, device=_DEVICE) + req_pool_indices = torch.tensor([1, 2], dtype=torch.int64, device=_DEVICE) + pool = _build_pool(max_reqs=4, max_context_len=4) + with self.assertRaises(ValueError): + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=pool, + ) + + def test_raises_on_bs_plus_one_exceeds_batch_block(self) -> None: + """bs+1 must fit in _SCATTER_BATCH_BLOCK; exceeding it triggers a ValueError.""" + bs = _SCATTER_BATCH_BLOCK + flat = torch.empty(0, dtype=torch.int64, device=_DEVICE) + offsets = torch.zeros(bs + 1, dtype=torch.int64, device=_DEVICE) + req_pool_indices = torch.zeros(bs, dtype=torch.int64, device=_DEVICE) + pool = _build_pool(max_reqs=4, max_context_len=4) + with self.assertRaises(ValueError): + launch_scatter_req_token_ids_kernel( + flat_in=flat, + offsets=offsets, + req_pool_indices=req_pool_indices, + pool_out=pool, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_utils.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e660ea74ac5ed7215dba20b1dab42e563700cba8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_utils.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from sglang.jit_kernel.benchmark.kv_canary.utils import ( + MAX_EXTEND_TOKENS_PER_FORWARD, + build_fast_matrix_cases, + build_full_matrix_cases, + cases_to_x_vals, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=3, stage="base-a", runner_config="cpu") + + +def test_fast_matrix_cases_include_e2e_decode_and_chunked_prefill_scenarios() -> None: + cases = build_fast_matrix_cases() + scenarios = {case.scenario for case in cases} + + assert { + "e2e_decode_steady", + "e2e_decode_tail", + "e2e_prefill_chunk_first", + "e2e_prefill_chunk_second", + "e2e_prefill_chunk_mid", + "e2e_prefill_chunk_last", + } <= scenarios + + +def test_extend_cases_are_bounded_to_scheduler_chunk_size() -> None: + cases = build_full_matrix_cases() + bad_cases = [ + case + for case in cases + if case.mode == "extend" + and case.bs * case.extend_len > MAX_EXTEND_TOKENS_PER_FORWARD + ] + + assert bad_cases == [] + + +def test_cases_to_x_vals_includes_scenario_axis() -> None: + case = build_fast_matrix_cases()[0] + + x_vals = cases_to_x_vals([case]) + + assert x_vals == [ + ( + case.scenario, + case.bs, + case.prefix_len, + case.mode, + case.extend_len, + case.pool_kind, + case.real_kv_kind, + case.hash_mode, + ) + ] + + +if __name__ == "__main__": + import sys + + import pytest + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_verify_fuzz.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_verify_fuzz.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f9497a953880686d97c3da1df74696fc03d00c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_verify_fuzz.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import random +from dataclasses import dataclass + +import pytest +import torch + +from sglang.jit_kernel.kv_canary import consts +from sglang.jit_kernel.kv_canary.verify import ( + CanaryLaunchTag, + RealKvSource, + VerifyPlan, +) +from sglang.jit_kernel.tests.kv_canary._canary_helpers import ( + FakeViolationLog, + make_canary_buf, + make_log_pair, + make_verify_plan_pair, + stamp_clean_chain, +) +from sglang.jit_kernel.tests.kv_canary._differential import _run_both_verify +from sglang.jit_kernel.tests.kv_canary._fixtures import ( + clone_real_kv_sources, + make_real_kv_sources, +) +from sglang.jit_kernel.tests.kv_canary._fuzz_driver import ( + FUZZ_SEEDS_PR, + run_fuzz_combo, +) +from sglang.jit_kernel.tests.kv_canary._invariants import VerifyInvariants +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + + +_DEVICE = torch.device("cuda") + +_FUZZ_ITER_PER_SEED = 30 + + +@dataclass(frozen=True, slots=True, kw_only=True) +class VerifyFuzzInputs: + cuda_canary_buf: torch.Tensor + ref_canary_buf: torch.Tensor + plan_cuda: VerifyPlan + plan_ref: VerifyPlan + kernel_kind: CanaryLaunchTag + real_kv_sources_cuda: tuple[RealKvSource, ...] + real_kv_sources_ref: tuple[RealKvSource, ...] + real_kv_hash_mode: consts.RealKvHashMode + ring_capacity: int + check_verify_expected_token: bool + + +def _draw_random_verify_inputs(rng: random.Random) -> VerifyFuzzInputs: + hash_mode = rng.choice( + [ + consts.RealKvHashMode.NONE, + consts.RealKvHashMode.PARTIAL, + consts.RealKvHashMode.ALL, + ] + ) + src_count = rng.choice([1, 2, 4]) + page_size = rng.choice([1, 16]) + bytes_per = rng.choice([16, 64, 128]) + kernel_kind = rng.choice(list(CanaryLaunchTag)) + plan_size = rng.randint(0, 32) + num_slots = max(plan_size + 8, 16) + ring_capacity = rng.choice([16, 64, 256]) + + sources_cuda = make_real_kv_sources( + count=src_count, + num_bytes_per_token=bytes_per, + page_size=page_size, + num_slots=num_slots, + device=_DEVICE, + rng=rng, + ) + sources_ref = clone_real_kv_sources(sources_cuda) + + cuda_buf = make_canary_buf( + num_slots=num_slots, slot_stride_bytes=32, device=_DEVICE + ) + ref_buf = cuda_buf.clone() + + slot_universe = list(range(1, num_slots)) + rng.shuffle(slot_universe) + slot_indices = slot_universe[:plan_size] + tokens = [rng.randint(0, 0xFFFFFFFF) for _ in range(plan_size)] + positions = list(range(plan_size)) + prev_slot_indices: list[int] = [] + for i in range(plan_size): + if i == 0: + prev_slot_indices.append(-1) + else: + prev_slot_indices.append(slot_indices[i - 1]) + + if hash_mode == consts.RealKvHashMode.NONE and plan_size > 0: + stamp_clean_chain( + cuda_buf=cuda_buf, + ref_buf=ref_buf, + slot_indices=slot_indices, + tokens=tokens, + positions=positions, + ) + + # Inject prev_slot == TOKEN_TO_KV_SLOT_PADDING into ~15% of entries so the differential + # harness exercises the chain-check-skip branch (added for SWA-evicted ancestor handling). + # Done AFTER stamp_clean_chain so the stored prev_hash on those slots is still chain-clean; + # the kernel must rely on prev_slot==padding (not on stored hash) to decide whether to skip. + for i in range(plan_size): + if rng.random() < 0.15: + prev_slot_indices[i] = consts.TOKEN_TO_KV_SLOT_PADDING + + check_verify_expected_token = rng.random() < 0.5 + expected_input_ids: list[int] = [] + for i in range(plan_size): + # Always pick a value; with check=False the kernel must not deref this column. + if rng.random() < 0.3: + expected_input_ids.append(-1) + elif rng.random() < 0.5: + expected_input_ids.append(int(tokens[i])) + else: + mutated = (int(tokens[i]) ^ 0x1) & 0xFFFFFFFF + expected_input_ids.append(mutated) + + plan_cuda, plan_ref = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=prev_slot_indices, + expected_input_ids=expected_input_ids if plan_size > 0 else None, + capacity=max(plan_size, 1), + device=_DEVICE, + ) + + return VerifyFuzzInputs( + cuda_canary_buf=cuda_buf, + ref_canary_buf=ref_buf, + plan_cuda=plan_cuda, + plan_ref=plan_ref, + kernel_kind=kernel_kind, + real_kv_sources_cuda=sources_cuda, + real_kv_sources_ref=sources_ref, + real_kv_hash_mode=hash_mode, + ring_capacity=ring_capacity, + check_verify_expected_token=check_verify_expected_token, + ) + + +def _run_one(inputs: VerifyFuzzInputs) -> None: + cuda_buf_before = inputs.cuda_canary_buf.clone() + cuda_log, ref_log = make_log_pair(capacity=inputs.ring_capacity, device=_DEVICE) + log_before = FakeViolationLog.allocate( + capacity=inputs.ring_capacity, device=_DEVICE + ) + _run_both_verify( + cuda_canary_buf=inputs.cuda_canary_buf, + ref_canary_buf=inputs.ref_canary_buf, + plan_cuda=inputs.plan_cuda, + plan_ref=inputs.plan_ref, + cuda_log=cuda_log, + ref_log=ref_log, + real_kv_sources_cuda=inputs.real_kv_sources_cuda, + real_kv_sources_ref=inputs.real_kv_sources_ref, + real_kv_hash_mode=inputs.real_kv_hash_mode, + kernel_kind=inputs.kernel_kind, + assert_equal=False, + check_verify_expected_token=inputs.check_verify_expected_token, + ) + assert int(cuda_log.kernel_run_counter[0].item()) == int( + ref_log.kernel_run_counter[0].item() + ) + assert int(cuda_log.slot_run_counter[0].item()) == int( + ref_log.slot_run_counter[0].item() + ) + assert int(cuda_log.write_index[0].item()) == int(ref_log.write_index[0].item()) + VerifyInvariants.assert_all( + canary_buf_before=cuda_buf_before, + canary_buf_after=inputs.cuda_canary_buf, + log_before=log_before, + log_after=cuda_log, + plan=inputs.plan_cuda, + kernel_kind=inputs.kernel_kind, + ) + + +def _summarize(inputs: VerifyFuzzInputs) -> str: + n_active = int(inputs.plan_cuda.verify_num_valid[0].item()) + return ( + f"plan_size={n_active} kind={inputs.kernel_kind.name} " + f"hash_mode={inputs.real_kv_hash_mode.name} " + f"sources={len(inputs.real_kv_sources_cuda)} " + f"ring={inputs.ring_capacity} " + f"check_token={inputs.check_verify_expected_token}" + ) + + +@pytest.mark.parametrize("seed", FUZZ_SEEDS_PR) +def test_verify_fuzz_full_combo(seed: int) -> None: + """Multi-dim verify fuzzer: random hash mode × kernel kind × page × bytes × N iters, byte-equal.""" + run_fuzz_combo( + seed, + draw_fn=_draw_random_verify_inputs, + run_one_fn=_run_one, + summarize_fn=_summarize, + n_iter=_FUZZ_ITER_PER_SEED, + ) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_verify_hand.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_verify_hand.py new file mode 100644 index 0000000000000000000000000000000000000000..861d913da128896c9efcc5781e7c45c631eee94a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_verify_hand.py @@ -0,0 +1,1928 @@ +from __future__ import annotations + +import random +import struct +from dataclasses import dataclass +from typing import Callable + +import pytest +import torch + +from sglang.jit_kernel.kv_canary import consts +from sglang.jit_kernel.kv_canary.consts import splitmix64, splitmix64_mix3 +from sglang.jit_kernel.kv_canary.verify import ( + CanaryLaunchTag, + RealKvSource, + VerifyOrWriteContext, + VerifyPlan, + launch_canary_verify_kernel, +) +from sglang.jit_kernel.kv_canary.verify_ref import ( + _compute_real_kv_hash_scalar, + launch_canary_verify_kernel_torch_reference, +) +from sglang.jit_kernel.kv_canary.write_ref import ( + launch_canary_write_kernel_torch_reference, +) +from sglang.jit_kernel.tests.kv_canary._canary_helpers import ( + FakeViolationLog, + assert_only_bits_set, + chain_anchor_signed, + make_canary_buf, + make_canary_buf_pair, + make_log_pair, + make_real_kv_source, + make_real_kv_sources, + make_verify_plan, + make_verify_plan_pair, + make_write_plan, + read_slot_fields, + stamp_clean_chain, + stamp_pair, + to_signed_int64, + write_slot_fields, +) +from sglang.jit_kernel.tests.kv_canary._differential import ( + _run_both_verify, + run_verify_diff, +) +from sglang.jit_kernel.tests.kv_canary._fixtures import clone_real_kv_sources +from sglang.jit_kernel.tests.kv_canary._hand_oracle import ( + _hand_fold_all, + _hand_fold_partial, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + + +_DEVICE = torch.device("cuda") + + +# --------------------------------------------------------------------------- +# Shared per-test scaffolding helpers. +# --------------------------------------------------------------------------- + + +def _buf_pair( + num_slots: int = 16, slot_stride_bytes: int = 32 +) -> tuple[torch.Tensor, torch.Tensor]: + return make_canary_buf_pair( + num_slots=num_slots, slot_stride_bytes=slot_stride_bytes, device=_DEVICE + ) + + +def _stamp_head( + buf_pair: tuple[torch.Tensor, torch.Tensor], + *, + slot_idx: int, + token: int = 42, + position: int = 0, + prev_hash: int | None = None, + real_kv_hash: int = 0, +) -> None: + """``stamp_pair`` with ``prev_hash`` defaulting to ``chain_anchor_signed()`` (the chain-head value).""" + stamp_pair( + buf_pair, + slot_idx=slot_idx, + token=token, + position=position, + prev_hash=chain_anchor_signed() if prev_hash is None else prev_hash, + real_kv_hash=real_kv_hash, + ) + + +def _plan_pair_single( + *, + slot_idx: int, + position: int, + prev_slot_idx: int = -1, + expected_input_id: int | None = None, + capacity: int | None = None, +) -> tuple[VerifyPlan, VerifyPlan]: + """Single-entry verify plan pair, with optional expected_input_id (None → default sentinel).""" + expected = None if expected_input_id is None else [expected_input_id] + return make_verify_plan_pair( + slot_indices=[slot_idx], + positions=[position], + prev_slot_indices=[prev_slot_idx], + expected_input_ids=expected, + capacity=capacity, + device=_DEVICE, + ) + + +def _n_violations(log: FakeViolationLog) -> int: + return int(log.write_index[0].item()) + + +def _fail_bits(log: FakeViolationLog, row: int = 0) -> int: + return int(log.ring[row, consts.VIOLATION_FIELD_FAIL_REASON_BITS].item()) + + +def _run_both_verify_no_rkv( + *, + buf_pair: tuple[torch.Tensor, torch.Tensor], + plan_pair: tuple[VerifyPlan, VerifyPlan], + cuda_log: FakeViolationLog, + ref_log: FakeViolationLog, + assert_equal: bool = True, + kernel_kind: CanaryLaunchTag = CanaryLaunchTag.HEAD_K_FULL, +) -> None: + """``_run_both_verify`` with empty real_kv sources / NONE mode — the most common in-place verify run.""" + _run_both_verify( + cuda_canary_buf=buf_pair[0], + ref_canary_buf=buf_pair[1], + plan_cuda=plan_pair[0], + plan_ref=plan_pair[1], + cuda_log=cuda_log, + ref_log=ref_log, + real_kv_sources_cuda=(), + real_kv_sources_ref=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + kernel_kind=kernel_kind, + assert_equal=assert_equal, + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class _VerifySingleSlotInput: + token: int = 42 + position: int = 0 + stored_prev_hash_signed: int + stored_real_kv_hash_signed: int = 0 + real_kv_sources: tuple[RealKvSource, ...] = () + real_kv_hash_mode: consts.RealKvHashMode = consts.RealKvHashMode.NONE + + +def _run_verify_single_slot_byte_equal(case: _VerifySingleSlotInput) -> None: + buf_pair = _buf_pair() + stamp_pair( + buf_pair, + slot_idx=1, + token=case.token, + position=case.position, + prev_hash=case.stored_prev_hash_signed, + real_kv_hash=case.stored_real_kv_hash_signed, + ) + sources_cuda = case.real_kv_sources + sources_ref = clone_real_kv_sources(sources_cuda) + plan_pair = _plan_pair_single(slot_idx=1, position=case.position) + run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=case.real_kv_hash_mode, + ) + + +def _stamp_clean_kv_chain( + *, + buf_pair: tuple[torch.Tensor, torch.Tensor], + sources_cuda: tuple[RealKvSource, ...], + input_ids: torch.Tensor, + positions: torch.Tensor, + out_cache_loc: torch.Tensor, + real_kv_hash_mode: consts.RealKvHashMode, +) -> None: + """Use the Python write ref impl to populate the canary buf for a fresh chain. + + Lets verify tests start from a known-good chain without re-implementing splitmix64 by hand. + """ + n = int(input_ids.shape[0]) + cuda_buf, ref_buf = buf_pair + write_plan = make_write_plan( + write_offsets=[0, n], + seed_slot_indices=[-1], + num_valid_reqs=1, + device=_DEVICE, + ) + log = FakeViolationLog.allocate(device=_DEVICE) + # enable_write_input_assert=False is hard-wired here, so the kernel API requires the + # expected_* tensors be None (otherwise it raises ValueError). + launch_canary_write_kernel_torch_reference( + context=VerifyOrWriteContext( + canary_buf=cuda_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=sources_cuda, + real_kv_hash_mode=real_kv_hash_mode, + ), + plan=write_plan, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + enable_write_input_assert=False, + expected_input_tokens=None, + expected_input_positions=None, + ) + ref_buf.copy_(cuda_buf) + + +# --------------------------------------------------------------------------- +# Kernel-contract invariants. +# --------------------------------------------------------------------------- + + +class TestChain: + def test_chain_head_anchor(self) -> None: + """``prev_slot_idx == -1`` → kernel uses ``splitmix64(consts.CANARY_CHAIN_ANCHOR)`` as the expected prev_hash.""" + # Step 1: stamp slot 5 such that stored.prev_hash already equals splitmix64(consts.CANARY_CHAIN_ANCHOR). + buf_pair = _buf_pair() + _stamp_head(buf_pair, slot_idx=5) + + # Step 2: a single-entry plan with prev_slot_idx = -1 should record no violation. + plan_pair = _plan_pair_single(slot_idx=5, position=0) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + assert _n_violations(cuda_log) == 0 + + def test_chain_link_byte_equal_5_step(self) -> None: + """5-step chain, CUDA vs ref byte-equal across ring / counters / canary_buf (read-only).""" + cuda_buf, ref_buf = _buf_pair() + slot_indices = [1, 2, 3, 4, 5] + tokens = [11, 22, 33, 44, 55] + positions = [0, 1, 2, 3, 4] + stamp_clean_chain( + cuda_buf=cuda_buf, + ref_buf=ref_buf, + tokens=tokens, + positions=positions, + slot_indices=slot_indices, + ) + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=[-1, 1, 2, 3, 4], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff(buf_pair=(cuda_buf, ref_buf), plan_pair=plan_pair) + assert _n_violations(cuda_log) == 0 + + def test_chain_link_byte_equal_5_step_hardcoded(self) -> None: + """5-step chain with hand-computed splitmix64 expected sequence; defends against ref + CUDA co-drift.""" + tokens = [101, 202, 303, 404, 505] + positions = [0, 1, 2, 3, 4] + slot_indices = [1, 2, 3, 4, 5] + real_kv_hashes = [0, 0, 0, 0, 0] + + # Step 1: compute the expected stored prev_hash sequence in pure Python via splitmix64. + expected_prev_hashes_u64: list[int] = [] + running = splitmix64(consts.CANARY_CHAIN_ANCHOR) + for token, position, real_kv_hash in zip(tokens, positions, real_kv_hashes): + expected_prev_hashes_u64.append(running) + running = splitmix64_mix3(running, token, position) + expected_prev_hashes_signed = [ + to_signed_int64(h) for h in expected_prev_hashes_u64 + ] + + # Step 2: stamp each slot manually with the hardcoded expected prev_hash. + buf_pair = _buf_pair() + cuda_buf, _ = buf_pair + for slot_idx, token, position, prev_hash in zip( + slot_indices, tokens, positions, expected_prev_hashes_signed + ): + stamp_pair( + buf_pair, + slot_idx=slot_idx, + token=token, + position=position, + prev_hash=prev_hash, + ) + + # Step 3: verify the 5-step chain — no violation expected and the ref vs CUDA state byte-equal. + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=[-1, 1, 2, 3, 4], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + + assert _n_violations(cuda_log) == 0 + + # Step 4: also independently confirm the *stored* prev_hash at each slot matches the hardcoded sequence. + for slot_idx, expected_signed in zip(slot_indices, expected_prev_hashes_signed): + _, _, stored_prev_hash, _ = read_slot_fields( + canary_buf=cuda_buf, slot_idx=slot_idx + ) + assert stored_prev_hash == expected_signed + + def test_chain_advance_formula_matches_spec(self) -> None: + """Ref impl agrees with the chained splitmix64 chain-step formula. + + The chain step folds each of the 3 inputs into the accumulator sequentially via + ``acc = splitmix64(acc ^ next)``, starting from ``splitmix64(prev_hash)``. ``splitmix64_mix3`` + must produce the same result as the explicit chain. ``real_kv_hash`` is intentionally NOT + part of the chain hash — see ``compute_slot_hash`` for the radix-folding rationale. + """ + cases = [ + (consts.CANARY_CHAIN_ANCHOR, 0, 0), + (0x1234567890ABCDEF, 100, 5), + (0, 0xFFFF, 0x7FFFFFFF), + (0x123, 1, 1), + (0xFFFFFFFFFFFFFFFF, 0xFFFF, 0xFFFF), + ] + for prev_hash, token, position in cases: + u64_mask = (1 << 64) - 1 + h = splitmix64(prev_hash & u64_mask) + h = splitmix64(h ^ (token & u64_mask)) + expected = splitmix64(h ^ (position & u64_mask)) + + actual = ( + splitmix64_mix3( + prev_hash & u64_mask, token & u64_mask, position & u64_mask + ) + & u64_mask + ) + assert actual == expected, ( + f"chain advance mismatch: prev={prev_hash:#x} token={token:#x} pos={position:#x} " + f"expected={expected:#x} actual={actual:#x}" + ) + + def test_chain_head_anchored_on_constant(self) -> None: + """prev_slot==-1 + stored prev_hash != splitmix64(ANCHOR) → CHAIN_HASH bit set.""" + buf_pair = _buf_pair() + slot_idx = 5 + _stamp_head(buf_pair, slot_idx=slot_idx, prev_hash=to_signed_int64(0xDEADBEEF)) + + plan_pair = _plan_pair_single(slot_idx=slot_idx, position=0) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + assert _n_violations(cuda_log) == 1 + assert _fail_bits(cuda_log) & consts.FailReason.VERIFY_CHAIN_HASH_MISMATCH + + def test_chain_head_prev_hash_equals_splitmix64_anchor_random_50(self) -> None: + random.seed(0) + expected_prev_hash_signed = to_signed_int64( + splitmix64(consts.CANARY_CHAIN_ANCHOR) + ) + + for _ in range(50): + token = random.randint(0, 0x7FFFFFFF) + position = random.randint(0, 0x7FFFFFFF) + slot_idx = random.randint(0, 15) + + buf_pair = _buf_pair() + _stamp_head( + buf_pair, + slot_idx=slot_idx, + token=token, + position=position, + prev_hash=expected_prev_hash_signed, + ) + + plan_pair = _plan_pair_single(slot_idx=slot_idx, position=position) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, plan_pair=plan_pair, assert_equal=False + ) + + assert ( + _n_violations(cuda_log) == 0 + ), f"unexpected violation at iteration token={token} position={position} slot={slot_idx}" + + def test_prev_slot_padding_skips_chain_check_arbitrary_stored_hash(self) -> None: + """prev_slot_idx == TOKEN_TO_KV_SLOT_PADDING → chain check is skipped, regardless of stored chain hash.""" + buf_pair = _buf_pair() + # Stamp slot 5 with an arbitrary (non-anchor, non-derivable) prev_hash. Without the skip, + # the kernel would compute expected_chain_hash from slot 0's canary (all zeros = 0) and + # flag VERIFY_CHAIN_HASH_MISMATCH on every such row. + stamp_pair( + buf_pair, + slot_idx=5, + token=42, + position=0, + prev_hash=to_signed_int64(0xDEADBEEFCAFEBABE), + ) + + plan_pair = _plan_pair_single( + slot_idx=5, position=0, prev_slot_idx=consts.TOKEN_TO_KV_SLOT_PADDING + ) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + assert _n_violations(cuda_log) == 0 + + def test_prev_slot_padding_does_not_mask_position_check(self) -> None: + """prev_slot == padding skips ONLY the chain check; position mismatch still fires.""" + buf_pair = _buf_pair() + stamp_pair( + buf_pair, + slot_idx=7, + token=11, + position=0, + prev_hash=to_signed_int64(0x12345678), + ) + + # Plan claims position 99 — chain check is skipped (prev=padding) but position must still fire. + plan_pair = _plan_pair_single( + slot_idx=7, position=99, prev_slot_idx=consts.TOKEN_TO_KV_SLOT_PADDING + ) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + + assert _n_violations(cuda_log) == 1 + assert_only_bits_set( + _fail_bits(cuda_log), consts.FailReason.VERIFY_POSITION_MISMATCH + ) + + +class TestViolationField: + def test_violation_token_mismatch(self) -> None: + """Stored token differs from a fresh write at the same slot → TOKEN-side accounting via the chain bit.""" + # Verify kernel doesn't have a TOKEN fail bit per se — token mismatch propagates into next-slot + # CHAIN_HASH mismatch. Inject token corruption at slot 2 and verify slot 3 sees CHAIN_HASH bit set. + cuda_buf, ref_buf = _buf_pair() + slot_indices = [1, 2, 3] + tokens = [100, 200, 300] + positions = [0, 1, 2] + stamp_clean_chain( + cuda_buf=cuda_buf, + ref_buf=ref_buf, + tokens=tokens, + positions=positions, + slot_indices=slot_indices, + ) + + # Step: corrupt the stored token at slot 2 in both buffers — chain hash propagates downstream. + stamp_pair( + (cuda_buf, ref_buf), + slot_idx=2, + token=999, + position=1, + prev_hash=0, + ) + + plan_pair = make_verify_plan_pair( + slot_indices=[3], positions=[2], prev_slot_indices=[2], device=_DEVICE + ) + cuda_log, _ = run_verify_diff(buf_pair=(cuda_buf, ref_buf), plan_pair=plan_pair) + + assert _n_violations(cuda_log) == 1 + assert_only_bits_set( + _fail_bits(cuda_log), consts.FailReason.VERIFY_CHAIN_HASH_MISMATCH + ) + + def test_violation_position_mismatch(self) -> None: + """Stored position differs from what the slot's chain reconstruction would yield → POSITION bit.""" + # Stamp slot 7 with a valid head chain but stored position = 0; ask verify to expect position 5. + buf_pair = _buf_pair() + _stamp_head(buf_pair, slot_idx=7) + + plan_pair = _plan_pair_single(slot_idx=7, position=5) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + + assert _n_violations(cuda_log) == 1 + assert_only_bits_set( + _fail_bits(cuda_log), consts.FailReason.VERIFY_POSITION_MISMATCH + ) + + def test_violation_position_diverges_from_plan(self) -> None: + """Plan-supplied position contradicts stored position → POSITION bit (verify trusts plan, not +1).""" + # Step: a clean chain head with stored position 0; plan claims position 99 — kernel must flag POSITION. + buf_pair = _buf_pair() + _stamp_head(buf_pair, slot_idx=3, token=11) + + plan_pair = _plan_pair_single(slot_idx=3, position=99) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + + assert_only_bits_set( + _fail_bits(cuda_log), consts.FailReason.VERIFY_POSITION_MISMATCH + ) + + def test_violation_prev_hash_mismatch(self) -> None: + """Stored prev_hash differs from predecessor-derived expectation → CHAIN_HASH bit.""" + cuda_buf, ref_buf = _buf_pair() + slot_indices = [1, 2] + tokens = [10, 20] + positions = [0, 1] + stamp_clean_chain( + cuda_buf=cuda_buf, + ref_buf=ref_buf, + tokens=tokens, + positions=positions, + slot_indices=slot_indices, + ) + + # Step: corrupt slot 2's stored prev_hash with a bogus signed int64. + stamp_pair( + (cuda_buf, ref_buf), + slot_idx=2, + token=20, + position=1, + prev_hash=0x1234567812345678, + ) + + plan_pair = make_verify_plan_pair( + slot_indices=[2], positions=[1], prev_slot_indices=[1], device=_DEVICE + ) + cuda_log, _ = run_verify_diff(buf_pair=(cuda_buf, ref_buf), plan_pair=plan_pair) + + assert_only_bits_set( + _fail_bits(cuda_log), consts.FailReason.VERIFY_CHAIN_HASH_MISMATCH + ) + + def test_violation_real_kv_hash_mismatch(self) -> None: + """Mutate one byte of a RealKvSource tensor after writing the chain → REAL_KV_HASH bit on verify.""" + buf_pair = _buf_pair() + sources_cuda = make_real_kv_sources(count=1, device=_DEVICE) + + # Step: write a chain with real_kv_hash mixin, then mutate one byte in the source tensors so the next + # verify reconstructs a hash that differs from the stored one. + _stamp_clean_kv_chain( + buf_pair=buf_pair, + sources_cuda=sources_cuda, + input_ids=torch.tensor([7, 8, 9], dtype=torch.int64, device=_DEVICE), + positions=torch.tensor([0, 1, 2], dtype=torch.int64, device=_DEVICE), + out_cache_loc=torch.tensor([1, 2, 3], dtype=torch.int64, device=_DEVICE), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + # Mutate one byte in BOTH copies so the verify recomputed hash diverges from stored. + sources_ref = clone_real_kv_sources(sources_cuda) + sources_cuda[0].tensor[1, 0] ^= 0xFF + sources_ref[0].tensor.copy_(sources_cuda[0].tensor) + + plan_pair = _plan_pair_single(slot_idx=1, position=0) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + assert_only_bits_set( + _fail_bits(cuda_log), consts.FailReason.VERIFY_REAL_KV_HASH_MISMATCH + ) + + @pytest.mark.parametrize("bit_to_trigger", ["POSITION", "PREV_HASH", "REAL_KV"]) + @pytest.mark.parametrize("injection_position", ["head", "mid", "last"]) + @pytest.mark.parametrize("ring_state", ["open", "full"]) + def test_violation_bit_injection_position_ring_state_matrix( + self, + bit_to_trigger: str, + injection_position: str, + ring_state: str, + ) -> None: + """Sweep injection_position x bit_to_trigger x ring_state for verify-kernel fail-reason coverage.""" + _RING_CAPACITY = 4 + slot_indices = [1, 2, 3, 4, 5] + tokens = [11, 22, 33, 44, 55] + positions = [0, 1, 2, 3, 4] + + corruption_index = {"head": 0, "mid": 2, "last": 4}[injection_position] + corrupt_slot = slot_indices[corruption_index] + + expected_bit = { + "POSITION": consts.FailReason.VERIFY_POSITION_MISMATCH, + "PREV_HASH": consts.FailReason.VERIFY_CHAIN_HASH_MISMATCH, + "REAL_KV": consts.FailReason.VERIFY_REAL_KV_HASH_MISMATCH, + }[bit_to_trigger] + + if bit_to_trigger == "REAL_KV": + buf_pair = _buf_pair() + sources_cuda = make_real_kv_sources(count=1, device=_DEVICE) + _stamp_clean_kv_chain( + buf_pair=buf_pair, + sources_cuda=sources_cuda, + input_ids=torch.tensor(tokens, dtype=torch.int64, device=_DEVICE), + positions=torch.tensor(positions, dtype=torch.int64, device=_DEVICE), + out_cache_loc=torch.tensor( + slot_indices, dtype=torch.int64, device=_DEVICE + ), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + sources_ref = clone_real_kv_sources(sources_cuda) + sources_cuda[0].tensor[corrupt_slot, 0] ^= 0xFF + sources_ref[0].tensor.copy_(sources_cuda[0].tensor) + real_kv_hash_mode = consts.RealKvHashMode.ALL + real_kv_sources_cuda = sources_cuda + real_kv_sources_ref = sources_ref + else: + cuda_buf, ref_buf = _buf_pair() + buf_pair = (cuda_buf, ref_buf) + stamp_clean_chain( + cuda_buf=cuda_buf, + ref_buf=ref_buf, + tokens=tokens, + positions=positions, + slot_indices=slot_indices, + ) + real_kv_hash_mode = consts.RealKvHashMode.NONE + real_kv_sources_cuda = () + real_kv_sources_ref = () + + if bit_to_trigger == "POSITION": + stored_token, stored_pos, stored_prev, stored_rkv = read_slot_fields( + canary_buf=cuda_buf, slot_idx=corrupt_slot + ) + stamp_pair( + buf_pair, + slot_idx=corrupt_slot, + token=stored_token, + position=stored_pos + 99, + prev_hash=stored_prev, + real_kv_hash=stored_rkv, + ) + else: + stored_token, stored_pos, stored_prev, stored_rkv = read_slot_fields( + canary_buf=cuda_buf, slot_idx=corrupt_slot + ) + flipped_prev = stored_prev ^ 1 + stamp_pair( + buf_pair, + slot_idx=corrupt_slot, + token=stored_token, + position=stored_pos, + prev_hash=flipped_prev, + real_kv_hash=stored_rkv, + ) + + ring_capacity = _RING_CAPACITY + cuda_log, ref_log = make_log_pair(capacity=ring_capacity, device=_DEVICE) + if ring_state == "full": + prefill_slots = list(range(8, 8 + ring_capacity)) + for slot_idx in prefill_slots: + _stamp_head(buf_pair, slot_idx=slot_idx, token=1) + prefill_plan_pair = make_verify_plan_pair( + slot_indices=prefill_slots, + positions=[99] * ring_capacity, + prev_slot_indices=[-1] * ring_capacity, + device=_DEVICE, + ) + _run_both_verify_no_rkv( + buf_pair=buf_pair, + plan_pair=prefill_plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + assert_equal=False, + ) + assert _n_violations(cuda_log) == ring_capacity + + prev_slot_indices = [-1, 1, 2, 3, 4] + plan_cuda, plan_ref = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=prev_slot_indices, + device=_DEVICE, + ) + + _run_both_verify( + cuda_canary_buf=buf_pair[0], + ref_canary_buf=buf_pair[1], + plan_cuda=plan_cuda, + plan_ref=plan_ref, + cuda_log=cuda_log, + ref_log=ref_log, + real_kv_sources_cuda=real_kv_sources_cuda, + real_kv_sources_ref=real_kv_sources_ref, + real_kv_hash_mode=real_kv_hash_mode, + assert_equal=False, + ) + + if ring_state == "open": + write_index = _n_violations(cuda_log) + rows_stored = min(write_index, ring_capacity) + found = any( + _fail_bits(cuda_log, row_idx) & expected_bit + for row_idx in range(rows_stored) + ) + assert found, ( + f"expected bit {expected_bit:#x} not found in any ring row " + f"(bit_to_trigger={bit_to_trigger} injection_position={injection_position})" + ) + else: + assert ( + _n_violations(cuda_log) > ring_capacity + ), "write_index did not advance beyond ring_capacity after overflow" + + def test_position_mismatch_sets_position_bit_only(self) -> None: + """Plan.position != stored.position with chain hash correct → only POSITION bit set.""" + buf_pair = _buf_pair() + slot_idx = 5 + _stamp_head(buf_pair, slot_idx=slot_idx, position=10) + + plan_pair = _plan_pair_single(slot_idx=slot_idx, position=99) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + assert _n_violations(cuda_log) == 1 + bits = _fail_bits(cuda_log) + assert ( + bits & consts.FailReason.VERIFY_POSITION_MISMATCH + ), f"expected POSITION bit, got {bits:#b}" + assert ( + bits & consts.FailReason.VERIFY_CHAIN_HASH_MISMATCH + ) == 0, f"chain hash bit unexpectedly set: {bits:#b}" + + +class TestRealKvHash: + def test_real_kv_mode_off_yields_zero(self) -> None: + """OFF mode → stored real_kv_hash field stays zero post-write; verify with OFF agrees byte-equal.""" + buf_pair = _buf_pair() + sources = make_real_kv_sources(count=2, device=_DEVICE) + + plan_pair = _plan_pair_single(slot_idx=1, position=0) + _stamp_head(buf_pair, slot_idx=1, token=1) + + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources, sources), + ) + + assert _n_violations(cuda_log) == 0 + + @pytest.mark.parametrize( + "mode", + [ + pytest.param(consts.RealKvHashMode.PARTIAL, id="partial"), + pytest.param(consts.RealKvHashMode.ALL, id="all"), + ], + ) + def test_real_kv_mode_byte_equal(self, mode: consts.RealKvHashMode) -> None: + """PARTIAL / ALL modes both produce CUDA-vs-ref byte-equal state on a clean 3-step chain.""" + buf_pair = _buf_pair() + sources_cuda = make_real_kv_sources(count=2, device=_DEVICE) + sources_ref = clone_real_kv_sources(sources_cuda) + + # Write a chain through the ref so both buffers are byte-equal post-write. + _stamp_clean_kv_chain( + buf_pair=buf_pair, + sources_cuda=sources_cuda, + input_ids=torch.tensor([10, 20, 30], dtype=torch.int64, device=_DEVICE), + positions=torch.tensor([0, 1, 2], dtype=torch.int64, device=_DEVICE), + out_cache_loc=torch.tensor([1, 2, 3], dtype=torch.int64, device=_DEVICE), + real_kv_hash_mode=mode, + ) + + plan_pair = make_verify_plan_pair( + slot_indices=[1, 2, 3], + positions=[0, 1, 2], + prev_slot_indices=[-1, 1, 2], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=mode, + ) + + assert _n_violations(cuda_log) == 0 + + @pytest.mark.parametrize("count", [1, 2, 3, 4]) + def test_real_kv_sources_fold_1_to_4(self, count: int) -> None: + """Fold ``count`` sources sequentially → CUDA matches ref for every count in {1..4}.""" + buf_pair = _buf_pair() + sources_cuda = make_real_kv_sources(count=count, device=_DEVICE) + sources_ref = clone_real_kv_sources(sources_cuda) + + _stamp_clean_kv_chain( + buf_pair=buf_pair, + sources_cuda=sources_cuda, + input_ids=torch.tensor([1, 2], dtype=torch.int64, device=_DEVICE), + positions=torch.tensor([0, 1], dtype=torch.int64, device=_DEVICE), + out_cache_loc=torch.tensor([1, 2], dtype=torch.int64, device=_DEVICE), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + plan_pair = make_verify_plan_pair( + slot_indices=[1, 2], + positions=[0, 1], + prev_slot_indices=[-1, 1], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + assert _n_violations(cuda_log) == 0 + + @pytest.mark.parametrize( + "mode,fold_fn,expected_hash", + [ + pytest.param( + consts.RealKvHashMode.PARTIAL, + _hand_fold_partial, + 0x6041580849E6407D, + id="partial", + ), + pytest.param( + consts.RealKvHashMode.ALL, + _hand_fold_all, + 0x6041580849E6407D, + id="all", + ), + ], + ) + def test_real_kv_hash_fold_mode_hardcoded( + self, + mode: consts.RealKvHashMode, + fold_fn: Callable[[bytes], int], + expected_hash: int, + ) -> None: + # Step 1: build one RealKvSource with read_bytes=16 and a fixed byte pattern at slot 1. + _PATTERN = bytes( + [ + 0x01, + 0x02, + 0x04, + 0x08, + 0x10, + 0x20, + 0x40, + 0x80, + 0x81, + 0x82, + 0x84, + 0x88, + 0x90, + 0xA0, + 0xC0, + 0xFF, + ] + ) + + buf_pair = _buf_pair() + source_cuda = make_real_kv_source( + num_slots=16, + num_bytes_per_token=16, + page_size=1, + read_bytes=16, + device=_DEVICE, + ) + source_cuda.tensor[1, :16] = torch.tensor(list(_PATTERN), dtype=torch.uint8) + source_ref = RealKvSource( + tensor=source_cuda.tensor.clone(), + page_size=source_cuda.page_size, + num_bytes_per_token=source_cuda.num_bytes_per_token, + read_bytes=source_cuda.read_bytes, + ) + + # Step 2: verify hand-computed fold matches the hex literal. + assert fold_fn(_PATTERN) == expected_hash + + # Step 3: stamp slot 1 with a chain-head entry whose real_kv_hash equals the expected value. + _stamp_head( + buf_pair, + slot_idx=1, + token=7, + real_kv_hash=to_signed_int64(expected_hash), + ) + + # Step 4: 1-entry verify plan; no violation because stored matches recomputed. + plan_pair = _plan_pair_single(slot_idx=1, position=0) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=((source_cuda,), (source_ref,)), + real_kv_hash_mode=mode, + assert_equal=False, + ) + + assert _n_violations(cuda_log) == 0 + + # Step 5: mutate one byte in the source so the recomputed hash diverges from stored. + source_cuda.tensor[1, 0] ^= 0xFF + source_ref.tensor.copy_(source_cuda.tensor) + + plan_pair2 = _plan_pair_single(slot_idx=1, position=0) + cuda_log2, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair2, + real_kv_sources_pair=((source_cuda,), (source_ref,)), + real_kv_hash_mode=mode, + ) + + assert_only_bits_set( + _fail_bits(cuda_log2), consts.FailReason.VERIFY_REAL_KV_HASH_MISMATCH + ) + + def test_real_kv_hash_all_mode_with_multiple_sources(self) -> None: + """ALL mode with count=2 page=16 bytes=128 sources: chain still verifies clean.""" + buf_pair = _buf_pair(num_slots=32) + sources_cuda = make_real_kv_sources( + count=2, + num_bytes_per_token=128, + page_size=16, + num_slots=32, + device=_DEVICE, + ) + sources_ref = clone_real_kv_sources(sources_cuda) + + slot_indices = [1, 2, 3] + tokens = [100, 200, 300] + positions = [0, 1, 2] + + running = splitmix64(consts.CANARY_CHAIN_ANCHOR) + real_kv_hashes: list[int] = [] + for slot_idx in slot_indices: + real_kv_hashes.append( + _compute_real_kv_hash_scalar( + real_kv_sources=sources_cuda, + real_kv_hash_mode=consts.RealKvHashMode.ALL, + slot_idx=slot_idx, + work_device=torch.device("cpu"), + ) + ) + + for slot_idx, token, position, rkv in zip( + slot_indices, tokens, positions, real_kv_hashes + ): + signed_prev = to_signed_int64(running) + stamp_pair( + buf_pair, + slot_idx=slot_idx, + token=token, + position=position, + prev_hash=signed_prev, + real_kv_hash=to_signed_int64(rkv), + ) + running = splitmix64_mix3(running, token, position) + + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=[-1, 1, 2], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + assert _n_violations(cuda_log) == 0 + + def test_real_kv_hash_partial_mode_detects_single_bit_flip(self) -> None: + """PARTIAL mode + 1-bit flip in source tensor → REAL_KV_HASH bit set in violation row.""" + buf_pair = _buf_pair() + sources_cuda = make_real_kv_sources( + count=1, num_bytes_per_token=16, device=_DEVICE + ) + slot_idx = 3 + row_bytes = ( + sources_cuda[0] + .tensor[slot_idx, : sources_cuda[0].read_bytes] + .detach() + .cpu() + .tolist() + ) + rkv_clean = _hand_fold_partial(bytes(row_bytes)) + _stamp_head( + buf_pair, + slot_idx=slot_idx, + real_kv_hash=to_signed_int64(rkv_clean), + ) + + sources_cuda[0].tensor[slot_idx, 0] ^= 1 + sources_ref = clone_real_kv_sources(sources_cuda) + + plan_pair = _plan_pair_single(slot_idx=slot_idx, position=0) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.PARTIAL, + ) + + assert _n_violations(cuda_log) >= 1 + bits = _fail_bits(cuda_log) + assert ( + bits & consts.FailReason.VERIFY_REAL_KV_HASH_MISMATCH + ), f"expected REAL_KV_HASH bit, got {bits:#b}" + + def test_real_kv_off_does_not_deref_real_kv_sources(self) -> None: + buf_pair = _buf_pair(num_slots=8) + _stamp_head(buf_pair, slot_idx=1, token=1) + + garbage_source = make_real_kv_source( + num_slots=8, + num_bytes_per_token=16, + page_size=1, + read_bytes=16, + device=_DEVICE, + fill=0xDE, + ) + + plan_pair = _plan_pair_single(slot_idx=1, position=0) + cuda_log, ref_log = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=((garbage_source,), (garbage_source,)), + assert_equal=False, + ) + + assert _n_violations(cuda_log) == 0 + assert _n_violations(ref_log) == 0 + + +class TestRealKvSource: + def test_real_kv_source_rejects_zero_read_bytes(self) -> None: + """RealKvSource has no \"skip me\" sentinel — read_bytes=0 must raise rather than silently pass.""" + with pytest.raises(ValueError, match="read_bytes"): + RealKvSource( + tensor=torch.zeros((1, 16), dtype=torch.uint8, device=_DEVICE), + page_size=1, + num_bytes_per_token=16, + read_bytes=0, + ) + + def test_real_kv_source_padding_below_4(self) -> None: + """Host wrapper pads to 4 slots when fewer sources are supplied; dummy slots are never dereferenced.""" + buf_pair = _buf_pair() + sources = make_real_kv_sources(count=2, device=_DEVICE) + + plan_pair = _plan_pair_single(slot_idx=1, position=0) + _stamp_head(buf_pair, slot_idx=1, token=1) + run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources, sources), + ) + + def test_real_kv_source_above_4_raises(self) -> None: + """``len(real_kv_sources) > 4`` → host wrapper raises ValueError before launching.""" + canary_buf = make_canary_buf(device=_DEVICE) + plan = make_verify_plan( + slot_indices=[1], positions=[0], prev_slot_indices=[-1], device=_DEVICE + ) + log = FakeViolationLog.allocate(device=_DEVICE) + sources = make_real_kv_sources(count=4, device=_DEVICE) + extra = make_real_kv_source(device=_DEVICE) + too_many = sources + (extra,) + + with pytest.raises(ValueError, match="at most 4 RealKvSource"): + launch_canary_verify_kernel( + context=VerifyOrWriteContext( + canary_buf=canary_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=too_many, + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ), + plan=plan, + check_verify_expected_token=True, + ) + + def test_real_kv_source_holey_dim1(self) -> None: + """``tensor.shape[1] > page_size * num_bytes_per_token`` → trailing bytes are skipped.""" + buf_pair = _buf_pair() + holey_source = make_real_kv_source( + num_slots=16, + num_bytes_per_token=16, + page_size=1, + read_bytes=16, + pad_dim1=16, # 16 trailing pad bytes per row; must be skipped. + device=_DEVICE, + ) + trailing_start = holey_source.page_size * holey_source.num_bytes_per_token + # Fill those skipped trailing bytes with garbage; CUDA must not read them. + holey_source.tensor[:, trailing_start:].fill_(0xAA) + sources = (holey_source,) + sources_ref = clone_real_kv_sources(sources) + + _stamp_clean_kv_chain( + buf_pair=buf_pair, + sources_cuda=sources, + input_ids=torch.tensor([1, 2], dtype=torch.int64, device=_DEVICE), + positions=torch.tensor([0, 1], dtype=torch.int64, device=_DEVICE), + out_cache_loc=torch.tensor([1, 2], dtype=torch.int64, device=_DEVICE), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + plan_pair = make_verify_plan_pair( + slot_indices=[1, 2], + positions=[0, 1], + prev_slot_indices=[-1, 1], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + assert _n_violations(cuda_log) == 0 + + +class TestLayoutAndScheduling: + def test_page_size_gt_1_access_pattern(self) -> None: + """``page_size > 1`` → byte access follows ``(row=slot//page, col=(slot%page)*bpt:)``.""" + buf_pair = _buf_pair(num_slots=8) + src = make_real_kv_source( + num_slots=8, + num_bytes_per_token=16, + page_size=4, # 2 rows × 4 slots/page × 16 bytes/slot. + read_bytes=16, + device=_DEVICE, + ) + # Each slot's 16 bytes get a slot-specific signature so kernel mis-indexing would shift the hash. + flat = src.tensor.view(-1) + for slot_idx in range(8): + row = slot_idx // src.page_size + col = (slot_idx % src.page_size) * src.num_bytes_per_token + for k in range(src.num_bytes_per_token): + flat_index = row * (src.page_size * src.num_bytes_per_token) + col + k + flat[flat_index] = (slot_idx * 13 + k) & 0xFF + sources = (src,) + sources_ref = clone_real_kv_sources(sources) + + _stamp_clean_kv_chain( + buf_pair=buf_pair, + sources_cuda=sources, + input_ids=torch.tensor([1, 2], dtype=torch.int64, device=_DEVICE), + positions=torch.tensor([0, 1], dtype=torch.int64, device=_DEVICE), + out_cache_loc=torch.tensor([1, 5], dtype=torch.int64, device=_DEVICE), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + plan_pair = make_verify_plan_pair( + slot_indices=[1, 5], + positions=[0, 1], + prev_slot_indices=[-1, 1], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + assert _n_violations(cuda_log) == 0 + + def test_swa_translated_slot_indices(self) -> None: + """SWA-translated slots already passed in plan; verify kernel does no further translation.""" + # SWA verify plans carry pre-translated slot indices — the verify kernel never sees the FULL slot + # index again. We pre-stamp the SWA-side slot and feed it directly into the verify plan to assert no + # extra translation happens kernel-side. + buf_pair = _buf_pair() + _stamp_head(buf_pair, slot_idx=2, token=99) + + plan_pair = _plan_pair_single(slot_idx=2, position=0) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + assert _n_violations(cuda_log) == 0 + + def test_empty_plan_no_op(self) -> None: + """``verify_num_valid = 0`` → no ring write, no slot_run_counter bump, only kernel_run_counter += 1.""" + buf_pair = _buf_pair() + plan_pair = make_verify_plan_pair( + slot_indices=[], + positions=[], + prev_slot_indices=[], + capacity=4, + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff(buf_pair=buf_pair, plan_pair=plan_pair) + + assert _n_violations(cuda_log) == 0 + assert int(cuda_log.slot_run_counter[0].item()) == 0 + assert int(cuda_log.kernel_run_counter[0].item()) == 1 + + def test_slot_zero_plan_entry_is_skipped(self) -> None: + """slot 0 is reserved padding: verify skips loads/violations but still counts the submitted entry.""" + canary_buf = make_canary_buf(num_slots=16, slot_stride_bytes=32, device=_DEVICE) + write_slot_fields( + canary_buf=canary_buf, + slot_idx=0, + token=999, + position=123, + prev_hash=to_signed_int64(0xDEADBEEF), + real_kv_hash=0, + ) + plan = make_verify_plan( + slot_indices=[0], + positions=[0], + prev_slot_indices=[-1], + device=_DEVICE, + ) + log = FakeViolationLog.allocate(capacity=8, device=_DEVICE) + + launch_canary_verify_kernel( + context=VerifyOrWriteContext( + canary_buf=canary_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ), + plan=plan, + check_verify_expected_token=True, + ) + torch.cuda.synchronize() + + assert _n_violations(log) == 0 + assert int(log.slot_run_counter[0].item()) == 1 + assert int(log.kernel_run_counter[0].item()) == 1 + + @pytest.mark.parametrize( + "runner", + [launch_canary_verify_kernel, launch_canary_verify_kernel_torch_reference], + ) + def test_disabled_plan_skips_slots_but_counts_kernel( + self, runner: Callable[..., None] + ) -> None: + """``VerifyPlan.enable = 0`` skips active entries while still marking the verify launch as run.""" + canary_buf = make_canary_buf(num_slots=16, slot_stride_bytes=32, device=_DEVICE) + slot_idx = 5 + write_slot_fields( + canary_buf=canary_buf, + slot_idx=slot_idx, + token=42, + position=1, + prev_hash=to_signed_int64(0x1234), + real_kv_hash=0, + ) + plan = make_verify_plan( + slot_indices=[slot_idx], + positions=[0], + prev_slot_indices=[-1], + device=_DEVICE, + ) + plan.enable[0] = 0 + + log = FakeViolationLog.allocate(capacity=8, device=_DEVICE) + log.ring.fill_(-777) + log.write_index[0] = 3 + log.slot_run_counter[0] = 11 + log.kernel_run_counter[0] = 13 + ring_before = log.ring.clone() + write_index_before = log.write_index.clone() + slot_run_before = log.slot_run_counter.clone() + kernel_run_before = log.kernel_run_counter.clone() + + runner( + context=VerifyOrWriteContext( + canary_buf=canary_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ), + plan=plan, + check_verify_expected_token=True, + ) + if runner is launch_canary_verify_kernel: + torch.cuda.synchronize() + + assert torch.equal(log.ring, ring_before) + assert torch.equal(log.write_index, write_index_before) + assert torch.equal(log.slot_run_counter, slot_run_before) + assert ( + int(log.kernel_run_counter[0].item()) + == int(kernel_run_before[0].item()) + 1 + ) + + def test_paged_layout_page_size_16(self) -> None: + """page_size=16: slot→page mapping doesn't change verify chain semantics on a clean chain.""" + buf_pair = _buf_pair(num_slots=64) + sources_cuda = make_real_kv_sources( + count=1, + num_bytes_per_token=16, + page_size=16, + num_slots=64, + device=_DEVICE, + ) + sources_ref = clone_real_kv_sources(sources_cuda) + + # Step: cross a page boundary by writing slots [15, 16] which straddle pages 0 and 1. + slot_indices = [15, 16] + tokens = [77, 88] + positions = [0, 1] + running = splitmix64(consts.CANARY_CHAIN_ANCHOR) + # Use the reference fold (8-byte little-endian word pack + splitmix64), not a + # byte-by-byte loop, so the stamped real_kv_hash matches what the kernel / + # verify reference will recompute. A byte-by-byte fold was the previous bug + # here and triggered REAL_KV_HASH violations on otherwise clean chains. + rkv_values = [ + _compute_real_kv_hash_scalar( + slot_idx=slot_idx, + real_kv_sources=sources_cuda, + real_kv_hash_mode=consts.RealKvHashMode.ALL, + work_device=_DEVICE, + ) + for slot_idx in slot_indices + ] + + for slot_idx, token, position, rkv in zip( + slot_indices, tokens, positions, rkv_values + ): + signed_prev = to_signed_int64(running) + stamp_pair( + buf_pair, + slot_idx=slot_idx, + token=token, + position=position, + prev_hash=signed_prev, + real_kv_hash=to_signed_int64(rkv), + ) + running = splitmix64_mix3(running, token, position) + + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=[-1, 15], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + assert _n_violations(cuda_log) == 0 + + def test_empty_plan_keeps_slot_counter_unchanged(self) -> None: + buf_pair = _buf_pair(num_slots=8) + _stamp_head(buf_pair, slot_idx=1, token=7) + + nonempty_plan_pair = _plan_pair_single(slot_idx=1, position=0) + empty_plan_pair = make_verify_plan_pair( + slot_indices=[], + positions=[], + prev_slot_indices=[], + capacity=4, + device=_DEVICE, + ) + cuda_log, ref_log = make_log_pair(device=_DEVICE) + for _ in range(30): + slot_before = int(cuda_log.slot_run_counter[0].item()) + kernel_before = int(cuda_log.kernel_run_counter[0].item()) + + _run_both_verify_no_rkv( + buf_pair=buf_pair, + plan_pair=empty_plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + assert_equal=False, + ) + + assert int(cuda_log.slot_run_counter[0].item()) == slot_before + assert int(cuda_log.kernel_run_counter[0].item()) == kernel_before + 1 + + _run_both_verify_no_rkv( + buf_pair=buf_pair, + plan_pair=nonempty_plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + assert_equal=False, + ) + + +class TestRunCounter: + def test_kernel_run_counter_per_call(self) -> None: + """``kernel_run_counter`` increments by 1 per call, even when ``verify_num_valid == 0``.""" + buf_pair = _buf_pair() + plan_pair = make_verify_plan_pair( + slot_indices=[], + positions=[], + prev_slot_indices=[], + capacity=4, + device=_DEVICE, + ) + # Use the low-level wrapper with explicit logs so we can observe the cross-call counter accumulation. + cuda_log, ref_log = make_log_pair(device=_DEVICE) + for _ in range(3): + _run_both_verify_no_rkv( + buf_pair=buf_pair, + plan_pair=plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + ) + + assert int(cuda_log.kernel_run_counter[0].item()) == 3 + + def test_slot_run_counter_per_entry(self) -> None: + """``slot_run_counter`` accumulates ``verify_num_valid`` entries per call.""" + cuda_buf, ref_buf = _buf_pair() + slot_indices = [1, 2, 3, 4] + tokens = [10, 11, 12, 13] + positions = [0, 1, 2, 3] + stamp_clean_chain( + cuda_buf=cuda_buf, + ref_buf=ref_buf, + tokens=tokens, + positions=positions, + slot_indices=slot_indices, + ) + + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=[-1, 1, 2, 3], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff(buf_pair=(cuda_buf, ref_buf), plan_pair=plan_pair) + + assert int(cuda_log.slot_run_counter[0].item()) == 4 + + def test_grid_stride_processes_entries_beyond_grid_size(self) -> None: + """``verify_num_valid`` exceeding the persistent grid thread count is fully processed via grid-stride.""" + n_active = 40000 + cuda_buf, ref_buf = make_canary_buf_pair( + num_slots=n_active + 1, slot_stride_bytes=32, device=_DEVICE + ) + slot_indices = list(range(1, n_active + 1)) + tokens = [i + 10 for i in range(n_active)] + positions = list(range(n_active)) + stamp_clean_chain( + cuda_buf=cuda_buf, + ref_buf=ref_buf, + tokens=tokens, + positions=positions, + slot_indices=slot_indices, + ) + + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=[-1] + slot_indices[:-1], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff(buf_pair=(cuda_buf, ref_buf), plan_pair=plan_pair) + + assert int(cuda_log.slot_run_counter[0].item()) == n_active + assert int(cuda_log.kernel_run_counter[0].item()) == 1 + + def test_replay_does_not_double_count_run_counters(self) -> None: + """Two consecutive runs on same plan: slot_run_counter += 2N, kernel_run_counter += 2.""" + cuda_buf, ref_buf = _buf_pair() + slot_indices = [1, 2, 3] + tokens = [10, 20, 30] + positions = [0, 1, 2] + stamp_clean_chain( + cuda_buf=cuda_buf, + ref_buf=ref_buf, + tokens=tokens, + positions=positions, + slot_indices=slot_indices, + ) + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=[-1, 1, 2], + device=_DEVICE, + ) + cuda_log, ref_log = make_log_pair(device=_DEVICE) + for _ in range(2): + _run_both_verify_no_rkv( + buf_pair=(cuda_buf, ref_buf), + plan_pair=plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + ) + + assert int(cuda_log.slot_run_counter[0].item()) == 2 * len(slot_indices) + assert int(cuda_log.kernel_run_counter[0].item()) == 2 + + def test_slot_run_counter_delta_equals_active_entries_across_random_plans( + self, + ) -> None: + random.seed(0) + num_slots = 32 + cuda_buf = make_canary_buf( + num_slots=num_slots, slot_stride_bytes=32, device=_DEVICE + ) + ref_buf = cuda_buf.clone() + buf_pair = (cuda_buf, ref_buf) + + for slot_idx in range(num_slots): + _stamp_head( + buf_pair, + slot_idx=slot_idx, + token=slot_idx + 10, + position=slot_idx, + ) + + cuda_log, ref_log = make_log_pair(device=_DEVICE) + for _ in range(50): + bs = random.randint(1, 16) + entries_per_req = random.randint(1, 8) + n_entries = bs * entries_per_req + if n_entries > num_slots: + n_entries = num_slots + slot_indices = random.sample(range(num_slots), n_entries) + positions = [random.randint(0, 99) for _ in range(n_entries)] + prev_slot_indices = [-1] * n_entries + + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=prev_slot_indices, + device=_DEVICE, + ) + + before = int(cuda_log.slot_run_counter[0].item()) + _run_both_verify_no_rkv( + buf_pair=buf_pair, + plan_pair=plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + assert_equal=False, + ) + after = int(cuda_log.slot_run_counter[0].item()) + assert after - before == n_entries + + def test_kernel_run_counter_per_call_invariant_50_calls(self) -> None: + buf_pair = _buf_pair(num_slots=8) + _stamp_head(buf_pair, slot_idx=1) + + plan_pair = _plan_pair_single(slot_idx=1, position=0) + cuda_log, ref_log = make_log_pair(device=_DEVICE) + for n in range(1, 51): + _run_both_verify_no_rkv( + buf_pair=buf_pair, + plan_pair=plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + assert_equal=False, + ) + assert int(cuda_log.kernel_run_counter[0].item()) == n + + +class TestViolationRing: + def test_violation_ring_fill_once_first_row(self) -> None: + """First violation lands at ring[0]; subsequent violations advance ``violation_write_index``.""" + buf_pair = _buf_pair() + # 3 chain-head entries with stored values that all yield POSITION mismatch (positions all 99). + for slot_idx in (1, 2, 3): + _stamp_head(buf_pair, slot_idx=slot_idx, token=1) + + plan_pair = make_verify_plan_pair( + slot_indices=[1, 2, 3], + positions=[99, 99, 99], + prev_slot_indices=[-1, -1, -1], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, plan_pair=plan_pair, assert_equal=False + ) + + assert _n_violations(cuda_log) == 3 + # row 0 is filled (slot 1 → POSITION bit). + assert _fail_bits(cuda_log) & consts.FailReason.VERIFY_POSITION_MISMATCH + + def test_violation_ring_overflow_counter_still_increments(self) -> None: + """Ring capacity exceeded → rows beyond are dropped but ``write_index`` still grows.""" + buf_pair = _buf_pair() + n_violations = 10 + slot_indices = list(range(1, n_violations + 1)) + for slot_idx in slot_indices: + _stamp_head(buf_pair, slot_idx=slot_idx, token=1) + + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=[99] * n_violations, + prev_slot_indices=[-1] * n_violations, + device=_DEVICE, + ) + cuda_log, ref_log = make_log_pair(capacity=4, device=_DEVICE) + _run_both_verify_no_rkv( + buf_pair=buf_pair, + plan_pair=plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + assert_equal=False, + ) + + assert _n_violations(cuda_log) == n_violations + assert _n_violations(ref_log) == n_violations + # Atomic-order may permute ring contents under overflow; only the write_index counter is + # byte-equal — we relax the ring-contents check here. + assert torch.equal(cuda_log.write_index, ref_log.write_index) + + def test_kernel_kind_stamped_into_row(self) -> None: + """Different ``CanaryLaunchTag`` values → violation row.kernel_kind reflects each.""" + buf_pair = _buf_pair() + _stamp_head(buf_pair, slot_idx=1, token=1) + + for tag in (CanaryLaunchTag.HEAD_K_FULL, CanaryLaunchTag.SWEEP_V_SWA): + plan_pair = _plan_pair_single(slot_idx=1, position=99) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, plan_pair=plan_pair, kernel_kind=tag + ) + kk = int(cuda_log.ring[0, consts.VIOLATION_FIELD_KERNEL_KIND].item()) + assert kk == int(tag) + + def test_violation_ring_row_byte_layout_hardcoded(self) -> None: + buf_pair = _buf_pair() + anchor_hash_signed = chain_anchor_signed() + _stamp_head(buf_pair, slot_idx=5, token=33) + + plan_pair = _plan_pair_single(slot_idx=5, position=99) + cuda_log, ref_log = make_log_pair(capacity=4, device=_DEVICE) + _run_both_verify_no_rkv( + buf_pair=buf_pair, + plan_pair=plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + ) + + assert _n_violations(cuda_log) == 1 + + # splitmix64(consts.CANARY_CHAIN_ANCHOR) = 0xde7fae23a9a1b716; signed = -2414019407054260458. + # Slot 5 was stamped with position=0 (stored); plan claims position=99 → POSITION mismatch. + # stored_chain_hash == expected_chain_hash (both splitmix64(ANCHOR)) → no CHAIN_HASH bit. + # plan has no populated verify_expected_tokens → entries read -1 sentinel, the + # verify kernel skips the token check (no TOKEN_MISMATCH bit) but the row's + # expected_token field reflects the gathered sentinel value. + # expected_aux = expected_chain_hash = splitmix64(ANCHOR) signed (same value as stored_chain_hash). + kernel_kind_val = int(CanaryLaunchTag.HEAD_K_FULL) + slot_idx_val = 5 + position_val = 0 + stored_token_val = 33 + expected_token_val = -1 + stored_chain_hash_val = anchor_hash_signed + expected_aux_val = anchor_hash_signed + fail_reason_bits_val = consts.FailReason.VERIFY_POSITION_MISMATCH + + expected_bytes = struct.pack( + "<8q", + kernel_kind_val, + slot_idx_val, + position_val, + stored_token_val, + expected_token_val, + stored_chain_hash_val, + expected_aux_val, + fail_reason_bits_val, + ) + + actual_bytes = cuda_log.ring[0].cpu().numpy().tobytes() + + if actual_bytes != expected_bytes: + expected_fields = struct.unpack("<8q", expected_bytes) + actual_fields = struct.unpack("<8q", actual_bytes) + field_names = [ + "kernel_kind", + "slot_idx", + "position", + "stored_token", + "expected_token", + "stored_chain_hash", + "expected_aux", + "fail_reason_bits", + ] + mismatches = [ + f" [{i}] {name}: expected {e} ({e:#x}) got {a} ({a:#x})" + for i, (name, e, a) in enumerate( + zip(field_names, expected_fields, actual_fields) + ) + if e != a + ] + raise AssertionError( + "violation_ring row binary layout mismatch:\n" + "\n".join(mismatches) + ) + + def test_violation_ring_atomic_with_many_violations(self) -> None: + """50 simultaneously-corrupted entries → write_index == 50 (no atomicity loss).""" + n = 50 + cuda_buf = make_canary_buf( + num_slots=n + 4, slot_stride_bytes=32, device=_DEVICE + ) + ref_buf = cuda_buf.clone() + slot_indices = list(range(1, n + 1)) + positions = [0] * n + + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=[-1] * n, + capacity=n, + device=_DEVICE, + ) + cuda_log, ref_log = make_log_pair(capacity=128, device=_DEVICE) + _run_both_verify_no_rkv( + buf_pair=(cuda_buf, ref_buf), + plan_pair=plan_pair, + cuda_log=cuda_log, + ref_log=ref_log, + assert_equal=False, + ) + + assert _n_violations(cuda_log) == n + assert _n_violations(ref_log) == n + + def test_violation_rows_have_valid_kernel_kind_and_slot(self) -> None: + """Each violation row's kernel_kind matches the launch tag; slot_idx is one of the plan slots.""" + buf_pair = _buf_pair() + slot_indices = [1, 2, 3, 4] + positions = [0, 1, 2, 3] + plan_pair = make_verify_plan_pair( + slot_indices=slot_indices, + positions=positions, + prev_slot_indices=[-1] * 4, + device=_DEVICE, + ) + launch_tag = CanaryLaunchTag.HEAD_V_SWA + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, plan_pair=plan_pair, kernel_kind=launch_tag + ) + n_violations = _n_violations(cuda_log) + plan_slot_set = set(slot_indices) + for row in range(n_violations): + kind = int(cuda_log.ring[row, consts.VIOLATION_FIELD_KERNEL_KIND].item()) + assert kind == int( + launch_tag + ), f"row {row} kind {kind} != {int(launch_tag)}" + slot = int(cuda_log.ring[row, 1].item()) + assert slot in plan_slot_set, f"row {row} slot {slot} not in plan" + + def test_clear_resets_ring_and_write_index_zero(self) -> None: + buf_pair = _buf_pair(num_slots=8) + for slot_idx in range(1, 4): + _stamp_head(buf_pair, slot_idx=slot_idx, token=1, position=99) + + plan_pair = make_verify_plan_pair( + slot_indices=[1, 2, 3], + positions=[0, 0, 0], + prev_slot_indices=[-1, -1, -1], + device=_DEVICE, + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, plan_pair=plan_pair, assert_equal=False + ) + + assert _n_violations(cuda_log) > 0 + + cuda_log_fresh = FakeViolationLog.allocate(device=_DEVICE) + assert _n_violations(cuda_log_fresh) == 0 + assert torch.all(cuda_log_fresh.ring == 0).item() + + +class TestBoundarySweep: + @pytest.mark.parametrize( + "token_val", + [0, 1, 0xFFFFFFFF, -1, 0x80000000, 0x7FFFFFFF], + ) + def test_token_boundary_byte_equal_sweep(self, token_val: int) -> None: + """Sweep token boundary values; assert CUDA vs ref state byte-equal.""" + _run_verify_single_slot_byte_equal( + _VerifySingleSlotInput( + token=token_val, stored_prev_hash_signed=chain_anchor_signed() + ) + ) + + @pytest.mark.parametrize( + "position_val", + [0, 1, 127, 128, 129, 0x7FFFFFFF], + ) + def test_position_boundary_byte_equal_sweep(self, position_val: int) -> None: + """Sweep position boundary values; assert CUDA vs ref state byte-equal.""" + _run_verify_single_slot_byte_equal( + _VerifySingleSlotInput( + position=position_val, stored_prev_hash_signed=chain_anchor_signed() + ) + ) + + @pytest.mark.parametrize( + "prev_hash_val", + [ + pytest.param(0, id="zero"), + pytest.param(None, id="splitmix64_of_zero"), + pytest.param(0xFFFFFFFFFFFFFFFF, id="all_ones"), + pytest.param(0x8000000000000000, id="sign_bit"), + ], + ) + def test_prev_hash_boundary_byte_equal_sweep( + self, prev_hash_val: int | None + ) -> None: + """Sweep prev_hash boundary values; assert CUDA vs ref state byte-equal.""" + if prev_hash_val is None: + prev_hash_val = splitmix64(0) + _run_verify_single_slot_byte_equal( + _VerifySingleSlotInput( + stored_prev_hash_signed=to_signed_int64(prev_hash_val) + ) + ) + + @pytest.mark.parametrize( + "stored_rkv_val", + [0, 1, 0xFFFFFFFFFFFFFFFF, 0x8000000000000000], + ) + def test_real_kv_hash_boundary_byte_equal_sweep(self, stored_rkv_val: int) -> None: + """Sweep real_kv_hash boundary values; assert CUDA vs ref state byte-equal.""" + sources_cuda = make_real_kv_sources(count=1, device=_DEVICE) + _run_verify_single_slot_byte_equal( + _VerifySingleSlotInput( + stored_prev_hash_signed=chain_anchor_signed(), + stored_real_kv_hash_signed=to_signed_int64(stored_rkv_val), + real_kv_sources=sources_cuda, + real_kv_hash_mode=consts.RealKvHashMode.PARTIAL, + ) + ) + + +class TestVerifyExpectedInputIds: + """Cover the new verify-time token-id check via VerifyPlan.verify_expected_tokens.""" + + def _run( + self, + *, + stored_token: int, + expected_input_id: int, + check_verify_expected_token: bool = True, + ) -> FakeViolationLog: + buf_pair = _buf_pair() + _stamp_head(buf_pair, slot_idx=1, token=stored_token) + plan_pair = _plan_pair_single( + slot_idx=1, position=0, expected_input_id=expected_input_id + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + check_verify_expected_token=check_verify_expected_token, + ) + return cuda_log + + def test_sentinel_skips_token_check(self) -> None: + """``expected_input_id == -1`` must not fire even if stored token differs.""" + log = self._run(stored_token=42, expected_input_id=-1) + assert _n_violations(log) == 0 + + def test_match_records_no_violation(self) -> None: + """Matching stored vs expected token: zero violations.""" + log = self._run(stored_token=42, expected_input_id=42) + assert _n_violations(log) == 0 + + def test_mismatch_fires_verify_token_bit(self) -> None: + """Mismatch: kVerifyTokenMismatch bit set; expected_token field populated.""" + log = self._run(stored_token=42, expected_input_id=99) + assert _n_violations(log) == 1 + row = log.ring[0].tolist() + assert_only_bits_set( + int(row[consts.VIOLATION_FIELD_FAIL_REASON_BITS]), + int(consts.FailReason.VERIFY_TOKEN_MISMATCH), + ) + assert int(row[consts.VIOLATION_FIELD_STORED_TOKEN]) == 42 + assert int(row[consts.VIOLATION_FIELD_EXPECTED_TOKEN]) == 99 + + def test_check_disabled_never_raises_token_mismatch(self) -> None: + """check_verify_expected_token=False: token mismatch is silently ignored byte-equal CUDA vs ref.""" + log = self._run( + stored_token=42, + expected_input_id=99, + check_verify_expected_token=False, + ) + assert _n_violations(log) == 0 + + def test_check_disabled_does_not_read_expected_tokens_tensor(self) -> None: + """check_verify_expected_token=False with garbage expected_input_id: kernel must not deref the tensor.""" + buf_pair = _buf_pair() + _stamp_head(buf_pair, slot_idx=1) + garbage_value = (1 << 63) - 1 + plan_pair = _plan_pair_single( + slot_idx=1, position=0, expected_input_id=garbage_value + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + check_verify_expected_token=False, + ) + assert _n_violations(cuda_log) == 0 + + def test_token_and_position_both_mismatch_set_both_bits(self) -> None: + """token mismatch + position mismatch: both fail bits set; expected_token row carries the gathered id.""" + buf_pair = _buf_pair() + slot_idx = 5 + _stamp_head(buf_pair, slot_idx=slot_idx, position=10) + plan_pair = _plan_pair_single( + slot_idx=slot_idx, position=99, expected_input_id=123 + ) + cuda_log, _ = run_verify_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + check_verify_expected_token=True, + ) + assert _n_violations(cuda_log) == 1 + row = cuda_log.ring[0].tolist() + expected_bits = int(consts.FailReason.VERIFY_TOKEN_MISMATCH) | int( + consts.FailReason.VERIFY_POSITION_MISMATCH + ) + assert_only_bits_set( + int(row[consts.VIOLATION_FIELD_FAIL_REASON_BITS]), expected_bits + ) + assert int(row[consts.VIOLATION_FIELD_STORED_TOKEN]) == 42 + assert int(row[consts.VIOLATION_FIELD_EXPECTED_TOKEN]) == 123 + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_write_fuzz.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_write_fuzz.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff56a7b871f1d1dbf493a8fc300e9f4cf19f965 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_write_fuzz.py @@ -0,0 +1,257 @@ +from __future__ import annotations + +import random +from dataclasses import dataclass + +import pytest +import torch + +from sglang.jit_kernel.kv_canary import consts +from sglang.jit_kernel.kv_canary.verify import ( + CanaryLaunchTag, + RealKvSource, +) +from sglang.jit_kernel.kv_canary.write import WritePlan +from sglang.jit_kernel.tests.kv_canary._canary_helpers import ( + FakeViolationLog, + make_canary_buf, + make_log_pair, + make_write_plan_pair, + stamp_pair, +) +from sglang.jit_kernel.tests.kv_canary._differential import _run_both_write +from sglang.jit_kernel.tests.kv_canary._fixtures import ( + clone_real_kv_sources, + make_real_kv_sources, +) +from sglang.jit_kernel.tests.kv_canary._fuzz_driver import ( + FUZZ_SEEDS_PR, + run_fuzz_combo, +) +from sglang.jit_kernel.tests.kv_canary._invariants import WriteInvariants +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + + +_DEVICE = torch.device("cuda") + +_FUZZ_ITER_PER_SEED = 30 + + +@dataclass(frozen=True, slots=True, kw_only=True) +class WriteFuzzInputs: + cuda_canary_buf: torch.Tensor + ref_canary_buf: torch.Tensor + plan_cuda: WritePlan + plan_ref: WritePlan + input_ids: torch.Tensor + positions: torch.Tensor + out_cache_loc: torch.Tensor + kernel_kind: CanaryLaunchTag + enable_write_verify_inputs: bool + expected_input_tokens: torch.Tensor + expected_input_positions: torch.Tensor + real_kv_sources_cuda: tuple[RealKvSource, ...] + real_kv_sources_ref: tuple[RealKvSource, ...] + real_kv_hash_mode: consts.RealKvHashMode + ring_capacity: int + + +def _draw_random_write_inputs(rng: random.Random) -> WriteFuzzInputs: + enable_write_verify_inputs = rng.choice([False, True]) + hash_mode = rng.choice( + [ + consts.RealKvHashMode.NONE, + consts.RealKvHashMode.PARTIAL, + consts.RealKvHashMode.ALL, + ] + ) + src_count = rng.choice([1, 2, 4]) + page_size = rng.choice([1, 16]) + bytes_per = rng.choice([16, 64, 128]) + kernel_kind = rng.choice(list(CanaryLaunchTag)) + ring_capacity = rng.choice([16, 64, 256]) + + n_reqs = rng.randint(1, 4) + per_req_tokens: list[int] = [rng.randint(1, 5) for _ in range(n_reqs)] + total_tokens = sum(per_req_tokens) + num_slots = max(total_tokens + 8, 16) + + sources_cuda = make_real_kv_sources( + count=src_count, + num_bytes_per_token=bytes_per, + page_size=page_size, + num_slots=num_slots, + device=_DEVICE, + rng=rng, + ) + sources_ref = clone_real_kv_sources(sources_cuda) + + cuda_buf = make_canary_buf( + num_slots=num_slots, slot_stride_bytes=32, device=_DEVICE + ) + ref_buf = cuda_buf.clone() + + write_offsets: list[int] = [0] + running = 0 + for t in per_req_tokens: + running += t + write_offsets.append(running) + slot_pool = list(range(1, num_slots)) + rng.shuffle(slot_pool) + seed_slot_indices: list[int] = [] + for _ in range(n_reqs): + if rng.random() < 0.4 or len(slot_pool) <= total_tokens: + seed_slot_indices.append(-1) + else: + seed_slot_indices.append(slot_pool.pop()) + + out_cache_loc_list: list[int] = [] + for _ in range(total_tokens): + if not slot_pool: + out_cache_loc_list.append(-1) + else: + out_cache_loc_list.append(slot_pool.pop()) + + plan_cuda, plan_ref = make_write_plan_pair( + write_offsets=write_offsets, + seed_slot_indices=seed_slot_indices, + num_valid_reqs=n_reqs, + device=_DEVICE, + ) + + input_ids = torch.tensor( + [rng.randint(-(1 << 31), (1 << 31) - 1) for _ in range(total_tokens)], + dtype=torch.int64, + device=_DEVICE, + ) + # Per-chain sequential positions so the write kernel's chain-step position assert holds. + # For chains with a real seed slot, stamp the seed with (chain_start_position - 1) so the + # first chain entry's position == seed.position + 1. + chain_start_positions: list[int] = [rng.randint(0, 1024) for _ in range(n_reqs)] + positions_list: list[int] = [] + for r in range(n_reqs): + start = chain_start_positions[r] + positions_list.extend(start + i for i in range(per_req_tokens[r])) + seed_slot = seed_slot_indices[r] + if seed_slot >= 0: + stamp_pair( + (cuda_buf, ref_buf), + slot_idx=seed_slot, + token=0, + position=start - 1, + prev_hash=0, + ) + positions = torch.tensor(positions_list, dtype=torch.int64, device=_DEVICE) + out_cache_loc = torch.tensor(out_cache_loc_list, dtype=torch.int64, device=_DEVICE) + expected_input_tokens = input_ids.clone() + expected_input_positions = positions.clone() + if enable_write_verify_inputs: + candidate_indices = [ + idx for idx, slot in enumerate(out_cache_loc_list) if slot >= 0 + ] + rng.shuffle(candidate_indices) + mismatch_count = rng.randint(0, len(candidate_indices)) + for idx in candidate_indices[:mismatch_count]: + if rng.choice([False, True]): + expected_input_tokens[idx] = expected_input_tokens[idx] + 1 + else: + expected_input_positions[idx] = expected_input_positions[idx] + 1 + + return WriteFuzzInputs( + cuda_canary_buf=cuda_buf, + ref_canary_buf=ref_buf, + plan_cuda=plan_cuda, + plan_ref=plan_ref, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + kernel_kind=kernel_kind, + enable_write_verify_inputs=enable_write_verify_inputs, + expected_input_tokens=expected_input_tokens, + expected_input_positions=expected_input_positions, + real_kv_sources_cuda=sources_cuda, + real_kv_sources_ref=sources_ref, + real_kv_hash_mode=hash_mode, + ring_capacity=ring_capacity, + ) + + +def _run_one(inputs: WriteFuzzInputs) -> None: + cuda_buf_before = inputs.cuda_canary_buf.clone() + cuda_log, ref_log = make_log_pair(capacity=inputs.ring_capacity, device=_DEVICE) + log_before = FakeViolationLog.allocate( + capacity=inputs.ring_capacity, device=_DEVICE + ) + _run_both_write( + cuda_canary_buf=inputs.cuda_canary_buf, + ref_canary_buf=inputs.ref_canary_buf, + plan_cuda=inputs.plan_cuda, + plan_ref=inputs.plan_ref, + input_ids=inputs.input_ids, + positions=inputs.positions, + out_cache_loc=inputs.out_cache_loc, + enable_write_verify_inputs=inputs.enable_write_verify_inputs, + expected_input_tokens=inputs.expected_input_tokens, + expected_input_positions=inputs.expected_input_positions, + cuda_log=cuda_log, + ref_log=ref_log, + real_kv_sources_cuda=inputs.real_kv_sources_cuda, + real_kv_sources_ref=inputs.real_kv_sources_ref, + real_kv_hash_mode=inputs.real_kv_hash_mode, + kernel_kind=inputs.kernel_kind, + assert_equal=False, + ) + assert torch.equal( + inputs.cuda_canary_buf, inputs.ref_canary_buf + ), "CUDA vs ref canary_buf diverged" + assert int(cuda_log.write_index[0].item()) == int(ref_log.write_index[0].item()) + assert int(cuda_log.slot_run_counter[0].item()) == int( + ref_log.slot_run_counter[0].item() + ) + assert int(cuda_log.kernel_run_counter[0].item()) == int( + ref_log.kernel_run_counter[0].item() + ) + WriteInvariants.assert_all( + canary_buf_before=cuda_buf_before, + canary_buf_after=inputs.cuda_canary_buf, + plan=inputs.plan_cuda, + input_ids=inputs.input_ids, + positions=inputs.positions, + out_cache_loc=inputs.out_cache_loc, + enable_write_verify_inputs=inputs.enable_write_verify_inputs, + expected_input_tokens=inputs.expected_input_tokens, + expected_input_positions=inputs.expected_input_positions, + log_before=log_before, + log_after=cuda_log, + ) + + +def _summarize(inputs: WriteFuzzInputs) -> str: + n_active = int(inputs.plan_cuda.write_num_valid_reqs[0].item()) + total = int(inputs.plan_cuda.write_offsets[n_active].item()) + return ( + f"n_reqs={n_active} total_tokens={total} kind={inputs.kernel_kind.name} " + f"pseudo={inputs.enable_write_verify_inputs} hash_mode={inputs.real_kv_hash_mode.name} " + f"sources={len(inputs.real_kv_sources_cuda)}" + ) + + +@pytest.mark.parametrize("seed", FUZZ_SEEDS_PR) +def test_write_fuzz_full_combo(seed: int) -> None: + """Multi-dim write fuzzer: random pseudo/hash/kernel/page/source × N iters, byte-equal.""" + run_fuzz_combo( + seed, + draw_fn=_draw_random_write_inputs, + run_one_fn=_run_one, + summarize_fn=_summarize, + n_iter=_FUZZ_ITER_PER_SEED, + ) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_write_hand.py b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_write_hand.py new file mode 100644 index 0000000000000000000000000000000000000000..20ad3582521a6cb0d38ea5a18233b132ec1a4fad --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/kv_canary/test_write_hand.py @@ -0,0 +1,1224 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Callable +from unittest.mock import patch + +import pytest +import torch + +from sglang.jit_kernel.kv_canary import consts +from sglang.jit_kernel.kv_canary import write as write_module +from sglang.jit_kernel.kv_canary.consts import splitmix64, splitmix64_mix3 +from sglang.jit_kernel.kv_canary.verify import ( + CANARY_SLOT_BYTES, + CanaryLaunchTag, + RealKvSource, + VerifyOrWriteContext, + launch_canary_verify_kernel, +) +from sglang.jit_kernel.kv_canary.write import ( + launch_canary_write_kernel, +) +from sglang.jit_kernel.tests.kv_canary._canary_helpers import ( + FakeViolationLog, + assert_canary_state_equal, + assert_only_bits_set, + chain_anchor_signed, + make_canary_buf, + make_canary_buf_pair, + make_log_pair, + make_real_kv_source, + make_real_kv_sources, + make_verify_plan, + make_write_plan, + make_write_plan_pair, + read_slot_fields, + stamp_pair, + to_signed_int64, +) +from sglang.jit_kernel.tests.kv_canary._differential import ( + _run_both_write, + run_write_diff, +) +from sglang.jit_kernel.tests.kv_canary._fixtures import ( + clone_real_kv_sources, + dummy_pseudo_tensors, +) +from sglang.jit_kernel.tests.kv_canary._hand_oracle import ( + _hand_fold_all, + _hand_fold_partial, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + + +_DEVICE = torch.device("cuda") + + +def _int32_tensor(values: list[int]) -> torch.Tensor: + return torch.tensor(values, dtype=torch.int64, device=_DEVICE) + + +def _make_default_buf_pair( + num_slots: int = 16, slot_stride_bytes: int = 32 +) -> tuple[torch.Tensor, torch.Tensor]: + return make_canary_buf_pair( + num_slots=num_slots, slot_stride_bytes=slot_stride_bytes, device=_DEVICE + ) + + +def _run_write( + *, + buf_pair: tuple[torch.Tensor, torch.Tensor], + input_ids: list[int] | torch.Tensor, + positions: list[int] | torch.Tensor, + out_cache_loc: list[int] | torch.Tensor, + write_offsets: list[int] | None = None, + seed_slot_indices: list[int] = (-1,), + num_valid_reqs: int = 1, + req_capacity: int | None = None, + enable_write_verify_inputs: bool = False, + expected_input_tokens: torch.Tensor | None = None, + expected_input_positions: torch.Tensor | None = None, + real_kv_sources_pair: ( + tuple[tuple[RealKvSource, ...], tuple[RealKvSource, ...]] | None + ) = None, + real_kv_hash_mode: consts.RealKvHashMode = consts.RealKvHashMode.NONE, + assert_equal: bool = True, +) -> tuple[FakeViolationLog, FakeViolationLog]: + """Shared scaffold: build write plan + pseudo tensors and call ``run_write_diff``. + + ``write_offsets`` defaults to ``[0, len(input_ids)]`` (one req covering all entries). + ``expected_input_*`` default to ``dummy_pseudo_tensors(len(input_ids))``. + """ + ids_t = ( + input_ids + if isinstance(input_ids, torch.Tensor) + else _int32_tensor(list(input_ids)) + ) + pos_t = ( + positions + if isinstance(positions, torch.Tensor) + else _int32_tensor(list(positions)) + ) + loc_t = ( + out_cache_loc + if isinstance(out_cache_loc, torch.Tensor) + else _int32_tensor(list(out_cache_loc)) + ) + n_tokens = int(ids_t.shape[0]) + + if write_offsets is None: + write_offsets = [0, n_tokens] + + plan_kwargs = dict( + write_offsets=write_offsets, + seed_slot_indices=list(seed_slot_indices), + num_valid_reqs=num_valid_reqs, + device=_DEVICE, + ) + if req_capacity is not None: + plan_kwargs["req_capacity"] = req_capacity + plan_pair = make_write_plan_pair(**plan_kwargs) + + if expected_input_tokens is None or expected_input_positions is None: + pseudo_tokens, pseudo_positions = dummy_pseudo_tensors(n_tokens) + if expected_input_tokens is None: + expected_input_tokens = pseudo_tokens + if expected_input_positions is None: + expected_input_positions = pseudo_positions + + extra_kwargs: dict = {} + if real_kv_sources_pair is not None: + extra_kwargs["real_kv_sources_pair"] = real_kv_sources_pair + return run_write_diff( + buf_pair=buf_pair, + plan_pair=plan_pair, + input_ids=ids_t, + positions=pos_t, + out_cache_loc=loc_t, + enable_write_verify_inputs=enable_write_verify_inputs, + expected_input_tokens=expected_input_tokens, + expected_input_positions=expected_input_positions, + real_kv_hash_mode=real_kv_hash_mode, + assert_equal=assert_equal, + **extra_kwargs, + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class _WriteSingleSlotInput: + token: int = 42 + position: int = 0 + enable_write_verify_inputs: bool = False + real_kv_sources: tuple[RealKvSource, ...] = () + real_kv_hash_mode: consts.RealKvHashMode = consts.RealKvHashMode.NONE + + +class _RecordingWriteModule: + def __init__(self) -> None: + self.calls: list[tuple[object, ...]] = [] + + def canary_write_step_cuda(self, *args: object) -> None: + self.calls.append(args) + + +def _run_write_single_slot_byte_equal(case: _WriteSingleSlotInput) -> None: + sources_cuda = case.real_kv_sources + sources_ref = clone_real_kv_sources(sources_cuda) + _run_write( + buf_pair=_make_default_buf_pair(), + input_ids=[case.token], + positions=[case.position], + out_cache_loc=[0], + enable_write_verify_inputs=case.enable_write_verify_inputs, + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=case.real_kv_hash_mode, + ) + + +class TestSeedSlot: + def setup_method(self) -> None: + self.buf_pair = _make_default_buf_pair() + + def test_seed_slot_idx_negative_uses_anchor(self) -> None: + """``seed_slot_idx == -1`` → initial ``running_prev_hash`` is ``splitmix64(consts.CANARY_CHAIN_ANCHOR)``.""" + _run_write( + buf_pair=self.buf_pair, + input_ids=[42], + positions=[0], + out_cache_loc=[3], + ) + + stored_token, stored_position, stored_prev_hash, _ = read_slot_fields( + canary_buf=self.buf_pair[0], slot_idx=3 + ) + assert stored_token == 42 + assert stored_position == 0 + assert stored_prev_hash == chain_anchor_signed() + + def test_seed_slot_idx_loads_predecessor(self) -> None: + """``seed_slot_idx >= 0`` → load 3 fields (token, position, prev_hash) from ``canary_buf[seed]`` and splitmix64_mix3-advance into prev_hash.""" + # Step: pre-stamp slot 7 with a known chain link. + seed_token, seed_position = 100, 4 + seed_prev_signed = to_signed_int64(splitmix64(consts.CANARY_CHAIN_ANCHOR)) + stamp_pair( + self.buf_pair, + slot_idx=7, + token=seed_token, + position=seed_position, + prev_hash=seed_prev_signed, + ) + + _run_write( + buf_pair=self.buf_pair, + input_ids=[999], + positions=[5], + out_cache_loc=[2], + seed_slot_indices=[7], + ) + + expected_prev_hash = splitmix64_mix3( + splitmix64(consts.CANARY_CHAIN_ANCHOR), seed_token, seed_position + ) + _, _, stored_prev_hash, _ = read_slot_fields( + canary_buf=self.buf_pair[0], slot_idx=2 + ) + assert stored_prev_hash == to_signed_int64(expected_prev_hash) + + def test_seed_slot_chain_link_continuous(self) -> None: + """After write, ``slot[0].prev_hash`` is consistent with verify's chain reconstruction from seed.""" + # Step 1: write a chain from seed slot=7 → newly written slot=2. Then run verify with prev=7 and + # assert no violation — i.e., slot[2].prev_hash is splitmix64_mix3(seed.prev_hash, seed.token, seed.position). + cuda_buf = self.buf_pair[0] + seed_token, seed_position = 11, 0 + seed_prev_signed = to_signed_int64(splitmix64(consts.CANARY_CHAIN_ANCHOR)) + stamp_pair( + self.buf_pair, + slot_idx=7, + token=seed_token, + position=seed_position, + prev_hash=seed_prev_signed, + ) + + _run_write( + buf_pair=self.buf_pair, + input_ids=[222], + positions=[1], + out_cache_loc=[2], + seed_slot_indices=[7], + assert_equal=False, + ) + + # Step 2: verify slot[2] with prev=7 — expects no violation. + verify_plan = make_verify_plan( + slot_indices=[2], positions=[1], prev_slot_indices=[7], device=_DEVICE + ) + verify_log = FakeViolationLog.allocate(device=_DEVICE) + launch_canary_verify_kernel( + context=VerifyOrWriteContext( + canary_buf=cuda_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=verify_log.ring, + violation_write_index=verify_log.write_index, + slot_run_counter=verify_log.slot_run_counter, + kernel_run_counter=verify_log.kernel_run_counter, + enable_chain_position_assert=verify_log.enable_chain_position_assert, + real_kv_sources=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ), + plan=verify_plan, + check_verify_expected_token=True, + ) + torch.cuda.synchronize() + assert int(verify_log.write_index[0].item()) == 0 + + def test_seed_slot_resume_5_step_hardcoded(self) -> None: + cuda_buf = make_canary_buf(num_slots=50, slot_stride_bytes=32, device=_DEVICE) + ref_buf = cuda_buf.clone() + buf_pair = (cuda_buf, ref_buf) + seed_token = 7 + seed_position = 10 + seed_prev_hash_signed = to_signed_int64(splitmix64(consts.CANARY_CHAIN_ANCHOR)) + stamp_pair( + buf_pair, + slot_idx=42, + token=seed_token, + position=seed_position, + prev_hash=seed_prev_hash_signed, + ) + + predecessor_advance = splitmix64_mix3( + splitmix64(consts.CANARY_CHAIN_ANCHOR), seed_token, seed_position + ) + + tokens = [101, 202, 303, 404, 505] + positions = [11, 12, 13, 14, 15] + real_kv = [0, 0, 0, 0, 0] + out_cache_loc = [0, 1, 2, 3, 4] + + expected_prev_hashes: list[int] = [] + running = predecessor_advance + for t, p, r in zip(tokens, positions, real_kv): + expected_prev_hashes.append(running) + running = splitmix64_mix3(running, t, p) + + cuda_log, _ = _run_write( + buf_pair=buf_pair, + input_ids=tokens, + positions=positions, + out_cache_loc=out_cache_loc, + write_offsets=[0, 5], + seed_slot_indices=[42], + ) + + for slot_idx, expected_token, expected_position, expected_prev_u64 in zip( + out_cache_loc, tokens, positions, expected_prev_hashes + ): + stored_token, stored_position, stored_prev_hash, stored_real_kv_hash = ( + read_slot_fields(canary_buf=cuda_buf, slot_idx=slot_idx) + ) + assert stored_token == expected_token + assert stored_position == expected_position + assert stored_prev_hash == to_signed_int64(expected_prev_u64) + assert stored_real_kv_hash == 0 + + assert int(cuda_log.write_index[0].item()) == 0 + + def test_seed_continues_existing_chain(self) -> None: + """Pre-stamp seed slot; subsequent write should continue chain from splitmix64_mix3(seed.*).""" + seed_slot = 3 + seed_token = 7 + seed_position = 1 + seed_real_kv = 0 + expected_seed_prev_hash = splitmix64(consts.CANARY_CHAIN_ANCHOR) + stamp_pair( + self.buf_pair, + slot_idx=seed_slot, + token=seed_token, + position=seed_position, + prev_hash=to_signed_int64(expected_seed_prev_hash), + real_kv_hash=to_signed_int64(seed_real_kv), + ) + + new_slot = 4 + new_token = 13 + new_position = 2 + expected_running = splitmix64_mix3( + expected_seed_prev_hash, seed_token, seed_position + ) + + _run_write( + buf_pair=self.buf_pair, + input_ids=[new_token], + positions=[new_position], + out_cache_loc=[new_slot], + seed_slot_indices=[seed_slot], + ) + + new_stored = read_slot_fields(canary_buf=self.buf_pair[0], slot_idx=new_slot) + assert new_stored[0] == new_token + assert new_stored[1] == new_position + assert new_stored[2] == to_signed_int64( + expected_running + ), f"new slot prev_hash {new_stored[2]} != expected {to_signed_int64(expected_running)}" + + +class TestChain: + def setup_method(self) -> None: + self.buf_pair = _make_default_buf_pair() + + def test_chain_link_byte_equal_5_step(self) -> None: + """5-step chain, buf / ring / counters byte-equal against ref.""" + _run_write( + buf_pair=self.buf_pair, + input_ids=[10, 20, 30, 40, 50], + positions=[0, 1, 2, 3, 4], + out_cache_loc=[0, 1, 2, 3, 4], + ) + + def test_chain_link_byte_equal_5_step_hardcoded(self) -> None: + """5-step write chain with hand-computed splitmix64 expected fields per slot.""" + tokens = [101, 202, 303, 404, 505] + positions = [0, 1, 2, 3, 4] + out_cache_loc = [0, 1, 2, 3, 4] + real_kv_hashes = [0, 0, 0, 0, 0] + + # Step 1: compute the expected stored prev_hash sequence in pure Python via splitmix64. + expected_prev_hashes_u64: list[int] = [] + running = splitmix64(consts.CANARY_CHAIN_ANCHOR) + for token, position, real_kv_hash in zip(tokens, positions, real_kv_hashes): + expected_prev_hashes_u64.append(running) + running = splitmix64_mix3(running, token, position) + expected_prev_hashes_signed = [ + to_signed_int64(h) for h in expected_prev_hashes_u64 + ] + + _run_write( + buf_pair=self.buf_pair, + input_ids=tokens, + positions=positions, + out_cache_loc=out_cache_loc, + ) + + # Step 2: verify every slot's stored 4 fields match the hardcoded expected sequence. + for slot_idx, expected_token, expected_position, expected_prev_signed in zip( + out_cache_loc, tokens, positions, expected_prev_hashes_signed + ): + stored_token, stored_position, stored_prev_hash, stored_real_kv_hash = ( + read_slot_fields(canary_buf=self.buf_pair[0], slot_idx=slot_idx) + ) + assert stored_token == expected_token + assert stored_position == expected_position + assert stored_prev_hash == expected_prev_signed + assert stored_real_kv_hash == 0 + + def test_chain_advances_with_real_kv_hash_all(self) -> None: + """ALL mode + 2 sources + 5-step chain: stored prev_hash recoverable from seed.""" + cuda_buf = self.buf_pair[0] + sources_cuda = make_real_kv_sources( + count=2, + num_bytes_per_token=16, + page_size=1, + num_slots=16, + device=_DEVICE, + ) + sources_ref = clone_real_kv_sources(sources_cuda) + + slot_indices = [1, 2, 3, 4, 5] + tokens = [11, 22, 33, 44, 55] + positions = [0, 1, 2, 3, 4] + + _run_write( + buf_pair=self.buf_pair, + input_ids=tokens, + positions=positions, + out_cache_loc=slot_indices, + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + running = splitmix64(consts.CANARY_CHAIN_ANCHOR) + for slot_idx, token, position in zip(slot_indices, tokens, positions): + stored_prev_signed, stored_real_kv_hash = read_slot_fields( + canary_buf=cuda_buf, slot_idx=slot_idx + )[2:] + assert stored_prev_signed == to_signed_int64( + running + ), f"slot {slot_idx}: stored prev_hash != recomputed chain step" + running = splitmix64_mix3(running, token, position) + + +class TestMockMode: + def setup_method(self) -> None: + self.buf_pair = _make_default_buf_pair() + + def test_mock_mode_off_ignores_expected(self) -> None: + """``enable_write_verify_inputs = OFF`` → expected tensors are ignored (we pass garbage to prove the kernel skips them).""" + # Garbage expected tensors that, if the kernel mistakenly reads, would generate mismatches. + cuda_log, _ = _run_write( + buf_pair=self.buf_pair, + input_ids=[1, 2, 3], + positions=[0, 1, 2], + out_cache_loc=[0, 1, 2], + expected_input_tokens=_int32_tensor([999, 999, 999]), + expected_input_positions=_int32_tensor([999, 999, 999]), + ) + + assert int(cuda_log.write_index[0].item()) == 0 + + def test_mock_mode_on_match_no_violation(self) -> None: + """``enable_write_verify_inputs = ON`` and expected matches actual → no violation, chain advances.""" + input_ids = _int32_tensor([7, 8, 9]) + positions = _int32_tensor([0, 1, 2]) + cuda_log, _ = _run_write( + buf_pair=self.buf_pair, + input_ids=input_ids, + positions=positions, + out_cache_loc=[0, 1, 2], + enable_write_verify_inputs=True, + expected_input_tokens=input_ids.clone(), + expected_input_positions=positions.clone(), + ) + + assert int(cuda_log.write_index[0].item()) == 0 + + def test_mock_mode_on_token_mismatch_records_violation(self) -> None: + """``enable_write_verify_inputs = ON`` token mismatch → violation recorded; chain advances on ACTUAL token.""" + cuda_log, _ = _run_write( + buf_pair=self.buf_pair, + input_ids=[42], + positions=[0], + out_cache_loc=[0], + enable_write_verify_inputs=True, + expected_input_tokens=_int32_tensor([99]), + expected_input_positions=_int32_tensor([0]), + ) + + fail_bits = int( + cuda_log.ring[0, consts.VIOLATION_FIELD_FAIL_REASON_BITS].item() + ) + assert_only_bits_set(fail_bits, consts.FailReason.WRITE_TOKEN_MISMATCH) + # Chain advances on actual (42), not expected (99). Stored token should be 42. + stored_token, _, _, _ = read_slot_fields( + canary_buf=self.buf_pair[0], slot_idx=0 + ) + assert stored_token == 42 + + def test_mock_mode_on_position_mismatch_records_violation(self) -> None: + """``enable_write_verify_inputs = ON`` position mismatch → violation recorded; chain advances on ACTUAL position.""" + cuda_log, _ = _run_write( + buf_pair=self.buf_pair, + input_ids=[42], + positions=[7], + out_cache_loc=[0], + enable_write_verify_inputs=True, + expected_input_tokens=_int32_tensor([42]), + expected_input_positions=_int32_tensor([0]), + ) + + fail_bits = int( + cuda_log.ring[0, consts.VIOLATION_FIELD_FAIL_REASON_BITS].item() + ) + assert_only_bits_set(fail_bits, consts.FailReason.WRITE_POSITION_MISMATCH) + _, stored_position, _, _ = read_slot_fields( + canary_buf=self.buf_pair[0], slot_idx=0 + ) + assert stored_position == 7 + + def test_mock_mode_chain_advances_on_actual_not_expected(self) -> None: + """Expected differs from actual on every entry → downstream verify must NOT cascade chain errors.""" + cuda_buf = self.buf_pair[0] + # Every actual differs from expected. + cuda_log, _ = _run_write( + buf_pair=self.buf_pair, + input_ids=[10, 20, 30], + positions=[0, 1, 2], + out_cache_loc=[1, 2, 3], + enable_write_verify_inputs=True, + expected_input_tokens=_int32_tensor([999, 999, 999]), + expected_input_positions=_int32_tensor([999, 999, 999]), + ) + + # All 3 entries should fire a violation row. + assert int(cuda_log.write_index[0].item()) == 3 + # Run a downstream verify — it must see no chain mismatch because chain advanced on actuals. + verify_plan = make_verify_plan( + slot_indices=[1, 2, 3], + positions=[0, 1, 2], + prev_slot_indices=[-1, 1, 2], + device=_DEVICE, + ) + verify_log = FakeViolationLog.allocate(device=_DEVICE) + launch_canary_verify_kernel( + context=VerifyOrWriteContext( + canary_buf=cuda_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=verify_log.ring, + violation_write_index=verify_log.write_index, + slot_run_counter=verify_log.slot_run_counter, + kernel_run_counter=verify_log.kernel_run_counter, + enable_chain_position_assert=verify_log.enable_chain_position_assert, + real_kv_sources=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ), + plan=verify_plan, + check_verify_expected_token=True, + ) + torch.cuda.synchronize() + assert int(verify_log.write_index[0].item()) == 0 + + @pytest.mark.parametrize("bit_to_trigger", ["MOCK_TOKEN", "MOCK_POSITION"]) + @pytest.mark.parametrize("injection_position", ["head", "mid", "last"]) + def test_mock_violation_bit_injection_position_matrix( + self, + bit_to_trigger: str, + injection_position: str, + ) -> None: + """Sweep injection_position x bit_to_trigger for write-kernel pseudo-mode fail-reason coverage.""" + slot_count = 5 + tokens = [10, 20, 30, 40, 50] + positions = [0, 1, 2, 3, 4] + out_cache_locs = [0, 1, 2, 3, 4] + corruption_index = {"head": 0, "mid": 2, "last": 4}[injection_position] + corrupt_slot = out_cache_locs[corruption_index] + + expected_bit = { + "MOCK_TOKEN": consts.FailReason.WRITE_TOKEN_MISMATCH, + "MOCK_POSITION": consts.FailReason.WRITE_POSITION_MISMATCH, + }[bit_to_trigger] + + input_ids = _int32_tensor(tokens) + positions_t = _int32_tensor(positions) + out_cache_loc = _int32_tensor(out_cache_locs) + + pseudo_tokens = input_ids.clone() + pseudo_positions = positions_t.clone() + + if bit_to_trigger == "MOCK_TOKEN": + pseudo_tokens[corruption_index] = tokens[corruption_index] + 999 + else: + pseudo_positions[corruption_index] = positions[corruption_index] + 99 + + cuda_log, ref_log = _run_write( + buf_pair=self.buf_pair, + input_ids=input_ids, + positions=positions_t, + out_cache_loc=out_cache_loc, + write_offsets=[0, slot_count], + enable_write_verify_inputs=True, + expected_input_tokens=pseudo_tokens, + expected_input_positions=pseudo_positions, + assert_equal=False, + ) + + found = False + for row_idx in range(int(cuda_log.write_index[0].item())): + fail_bits = int( + cuda_log.ring[row_idx, consts.VIOLATION_FIELD_FAIL_REASON_BITS].item() + ) + row_slot = int(cuda_log.ring[row_idx, 1].item()) + if (fail_bits & expected_bit) and row_slot == corrupt_slot: + found = True + break + assert found, ( + f"expected bit {expected_bit:#x} at slot {corrupt_slot} not found in ring " + f"(bit_to_trigger={bit_to_trigger} injection_position={injection_position})" + ) + assert_canary_state_equal(log_a=cuda_log, log_b=ref_log) + + +class TestSlotHandling: + def setup_method(self) -> None: + self.buf_pair = _make_default_buf_pair() + + def test_negative_slot_skips_entry(self) -> None: + """``out_cache_loc[i] < 0`` → that entry is skipped: no buf write, no violation, no + canary slot mutation, and no write slot_run_counter increment. + Covers both SWA out-of-window (after caller-side LUT gather) and explicit padding intents. + """ + # Two entries: first writes to slot 4 normally; second has slot=-1 and must be skipped. + cuda_log, _ = _run_write( + buf_pair=self.buf_pair, + input_ids=[42, 99], + positions=[0, 1], + out_cache_loc=[4, -1], + ) + + stored_token, _, _, _ = read_slot_fields( + canary_buf=self.buf_pair[0], slot_idx=4 + ) + assert stored_token == 42 + assert int(cuda_log.slot_run_counter.item()) == 1 + + def test_pre_translated_slot_writes_normally(self) -> None: + """``out_cache_loc[i] >= 0`` → the kernel writes to exactly that slot, with no LUT applied. This + confirms the kernel is SWA-agnostic: SWA endpoints feed the same shape of input here after their + host-side gather, so the contract is symmetric across FULL / SWA groups. + """ + # Slot 4 here could equally be a FULL-group raw out_cache_loc value, or the result of an SWA + # endpoint's host gather. The kernel can't tell the difference and that's the point. + _run_write( + buf_pair=self.buf_pair, + input_ids=[55], + positions=[0], + out_cache_loc=[4], + ) + + stored_token, _, _, _ = read_slot_fields( + canary_buf=self.buf_pair[0], slot_idx=4 + ) + assert stored_token == 55 + + def test_padding_block_skipped(self) -> None: + """``blockIdx.x >= write_num_valid_reqs[0]`` → block early-exits, no write to canary_buf.""" + # Allocate plan with req_capacity=4 but only declare 1 active req. + _run_write( + buf_pair=self.buf_pair, + input_ids=[1], + positions=[0], + out_cache_loc=[0], + req_capacity=4, + ) + + # Only slot 0 should have been written; padding blocks 1..3 must not touch the buffer. + stored_token, _, _, _ = read_slot_fields( + canary_buf=self.buf_pair[0], slot_idx=0 + ) + assert stored_token == 1 + for slot_idx in (1, 2, 3): + stored_token_other, _, _, _ = read_slot_fields( + canary_buf=self.buf_pair[0], slot_idx=slot_idx + ) + assert stored_token_other == 0 + + def test_write_skip_when_out_cache_loc_is_minus_one(self) -> None: + """out_cache_loc[i] = -1 → that entry's slot is untouched by write kernel.""" + cuda_buf = self.buf_pair[0] + cuda_buf_before_slot_view = cuda_buf.view(torch.int64).clone() + + _run_write( + buf_pair=self.buf_pair, + input_ids=[100, 200, 300], + positions=[0, 1, 2], + out_cache_loc=[5, -1, 7], + ) + + after = cuda_buf.view(torch.int64) + for slot in range(cuda_buf.shape[0]): + if slot in (5, 7): + continue + assert torch.equal( + after[slot], cuda_buf_before_slot_view[slot] + ), f"slot {slot} should not have been written" + + def test_shrink_active_reqs_does_not_write_stale_slots(self) -> None: + """Run write with bs=3 plan after a bs=8 run on same buffer: stale slots from bs=8 stay intact.""" + cuda_buf = make_canary_buf(num_slots=32, slot_stride_bytes=32, device=_DEVICE) + ref_buf = cuda_buf.clone() + buf_pair = (cuda_buf, ref_buf) + + big_slots = list(range(1, 9)) + _run_write( + buf_pair=buf_pair, + input_ids=list(range(100, 108)), + positions=[0] * 8, + out_cache_loc=big_slots, + write_offsets=[0, 1, 2, 3, 4, 5, 6, 7, 8], + seed_slot_indices=[-1] * 8, + num_valid_reqs=8, + assert_equal=False, + ) + + untouched_snapshot = cuda_buf.view(torch.int64).clone() + + small_slots = [20, 21, 22] + _run_write( + buf_pair=buf_pair, + input_ids=[7, 8, 9], + positions=[0, 0, 0], + out_cache_loc=small_slots, + write_offsets=[0, 1, 2, 3], + seed_slot_indices=[-1, -1, -1], + num_valid_reqs=3, + assert_equal=False, + ) + + after = cuda_buf.view(torch.int64) + for slot in big_slots: + assert torch.equal( + after[slot], untouched_snapshot[slot] + ), f"slot {slot} from earlier bs=8 run was overwritten by bs=3 run" + + +class TestRealKvHash: + def setup_method(self) -> None: + self.buf_pair = _make_default_buf_pair() + + def test_real_kv_mode_off_writes_zero(self) -> None: + """``consts.RealKvHashMode.NONE`` → ``real_kv_hash`` field is written as 0 regardless of source presence.""" + sources = make_real_kv_sources(count=2, device=_DEVICE) + + _run_write( + buf_pair=self.buf_pair, + input_ids=[1, 2], + positions=[0, 1], + out_cache_loc=[0, 1], + real_kv_sources_pair=(sources, sources), + ) + + _, _, _, real_kv_0 = read_slot_fields(canary_buf=self.buf_pair[0], slot_idx=0) + _, _, _, real_kv_1 = read_slot_fields(canary_buf=self.buf_pair[0], slot_idx=1) + assert real_kv_0 == 0 + assert real_kv_1 == 0 + + @pytest.mark.parametrize( + "mode", + [ + pytest.param(consts.RealKvHashMode.PARTIAL, id="partial"), + pytest.param(consts.RealKvHashMode.ALL, id="all"), + ], + ) + def test_real_kv_mode_byte_equal(self, mode: consts.RealKvHashMode) -> None: + """PARTIAL / ALL modes both produce CUDA-vs-ref byte-equal write state on a 3-entry chain.""" + sources_cuda = make_real_kv_sources(count=2, device=_DEVICE) + sources_ref = clone_real_kv_sources(sources_cuda) + + _run_write( + buf_pair=self.buf_pair, + input_ids=[10, 20, 30], + positions=[0, 1, 2], + out_cache_loc=[0, 1, 2], + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=mode, + ) + + @pytest.mark.parametrize("count", [1, 2, 3, 4]) + def test_real_kv_sources_fold_1_to_4(self, count: int) -> None: + """Folding ``count`` sources sequentially → CUDA matches ref for every count in {1..4}.""" + sources_cuda = make_real_kv_sources(count=count, device=_DEVICE) + sources_ref = clone_real_kv_sources(sources_cuda) + + _run_write( + buf_pair=self.buf_pair, + input_ids=[1, 2], + positions=[0, 1], + out_cache_loc=[0, 1], + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + def test_real_kv_source_above_4_raises(self) -> None: + """``len(real_kv_sources) > 4`` → host wrapper raises ValueError before launching.""" + cuda_buf = make_canary_buf(device=_DEVICE) + plan = make_write_plan( + write_offsets=[0, 1], + seed_slot_indices=[-1], + num_valid_reqs=1, + device=_DEVICE, + ) + input_ids = _int32_tensor([1]) + positions = _int32_tensor([0]) + out_cache_loc = _int32_tensor([0]) + log = FakeViolationLog.allocate(device=_DEVICE) + sources = make_real_kv_sources(count=4, device=_DEVICE) + extra = make_real_kv_source(device=_DEVICE) + too_many = sources + (extra,) + + with pytest.raises(ValueError, match="at most 4 RealKvSource"): + launch_canary_write_kernel( + context=VerifyOrWriteContext( + canary_buf=cuda_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=too_many, + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ), + plan=plan, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + enable_write_input_assert=False, + expected_input_tokens=None, + expected_input_positions=None, + ) + + @pytest.mark.parametrize( + "mode,fold_fn,expected_hash", + [ + pytest.param( + consts.RealKvHashMode.PARTIAL, + _hand_fold_partial, + 0x6041580849E6407D, + id="partial", + ), + pytest.param( + consts.RealKvHashMode.ALL, + _hand_fold_all, + 0x6041580849E6407D, + id="all", + ), + ], + ) + def test_real_kv_hash_fold_mode_writes_expected_hash_hardcoded( + self, + mode: consts.RealKvHashMode, + fold_fn: Callable[[bytes], int], + expected_hash: int, + ) -> None: + # Step 1: build one RealKvSource with read_bytes=16 and a fixed byte pattern at slot 0. + _PATTERN = bytes( + [ + 0x01, + 0x02, + 0x04, + 0x08, + 0x10, + 0x20, + 0x40, + 0x80, + 0x81, + 0x82, + 0x84, + 0x88, + 0x90, + 0xA0, + 0xC0, + 0xFF, + ] + ) + + # Step 2: verify hand-computed fold matches the hex literal. + assert fold_fn(_PATTERN) == expected_hash + + source_cuda = make_real_kv_source( + num_slots=16, + num_bytes_per_token=16, + page_size=1, + read_bytes=16, + device=_DEVICE, + ) + source_cuda.tensor[0, :16] = torch.tensor(list(_PATTERN), dtype=torch.uint8) + source_ref = RealKvSource( + tensor=source_cuda.tensor.clone(), + page_size=source_cuda.page_size, + num_bytes_per_token=source_cuda.num_bytes_per_token, + read_bytes=source_cuda.read_bytes, + ) + + # Step 3: run write kernel on slot 0 with the given mode. + _run_write( + buf_pair=self.buf_pair, + input_ids=[7], + positions=[0], + out_cache_loc=[0], + real_kv_sources_pair=((source_cuda,), (source_ref,)), + real_kv_hash_mode=mode, + ) + + # Step 4: assert stored real_kv_hash equals the hand-computed hex literal. + _, _, _, stored_real_kv_hash = read_slot_fields( + canary_buf=self.buf_pair[0], slot_idx=0 + ) + assert stored_real_kv_hash == to_signed_int64( + expected_hash + ), f"stored_real_kv_hash={stored_real_kv_hash:#x} expected={to_signed_int64(expected_hash):#x}" + + def test_paged_real_kv_hash_consistent_across_slots(self) -> None: + """page=16: writing two slots inside same page yields independent real_kv_hash per slot.""" + sources_cuda = make_real_kv_sources( + count=1, + num_bytes_per_token=16, + page_size=16, + num_slots=16, + device=_DEVICE, + ) + pattern_slot3 = bytes(range(1, 17)) + pattern_slot7 = bytes(range(101, 117)) + sources_cuda[0].tensor[0, 3 * 16 : 4 * 16] = torch.tensor( + list(pattern_slot3), dtype=torch.uint8, device=_DEVICE + ) + sources_cuda[0].tensor[0, 7 * 16 : 8 * 16] = torch.tensor( + list(pattern_slot7), dtype=torch.uint8, device=_DEVICE + ) + sources_ref = clone_real_kv_sources(sources_cuda) + + _run_write( + buf_pair=self.buf_pair, + input_ids=[42, 84], + positions=[0, 1], + out_cache_loc=[3, 7], + real_kv_sources_pair=(sources_cuda, sources_ref), + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ) + + slot3 = read_slot_fields(canary_buf=self.buf_pair[0], slot_idx=3) + slot7 = read_slot_fields(canary_buf=self.buf_pair[0], slot_idx=7) + assert slot3[3] == to_signed_int64(_hand_fold_all(pattern_slot3)) + assert slot7[3] == to_signed_int64(_hand_fold_all(pattern_slot7)) + assert slot3[3] != slot7[3] + + def test_multi_source_real_kv_fold_order_matters(self) -> None: + """Two sources folded in reverse order yields a different real_kv_hash (fold is ordered).""" + sources_a = make_real_kv_sources( + count=2, num_bytes_per_token=16, num_slots=8, device=_DEVICE + ) + sources_b = tuple(reversed(sources_a)) + + def _run_with(srcs: tuple[RealKvSource, ...]) -> tuple[int, int, int, int]: + buf = make_canary_buf(num_slots=16, slot_stride_bytes=32, device=_DEVICE) + plan = make_write_plan( + write_offsets=[0, 1], + seed_slot_indices=[-1], + num_valid_reqs=1, + device=_DEVICE, + ) + log = FakeViolationLog.allocate(device=_DEVICE) + launch_canary_write_kernel( + context=VerifyOrWriteContext( + canary_buf=buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=srcs, + real_kv_hash_mode=consts.RealKvHashMode.ALL, + ), + plan=plan, + input_ids=_int32_tensor([1]), + positions=_int32_tensor([0]), + out_cache_loc=_int32_tensor([2]), + enable_write_input_assert=False, + expected_input_tokens=None, + expected_input_positions=None, + ) + torch.cuda.synchronize() + return read_slot_fields(canary_buf=buf, slot_idx=2) + + fields_a = _run_with(sources_a) + fields_b = _run_with(sources_b) + assert fields_a[3] != 0 + assert fields_b[3] != 0 + assert ( + fields_a[3] != fields_b[3] + ), "reversing source order must change real_kv_hash (fold is ordered)" + + +class TestRunCounter: + def setup_method(self) -> None: + self.buf_pair = _make_default_buf_pair() + + def test_kernel_run_counter_per_call(self) -> None: + """``kernel_run_counter`` increments by 1 per call (even when ``write_num_valid_reqs == 0``).""" + plan_pair = make_write_plan_pair( + write_offsets=[0, 0], + seed_slot_indices=[-1], + num_valid_reqs=0, + device=_DEVICE, + ) + input_ids = _int32_tensor([0]) + positions = _int32_tensor([0]) + out_cache_loc = _int32_tensor([0]) + pseudo_tokens, pseudo_positions = dummy_pseudo_tensors(1) + cuda_log, ref_log = make_log_pair(device=_DEVICE) + + for _ in range(3): + _run_both_write( + cuda_canary_buf=self.buf_pair[0], + ref_canary_buf=self.buf_pair[1], + plan_cuda=plan_pair[0], + plan_ref=plan_pair[1], + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + enable_write_verify_inputs=False, + expected_input_tokens=pseudo_tokens, + expected_input_positions=pseudo_positions, + cuda_log=cuda_log, + ref_log=ref_log, + real_kv_sources_cuda=(), + real_kv_sources_ref=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + assert_equal=False, + ) + + assert int(cuda_log.kernel_run_counter[0].item()) == 3 + assert_canary_state_equal(log_a=cuda_log, log_b=ref_log) + + def test_slot_run_counter_sums_entries(self) -> None: + """``slot_run_counter`` += sum(entry_count) across all active reqs in this call.""" + cuda_log, _ = _run_write( + buf_pair=self.buf_pair, + input_ids=[1, 2, 3, 4, 5], + positions=[0, 1, 0, 1, 2], + out_cache_loc=[0, 1, 2, 3, 4], + write_offsets=[0, 2, 5], + seed_slot_indices=[-1, -1], + num_valid_reqs=2, + ) + + assert int(cuda_log.slot_run_counter[0].item()) == 5 + + +class TestMisc: + def test_empty_plan_no_op(self) -> None: + """``write_num_valid_reqs = 0`` → no buf write, no slot_run_counter bump, only kernel_run_counter += 1.""" + cuda_log, _ = _run_write( + buf_pair=_make_default_buf_pair(), + input_ids=[0], + positions=[0], + out_cache_loc=[0], + write_offsets=[0, 0], + num_valid_reqs=0, + req_capacity=4, + ) + + assert int(cuda_log.write_index[0].item()) == 0 + assert int(cuda_log.slot_run_counter[0].item()) == 0 + assert int(cuda_log.kernel_run_counter[0].item()) == 1 + + def test_disabled_input_verify_does_not_deref_expected_inputs(self) -> None: + """``enable_write_verify_inputs=False`` must short-circuit before any expected_input_* dereference; + poison those tensors with 0x7F7F7F7F and assert nothing records a violation.""" + cuda_buf = make_canary_buf(num_slots=8, slot_stride_bytes=32, device=_DEVICE) + ref_buf = cuda_buf.clone() + buf_pair = (cuda_buf, ref_buf) + + garbage_expected_tokens = torch.full( + (1,), 0x7F7F7F7F, dtype=torch.int64, device=_DEVICE + ) + garbage_expected_positions = torch.full( + (1,), 0x7F7F7F7F, dtype=torch.int64, device=_DEVICE + ) + + cuda_log, ref_log = _run_write( + buf_pair=buf_pair, + input_ids=[42], + positions=[0], + out_cache_loc=[0], + expected_input_tokens=garbage_expected_tokens, + expected_input_positions=garbage_expected_positions, + assert_equal=False, + ) + + assert int(cuda_log.write_index[0].item()) == 0 + assert int(ref_log.write_index[0].item()) == 0 + + def test_disabled_assert_inputs_passes_none_to_cuda(self) -> None: + """Disabled input assertions pass None instead of dummy tensors.""" + canary_buf = torch.zeros( + 4, CANARY_SLOT_BYTES, dtype=torch.uint8, device=_DEVICE + ) + plan = make_write_plan( + write_offsets=[0, 0], + seed_slot_indices=[-1], + num_valid_reqs=0, + device=_DEVICE, + ) + input_ids = torch.zeros(1, dtype=torch.int64, device=_DEVICE) + positions = torch.zeros(1, dtype=torch.int64, device=_DEVICE) + out_cache_loc = torch.zeros(1, dtype=torch.int64, device=_DEVICE) + log = FakeViolationLog.allocate(capacity=2, device=_DEVICE) + context = VerifyOrWriteContext( + canary_buf=canary_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=log.ring, + violation_write_index=log.write_index, + slot_run_counter=log.slot_run_counter, + kernel_run_counter=log.kernel_run_counter, + enable_chain_position_assert=log.enable_chain_position_assert, + real_kv_sources=(), + real_kv_hash_mode=consts.RealKvHashMode.NONE, + ) + module = _RecordingWriteModule() + + with patch.object(write_module, "_jit_canary_write_module", lambda: module): + launch_canary_write_kernel( + context=context, + plan=plan, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + enable_write_input_assert=False, + expected_input_tokens=None, + expected_input_positions=None, + ) + + assert len(module.calls) == 1 + call = module.calls[0] + assert call[8] == 0 + assert call[9] is None + assert call[10] is None + + +class TestBoundarySweep: + @pytest.mark.parametrize( + "token_val", + [0, 1, 0xFFFFFFFF, -1, 0x80000000, 0x7FFFFFFF], + ) + def test_token_boundary_byte_equal_sweep(self, token_val: int) -> None: + """Sweep token boundary values; assert CUDA write vs ref buf + state byte-equal.""" + _run_write_single_slot_byte_equal(_WriteSingleSlotInput(token=token_val)) + + @pytest.mark.parametrize( + "position_val", + [0, 1, 127, 128, 129, 0x7FFFFFFF], + ) + def test_position_boundary_byte_equal_sweep(self, position_val: int) -> None: + """Sweep position boundary values; assert CUDA write vs ref buf + state byte-equal.""" + _run_write_single_slot_byte_equal(_WriteSingleSlotInput(position=position_val)) + + +class TestPseudoMode: + def setup_method(self) -> None: + self.buf_pair = _make_default_buf_pair() + + def test_pseudo_mode_on_catches_token_mismatch(self) -> None: + """enable_write_verify_inputs=ON + intentional token mismatch → WRITE_TOKEN_MISMATCH bit recorded.""" + input_ids = _int32_tensor([10, 20, 30, 40, 50]) + positions = _int32_tensor([0, 1, 2, 3, 4]) + out_cache_loc = _int32_tensor([1, 2, 3, 4, 5]) + pseudo_tokens = _int32_tensor([10, 20, 30, 999, 50]) + pseudo_positions = positions.clone() + + cuda_log, _ = _run_write( + buf_pair=self.buf_pair, + input_ids=input_ids, + positions=positions, + out_cache_loc=out_cache_loc, + enable_write_verify_inputs=True, + expected_input_tokens=pseudo_tokens, + expected_input_positions=pseudo_positions, + ) + assert int(cuda_log.write_index[0].item()) >= 1 + bits = int(cuda_log.ring[0, consts.VIOLATION_FIELD_FAIL_REASON_BITS].item()) + assert ( + bits & consts.FailReason.WRITE_TOKEN_MISMATCH + ), f"expected WRITE_TOKEN_MISMATCH bit, got {bits:#b}" + + def test_pseudo_mode_off_skips_token_check(self) -> None: + """enable_write_verify_inputs=False makes the caller pass no expected-input tensors.""" + cuda_log, _ = _run_write( + buf_pair=self.buf_pair, + input_ids=[10, 20, 30], + positions=[0, 1, 2], + out_cache_loc=[1, 2, 3], + expected_input_tokens=_int32_tensor([99, 99, 99]), + expected_input_positions=_int32_tensor([99, 99, 99]), + ) + assert int(cuda_log.write_index[0].item()) == 0 + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_decode_topk.py b/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_decode_topk.py new file mode 100644 index 0000000000000000000000000000000000000000..6ace704aeb1d6427d276b0c4499a2d5a2e015d5d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_decode_topk.py @@ -0,0 +1,145 @@ +"""Correctness tests for the MiniMax-M3 single-stage radix-select decode topk. + +The kernel selects, per (head, batch) row, the indices of the ``topk`` largest +block scores among the row's first ``num_blocks = ceil(seq_len / block_size)`` +entries, front-packing valid block ids and ``-1``-padding the tail. This mirrors +the consumer ``_gqa_share_sparse_decode_kernel`` contract. +""" + +import pytest +import torch + +from sglang.jit_kernel.minimax_decode_topk import minimax_decode_topk +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=40, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=40, stage="base-b-kernel-unit", runner_config="4-gpu-b200") +register_amd_ci(est_time=15, suite="nightly-amd-kernel-1-gpu", nightly=True) + + +def _ref(score, seq_lens, block_size, topk): + H, B, S = score.shape + out = torch.full((H, B, topk), -1, dtype=torch.int32, device=score.device) + for h in range(H): + for b in range(B): + sl = int(seq_lens[b]) + nb = min((sl + block_size - 1) // block_size, S) + if nb <= topk: + for i in range(nb): + out[h, b, i] = i + continue + keff = min(topk, nb) + _, idx = torch.topk(score[h, b, :nb], keff) + out[h, b, :keff] = idx.to(torch.int32) + return out + + +def _selected_scores_sorted(score, out): + """Per-row sorted-desc multiset of the scores the kernel selected (tie-robust).""" + H, B, _ = score.shape + rows = [] + for h in range(H): + for b in range(B): + sel = out[h, b] + sel = sel[sel >= 0].long() + assert len(sel.unique()) == len(sel), f"duplicate idx h{h} b{b}: {sel}" + rows.append(torch.sort(score[h, b, sel], descending=True).values) + return rows + + +def _check_contract(out, seq_lens, block_size, topk, S): + H, B, _ = out.shape + for h in range(H): + for b in range(B): + o = out[h, b] + nvalid = int((o >= 0).sum()) + # valid entries are front-packed, -1 after + assert torch.all(o[:nvalid] >= 0) and torch.all(o[nvalid:] == -1), o + nb = min((int(seq_lens[b]) + block_size - 1) // block_size, S) + assert nvalid == min(topk, nb) + assert torch.all(o[:nvalid] < nb) + + +@pytest.mark.parametrize("dtype_sl", [torch.int32, torch.int64]) +@pytest.mark.parametrize("H", [1, 2]) +@pytest.mark.parametrize("B", [1, 5, 32]) +@pytest.mark.parametrize("topk", [16, 32, 64]) +@pytest.mark.parametrize("max_ctx", [4096, 131072, 524288]) +def test_decode_topk_distinct(dtype_sl, H, B, topk, max_ctx): + torch.manual_seed(1234) + block_size = 128 + S = (max_ctx + block_size - 1) // block_size + # distinct scores per row -> exact index-set match against torch.topk + score = torch.empty(H, B, S, dtype=torch.float32, device="cuda") + for h in range(H): + for b in range(B): + score[h, b] = torch.randperm(S, device="cuda").float() + torch.rand( + 1, device="cuda" + ) + seq_lens = torch.randint(1, max_ctx + 1, (B,), device="cuda", dtype=dtype_sl) + + out = minimax_decode_topk(score, seq_lens, block_size, topk) + ref = _ref(score, seq_lens, block_size, topk) + _check_contract(out, seq_lens, block_size, topk, S) + # exact index-set equality (distinct scores) + for h in range(H): + for b in range(B): + assert set(out[h, b][out[h, b] >= 0].tolist()) == set( + ref[h, b][ref[h, b] >= 0].tolist() + ) + + +@pytest.mark.parametrize("kind", ["ties", "negative", "neg_inf_padding", "all_equal"]) +def test_decode_topk_adversarial(kind): + torch.manual_seed(7) + block_size = 128 + H, B, S, topk = 1, 6, 1024, 16 + if kind == "ties": + score = torch.randint(0, 4, (H, B, S), device="cuda").float() + elif kind == "negative": + score = -torch.rand(H, B, S, device="cuda") * 1000 - 1.0 + elif kind == "neg_inf_padding": + score = torch.randn(H, B, S, device="cuda") + score[:, :, ::7] = float("-inf") # scattered -inf in valid range + else: # all_equal + score = torch.full((H, B, S), 3.14, dtype=torch.float32, device="cuda") + seq_lens = torch.randint(1, S * block_size, (B,), device="cuda", dtype=torch.int32) + + out = minimax_decode_topk(score, seq_lens, block_size, topk) + ref = _ref(score, seq_lens, block_size, topk) + _check_contract(out, seq_lens, block_size, topk, S) + # tie-robust: the multiset of selected scores must match torch.topk's + for a, b in zip( + _selected_scores_sorted(score, out), _selected_scores_sorted(score, ref) + ): + torch.testing.assert_close(a, b, rtol=0, atol=0) + + +@pytest.mark.parametrize("seq_len", [1, 128, 129, 2048, 2049]) +def test_decode_topk_small_num_blocks(seq_len): + # num_blocks around / below topk -> naive identity path and boundary. + block_size = 128 + H, B, S, topk = 1, 1, 64, 16 + score = torch.randn(H, B, S, dtype=torch.float32, device="cuda") + seq_lens = torch.tensor([seq_len], device="cuda", dtype=torch.int32) + out = minimax_decode_topk(score, seq_lens, block_size, topk) + _check_contract(out, seq_lens, block_size, topk, S) + nb = min((seq_len + block_size - 1) // block_size, S) + if nb <= topk: + assert out[0, 0, :nb].tolist() == list(range(nb)) + + +def test_decode_topk_out_param(): + block_size = 128 + H, B, S, topk = 1, 4, 1024, 16 + score = torch.randn(H, B, S, dtype=torch.float32, device="cuda") + seq_lens = torch.full((B,), 100000, device="cuda", dtype=torch.int32) + out = torch.empty((H, B, topk), dtype=torch.int32, device="cuda") + res = minimax_decode_topk(score, seq_lens, block_size, topk, out=out) + assert res is out + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_decode_topk_page_table.py b/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_decode_topk_page_table.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e983818d8feb84af678e8fd8dee5774e87fec8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_decode_topk_page_table.py @@ -0,0 +1,178 @@ +"""Fused decode top-k + page-table transform. + +`minimax_decode_topk_page_table` selects the top-k blocks (same as the block-id +`minimax_decode_topk`) and emits the per-query paged page table consumed by the +dense backend (trtllm_mha), instead of block ids. This checks the fused output +end-to-end: trtllm decode over the emitted page table matches the custom +`_gqa_share_sparse_decode_kernel` fed the block-id selection from the same score. +Only the TP>=4 case (num_kv_heads == 1) is covered. +""" + +import random +import sys + +import pytest +import torch + +flashinfer = pytest.importorskip("flashinfer") + +from sglang.jit_kernel.minimax_decode_topk import ( + minimax_decode_topk, + minimax_decode_topk_page_table, +) +from sglang.srt.layers.attention.minimax_sparse_ops.decode.topk_sparse import ( + flash_decode_with_gqa_share_sparse, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=25, stage="base-b-kernel-unit", runner_config="4-gpu-b200") + +dev = "cuda" + + +def _effective_kv_from_selection(ti, seq_lens, block): + # Ground-truth effective KV length: sum of valid tokens over the selected + # blocks (only the final block can be partial), per query. + bs = seq_lens.shape[0] + out = torch.zeros(bs, dtype=torch.int32, device=ti.device) + for b in range(bs): + sl = int(seq_lens[b]) + tot = 0 + for c in ti[0, b].tolist(): + if c < 0: + continue + tot += min(block, sl - c * block) + out[b] = tot + return out + + +@pytest.mark.parametrize( + "bs,seq_len", + [ + (1, 5000), + (2, 300), + (3, 160), + (4, 2048), + (8, 4096), + (16, 8000), + (2, 40000), # num_blocks=313 -> medium radix path + (1, 90000), # num_blocks=704 -> large compaction path + (1, 480000), # num_blocks=3750 -> large path near kMaxNumBlocks + ], +) +@pytest.mark.parametrize("nqh", [8, 16]) +def test_fused_page_table_matches_custom(bs, seq_len, nqh): + arch_major, _ = torch.cuda.get_device_capability(torch.cuda.current_device()) + if arch_major < 10: + pytest.skip("trtllm-gen decode is Blackwell (sm100)") + nkv, D, block, topk, ps = 1, 128, 128, 16, 64 + torch.manual_seed(bs * 31 + seq_len + nqh) + random.seed(bs * 31 + seq_len) + + ppr = (seq_len + ps - 1) // ps + npages = bs * ppr + 4 + kf = torch.randn(npages * ps, nkv, D, device=dev, dtype=torch.bfloat16) * 0.5 + vf = torch.randn(npages * ps, nkv, D, device=dev, dtype=torch.bfloat16) * 0.5 + q = torch.randn(bs, nqh, D, device=dev, dtype=torch.bfloat16) * 0.5 + + r2t = torch.zeros(bs, seq_len, dtype=torch.int32, device=dev) + sl = torch.full((bs,), seq_len, dtype=torch.int32, device=dev) + sid = torch.arange(bs, dtype=torch.int64, device=dev) + idxs = torch.arange(seq_len, device=dev) + for b in range(bs): + r2t[b] = ((b * ppr + idxs // ps) * ps + idxs % ps).int() + + nb = (seq_len + block - 1) // block + score = torch.full((1, bs, nb), -float("inf"), device=dev, dtype=torch.float32) + score[0, :, :nb] = torch.randn(bs, nb, device=dev) + score[0, :, nb - 1] = 1e30 # final (local) block always selected + + # block-id selection -> custom kernel (reference) + ti = minimax_decode_topk(score, sl, block, topk) + ref = flash_decode_with_gqa_share_sparse( + q, None, kf, vf, r2t, sl, sid, block, ti, sm_scale=D**-0.5 + ) + + # fused page-table + effective KV length -> trtllm (allocated + returned) + pt, cache = minimax_decode_topk_page_table(score, sl, r2t, sid, block, topk, ps) + # the kernel's effective KV length must match the actual block selection + expect_cache = _effective_kv_from_selection(ti, sl, block) + assert torch.equal(cache, expect_cache), f"{cache} != {expect_cache}" + ws = torch.zeros(128 * 1024 * 1024, dtype=torch.int8, device=dev) + kv = ( + kf.view(npages, ps, nkv, D).permute(0, 2, 1, 3), + vf.view(npages, ps, nkv, D).permute(0, 2, 1, 3), + ) + o = flashinfer.decode.trtllm_batch_decode_with_kv_cache( + query=q, + kv_cache=kv, + workspace_buffer=ws, + block_tables=pt, + seq_lens=cache, + max_seq_len=topk * block, + bmm1_scale=D**-0.5, + bmm2_scale=1.0, + ) + cos = torch.nn.functional.cosine_similarity( + ref.float().flatten(), o.float().flatten(), dim=0 + ).item() + assert cos > 0.999, f"cos={cos}" + + +@pytest.mark.parametrize("seq_len", [300, 5000, 90000]) +@pytest.mark.parametrize("bs", [1, 3]) +@pytest.mark.parametrize("nkv", [2, 4]) +def test_dp_flattened_page_table(nkv, bs, seq_len): + """DP attention (num_kv_heads>1): each kv head selects its own blocks, flattened + into bs*nkv pseudo-requests (row = b*nkv + h). Validate the flattened page table + + effective KV length against the per-head block-id selection, including the + head-minor head-encoded page index (base_page*nkv + h, the index into an HND + cache [num_pages, nkv, ps, D] reshaped to [num_pages*nkv, 1, ps, D]).""" + D, block, topk, ps = 128, 128, 16, 64 + ppb = block // ps + torch.manual_seed(nkv * 131 + bs * 31 + seq_len) + ppr = (seq_len + ps - 1) // ps + max_kv = seq_len # req_to_token width + + r2t = torch.zeros(bs, seq_len, dtype=torch.int32, device=dev) + sl = torch.full((bs,), seq_len, dtype=torch.int32, device=dev) + sid = torch.arange(bs, dtype=torch.int64, device=dev) + idxs = torch.arange(seq_len, device=dev) + for b in range(bs): + r2t[b] = ((b * ppr + idxs // ps) * ps + idxs % ps).int() + + nb = (seq_len + block - 1) // block + score = torch.full((nkv, bs, nb), -float("inf"), device=dev, dtype=torch.float32) + score[:, :, :nb] = torch.randn(nkv, bs, nb, device=dev) + score[:, :, nb - 1] = 1e30 # final (local) block always selected + + # per-head block-id selection is the reference for the flattened page table + ti = minimax_decode_topk(score, sl, block, topk) # [nkv, bs, topk] + pt, cache = minimax_decode_topk_page_table(score, sl, r2t, sid, block, topk, ps) + msp = topk * ppb + assert pt.shape == (bs * nkv, msp) and cache.shape == (bs * nkv,) + + r2t_cpu = r2t.cpu() + for b in range(bs): + for h in range(nkv): + blocks = sorted(c for c in ti[h, b].tolist() if c >= 0) + row = b * nkv + h + # effective KV length = sum of valid tokens over selected blocks + exp_kv = sum(min(block, seq_len - c * block) for c in blocks) + assert ( + int(cache[row]) == exp_kv + ), f"row {row}: {int(cache[row])} != {exp_kv}" + # page table: each block -> ppb pages via req_to_token, head-minor encoded + for e in range(len(blocks) * ppb): + c = blocks[e // ppb] + tok = c * block + (e % ppb) * ps + if tok >= max_kv: + tok = max_kv - 1 + exp = int(r2t_cpu[b, tok]) // ps * nkv + h + assert ( + int(pt[row, e]) == exp + ), f"row {row} e {e}: {int(pt[row,e])} != {exp}" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_qknorm_rope.py b/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_qknorm_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..813fd21dbb898944d4fdb534e0b4a6024a1e04e3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_qknorm_rope.py @@ -0,0 +1,178 @@ +"""Correctness for the fused MiniMax-M3 Gemma-RMSNorm + partial NeoX RoPE kernel. + +Verifies the in-place fused kernel reproduces GemmaRMSNorm((1+w)) + partial NeoX +RoPE to the bf16 round-off floor, leaves V untouched, and matches sglang's RoPE +convention (cos|sin cache, neox pairs (i, i+rotary_dim/2)). +""" + +import pytest +import torch + +from sglang.jit_kernel.minimax_qknorm_rope import ( + minimax_qknorm_rope, + minimax_qknorm_rope_grouped, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="4-gpu-b200") + +dev = "cuda" +HEAD_DIM, ROTARY_DIM, BASE, EPS = 128, 64, 5_000_000, 1e-6 + + +def _build_cache(max_pos): + inv_freq = 1.0 / ( + BASE + ** (torch.arange(0, ROTARY_DIM, 2, dtype=torch.float, device=dev) / ROTARY_DIM) + ) # [32] + t = torch.arange(max_pos, dtype=torch.float, device=dev) + freqs = torch.outer(t, inv_freq) # [max_pos, 32] + return torch.cat([freqs.cos(), freqs.sin()], dim=-1).contiguous() # [max_pos, 64] + + +def _ref(q, k, wq, wk, cache, positions, nq, nk): + T = q.shape[0] + + def norm(x, w, nh): + x = x.reshape(T, nh, HEAD_DIM).float() + var = x.pow(2).mean(-1, keepdim=True) + return x * torch.rsqrt(var + EPS) * (1.0 + w.float()) + + cs = cache.index_select(0, positions).float() + cos, sin = cs[:, :32], cs[:, 32:] + + def rope(x): + x1, x2 = x[..., :32], x[..., 32:64] + o1 = x1 * cos[:, None, :] - x2 * sin[:, None, :] + o2 = x2 * cos[:, None, :] + x1 * sin[:, None, :] + return torch.cat([o1, o2, x[..., 64:]], dim=-1) + + return rope(norm(q, wq, nq)).reshape(T, -1), rope(norm(k, wk, nk)).reshape(T, -1) + + +@pytest.mark.parametrize("nq,nk", [(8, 1), (64, 8), (16, 2)]) +@pytest.mark.parametrize("T", [1, 7, 64, 1024, 4096]) +@pytest.mark.parametrize("pos_dtype", [torch.int32, torch.int64]) +def test_fused_qknorm_rope(nq, nk, T, pos_dtype): + torch.manual_seed(T * 131 + nq) + max_pos = 8192 + cache = _build_cache(max_pos) + wq = (torch.randn(HEAD_DIM, device=dev) * 0.1).to(torch.bfloat16) + wk = (torch.randn(HEAD_DIM, device=dev) * 0.1).to(torch.bfloat16) + q = torch.randn(T, nq * HEAD_DIM, dtype=torch.bfloat16, device=dev) + k = torch.randn(T, nk * HEAD_DIM, dtype=torch.bfloat16, device=dev) + v = torch.randn(T, nk * HEAD_DIM, dtype=torch.bfloat16, device=dev) + positions = torch.randint(0, max_pos, (T,), device=dev, dtype=pos_dtype) + + qr, kr = _ref(q, k, wq, wk, cache, positions.long(), nq, nk) + + qkv = torch.cat([q, k, v], dim=-1).contiguous() + minimax_qknorm_rope(qkv, wq, wk, cache, positions, nq, nk, nk, EPS) + qf, kf, vf = qkv.split([nq * HEAD_DIM, nk * HEAD_DIM, nk * HEAD_DIM], dim=-1) + + floor = (qr.bfloat16().float() - qr.float()).abs().max().item() + assert (qf.float() - qr.float()).abs().max().item() <= 2 * floor + 1e-3 + assert (kf.float() - kr.float()).abs().max().item() <= 2 * floor + 1e-3 + assert (vf.float() - v.float()).abs().max().item() == 0.0 # V untouched + + +def test_index_branch_shapes(): + # idx_q (nq=num_idx_heads, nk=0) and idx_k (nq=1) in-place calls. + torch.manual_seed(0) + max_pos = 4096 + cache = _build_cache(max_pos) + w = (torch.randn(HEAD_DIM, device=dev) * 0.1).to(torch.bfloat16) + T, num_idx = 33, 4 + positions = torch.randint(0, max_pos, (T,), device=dev, dtype=torch.int64) + for nq in (num_idx, 1): + x = torch.randn(T, nq * HEAD_DIM, dtype=torch.bfloat16, device=dev) + ref, _ = _ref(x, x[:, :HEAD_DIM], w, w, cache, positions, nq, 1) + xc = x.clone() + minimax_qknorm_rope(xc, w, w, cache, positions, nq, 0, 0, EPS) + floor = (ref.bfloat16().float() - ref.float()).abs().max().item() + assert (xc.float() - ref.float()).abs().max().item() <= 2 * floor + 1e-3 + + +def _norm_rope_one(x_heads, w, cache, positions): + # x_heads: [T, nh, HEAD_DIM] fp32; returns same shape, GemmaRMSNorm(1+w)+rope. + var = x_heads.pow(2).mean(-1, keepdim=True) + y = x_heads * torch.rsqrt(var + EPS) * (1.0 + w.float()) + cs = cache.index_select(0, positions).float() + cos, sin = cs[:, None, :32], cs[:, None, 32:] + x1, x2 = y[..., :32], y[..., 32:64] + o1 = x1 * cos - x2 * sin + o2 = x2 * cos + x1 * sin + return torch.cat([o1, o2, y[..., 64:]], dim=-1) + + +@pytest.mark.parametrize("nq,nkv,niq", [(8, 1, 1), (8, 1, 4), (16, 2, 2)]) +@pytest.mark.parametrize("idx_v", [0, 1]) +@pytest.mark.parametrize("T", [1, 7, 64, 1024]) +@pytest.mark.parametrize("pos_dtype", [torch.int32, torch.int64]) +def test_combined_main_index_grouped(nq, nkv, niq, idx_v, T, pos_dtype): + """Combined main(q,k,v) + index(idx_q,idx_k,[idx_v]) layout in one launch. + + Mirrors the fused qkv+index_qkv GEMM output: a uniform [total_heads, 128] + grid where Q / K main heads and index-Q / index-K heads are normed+roped in + one pass and the V / index-V heads are left untouched. + """ + torch.manual_seed(T * 17 + nq * 3 + niq + idx_v) + max_pos = 8192 + cache = _build_cache(max_pos) + positions = torch.randint(0, max_pos, (T,), device=dev, dtype=pos_dtype) + + # head layout: q(nq) k(nkv) v(nkv) idx_q(niq) idx_k(1) [idx_v(1)] + off_q = 0 + off_k = nq + off_v = nq + nkv + off_iq = nq + 2 * nkv + off_ik = off_iq + niq + total_heads = off_ik + 1 + idx_v + + wq = (torch.randn(HEAD_DIM, device=dev) * 0.1).to(torch.bfloat16) + wk = (torch.randn(HEAD_DIM, device=dev) * 0.1).to(torch.bfloat16) + wiq = (torch.randn(HEAD_DIM, device=dev) * 0.1).to(torch.bfloat16) + wik = (torch.randn(HEAD_DIM, device=dev) * 0.1).to(torch.bfloat16) + + x = torch.randn(T, total_heads, HEAD_DIM, dtype=torch.bfloat16, device=dev) + ref = x.float().clone() + ref[:, off_q:off_k] = _norm_rope_one( + ref[:, off_q:off_k], wq, cache, positions.long() + ) + ref[:, off_k:off_v] = _norm_rope_one( + ref[:, off_k:off_v], wk, cache, positions.long() + ) + ref[:, off_iq:off_ik] = _norm_rope_one( + ref[:, off_iq:off_ik], wiq, cache, positions.long() + ) + ref[:, off_ik : off_ik + 1] = _norm_rope_one( + ref[:, off_ik : off_ik + 1], wik, cache, positions.long() + ) + + qkv = x.reshape(T, total_heads * HEAD_DIM).contiguous() + minimax_qknorm_rope_grouped( + qkv, + [(wq, off_q, nq), (wk, off_k, nkv), (wiq, off_iq, niq), (wik, off_ik, 1)], + cache, + positions, + EPS, + ) + out = qkv.reshape(T, total_heads, HEAD_DIM) + + floor = (ref.bfloat16().float() - ref).abs().max().item() + assert (out.float() - ref).abs().max().item() <= 2 * floor + 1e-3 + # V and index-V heads untouched (bit-exact). + assert ( + out[:, off_v:off_iq].float() - x[:, off_v:off_iq].float() + ).abs().max() == 0.0 + if idx_v: + assert ( + out[:, off_ik + 1 :].float() - x[:, off_ik + 1 :].float() + ).abs().max() == 0.0 + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_store_kv_index.py b/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_store_kv_index.py new file mode 100644 index 0000000000000000000000000000000000000000..757840c2bfd60086f72f2b94dedc08fe5f00664c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/minimax/test_minimax_store_kv_index.py @@ -0,0 +1,79 @@ +"""Correctness for the fused MiniMax-M3 KV + index cache store kernel. + +Verifies the single fused launch writes the main K/V, the index K, and the +optional index V into their pools at out_cache_loc rows exactly as the separate +index_put_ stores would, for both value modes and int32/int64 indices. +""" + +import pytest +import torch + +from sglang.jit_kernel.minimax_store_kv_index import store_kv_index +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="4-gpu-b200") +register_amd_ci(est_time=10, suite="nightly-amd-kernel-1-gpu", nightly=True) + +dev = "cuda" +HEAD_DIM = 128 + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("num_kv_heads", [1, 4, 8]) +@pytest.mark.parametrize("has_v", [False, True]) +@pytest.mark.parametrize("idx_dtype", [torch.int32, torch.int64]) +@pytest.mark.parametrize("T", [1, 7, 128, 513]) +def test_store_kv_index(dtype, num_kv_heads, has_v, idx_dtype, T): + torch.manual_seed(T * 17 + num_kv_heads) + head_bytes = HEAD_DIM * dtype.itemsize + N = 4096 + + def rnd(*shape): + return torch.randn(*shape, dtype=dtype, device=dev) + + k = rnd(T, num_kv_heads * HEAD_DIM) + v = rnd(T, num_kv_heads * HEAD_DIM) + idx_k = rnd(T, HEAD_DIM) + idx_v = rnd(T, HEAD_DIM) if has_v else None + + k_cache = torch.zeros(N, num_kv_heads * HEAD_DIM, dtype=dtype, device=dev) + v_cache = torch.zeros_like(k_cache) + idx_k_cache = torch.zeros(N, HEAD_DIM, dtype=dtype, device=dev) + idx_v_cache = torch.zeros_like(idx_k_cache) if has_v else None + + loc = torch.randperm(N, device=dev)[:T].to(idx_dtype) + + store_kv_index( + k, + v, + k_cache, + v_cache, + idx_k, + idx_k_cache, + idx_v, + idx_v_cache, + loc, + num_kv_heads=num_kv_heads, + head_bytes=head_bytes, + ) + + ll = loc.long() + k_ref = torch.zeros_like(k_cache) + v_ref = torch.zeros_like(v_cache) + ik_ref = torch.zeros_like(idx_k_cache) + k_ref[ll], v_ref[ll], ik_ref[ll] = k, v, idx_k + + assert torch.equal(k_cache, k_ref) + assert torch.equal(v_cache, v_ref) + assert torch.equal(idx_k_cache, ik_ref) + if has_v: + iv_ref = torch.zeros_like(idx_v_cache) + iv_ref[ll] = idx_v + assert torch.equal(idx_v_cache, iv_ref) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_activation.py b/asian_ai/performance/SGLang/test/registered/jit/test_activation.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ec17457e0a6402a37731bbcf2444e20f32519c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_activation.py @@ -0,0 +1,210 @@ +import sys + +import pytest +import torch +import torch.nn.functional as F + +from sglang.jit_kernel.activation import ( + SUPPORTED_ACTIVATIONS, + relu2, + run_activation, +) +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=20, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=30, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=20, stage="jit-kernel-unit", runner_config="amd") + + +OPS = SUPPORTED_ACTIVATIONS +DTYPES = [torch.float16, torch.bfloat16, torch.float32] +SHAPES = get_ci_test_range( + full_range=[ + (7, 16), + (83, 1024), + (3, 5, 16), + (2, 3, 512), + (1, 17, 4096), + (48, 3072), + (38, 8192), + (39, 32768), + *[(2**x, 2048) for x in range(0, 15, 2)], + *[(2**x, 65536) for x in range(0, 5, 2)], + ], + ci_range=[(7, 16), (2, 3, 512), (48, 3072), (38, 8192)], +) + + +def _reference(op_name: str, x: torch.Tensor) -> torch.Tensor: + d = x.shape[-1] // 2 + lhs = x[..., :d].float() + rhs = x[..., d:] + if op_name == "silu": + act = F.silu(lhs) + elif op_name == "gelu": + act = F.gelu(lhs, approximate="none") + else: + act = F.gelu(lhs, approximate="tanh") + return act.to(dtype=x.dtype) * rhs + + +def _tolerances(dtype: torch.dtype) -> tuple[float, float]: + if dtype == torch.float32: + return 1e-4, 1e-4 + return 1e-2, 1e-2 + + +@pytest.mark.parametrize("op_name", OPS) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("shape", SHAPES) +def test_activation_correctness( + op_name: str, dtype: torch.dtype, shape: tuple[int, ...] +) -> None: + x = torch.randn(shape, dtype=dtype, device="cuda") + out = run_activation(op_name, x, None) + expected = _reference(op_name, x) + atol, rtol = _tolerances(dtype) + torch.testing.assert_close(out, expected, atol=atol, rtol=rtol) + + +@pytest.mark.parametrize("op_name", OPS) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("shape", SHAPES) +def test_activation_out_param( + op_name: str, dtype: torch.dtype, shape: tuple[int, ...] +) -> None: + x = torch.randn(shape, dtype=dtype, device="cuda") + out = torch.empty(shape[:-1] + (shape[-1] // 2,), dtype=dtype, device="cuda") + result = run_activation(op_name, x, out) + assert result is out + expected = _reference(op_name, x) + atol, rtol = _tolerances(dtype) + torch.testing.assert_close(out, expected, atol=atol, rtol=rtol) + + +FILTER_SHAPES = get_ci_test_range( + full_range=[(83, 1024), (256, 2048), (1024, 4096)], + ci_range=[(83, 1024)], +) +EXPERT_STEPS = [1, 16] + + +@pytest.mark.parametrize("op_name", OPS) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("shape", FILTER_SHAPES) +@pytest.mark.parametrize("expert_step", EXPERT_STEPS) +def test_activation_filter_expert( + op_name: str, + dtype: torch.dtype, + shape: tuple[int, int], + expert_step: int, +) -> None: + """expert_ids[token // expert_step] == -1 must leave the output row untouched.""" + num_tokens = shape[0] + x = torch.randn(shape, dtype=dtype, device="cuda") + # Pre-fill out with a sentinel so we can detect untouched rows. + sentinel = float("nan") + out = torch.full( + shape[:-1] + (shape[-1] // 2,), + sentinel, + dtype=dtype, + device="cuda", + ) + + num_groups = (num_tokens + expert_step - 1) // expert_step + expert_ids = torch.randint( + low=0, high=8, size=(num_groups,), dtype=torch.int32, device="cuda" + ) + skip_mask = torch.rand(num_groups, device="cuda") < 0.4 + expert_ids[skip_mask] = -1 + + result = run_activation(op_name, x, out, expert_ids, expert_step) + assert result is out + + token_skip = skip_mask[torch.arange(num_tokens, device="cuda") // expert_step] + expected = _reference(op_name, x) + atol, rtol = _tolerances(dtype) + + kept = ~token_skip + if kept.any(): + torch.testing.assert_close(out[kept], expected[kept], atol=atol, rtol=rtol) + if token_skip.any(): + assert torch.isnan( + out[token_skip] + ).all(), "filter_expert kernel touched rows whose expert_id is -1" + + +@pytest.mark.parametrize("op_name", OPS) +def test_activation_filter_expert_all_skipped(op_name: str) -> None: + """If every expert id is -1, the output must be left entirely untouched.""" + shape = (32, 512) + x = torch.randn(shape, dtype=torch.bfloat16, device="cuda") + out = torch.full( + shape[:-1] + (shape[-1] // 2,), + float("nan"), + dtype=torch.bfloat16, + device="cuda", + ) + expert_ids = torch.full((shape[0],), -1, dtype=torch.int32, device="cuda") + run_activation(op_name, x, out, expert_ids, 1) + assert torch.isnan(out).all() + + +@pytest.mark.parametrize("op_name", OPS) +def test_activation_filter_expert_none_skipped(op_name: str) -> None: + """No -1 in expert_ids must yield bit-identical output to the unfiltered path.""" + shape = (64, 512) + dtype = torch.bfloat16 + x = torch.randn(shape, dtype=dtype, device="cuda") + expert_ids = torch.zeros((shape[0],), dtype=torch.int32, device="cuda") + out_filtered = run_activation(op_name, x, None, expert_ids, 1) + out_unfiltered = run_activation(op_name, x, None) + torch.testing.assert_close(out_filtered, out_unfiltered, atol=0.0, rtol=0.0) + + +UNARY_SHAPES = get_ci_test_range( + full_range=[ + (7, 16), + (83, 1024), + (3, 5, 16), + (2, 3, 512), + (1, 17, 4096), + (38, 4096), + *[(2**x, 2048) for x in range(0, 15, 2)], + ], + ci_range=[(7, 16), (2, 3, 512), (38, 4096)], +) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("shape", UNARY_SHAPES) +def test_relu2_correctness(dtype: torch.dtype, shape: tuple[int, ...]) -> None: + x = torch.randn(shape, dtype=dtype, device="cuda") + out = relu2(x) + expected = F.relu(x.float()).pow(2).to(dtype=dtype) + atol, rtol = _tolerances(dtype) + torch.testing.assert_close(out, expected, atol=atol, rtol=rtol) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("shape", UNARY_SHAPES) +def test_relu2_out_param(dtype: torch.dtype, shape: tuple[int, ...]) -> None: + x = torch.randn(shape, dtype=dtype, device="cuda") + out = torch.empty(shape, dtype=dtype, device="cuda") + result = relu2(x, out) + assert result is out + expected = F.relu(x.float()).pow(2).to(dtype=dtype) + atol, rtol = _tolerances(dtype) + torch.testing.assert_close(out, expected, atol=atol, rtol=rtol) + + +def test_relu2_negative_inputs_zeroed() -> None: + """All-negative input must produce an all-zero output.""" + x = -torch.rand((64, 512), dtype=torch.bfloat16, device="cuda") - 1e-3 + out = relu2(x) + assert torch.count_nonzero(out) == 0 + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_add_constant.py b/asian_ai/performance/SGLang/test/registered/jit/test_add_constant.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1fca403bb9d21ed8075b6d775ee20192525e01 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_add_constant.py @@ -0,0 +1,42 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.add_constant import add_constant +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=180, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=8, stage="jit-kernel-unit", runner_config="amd") + + +@pytest.mark.parametrize("size", [1, 2, 127, 128, 1024, 1025, 4096, 4097]) +@pytest.mark.parametrize("constant", [0, 1, 7, 1024, -3]) +def test_add_constant(size: int, constant: int) -> None: + src = torch.arange(0, size, dtype=torch.int32, device="cuda") + dst = add_constant(src, constant) + assert torch.all(dst == src + constant) + + +def test_add_constant_unaligned_input() -> None: + src = torch.arange(0, 4098, dtype=torch.int32, device="cuda")[1:] + dst = add_constant(src, 7) + assert torch.all(dst == src + 7) + + +@pytest.mark.parametrize("size", [2**20, 2**20 + 3]) +def test_add_constant_large_aligned_input(size: int) -> None: + src = torch.arange(0, size, dtype=torch.int32, device="cuda") + dst = add_constant(src, -3) + assert torch.all(dst == src - 3) + + +def test_add_constant_large_unaligned_input() -> None: + src = torch.arange(0, 2**20 + 4, dtype=torch.int32, device="cuda")[1:] + dst = add_constant(src, 7) + assert torch.all(dst == src + 7) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_amd_deterministic_custom_allreduce.py b/asian_ai/performance/SGLang/test/registered/jit/test_amd_deterministic_custom_allreduce.py new file mode 100644 index 0000000000000000000000000000000000000000..cef3ee65f1dd1d5e761846841f7f055da16040bd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_amd_deterministic_custom_allreduce.py @@ -0,0 +1,254 @@ +""" +Test deterministic custom all-reduce kernel behavior with batch size invariance. + +This test uses the 1-stage all-reduce kernel which is inherently deterministic +due to fixed accumulation ordering (each GPU reads all data from all GPUs and +reduces locally in a fixed order - no atomics, no race conditions). + +Note: This is NOT a reduce-scatter + all-gather (RS+AG) approach. + +This test compares: +1. Deterministic kernel (same batch size) +2. Deterministic kernel (different batch size) + +Usage: + pytest test_amd_deterministic_custom_allreduce.py +""" + +import multiprocessing as mp +import socket + +import pytest +import torch +import torch.distributed as dist + +from sglang.srt.environ import envs +from sglang.test.ci.ci_register import register_amd_ci + +register_amd_ci(est_time=120, stage="sgl-kernel-unit", runner_config="2-gpu-amd") + + +def get_open_port(): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def worker(world_size, rank, port): + envs.SGLANG_USE_1STAGE_ALLREDUCE.set("1") + device = torch.device(f"cuda:{rank}") + torch.cuda.set_device(device) + + dist.init_process_group( + backend="nccl", + init_method=f"tcp://localhost:{port}", + rank=rank, + world_size=world_size, + ) + + # Try to import and use deterministic kernel + try: + from torch.distributed import new_group + + from sglang.srt.distributed.device_communicators.custom_all_reduce import ( + CustomAllreduce, + ) + + # Create gloo group for custom AR + dist.barrier() + ar_group = new_group(backend="gloo") + dist.barrier() + + custom_ar = CustomAllreduce(group=ar_group, device=device) + + if custom_ar is None or custom_ar.disabled: + if rank == 0: + print("✗ Custom AR not available or disabled") + dist.destroy_process_group() + return + except Exception as e: + if rank == 0: + print(f"✗ Failed to initialize deterministic kernel: {e}") + import traceback + + traceback.print_exc() + dist.destroy_process_group() + return + + num_trials = 10 + + # Matrix sizes similar to real model layers + # Format: (batch_size, hidden_dim) - typical tensor shape for all-reduce + BS = 50 # max batch_size (1..BS) + hidden_dim = 16384 # hidden dimension / intermediate dimension + + # Different seed per rank - each GPU has DIFFERENT input + torch.manual_seed(42 + rank) + + # Create fixed inputs for all trials + # Single request: (hidden_dim,) + base_input = torch.randn(hidden_dim, dtype=torch.bfloat16, device=device) + base_input_rand = torch.randn(hidden_dim, dtype=torch.bfloat16, device=device) + + # Check if inputs fit in buffer + # Buffer size is max_size bytes, input size is numel * element_size bytes + input_size_bytes = base_input.numel() * base_input.element_size() + if input_size_bytes > custom_ar.max_size and rank == 0: + print( + f"Warning: Input size ({input_size_bytes/(1024*1024):.1f} MB) exceeds buffer size ({custom_ar.max_size/(1024*1024):.1f} MB)" + ) + print(" Using unregistered mode (will copy to buffer)") + + dist.barrier() + + # ========================================================================= + # TEST 1: Deterministic kernel (same batch size) - should be DETERMINISTIC + # ========================================================================= + if rank == 0: + print(f"\n{'='*70}") + print("TEST 1: Deterministic kernel (same batch size)") + print(f"{'='*70}") + dist.barrier() + + results_allreduce_only = [] + for trial in range(num_trials): + # Clone the same input + inp = base_input.clone() + + result = custom_ar.custom_all_reduce(inp) + torch.cuda.synchronize() + + # Store checksum + checksum = result.view(-1).sum().item() + first_vals = result.view(-1)[:5].clone() + results_allreduce_only.append((checksum, first_vals)) + + if rank == 0: + print( + f" Trial {trial+1:2d}: sum={checksum:.6f}, first5={first_vals.tolist()}" + ) + + # Check determinism + if rank == 0: + ref_sum, ref_vals = results_allreduce_only[0] + all_match = True + for i, (s, vals) in enumerate(results_allreduce_only[1:], 1): + if abs(ref_sum - s) > 1e-3 or not torch.allclose(ref_vals, vals, rtol=1e-3): + all_match = False + print(f" Trial {i+1} DIFFERS! ref_sum={ref_sum:.6f}, got={s:.6f}") + + if all_match: + print(" ✓ DETERMINISTIC KERNEL (fixed BS): DETERMINISTIC (as expected)") + else: + print( + " ✗ DETERMINISTIC KERNEL (fixed BS): NON-DETERMINISTIC (unexpected!)" + ) + + dist.barrier() + + # ========================================================================= + # TEST 2: Deterministic kernel (different batch size) - should be DETERMINISTIC + # [a], [a, x], [a, x, x], ... + # ========================================================================= + if rank == 0: + print(f"\n{'='*70}") + print("TEST 2: Deterministic kernel (different batch size)") + print("Batches: [a], [a,x], [a,x,x], ...") + print(f"{'='*70}") + dist.barrier() + + results_allreduce_only = {trial: [] for trial in range(num_trials)} + for trial in range(num_trials): + for bs in range(1, BS + 1): + # Construct batch: (batch_size, hidden_dim) + # First element is base_input, rest are base_input_rand + batch = torch.stack([base_input] + [base_input_rand] * (bs - 1), dim=0) + # Shape: (bs, hidden_dim) + + # Flatten for all-reduce: (bs * hidden_dim,) + batch_flat = batch.view(-1) + + result_flat = custom_ar.custom_all_reduce(batch_flat) + torch.cuda.synchronize() + + # Reshape back to (bs, hidden_dim) + batch_out = result_flat.view(bs, hidden_dim) + + # Only compare output corresponding to first request + out_first_req = batch_out[0].clone() + checksum = out_first_req.sum().item() + first_vals = out_first_req[:5].clone() + results_allreduce_only[trial].append((bs, checksum, first_vals)) + + if rank == 0: + print( + f" Batch size {bs:2d}: sum={checksum:.6f}, first5={first_vals.tolist()}" + ) + + # Check determinism + if rank == 0: + for trial in range(num_trials): + results = results_allreduce_only[trial] + + _, ref_sum, ref_vals = results[0] + all_match = True + for _, s, vals in results[1:]: + if abs(ref_sum - s) > 1e-3 or not torch.allclose( + ref_vals, vals, rtol=1e-3 + ): + all_match = False + + if all_match: + print(" ✓ DETERMINISTIC KERNEL (variant BS): DETERMINISTIC") + else: + print(" ✗ DETERMINISTIC KERNEL (variant BS): NON-DETERMINISTIC") + + dist.barrier() + + dist.destroy_process_group() + + +def main(): + world_size = 8 + available_gpus = torch.cuda.device_count() + + print("=" * 70) + print("Deterministic Kernel All-Reduce Determinism Test") + print("=" * 70) + print(f"Available GPUs: {available_gpus}") + print(f"Using world_size: {world_size}") + + if available_gpus < world_size: + print( + f"WARNING: Only {available_gpus} GPUs available, using {available_gpus} instead" + ) + world_size = available_gpus + + if world_size < 2: + print("ERROR: Need at least 2 GPUs for this test") + return + + mp.set_start_method("spawn", force=True) + port = get_open_port() + + procs = [] + for rank in range(world_size): + p = mp.Process(target=worker, args=(world_size, rank, port)) + p.start() + procs.append(p) + + for p in procs: + p.join() + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.device_count() < 2, + reason="Requires at least 2 CUDA GPUs", +) +def test_deterministic_custom_allreduce(): + """Test that deterministic custom all-reduce produces consistent results.""" + main() + + +if __name__ == "__main__": + main() diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_amd_nccl_allreduce_determinism.py b/asian_ai/performance/SGLang/test/registered/jit/test_amd_nccl_allreduce_determinism.py new file mode 100644 index 0000000000000000000000000000000000000000..352b705fab7eb10a13d2741a2f5b4783e3bd65ef --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_amd_nccl_allreduce_determinism.py @@ -0,0 +1,212 @@ +""" +Test to confirm non-determinism of default NCCL all-reduce with batch size invariance. + +This test uses the default torch.distributed.all_reduce (NCCL) which can be +NON-DETERMINISTIC due to tree-based reduction algorithms that don't guarantee +fixed accumulation order for bfloat16/float16. + +This test compares: +1. Default all-reduce (same batch size) - should be DETERMINISTIC +2. Default all-reduce (different batch size) - typically NON-DETERMINISTIC for bfloat16 + +Usage: + pytest test_amd_nccl_allreduce_determinism.py +""" + +import multiprocessing as mp +import socket + +import pytest +import torch +import torch.distributed as dist + +from sglang.test.ci.ci_register import register_amd_ci + +register_amd_ci(est_time=120, stage="sgl-kernel-unit", runner_config="2-gpu-amd") + + +def get_open_port(): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def worker(world_size, rank, port): + device = torch.device(f"cuda:{rank}") + torch.cuda.set_device(device) + + dist.init_process_group( + backend="nccl", + init_method=f"tcp://localhost:{port}", + rank=rank, + world_size=world_size, + ) + + num_trials = 10 + + # Matrix sizes similar to real model layers + # Format: (batch_size, hidden_dim) - typical tensor shape for all-reduce + BS = 50 # max batch_size (1..BS) + hidden_dim = 16384 # hidden dimension / intermediate dimension + + # Different seed per rank - each GPU has DIFFERENT input + torch.manual_seed(42 + rank) + + # Create fixed inputs for all trials + # Single request: (hidden_dim,) + base_input = torch.randn(hidden_dim, dtype=torch.bfloat16, device=device) + base_input_rand = torch.randn(hidden_dim, dtype=torch.bfloat16, device=device) + + dist.barrier() + + # ========================================================================= + # TEST 1: Default all-reduce (same batch size) - should be DETERMINISTIC + # ========================================================================= + if rank == 0: + print(f"\n{'='*70}") + print("TEST 1: Default NCCL all_reduce (same batch size)") + print(f"{'='*70}") + dist.barrier() + + results_allreduce_only = [] + for trial in range(num_trials): + # Clone the same input + inp = base_input.clone() + + # Use default NCCL all-reduce + dist.all_reduce(inp) + torch.cuda.synchronize() + + # Store checksum + checksum = inp.view(-1).sum().item() + first_vals = inp.view(-1)[:5].clone() + results_allreduce_only.append((checksum, first_vals)) + + if rank == 0: + print( + f" Trial {trial+1:2d}: sum={checksum:.6f}, first5={first_vals.tolist()}" + ) + + # Check determinism + if rank == 0: + ref_sum, ref_vals = results_allreduce_only[0] + all_match = True + for i, (s, vals) in enumerate(results_allreduce_only[1:], 1): + if abs(ref_sum - s) > 1e-3 or not torch.allclose(ref_vals, vals, rtol=1e-3): + all_match = False + print(f" Trial {i+1} DIFFERS! ref_sum={ref_sum:.6f}, got={s:.6f}") + + if all_match: + print(" ✓ DEFAULT ALL_REDUCE (fixed BS): DETERMINISTIC (as expected)") + else: + print(" ✗ DEFAULT ALL_REDUCE (fixed BS): NON-DETERMINISTIC (unexpected!)") + + dist.barrier() + + # ========================================================================= + # TEST 2: Default all-reduce (different batch size) - typically NON-DETERMINISTIC + # [a], [a, x], [a, x, x], ... + # ========================================================================= + if rank == 0: + print(f"\n{'='*70}") + print("TEST 2: Default NCCL all_reduce (different batch size)") + print("Batches: [a], [a,x], [a,x,x], ...") + print(f"{'='*70}") + dist.barrier() + + results_allreduce_only = {trial: [] for trial in range(num_trials)} + for trial in range(num_trials): + for bs in range(1, BS + 1): + # Construct batch: (batch_size, hidden_dim) + # First element is base_input, rest are base_input_rand + batch = torch.stack([base_input] + [base_input_rand] * (bs - 1), dim=0) + # Shape: (bs, hidden_dim) + + # Flatten for all-reduce: (bs * hidden_dim,) + batch_flat = batch.view(-1) + + # Use default NCCL all-reduce + dist.all_reduce(batch_flat) + torch.cuda.synchronize() + + # Reshape back to (bs, hidden_dim) + batch_out = batch_flat.view(bs, hidden_dim) + + # Only compare output corresponding to first request + out_first_req = batch_out[0].clone() + checksum = out_first_req.sum().item() + first_vals = out_first_req[:5].clone() + results_allreduce_only[trial].append((bs, checksum, first_vals)) + + if rank == 0: + print( + f" Batch size {bs:2d}: sum={checksum:.6f}, first5={first_vals.tolist()}" + ) + + # Check determinism + if rank == 0: + for trial in range(num_trials): + results = results_allreduce_only[trial] + + _, ref_sum, ref_vals = results[0] + all_match = True + for _, s, vals in results[1:]: + if abs(ref_sum - s) > 1e-3 or not torch.allclose( + ref_vals, vals, rtol=1e-3 + ): + all_match = False + + if all_match: + print(" ✓ DEFAULT ALL_REDUCE (variant BS): DETERMINISTIC") + else: + print(" ✗ DEFAULT ALL_REDUCE (variant BS): NON-DETERMINISTIC") + + dist.barrier() + + dist.destroy_process_group() + + +def main(): + world_size = 8 + available_gpus = torch.cuda.device_count() + + print("=" * 70) + print("Default NCCL All-Reduce Determinism Test") + print("=" * 70) + print(f"Available GPUs: {available_gpus}") + print(f"Using world_size: {world_size}") + + if available_gpus < world_size: + print( + f"WARNING: Only {available_gpus} GPUs available, using {available_gpus} instead" + ) + world_size = available_gpus + + if world_size < 2: + print("ERROR: Need at least 2 GPUs for this test") + return + + mp.set_start_method("spawn", force=True) + port = get_open_port() + + procs = [] + for rank in range(world_size): + p = mp.Process(target=worker, args=(world_size, rank, port)) + p.start() + procs.append(p) + + for p in procs: + p.join() + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.device_count() < 2, + reason="Requires at least 2 CUDA GPUs", +) +def test_nccl_allreduce_determinism(): + """Test NCCL all-reduce determinism behavior with varying batch sizes.""" + main() + + +if __name__ == "__main__": + main() diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_awq_dequantize.py b/asian_ai/performance/SGLang/test/registered/jit/test_awq_dequantize.py new file mode 100644 index 0000000000000000000000000000000000000000..1f9184bc88f05fd87c8005a658a75dee04a51ad5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_awq_dequantize.py @@ -0,0 +1,169 @@ +import itertools +import sys + +import pytest +import torch + +from sglang.jit_kernel.awq_dequantize import awq_dequantize as jit_awq_dequantize +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=9, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +try: + from sgl_kernel import awq_dequantize as aot_awq_dequantize + + AOT_AVAILABLE = True +except ImportError: + AOT_AVAILABLE = False + + +def reverse_awq_order(t: torch.Tensor): + bits = 4 + AWQ_REVERSE_ORDER = [0, 4, 1, 5, 2, 6, 3, 7] + reverse_order_tensor = torch.arange( + t.shape[-1], + dtype=torch.int32, + device=t.device, + ) + reverse_order_tensor = reverse_order_tensor.view(-1, 32 // bits) + reverse_order_tensor = reverse_order_tensor[:, AWQ_REVERSE_ORDER] + reverse_order_tensor = reverse_order_tensor.view(-1) + + t = t[:, reverse_order_tensor] & 0xF + return t + + +# qweights - [R , C // 8], int32 +# scales - [R // G, C ], float16 +# zeros - [R // G, C // 8], int32 +def awq_dequantize_torch( + qweight: torch.Tensor, scales: torch.Tensor, qzeros: torch.Tensor, group_size: int +) -> torch.Tensor: + if group_size == -1: + group_size = qweight.shape[0] + + bits = 4 + shifts = torch.arange(0, 32, bits, device=qzeros.device) + + iweights = torch.bitwise_right_shift(qweight[:, :, None], shifts[None, None, :]).to( + torch.int8 + ) + + iweights = iweights.view(iweights.shape[0], -1) + + zeros = torch.bitwise_right_shift(qzeros[:, :, None], shifts[None, None, :]).to( + torch.int8 + ) + zeros = zeros.view(qzeros.shape[0], -1) + zeros = reverse_awq_order(zeros) + + iweights = reverse_awq_order(iweights) + + iweights = torch.bitwise_and(iweights, (2**bits) - 1) + zeros = torch.bitwise_and(zeros, (2**bits) - 1) + + scales = scales.repeat_interleave(group_size, dim=0) + zeros = zeros.repeat_interleave(group_size, dim=0) + return (iweights - zeros) * scales + + +@pytest.mark.parametrize( + "qweight_row,qweight_col,is_bf16_act", + list( + itertools.product( + [128, 256, 512, 1024, 3584], + [16, 32, 64, 128, 448], + [True, False], + ) + ), +) +def test_awq_dequantize_jit_vs_torch( + qweight_row: int, qweight_col: int, is_bf16_act: bool +): + device = torch.device("cuda") + qweight = torch.randint( + 0, + torch.iinfo(torch.int32).max, + (qweight_row, qweight_col), + dtype=torch.int32, + device=device, + ) + group_size = qweight_row + scales_row = qweight_row // group_size + scales_col = qweight_col * 8 + + if is_bf16_act: + scales = torch.rand(scales_row, scales_col, dtype=torch.bfloat16, device=device) + else: + scales = torch.rand(scales_row, scales_col, dtype=torch.float16, device=device) + + qzeros = torch.randint( + 0, + torch.iinfo(torch.int32).max, + (scales_row, qweight_col), + dtype=torch.int32, + device=device, + ) + + # Run both implementations + torch_out = awq_dequantize_torch(qweight, scales, qzeros, group_size) + jit_out = jit_awq_dequantize(qweight, scales, qzeros) + + # Compare results (approximate due to different computation paths) + torch.testing.assert_close( + torch_out.to(torch.float32), jit_out.to(torch.float32), rtol=1e-3, atol=1e-5 + ) + + +@pytest.mark.parametrize( + "qweight_row,qweight_col,is_bf16_act", + list( + itertools.product( + [128, 256, 512, 1024, 3584], + [16, 32, 64, 128, 448], + [True, False], + ) + ), +) +def test_awq_dequantize_jit_vs_aot( + qweight_row: int, qweight_col: int, is_bf16_act: bool +): + if not AOT_AVAILABLE: + pytest.skip("sgl_kernel AOT not available") + + device = torch.device("cuda") + qweight = torch.randint( + 0, + torch.iinfo(torch.int32).max, + (qweight_row, qweight_col), + dtype=torch.int32, + device=device, + ) + group_size = qweight_row + scales_row = qweight_row // group_size + scales_col = qweight_col * 8 + + if is_bf16_act: + scales = torch.rand(scales_row, scales_col, dtype=torch.bfloat16, device=device) + else: + scales = torch.rand(scales_row, scales_col, dtype=torch.float16, device=device) + + qzeros = torch.randint( + 0, + torch.iinfo(torch.int32).max, + (scales_row, qweight_col), + dtype=torch.int32, + device=device, + ) + + # Run both implementations + aot_out = aot_awq_dequantize(qweight, scales, qzeros) + jit_out = jit_awq_dequantize(qweight, scales, qzeros) + + # Bitwise equality + torch.testing.assert_close(jit_out, aot_out, rtol=0, atol=0) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_awq_marlin_moe_repack.py b/asian_ai/performance/SGLang/test/registered/jit/test_awq_marlin_moe_repack.py new file mode 100644 index 0000000000000000000000000000000000000000..b7ba714b08ab1d940dc98ad7c3e583f0f577d29d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_awq_marlin_moe_repack.py @@ -0,0 +1,125 @@ +import sys + +import numpy as np +import pytest +import torch +from sgl_kernel.scalar_type import scalar_types + +from sglang.jit_kernel.awq_marlin_repack import ( + awq_marlin_moe_repack as jit_awq_marlin_moe_repack, +) +from sglang.srt.layers.quantization.utils import pack_cols, quantize_weights +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def _has_aot_awq_marlin_moe_repack() -> bool: + return hasattr(torch.ops.sgl_kernel, "awq_marlin_moe_repack") and hasattr( + torch.ops.sgl_kernel.awq_marlin_moe_repack, "default" + ) + + +AOT_AVAILABLE = _has_aot_awq_marlin_moe_repack() + + +def awq_pack( + q_w: torch.Tensor, + num_bits: int, + size_k: int, + size_n: int, +): + assert q_w.shape == (size_k, size_n) + + if num_bits == 4: + interleave = np.array([0, 2, 4, 6, 1, 3, 5, 7]) + elif num_bits == 8: + interleave = np.array([0, 2, 1, 3]) + else: + raise Exception("num_bits must be 4 or 8, got {}".format(num_bits)) + + q_w = q_w.reshape((-1, len(interleave)))[:, interleave].ravel() + q_w = q_w.reshape((-1, size_n)).contiguous() + + return pack_cols(q_w, num_bits, size_k, size_n) + + +@pytest.mark.parametrize("num_bits", [4]) +@pytest.mark.parametrize("num_experts", [2, 4, 8]) +@pytest.mark.parametrize("k_tiles,n_tiles", [(1, 1), (2, 2), (4, 4)]) +@pytest.mark.parametrize("group_size", [16, 32]) +def test_awq_marlin_moe_repack_jit_vs_aot( + num_bits, num_experts, k_tiles, n_tiles, group_size +): + if not AOT_AVAILABLE: + pytest.skip("sgl_kernel AOT not available") + + tile_k, tile_n = 16, 64 + size_k = k_tiles * tile_k + size_n = n_tiles * tile_n + pack_factor = 32 // num_bits + + # Create per-expert AWQ-packed weights + b_q_weight = torch.empty( + (num_experts, size_k, size_n // pack_factor), + dtype=torch.int32, + device="cuda", + ) + for e in range(num_experts): + b_weight = torch.randn((size_k, size_n), dtype=torch.float16, device="cuda") + w_ref, q_w, s, zp = quantize_weights( + b_weight, scalar_types.uint4, group_size, zero_points=True + ) + b_q_weight[e] = awq_pack(q_w, num_bits, size_k, size_n) + + perm = torch.empty((num_experts, 0), dtype=torch.int32, device="cuda") + + out_jit = jit_awq_marlin_moe_repack(b_q_weight, perm, size_k, size_n, num_bits) + out_aot = torch.ops.sgl_kernel.awq_marlin_moe_repack.default( + b_q_weight, perm, size_k, size_n, num_bits + ) + + torch.cuda.synchronize() + + # Bitwise equality + torch.testing.assert_close(out_jit, out_aot, rtol=0, atol=0) + + +@pytest.mark.parametrize("num_bits", [4]) +@pytest.mark.parametrize("num_experts", [2, 4]) +@pytest.mark.parametrize("k_tiles,n_tiles", [(1, 1), (2, 2)]) +@pytest.mark.parametrize("group_size", [16, 32]) +def test_awq_marlin_moe_repack_shape( + num_bits, num_experts, k_tiles, n_tiles, group_size +): + tile_k, tile_n = 16, 64 + size_k = k_tiles * tile_k + size_n = n_tiles * tile_n + pack_factor = 32 // num_bits + + # Create per-expert AWQ-packed weights + b_q_weight = torch.empty( + (num_experts, size_k, size_n // pack_factor), + dtype=torch.int32, + device="cuda", + ) + for e in range(num_experts): + b_weight = torch.randn((size_k, size_n), dtype=torch.float16, device="cuda") + w_ref, q_w, s, zp = quantize_weights( + b_weight, scalar_types.uint4, group_size, zero_points=True + ) + b_q_weight[e] = awq_pack(q_w, num_bits, size_k, size_n) + + perm = torch.empty((num_experts, 0), dtype=torch.int32, device="cuda") + + out = jit_awq_marlin_moe_repack(b_q_weight, perm, size_k, size_n, num_bits) + torch.cuda.synchronize() + + assert out.is_cuda and out.dtype == torch.int32 + expected_shape = (num_experts, size_k // 16, size_n * (num_bits // 2)) + assert list(out.shape) == list(expected_shape) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_awq_marlin_repack.py b/asian_ai/performance/SGLang/test/registered/jit/test_awq_marlin_repack.py new file mode 100644 index 0000000000000000000000000000000000000000..380698a47b578c64e4fa02ded2179d9f737a2874 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_awq_marlin_repack.py @@ -0,0 +1,111 @@ +import sys + +import numpy as np +import pytest +import torch +from sgl_kernel.scalar_type import scalar_types + +from sglang.jit_kernel.awq_marlin_repack import ( + awq_marlin_repack as jit_awq_marlin_repack, +) +from sglang.srt.layers.quantization.utils import pack_cols, quantize_weights +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_marlin_utils import get_weight_perm, marlin_weights + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def _has_aot_awq_marlin_repack() -> bool: + return hasattr(torch.ops.sgl_kernel, "awq_marlin_repack") and hasattr( + torch.ops.sgl_kernel.awq_marlin_repack, "default" + ) + + +AOT_AVAILABLE = _has_aot_awq_marlin_repack() + + +def awq_pack( + q_w: torch.Tensor, + num_bits: int, + size_k: int, + size_n: int, +): + assert q_w.shape == (size_k, size_n) + + if num_bits == 4: + interleave = np.array([0, 2, 4, 6, 1, 3, 5, 7]) + elif num_bits == 8: + interleave = np.array([0, 2, 1, 3]) + else: + raise Exception("num_bits must be 4 or 8, got {}".format(num_bits)) + + q_w = q_w.reshape((-1, len(interleave)))[:, interleave].ravel() + q_w = q_w.reshape((-1, size_n)).contiguous() + + return pack_cols(q_w, num_bits, size_k, size_n) + + +@pytest.mark.parametrize("num_bits", [4, 8]) +@pytest.mark.parametrize("k_tiles,n_tiles", [(1, 1), (2, 2), (4, 4)]) +@pytest.mark.parametrize("group_size", [16, 32]) +def test_awq_marlin_repack_jit_vs_aot(num_bits, k_tiles, n_tiles, group_size): + if not AOT_AVAILABLE: + pytest.skip("sgl_kernel AOT not available") + + tile_k, tile_n = 16, 64 + size_k = k_tiles * tile_k + size_n = n_tiles * tile_n + + b_weight = torch.randn((size_k, size_n), dtype=torch.float16, device="cuda") + + w_ref, q_w, s, zp = quantize_weights( + b_weight, scalar_types.uint4, group_size, zero_points=True + ) + + q_w_awq = awq_pack(q_w, num_bits, size_k, size_n) + + out_jit = jit_awq_marlin_repack(q_w_awq, size_k, size_n, num_bits) + out_aot = torch.ops.sgl_kernel.awq_marlin_repack.default( + q_w_awq, size_k, size_n, num_bits + ) + + torch.cuda.synchronize() + + # Bitwise equality + torch.testing.assert_close(out_jit, out_aot, rtol=0, atol=0) + + +@pytest.mark.parametrize("num_bits", [4, 8]) +@pytest.mark.parametrize("k_tiles,n_tiles", [(1, 1), (2, 2)]) +@pytest.mark.parametrize("group_size", [16, 32]) +def test_awq_marlin_repack_correct(num_bits, k_tiles, n_tiles, group_size): + tile_k, tile_n = 16, 64 + size_k = k_tiles * tile_k + size_n = n_tiles * tile_n + pack_factor = 32 // num_bits + + b_weight = torch.randn((size_k, size_n), dtype=torch.float16, device="cuda") + + w_ref, q_w, s, zp = quantize_weights( + b_weight, scalar_types.uint4, group_size, zero_points=True + ) + + q_w_awq = awq_pack(q_w, num_bits, size_k, size_n) + + weight_perm = get_weight_perm(num_bits) + q_w_marlin = marlin_weights(q_w, size_k, size_n, num_bits, weight_perm) + + out_gpu = jit_awq_marlin_repack(q_w_awq, size_k, size_n, num_bits) + assert out_gpu.is_cuda and out_gpu.dtype == torch.int32 + + expected_cols = size_n * tile_k // pack_factor + assert list(out_gpu.shape) == [size_k // tile_k, expected_cols] + + torch.cuda.synchronize() + + torch.testing.assert_close(out_gpu, q_w_marlin) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_clamp_position.py b/asian_ai/performance/SGLang/test/registered/jit/test_clamp_position.py new file mode 100644 index 0000000000000000000000000000000000000000..c19a0e6e5f5276b6f8569b99ddd2229053a631f8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_clamp_position.py @@ -0,0 +1,47 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.clamp_position import clamp_position_cuda +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=12, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=12, stage="jit-kernel-unit", runner_config="amd") + + +def _reference_clamp_position(seq_lens): + return torch.clamp(seq_lens - 1, min=0).to(seq_lens.dtype) + + +@pytest.mark.parametrize("size", [1, 2, 127, 128, 255, 256, 1024, 4097]) +@pytest.mark.parametrize("dtype", [torch.int32, torch.int64]) +class TestClampPosition: + def test_normal(self, size: int, dtype: torch.dtype) -> None: + seq_lens = torch.randint(1, 10000, (size,), dtype=dtype, device="cuda") + expected = _reference_clamp_position(seq_lens) + result = clamp_position_cuda(seq_lens) + assert torch.equal(result, expected) + + def test_zeros(self, size: int, dtype: torch.dtype) -> None: + seq_lens = torch.zeros(size, dtype=dtype, device="cuda") + expected = _reference_clamp_position(seq_lens) + result = clamp_position_cuda(seq_lens) + assert torch.equal(result, expected) + + def test_ones(self, size: int, dtype: torch.dtype) -> None: + seq_lens = torch.ones(size, dtype=dtype, device="cuda") + expected = _reference_clamp_position(seq_lens) + result = clamp_position_cuda(seq_lens) + assert torch.equal(result, expected) + + def test_mixed(self, size: int, dtype: torch.dtype) -> None: + seq_lens = torch.randint(0, 10000, (size,), dtype=dtype, device="cuda") + expected = _reference_clamp_position(seq_lens) + result = clamp_position_cuda(seq_lens) + assert torch.equal(result, expected) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_concat_mla.py b/asian_ai/performance/SGLang/test/registered/jit/test_concat_mla.py new file mode 100644 index 0000000000000000000000000000000000000000..3fddee233b9a7dd0ff6d5d3b73c8d4a1b30d5643 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_concat_mla.py @@ -0,0 +1,175 @@ +import itertools +import sys + +import pytest +import torch +import triton + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=17, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def torch_concat_mla_k( + k: torch.Tensor, k_nope: torch.Tensor, k_rope: torch.Tensor +) -> None: + """Reference PyTorch implementation for concat_mla_k.""" + # k_nope: [num_tokens, num_heads, nope_head_dim] + # k_rope: [num_tokens, 1, rope_head_dim] + # k: [num_tokens, num_heads, nope_head_dim + rope_head_dim] + nope_head_dim = k_nope.shape[-1] + k[:, :, :nope_head_dim] = k_nope + # Broadcast k_rope across all heads + k[:, :, nope_head_dim:] = k_rope.expand(-1, k.shape[1], -1) + + +def torch_concat_mla_absorb_q( + a: torch.Tensor, b: torch.Tensor, out: torch.Tensor +) -> None: + """Reference PyTorch implementation for concat_mla_absorb_q.""" + # a: [dim_0, dim_1, a_last_dim] + # b: [dim_0, dim_1, b_last_dim] + # out: [dim_0, dim_1, a_last_dim + b_last_dim] + a_last_dim = a.shape[-1] + out[:, :, :a_last_dim] = a + out[:, :, a_last_dim:] = b + + +def sgl_kernel_concat_mla_k( + k: torch.Tensor, k_nope: torch.Tensor, k_rope: torch.Tensor +) -> None: + """AOT compiled sgl_kernel implementation.""" + from sgl_kernel import concat_mla_k + + concat_mla_k(k, k_nope, k_rope) + + +def sgl_kernel_concat_mla_absorb_q( + a: torch.Tensor, b: torch.Tensor, out: torch.Tensor +) -> None: + """AOT compiled sgl_kernel implementation.""" + from sgl_kernel import concat_mla_absorb_q + + result = concat_mla_absorb_q(a, b) # AOT returns output + out.copy_(result) # Copy to provided tensor for comparison + + +def jit_concat_mla_k( + k: torch.Tensor, k_nope: torch.Tensor, k_rope: torch.Tensor +) -> None: + """JIT compiled implementation.""" + from sglang.jit_kernel.concat_mla import concat_mla_k + + concat_mla_k(k, k_nope, k_rope) + + +def jit_concat_mla_absorb_q( + a: torch.Tensor, b: torch.Tensor, out: torch.Tensor +) -> None: + """JIT compiled implementation - wrapper for test compatibility.""" + from sglang.jit_kernel.concat_mla import concat_mla_absorb_q + + result = concat_mla_absorb_q(a, b) + out.copy_(result) + + +# Constants matching the kernel +NUM_LOCAL_HEADS = 128 +QK_NOPE_HEAD_DIM = 128 +QK_ROPE_HEAD_DIM = 64 +K_HEAD_DIM = QK_NOPE_HEAD_DIM + QK_ROPE_HEAD_DIM + +A_LAST_DIM = 512 +B_LAST_DIM = 64 +OUT_LAST_DIM = A_LAST_DIM + B_LAST_DIM + +DEVICE = "cuda" +DTYPE = torch.bfloat16 + +# Test configurations +NUM_TOKENS_LIST = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] + + +@pytest.mark.parametrize("num_tokens", NUM_TOKENS_LIST) +def test_concat_mla_k_jit_vs_torch(num_tokens: int) -> None: + """Test JIT kernel against PyTorch reference.""" + k_jit = torch.empty( + num_tokens, NUM_LOCAL_HEADS, K_HEAD_DIM, device=DEVICE, dtype=DTYPE + ) + k_torch = torch.empty( + num_tokens, NUM_LOCAL_HEADS, K_HEAD_DIM, device=DEVICE, dtype=DTYPE + ) + + k_nope = torch.randn( + num_tokens, NUM_LOCAL_HEADS, QK_NOPE_HEAD_DIM, device=DEVICE, dtype=DTYPE + ) + k_rope = torch.randn(num_tokens, 1, QK_ROPE_HEAD_DIM, device=DEVICE, dtype=DTYPE) + + torch_concat_mla_k(k_torch, k_nope, k_rope) + jit_concat_mla_k(k_jit, k_nope, k_rope) + + triton.testing.assert_close(k_jit, k_torch, atol=0, rtol=0) + + +@pytest.mark.parametrize("num_tokens", NUM_TOKENS_LIST) +def test_concat_mla_k_jit_vs_aot(num_tokens: int) -> None: + """Test JIT kernel against AOT kernel for bitwise equivalence.""" + k_jit = torch.empty( + num_tokens, NUM_LOCAL_HEADS, K_HEAD_DIM, device=DEVICE, dtype=DTYPE + ) + k_aot = torch.empty( + num_tokens, NUM_LOCAL_HEADS, K_HEAD_DIM, device=DEVICE, dtype=DTYPE + ) + + k_nope = torch.randn( + num_tokens, NUM_LOCAL_HEADS, QK_NOPE_HEAD_DIM, device=DEVICE, dtype=DTYPE + ) + k_rope = torch.randn(num_tokens, 1, QK_ROPE_HEAD_DIM, device=DEVICE, dtype=DTYPE) + + sgl_kernel_concat_mla_k(k_aot, k_nope, k_rope) + jit_concat_mla_k(k_jit, k_nope, k_rope) + + triton.testing.assert_close(k_jit, k_aot, atol=0, rtol=0) + + +DIM_0_LIST = [1, 2, 4, 8, 16, 32] +DIM_1_LIST = [1, 2, 4, 8, 16, 128] + + +@pytest.mark.parametrize( + "dim_0,dim_1", + list(itertools.product(DIM_0_LIST, DIM_1_LIST)), +) +def test_concat_mla_absorb_q_jit_vs_torch(dim_0: int, dim_1: int) -> None: + """Test JIT kernel against PyTorch reference.""" + a = torch.randn(dim_0, dim_1, A_LAST_DIM, device=DEVICE, dtype=DTYPE) + b = torch.randn(dim_0, dim_1, B_LAST_DIM, device=DEVICE, dtype=DTYPE) + out_jit = torch.empty(dim_0, dim_1, OUT_LAST_DIM, device=DEVICE, dtype=DTYPE) + out_torch = torch.empty(dim_0, dim_1, OUT_LAST_DIM, device=DEVICE, dtype=DTYPE) + + torch_concat_mla_absorb_q(a, b, out_torch) + jit_concat_mla_absorb_q(a, b, out_jit) + + triton.testing.assert_close(out_jit, out_torch, atol=0, rtol=0) + + +@pytest.mark.parametrize( + "dim_0,dim_1", + list(itertools.product(DIM_0_LIST, DIM_1_LIST)), +) +def test_concat_mla_absorb_q_jit_vs_aot(dim_0: int, dim_1: int) -> None: + """Test JIT kernel against AOT kernel for bitwise equivalence.""" + a = torch.randn(dim_0, dim_1, A_LAST_DIM, device=DEVICE, dtype=DTYPE) + b = torch.randn(dim_0, dim_1, B_LAST_DIM, device=DEVICE, dtype=DTYPE) + out_jit = torch.empty(dim_0, dim_1, OUT_LAST_DIM, device=DEVICE, dtype=DTYPE) + out_aot = torch.empty(dim_0, dim_1, OUT_LAST_DIM, device=DEVICE, dtype=DTYPE) + + sgl_kernel_concat_mla_absorb_q(a, b, out_aot) + jit_concat_mla_absorb_q(a, b, out_jit) + + triton.testing.assert_close(out_jit, out_aot, atol=0, rtol=0) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_custom_all_reduce.py b/asian_ai/performance/SGLang/test/registered/jit/test_custom_all_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..631d454d84511e5328db355780aac64be7304721 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_custom_all_reduce.py @@ -0,0 +1,239 @@ +"""Correctness test for the JIT custom all-reduce (v2) kernel. + +Compares the JIT custom all-reduce output against NCCL all-reduce for a sweep +of tensor sizes, dtypes, and algorithms, in both eager and CUDA-graph modes. + +Usage:: + + # Run the test on the default world sizes (2, 4, 8 GPUs): + python tests/test_custom_all_reduce.py + # Pick a specific world size (or comma-separated list), e.g. the rarer + # odd / non-power-of-two counts that the default sweep skips: + python tests/test_custom_all_reduce.py --num-gpu 3 + python tests/test_custom_all_reduce.py --num-gpu 2,4,6,8 + # Extra pytest args (forwarded to each torchrun worker): + python tests/test_custom_all_reduce.py -k bfloat16 +""" + +from __future__ import annotations + +import atexit +import itertools +import logging +import multiprocessing +import os +from multiprocessing.context import SpawnProcess +from typing import List + +import pytest +import torch +import torch.distributed as dist +import triton + +import sglang.srt.distributed.parallel_state as ps +from sglang.jit_kernel.all_reduce import ( + AllReduceAlgo, + _jit_custom_all_reduce_pull_module, + _jit_custom_all_reduce_push_module, +) +from sglang.jit_kernel.mp import register_comm_cleanup +from sglang.jit_kernel.tests.utils import multigpu_pytest_main +from sglang.jit_kernel.utils import cache_once, get_ci_test_range +from sglang.srt.distributed.device_communicators.custom_all_reduce_v2 import ( + CustomAllReduceV2, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=300, + stage="base-b-kernel-unit", + runner_config="8-gpu-h200", +) +register_cuda_ci( + est_time=300, + suite="nightly-kernel-8-gpu-h200", + nightly=True, +) + +# --------------------------------------------------------------------------- +# Test parameters +# --------------------------------------------------------------------------- + +TEST_SIZES = [ + 16, + 32, + 512, + 1024, + 1024 + 16, # weird case + 4 * 1024, + 32 * 1024, + 256 * 1024, + 2 * 1024 * 1024, + 4 * 1024 * 1024, +] +TEST_DTYPES = [torch.float16, torch.bfloat16, torch.float32] +TEST_ALGOS = [ + AllReduceAlgo.ONE_SHOT_PULL, + AllReduceAlgo.ONE_SHOT_PUSH, + AllReduceAlgo.TWO_SHOT_PULL, +] +USE_GRAPH_OPTIONS = [False, True] +TEST_LAYERS = 4 +TEST_LOOP = 16 + +TEST_SIZES = get_ci_test_range(TEST_SIZES, [16, 1024, 32 * 1024, 2 * 1024 * 1024]) +TEST_DTYPES = get_ci_test_range(TEST_DTYPES, [torch.bfloat16]) + +# --------------------------------------------------------------------------- +# Parallel JIT precompile (outer process, before any torchrun child starts) +# --------------------------------------------------------------------------- + + +def _compile_one(dtype: torch.dtype, world_size: int) -> None: + """Compile both (push, pull) variants for a single (dtype, world_size). + + Top-level so it survives ``spawn`` pickling. Compiled artifacts are + cached on disk by ``tvm_ffi``; torchrun children will reuse them. + """ + _jit_custom_all_reduce_pull_module(dtype, world_size) + _jit_custom_all_reduce_push_module(dtype, world_size) + + +def _precompile_kernels(num_gpus: List[int]) -> None: + """Fan out one process per (dtype, world_size) to warm the JIT cache. + + Without this, every torchrun child serial-compiles its kernels on first + use, multiplying the wall-clock cost of the run by ~(#dtypes * #ranks). + """ + ctx = multiprocessing.get_context("spawn") + procs: list[tuple[torch.dtype, int, SpawnProcess]] = [] + for dtype, world_size in itertools.product(TEST_DTYPES, num_gpus): + p = ctx.Process(target=_compile_one, args=(dtype, world_size)) + p.start() + procs.append((dtype, world_size, p)) + for dtype, world_size, p in procs: + p.join() + if p.exitcode != 0: + raise RuntimeError( + f"Custom-all-reduce precompile failed for " + f"{dtype=} {world_size=} (exit {p.exitcode})" + ) + + +# --------------------------------------------------------------------------- +# Per-rank distributed setup (run once per torchrun worker) +# --------------------------------------------------------------------------- + + +@cache_once +def _init_cpu_group_once() -> dist.ProcessGroup: + """Initialize gloo world group + cuda device for this rank.""" + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + torch.cuda.set_device(local_rank) + dist.init_process_group(backend="gloo") + ps._WORLD = coord = ps.init_world_group( + ranks=list(range(world_size)), + local_rank=local_rank, + backend="nccl", + ) + atexit.register(dist.destroy_process_group) + cpu_group = coord.cpu_group + assert isinstance(cpu_group, dist.ProcessGroup) + # Suppress chatty internal logging for cleaner test output. + logging.disable(logging.INFO) + # Use a non-default stream (mirrors prior behavior). + torch.cuda.set_stream(torch.cuda.Stream()) + return cpu_group + + +@cache_once +def _init_nccl_group_once() -> dist.ProcessGroup: + _init_cpu_group_once() + coord = ps._WORLD + assert coord is not None and coord.device_group is not None + return coord.device_group + + +@cache_once +def _init_comm_once() -> CustomAllReduceV2: + cpu_group = _init_cpu_group_once() + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + max_size = max(TEST_SIZES) * max( + torch.tensor([], dtype=d).element_size() for d in TEST_DTYPES + ) + comm = CustomAllReduceV2(cpu_group, device, max_size, max_size) + if comm.disabled: + raise RuntimeError("JIT CustomAllReduceV2 is disabled on this system") + register_comm_cleanup(comm) + return comm + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("use_graph", USE_GRAPH_OPTIONS) +@pytest.mark.parametrize("algo", TEST_ALGOS) +@pytest.mark.parametrize("dtype", TEST_DTYPES) +@pytest.mark.parametrize("size", TEST_SIZES) +@torch.inference_mode() +def test_custom_all_reduce( + size: int, + dtype: torch.dtype, + algo: AllReduceAlgo, + use_graph: bool, +) -> None: + nccl_group = _init_nccl_group_once() + comm = _init_comm_once() + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + comm.override_algo = algo + + if use_graph: + graph = torch.cuda.CUDAGraph() + graph_inp = torch.zeros((TEST_LAYERS, size), dtype=dtype, device=device) + outs: list[torch.Tensor] = [] + with comm.capture(): + with torch.cuda.graph(graph): + for i in range(TEST_LAYERS): + outs.append(comm.custom_all_reduce(graph_inp[i])) + out_jit_stack = torch.stack(outs) + torch.cuda.synchronize() + + def run(x: torch.Tensor) -> torch.Tensor: + graph_inp.copy_(x) + graph.replay() + return out_jit_stack.clone() + + else: + + def run(x: torch.Tensor) -> torch.Tensor: + eager_inp = x.clone() + outs = [] + for i in range(TEST_LAYERS): + outs.append(comm.custom_all_reduce(eager_inp[i])) + torch.cuda.synchronize() + return torch.stack(outs) + + for _ in range(TEST_LOOP): + # NOTE: 15 * 8 < 128, which is the precision limit for bf16 + inp = torch.randint(0, 16, (TEST_LAYERS, size), dtype=dtype, device=device) + assert comm.should_custom_ar(inp[0]) + out_ref = inp.clone() + dist.all_reduce(out_ref, group=nccl_group) + out_jit = run(inp) + # Exact equality, since values are small integers within bf16 precision. + triton.testing.assert_close(out_ref, out_jit, atol=0, rtol=0) + + +if __name__ == "__main__": + # Only sweep the common world sizes (2, 4, 8) by default: testing every + # count in 2..8 serially overruns the per-file CI time budget, and 3/5/6/7 + # are rare in practice. Use --num-gpu to exercise them explicitly. + multigpu_pytest_main( + __name__, + __file__, + num_gpus=(2, 4, 8), + pre_launch_fn=_precompile_kernels, + ) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_cutedsl_dsv3_fused_a_gemm.py b/asian_ai/performance/SGLang/test/registered/jit/test_cutedsl_dsv3_fused_a_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad63b2c6df5469d5511a6ccdbca53c3d570fc3b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_cutedsl_dsv3_fused_a_gemm.py @@ -0,0 +1,47 @@ +"""Tests for the CuTe DSL DeepSeek-V3 fused-A GEMM kernel.""" + +import sys + +import pytest +import torch + +from sglang.jit_kernel.utils import get_ci_test_range, get_jit_cuda_arch, is_hip_runtime +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +if not torch.cuda.is_available(): + pytest.skip("CUDA required", allow_module_level=True) + +from sglang.jit_kernel.cutedsl_dsv3_fused_a_gemm import dsv3_fused_a_gemm # noqa: E402 + +# hd_in must be a multiple of 256; 6144/7168 cover the real fused-A shapes. +HD_INS = [6144, 7168] +# hd_out must be a multiple of 16; 2112 and 2624 cover real fused-A variants. +HD_OUTS = [2112, 2624] +NUM_TOKENS = get_ci_test_range(list(range(1, 17)), [1, 8, 16]) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +@pytest.mark.parametrize("hd_out", HD_OUTS) +@pytest.mark.parametrize("hd_in", HD_INS) +@pytest.mark.parametrize("num_tokens", NUM_TOKENS) +def test_dsv3_fused_a_gemm(num_tokens, hd_in, hd_out): + if is_hip_runtime() or get_jit_cuda_arch().major < 9: + pytest.skip("SM90+ required") + + torch.manual_seed(num_tokens) + weight = torch.randn(hd_out, hd_in, dtype=torch.bfloat16, device="cuda") + mat_a = torch.randn(num_tokens, hd_in, dtype=torch.bfloat16, device="cuda") + mat_b = weight.t() + + out = dsv3_fused_a_gemm(mat_a, mat_b) + assert out.shape == (num_tokens, hd_out) + assert out.dtype == torch.bfloat16 + + ref = (mat_a.float() @ weight.float().T).bfloat16() + torch.testing.assert_close(out, ref, rtol=2e-2, atol=2.5) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_cutedsl_gdn.py b/asian_ai/performance/SGLang/test/registered/jit/test_cutedsl_gdn.py new file mode 100644 index 0000000000000000000000000000000000000000..8d9fddce1e2ba6a9f78d7c7c675bfdafb0d1a65f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_cutedsl_gdn.py @@ -0,0 +1,312 @@ +"""Tests for CuTe DSL fused sigmoid gating delta rule kernel (GDN).""" + +import sys + +import numpy as np +import pytest +import torch + +from sglang.test.ci.ci_register import register_cuda_ci + +try: + import cuda.bindings.driver as cuda_driver + import cutlass # noqa: F401 + from cutlass.cute.runtime import from_dlpack + + from sglang.jit_kernel import cutedsl_gdn + + CUTEDSL_AVAILABLE = True +except ImportError: + CUTEDSL_AVAILABLE = False + cutedsl_gdn = None + +try: + from sglang.srt.layers.attention.fla.fused_sigmoid_gating_recurrent import ( + fused_sigmoid_gating_delta_rule_update, + ) + + TRITON_AVAILABLE = True +except ImportError: + TRITON_AVAILABLE = False + +register_cuda_ci(est_time=5, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def run_triton_kernel(A_log, dt_bias, q, k, v, a, b, initial_state, indices, scale): + return fused_sigmoid_gating_delta_rule_update( + A_log=A_log, + a=a, + dt_bias=dt_bias, + softplus_beta=1.0, + softplus_threshold=20.0, + q=q, + k=k, + v=v, + b=b, + initial_state_source=initial_state, + initial_state_indices=indices, + scale=scale, + use_qk_l2norm_in_kernel=True, + cu_seqlens=None, + ) + + +@pytest.mark.skipif(not CUTEDSL_AVAILABLE, reason="CuTe DSL not available") +@pytest.mark.skipif(not TRITON_AVAILABLE, reason="Triton kernel not available") +@pytest.mark.skip( + reason=( + "Temporary CI workaround: CuTe DSL GDN precision is currently unstable " + "against the Triton reference and needs follow-up investigation." + ) +) +@pytest.mark.parametrize("B", [16, 128]) +def test_cutedsl_gdn_precision(B: int): + """Test precision of CuTe DSL GDN kernel against Triton reference.""" + torch.manual_seed(2025) + T, H, K, V, HV = 1, 16, 128, 128, 32 + scale = K**-0.5 + + A_log = torch.randn(HV, dtype=torch.float32, device="cuda") + dt_bias = torch.randn(HV, dtype=torch.bfloat16, device="cuda") + a = torch.randn(B, T, HV, dtype=torch.bfloat16, device="cuda") + b = torch.randn(B, T, HV, dtype=torch.bfloat16, device="cuda") + q = torch.randn(B, T, H, K, dtype=torch.bfloat16, device="cuda") + k = torch.randn(B, T, H, K, dtype=torch.bfloat16, device="cuda") + v = torch.randn(B, T, HV, V, dtype=torch.bfloat16, device="cuda") + indices = torch.arange(B, dtype=torch.int32, device="cuda") + state_cutedsl = torch.randn(B, HV, K, V, dtype=torch.float32, device="cuda") + state_triton = state_cutedsl.clone().reshape(-1).contiguous() + + # Warmup compilation + _ = cutedsl_gdn.cutedsl_fused_sigmoid_gating_delta_rule_update( + A_log, dt_bias, q, k, v, a, b, state_cutedsl.clone(), indices, scale=scale + ) + torch.cuda.synchronize() + + # Fresh state for actual test + state_cutedsl = torch.randn(B, HV, K, V, dtype=torch.float32, device="cuda") + state_triton = state_cutedsl.clone().reshape(-1).contiguous() + + out_cutedsl = cutedsl_gdn.cutedsl_fused_sigmoid_gating_delta_rule_update( + A_log, dt_bias, q, k, v, a, b, state_cutedsl, indices, scale=scale + ) + out_triton = run_triton_kernel( + A_log, dt_bias, q, k, v, a, b, state_triton, indices, scale + ) + + # Check precision: diff > 0.1 must be < 1% of elements + abs_diff = (out_triton.float() - out_cutedsl.float()).abs() + max_diff = abs_diff.max().item() + mean_diff = abs_diff.mean().item() + fail_rate = (abs_diff > 0.1).float().mean().item() * 100 + has_nan = torch.isnan(out_cutedsl).any() or torch.isinf(out_cutedsl).any() + + kernel_type = "SmallBatch" if B < 32 else "LargeBatch" + print( + f"\n B={B} ({kernel_type}): max_diff={max_diff:.2e}, mean_diff={mean_diff:.2e}, fail_rate={fail_rate:.2f}%" + ) + + assert not has_nan, "Output contains NaN/Inf" + assert fail_rate < 1.0, f"Fail rate {fail_rate:.2f}% >= 1%" + + +@pytest.mark.skipif( + True, + reason="Skip the performance test because the speedup ratio is highly unstable in the CI environment. ", +) +@pytest.mark.skipif(not CUTEDSL_AVAILABLE, reason="CuTe DSL not available") +@pytest.mark.skipif(not TRITON_AVAILABLE, reason="Triton kernel not available") +@pytest.mark.parametrize("B", [1, 128]) +def test_cutedsl_gdn_performance(B: int): + """Benchmark CuTe DSL GDN kernel against Triton reference.""" + torch.manual_seed(2025) + T, H, K, V, HV = 1, 16, 128, 128, 32 + N = B + scale = K**-0.5 + is_varlen = True + warmup, bench_iters, run_iters = 10, 100, 10 + + A_log = torch.randn(HV, dtype=torch.float32, device="cuda") + dt_bias = torch.randn(HV, dtype=torch.bfloat16, device="cuda") + indices = torch.arange(N, dtype=torch.int32, device="cuda") + state_cutedsl = torch.randn(N, HV, K, V, dtype=torch.float32, device="cuda") + state_triton = state_cutedsl.reshape(-1).contiguous() + cu_seqlens = torch.zeros(N + 1, dtype=torch.int32, device="cuda") + o_cutedsl = torch.zeros(1, N, HV, V, dtype=torch.bfloat16, device="cuda") + + # Prepare tensors for multiple runs + q_list, k_list, v_list, a_list, b_list = [], [], [], [], [] + q_tensor_list, k_tensor_list, v_tensor_list, a_tensor_list, b_tensor_list = ( + [], + [], + [], + [], + [], + ) + q_triton, k_triton, v_triton, a_triton, b_triton = [], [], [], [], [] + + for ri in range(run_iters): + torch.manual_seed(2025 + ri) + q_i = torch.randn(1, N, H, K, dtype=torch.bfloat16, device="cuda") + k_i = torch.randn(1, N, H, K, dtype=torch.bfloat16, device="cuda") + v_i = torch.randn(1, N, HV, V, dtype=torch.bfloat16, device="cuda") + a_i = torch.randn(N, HV, dtype=torch.bfloat16, device="cuda") + b_i = torch.randn(N, HV, dtype=torch.bfloat16, device="cuda") + + q_list.append(q_i) + k_list.append(k_i) + v_list.append(v_i) + a_list.append(a_i) + b_list.append(b_i) + q_tensor_list.append(from_dlpack(q_i, assumed_align=16)) + k_tensor_list.append(from_dlpack(k_i, assumed_align=16)) + v_tensor_list.append(from_dlpack(v_i, assumed_align=16)) + a_tensor_list.append(from_dlpack(a_i, assumed_align=16)) + b_tensor_list.append(from_dlpack(b_i, assumed_align=16)) + q_triton.append(q_i.transpose(0, 1).contiguous()) + k_triton.append(k_i.transpose(0, 1).contiguous()) + v_triton.append(v_i.transpose(0, 1).contiguous()) + a_triton.append(a_i.unsqueeze(1).contiguous()) + b_triton.append(b_i.unsqueeze(1).contiguous()) + + A_log_t = from_dlpack(A_log, assumed_align=16) + dt_bias_t = from_dlpack(dt_bias, assumed_align=16) + h0_t = from_dlpack(state_cutedsl, assumed_align=16) + idx_t = from_dlpack(indices, assumed_align=16) + o_t = from_dlpack(o_cutedsl, assumed_align=16) + cu_t = from_dlpack(cu_seqlens, assumed_align=16) + + torch_stream = torch.cuda.Stream() + stream = cuda_driver.CUstream(torch_stream.cuda_stream) + + # Compile kernels + compiled = cutedsl_gdn._get_compiled_kernel(N, H, HV, K, V, N, N < 32, is_varlen) + torch.cuda.synchronize() + + for ri in range(run_iters): + _ = run_triton_kernel( + A_log, + dt_bias, + q_triton[ri], + k_triton[ri], + v_triton[ri], + a_triton[ri], + b_triton[ri], + state_triton, + indices, + scale, + ) + torch.cuda.synchronize() + + def run_cutedsl(): + for ri in range(run_iters): + compiled( + cu_t, + q_tensor_list[ri], + k_tensor_list[ri], + v_tensor_list[ri], + a_tensor_list[ri], + b_tensor_list[ri], + A_log_t, + dt_bias_t, + h0_t, + idx_t, + o_t, + stream, + ) + + def run_triton(): + for ri in range(run_iters): + _ = run_triton_kernel( + A_log, + dt_bias, + q_triton[ri], + k_triton[ri], + v_triton[ri], + a_triton[ri], + b_triton[ri], + state_triton, + indices, + scale, + ) + + # Warmup + with torch.cuda.stream(torch_stream): + run_cutedsl() + torch.cuda.synchronize() + run_triton() + torch.cuda.synchronize() + + # Capture CUDA graphs + graph_triton = torch.cuda.CUDAGraph() + graph_cutedsl = torch.cuda.CUDAGraph() + try: + with torch.cuda.graph(graph_triton): + run_triton() + with torch.cuda.graph(graph_cutedsl, stream=torch_stream): + run_cutedsl() + torch.cuda.synchronize() + except Exception: + graph_triton = graph_cutedsl = None + + # Warmup with graphs + for _ in range(warmup): + if graph_cutedsl: + graph_cutedsl.replay() + else: + with torch.cuda.stream(torch_stream): + run_cutedsl() + torch.cuda.synchronize() + + if graph_triton: + graph_triton.replay() + else: + run_triton() + torch.cuda.synchronize() + + # Benchmark + triton_times, cutedsl_times = [], [] + for _ in range(bench_iters): + start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event( + enable_timing=True + ) + start.record() + if graph_triton: + graph_triton.replay() + else: + run_triton() + end.record() + torch.cuda.synchronize() + triton_times.append(start.elapsed_time(end)) + + start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event( + enable_timing=True + ) + with torch.cuda.stream(torch_stream): + start.record() + if graph_cutedsl: + graph_cutedsl.replay() + else: + run_cutedsl() + end.record() + torch.cuda.synchronize() + cutedsl_times.append(start.elapsed_time(end)) + + triton_mean = np.mean(triton_times) / run_iters * 1000 + triton_std = np.std(triton_times) / run_iters * 1000 + cutedsl_mean = np.mean(cutedsl_times) / run_iters * 1000 + cutedsl_std = np.std(cutedsl_times) / run_iters * 1000 + speedup = triton_mean / cutedsl_mean + + kernel_type = "SmallBatch" if B < 32 else "LargeBatch" + print( + f"\n B={B} ({kernel_type}): Triton={triton_mean:.2f}±{triton_std:.2f}μs, CuTeDSL={cutedsl_mean:.2f}±{cutedsl_std:.2f}μs, speedup={speedup:.2f}x" + ) + + min_speedup = 1.0 if B < 32 else 1.15 + assert speedup >= min_speedup, f"Speedup {speedup:.2f}x < {min_speedup}x for B={B}" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_deepseek_v4_compress_state_runtime_shapes.py b/asian_ai/performance/SGLang/test/registered/jit/test_deepseek_v4_compress_state_runtime_shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..804e1dadb76af234ae4278c7867bd724e3650914 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_deepseek_v4_compress_state_runtime_shapes.py @@ -0,0 +1,1083 @@ +# DeepSeek V4 compress-state test and benchmark entry. +# +# What this covers: +# - Synthetic Flash/Pro C4/C128 decode/prefill shapes for broad operator +# performance coverage. +# - Replays 84 compress shapes captured from zc01 DeepSeek-V4-Flash serving. +# - The capture used EAGLE, so runtime compress plans were prefill-style plans +# for both EXTEND and TARGET_VERIFY. Some short C128 cases have out_shape=0. +# - This file keeps the out_shape=0 diff handling local to the runtime replay +# benchmark path. +# +# Test command: +# python3 -m pytest -q \ +# test/registered/jit/test_deepseek_v4_compress_state_runtime_shapes.py +# +# Runtime-shape benchmark command: +# python3 test/registered/jit/test_deepseek_v4_compress_state_runtime_shapes.py \ +# --benchmark \ +# --shape-source runtime \ +# --warmup 20 \ +# --iters 100 \ +# --csv /data00/eval_results/operator_bench/runtime_shape_bench.csv +# +# Synthetic Flash/Pro shape benchmark command: +# python3 test/registered/jit/test_deepseek_v4_compress_state_runtime_shapes.py \ +# --benchmark \ +# --shape-source preset \ +# --shape-presets all \ +# --shape-tier smoke \ +# --warmup 10 \ +# --iters 30 \ +# --csv /data00/eval_results/operator_bench/preset_shape_bench.csv +# +# Service-level scenario where BF16 state compression is more likely to help: +# - Disable speculative/EAGLE so the workload is not dominated by small +# TARGET_VERIFY shapes. +# - Prefer TP-only or DP=1 first; DP attention may reduce chunked prefill from +# 4096 to 512, which makes fixed kernel overhead dominate. +# - Use long random prompts and short outputs to make prefill dominate: +# SGLANG_DSV4_COMPRESS_STATE_DTYPE=bf16 \ +# SGLANG_SHARED_EXPERT_TP1=1 \ +# SGLANG_ENABLE_THINKING=1 \ +# SGLANG_DSV4_FP4_EXPERTS=1 \ +# SGLANG_JIT_DEEPGEMM_PRECOMPILE=1 \ +# sglang serve \ +# --trust-remote-code \ +# --model-path /data00/models/DeepSeek-V4-Flash \ +# --tp 8 \ +# --host 0.0.0.0 \ +# --port 8080 \ +# --mem-fraction-static 0.9 \ +# --moe-runner-backend marlin \ +# --chunked-prefill-size 4096 \ +# --max-prefill-tokens 16384 \ +# --max-running-requests 32 \ +# --cuda-graph-max-bs-decode 16 \ +# --enable-metrics \ +# --disable-radix-cache +# +# Workload for the service-level scenario: +# HF_ENDPOINT=https://hf-mirror.com \ +# python3 -m sglang.benchmark.serving \ +# --host localhost \ +# --port 8080 \ +# --model /data00/models/DeepSeek-V4-Flash \ +# --dataset-name random \ +# --random-input-len 8192 \ +# --random-output-len 8 \ +# --random-range-ratio 1 \ +# --num-prompts 128 \ +# --max-concurrency 16 \ +# --request-rate 16 +# +# Compare with the same service command without +# SGLANG_DSV4_COMPRESS_STATE_DTYPE=bf16. A visible service-level gain requires +# large prefill shapes and a non-trivial compress-kernel share in the profile. + +from __future__ import annotations + +import argparse +import csv +import math +import sys +from dataclasses import dataclass +from pathlib import Path +from types import SimpleNamespace +from typing import Callable, Iterable, Literal, Optional + +import pytest +import torch + +from sglang.jit_kernel.dsv4 import ( + CompressorDecodePlan, + CompressorPrefillPlan, + compress_forward, +) +from sglang.jit_kernel.tests.deepseek_v4.common import ( + make_legacy_context, + to_seq_extend, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.utils import is_in_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=25, suite="nightly-amd-kernel-1-gpu", nightly=True) + +Mode = Literal["decode", "prefill"] +ShapeTier = Literal["ci", "smoke", "full"] +MAX_PRESET_PREFILL_Q_TOKENS = 32768 + + +@dataclass(frozen=True) +class ShapePreset: + name: str + hidden_size: int + num_attention_heads: int + index_topk: int + ratios: tuple[Literal[4, 128], ...] + decode_batch_sizes: dict[ShapeTier, tuple[int, ...]] + prefill_batch_sizes: dict[ShapeTier, tuple[int, ...]] + decode_seq_lens: dict[ShapeTier, tuple[int, ...]] + prefill_extend_lens: dict[ShapeTier, dict[Literal[4, 128], tuple[int, ...]]] + + +SHAPE_PRESETS: dict[str, ShapePreset] = { + # DeepSeek-V4-Flash config on zc01: + # hidden_size=4096, num_attention_heads=64, index_topk=512, + # compress_ratios=[0, 0, 4, 128, ... alternating ..., 0]. + # The compress kernel itself uses head_dim=512 + # (= qk_nope_head_dim 448 + qk_rope_head_dim 64). + "flash": ShapePreset( + name="flash", + hidden_size=4096, + num_attention_heads=64, + index_topk=512, + ratios=(4, 128), + decode_batch_sizes={ + "ci": (16,), + "smoke": (16, 128), + "full": (1, 2, 4, 8, 16, 32, 64, 128), + }, + prefill_batch_sizes={ + "ci": (1,), + "smoke": (1, 16), + "full": (1, 2, 4, 8, 16, 32), + }, + decode_seq_lens={ + "ci": (128,), + "smoke": (128,), + "full": (128, 256, 4096), + }, + prefill_extend_lens={ + "ci": {4: (128,), 128: (128,)}, + "smoke": {4: (16, 128, 4096), 128: (128, 4096)}, + "full": {4: (16, 128, 4096), 128: (128, 4096)}, + }, + ), + # DeepSeek-V4-Pro config on zc01: + # hidden_size=7168, num_attention_heads=128, index_topk=1024, + # compress_ratios=[128, 128, 4, 128, ... alternating ..., 0]. + "pro": ShapePreset( + name="pro", + hidden_size=7168, + num_attention_heads=128, + index_topk=1024, + ratios=(4, 128), + decode_batch_sizes={ + "ci": (16,), + "smoke": (16, 32), + "full": (1, 2, 4, 8, 16, 32), + }, + prefill_batch_sizes={ + "ci": (1,), + "smoke": (1, 16), + "full": (1, 2, 4, 8, 16, 32), + }, + decode_seq_lens={ + "ci": (128,), + "smoke": (128,), + "full": (128, 256, 4096), + }, + prefill_extend_lens={ + "ci": {4: (128,), 128: (128,)}, + "smoke": {4: (16, 128, 4096), 128: (128, 4096)}, + "full": {4: (16, 128, 4096), 128: (128, 4096)}, + }, + ), +} + + +@dataclass(frozen=True) +class BenchSpec: + shape_name: str + ratio: Literal[4, 128] + mode: Mode + batch_size: int + head_dim: int + tokens_per_req: int + + +@dataclass +class BenchInput: + state_pool: torch.Tensor + kv_score_input: torch.Tensor + ape: torch.Tensor + out: torch.Tensor + plan: CompressorDecodePlan | CompressorPrefillPlan + spec: BenchSpec + + @property + def effective_bytes(self) -> int: + tensors = (self.state_pool, self.kv_score_input, self.ape, self.out) + return sum(t.numel() * t.element_size() for t in tensors) + + def run(self) -> torch.Tensor: + return compress_forward( + kv_score_buffer=self.state_pool, + kv_score_input=self.kv_score_input, + ape=self.ape, + plan=self.plan, + head_dim=self.spec.head_dim, + compress_ratio=self.spec.ratio, + out=self.out, + ) + + +@dataclass +class BenchResult: + shape_name: str + ratio: int + mode: str + batch_size: int + tokens_per_req: int + head_dim: int + state_shape: str + input_shape: str + ape_shape: str + out_shape: str + fp32_state_mib: float + bf16_state_mib: float + input_mib: float + ape_mib: float + out_mib: float + fp32_effective_mib: float + bf16_effective_mib: float + fp32_us: float + fp32_gbps: float + bf16_us: float + bf16_gbps: float + out_diff: float + state_diff: float + + @property + def speedup(self) -> float: + return self.fp32_us / self.bf16_us + + +def _last_dim(ratio: int, head_dim: int) -> int: + return head_dim * (4 if ratio == 4 else 2) + + +def _ape_len(ratio: int) -> int: + return 8 if ratio == 4 else 128 + + +def _shape_str(tensor: torch.Tensor) -> str: + return "x".join(str(dim) for dim in tensor.shape) + + +def _mib(num_bytes: int) -> float: + return num_bytes / 1024 / 1024 + + +def _tensor_mib(tensor: torch.Tensor) -> float: + return _mib(tensor.numel() * tensor.element_size()) + + +def _make_plan(spec: BenchSpec): + ctx = make_legacy_context( + bs=spec.batch_size, + compress_ratio=spec.ratio, + head_dim=spec.head_dim, + ) + if spec.mode == "decode": + seq_lens = torch.full( + (spec.batch_size,), + spec.tokens_per_req, + dtype=torch.int64, + device="cuda", + ) + plan = ctx.make_decode_plan(seq_lens) + num_output_tokens = spec.batch_size + else: + seq_lens_cpu, extend_lens_cpu, num_q_tokens = to_seq_extend( + [(spec.tokens_per_req, spec.tokens_per_req)] * spec.batch_size + ) + plan = ctx.make_prefill_plan(seq_lens_cpu, extend_lens_cpu, num_q_tokens) + num_output_tokens = int(plan.plan_c.shape[0]) + return ctx, plan, num_output_tokens + + +def _make_bench_input( + spec: BenchSpec, + state_dtype: torch.dtype, + base_state: torch.Tensor, + base_input: torch.Tensor, + base_ape: torch.Tensor, + plan: CompressorDecodePlan | CompressorPrefillPlan, + num_q_tokens: int, +) -> BenchInput: + state_pool = base_state.to(state_dtype) + kv_score_input = base_input.clone() + ape = base_ape.clone() + out = torch.empty( + (num_q_tokens, spec.head_dim), + dtype=kv_score_input.dtype, + device=kv_score_input.device, + ) + return BenchInput( + state_pool=state_pool, + kv_score_input=kv_score_input, + ape=ape, + out=out, + plan=plan, + spec=spec, + ) + + +def _make_pair(spec: BenchSpec, seed: int) -> tuple[BenchInput, BenchInput]: + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + ctx, plan, num_q_tokens = _make_plan(spec) + last_dim = _last_dim(spec.ratio, spec.head_dim) + + if spec.mode == "decode": + base_state = torch.randn( + (ctx.num_pages, spec.ratio, last_dim), + dtype=torch.float32, + device="cuda", + ) + input_rows = spec.batch_size + else: + base_state = torch.zeros( + (ctx.num_pages, spec.ratio, last_dim), + dtype=torch.float32, + device="cuda", + ) + input_rows = spec.batch_size * spec.tokens_per_req + + base_input = torch.randn( + (input_rows, last_dim), + dtype=torch.float32, + device="cuda", + ) + base_ape = torch.randn( + (_ape_len(spec.ratio), spec.head_dim), + dtype=torch.float32, + device="cuda", + ) + + return ( + _make_bench_input( + spec, torch.float32, base_state, base_input, base_ape, plan, num_q_tokens + ), + _make_bench_input( + spec, torch.bfloat16, base_state, base_input, base_ape, plan, num_q_tokens + ), + ) + + +def _time_us(fn: Callable[[], torch.Tensor], warmup: int, iters: int) -> float: + for _ in range(warmup): + fn() + torch.cuda.synchronize() + + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + start.record() + for _ in range(iters): + fn() + end.record() + torch.cuda.synchronize() + return start.elapsed_time(end) * 1000.0 / iters + + +def _gbps(effective_bytes: int, elapsed_us: float) -> float: + return effective_bytes / (elapsed_us * 1e-6) / 1e9 + + +def _benchmark_spec( + spec: BenchSpec, + warmup: int, + iters: int, + seed: int, +) -> BenchResult: + fp32_case, bf16_case = _make_pair(spec, seed) + fp32_case.run() + bf16_case.run() + torch.cuda.synchronize() + + fp32_us = _time_us(fp32_case.run, warmup=warmup, iters=iters) + bf16_us = _time_us(bf16_case.run, warmup=warmup, iters=iters) + + # Recreate once for diff so the timed loop's repeated in-place state writes + # do not affect the comparison. + fp32_diff_case, bf16_diff_case = _make_pair(spec, seed) + fp32_out = fp32_diff_case.run() + bf16_out = bf16_diff_case.run() + torch.cuda.synchronize() + + out_diff = (fp32_out.float() - bf16_out.float()).abs().max().item() + state_diff = ( + (fp32_diff_case.state_pool.float() - bf16_diff_case.state_pool.float()) + .abs() + .max() + .item() + ) + + return BenchResult( + shape_name=spec.shape_name, + ratio=spec.ratio, + mode=spec.mode, + batch_size=spec.batch_size, + tokens_per_req=spec.tokens_per_req, + head_dim=spec.head_dim, + state_shape=_shape_str(fp32_case.state_pool), + input_shape=_shape_str(fp32_case.kv_score_input), + ape_shape=_shape_str(fp32_case.ape), + out_shape=_shape_str(fp32_case.out), + fp32_state_mib=_tensor_mib(fp32_case.state_pool), + bf16_state_mib=_tensor_mib(bf16_case.state_pool), + input_mib=_tensor_mib(fp32_case.kv_score_input), + ape_mib=_tensor_mib(fp32_case.ape), + out_mib=_tensor_mib(fp32_case.out), + fp32_effective_mib=_mib(fp32_case.effective_bytes), + bf16_effective_mib=_mib(bf16_case.effective_bytes), + fp32_us=fp32_us, + fp32_gbps=_gbps(fp32_case.effective_bytes, fp32_us), + bf16_us=bf16_us, + bf16_gbps=_gbps(bf16_case.effective_bytes, bf16_us), + out_diff=out_diff, + state_diff=state_diff, + ) + + +def _expand_shape_names(shape_presets: list[str]) -> list[str]: + if "all" in shape_presets: + return ["flash", "pro"] + if "custom" in shape_presets and len(shape_presets) > 1: + raise ValueError("--shape-presets custom cannot be mixed with shape presets.") + return shape_presets + + +def _one_or_many( + value: Optional[list[int]], fallback: tuple[int, ...] +) -> tuple[int, ...]: + return tuple(value) if value is not None else fallback + + +def _validate_tokens(mode: Mode, ratio: int, tokens_per_req: int) -> None: + if tokens_per_req % ratio != 0: + raise ValueError( + f"{mode} tokens_per_req={tokens_per_req} must be a multiple " + f"of ratio={ratio}" + ) + + +def _make_shape_specs(args: argparse.Namespace) -> Iterable[BenchSpec]: + shape_names = _expand_shape_names(args.shape_presets) + for shape_name in shape_names: + if shape_name == "custom": + yield from _make_custom_specs(args) + continue + + preset = SHAPE_PRESETS[shape_name] + ratios = tuple(args.ratios) if args.ratios is not None else preset.ratios + modes = tuple(args.modes) if args.modes is not None else ("decode", "prefill") + decode_batch_sizes = _one_or_many( + args.decode_batch_sizes or args.batch_sizes, + preset.decode_batch_sizes[args.shape_tier], + ) + prefill_batch_sizes = _one_or_many( + args.prefill_batch_sizes or args.batch_sizes, + preset.prefill_batch_sizes[args.shape_tier], + ) + decode_seq_lens = _one_or_many( + args.decode_seq_lens, + preset.decode_seq_lens[args.shape_tier], + ) + + for ratio in ratios: + if ratio not in preset.ratios: + continue + if "decode" in modes: + for tokens_per_req in decode_seq_lens: + _validate_tokens("decode", ratio, tokens_per_req) + for batch_size in decode_batch_sizes: + yield BenchSpec( + shape_name=shape_name, + ratio=ratio, + mode="decode", + batch_size=batch_size, + head_dim=args.head_dim, + tokens_per_req=tokens_per_req, + ) + + if "prefill" in modes: + prefill_extend_lens = _one_or_many( + args.prefill_extend_lens, + preset.prefill_extend_lens[args.shape_tier][ratio], + ) + for tokens_per_req in prefill_extend_lens: + _validate_tokens("prefill", ratio, tokens_per_req) + for batch_size in prefill_batch_sizes: + # The legacy prefill planner rejects very large + # synthetic q-token grids. Keep long-prefill coverage, + # but do not form unsupported cross-product cases. + if batch_size * tokens_per_req > MAX_PRESET_PREFILL_Q_TOKENS: + continue + yield BenchSpec( + shape_name=shape_name, + ratio=ratio, + mode="prefill", + batch_size=batch_size, + head_dim=args.head_dim, + tokens_per_req=tokens_per_req, + ) + + +def _make_custom_specs(args: argparse.Namespace) -> Iterable[BenchSpec]: + ratios = tuple(args.ratios) if args.ratios is not None else (4, 128) + modes = tuple(args.modes) if args.modes is not None else ("decode", "prefill") + batch_sizes = tuple(args.batch_sizes or [16, 32, 64, 128, 256]) + decode_seq_lens = tuple(args.decode_seq_lens or [128]) + prefill_extend_lens = tuple(args.prefill_extend_lens or [128]) + + for ratio in ratios: + for mode in modes: + seq_lens = decode_seq_lens if mode == "decode" else prefill_extend_lens + for tokens_per_req in seq_lens: + _validate_tokens(mode, ratio, tokens_per_req) + for batch_size in batch_sizes: + yield BenchSpec( + shape_name="custom", + ratio=ratio, + mode=mode, + batch_size=batch_size, + head_dim=args.head_dim, + tokens_per_req=tokens_per_req, + ) + + +def _format_table(results: list[BenchResult]) -> str: + if not results: + return "No benchmark cases selected." + + headers = [ + "shape", + "ratio", + "mode", + "bs", + "tok/req", + "head", + "state", + "input", + "ape", + "out", + "state MiB", + "input MiB", + "ape MiB", + "out MiB", + "FP32 MiB", + "BF16 MiB", + "FP32 us", + "FP32 GB/s", + "BF16 us", + "BF16 GB/s", + "out diff", + "state diff", + "Speedup", + ] + rows = [ + [ + r.shape_name, + str(r.ratio), + r.mode, + str(r.batch_size), + str(r.tokens_per_req), + str(r.head_dim), + r.state_shape, + r.input_shape, + r.ape_shape, + r.out_shape, + f"{r.fp32_state_mib:.2f}/{r.bf16_state_mib:.2f}", + f"{r.input_mib:.2f}", + f"{r.ape_mib:.3f}", + f"{r.out_mib:.2f}", + f"{r.fp32_effective_mib:.2f}", + f"{r.bf16_effective_mib:.2f}", + f"{r.fp32_us:.2f}", + f"{r.fp32_gbps:.1f}", + f"{r.bf16_us:.2f}", + f"{r.bf16_gbps:.1f}", + f"{r.out_diff:.4g}", + f"{r.state_diff:.4g}", + f"{r.speedup:.2f}x", + ] + for r in results + ] + widths = [ + max(len(headers[i]), *(len(row[i]) for row in rows)) + for i in range(len(headers)) + ] + line = " ".join(headers[i].rjust(widths[i]) for i in range(len(headers))) + sep = " ".join("-" * widths[i] for i in range(len(headers))) + body = [ + " ".join(row[i].rjust(widths[i]) for i in range(len(headers))) for row in rows + ] + return "\n".join([line, sep, *body]) + + +def _write_csv(path: Path, results: list[BenchResult]) -> None: + with path.open("w", newline="") as f: + writer = csv.DictWriter( + f, + fieldnames=[ + "ratio", + "shape", + "mode", + "batch_size", + "tokens_per_req", + "head_dim", + "state_shape", + "input_shape", + "ape_shape", + "out_shape", + "fp32_state_mib", + "bf16_state_mib", + "input_mib", + "ape_mib", + "out_mib", + "fp32_effective_mib", + "bf16_effective_mib", + "fp32_us", + "fp32_gbps", + "bf16_us", + "bf16_gbps", + "out_diff", + "state_diff", + "speedup", + ], + ) + writer.writeheader() + for r in results: + writer.writerow( + { + "ratio": r.ratio, + "shape": r.shape_name, + "mode": r.mode, + "batch_size": r.batch_size, + "tokens_per_req": r.tokens_per_req, + "head_dim": r.head_dim, + "state_shape": r.state_shape, + "input_shape": r.input_shape, + "ape_shape": r.ape_shape, + "out_shape": r.out_shape, + "fp32_state_mib": r.fp32_state_mib, + "bf16_state_mib": r.bf16_state_mib, + "input_mib": r.input_mib, + "ape_mib": r.ape_mib, + "out_mib": r.out_mib, + "fp32_effective_mib": r.fp32_effective_mib, + "bf16_effective_mib": r.bf16_effective_mib, + "fp32_us": r.fp32_us, + "fp32_gbps": r.fp32_gbps, + "bf16_us": r.bf16_us, + "bf16_gbps": r.bf16_gbps, + "out_diff": r.out_diff, + "state_diff": r.state_diff, + "speedup": r.speedup, + } + ) + + +def _preset_args(**overrides): + args = dict( + shape_presets=["all"], + model_shapes=None, + shape_tier="ci", + ratios=None, + modes=None, + batch_sizes=None, + decode_batch_sizes=None, + prefill_batch_sizes=None, + decode_seq_lens=None, + prefill_extend_lens=None, + head_dim=512, + ) + args.update(overrides) + return SimpleNamespace(**args) + + +def test_flash_pro_shape_presets_cover_compress_paths() -> None: + specs = list(_make_shape_specs(_preset_args())) + keys = { + (s.shape_name, s.ratio, s.mode, s.batch_size, s.tokens_per_req) for s in specs + } + + for shape_name in ("flash", "pro"): + assert (shape_name, 4, "decode", 16, 128) in keys + assert (shape_name, 4, "prefill", 1, 128) in keys + assert (shape_name, 128, "decode", 16, 128) in keys + assert (shape_name, 128, "prefill", 1, 128) in keys + + assert all(s.head_dim == 512 for s in specs) + assert all(s.tokens_per_req % s.ratio == 0 for s in specs) + + +@pytest.mark.parametrize( + "spec", + [ + BenchSpec("flash", 4, "decode", 2, 512, 128), + BenchSpec("flash", 4, "prefill", 1, 512, 16), + BenchSpec("pro", 128, "decode", 2, 512, 128), + BenchSpec("pro", 128, "prefill", 1, 512, 128), + ], +) +def test_compress_state_benchmark_cuda_smoke(spec: BenchSpec) -> None: + if not torch.cuda.is_available(): + pytest.skip("CUDA is required for DeepSeek V4 compress benchmark smoke.") + + result = _benchmark_spec(spec, warmup=1, iters=1, seed=20260603) + assert math.isfinite(result.fp32_us) and result.fp32_us > 0 + assert math.isfinite(result.bf16_us) and result.bf16_us > 0 + assert result.out_diff < 0.1 + assert result.state_diff < 0.1 + + +# Captured from DeepSeek-V4-Flash runtime on zc01 with EAGLE enabled: +# /data00/eval_results/operator_bench/runtime_shape_20260603/shapes.jsonl +# The service used prefill-style compress plans for both EXTEND and TARGET_VERIFY. +CAPTURED_FLASH_RUNTIME_SPECS = [ + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 1), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 6), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 28), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 29), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 30), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 284), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 285), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 286), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 287), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 288), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 289), + BenchSpec("flash-runtime-indexer", 4, "prefill", 1, 128, 512), + BenchSpec("flash-runtime-indexer", 4, "prefill", 2, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 2, 128, 142), + BenchSpec("flash-runtime-indexer", 4, "prefill", 2, 128, 143), + BenchSpec("flash-runtime-indexer", 4, "prefill", 2, 128, 144), + BenchSpec("flash-runtime-indexer", 4, "prefill", 2, 128, 145), + BenchSpec("flash-runtime-indexer", 4, "prefill", 3, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 4, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 5, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 6, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 7, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 8, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 10, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 12, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 14, 128, 4), + BenchSpec("flash-runtime-indexer", 4, "prefill", 16, 128, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 1), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 6), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 28), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 29), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 30), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 284), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 285), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 286), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 287), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 288), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 289), + BenchSpec("flash-runtime-core", 4, "prefill", 1, 512, 512), + BenchSpec("flash-runtime-core", 4, "prefill", 2, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 2, 512, 142), + BenchSpec("flash-runtime-core", 4, "prefill", 2, 512, 143), + BenchSpec("flash-runtime-core", 4, "prefill", 2, 512, 144), + BenchSpec("flash-runtime-core", 4, "prefill", 2, 512, 145), + BenchSpec("flash-runtime-core", 4, "prefill", 3, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 4, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 5, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 6, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 7, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 8, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 10, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 12, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 14, 512, 4), + BenchSpec("flash-runtime-core", 4, "prefill", 16, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 1), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 6), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 28), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 29), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 30), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 284), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 285), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 286), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 287), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 288), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 289), + BenchSpec("flash-runtime-core", 128, "prefill", 1, 512, 512), + BenchSpec("flash-runtime-core", 128, "prefill", 2, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 2, 512, 142), + BenchSpec("flash-runtime-core", 128, "prefill", 2, 512, 143), + BenchSpec("flash-runtime-core", 128, "prefill", 2, 512, 144), + BenchSpec("flash-runtime-core", 128, "prefill", 2, 512, 145), + BenchSpec("flash-runtime-core", 128, "prefill", 3, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 4, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 5, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 6, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 7, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 8, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 10, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 12, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 14, 512, 4), + BenchSpec("flash-runtime-core", 128, "prefill", 16, 512, 4), +] + + +def _max_abs_diff(lhs: torch.Tensor, rhs: torch.Tensor) -> float: + if lhs.numel() == 0: + return 0.0 + return (lhs.float() - rhs.float()).abs().max().item() + + +def _benchmark_runtime_spec( + spec: BenchSpec, + warmup: int, + iters: int, + seed: int, +) -> BenchResult: + fp32_case, bf16_case = _make_pair(spec, seed) + fp32_case.run() + bf16_case.run() + torch.cuda.synchronize() + + fp32_us = _time_us(fp32_case.run, warmup=warmup, iters=iters) + bf16_us = _time_us(bf16_case.run, warmup=warmup, iters=iters) + + fp32_diff_case, bf16_diff_case = _make_pair(spec, seed) + fp32_out = fp32_diff_case.run() + bf16_out = bf16_diff_case.run() + torch.cuda.synchronize() + + out_diff = _max_abs_diff(fp32_out, bf16_out) + state_diff = _max_abs_diff( + fp32_diff_case.state_pool, + bf16_diff_case.state_pool, + ) + + return BenchResult( + shape_name=spec.shape_name, + ratio=spec.ratio, + mode=spec.mode, + batch_size=spec.batch_size, + tokens_per_req=spec.tokens_per_req, + head_dim=spec.head_dim, + state_shape=_shape_str(fp32_case.state_pool), + input_shape=_shape_str(fp32_case.kv_score_input), + ape_shape=_shape_str(fp32_case.ape), + out_shape=_shape_str(fp32_case.out), + fp32_state_mib=_tensor_mib(fp32_case.state_pool), + bf16_state_mib=_tensor_mib(bf16_case.state_pool), + input_mib=_tensor_mib(fp32_case.kv_score_input), + ape_mib=_tensor_mib(fp32_case.ape), + out_mib=_tensor_mib(fp32_case.out), + fp32_effective_mib=_mib(fp32_case.effective_bytes), + bf16_effective_mib=_mib(bf16_case.effective_bytes), + fp32_us=fp32_us, + fp32_gbps=_gbps(fp32_case.effective_bytes, fp32_us), + bf16_us=bf16_us, + bf16_gbps=_gbps(bf16_case.effective_bytes, bf16_us), + out_diff=out_diff, + state_diff=state_diff, + ) + + +def test_captured_flash_runtime_specs_are_unique() -> None: + keys = { + (s.shape_name, s.ratio, s.mode, s.batch_size, s.head_dim, s.tokens_per_req) + for s in CAPTURED_FLASH_RUNTIME_SPECS + } + assert len(keys) == len(CAPTURED_FLASH_RUNTIME_SPECS) + assert len(CAPTURED_FLASH_RUNTIME_SPECS) == 84 + assert any(s.head_dim == 128 and s.ratio == 4 for s in CAPTURED_FLASH_RUNTIME_SPECS) + assert any(s.head_dim == 512 and s.ratio == 4 for s in CAPTURED_FLASH_RUNTIME_SPECS) + assert any( + s.head_dim == 512 and s.ratio == 128 for s in CAPTURED_FLASH_RUNTIME_SPECS + ) + + +@pytest.mark.parametrize("spec", CAPTURED_FLASH_RUNTIME_SPECS) +def test_compress_state_runtime_shape_cuda_smoke(spec: BenchSpec) -> None: + if not torch.cuda.is_available(): + pytest.skip("CUDA is required for DeepSeek V4 runtime compress shape smoke.") + + result = _benchmark_runtime_spec(spec, warmup=1, iters=1, seed=20260603) + assert math.isfinite(result.fp32_us) and result.fp32_us > 0 + assert math.isfinite(result.bf16_us) and result.bf16_us > 0 + assert result.out_diff < 0.1 + assert result.state_diff < 0.1 + + +def _run_benchmark(args: argparse.Namespace) -> int: + ci = is_in_ci() + args.warmup = args.warmup if args.warmup is not None else (5 if ci else 10) + args.iters = args.iters if args.iters is not None else (20 if ci else 30) + + if not torch.cuda.is_available(): + print("[skip] CUDA is required for this benchmark.") + return 0 + if args.head_dim % 128 != 0: + raise ValueError("--head-dim must be a multiple of 128.") + + print("DeepSeek V4 compress state dtype benchmark") + print( + "effective GB/s = " + "state_pool + kv_score_input + ape + output footprint / kernel time" + ) + + if args.shape_source == "runtime": + specs = CAPTURED_FLASH_RUNTIME_SPECS + if args.limit is not None: + specs = specs[: args.limit] + print( + f"config: shape_source=runtime, cases={len(specs)}, " + f"warmup={args.warmup}, iters={args.iters}" + ) + results = [ + _benchmark_runtime_spec( + spec, + warmup=args.warmup, + iters=args.iters, + seed=args.seed, + ) + for spec in specs + ] + else: + args.shape_presets = args.shape_presets or args.model_shapes or ["all"] + args.shape_tier = args.shape_tier or ("ci" if ci else "smoke") + if args.decode_seq_len is not None: + args.decode_seq_lens = [args.decode_seq_len] + if args.prefill_extend_len is not None: + args.prefill_extend_lens = [args.prefill_extend_len] + + specs = list(_make_shape_specs(args)) + if args.limit is not None: + specs = specs[: args.limit] + print( + f"config: shape_source=preset, shape_presets={args.shape_presets}, " + f"shape_tier={args.shape_tier}, ratios={args.ratios}, " + f"modes={args.modes}, batch_sizes={args.batch_sizes}, " + f"decode_batch_sizes={args.decode_batch_sizes}, " + f"prefill_batch_sizes={args.prefill_batch_sizes}, " + f"head_dim={args.head_dim}, decode_seq_lens={args.decode_seq_lens}, " + f"prefill_extend_lens={args.prefill_extend_lens}, " + f"cases={len(specs)}, warmup={args.warmup}, iters={args.iters}" + ) + results = [ + _benchmark_spec( + spec, + warmup=args.warmup, + iters=args.iters, + seed=args.seed, + ) + for spec in specs + ] + + print(_format_table(results)) + if args.csv: + _write_csv(args.csv, results) + print(f"\nWrote CSV: {args.csv}") + return 0 + + +def _parse_args(argv: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Run DeepSeek V4 compress state tests, runtime-shape replay benchmark, " + "or synthetic Flash/Pro shape benchmark." + ) + ) + parser.add_argument("--benchmark", action="store_true") + parser.add_argument( + "--shape-source", + choices=("runtime", "preset"), + default="runtime", + help=( + "runtime replays captured serving shapes; preset runs synthetic " + "Flash/Pro/custom shape grids." + ), + ) + parser.add_argument( + "--shape-presets", + nargs="+", + choices=("flash", "pro", "all", "custom"), + default=None, + help=( + "Preset shapes for --shape-source preset. 'all' covers Flash and Pro. " + "Use 'custom' with manual shape args." + ), + ) + parser.add_argument( + "--model-shapes", + nargs="+", + choices=("flash", "pro", "all", "custom"), + default=None, + help=argparse.SUPPRESS, + ) + parser.add_argument( + "--shape-tier", + choices=("ci", "smoke", "full"), + default=None, + help=( + "Shape grid size for preset shapes. Defaults to ci in CI and smoke " + "otherwise." + ), + ) + parser.add_argument("--ratios", type=int, nargs="+", choices=(4, 128), default=None) + parser.add_argument( + "--modes", + nargs="+", + choices=("decode", "prefill"), + default=None, + ) + parser.add_argument("--batch-sizes", type=int, nargs="+", default=None) + parser.add_argument("--decode-batch-sizes", type=int, nargs="+", default=None) + parser.add_argument("--prefill-batch-sizes", type=int, nargs="+", default=None) + parser.add_argument("--head-dim", type=int, default=512) + parser.add_argument( + "--decode-seq-lens", + type=int, + nargs="+", + default=None, + help="Decode seq_len values. Overrides preset decode seq_len grid.", + ) + parser.add_argument( + "--prefill-extend-lens", + type=int, + nargs="+", + default=None, + help="Prefill extend_len values. Overrides preset prefill extend_len grid.", + ) + parser.add_argument( + "--decode-seq-len", + type=int, + default=None, + help=argparse.SUPPRESS, + ) + parser.add_argument( + "--prefill-extend-len", + type=int, + default=None, + help=argparse.SUPPRESS, + ) + parser.add_argument("--warmup", type=int, default=None) + parser.add_argument("--iters", type=int, default=None) + parser.add_argument("--seed", type=int, default=20260603) + parser.add_argument( + "--limit", + type=int, + default=None, + help="Limit benchmark cases after shape expansion.", + ) + parser.add_argument("--csv", type=Path, default=None) + return parser.parse_args(argv) + + +if __name__ == "__main__": + if "--benchmark" in sys.argv: + sys.exit(_run_benchmark(_parse_args(sys.argv[1:]))) + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_dsv32_indexer_fusion.py b/asian_ai/performance/SGLang/test/registered/jit/test_dsv32_indexer_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..cb8c7e6220a19a79ea765d7c243fbd0ddf50c1ba --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_dsv32_indexer_fusion.py @@ -0,0 +1,269 @@ +"""Correctness tests for the DeepSeek-V3.2 DSA indexer fused kernels. + +Covers: + - fused_q_indexer_rope_first_quant (Q: rope-first + fp8 quant + head-gate fold) + - fused_k_indexer_norm_rope (K: LayerNorm + rope-first -> bf16) + - fused_k_indexer_norm_rope_store (K: the above + fp8 quant + paged index-k cache write) + +The store kernel is checked for byte-exact equivalence against the un-fused path +(bf16 K kernel + standalone fused_store_index_k_cache), so it needs no fp8 +reference. The Q/K math kernels are checked against torch references. Strided +inputs (the non-contiguous wk_weights_proj slices) are checked to match +contiguous inputs (the no-copy path). +""" + +from __future__ import annotations + +import pytest +import torch + +from sglang.jit_kernel.dsv4 import fused_q_indexer_rope_first_quant +from sglang.jit_kernel.dsv32 import ( + fused_k_indexer_norm_rope, + fused_k_indexer_norm_rope_store, +) +from sglang.jit_kernel.fused_store_index_cache import ( + can_use_dsa_fused_store, + fused_store_index_k_cache, +) +from sglang.srt.utils import is_hip +from sglang.test.ci.ci_register import register_cuda_ci + +_is_hip = is_hip() + +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=90, suite="nightly-kernel-1-gpu", nightly=True) + +HEAD_DIM = 128 +ROPE_DIM = 64 +HALF = ROPE_DIM // 2 +FP8_MAX = 448.0 +PAGE_SIZE = 64 +BYTES_PER_TOKEN = HEAD_DIM + 4 # 128 fp8 + 4-byte fp32 scale +EPS = 1e-6 +MAX_POS = 8192 + + +def _skip_if_unavailable(): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + if _is_hip: + pytest.skip("Indexer fused kernels are CUDA-specific") + + +def _make_inputs(B, seed=0, pos_dtype=torch.int32): + g = torch.Generator(device="cuda").manual_seed(seed) + dev = "cuda" + cos = torch.randn(MAX_POS, HALF, device=dev, generator=g) + sin = torch.randn(MAX_POS, HALF, device=dev, generator=g) + cos_sin_cache = torch.cat((cos, sin), dim=-1) + positions = torch.randint(0, 4096, (B,), device=dev, dtype=pos_dtype, generator=g) + return cos, sin, cos_sin_cache, positions + + +def _rope_first(x, cos_p, sin_p): + """Interleaved complex rope on the leading ROPE_DIM dims (kRopeFirst).""" + x = x.clone() + xr = x[..., 0:ROPE_DIM:2].clone() + xi = x[..., 1:ROPE_DIM:2].clone() + x[..., 0:ROPE_DIM:2] = xr * cos_p - xi * sin_p + x[..., 1:ROPE_DIM:2] = xr * sin_p + xi * cos_p + return x + + +# ---------------------------------------------------------------------------- +# K kernel (-> bf16): LayerNorm + rope-first +# ---------------------------------------------------------------------------- +def test_k_norm_rope_matches_reference(): + _skip_if_unavailable() + dev = "cuda" + B = 37 + cos, sin, cos_sin_cache, positions = _make_inputs(B) + key = torch.randn(B, HEAD_DIM, dtype=torch.bfloat16, device=dev) + weight = torch.randn(HEAD_DIM, dtype=torch.float32, device=dev) + bias = torch.randn(HEAD_DIM, dtype=torch.float32, device=dev) + + out = fused_k_indexer_norm_rope(key, weight, bias, EPS, cos_sin_cache, positions) + torch.cuda.synchronize() + + normed = torch.nn.functional.layer_norm( + key.float(), (HEAD_DIM,), weight=weight, bias=bias, eps=EPS + ) + cp, sp = cos[positions.long()], sin[positions.long()] + ref = _rope_first(normed, cp, sp) + + torch.testing.assert_close(out.float(), ref, atol=0.06, rtol=0.0) + + +# ---------------------------------------------------------------------------- +# K kernel + fused store == bf16 K kernel + standalone store (byte-exact). +# Also covers the strided (non-contiguous wk slice) no-copy input path. +# ---------------------------------------------------------------------------- +@pytest.mark.parametrize("strided", [False, True]) +def test_k_store_matches_unfused(strided): + _skip_if_unavailable() + if not can_use_dsa_fused_store(torch.bfloat16, torch.int64, PAGE_SIZE): + pytest.skip("fused store JIT unavailable") + dev = "cuda" + B, n_heads = 41, 64 + cos, sin, cos_sin_cache, positions = _make_inputs(B) + weight = torch.randn(HEAD_DIM, dtype=torch.float32, device=dev) + bias = torch.randn(HEAD_DIM, dtype=torch.float32, device=dev) + + if strided: + # Mimic the fused wk_weights_proj GEMM output: key is kw[:, :head_dim]. + kw = torch.randn(B, HEAD_DIM + n_heads, dtype=torch.bfloat16, device=dev) + key = kw[:, :HEAD_DIM] + assert not key.is_contiguous() + else: + key = torch.randn(B, HEAD_DIM, dtype=torch.bfloat16, device=dev) + + loc = torch.randperm(B * 4, device=dev)[:B].to(torch.int64) + num_pages = int(loc.max().item()) // PAGE_SIZE + 2 + buf_ref = torch.zeros( + num_pages, BYTES_PER_TOKEN * PAGE_SIZE, dtype=torch.uint8, device=dev + ) + buf_fused = torch.zeros_like(buf_ref) + + key_bf16 = fused_k_indexer_norm_rope( + key, weight, bias, EPS, cos_sin_cache, positions + ) + fused_store_index_k_cache(key_bf16, buf_ref, loc, PAGE_SIZE) + + fused_k_indexer_norm_rope_store( + key, buf_fused, loc, weight, bias, EPS, cos_sin_cache, positions, PAGE_SIZE + ) + torch.cuda.synchronize() + + assert torch.equal(buf_ref, buf_fused) + + +# ---------------------------------------------------------------------------- +# Q kernel: rope-first + fp8 quant + head-gate fold +# ---------------------------------------------------------------------------- +@pytest.mark.parametrize("pos_dtype", [torch.int32, torch.int64]) +def test_q_rope_quant_matches_reference(pos_dtype): + _skip_if_unavailable() + dev = "cuda" + B, n_heads = 37, 64 + cos, sin, cos_sin_cache, positions = _make_inputs(B, pos_dtype=pos_dtype) + q = torch.randn(B, n_heads, HEAD_DIM, dtype=torch.bfloat16, device=dev) + weight = torch.randn(B, n_heads, dtype=torch.bfloat16, device=dev) + weight_scale = 0.137 + + q_fp8, weights_out = fused_q_indexer_rope_first_quant( + q, weight, weight_scale, cos_sin_cache, positions + ) + torch.cuda.synchronize() + + cp = cos[positions.long()][:, None, :] + sp = sin[positions.long()][:, None, :] + ref = _rope_first(q.float(), cp, sp) # [B, n_heads, 128] + amax = ref.abs().amax(dim=-1, keepdim=True) + scale = torch.clamp(amax, min=1e-4) / FP8_MAX + + # weights_out[b,h] = weight * weight_scale * scale + w_ref = weight.float() * weight_scale * scale.squeeze(-1) + torch.testing.assert_close(weights_out.squeeze(-1), w_ref, atol=1e-3, rtol=1e-3) + + # dequantized q should match the rope result within fp8-e4m3 precision: + # round-to-nearest with 3 mantissa bits => <= 1/16 relative error, plus one + # scale step at the bottom of the range. + deq = q_fp8.float() * scale + err = (deq - ref).abs() + assert ( + err <= 0.0625 * ref.abs() + scale + ).all(), f"max fp8 dequant error {err.max().item()}" + + +# ---------------------------------------------------------------------------- +# Strided weight (the wk_weights_proj slice) matches contiguous for the Q kernel +# ---------------------------------------------------------------------------- +def test_q_strided_weight_matches_contiguous(): + _skip_if_unavailable() + dev = "cuda" + B, n_heads = 29, 64 + cos, sin, cos_sin_cache, positions = _make_inputs(B) + q = torch.randn(B, n_heads, HEAD_DIM, dtype=torch.bfloat16, device=dev) + # weights_raw = kw[:, head_dim:] is a non-contiguous slice. + kw = torch.randn(B, HEAD_DIM + n_heads, dtype=torch.bfloat16, device=dev) + w_strided = kw[:, HEAD_DIM:] + w_contig = w_strided.contiguous() + assert not w_strided.is_contiguous() + + a_fp8, a_w = fused_q_indexer_rope_first_quant( + q, w_strided, 0.137, cos_sin_cache, positions + ) + b_fp8, b_w = fused_q_indexer_rope_first_quant( + q, w_contig, 0.137, cos_sin_cache, positions + ) + torch.cuda.synchronize() + assert torch.equal(a_fp8, b_fp8) + assert torch.equal(a_w, b_w) + + +def test_indexer_uses_replaced_rope_cache_for_fused_kernels(): + _skip_if_unavailable() + from sglang.srt.layers.attention.dsa.dsa_indexer import Indexer + + dev = "cuda" + B, n_heads = 7, 64 + old_len = 16 + new_len = 128 + g = torch.Generator(device=dev).manual_seed(123) + old_cache = torch.randn(old_len, ROPE_DIM, dtype=torch.float32, device=dev) + cos = torch.randn(new_len, HALF, dtype=torch.float32, device=dev, generator=g) + sin = torch.randn(new_len, HALF, dtype=torch.float32, device=dev, generator=g) + grown_cache = torch.cat((cos, sin), dim=-1) + positions = torch.arange(old_len, old_len + B, device=dev, dtype=torch.int32) + + class DummyRotary: + pass + + rotary_emb = DummyRotary() + rotary_emb.cos_sin_cache = old_cache + indexer = Indexer.__new__(Indexer) + indexer.rotary_emb = rotary_emb + assert indexer._indexer_cos_sin_cache.data_ptr() == old_cache.data_ptr() + + rotary_emb.cos_sin_cache = grown_cache + assert indexer._indexer_cos_sin_cache.data_ptr() == grown_cache.data_ptr() + + key = torch.randn(B, HEAD_DIM, dtype=torch.bfloat16, device=dev, generator=g) + k_weight = torch.randn(HEAD_DIM, dtype=torch.float32, device=dev, generator=g) + k_bias = torch.randn(HEAD_DIM, dtype=torch.float32, device=dev, generator=g) + k_out = fused_k_indexer_norm_rope( + key, k_weight, k_bias, EPS, indexer._indexer_cos_sin_cache, positions + ) + + normed = torch.nn.functional.layer_norm( + key.float(), (HEAD_DIM,), weight=k_weight, bias=k_bias, eps=EPS + ) + k_ref = _rope_first(normed, cos[positions.long()], sin[positions.long()]) + torch.testing.assert_close(k_out.float(), k_ref, atol=0.06, rtol=0.0) + + q = torch.randn(B, n_heads, HEAD_DIM, dtype=torch.bfloat16, device=dev, generator=g) + q_weight = torch.randn(B, n_heads, dtype=torch.bfloat16, device=dev, generator=g) + weight_scale = 0.137 + q_fp8, weights_out = fused_q_indexer_rope_first_quant( + q, q_weight, weight_scale, indexer._indexer_cos_sin_cache, positions + ) + torch.cuda.synchronize() + + q_ref = _rope_first( + q.float(), cos[positions.long()][:, None, :], sin[positions.long()][:, None, :] + ) + scale = torch.clamp(q_ref.abs().amax(dim=-1, keepdim=True), min=1e-4) / FP8_MAX + torch.testing.assert_close( + weights_out.squeeze(-1), + q_weight.float() * weight_scale * scale.squeeze(-1), + atol=1e-3, + rtol=1e-3, + ) + assert ((q_fp8.float() * scale - q_ref).abs() <= 0.0625 * q_ref.abs() + scale).all() + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_dsv3_fused_a_gemm.py b/asian_ai/performance/SGLang/test/registered/jit/test_dsv3_fused_a_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..331e9874d3c173c88efc2be47d4f0a5d2546c88f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_dsv3_fused_a_gemm.py @@ -0,0 +1,44 @@ +"""Tests for JIT dsv3_fused_a_gemm kernel.""" + +import sys + +import pytest +import torch +import torch.nn.functional as F + +from sglang.jit_kernel.dsv3_fused_a_gemm import dsv3_fused_a_gemm +from sglang.jit_kernel.utils import get_ci_test_range, get_jit_cuda_arch, is_hip_runtime +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +# hd_in must be a multiple of 256; 6144/7168 cover the real fused-A shapes. +HD_INS = [6144, 7168] +# hd_out must be a multiple of 16; 2112 and 2624 cover real fused-A variants. +HD_OUTS = [2112, 2624] +NUM_TOKENS = get_ci_test_range(list(range(1, 17)), [1, 8, 16]) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +@pytest.mark.parametrize("hd_out", HD_OUTS) +@pytest.mark.parametrize("hd_in", HD_INS) +@pytest.mark.parametrize("num_tokens", NUM_TOKENS) +def test_dsv3_fused_a_gemm(num_tokens, hd_in, hd_out): + if is_hip_runtime() or get_jit_cuda_arch().major < 9: + pytest.skip("SM90+ required") + + mat_a = torch.randn(num_tokens, hd_in, dtype=torch.bfloat16, device="cuda") + mat_b = torch.randn(hd_out, hd_in, dtype=torch.bfloat16, device="cuda").transpose( + 0, 1 + ) + + ref = F.linear(mat_a, mat_b.T) + out = dsv3_fused_a_gemm(mat_a, mat_b) + + assert out.shape == (num_tokens, hd_out) + assert out.dtype == torch.bfloat16 + torch.testing.assert_close(out, ref, rtol=1e-2, atol=1e-3) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_dsv3_router_gemm.py b/asian_ai/performance/SGLang/test/registered/jit/test_dsv3_router_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..826ce7d86f72ed592234838e8573086c492d20b2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_dsv3_router_gemm.py @@ -0,0 +1,63 @@ +"""Tests for JIT dsv3_router_gemm kernel.""" + +import itertools +import sys + +import pytest +import torch + +from sglang.jit_kernel.dsv3_router_gemm import dsv3_router_gemm +from sglang.jit_kernel.utils import get_ci_test_range, get_jit_cuda_arch, is_hip_runtime +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=37, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=148, suite="nightly-kernel-1-gpu", nightly=True) + +HIDDEN_DIMS = [1024, 4096, 5120, 6144, 7168] +ROUTER_GEMM_CASES = get_ci_test_range( + list( + itertools.product( + [256, 384], + HIDDEN_DIMS, + list(range(1, 17)), + [torch.bfloat16, torch.float32], + ) + ), + [ + (256, 1024, 1, torch.bfloat16), + (256, 7168, 6, torch.bfloat16), + (256, 6144, 4, torch.float32), + (384, 7168, 8, torch.bfloat16), + (256, 7168, 16, torch.float32), + (384, 5120, 16, torch.float32), + ], +) +ATOL = 1e-2 +RTOL = 1e-2 + + +def _ref(hidden_states, router_weights, out_dtype): + return (hidden_states.float() @ router_weights.float().T).to(out_dtype) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +@pytest.mark.parametrize( + "num_experts,hidden_dim,num_tokens,out_dtype", ROUTER_GEMM_CASES +) +def test_dsv3_router_gemm(num_experts, hidden_dim, num_tokens, out_dtype): + if is_hip_runtime() or get_jit_cuda_arch().major < 9: + pytest.skip("SM90+ required") + + mat_a = torch.randn(num_tokens, hidden_dim, dtype=torch.bfloat16, device="cuda") + mat_b = torch.randn(num_experts, hidden_dim, dtype=torch.bfloat16, device="cuda") + + ref = _ref(mat_a, mat_b, out_dtype) + out = dsv3_router_gemm(mat_a, mat_b, out_dtype=out_dtype) + + assert out.shape == (num_tokens, num_experts) + assert out.dtype == out_dtype + torch.testing.assert_close(out.float(), ref.float(), atol=ATOL, rtol=RTOL) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_flash_attention_3_only_qv.py b/asian_ai/performance/SGLang/test/registered/jit/test_flash_attention_3_only_qv.py new file mode 100644 index 0000000000000000000000000000000000000000..3db11a382c7c76daf5e4561aafccede20b590d94 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_flash_attention_3_only_qv.py @@ -0,0 +1,100 @@ +# Adapted from sgl-flash-attn hopper/test_attn_kvcache.py::test_flash_attn_kvcache_only_qv +# Covers the only_qv (NoPE) decode path that FA3 adds for sparse MLA on SM90: +# the QK^T matmul is skipped and attention is computed as softmax(qv * V) over +# a paged V cache (no K cache, no rope). + +import math +import sys +import unittest + +import pytest +import torch +from einops import rearrange, repeat + +from sglang.jit_kernel.flash_attention import flash_attn_with_kvcache +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +# FA3 only_qv path is SM90 (Hopper) only — skip on pre-Hopper and on +# Blackwell+ (sm100+) where FA3 is not built. +skip_condition = not torch.cuda.is_available() or ( + torch.cuda.get_device_capability()[0] != 9 +) + + +def _only_qv_reference(qv, v_cache, page_table, batch_size, nheads_q): + v_ref = rearrange( + v_cache.float()[page_table.flatten()], + "(b s) p h d -> b (s p) h d", + b=batch_size, + ) + v_ref = repeat(v_ref, "b s h d -> b s (h g) d", g=nheads_q) + scores = torch.einsum("bqhd,bkhd->bhqk", qv.float(), v_ref) + probs = torch.softmax(scores / math.sqrt(qv.shape[-1]), dim=-1) + return torch.einsum("bhqk,bkhd->bqhd", probs, v_ref).to(qv.dtype) + + +@pytest.mark.skipif( + skip_condition, reason="FA3 only_qv requires compute capability sm90 (Hopper)." +) +@pytest.mark.parametrize("batch_size", [1, 2]) +@pytest.mark.parametrize("seqlen_k", [129, 257]) +@pytest.mark.parametrize("nheads_q", [8, 16]) +def test_flash_attn_kvcache_only_qv(batch_size, seqlen_k, nheads_q): + torch.manual_seed(0) + device = "cuda" + dtype = torch.bfloat16 + seqlen_q = 1 + nheads_kv = 1 + v_dim = 512 + page_size = 1 + num_pages = batch_size * seqlen_k + + v_cache = torch.randn( + num_pages, page_size, nheads_kv, v_dim, device=device, dtype=dtype + ) + page_table = torch.arange(num_pages, device=device, dtype=torch.int32).view( + batch_size, seqlen_k + ) + qv = torch.randn(batch_size, seqlen_q, nheads_q, v_dim, device=device, dtype=dtype) + cache_seqlens = torch.full( + (batch_size,), seqlen_k, device=device, dtype=torch.int32 + ) + + out_ref = _only_qv_reference(qv, v_cache, page_table, batch_size, nheads_q) + + out = flash_attn_with_kvcache( + q=None, + k_cache=None, + v_cache=v_cache, + qv=qv, + cache_seqlens=cache_seqlens, + page_table=page_table, + only_qv=True, + num_splits=1, + ver=3, + ) + + max_err = (out - out_ref).abs().max().item() + mean_err = (out - out_ref).abs().mean().item() + print(f"only_qv max diff: {max_err} mean diff: {mean_err}") + + assert max_err <= 8e-3, f"max abs err {max_err} > 8e-3" + assert mean_err <= 3e-4, f"mean abs err {mean_err} > 3e-4" + + +class TestFlashAttentionV3OnlyQV(CustomTestCase): + """unittest wrapper so `python -m unittest` and direct invocation also work.""" + + @unittest.skipIf( + skip_condition, + "FA3 only_qv requires compute capability sm90 (Hopper).", + ) + def test_only_qv_smoke(self): + test_flash_attn_kvcache_only_qv(batch_size=2, seqlen_k=257, nheads_q=8) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_flash_attention_4.py b/asian_ai/performance/SGLang/test/registered/jit/test_flash_attention_4.py new file mode 100644 index 0000000000000000000000000000000000000000..9173efd6ff0b9037e81fcd267007cdf6eb317f71 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_flash_attention_4.py @@ -0,0 +1,1512 @@ +# Adapted from https://github.com/Dao-AILab/flash-attention/blob/8ecf128f683266735ba68e3c106ff67a2611886e/tests/cute/test_flash_attn.py + +# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. + +import itertools +import math +import sys + +import pytest +import torch +import torch.nn.functional as F +from einops import rearrange, repeat + +from sglang.jit_kernel.flash_attention import flash_attn_varlen_func +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=120, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, stage="base-b-kernel-unit", runner_config="4-gpu-b200") +register_cuda_ci(est_time=900, suite="nightly-kernel-1-gpu", nightly=True) + +# Skip this test on Hopper machine +skip_condition = torch.cuda.get_device_capability() < (10, 0) + + +def apply_rotary_emb( + x: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + seqlen_offsets: torch.Tensor | int | None = 0, + interleaved: bool = False, +) -> torch.Tensor: + rotary_dim = cos.shape[-1] * 2 + x_rot = x[..., :rotary_dim] + x_pass = x[..., rotary_dim:] + + cos = cos.to(dtype=x.dtype) + sin = sin.to(dtype=x.dtype) + + if x_rot.dim() < 2: + raise ValueError(f"apply_rotary_emb expects x.dim() >= 2, got {x_rot.dim()}") + + b = x_rot.shape[0] + s = x_rot.shape[1] + + if seqlen_offsets is None: + seqlen_offsets = 0 + + if isinstance(seqlen_offsets, int): + positions = ( + torch.arange(s, device=x_rot.device, dtype=torch.long) + seqlen_offsets + ) + cos_s = cos.index_select(0, positions) + sin_s = sin.index_select(0, positions) + cos_s = cos_s.unsqueeze(0).expand(b, -1, -1) + sin_s = sin_s.unsqueeze(0).expand(b, -1, -1) + else: + if seqlen_offsets.dim() != 1 or seqlen_offsets.shape[0] != b: + raise ValueError( + "apply_rotary_emb expects seqlen_offsets to be int or shape [batch]" + ) + positions = torch.arange(s, device=x_rot.device, dtype=torch.long).unsqueeze( + 0 + ) + seqlen_offsets.to(dtype=torch.long).unsqueeze(1) + cos_s = cos.index_select(0, positions.reshape(-1)).view(b, s, -1) + sin_s = sin.index_select(0, positions.reshape(-1)).view(b, s, -1) + + x_rot = x_rot.reshape(b, s, -1, rotary_dim) + cos_s = cos_s.unsqueeze(2) + sin_s = sin_s.unsqueeze(2) + + if interleaved: + x1 = x_rot[..., ::2] + x2 = x_rot[..., 1::2] + o1 = x1 * cos_s - x2 * sin_s + o2 = x2 * cos_s + x1 * sin_s + x_rot = torch.stack((o1, o2), dim=-1).flatten(-2) + else: + x1, x2 = torch.chunk(x_rot, 2, dim=-1) + o1 = x1 * cos_s - x2 * sin_s + o2 = x2 * cos_s + x1 * sin_s + x_rot = torch.cat((o1, o2), dim=-1) + + x_rot = x_rot.reshape_as(x[..., :rotary_dim]) + return torch.cat((x_rot, x_pass), dim=-1) + + +def unpad_input(hidden_states, attention_mask, unused_mask=None): + """ + Arguments: + hidden_states: (batch, seqlen, ...) + attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid. + unused_mask: (batch, seqlen), bool / int, 1 means the element is allocated but unused. + Return: + hidden_states: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask + unused_mask. + indices: (total_nnz), the indices of masked tokens from the flattened input sequence. + cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states. + max_seqlen_in_batch: int + seqused: (batch), returns the number of tokens selected in attention_mask + unused_mask. + """ + all_masks = ( + (attention_mask + unused_mask) if unused_mask is not None else attention_mask + ) + seqlens_in_batch = all_masks.sum(dim=-1, dtype=torch.int32) + used_seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) + indices = torch.nonzero(all_masks.flatten(), as_tuple=False).flatten() + max_seqlen_in_batch = seqlens_in_batch.max().item() + cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) + # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the + # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim + # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to + # index with integer indices. + return ( + rearrange(hidden_states, "b s ... -> (b s) ...")[indices], + indices, + cu_seqlens, + max_seqlen_in_batch, + used_seqlens_in_batch, + ) + + +def pad_input(hidden_states, indices, batch, seqlen): + """ + Arguments: + hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask. + indices: (total_nnz), the indices that represent the non-masked tokens of the original padded input sequence. + batch: int, batch size for the padded sequence. + seqlen: int, maximum sequence length for the padded sequence. + Return: + hidden_states: (batch, seqlen, ...) + """ + dim = hidden_states.shape[1:] + output = torch.zeros( + (batch * seqlen), *dim, device=hidden_states.device, dtype=hidden_states.dtype + ) + output[indices] = hidden_states + return rearrange(output, "(b s) ... -> b s ...", b=batch) + + +def generate_random_padding_mask( + max_seqlen, batch_size, device, mode="random", zero_lengths=False +): + assert mode in ["full", "random", "third"] + if mode == "full": + lengths = torch.full( + (batch_size, 1), max_seqlen, device=device, dtype=torch.int32 + ) + elif mode == "random": + lengths = torch.randint( + max(0 if zero_lengths else 1, max_seqlen - 20), + max_seqlen + 1, + (batch_size, 1), + device=device, + ) + elif mode == "third": + lengths = torch.randint( + max_seqlen // 3, max_seqlen + 1, (batch_size, 1), device=device + ) + else: + # This should never happen due to the assertion above, but for linter + lengths = torch.full( + (batch_size, 1), max_seqlen, device=device, dtype=torch.int32 + ) + + if zero_lengths: + # Generate zero-lengths every 5 batches and the last batch. + for i in range(batch_size): + if i % 5 == 0: + lengths[i] = 0 + lengths[-1] = 0 + padding_mask = ( + repeat(torch.arange(max_seqlen, device=device), "s -> b s", b=batch_size) + < lengths + ) + return padding_mask + + +def generate_qkv( + q, + k, + v, + query_padding_mask=None, + key_padding_mask=None, + qv=None, + kvpacked=False, + qkvpacked=False, + query_unused_mask=None, + key_unused_mask=None, +): + """ + Arguments: + q: (batch_size, seqlen_q, nheads, d) + k: (batch_size, seqlen_k, nheads_k, d) + v: (batch_size, seqlen_k, nheads_k, d_v) + query_padding_mask: (batch_size, seqlen), bool + key_padding_mask: (batch_size, seqlen), bool + """ + assert not (kvpacked and qkvpacked) + batch_size, seqlen_q, nheads, d = q.shape + d_v = v.shape[-1] + _, seqlen_k, nheads_k, _ = k.shape + assert k.shape == (batch_size, seqlen_k, nheads_k, d) + assert v.shape == (batch_size, seqlen_k, nheads_k, d_v) + if query_unused_mask is not None or key_unused_mask is not None: + assert not kvpacked + assert not qkvpacked + + if query_padding_mask is not None: + q_unpad, indices_q, cu_seqlens_q, max_seqlen_q, seqused_q = unpad_input( + q, query_padding_mask, query_unused_mask + ) + output_pad_fn = lambda output_unpad: pad_input( + output_unpad, indices_q, batch_size, seqlen_q + ) + qv_unpad = ( + rearrange(qv, "b s ... -> (b s) ...")[indices_q] if qv is not None else None + ) + else: + q_unpad = rearrange(q, "b s h d -> (b s) h d") + cu_seqlens_q = torch.arange( + 0, + (batch_size + 1) * seqlen_q, + step=seqlen_q, + dtype=torch.int32, + device=q_unpad.device, + ) + seqused_q = None + max_seqlen_q = seqlen_q + output_pad_fn = lambda output_unpad: rearrange( + output_unpad, "(b s) h d -> b s h d", b=batch_size + ) + qv_unpad = rearrange(qv, "b s ... -> (b s) ...") if qv is not None else None + + if key_padding_mask is not None: + k_unpad, indices_k, cu_seqlens_k, max_seqlen_k, seqused_k = unpad_input( + k, key_padding_mask, key_unused_mask + ) + v_unpad, *rest = unpad_input(v, key_padding_mask, key_unused_mask) + else: + k_unpad = rearrange(k, "b s h d -> (b s) h d") + v_unpad = rearrange(v, "b s h d -> (b s) h d") + cu_seqlens_k = torch.arange( + 0, + (batch_size + 1) * seqlen_k, + step=seqlen_k, + dtype=torch.int32, + device=k_unpad.device, + ) + seqused_k = None + max_seqlen_k = seqlen_k + + if qkvpacked: + assert (query_padding_mask == key_padding_mask).all() + assert nheads == nheads_k + qkv_unpad = torch.stack([q_unpad, k_unpad, v_unpad], dim=1) + qkv = torch.stack([q, k, v], dim=2) + if query_padding_mask is not None: + dqkv_pad_fn = lambda dqkv_unpad: pad_input( + dqkv_unpad, indices_q, batch_size, seqlen_q + ) + else: + dqkv_pad_fn = lambda dqkv_unpad: rearrange( + dqkv_unpad, "(b s) t h d -> b s t h d", b=batch_size + ) + return ( + qkv_unpad.detach().requires_grad_(), + cu_seqlens_q, + max_seqlen_q, + qkv.detach().requires_grad_(), + output_pad_fn, + dqkv_pad_fn, + ) + elif kvpacked: + kv_unpad = torch.stack([k_unpad, v_unpad], dim=1) + kv = torch.stack([k, v], dim=2) + dq_pad_fn = output_pad_fn + if key_padding_mask is not None: + dkv_pad_fn = lambda dkv_unpad: pad_input( + dkv_unpad, indices_k, batch_size, seqlen_k + ) + else: + dkv_pad_fn = lambda dkv_unpad: rearrange( + dkv_unpad, "(b s) t h d -> b s t h d", b=batch_size + ) + return ( + q_unpad.detach().requires_grad_(), + kv_unpad.detach().requires_grad_(), + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + q.detach().requires_grad_(), + kv.detach().requires_grad_(), + output_pad_fn, + dq_pad_fn, + dkv_pad_fn, + ) + else: + dq_pad_fn = output_pad_fn + if key_padding_mask is not None: + dk_pad_fn = lambda dk_unpad: pad_input( + dk_unpad, indices_k, batch_size, seqlen_k + ) + else: + dk_pad_fn = lambda dk_unpad: rearrange( + dk_unpad, "(b s) h d -> b s h d", b=batch_size + ) + return ( + q_unpad.detach().requires_grad_(), + k_unpad.detach().requires_grad_(), + v_unpad.detach().requires_grad_(), + qv_unpad.detach() if qv is not None else None, + cu_seqlens_q, + cu_seqlens_k, + seqused_q, + seqused_k, + max_seqlen_q, + max_seqlen_k, + q.detach().requires_grad_(), + k.detach().requires_grad_(), + v.detach().requires_grad_(), + qv.detach() if qv is not None else None, + output_pad_fn, + dq_pad_fn, + dk_pad_fn, + ) + + +def construct_local_mask( + seqlen_q, + seqlen_k, + window_size=(None, None), + sink_token_length=0, + query_padding_mask=None, + key_padding_mask=None, + key_leftpad=None, + device=None, +): + row_idx = rearrange( + torch.arange(seqlen_q, device=device, dtype=torch.long), "s -> s 1" + ) + col_idx = torch.arange(seqlen_k, device=device, dtype=torch.long) + if key_leftpad is not None: + key_leftpad = rearrange(key_leftpad, "b -> b 1 1 1") + col_idx = repeat(col_idx, "s -> b 1 1 s", b=key_leftpad.shape[0]) + col_idx = torch.where(col_idx >= key_leftpad, col_idx - key_leftpad, 2**32) + sk = ( + seqlen_k + if key_padding_mask is None + else rearrange(key_padding_mask.sum(-1), "b -> b 1 1 1") + ) + sq = ( + seqlen_q + if query_padding_mask is None + else rearrange(query_padding_mask.sum(-1), "b -> b 1 1 1") + ) + if window_size[0] is None: + return col_idx > row_idx + sk - sq + window_size[1] + else: + sk = torch.full_like(col_idx, seqlen_k) if key_padding_mask is None else sk + return torch.logical_or( + col_idx > torch.minimum(row_idx + sk - sq + window_size[1], sk), + torch.logical_and( + col_idx < row_idx + sk - sq - window_size[0], + col_idx >= sink_token_length, + ), + ) + + +def construct_chunk_mask( + seqlen_q, + seqlen_k, + attention_chunk, + query_padding_mask=None, + key_padding_mask=None, + key_leftpad=None, + device=None, +): + row_idx = rearrange( + torch.arange(seqlen_q, device=device, dtype=torch.long), "s -> s 1" + ) + col_idx = torch.arange(seqlen_k, device=device, dtype=torch.long) + if key_leftpad is not None: + key_leftpad = rearrange(key_leftpad, "b -> b 1 1 1") + col_idx = repeat(col_idx, "s -> b 1 1 s", b=key_leftpad.shape[0]) + col_idx = torch.where(col_idx >= key_leftpad, col_idx - key_leftpad, 2**32) + sk = ( + seqlen_k + if key_padding_mask is None + else rearrange(key_padding_mask.sum(-1), "b -> b 1 1 1") + ) + sq = ( + seqlen_q + if query_padding_mask is None + else rearrange(query_padding_mask.sum(-1), "b -> b 1 1 1") + ) + sk = torch.full_like(col_idx, seqlen_k) if key_padding_mask is None else sk + # Subtract remainder instead of divide and then multiply to take care of negative values + col_limit_left_chunk = row_idx + sk - sq - (row_idx + sk - sq) % attention_chunk + return torch.logical_or( + col_idx < col_limit_left_chunk, + col_idx >= col_limit_left_chunk + attention_chunk, + ) + + +def attention_ref( + q, + k, + v, + query_padding_mask=None, + key_padding_mask=None, + key_leftpad=None, + attn_bias=None, + dropout_p=0.0, + dropout_mask=None, + causal=False, + qv=None, + q_descale=None, + k_descale=None, + v_descale=None, + window_size=(None, None), + attention_chunk=0, + sink_token_length=0, + learnable_sink=None, + softcap=0.0, + upcast=True, + reorder_ops=False, + intermediate_dtype=None, +): + """ + Arguments: + q: (batch_size, seqlen_q, nheads, head_dim) + k: (batch_size, seqlen_k, nheads, head_dim) + v: (batch_size, seqlen_k, nheads, head_dim_v) + qv: (batch_size, seqlen_q, nheads, head_dim_v) + query_padding_mask: (batch_size, seqlen_q) + key_padding_mask: (batch_size, seqlen_k) + attn_bias: broadcastable to (batch_size, nheads, seqlen_q, seqlen_k) + dropout_p: float + dropout_mask: (batch_size, nheads, seqlen_q, seqlen_k) + causal: whether to apply causal masking + upcast: whether to cast all inputs to fp32, do all computation in fp32, then cast + output back to fp16/bf16. + reorder_ops: whether to change the order of operations (scaling k instead of scaling k, etc.) + without changing the math. This is to estimate the numerical error from operation + reordering. + Output: + output: (batch_size, seqlen_q, nheads, head_dim_v) + attention: (batch_size, nheads, seqlen_q, seqlen_k), softmax after dropout + """ + if causal: + window_size = (window_size[0], 0) + dtype_og = q.dtype + if upcast: + q, k, v = q.float(), k.float(), v.float() + qv = qv.float() if qv is not None else None + if q_descale is not None: + q_descale = repeat(q_descale, "b h -> b 1 (h g) 1", g=q.shape[2] // k.shape[2]) + q = (q.float() * q_descale).to(q.dtype) + qv = (qv.float() * q_descale).to(qv.dtype) if qv is not None else None + if k_descale is not None: + k = (k.float() * rearrange(k_descale, "b h -> b 1 h 1")).to(dtype=k.dtype) + if v_descale is not None: + v = (v.float() * rearrange(v_descale, "b h -> b 1 h 1")).to(dtype=v.dtype) + seqlen_q, seqlen_k = q.shape[1], k.shape[1] + k = repeat(k, "b s h d -> b s (h g) d", g=q.shape[2] // k.shape[2]) + v = repeat(v, "b s h d -> b s (h g) d", g=q.shape[2] // v.shape[2]) + d = q.shape[-1] + dv = v.shape[-1] + softmax_scale = 1.0 / math.sqrt(d if qv is None else d + dv) + if not reorder_ops: + scores = torch.einsum("bthd,bshd->bhts", q * softmax_scale, k) + else: + scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale) + if qv is not None: + scores = scores + torch.einsum("bthd,bshd->bhts", qv * softmax_scale, v) + if softcap > 0: + scores = torch.tanh(scores / softcap) * softcap + if key_padding_mask is not None: + scores.masked_fill_( + rearrange(~key_padding_mask, "b s -> b 1 1 s"), float("-inf") + ) + local_mask = None + if window_size[0] is not None or window_size[1] is not None: + local_mask = construct_local_mask( + seqlen_q, + seqlen_k, + window_size, + sink_token_length, + query_padding_mask, + key_padding_mask, + key_leftpad=key_leftpad, + device=q.device, + ) + if attention_chunk > 0: + chunk_mask = construct_chunk_mask( + seqlen_q, + seqlen_k, + attention_chunk, + query_padding_mask, + key_padding_mask, + key_leftpad=key_leftpad, + device=q.device, + ) + local_mask = ( + torch.logical_or(local_mask, chunk_mask) + if local_mask is not None + else chunk_mask + ) + if local_mask is not None: + scores.masked_fill_(local_mask, float("-inf")) + if attn_bias is not None: + scores = scores + attn_bias + if learnable_sink is None: + attention = torch.softmax(scores, dim=-1).to(v.dtype) + else: + scores_fp32 = scores.to(torch.float32) + logits_max = torch.amax(scores_fp32, dim=-1, keepdim=True) + learnable_sink = rearrange(learnable_sink, "h -> h 1 1") + logits_or_sinks_max = torch.maximum(learnable_sink, logits_max) + unnormalized_scores = torch.exp(scores_fp32 - logits_or_sinks_max) + normalizer = unnormalized_scores.sum(dim=-1, keepdim=True) + torch.exp( + learnable_sink - logits_or_sinks_max + ) + attention = (unnormalized_scores / normalizer).to(v.dtype) + # We want to mask here so that the attention matrix doesn't have any NaNs + # Otherwise we'll get NaN in dV + if query_padding_mask is not None: + attention = attention.masked_fill( + rearrange(~query_padding_mask, "b s -> b 1 s 1"), 0.0 + ) + # Without this we might get NaN in dv + if key_padding_mask is not None: + attention = attention.masked_fill( + rearrange(~key_padding_mask, "b s -> b 1 1 s"), 0.0 + ) + # Some rows might be completely masked out so we fill them with zero instead of NaN + if local_mask is not None: + attention = attention.masked_fill( + torch.all(local_mask, dim=-1, keepdim=True), 0.0 + ) + dropout_scaling = 1.0 / (1 - dropout_p) + # attention_drop = attention.masked_fill(~dropout_mask, 0.0) * dropout_scaling + # output = torch.einsum('bhts,bshd->bthd', attention_drop , v) + if dropout_mask is not None: + attention_drop = attention.masked_fill(~dropout_mask, 0.0) + else: + attention_drop = attention + if intermediate_dtype is not None: + attention_drop = attention_drop.to(intermediate_dtype).to(attention_drop.dtype) + output = torch.einsum("bhts,bshd->bthd", attention_drop, v * dropout_scaling) + if query_padding_mask is not None: + output.masked_fill_(rearrange(~query_padding_mask, "b s -> b s 1 1"), 0.0) + return output.to(dtype=dtype_og), attention.to(dtype=dtype_og) + + +@pytest.mark.skipif( + skip_condition, reason="FA4 Requires compute capability of 10 or above." +) +# @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float8_e4m3fn]) +@pytest.mark.parametrize("dtype", [torch.bfloat16]) +@pytest.mark.parametrize("mha_type", ["mha", "mqa", "gqa"]) +# @pytest.mark.parametrize("mha_type", ["mqa"]) +@pytest.mark.parametrize("has_learnable_sink", [False, True]) +# @pytest.mark.parametrize("has_learnable_sink", [False]) +# @pytest.mark.parametrize("has_qv", [False, True]) +@pytest.mark.parametrize("has_qv", [False]) +# @pytest.mark.parametrize("deterministic", [False, True]) +@pytest.mark.parametrize("deterministic", [False]) +# @pytest.mark.parametrize("softcap", [0.0, 15.0]) +@pytest.mark.parametrize("softcap", [0.0]) +# @pytest.mark.parametrize("local", [False, True]) +@pytest.mark.parametrize("local", [False]) +@pytest.mark.parametrize("causal", [False, True]) +# @pytest.mark.parametrize("causal", [False]) +# @pytest.mark.parametrize("add_unused_qkv", [False, True]) +@pytest.mark.parametrize("add_unused_qkv", [False]) +# @pytest.mark.parametrize("d", [32, 64, 96, 128, 160, 192, 224, 256]) +# @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192, 256]) +# @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192]) +# @pytest.mark.parametrize('d', [56, 80]) +# @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128]) +# @pytest.mark.parametrize("d", [64, 96, 128]) +@pytest.mark.parametrize("d", [64, 128]) +# @pytest.mark.parametrize("d", [192]) +@pytest.mark.parametrize( + "seqlen_q,seqlen_k", + [ + # (1, 1), + # (1, 3), + # (2, 1), + (511, 1), + (3, 513), + (64, 128), + (128, 128), + (256, 256), + # (113, 203), + # (128, 217), + # (113, 211), + # (108, 256), + # (256, 512), + (307, 256), + (640, 128), + (512, 256), + (1024, 1024), + (1023, 1024), + (1024, 1023), + (2048, 2048), + ], +) +def test_flash_attn_varlen_output( + seqlen_q, + seqlen_k, + d, + add_unused_qkv, + causal, + local, + softcap, + deterministic, + has_qv, + has_learnable_sink, + mha_type, + dtype, +): + if ( + causal or local + ): # Right now we only support causal attention with seqlen_k == seqlen_q + seqlen_k = seqlen_q + device = "cuda" + # set seed + torch.random.manual_seed(seqlen_q + seqlen_k + d + int(causal) * 2 + int(local)) + batch_size = 49 if seqlen_q <= 1024 else 7 + nheads = 6 + # batch_size = 1 + # nheads = 1 + nheads_kv = nheads if mha_type == "mha" else (3 if mha_type == "gqa" else 1) + dtype_ref = torch.bfloat16 if dtype == torch.float8_e4m3fn else dtype + # dv_vals = [128, d] if d > 128 and d <= 192 else ([256, 512, d] if d <= 64 else [d]) + dv_vals = [128] if d == 192 else ([d] if d != 128 else [64, d]) + if dtype == torch.float8_e4m3fn: + dv_vals = [d] + # attention_chunk_vals = [torch.randint(1, seqlen_k * 2, (1,)).item(), 0] if seqlen_q <= seqlen_k else [0] + attention_chunk_vals = [0] + for dv, attention_chunk in itertools.product(dv_vals, attention_chunk_vals): + q_ref = torch.randn( + batch_size, seqlen_q, nheads, d, device=device, dtype=dtype_ref + ) + if softcap > 0.0: + # Ensure the values of qk are at least within softcap range. + q_ref = (q_ref * softcap / 4).detach().requires_grad_() + q_ref = q_ref.to(dtype).to(dtype_ref).requires_grad_() + k_ref = ( + torch.randn( + batch_size, seqlen_k, nheads_kv, d, device=device, dtype=dtype_ref + ) + .to(dtype) + .to(dtype_ref) + .requires_grad_() + ) + v_ref = ( + torch.randn( + batch_size, seqlen_k, nheads_kv, dv, device=device, dtype=dtype_ref + ) + .to(dtype) + .to(dtype_ref) + .requires_grad_() + ) + if has_qv: + qv_ref = ( + torch.randn( + batch_size, seqlen_q, nheads, dv, device=device, dtype=dtype_ref + ) + .to(dtype) + .to(dtype_ref) + ) + else: + qv_ref = None + # Put window_size after QKV randn so that window_size changes from test to test + window_size = ( + (None, None) if not local else torch.randint(0, seqlen_k, (2,)).tolist() + ) + if has_learnable_sink: + learnable_sink = torch.randn(nheads, dtype=torch.bfloat16, device=device) + else: + learnable_sink = None + if dtype == torch.float8_e4m3fn: + q_descale, k_descale, v_descale = [ + torch.rand(batch_size, nheads_kv, device=device, dtype=torch.float32) + * 2 + for _ in range(3) + ] + else: + q_descale, k_descale, v_descale = None, None, None + q, k, v = [x.detach().requires_grad_() for x in (q_ref, k_ref, v_ref)] + qv = qv_ref.detach() if has_qv else None + query_padding_mask = generate_random_padding_mask( + seqlen_q, batch_size, device, mode="random", zero_lengths=False + ) + # TODO: test zero_lengths + key_padding_mask = generate_random_padding_mask( + # seqlen_k, batch_size, device, mode="random", zero_lengths=True + seqlen_k, + batch_size, + device, + mode="random", + zero_lengths=False, + ) + + def _gen_unused_masks(padding_mask, add_unused, max_seq_len, bs, device): + if add_unused: + another_mask = generate_random_padding_mask(max_seq_len, bs, device) + attn_mask = torch.logical_and(padding_mask, another_mask) + unused_mask = torch.logical_xor( + torch.logical_or(padding_mask, another_mask), attn_mask + ) + else: + attn_mask = padding_mask + unused_mask = None + return attn_mask, unused_mask + + query_padding_mask, query_unused_mask = _gen_unused_masks( + query_padding_mask, add_unused_qkv, seqlen_q, batch_size, q.device + ) + # query_padding_mask[:] = True + # query_unused_mask = None + key_padding_mask, key_unused_mask = _gen_unused_masks( + key_padding_mask, add_unused_qkv, seqlen_k, batch_size, k.device + ) + + if causal or local: + key_padding_mask = query_padding_mask + + result = generate_qkv( + q, + k, + v, + query_padding_mask, + key_padding_mask, + qv=qv, + kvpacked=False, + query_unused_mask=query_unused_mask, + key_unused_mask=key_unused_mask, + ) + ( + q_unpad, # 0 + k_unpad, # 1 + v_unpad, # 2 + qv_unpad, # 3 + cu_seqlens_q, # 4 + cu_seqlens_k, # 5 + seqused_q, # 6 + seqused_k, # 7 + max_seqlen_q, # 8 + max_seqlen_k, # 9 + q, # 10 + k, # 11 + v, # 12 + qv, # 13 + output_pad_fn, # 14 + dq_pad_fn, # 15 + dk_pad_fn, # 16 + ) = result + q_unpad, k_unpad, v_unpad = [ + x.detach().to(dtype).requires_grad_() for x in (q_unpad, k_unpad, v_unpad) + ] + out_ref, attn_ref = attention_ref( + q_ref, + k_ref, + v_ref, + query_padding_mask, + key_padding_mask, + causal=causal, + qv=qv_ref, + q_descale=q_descale, + k_descale=k_descale, + v_descale=v_descale, + window_size=window_size, + attention_chunk=attention_chunk, + learnable_sink=learnable_sink, + softcap=softcap, + ) + out_pt, attn_pt = attention_ref( + q_ref, + k_ref, + v_ref, + query_padding_mask, + key_padding_mask, + causal=causal, + qv=qv_ref, + q_descale=q_descale, + k_descale=k_descale, + v_descale=v_descale, + window_size=window_size, + attention_chunk=attention_chunk, + learnable_sink=learnable_sink, + softcap=softcap, + upcast=False, + reorder_ops=True, + intermediate_dtype=dtype if dtype == torch.float8_e4m3fn else None, + ) + + print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}") + print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}") + + if query_unused_mask is not None: + q_zero_masking = rearrange(query_unused_mask, "b s -> b s 1 1") + + # Numerical error if we just do any arithmetic on out_ref + fwd_atol = 2 * (out_ref + 0.3 - 0.3 - out_ref).abs().max().item() + rtol = 2 if softcap == 0.0 else 3 + + pack_gqa_vals = [False, True, None] + # num_splits_vals = [1, 3] + num_splits_vals = [1] + for pack_gqa, num_splits in itertools.product(pack_gqa_vals, num_splits_vals): + out_unpad, lse = flash_attn_varlen_func( + q_unpad, + k_unpad, + v_unpad, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + # max_seqlen_q and max_seqlen_k not needed for FA4 + seqused_q=seqused_q, + seqused_k=seqused_k, + causal=causal, + window_size=window_size, + softcap=softcap, + sinks=learnable_sink, # FA4 uses learnable_sink, not sinks + pack_gqa=pack_gqa, + return_softmax_lse=True, + ver=4, + ) + out = output_pad_fn(out_unpad) + if query_unused_mask is not None: + out.masked_fill_(q_zero_masking, 0.0) + print(f"Output max diff: {(out - out_ref).abs().max().item()}") + print(f"Output mean diff: {(out - out_ref).abs().mean().item()}") + # if not causal: + # print(f"LSE max diff: {(lse - lse_ref).abs().max().item()}") + # breakpoint() + + # Check that FlashAttention's numerical error is at most 3x the numerical error + # of a Pytorch implementation. + assert (out - out_ref).abs().max().item() <= rtol * ( + out_pt - out_ref + ).abs().max().item() + fwd_atol + + if ( + dtype != torch.float8_e4m3fn + and not has_qv + and not dv > 256 + and not attention_chunk != 0 + and dv == d + and not has_learnable_sink + and False + ): + g_unpad = torch.randn_like(out_unpad) + do_o = ((g_unpad.float() * out_unpad.float()).sum(-1)).transpose(-1, -2) + # import flash_attn_3_cuda + # dq_unpad, dk_unpad, dv_unpad, softmax_d, dq_accum, lse_log2 = flash_attn_3_cuda.bwd_varlen( + # g_unpad, + # q_unpad, + # k_unpad, + # v_unpad, + # out_unpad, + # lse, + # None, + # None, + # None, + # cu_seqlens_q, + # cu_seqlens_k, + # None, None, + # max_seqlen_q, + # max_seqlen_k, + # d ** (-0.5), + # causal, + # window_size[0], window_size[1], + # softcap, + # deterministic, + # 0, # sm_margin + # ) + dq_unpad, dk_unpad, dv_unpad = torch.autograd.grad( + out_unpad, (q_unpad, k_unpad, v_unpad), g_unpad + ) + dq = dq_pad_fn(dq_unpad) + dk = dk_pad_fn(dk_unpad) + dv = dk_pad_fn(dv_unpad) + if key_unused_mask is not None: + k_zero_masking = rearrange(key_unused_mask, "b s -> b s 1 1") + dk.masked_fill_(k_zero_masking, 0.0) + dv.masked_fill_(k_zero_masking, 0.0) + if query_unused_mask is not None: + dq.masked_fill_(q_zero_masking, 0.0) + # print(f"dO_O max diff: {(softmax_d - do_o).abs().max().item()}") + # assert (softmax_d - do_o).abs().max().item() <= 1e-5 + # assert dq_accum.abs().max().item() == 0.0 + g = output_pad_fn(g_unpad) + + # qk = torch.einsum('bthd,bshd->bhts', q / (d ** 0.5), k).float() + # qk = torch.masked_fill(qk, rearrange(~key_padding_mask, "b s -> b 1 1 s"), float("-inf")) + # dS = torch.einsum('bthd,bshd->bhts', g.float(), v.float()) + # P = torch.softmax(qk, -1) + # dP = P * (dS - (g.float() * out.float()).sum(-1).transpose(1, 2).unsqueeze(-1)) + # dQ = torch.einsum('bhts,bshd->bthd', dP, k.float()) + # dV = torch.einsum('bhts,bthd->bshd', P, g.float()) + # dK = torch.einsum('bhts,bthd->bshd', dP, q.float()) + + # dq, dk, dv = torch.autograd.grad(out, (q, k, v), g) + dq_ref, dk_ref, dv_ref = torch.autograd.grad( + out_ref, (q_ref, k_ref, v_ref), g + ) + dq_pt, dk_pt, dv_pt = torch.autograd.grad(out_pt, (q_ref, k_ref, v_ref), g) + print(f"dQ max diff: {(dq - dq_ref).abs().max().item()}") + print(f"dK max diff: {(dk - dk_ref).abs().max().item()}") + print(f"dV max diff: {(dv - dv_ref).abs().max().item()}") + print(f"dQ mean diff: {(dq - dq_ref).abs().mean().item()}") + print(f"dK mean diff: {(dk - dk_ref).abs().mean().item()}") + print(f"dV mean diff: {(dv - dv_ref).abs().mean().item()}") + print(f"dQ Pytorch max diff: {(dq_pt - dq_ref).abs().max().item()}") + print(f"dK Pytorch max diff: {(dk_pt - dk_ref).abs().max().item()}") + print(f"dV Pytorch max diff: {(dv_pt - dv_ref).abs().max().item()}") + print(f"dQ Pytorch mean diff: {(dq_pt - dq_ref).abs().mean().item()}") + print(f"dK Pytorch mean diff: {(dk_pt - dk_ref).abs().mean().item()}") + print(f"dV Pytorch mean diff: {(dv_pt - dv_ref).abs().mean().item()}") + # breakpoint() + dq_atol = 2 * (dq_ref + 0.3 - 0.3 - dq_ref).abs().max().item() + ( + 0 if softcap == 0 else 3e-4 + ) + assert (dq - dq_ref).abs().max().item() <= rtol * ( + dq_pt - dq_ref + ).abs().max().item() + dq_atol + dk_atol = 2 * (dk_ref + 0.3 - 0.3 - dk_ref).abs().max().item() + ( + 0 if softcap == 0 else 3e-4 + ) + assert (dk - dk_ref).abs().max().item() <= rtol * ( + dk_pt - dk_ref + ).abs().max().item() + dk_atol + dv_atol = 2 * (dv_ref + 0.3 - 0.3 - dv_ref).abs().max().item() + ( + 0 if softcap == 0 else 3e-4 + ) + assert (dv - dv_ref).abs().max().item() <= rtol * ( + dv_pt - dv_ref + ).abs().max().item() + dv_atol + + +@pytest.mark.skipif( + skip_condition, reason="FA4 Requires compute capability of 10 or above." +) +# @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float8_e4m3fn]) +@pytest.mark.parametrize("dtype", [torch.bfloat16]) +# @pytest.mark.parametrize("dtype", [torch.float8_e4m3fn]) +@pytest.mark.parametrize("mha_type", ["mha", "mqa", "gqa"]) +# @pytest.mark.parametrize("mha_type", ["mha"]) +@pytest.mark.parametrize("has_learnable_sink", [False, True]) +# @pytest.mark.parametrize("has_learnable_sink", [False]) +# @pytest.mark.parametrize("new_kv", [False, True]) +@pytest.mark.parametrize("new_kv", [False]) +# @pytest.mark.parametrize("local", [False, True]) +@pytest.mark.parametrize("local", [False]) +# @pytest.mark.parametrize("causal", [False, True]) +@pytest.mark.parametrize("causal", [True]) +# @pytest.mark.parametrize("seqlen_new_eq_seqlen_q", [True, False]) +@pytest.mark.parametrize("seqlen_new_eq_seqlen_q", [False]) +# @pytest.mark.parametrize("has_rotary_seqlens", [False, True]) +@pytest.mark.parametrize("has_rotary_seqlens", [False]) +# @pytest.mark.parametrize("rotary_interleaved", [False, True]) +@pytest.mark.parametrize("rotary_interleaved", [True]) +# @pytest.mark.parametrize("rotary_fraction", [0.0, 0.5, 1.0]) +@pytest.mark.parametrize("rotary_fraction", [0.0]) +# @pytest.mark.parametrize("page_size", [None] + ([1, 4, 128])) +# @pytest.mark.parametrize("page_size", [None, 128]) +@pytest.mark.parametrize("page_size", [128]) +# @pytest.mark.parametrize("has_leftpad", [False, True]) +@pytest.mark.parametrize("has_leftpad", [False]) +# @pytest.mark.parametrize("has_batch_idx", [False, True]) +@pytest.mark.parametrize("has_batch_idx", [False]) +# @pytest.mark.parametrize("varlen_q", [False, True]) +@pytest.mark.parametrize("varlen_q", [False]) +# @pytest.mark.parametrize("d", [32, 59, 64, 80, 128, 256]) +# @pytest.mark.parametrize("d", [32, 64, 96, 128, 160, 192, 224, 256]) +# @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192]) +# @pytest.mark.parametrize('d', [56, 80]) +# @pytest.mark.parametrize("d", [128]) +@pytest.mark.parametrize("d", [64]) +# @pytest.mark.parametrize("d", [192]) +@pytest.mark.parametrize( + "seqlen_q,seqlen_k", + [ + (1, 128), + (1, 339), + (3, 1024), + (64, 800), + (64, 256), + (3, 799), + (64, 2048), + (16, 20000), + # # (1, 128 * 1024), + # # (16, 128 * 1024), + # (128, 128), + # (256, 512), # To test appending KV with more than 1 block + # (2048, 3577), # Enough tile to test persistent scheduler + ], +) +# @pytest.mark.parametrize('seqlen_q,seqlen_k', [(256, 128)]) +def test_flash_attn_kvcache( + seqlen_q, + seqlen_k, + d, + varlen_q, + has_batch_idx, + has_leftpad, + page_size, + rotary_fraction, + rotary_interleaved, + has_rotary_seqlens, + seqlen_new_eq_seqlen_q, + causal, + local, + new_kv, + has_learnable_sink, + mha_type, + dtype, +): + if page_size is not None and seqlen_k % page_size != 0: + pytest.skip() + if seqlen_q > seqlen_k and new_kv: + pytest.skip() + if not new_kv and rotary_fraction > 0.0: + pytest.skip() + if rotary_fraction == 0.0 and has_rotary_seqlens: + pytest.skip() + device = "cuda" + # set seed + torch.random.manual_seed(0) + batch_size = 5 + # batch_size = 1 + batch_size_cache = batch_size if not has_batch_idx else batch_size * 2 + nheads = 6 + # nheads = 1 + # rotary_dim must be a multiple of 16, and must be <= d + rotary_dim = math.floor(int(rotary_fraction * d) / 16) * 16 + nheads_k = nheads if mha_type == "mha" else (1 if mha_type == "mqa" else 3) + assert nheads % nheads_k == 0 + dtype_ref = torch.bfloat16 if dtype == torch.float8_e4m3fn else dtype + # dv_vals = [128, d] if d > 128 and d <= 192 else ([256, 512, d] if d <= 64 else [d]) + dv_vals = [d] + if dtype == torch.float8_e4m3fn: + dv_vals = [d] + # attention_chunk_vals = [torch.randint(1, seqlen_k * 2, (1,)).item(), 0] if (causal or local) else [0] + attention_chunk_vals = [0] + for dv, attention_chunk in itertools.product(dv_vals, attention_chunk_vals): + # has_qv = d == 64 and dv >= 256 + has_qv = False + q = ( + torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype_ref) + .to(dtype) + .to(dtype_ref) + ) + if has_qv: + qv = ( + torch.randn( + batch_size, seqlen_q, nheads, dv, device=device, dtype=dtype_ref + ) + .to(dtype) + .to(dtype_ref) + ) + else: + qv = None + if varlen_q: + query_padding_mask = generate_random_padding_mask( + seqlen_q, batch_size, device, mode="random" + ) + q_unpad, indices_q, cu_seqlens_q, max_seqlen_q, *rest = unpad_input( + q, query_padding_mask + ) + output_pad_fn = lambda output_unpad: pad_input( + output_unpad, indices_q, batch_size, seqlen_q + ) + qv_unpad = ( + rearrange(qv, "b s ... -> (b s) ...")[indices_q] if has_qv else None + ) + else: + query_padding_mask = None + q_unpad = q + qv_unpad = qv + cu_seqlens_q, max_seqlen_q = None, None + # Put window_size after QKV randn so that window_size changes from test to test + window_size = ( + (None, None) if not local else torch.randint(0, seqlen_k, (2,)).tolist() + ) + if has_learnable_sink: + learnable_sink = torch.randn(nheads, dtype=torch.bfloat16, device=device) + else: + learnable_sink = None + + seqlen_new = ( + seqlen_q + if seqlen_new_eq_seqlen_q + else torch.randint(1, seqlen_q + 1, (1,)).item() + ) + cu_seqlens_k_new = None + key_new_padding_mask = None + if new_kv: + k = ( + torch.randn( + batch_size, seqlen_new, nheads_k, d, device=device, dtype=dtype_ref + ) + .to(dtype) + .to(dtype_ref) + ) + v = ( + torch.randn( + batch_size, seqlen_new, nheads_k, dv, device=device, dtype=dtype_ref + ) + .to(dtype) + .to(dtype_ref) + ) + if varlen_q: # k & v are also varlen + key_new_padding_mask = generate_random_padding_mask( + seqlen_new, batch_size, device, mode="random" + ) + k_unpad, indices_k, cu_seqlens_k_new, *rest = unpad_input( + k, key_new_padding_mask + ) + v_unpad, *rest = unpad_input(v, key_new_padding_mask) + else: + k_unpad, v_unpad = k, v + else: + k, v, k_unpad, v_unpad = None, None, None, None + if page_size is None: + k_cache = ( + torch.randn( + batch_size_cache, + seqlen_k, + nheads_k, + d, + device=device, + dtype=dtype_ref, + ) + .to(dtype) + .to(dtype_ref) + ) + v_cache = ( + torch.randn( + batch_size_cache, + seqlen_k, + nheads_k, + dv, + device=device, + dtype=dtype_ref, + ) + .to(dtype) + .to(dtype_ref) + ) + page_table = None + num_blocks = None + else: + ( + k_cache, + v_cache, + page_table, + k_cache_paged, + v_cache_paged, + num_blocks, + ) = _generate_block_kvcache( + seqlen_k, + page_size, + batch_size_cache, + nheads_k, + d, + dv, + device, + dtype, + dtype_ref, + ) + cache_seqlens = torch.randint( + 0 if new_kv else 1, + # If we don't use seqlen_q in the case of causal and rotary, cos/sin won't be long enough + ( + ( + seqlen_k + - (seqlen_q if (causal or local) and rotary_dim > 1 else seqlen_new) + + 1 + ) + if new_kv + else (seqlen_k + 1) + ), + (batch_size,), + dtype=torch.int32, + device=device, + ) + if has_leftpad: + cache_leftpad = torch.cat( + [ + ( + torch.randint( + 0, + cache_seqlens[i].item(), + (1,), + dtype=torch.int32, + device=device, + ) + if cache_seqlens[i].item() > 0 + else torch.zeros(1, dtype=torch.int32, device=device) + ) + for i in range(batch_size) + ] + ) + else: + cache_leftpad = None + if has_batch_idx: + cache_batch_idx = torch.randperm( + batch_size_cache, dtype=torch.int32, device=device + )[:batch_size] + else: + cache_batch_idx = None + arange = rearrange(torch.arange(seqlen_k, device=device), "s -> 1 s") + cache_seqlens_expanded = rearrange(cache_seqlens, "b -> b 1") + if not new_kv: + key_padding_mask = arange < cache_seqlens_expanded + else: + k_new_seqlens = ( + key_new_padding_mask.sum(-1, keepdims=True) if varlen_q else seqlen_new + ) + key_padding_mask = arange < cache_seqlens_expanded + k_new_seqlens + if has_leftpad: + key_padding_mask = torch.logical_and( + key_padding_mask, + arange >= cache_leftpad.unsqueeze(-1).expand(-1, seqlen_k), + ) + # cache_seqlens = torch.tensor([64], dtype=torch.int32, device=device) + rotary_seqlens = cache_seqlens if not has_rotary_seqlens else cache_seqlens // 2 + if rotary_dim > 0: + angle = ( + torch.rand( + seqlen_k if page_size is None else num_blocks * page_size, + rotary_dim // 2, + device=device, + ) + * 2 + * math.pi + ) + cos = torch.cos(angle).to(dtype=dtype_ref).to(dtype).to(dtype_ref) + sin = torch.sin(angle).to(dtype=dtype_ref).to(dtype).to(dtype_ref) + if causal or local: + q_ro = apply_rotary_emb( + q, + cos, + sin, + seqlen_offsets=rotary_seqlens, + interleaved=rotary_interleaved, + ) + else: + q_ro = rearrange( + apply_rotary_emb( + rearrange(q, "b s h d -> b 1 (s h) d"), + cos, + sin, + seqlen_offsets=rotary_seqlens, + interleaved=rotary_interleaved, + ), + "b 1 (s h) d -> b s h d", + s=seqlen_q, + ) + # q_ro = q + k_ro = apply_rotary_emb( + k, + cos, + sin, + seqlen_offsets=rotary_seqlens, + interleaved=rotary_interleaved, + ) + else: + cos, sin = None, None + q_ro, k_ro = q, k + # k_cache[:, 64:] = -1 + k_cache_ref = ( + k_cache if not has_batch_idx else k_cache[cache_batch_idx] + ).clone() + v_cache_ref = ( + v_cache if not has_batch_idx else v_cache[cache_batch_idx] + ).clone() + if new_kv: + update_mask = torch.logical_and( + cache_seqlens_expanded <= arange, + arange < cache_seqlens_expanded + k_new_seqlens, + ) + k_to_update = rearrange(k_ro, "b s ... -> (b s) ...") + v_to_update = rearrange(v, "b s ... -> (b s) ...") + if varlen_q: + k_to_update = k_to_update[indices_k] + v_to_update = v_to_update[indices_k] + k_cache_ref[update_mask] = k_to_update + v_cache_ref[update_mask] = v_to_update + k_cache_rep = repeat( + k_cache_ref, "b s h d -> b s (h g) d", g=nheads // nheads_k + ) + v_cache_rep = repeat( + v_cache_ref, "b s h d -> b s (h g) d", g=nheads // nheads_k + ) + out_ref, _ = attention_ref( + q_ro, + k_cache_rep, + v_cache_rep, + query_padding_mask, + key_padding_mask, + causal=causal, + qv=qv, + window_size=window_size, + learnable_sink=learnable_sink, + attention_chunk=attention_chunk, + key_leftpad=cache_leftpad, + ) + out_pt, _ = attention_ref( + q_ro, + k_cache_rep, + v_cache_rep, + query_padding_mask, + key_padding_mask, + causal=causal, + qv=qv, + window_size=window_size, + learnable_sink=learnable_sink, + attention_chunk=attention_chunk, + upcast=False, + reorder_ops=True, + key_leftpad=cache_leftpad, + intermediate_dtype=dtype if dtype == torch.float8_e4m3fn else None, + ) + q = q.to(dtype) + q_unpad = q_unpad.to(dtype) if varlen_q else None + k_cache = k_cache.to(dtype) + v_cache = v_cache.to(dtype) + k_cache_paged = k_cache_paged.to(dtype) if page_size is not None else None + v_cache_paged = v_cache_paged.to(dtype) if page_size is not None else None + k = k.to(dtype) if k is not None else None + v = v.to(dtype) if v is not None else None + k_unpad = k_unpad.to(dtype) if k_unpad is not None else None + v_unpad = v_unpad.to(dtype) if v_unpad is not None else None + qv = qv.to(dtype) if qv is not None else None + qv_unpad = qv_unpad.to(dtype) if (varlen_q and qv is not None) else None + cos = cos.to(dtype) if cos is not None else None + sin = sin.to(dtype) if sin is not None else None + k_cache_saved = k_cache.clone() if page_size is None else k_cache_paged.clone() + v_cache_saved = v_cache.clone() if page_size is None else v_cache_paged.clone() + # num_splits_vals = [1, 0] + num_splits_vals = [1] + # precompute_metadata_vals = [False, True] + precompute_metadata_vals = [False] + for num_splits, precompute_metadata in itertools.product( + num_splits_vals, precompute_metadata_vals + ): + # if precompute_metadata: + # scheduler_metadata = get_scheduler_metadata( + # batch_size, max_seqlen_q if varlen_q else seqlen_q, seqlen_k, nheads, nheads_k, d, + # cache_seqlens, q.dtype, headdim_v=dv, cu_seqlens_q=cu_seqlens_q, + # cu_seqlens_k_new=cu_seqlens_k_new, cache_leftpad=cache_leftpad, + # max_seqlen_k_new=seqlen_new, page_size=page_size, + # causal=causal, window_size=window_size, attention_chunk=attention_chunk, + # num_splits=num_splits + # ) + # else: + # scheduler_metadata = None + scheduler_metadata = None + # Repeat to test metadata reuse + for _ in range(1 if not precompute_metadata else 2): + if page_size is None: + k_cache.copy_(k_cache_saved) + v_cache.copy_(v_cache_saved) + else: + k_cache_paged.copy_(k_cache_saved) + v_cache_paged.copy_(v_cache_saved) + # For FA4, use flash_attn_varlen_func directly instead of flash_attn_with_kvcache + # This matches the pattern from the original FA4 test + out, lse = flash_attn_varlen_func( + q if not varlen_q else q_unpad, + k_cache if page_size is None else k_cache_paged, + v_cache if page_size is None else v_cache_paged, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=None, # FA4 doesn't use cu_seqlens_k for KV cache + # max_seqlen_q and max_seqlen_k not needed for FA4 + seqused_k=cache_seqlens, # Use cache_seqlens as seqused_k + page_table=page_table, + causal=causal, + window_size=window_size, + sinks=learnable_sink, # FA4 uses learnable_sink, not sinks + softcap=0.0, + pack_gqa=None, + return_softmax_lse=True, + ver=4, + ) + if varlen_q: + out = output_pad_fn(out) + # out = flash_attn_with_kvcache( + # q, k_cache, v_cache, cache_seqlens=cache_seqlens, causal=causal, window_size=window_size + # ) + # out = flash_attn_with_kvcache(q, k_cache, v_cache, causal=causal, window_size=window_size) + # qk = torch.einsum("bqhd,bkhd->bhqk", q, k_cache_ref) + # m = qk.amax(-1, keepdim=True) + # s_tmp = torch.exp((qk - m) / math.sqrt(d)) + # o1 = torch.einsum('bhst,bthd->bshd', s_tmp, v_cache_ref) + # lse_ref = torch.logsumexp(qk / math.sqrt(d), -1) + # probs = torch.softmax(qk, dim=-1) + print(f"Output max diff: {(out - out_ref).abs().max().item()}") + print(f"Output mean diff: {(out - out_ref).abs().mean().item()}") + print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}") + print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}") + # breakpoint() + + # Check that FlashAttention's numerical error is at most twice the numerical error + # of a Pytorch implementation. + if new_kv: + if page_size is None: + k_cache_select = ( + k_cache.to(dtype_ref) + if not has_batch_idx + else k_cache.to(dtype_ref)[cache_batch_idx] + ) + v_cache_select = ( + v_cache.to(dtype_ref) + if not has_batch_idx + else v_cache.to(dtype_ref)[cache_batch_idx] + ) + else: + k_cache_select = rearrange( + k_cache_paged.to(dtype_ref)[ + ( + page_table + if not has_batch_idx + else page_table[cache_batch_idx] + ).flatten() + ], + "(b nblocks) block_size ... -> b (nblocks block_size) ...", + b=batch_size, + )[:, :seqlen_k].to(dtype_ref) + v_cache_select = rearrange( + v_cache_paged.to(dtype_ref)[ + ( + page_table + if not has_batch_idx + else page_table[cache_batch_idx] + ).flatten() + ], + "(b nblocks) block_size ... -> b (nblocks block_size) ...", + b=batch_size, + )[:, :seqlen_k].to(dtype_ref) + k_cache_ref = k_cache_ref.to(dtype).to(dtype_ref) + v_cache_ref = v_cache_ref.to(dtype).to(dtype_ref) + if dtype is not torch.float8_e4m3fn: + assert torch.equal(v_cache_select, v_cache_ref) + else: + assert torch.allclose( + v_cache_select, v_cache_ref, rtol=1e-3, atol=1e-3 + ) + # breakpoint() + # if rotary_dim == 0 and dtype is not torch.float8_e4m3fn: + if rotary_dim == 0: + assert torch.equal(k_cache_select, k_cache_ref) + else: + # if not torch.allclose(k_cache_select, k_cache_ref, rtol=1e-3, atol=1e-3): + # breakpoint() + if dtype is not torch.float8_e4m3fn: + assert torch.allclose( + k_cache_select, k_cache_ref, rtol=1e-3, atol=1e-3 + ) + else: + assert torch.allclose( + k_cache_select, k_cache_ref, rtol=1e-1, atol=1e-1 + ) + mult = 4 if dtype == torch.float8_e4m3fn else 2 + assert (out - out_ref).abs().max().item() <= mult * ( + out_pt - out_ref + ).abs().max().item() + 1e-5 + mult_mean = 3 if dtype == torch.float8_e4m3fn else 1.5 + assert (out - out_ref).abs().mean().item() <= mult_mean * ( + out_pt - out_ref + ).abs().mean().item() + + +def _generate_block_kvcache( + seqlen_k, page_size, batch_size, nheads_k, d, dv, device, dtype, dtype_ref +): + num_blocks = math.ceil(seqlen_k / page_size) * batch_size * 3 + k_cache_paged = ( + torch.randn(num_blocks, page_size, nheads_k, d, device=device, dtype=dtype_ref) + .to(dtype) + .to(dtype_ref) + ) + v_cache_paged = ( + torch.randn(num_blocks, page_size, nheads_k, dv, device=device, dtype=dtype_ref) + .to(dtype) + .to(dtype_ref) + ) + page_table = rearrange( + torch.randperm(num_blocks, dtype=torch.int32, device=device), + "(b nblocks) -> b nblocks", + b=batch_size, + ) + k_cache = rearrange( + k_cache_paged[page_table.flatten()], + "(b nblocks) block_size ... -> b (nblocks block_size) ...", + b=batch_size, + )[:, :seqlen_k] + v_cache = rearrange( + v_cache_paged[page_table.flatten()], + "(b nblocks) block_size ... -> b (nblocks block_size) ...", + b=batch_size, + )[:, :seqlen_k] + return k_cache, v_cache, page_table, k_cache_paged, v_cache_paged, num_blocks + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_fused_add_rmsnorm.py b/asian_ai/performance/SGLang/test/registered/jit/test_fused_add_rmsnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..28ab15add96f8255350883ad5a5483fd037201df --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_fused_add_rmsnorm.py @@ -0,0 +1,105 @@ +import itertools +import sys + +import pytest +import torch + +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def sglang_jit_fused_add_rmsnorm( + input: torch.Tensor, + residual: torch.Tensor, + weight: torch.Tensor, + eps: float, + *, + cast_x_before_out_mul: bool = False, +) -> None: + from sglang.jit_kernel.norm import fused_add_rmsnorm + + fused_add_rmsnorm( + input, residual, weight, eps, cast_x_before_out_mul=cast_x_before_out_mul + ) + + +def flashinfer_fused_add_rmsnorm( + input: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, eps: float +) -> None: + from flashinfer.norm import fused_add_rmsnorm + + fused_add_rmsnorm(input, residual, weight, eps=eps) + + +def forward_native_hf_reference( + x: torch.Tensor, residual: torch.Tensor, w: torch.Tensor, eps: float +) -> tuple[torch.Tensor, torch.Tensor]: + sum_fp32 = x.to(torch.float32) + residual.to(torch.float32) + residual_out = sum_fp32.to(x.dtype) + variance = sum_fp32.pow(2).mean(-1, keepdim=True) + out = w * (sum_fp32 * torch.rsqrt(variance + eps)).to(x.dtype) + return out, residual_out + + +BS_LIST = [2**n for n in range(0, 14)] +BS_LIST += [x + 1 + i for i, x in enumerate(BS_LIST)] +HIDDEN_SIZE_LIST = [512, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 7168, 8192] +FUSED_ADD_RMSNORM_CASES = get_ci_test_range( + list(itertools.product(BS_LIST, HIDDEN_SIZE_LIST)), + [ + (1, 512), + (18, 4096), + (38, 4096), + (39, 4096), + (39, 5120), + (39, 8192), + (44, 8192), + (89, 4096), + ], +) +DEVICE = "cuda" +DTYPE = torch.bfloat16 +EPS = torch.finfo(torch.bfloat16).eps + + +@pytest.mark.parametrize( + "batch_size,hidden_size,cast_x_before_out_mul", + [(bs, hs, cast) for bs, hs in FUSED_ADD_RMSNORM_CASES for cast in [False, True]], +) +def test_fused_add_rmsnorm( + batch_size: int, hidden_size: int, cast_x_before_out_mul: bool +) -> None: + torch.manual_seed(0) + input = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=DTYPE) + residual = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=DTYPE) + weight = torch.randn(hidden_size, device=DEVICE, dtype=DTYPE) + + input_sglang = input.clone() + residual_sglang = residual.clone() + sglang_jit_fused_add_rmsnorm( + input_sglang, + residual_sglang, + weight, + EPS, + cast_x_before_out_mul=cast_x_before_out_mul, + ) + + if cast_x_before_out_mul: + out_ref, residual_ref = forward_native_hf_reference( + input, residual, weight, EPS + ) + else: + input_ref = input.clone() + residual_ref_buf = residual.clone() + flashinfer_fused_add_rmsnorm(input_ref, residual_ref_buf, weight, EPS) + out_ref, residual_ref = input_ref, residual_ref_buf + + torch.testing.assert_close(input_sglang, out_ref, atol=1e-2, rtol=1e-2) + torch.testing.assert_close(residual_sglang, residual_ref, atol=1e-2, rtol=1e-2) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_fused_eh_norm.py b/asian_ai/performance/SGLang/test/registered/jit/test_fused_eh_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..54eca757f4b40561ce9e9e90bc3957c09929084a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_fused_eh_norm.py @@ -0,0 +1,122 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.fused_eh_norm import fused_eh_norm +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or torch.version.cuda is None, + reason="fused_eh_norm requires CUDA", +) + + +def _reference( + inputs_embeds: torch.Tensor, + previous_hidden: torch.Tensor, + enorm_weight: torch.Tensor, + hnorm_weight: torch.Tensor, + eps: float, +) -> torch.Tensor: + embeds = inputs_embeds.float() + prev = previous_hidden.float() + embeds_var = embeds.pow(2).mean(dim=-1, keepdim=True) + prev_var = prev.pow(2).mean(dim=-1, keepdim=True) + return torch.cat( + ( + (embeds * torch.rsqrt(embeds_var + eps) * enorm_weight.float()).to( + inputs_embeds.dtype + ), + (prev * torch.rsqrt(prev_var + eps) * hnorm_weight.float()).to( + previous_hidden.dtype + ), + ), + dim=-1, + ) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("hidden_size", [6144, 7168]) +@pytest.mark.parametrize("num_tokens", [1, 6, 128]) +def test_fused_eh_norm_matches_reference( + dtype: torch.dtype, hidden_size: int, num_tokens: int +): + torch.manual_seed(0) + eps = 1e-6 + inputs_embeds = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype) + previous_hidden = torch.randn_like(inputs_embeds) + enorm_weight = torch.randn(hidden_size, device="cuda", dtype=dtype) + hnorm_weight = torch.randn(hidden_size, device="cuda", dtype=dtype) + + actual = fused_eh_norm( + inputs_embeds, previous_hidden, enorm_weight, hnorm_weight, eps + ) + expected = _reference( + inputs_embeds, previous_hidden, enorm_weight, hnorm_weight, eps + ) + torch.testing.assert_close(actual.float(), expected.float(), rtol=1e-2, atol=1e-2) + + +def test_fused_eh_norm_zero_tokens(): + hidden_size = 7168 + inputs_embeds = torch.empty(0, hidden_size, device="cuda", dtype=torch.bfloat16) + previous_hidden = torch.empty_like(inputs_embeds) + enorm_weight = torch.randn(hidden_size, device="cuda", dtype=torch.bfloat16) + hnorm_weight = torch.randn(hidden_size, device="cuda", dtype=torch.bfloat16) + + actual = fused_eh_norm( + inputs_embeds, previous_hidden, enorm_weight, hnorm_weight, 1e-6 + ) + assert actual.shape == (0, hidden_size * 2) + assert actual.dtype == inputs_embeds.dtype + assert actual.device == inputs_embeds.device + + +def test_fused_eh_norm_row_strided_inputs(): + torch.manual_seed(1) + hidden_size = 7168 + eps = 1e-6 + base = torch.randn(12, hidden_size, device="cuda", dtype=torch.bfloat16) + prev_base = torch.randn_like(base) + inputs_embeds = base[::2] + previous_hidden = prev_base[::2] + enorm_weight = torch.randn(hidden_size, device="cuda", dtype=torch.bfloat16) + hnorm_weight = torch.randn(hidden_size, device="cuda", dtype=torch.bfloat16) + + actual = fused_eh_norm( + inputs_embeds, previous_hidden, enorm_weight, hnorm_weight, eps + ) + expected = _reference( + inputs_embeds, previous_hidden, enorm_weight, hnorm_weight, eps + ) + torch.testing.assert_close(actual.float(), expected.float(), rtol=1e-2, atol=1e-2) + + +def test_fused_eh_norm_rejects_unsupported_dtype(): + hidden_size = 7168 + inputs_embeds = torch.randn(1, hidden_size, device="cuda", dtype=torch.float32) + previous_hidden = torch.randn_like(inputs_embeds) + enorm_weight = torch.randn(hidden_size, device="cuda", dtype=torch.float32) + hnorm_weight = torch.randn(hidden_size, device="cuda", dtype=torch.float32) + + with pytest.raises(RuntimeError, match="unsupported dtype"): + fused_eh_norm(inputs_embeds, previous_hidden, enorm_weight, hnorm_weight, 1e-6) + + +def test_fused_eh_norm_rejects_unsupported_hidden_size(): + hidden_size = 5000 + inputs_embeds = torch.randn(1, hidden_size, device="cuda", dtype=torch.bfloat16) + previous_hidden = torch.randn_like(inputs_embeds) + enorm_weight = torch.randn(hidden_size, device="cuda", dtype=torch.bfloat16) + hnorm_weight = torch.randn(hidden_size, device="cuda", dtype=torch.bfloat16) + + with pytest.raises(RuntimeError, match="unsupported hidden_size"): + fused_eh_norm(inputs_embeds, previous_hidden, enorm_weight, hnorm_weight, 1e-6) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_fused_metadata_copy.py b/asian_ai/performance/SGLang/test/registered/jit/test_fused_metadata_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..5324875b9f05c569082ab0b6b4d354dd794a286e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_fused_metadata_copy.py @@ -0,0 +1,1074 @@ +""" +Comprehensive tests for JIT-compiled fused metadata copy kernels. + +This test suite verifies: +1. Single-backend fused kernel (fused_metadata_copy_cuda) - all forward modes +2. Multi-backend fused kernel (fused_metadata_copy_multi_cuda) - 3 backends at once +3. Correctness against reference implementations +4. Performance benchmarks and speedup measurements +""" + +import sys +import time + +import pytest +import torch + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=100, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=400, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=100, suite="nightly-amd-kernel-1-gpu", nightly=True) + +# ============================================================================= +# Helper Functions +# ============================================================================= + + +def create_test_metadata( + bs: int, + max_len: int, + max_seqlen_k: int, + seqlens_expanded_size: int, + has_real_page_table: bool = False, + has_flashmla: bool = False, + device: str = "cuda", +): + """Create test metadata tensors matching DSA backend structure.""" + # Basic tensors (always present) + cache_seqlens_src = torch.randint( + 1, max_len, (bs,), dtype=torch.int32, device=device + ) + cu_seqlens_k_src = torch.zeros(bs + 1, dtype=torch.int32, device=device) + cu_seqlens_k_src[1:] = torch.cumsum(cache_seqlens_src, dim=0) + + page_indices_src = torch.randint( + 0, 1000, (bs, max_len), dtype=torch.int32, device=device + ) + dsa_cache_seqlens_src = torch.randint( + 1, max_len, (seqlens_expanded_size,), dtype=torch.int32, device=device + ) + seqlens_expanded_src = torch.randint( + 1, max_seqlen_k, (seqlens_expanded_size,), dtype=torch.int32, device=device + ) + dsa_cu_seqlens_k_src = torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ) + dsa_cu_seqlens_k_src[1:] = torch.cumsum(dsa_cache_seqlens_src, dim=0) + + # Destination tensors + cache_seqlens_dst = torch.zeros(bs, dtype=torch.int32, device=device) + cu_seqlens_k_dst = torch.zeros(bs + 1, dtype=torch.int32, device=device) + page_table_1_dst = torch.zeros((bs, max_len + 16), dtype=torch.int32, device=device) + dsa_cache_seqlens_dst = torch.zeros( + seqlens_expanded_size, dtype=torch.int32, device=device + ) + dsa_seqlens_expanded_dst = torch.zeros( + seqlens_expanded_size, dtype=torch.int32, device=device + ) + dsa_cu_seqlens_k_dst = torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ) + + # Optional tensors + real_page_table_src = None + real_page_table_dst = None + if has_real_page_table: + real_page_table_cols = max_len // 2 + real_page_table_src = torch.randint( + 0, 1000, (bs, real_page_table_cols), dtype=torch.int32, device=device + ) + real_page_table_dst = torch.zeros( + (bs, real_page_table_cols + 8), dtype=torch.int32, device=device + ) + + flashmla_num_splits_src = None + flashmla_num_splits_dst = None + flashmla_metadata_src = None + flashmla_metadata_dst = None + if has_flashmla: + flashmla_num_splits_src = torch.randint( + 1, 10, (seqlens_expanded_size + 1,), dtype=torch.int32, device=device + ) + flashmla_num_splits_dst = torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ) + # FlashMLA metadata is typically (num_sm_parts, TileSchedulerMetaDataSize) + # For testing, we use a simplified size + flashmla_metadata_size = 128 + flashmla_metadata_src = torch.randint( + 0, 100, (flashmla_metadata_size,), dtype=torch.int32, device=device + ) + flashmla_metadata_dst = torch.zeros( + flashmla_metadata_size, dtype=torch.int32, device=device + ) + + return { + "src": { + "cache_seqlens": cache_seqlens_src, + "cu_seqlens_k": cu_seqlens_k_src, + "page_indices": page_indices_src, + "dsa_cache_seqlens": dsa_cache_seqlens_src, + "seqlens_expanded": seqlens_expanded_src, + "dsa_cu_seqlens_k": dsa_cu_seqlens_k_src, + "real_page_table": real_page_table_src, + "flashmla_num_splits": flashmla_num_splits_src, + "flashmla_metadata": flashmla_metadata_src, + }, + "dst": { + "cache_seqlens": cache_seqlens_dst, + "cu_seqlens_k": cu_seqlens_k_dst, + "page_table_1": page_table_1_dst, + "dsa_cache_seqlens": dsa_cache_seqlens_dst, + "dsa_seqlens_expanded": dsa_seqlens_expanded_dst, + "dsa_cu_seqlens_k": dsa_cu_seqlens_k_dst, + "real_page_table": real_page_table_dst, + "flashmla_num_splits": flashmla_num_splits_dst, + "flashmla_metadata": flashmla_metadata_dst, + }, + } + + +def reference_copy_decode(src, dst, max_len): + """Reference implementation: individual .copy_() for DECODE mode.""" + bs = src["cache_seqlens"].shape[0] + dst["cache_seqlens"].copy_(src["cache_seqlens"]) + dst["cu_seqlens_k"][1:].copy_(src["cu_seqlens_k"][1:]) + dst["page_table_1"][:, :max_len].copy_(src["page_indices"]) + dst["dsa_cache_seqlens"].copy_(src["dsa_cache_seqlens"]) + dst["dsa_cu_seqlens_k"][1 : bs + 1].copy_(src["dsa_cu_seqlens_k"][1 : bs + 1]) + + if src["real_page_table"] is not None: + rows, cols = src["real_page_table"].shape + dst["real_page_table"][:rows, :cols].copy_(src["real_page_table"]) + + if src["flashmla_num_splits"] is not None: + flashmla_size = bs + 1 + dst["flashmla_num_splits"][:flashmla_size].copy_( + src["flashmla_num_splits"][:flashmla_size] + ) + + if src["flashmla_metadata"] is not None: + dst["flashmla_metadata"].copy_(src["flashmla_metadata"]) + + +def reference_copy_target_verify(src, dst, max_seqlen_k, seqlens_expanded_size): + """Reference implementation: individual .copy_() for TARGET_VERIFY mode.""" + bs = src["cache_seqlens"].shape[0] + dst["cache_seqlens"].copy_(src["cache_seqlens"]) + dst["cu_seqlens_k"][1:].copy_(src["cu_seqlens_k"][1:]) + + rows, cols = src["page_indices"].shape + dst["page_table_1"][:rows, :cols].copy_(src["page_indices"]) + dst["dsa_seqlens_expanded"][:seqlens_expanded_size].copy_(src["seqlens_expanded"]) + dst["dsa_cache_seqlens"][:seqlens_expanded_size].copy_(src["dsa_cache_seqlens"]) + dst["dsa_cu_seqlens_k"][1 : seqlens_expanded_size + 1].copy_( + src["dsa_cu_seqlens_k"][1 : seqlens_expanded_size + 1] + ) + + if src["real_page_table"] is not None: + rows, cols = src["real_page_table"].shape + dst["real_page_table"][:rows, :cols].copy_(src["real_page_table"]) + + if src["flashmla_num_splits"] is not None: + flashmla_size = seqlens_expanded_size + 1 + dst["flashmla_num_splits"][:flashmla_size].copy_( + src["flashmla_num_splits"][:flashmla_size] + ) + + if src["flashmla_metadata"] is not None: + dst["flashmla_metadata"].copy_(src["flashmla_metadata"]) + + +def reference_copy_draft_extend(src, dst, max_seqlen_k, seqlens_expanded_size): + """Reference implementation: individual .copy_() for DRAFT_EXTEND mode.""" + bs = src["cache_seqlens"].shape[0] + dst["cache_seqlens"].copy_(src["cache_seqlens"]) + dst["cu_seqlens_k"][1:].copy_(src["cu_seqlens_k"][1:]) + + rows, cols = src["page_indices"].shape + dst["page_table_1"][:rows, :cols].copy_(src["page_indices"]) + dst["dsa_seqlens_expanded"][:seqlens_expanded_size].copy_(src["seqlens_expanded"]) + dst["dsa_cache_seqlens"][:seqlens_expanded_size].copy_(src["dsa_cache_seqlens"]) + dst["dsa_cu_seqlens_k"][1 : seqlens_expanded_size + 1].copy_( + src["dsa_cu_seqlens_k"][1 : seqlens_expanded_size + 1] + ) + + if src["real_page_table"] is not None: + rows, cols = src["real_page_table"].shape + dst["real_page_table"][:rows, :cols].copy_(src["real_page_table"]) + + if src["flashmla_num_splits"] is not None: + flashmla_size = seqlens_expanded_size + 1 + dst["flashmla_num_splits"][:flashmla_size].copy_( + src["flashmla_num_splits"][:flashmla_size] + ) + + if src["flashmla_metadata"] is not None: + dst["flashmla_metadata"].copy_(src["flashmla_metadata"]) + + +# ============================================================================= +# Single-Backend Kernel Tests +# ============================================================================= + + +def test_fused_metadata_copy_dtype_validation(): + """Test that dtype validation rejects non-int32 tensors.""" + if not torch.cuda.is_available(): + pytest.skip("CUDA not available") + + from sglang.jit_kernel.fused_metadata_copy import fused_metadata_copy_cuda + + bs = 2 + max_len = 128 + max_seqlen_k = 256 + seqlens_expanded_size = bs + device = "cuda" + + # Create tensors with WRONG dtype (int64 instead of int32) + cache_seqlens_src_wrong = torch.randint( + 1, max_len, (bs,), dtype=torch.int64, device=device + ) + cu_seqlens_k_src = torch.zeros(bs + 1, dtype=torch.int32, device=device) + page_indices_src = torch.randint( + 0, 1000, (bs, max_len), dtype=torch.int32, device=device + ) + dsa_cache_seqlens_src = torch.randint( + 1, max_len, (seqlens_expanded_size,), dtype=torch.int32, device=device + ) + seqlens_expanded_src = torch.randint( + 1, max_seqlen_k, (seqlens_expanded_size,), dtype=torch.int32, device=device + ) + dsa_cu_seqlens_k_src = torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ) + + # Destination tensors (correct dtype) + cache_seqlens_dst = torch.zeros(bs, dtype=torch.int32, device=device) + cu_seqlens_k_dst = torch.zeros(bs + 1, dtype=torch.int32, device=device) + page_table_1_dst = torch.zeros((bs, max_len + 16), dtype=torch.int32, device=device) + dsa_cache_seqlens_dst = torch.zeros( + seqlens_expanded_size, dtype=torch.int32, device=device + ) + dsa_seqlens_expanded_dst = torch.zeros( + seqlens_expanded_size, dtype=torch.int32, device=device + ) + dsa_cu_seqlens_k_dst = torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ) + + # Test 1: Wrong dtype for source tensor should raise RuntimeError + with pytest.raises(RuntimeError, match="must have dtype int32"): + fused_metadata_copy_cuda( + cache_seqlens_src_wrong, # Wrong dtype: int64 + cu_seqlens_k_src, + page_indices_src, + dsa_cache_seqlens_src, + seqlens_expanded_src, + dsa_cu_seqlens_k_src, + None, # real_page_table_src + None, # flashmla_num_splits_src + None, # flashmla_metadata_src + cache_seqlens_dst, + cu_seqlens_k_dst, + page_table_1_dst, + dsa_cache_seqlens_dst, + dsa_seqlens_expanded_dst, + dsa_cu_seqlens_k_dst, + None, # real_page_table_dst + None, # flashmla_num_splits_dst + None, # flashmla_metadata_dst + 0, # forward_mode + bs, + max_len, + max_seqlen_k, + seqlens_expanded_size, + ) + + # Test 2: Wrong dtype for destination tensor should also raise RuntimeError + cache_seqlens_src = torch.randint( + 1, max_len, (bs,), dtype=torch.int32, device=device + ) + cache_seqlens_dst_wrong = torch.zeros(bs, dtype=torch.int64, device=device) + + with pytest.raises(RuntimeError, match="must have dtype int32"): + fused_metadata_copy_cuda( + cache_seqlens_src, + cu_seqlens_k_src, + page_indices_src, + dsa_cache_seqlens_src, + seqlens_expanded_src, + dsa_cu_seqlens_k_src, + None, + None, + None, + cache_seqlens_dst_wrong, # Wrong dtype: int64 + cu_seqlens_k_dst, + page_table_1_dst, + dsa_cache_seqlens_dst, + dsa_seqlens_expanded_dst, + dsa_cu_seqlens_k_dst, + None, + None, + None, + 0, + bs, + max_len, + max_seqlen_k, + seqlens_expanded_size, + ) + + +@pytest.mark.parametrize("bs", [1, 2, 4, 8]) +@pytest.mark.parametrize( + "forward_mode", [0] +) # DECODE mode only (other modes not fully tested yet) +@pytest.mark.parametrize("has_real_page_table", [False, True]) +@pytest.mark.parametrize("has_flashmla", [False, True]) +def test_fused_metadata_copy(bs, forward_mode, has_real_page_table, has_flashmla): + """Test fused metadata copy kernel against reference implementation.""" + if not torch.cuda.is_available(): + pytest.skip("CUDA not available") + + from sglang.jit_kernel.fused_metadata_copy import fused_metadata_copy_cuda + + max_len = 128 + max_seqlen_k = 256 + seqlens_expanded_size = bs if forward_mode == 0 else bs * 2 + + # Create test data + data = create_test_metadata( + bs=bs, + max_len=max_len, + max_seqlen_k=max_seqlen_k, + seqlens_expanded_size=seqlens_expanded_size, + has_real_page_table=has_real_page_table, + has_flashmla=has_flashmla, + ) + + # Create separate destination tensors for reference and fused kernel + dst_ref = {k: v.clone() if v is not None else None for k, v in data["dst"].items()} + dst_fused = { + k: v.clone() if v is not None else None for k, v in data["dst"].items() + } + + # Run reference implementation + if forward_mode == 0: # DECODE + reference_copy_decode(data["src"], dst_ref, max_len) + elif forward_mode == 1: # TARGET_VERIFY + reference_copy_target_verify( + data["src"], dst_ref, max_seqlen_k, seqlens_expanded_size + ) + else: # DRAFT_EXTEND + reference_copy_draft_extend( + data["src"], dst_ref, max_seqlen_k, seqlens_expanded_size + ) + + # Run fused kernel + fused_metadata_copy_cuda( + data["src"]["cache_seqlens"], + data["src"]["cu_seqlens_k"], + data["src"]["page_indices"], + data["src"]["dsa_cache_seqlens"], + data["src"]["seqlens_expanded"], + data["src"]["dsa_cu_seqlens_k"], + data["src"]["real_page_table"], + data["src"]["flashmla_num_splits"], + data["src"]["flashmla_metadata"], + dst_fused["cache_seqlens"], + dst_fused["cu_seqlens_k"], + dst_fused["page_table_1"], + dst_fused["dsa_cache_seqlens"], + dst_fused["dsa_seqlens_expanded"], + dst_fused["dsa_cu_seqlens_k"], + dst_fused["real_page_table"], + dst_fused["flashmla_num_splits"], + dst_fused["flashmla_metadata"], + forward_mode, + bs, + max_len, + max_seqlen_k, + seqlens_expanded_size, + ) + + # Compare results + assert torch.equal( + dst_ref["cache_seqlens"], dst_fused["cache_seqlens"] + ), "cache_seqlens mismatch" + assert torch.equal( + dst_ref["cu_seqlens_k"], dst_fused["cu_seqlens_k"] + ), "cu_seqlens_k mismatch" + assert torch.equal( + dst_ref["page_table_1"], dst_fused["page_table_1"] + ), "page_table_1 mismatch" + assert torch.equal( + dst_ref["dsa_cache_seqlens"], dst_fused["dsa_cache_seqlens"] + ), "dsa_cache_seqlens mismatch" + assert torch.equal( + dst_ref["dsa_seqlens_expanded"], dst_fused["dsa_seqlens_expanded"] + ), "dsa_seqlens_expanded mismatch" + assert torch.equal( + dst_ref["dsa_cu_seqlens_k"], dst_fused["dsa_cu_seqlens_k"] + ), "dsa_cu_seqlens_k mismatch" + + if has_real_page_table: + assert torch.equal( + dst_ref["real_page_table"], dst_fused["real_page_table"] + ), "real_page_table mismatch" + + if has_flashmla: + assert torch.equal( + dst_ref["flashmla_num_splits"], dst_fused["flashmla_num_splits"] + ), "flashmla_num_splits mismatch" + assert torch.equal( + dst_ref["flashmla_metadata"], dst_fused["flashmla_metadata"] + ), "flashmla_metadata mismatch" + + +@pytest.mark.parametrize("bs", [16, 32]) +def test_fused_metadata_copy_large_batch(bs): + """Test with larger batch sizes.""" + if not torch.cuda.is_available(): + pytest.skip("CUDA not available") + + from sglang.jit_kernel.fused_metadata_copy import fused_metadata_copy_cuda + + forward_mode = 0 # DECODE + max_len = 128 + max_seqlen_k = 256 + seqlens_expanded_size = bs + + data = create_test_metadata( + bs=bs, + max_len=max_len, + max_seqlen_k=max_seqlen_k, + seqlens_expanded_size=seqlens_expanded_size, + has_real_page_table=True, + has_flashmla=True, + ) + + dst_ref = {k: v.clone() if v is not None else None for k, v in data["dst"].items()} + dst_fused = { + k: v.clone() if v is not None else None for k, v in data["dst"].items() + } + + reference_copy_decode(data["src"], dst_ref, max_len) + + fused_metadata_copy_cuda( + data["src"]["cache_seqlens"], + data["src"]["cu_seqlens_k"], + data["src"]["page_indices"], + data["src"]["dsa_cache_seqlens"], + data["src"]["seqlens_expanded"], + data["src"]["dsa_cu_seqlens_k"], + data["src"]["real_page_table"], + data["src"]["flashmla_num_splits"], + data["src"]["flashmla_metadata"], + dst_fused["cache_seqlens"], + dst_fused["cu_seqlens_k"], + dst_fused["page_table_1"], + dst_fused["dsa_cache_seqlens"], + dst_fused["dsa_seqlens_expanded"], + dst_fused["dsa_cu_seqlens_k"], + dst_fused["real_page_table"], + dst_fused["flashmla_num_splits"], + dst_fused["flashmla_metadata"], + forward_mode, + bs, + max_len, + max_seqlen_k, + seqlens_expanded_size, + ) + + # Verify all tensors match + for key in dst_ref: + if dst_ref[key] is not None: + assert torch.equal(dst_ref[key], dst_fused[key]), f"{key} mismatch" + + +# ============================================================================= +# Multi-Backend Kernel Tests +# ============================================================================= + + +def create_test_metadata_multi( + bs: int, + max_len: int, + seqlens_expanded_size: int, + has_real_page_table: bool = False, + has_flashmla: bool = False, + device: str = "cuda", +): + """Create test metadata tensors for multi-backend testing.""" + # Source tensors (precomputed metadata) + cache_seqlens_src = torch.randint( + 1, max_len, (bs,), dtype=torch.int32, device=device + ) + cu_seqlens_k_src = torch.zeros(bs + 1, dtype=torch.int32, device=device) + cu_seqlens_k_src[1:] = torch.cumsum(cache_seqlens_src, dim=0) + + page_indices_src = torch.randint( + 0, 1000, (bs, max_len), dtype=torch.int32, device=device + ) + dsa_cache_seqlens_src = torch.randint( + 1, max_len, (seqlens_expanded_size,), dtype=torch.int32, device=device + ) + dsa_cu_seqlens_k_src = torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ) + dsa_cu_seqlens_k_src[1:] = torch.cumsum(dsa_cache_seqlens_src, dim=0) + + # Optional tensors + real_page_table_src = None + if has_real_page_table: + real_page_table_cols = max_len // 2 + real_page_table_src = torch.randint( + 0, 1000, (bs, real_page_table_cols), dtype=torch.int32, device=device + ) + + flashmla_num_splits_src = None + flashmla_metadata_src = None + if has_flashmla: + flashmla_num_splits_src = torch.randint( + 1, 10, (seqlens_expanded_size + 1,), dtype=torch.int32, device=device + ) + flashmla_metadata_size = 128 + flashmla_metadata_src = torch.randint( + 0, 100, (flashmla_metadata_size,), dtype=torch.int32, device=device + ) + + # Create destination tensors for 3 backends + def create_dst_tensors(): + cache_seqlens_dst = torch.zeros(bs, dtype=torch.int32, device=device) + cu_seqlens_k_dst = torch.zeros(bs + 1, dtype=torch.int32, device=device) + page_table_1_dst = torch.zeros( + (bs, max_len + 16), dtype=torch.int32, device=device + ) + dsa_cache_seqlens_dst = torch.zeros( + seqlens_expanded_size, dtype=torch.int32, device=device + ) + dsa_cu_seqlens_k_dst = torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ) + + real_page_table_dst = None + if has_real_page_table: + real_page_table_cols = max_len // 2 + real_page_table_dst = torch.zeros( + (bs, real_page_table_cols + 8), dtype=torch.int32, device=device + ) + + flashmla_num_splits_dst = None + flashmla_metadata_dst = None + if has_flashmla: + flashmla_num_splits_dst = torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ) + flashmla_metadata_size = 128 + flashmla_metadata_dst = torch.zeros( + flashmla_metadata_size, dtype=torch.int32, device=device + ) + + return { + "cache_seqlens_int32": cache_seqlens_dst, + "cu_seqlens_k": cu_seqlens_k_dst, + "page_table_1": page_table_1_dst, + "dsa_cache_seqlens_int32": dsa_cache_seqlens_dst, + "dsa_cu_seqlens_k": dsa_cu_seqlens_k_dst, + "real_page_table": real_page_table_dst, + "flashmla_num_splits": flashmla_num_splits_dst, + "flashmla_metadata": flashmla_metadata_dst, + } + + return { + "src": { + "cache_seqlens": cache_seqlens_src, + "cu_seqlens_k": cu_seqlens_k_src, + "page_indices": page_indices_src, + "dsa_cache_seqlens": dsa_cache_seqlens_src, + "dsa_cu_seqlens_k": dsa_cu_seqlens_k_src, + "real_page_table": real_page_table_src, + "flashmla_num_splits": flashmla_num_splits_src, + "flashmla_metadata": flashmla_metadata_src, + }, + "dst0": create_dst_tensors(), + "dst1": create_dst_tensors(), + "dst2": create_dst_tensors(), + } + + +def reference_copy_for_loop(src, dst_list, bs, max_len): + """Reference implementation: for-loop calling copy for each backend.""" + for dst in dst_list: + # Simulate what init_forward_metadata_replay_cuda_graph_from_precomputed does + dst["cache_seqlens_int32"].copy_(src["cache_seqlens"]) + dst["cu_seqlens_k"][1:].copy_(src["cu_seqlens_k"][1:]) + dst["page_table_1"][:, :max_len].copy_(src["page_indices"]) + dst["dsa_cache_seqlens_int32"].copy_(src["dsa_cache_seqlens"]) + dst["dsa_cu_seqlens_k"][1 : bs + 1].copy_(src["dsa_cu_seqlens_k"][1 : bs + 1]) + + if src["real_page_table"] is not None: + rows, cols = src["real_page_table"].shape + dst["real_page_table"][:rows, :cols].copy_(src["real_page_table"]) + + if src["flashmla_num_splits"] is not None: + flashmla_size = bs + 1 + dst["flashmla_num_splits"][:flashmla_size].copy_( + src["flashmla_num_splits"][:flashmla_size] + ) + + if src["flashmla_metadata"] is not None: + dst["flashmla_metadata"].copy_(src["flashmla_metadata"]) + + +def test_fused_metadata_copy_multi_dtype_validation(): + """Test that dtype validation rejects non-int32 tensors for multi-backend kernel.""" + if not torch.cuda.is_available(): + pytest.skip("CUDA not available") + + from sglang.jit_kernel.fused_metadata_copy import fused_metadata_copy_multi_cuda + + bs = 2 + max_len = 128 + seqlens_expanded_size = bs + device = "cuda" + + # Create source tensors - one with WRONG dtype + cache_seqlens_src_wrong = torch.randint( + 1, max_len, (bs,), dtype=torch.int64, device=device # Wrong dtype! + ) + cu_seqlens_k_src = torch.zeros(bs + 1, dtype=torch.int32, device=device) + page_indices_src = torch.randint( + 0, 1000, (bs, max_len), dtype=torch.int32, device=device + ) + dsa_cache_seqlens_src = torch.randint( + 1, max_len, (seqlens_expanded_size,), dtype=torch.int32, device=device + ) + dsa_cu_seqlens_k_src = torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ) + + # Create destination tensors for 3 backends (all correct dtype) + def create_dst(): + return { + "cache_seqlens": torch.zeros(bs, dtype=torch.int32, device=device), + "cu_seqlens_k": torch.zeros(bs + 1, dtype=torch.int32, device=device), + "page_table_1": torch.zeros( + (bs, max_len + 16), dtype=torch.int32, device=device + ), + "dsa_cache_seqlens": torch.zeros( + seqlens_expanded_size, dtype=torch.int32, device=device + ), + "dsa_cu_seqlens_k": torch.zeros( + seqlens_expanded_size + 1, dtype=torch.int32, device=device + ), + } + + dst0 = create_dst() + dst1 = create_dst() + dst2 = create_dst() + + # Test: Wrong dtype for source tensor should raise RuntimeError + with pytest.raises(RuntimeError, match="must have dtype int32"): + fused_metadata_copy_multi_cuda( + cache_seqlens_src_wrong, # Wrong dtype: int64 + cu_seqlens_k_src, + page_indices_src, + dsa_cache_seqlens_src, + dsa_cu_seqlens_k_src, + None, # real_page_table_src + None, # flashmla_num_splits_src + None, # flashmla_metadata_src + # Backend 0 + dst0["cache_seqlens"], + dst0["cu_seqlens_k"], + dst0["page_table_1"], + dst0["dsa_cache_seqlens"], + dst0["dsa_cu_seqlens_k"], + None, + None, + None, + # Backend 1 + dst1["cache_seqlens"], + dst1["cu_seqlens_k"], + dst1["page_table_1"], + dst1["dsa_cache_seqlens"], + dst1["dsa_cu_seqlens_k"], + None, + None, + None, + # Backend 2 + dst2["cache_seqlens"], + dst2["cu_seqlens_k"], + dst2["page_table_1"], + dst2["dsa_cache_seqlens"], + dst2["dsa_cu_seqlens_k"], + None, + None, + None, + # Parameters + bs, + max_len, + seqlens_expanded_size, + ) + + +@pytest.mark.parametrize("bs", [1, 2, 4, 8, 16]) +@pytest.mark.parametrize("has_real_page_table", [False, True]) +@pytest.mark.parametrize("has_flashmla", [False, True]) +def test_fused_metadata_copy_multi(bs, has_real_page_table, has_flashmla): + """Test fused multi-backend metadata copy kernel against for-loop version.""" + if not torch.cuda.is_available(): + pytest.skip("CUDA not available") + + from sglang.jit_kernel.fused_metadata_copy import fused_metadata_copy_multi_cuda + + max_len = 128 + seqlens_expanded_size = bs + + # Create test data + data = create_test_metadata_multi( + bs=bs, + max_len=max_len, + seqlens_expanded_size=seqlens_expanded_size, + has_real_page_table=has_real_page_table, + has_flashmla=has_flashmla, + ) + + # Create separate destination tensors for reference (for-loop) and fused kernel + dst_ref_0 = { + k: v.clone() if v is not None else None for k, v in data["dst0"].items() + } + dst_ref_1 = { + k: v.clone() if v is not None else None for k, v in data["dst1"].items() + } + dst_ref_2 = { + k: v.clone() if v is not None else None for k, v in data["dst2"].items() + } + + dst_fused_0 = { + k: v.clone() if v is not None else None for k, v in data["dst0"].items() + } + dst_fused_1 = { + k: v.clone() if v is not None else None for k, v in data["dst1"].items() + } + dst_fused_2 = { + k: v.clone() if v is not None else None for k, v in data["dst2"].items() + } + + # Run reference implementation (for-loop) + torch.cuda.synchronize() + loop_start = time.perf_counter() + reference_copy_for_loop(data["src"], [dst_ref_0, dst_ref_1, dst_ref_2], bs, max_len) + torch.cuda.synchronize() + loop_end = time.perf_counter() + loop_time = loop_end - loop_start + + # Run fused kernel + torch.cuda.synchronize() + fused_start = time.perf_counter() + fused_metadata_copy_multi_cuda( + # Source tensors + data["src"]["cache_seqlens"], + data["src"]["cu_seqlens_k"], + data["src"]["page_indices"], + data["src"]["dsa_cache_seqlens"], + data["src"]["dsa_cu_seqlens_k"], + data["src"]["real_page_table"], + data["src"]["flashmla_num_splits"], + data["src"]["flashmla_metadata"], + # Destination tensors for backend 0 + dst_fused_0["cache_seqlens_int32"], + dst_fused_0["cu_seqlens_k"], + dst_fused_0["page_table_1"], + dst_fused_0["dsa_cache_seqlens_int32"], + dst_fused_0["dsa_cu_seqlens_k"], + dst_fused_0["real_page_table"], + dst_fused_0["flashmla_num_splits"], + dst_fused_0["flashmla_metadata"], + # Destination tensors for backend 1 + dst_fused_1["cache_seqlens_int32"], + dst_fused_1["cu_seqlens_k"], + dst_fused_1["page_table_1"], + dst_fused_1["dsa_cache_seqlens_int32"], + dst_fused_1["dsa_cu_seqlens_k"], + dst_fused_1["real_page_table"], + dst_fused_1["flashmla_num_splits"], + dst_fused_1["flashmla_metadata"], + # Destination tensors for backend 2 + dst_fused_2["cache_seqlens_int32"], + dst_fused_2["cu_seqlens_k"], + dst_fused_2["page_table_1"], + dst_fused_2["dsa_cache_seqlens_int32"], + dst_fused_2["dsa_cu_seqlens_k"], + dst_fused_2["real_page_table"], + dst_fused_2["flashmla_num_splits"], + dst_fused_2["flashmla_metadata"], + # Parameters + bs, + max_len, + seqlens_expanded_size, + ) + torch.cuda.synchronize() + fused_end = time.perf_counter() + fused_time = fused_end - fused_start + + # Compare results for all 3 backends + speedup = loop_time / fused_time if fused_time > 0 else 0 + print( + f"\n[VERIFY] bs={bs}, real_page_table={has_real_page_table}, flashmla={has_flashmla}" + ) + print( + f"[VERIFY] Fused time: {fused_time*1000:.3f}ms, Loop time: {loop_time*1000:.3f}ms, Speedup: {speedup:.2f}x" + ) + + max_diff = 0.0 + all_match = True + + for backend_idx, (dst_ref, dst_fused) in enumerate( + [ + (dst_ref_0, dst_fused_0), + (dst_ref_1, dst_fused_1), + (dst_ref_2, dst_fused_2), + ] + ): + for key in [ + "cache_seqlens_int32", + "cu_seqlens_k", + "page_table_1", + "dsa_cache_seqlens_int32", + "dsa_cu_seqlens_k", + ]: + if not torch.equal(dst_ref[key], dst_fused[key]): + diff = ( + (dst_ref[key].float() - dst_fused[key].float()).abs().max().item() + ) + max_diff = max(max_diff, diff) + all_match = False + print( + f"[ERROR] Backend {backend_idx} {key}: MISMATCH! Max diff: {diff}" + ) + + if has_real_page_table and dst_ref["real_page_table"] is not None: + if not torch.equal( + dst_ref["real_page_table"], dst_fused["real_page_table"] + ): + diff = ( + ( + dst_ref["real_page_table"].float() + - dst_fused["real_page_table"].float() + ) + .abs() + .max() + .item() + ) + max_diff = max(max_diff, diff) + all_match = False + print( + f"[ERROR] Backend {backend_idx} real_page_table: MISMATCH! Max diff: {diff}" + ) + + if has_flashmla: + if dst_ref["flashmla_num_splits"] is not None and not torch.equal( + dst_ref["flashmla_num_splits"], dst_fused["flashmla_num_splits"] + ): + diff = ( + ( + dst_ref["flashmla_num_splits"].float() + - dst_fused["flashmla_num_splits"].float() + ) + .abs() + .max() + .item() + ) + max_diff = max(max_diff, diff) + all_match = False + print( + f"[ERROR] Backend {backend_idx} flashmla_num_splits: MISMATCH! Max diff: {diff}" + ) + + if dst_ref["flashmla_metadata"] is not None and not torch.equal( + dst_ref["flashmla_metadata"], dst_fused["flashmla_metadata"] + ): + diff = ( + ( + dst_ref["flashmla_metadata"].float() + - dst_fused["flashmla_metadata"].float() + ) + .abs() + .max() + .item() + ) + max_diff = max(max_diff, diff) + all_match = False + print( + f"[ERROR] Backend {backend_idx} flashmla_metadata: MISMATCH! Max diff: {diff}" + ) + + if not all_match: + error_msg = ( + f"Fused metadata copy verification FAILED! " + f"Maximum difference: {max_diff}. " + f"The fused kernel produces different results than the for-loop version." + ) + print(f"[ERROR] {error_msg}") + raise AssertionError(error_msg) + + print(f"[VERIFY] Verification PASSED - all tensors match!") + + +@pytest.mark.parametrize("bs", [32, 64]) +def test_fused_metadata_copy_multi_large_batch(bs): + """Test with larger batch sizes and timing comparison.""" + if not torch.cuda.is_available(): + pytest.skip("CUDA not available") + + from sglang.jit_kernel.fused_metadata_copy import fused_metadata_copy_multi_cuda + + max_len = 128 + seqlens_expanded_size = bs + + data = create_test_metadata_multi( + bs=bs, + max_len=max_len, + seqlens_expanded_size=seqlens_expanded_size, + has_real_page_table=True, + has_flashmla=True, + ) + + dst_ref_0 = { + k: v.clone() if v is not None else None for k, v in data["dst0"].items() + } + dst_ref_1 = { + k: v.clone() if v is not None else None for k, v in data["dst1"].items() + } + dst_ref_2 = { + k: v.clone() if v is not None else None for k, v in data["dst2"].items() + } + + dst_fused_0 = { + k: v.clone() if v is not None else None for k, v in data["dst0"].items() + } + dst_fused_1 = { + k: v.clone() if v is not None else None for k, v in data["dst1"].items() + } + dst_fused_2 = { + k: v.clone() if v is not None else None for k, v in data["dst2"].items() + } + + # Warmup + for _ in range(5): + reference_copy_for_loop( + data["src"], [dst_ref_0, dst_ref_1, dst_ref_2], bs, max_len + ) + fused_metadata_copy_multi_cuda( + data["src"]["cache_seqlens"], + data["src"]["cu_seqlens_k"], + data["src"]["page_indices"], + data["src"]["dsa_cache_seqlens"], + data["src"]["dsa_cu_seqlens_k"], + data["src"]["real_page_table"], + data["src"]["flashmla_num_splits"], + data["src"]["flashmla_metadata"], + dst_fused_0["cache_seqlens_int32"], + dst_fused_0["cu_seqlens_k"], + dst_fused_0["page_table_1"], + dst_fused_0["dsa_cache_seqlens_int32"], + dst_fused_0["dsa_cu_seqlens_k"], + dst_fused_0["real_page_table"], + dst_fused_0["flashmla_num_splits"], + dst_fused_0["flashmla_metadata"], + dst_fused_1["cache_seqlens_int32"], + dst_fused_1["cu_seqlens_k"], + dst_fused_1["page_table_1"], + dst_fused_1["dsa_cache_seqlens_int32"], + dst_fused_1["dsa_cu_seqlens_k"], + dst_fused_1["real_page_table"], + dst_fused_1["flashmla_num_splits"], + dst_fused_1["flashmla_metadata"], + dst_fused_2["cache_seqlens_int32"], + dst_fused_2["cu_seqlens_k"], + dst_fused_2["page_table_1"], + dst_fused_2["dsa_cache_seqlens_int32"], + dst_fused_2["dsa_cu_seqlens_k"], + dst_fused_2["real_page_table"], + dst_fused_2["flashmla_num_splits"], + dst_fused_2["flashmla_metadata"], + bs, + max_len, + seqlens_expanded_size, + ) + torch.cuda.synchronize() + + # Actual timing + torch.cuda.synchronize() + loop_start = time.perf_counter() + reference_copy_for_loop(data["src"], [dst_ref_0, dst_ref_1, dst_ref_2], bs, max_len) + torch.cuda.synchronize() + loop_time = time.perf_counter() - loop_start + + torch.cuda.synchronize() + fused_start = time.perf_counter() + fused_metadata_copy_multi_cuda( + data["src"]["cache_seqlens"], + data["src"]["cu_seqlens_k"], + data["src"]["page_indices"], + data["src"]["dsa_cache_seqlens"], + data["src"]["dsa_cu_seqlens_k"], + data["src"]["real_page_table"], + data["src"]["flashmla_num_splits"], + data["src"]["flashmla_metadata"], + dst_fused_0["cache_seqlens_int32"], + dst_fused_0["cu_seqlens_k"], + dst_fused_0["page_table_1"], + dst_fused_0["dsa_cache_seqlens_int32"], + dst_fused_0["dsa_cu_seqlens_k"], + dst_fused_0["real_page_table"], + dst_fused_0["flashmla_num_splits"], + dst_fused_0["flashmla_metadata"], + dst_fused_1["cache_seqlens_int32"], + dst_fused_1["cu_seqlens_k"], + dst_fused_1["page_table_1"], + dst_fused_1["dsa_cache_seqlens_int32"], + dst_fused_1["dsa_cu_seqlens_k"], + dst_fused_1["real_page_table"], + dst_fused_1["flashmla_num_splits"], + dst_fused_1["flashmla_metadata"], + dst_fused_2["cache_seqlens_int32"], + dst_fused_2["cu_seqlens_k"], + dst_fused_2["page_table_1"], + dst_fused_2["dsa_cache_seqlens_int32"], + dst_fused_2["dsa_cu_seqlens_k"], + dst_fused_2["real_page_table"], + dst_fused_2["flashmla_num_splits"], + dst_fused_2["flashmla_metadata"], + bs, + max_len, + seqlens_expanded_size, + ) + torch.cuda.synchronize() + fused_time = time.perf_counter() - fused_start + + speedup = loop_time / fused_time if fused_time > 0 else 0 + print( + f"\n[PERF] Large batch (bs={bs}): Fused={fused_time*1000:.3f}ms, Loop={loop_time*1000:.3f}ms, Speedup={speedup:.2f}x" + ) + + # Verify correctness + for backend_idx, (dst_ref, dst_fused) in enumerate( + [ + (dst_ref_0, dst_fused_0), + (dst_ref_1, dst_fused_1), + (dst_ref_2, dst_fused_2), + ] + ): + for key in dst_ref: + if dst_ref[key] is not None and dst_fused[key] is not None: + assert torch.equal( + dst_ref[key], dst_fused[key] + ), f"Backend {backend_idx} {key} mismatch" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_fused_qk_gemma_rmsnorm_gate.py b/asian_ai/performance/SGLang/test/registered/jit/test_fused_qk_gemma_rmsnorm_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd2001b03cd369813bd20b3d6009a92a5096d80 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_fused_qk_gemma_rmsnorm_gate.py @@ -0,0 +1,151 @@ +import itertools +import sys + +import pytest +import torch + +from sglang.srt.models.utils import fused_qk_gemma_rmsnorm_with_gate +from sglang.test.ci.ci_register import register_amd_ci + +register_amd_ci(est_time=20, stage="jit-kernel-unit", runner_config="amd") + + +def reference_qk_gemma_rmsnorm_with_gate( + q_gate: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + eps: float, + head_dim: int, + num_heads: int, +): + """Pure-PyTorch reference: deinterleave q/gate, GemmaRMSNorm q and k.""" + seq_len = q_gate.shape[0] + + # Deinterleave q and gate from [q_h0, gate_h0, q_h1, gate_h1, ...] + qg_3d = q_gate.view(seq_len, num_heads, 2 * head_dim) + q = qg_3d[:, :, :head_dim].contiguous().view(-1, head_dim) + gate = qg_3d[:, :, head_dim:].contiguous().view(-1, head_dim) + + k_flat = k.reshape(-1, head_dim) + + # GemmaRMSNorm: x * rsqrt(mean(x^2) + eps) * (weight + 1) + def gemma_rmsnorm(x, w): + x_fp32 = x.float() + var = x_fp32.pow(2).mean(dim=-1, keepdim=True) + normed = x_fp32 * (var + eps).rsqrt() * (w.float() + 1.0) + return normed.to(x.dtype) + + q_out = gemma_rmsnorm(q, q_weight) + k_out = gemma_rmsnorm(k_flat, k_weight) + + return q_out, k_out, gate + + +DEVICE = "cuda" +DTYPE = torch.bfloat16 + +SEQ_LENS = [1, 2, 4, 7, 16, 128] +NUM_HEADS_LIST = [8, 16, 32] +NUM_KV_HEADS_LIST = [2, 4, 8] +HEAD_DIM_LIST = [64, 128] + + +@pytest.mark.parametrize( + "seq_len,num_heads,num_kv_heads,head_dim", + list(itertools.product(SEQ_LENS, NUM_HEADS_LIST, NUM_KV_HEADS_LIST, HEAD_DIM_LIST)), +) +def test_fused_qk_gemma_rmsnorm_with_gate( + seq_len: int, num_heads: int, num_kv_heads: int, head_dim: int +): + if num_kv_heads > num_heads: + pytest.skip("num_kv_heads > num_heads is not a valid config") + + eps = 1e-6 + q_size = num_heads * head_dim + kv_size = num_kv_heads * head_dim + + # Build a full qkv buffer and split — this gives non-contiguous k, + # which is the real usage pattern + qkv = torch.randn( + seq_len, q_size * 2 + kv_size + kv_size, device=DEVICE, dtype=DTYPE + ) + q_gate, k, v = qkv.split([q_size * 2, kv_size, kv_size], dim=-1) + + q_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + k_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + + # Reference + q_ref, k_ref, gate_ref = reference_qk_gemma_rmsnorm_with_gate( + q_gate, k, q_weight, k_weight, eps, head_dim, num_heads + ) + + # Fused kernel + q_out, k_out, gate_out = fused_qk_gemma_rmsnorm_with_gate( + q_gate, k, q_weight, k_weight, eps, head_dim, num_heads + ) + + torch.testing.assert_close(q_out, q_ref, atol=1e-2, rtol=1e-2) + torch.testing.assert_close(k_out, k_ref, atol=1e-2, rtol=1e-2) + torch.testing.assert_close(gate_out, gate_ref, atol=0, rtol=0) + + +@pytest.mark.parametrize("head_dim", [64, 128, 256]) +def test_gate_is_exact_copy(head_dim: int): + """Gate output must be a bitwise-exact copy of the input gate data.""" + seq_len = 4 + num_heads = 16 + num_kv_heads = 4 + eps = 1e-6 + q_size = num_heads * head_dim + kv_size = num_kv_heads * head_dim + + qkv = torch.randn( + seq_len, q_size * 2 + kv_size + kv_size, device=DEVICE, dtype=DTYPE + ) + q_gate, k, v = qkv.split([q_size * 2, kv_size, kv_size], dim=-1) + q_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + k_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + + _, _, gate_out = fused_qk_gemma_rmsnorm_with_gate( + q_gate, k, q_weight, k_weight, eps, head_dim, num_heads + ) + + # Extract gate from interleaved buffer manually + qg_3d = q_gate.view(seq_len, num_heads, 2 * head_dim) + gate_expected = qg_3d[:, :, head_dim:].contiguous().view(-1, head_dim) + + assert torch.equal(gate_out, gate_expected), "Gate must be bitwise exact" + + +@pytest.mark.parametrize("seq_len", [1, 8]) +def test_contiguous_k_also_works(seq_len: int): + """Kernel should work even when k is already contiguous.""" + num_heads = 16 + num_kv_heads = 4 + head_dim = 128 + eps = 1e-6 + q_size = num_heads * head_dim + kv_size = num_kv_heads * head_dim + + q_gate = torch.randn(seq_len, q_size * 2, device=DEVICE, dtype=DTYPE) + k = torch.randn(seq_len, kv_size, device=DEVICE, dtype=DTYPE) + assert k.is_contiguous() + + q_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + k_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + + q_ref, k_ref, gate_ref = reference_qk_gemma_rmsnorm_with_gate( + q_gate, k, q_weight, k_weight, eps, head_dim, num_heads + ) + q_out, k_out, gate_out = fused_qk_gemma_rmsnorm_with_gate( + q_gate, k, q_weight, k_weight, eps, head_dim, num_heads + ) + + torch.testing.assert_close(q_out, q_ref, atol=1e-2, rtol=1e-2) + torch.testing.assert_close(k_out, k_ref, atol=1e-2, rtol=1e-2) + torch.testing.assert_close(gate_out, gate_ref, atol=0, rtol=0) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_fused_store_index_cache.py b/asian_ai/performance/SGLang/test/registered/jit/test_fused_store_index_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..ceef13c0ef1390b00f92d55ada73eedb25a341f6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_fused_store_index_cache.py @@ -0,0 +1,460 @@ +""" +Test for fused_store_index_k_cache kernel. + +Design Notes: + 1. torch.cuda.synchronize() needed after TVM FFI kernel call. + 2. _split_buffer used buf[:, :vb].reshape(-1) which COPIES data for + non-contiguous slices → reference buffer stayed all-zeros. + Fix: use flat byte-offset indexing. + 3. act_quant may use a different quantization scheme → generous tolerance. + 4. FP8 E4M3 1-ULP rounding differences between CUDA hardware cast + (__nv_fp8_e4m3) and PyTorch .to(float8_e4m3fn) at tie-break points. + Adjacent FP8 representable values at the high end differ by up to 32 + in float space (e.g. 288, 320, 352, ..., 448). + Need to compare dequantized values with FP8-appropriate tolerance. +""" + +from __future__ import annotations + +import sys +from typing import Optional, Tuple + +import pytest +import torch + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +try: + from sglang.jit_kernel.fused_store_index_cache import ( + can_use_dsa_fused_store, + fused_store_index_k_cache, + ) + + HAS_FUSED = True +except ImportError: + HAS_FUSED = False + +try: + from sglang.srt.utils import is_hip + + _is_hip = is_hip() +except ImportError: + _is_hip = False + +try: + from sglang.srt.layers.quantization.fp8_kernel import is_fp8_fnuz + + _is_fp8_fnuz = is_fp8_fnuz() +except ImportError: + _is_fp8_fnuz = False + +register_cuda_ci(est_time=24, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=24, suite="nightly-amd-kernel-1-gpu", nightly=True) + +PAGE_SIZE = 64 +HEAD_DIM = 128 +FP8_E4M3_MAX = 448.0 +FP8_DTYPE = torch.float8_e4m3fn +BYTES_PER_TOKEN = 128 + 4 # 128 fp8 bytes + 4 scale bytes +BYTES_PER_PAGE = PAGE_SIZE * BYTES_PER_TOKEN + + +def _skip_if_unavailable(page_size: int = PAGE_SIZE): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + if _is_hip: + pytest.skip("Fused store kernel is CUDA-specific") + if _is_fp8_fnuz: + pytest.skip("Fused store path disabled for FP8 FNUZ") + if not hasattr(torch, "float8_e4m3fn"): + pytest.skip("torch.float8_e4m3fn not available") + if not HAS_FUSED: + pytest.skip("fused_store_index_cache not importable") + if not can_use_dsa_fused_store(torch.bfloat16, torch.int64, page_size): + pytest.skip("JIT kernel unavailable / failed to compile") + + +def _num_pages(loc: torch.Tensor, page_size: int, extra: int = 1) -> int: + return int(loc.max().item()) // page_size + 1 + extra + + +def _make_buffer(num_pages: int, page_size: int = PAGE_SIZE) -> torch.Tensor: + return torch.zeros( + (num_pages, page_size * BYTES_PER_TOKEN), + dtype=torch.uint8, + device="cuda", + ) + + +def _read_token_from_buffer( + buf: torch.Tensor, + token_idx: int, + page_size: int = PAGE_SIZE, +) -> Tuple[torch.Tensor, float]: + """ + Read a single token's fp8 values and scale from the paged buffer + using flat byte offsets. + """ + page = token_idx // page_size + offset = token_idx % page_size + page_bytes = page_size * BYTES_PER_TOKEN + + buf_flat = buf.reshape(-1) + + val_start = page * page_bytes + offset * 128 + fp8_bytes = buf_flat[val_start : val_start + 128] + fp8_vals = fp8_bytes.view(FP8_DTYPE).float() + + scale_start = page * page_bytes + 128 * page_size + offset * 4 + scale_bytes = buf_flat[scale_start : scale_start + 4] + scale = scale_bytes.view(torch.float32).item() + + return fp8_vals, scale + + +def _write_token_to_buffer( + buf: torch.Tensor, + token_idx: int, + fp8_data: torch.Tensor, + scale: float, + page_size: int = PAGE_SIZE, +) -> None: + """ + Write a single token's fp8 values and scale into the paged buffer + using flat byte offsets on buf.reshape(-1) (which is a true view + since buf is contiguous). + """ + page = token_idx // page_size + offset = token_idx % page_size + page_bytes = page_size * BYTES_PER_TOKEN + + buf_flat = buf.reshape(-1) + + val_start = page * page_bytes + offset * 128 + buf_flat[val_start : val_start + 128] = fp8_data.view(torch.uint8) + + scale_start = page * page_bytes + 128 * page_size + offset * 4 + scale_t = torch.tensor([scale], dtype=torch.float32, device=buf.device) + buf_flat[scale_start : scale_start + 4] = scale_t.view(torch.uint8) + + +def _gather_tokens( + buf: torch.Tensor, + loc: torch.Tensor, + page_size: int = PAGE_SIZE, +) -> Tuple[torch.Tensor, torch.Tensor]: + N = loc.shape[0] + fp8_f32 = torch.empty((N, HEAD_DIM), dtype=torch.float32, device=buf.device) + scales = torch.empty((N,), dtype=torch.float32, device=buf.device) + for i in range(N): + idx = int(loc[i].item()) + vals, s = _read_token_from_buffer(buf, idx, page_size) + fp8_f32[i] = vals + scales[i] = s + return fp8_f32, scales + + +# Reference kernel +def _reference_quantize_and_store( + key_bf16: torch.Tensor, + loc: torch.Tensor, + num_pages: int, + page_size: int = PAGE_SIZE, +) -> torch.Tensor: + """ + Reference kernel of the fused kernel's quantization: + abs_max = max(|row|) + scale = max(1e-4, abs_max) / 448 + fp8_val = clip(val / scale, -448, 448) -> cast to fp8 + """ + N = key_bf16.shape[0] + key_f32 = key_bf16.float() + buf = _make_buffer(num_pages, page_size) + + for i in range(N): + row = key_f32[i] + abs_max = row.abs().max().item() + scale = max(1e-4, abs_max) / FP8_E4M3_MAX + inv_scale = 1.0 / scale + quantized = (row * inv_scale).clamp(-FP8_E4M3_MAX, FP8_E4M3_MAX) + quantized_fp8 = quantized.to(FP8_DTYPE) + + idx = int(loc[i].item()) + _write_token_to_buffer(buf, idx, quantized_fp8, scale, page_size) + + return buf + + +def _import_act_quant(): + try: + from sglang.srt.layers.attention.dsa.triton_kernel import act_quant + + return act_quant + except Exception: + return None + + +def _ref_store_via_act_quant( + key_bf16: torch.Tensor, + loc: torch.Tensor, + num_pages: int, + page_size: int = PAGE_SIZE, + block_size: int = 128, + scale_fmt: Optional[str] = None, +) -> Optional[torch.Tensor]: + act_quant = _import_act_quant() + if act_quant is None: + return None + + try: + k_fp8, k_scale = act_quant(key_bf16, block_size, scale_fmt) + except TypeError: + k_fp8, k_scale = act_quant(key_bf16, block_size) + + if k_fp8.dim() == 3 and k_fp8.shape[1] == 1: + k_fp8 = k_fp8.squeeze(1) + if k_scale is not None and k_scale.dim() == 3 and k_scale.shape[1] == 1: + k_scale = k_scale.squeeze(1) + k_scale = k_scale.view(-1).float() + + buf = _make_buffer(num_pages, page_size) + N = key_bf16.shape[0] + for i in range(N): + idx = int(loc[i].item()) + _write_token_to_buffer( + buf, idx, k_fp8[i].to(FP8_DTYPE), k_scale[i].item(), page_size + ) + return buf + + +# TEST 1: Fused kernel vs. its own algorithm (pure-Python reference) +# +# NOTE on FP8 rounding: +# CUDA hardware fp8 cast (__nv_fp8_e4m3) and PyTorch .to(float8_e4m3fn) +# may round differently at tie-break points. This causes up to 1-ULP +# differences in the FP8 codes. In FP8 E4M3, adjacent representable +# values at the high end differ by up to 32 in float space (e.g. +# 288 vs 320). After dequantization (fp8_float * scale), the error +# from 1-ULP is: scale * ulp ≈ (abs_max/448) * 32 ≈ 0.07 * abs_max. +# For randn inputs (abs_max ≈ 3-4), this is about 0.2-0.3. +# +# We therefore compare dequantized values with tolerances that +# accommodate 1-ULP FP8 rounding, NOT byte-exact fp8 codes. +@pytest.mark.parametrize( + "num_tokens,base_index", + [(1, 0), (32, 0), (64, 0), (128, 64), (257, 65), (512, 0)], +) +def test_fused_kernel_matches_own_algorithm(num_tokens: int, base_index: int): + """Compare fused CUDA kernel against a pure-Python implementation + of the *same* quantization formula.""" + _skip_if_unavailable() + device = torch.device("cuda") + + key = torch.randn((num_tokens, HEAD_DIM), device=device, dtype=torch.bfloat16) + loc = ( + base_index + torch.randperm(num_tokens, device=device, dtype=torch.int64) + ).contiguous() + num_pages = _num_pages(loc, PAGE_SIZE) + + # Reference kernel + ref_buf = _reference_quantize_and_store(key, loc, num_pages) + + # Fused kernel + out_buf = _make_buffer(num_pages) + fused_store_index_k_cache(key, out_buf, loc, page_size=PAGE_SIZE) + torch.cuda.synchronize() + + out_f, out_s = _gather_tokens(out_buf, loc) + ref_f, ref_s = _gather_tokens(ref_buf, loc) + + # 1) Scales must match tightly (same f32 formula, no rounding ambiguity) + torch.testing.assert_close(out_s, ref_s, rtol=1e-5, atol=1e-7) + + # 2) Most FP8 codes should match; allow rare 1-ULP differences. + # 1-ULP at FP8 E4M3 high end = 32 in float space. + mismatch = out_f != ref_f + mismatch_frac = mismatch.float().mean().item() + assert mismatch_frac < 0.01, ( + f"Too many FP8 code mismatches: {mismatch_frac:.2%} " + f"(expected < 1% from rounding tie-breaks)" + ) + + # 3) Where codes differ, the difference should be exactly 1 ULP. + # In FP8 E4M3: if the float-cast value is V, the adjacent value + # differs by ~V * 0.1 (relative) at most. + if mismatch.any(): + diff = (out_f[mismatch] - ref_f[mismatch]).abs() + rel_diff = diff / ref_f[mismatch].abs().clamp(min=1e-6) + # 1-ULP relative difference for E4M3 is at most ~12.5% (2^-3) + assert rel_diff.max().item() <= 0.15, ( + f"FP8 code difference exceeds 1-ULP: max relative diff = " + f"{rel_diff.max().item():.4f}" + ) + + # 4) Dequantized values should be close. + # Max error from 1-ULP: scale * fp8_ulp ≈ (abs_max/448) * 32 + # For randn abs_max ≈ 3-4: max_err ≈ 0.21 - 0.29 + out_deq = out_f * out_s.unsqueeze(-1) + ref_deq = ref_f * ref_s.unsqueeze(-1) + torch.testing.assert_close(out_deq, ref_deq, rtol=0.15, atol=0.5) + + +# TEST 2: Cross-check against act_quant +@pytest.mark.parametrize("scale_fmt", [None, "fp32"]) +def test_fused_kernel_vs_act_quant_semantic(scale_fmt: Optional[str]): + """Both fused kernel and act_quant should approximately reconstruct + the original bf16 values.""" + _skip_if_unavailable() + device = torch.device("cuda") + + num_tokens = 257 + base_index = 65 + key = torch.randn((num_tokens, HEAD_DIM), device=device, dtype=torch.bfloat16) + loc = ( + base_index + torch.randperm(num_tokens, device=device, dtype=torch.int64) + ).contiguous() + num_pages = _num_pages(loc, PAGE_SIZE) + + ref_buf = _ref_store_via_act_quant(key, loc, num_pages, scale_fmt=scale_fmt) + if ref_buf is None: + pytest.skip("act_quant not available") + + out_buf = _make_buffer(num_pages) + fused_store_index_k_cache(key, out_buf, loc, page_size=PAGE_SIZE) + torch.cuda.synchronize() + + out_f, out_s = _gather_tokens(out_buf, loc) + ref_f, ref_s = _gather_tokens(ref_buf, loc) + + out_deq = out_f * out_s.unsqueeze(-1) + ref_deq = ref_f * ref_s.unsqueeze(-1) + orig_f32 = key.float() + + # Fused kernel should reconstruct original within FP8 precision + torch.testing.assert_close( + out_deq, + orig_f32, + rtol=0.15, + atol=5e-2, + msg="Fused kernel dequantized values don't approximate original", + ) + + # act_quant may use a very different scale policy. + try: + torch.testing.assert_close( + ref_deq, + orig_f32, + rtol=0.25, + atol=0.5, + msg="act_quant dequantized values don't approximate original", + ) + except AssertionError: + nonzero_frac = (ref_deq.abs() > 1e-6).float().mean().item() + if nonzero_frac < 0.5: + pytest.fail( + f"act_quant output looks mostly zero ({nonzero_frac:.1%} nonzero)." + ) + else: + pytest.skip( + f"act_quant uses a very different quantization scheme " + f"(scale_fmt={scale_fmt}). Fused kernel validated independently." + ) + + torch.testing.assert_close( + out_deq, + ref_deq, + rtol=0.3, + atol=0.5, + msg="Fused and act_quant dequantized values diverge too much", + ) + + +# TEST 3: Roundtrip reconstruction +@pytest.mark.parametrize("num_tokens", [1, 64, 257]) +def test_roundtrip_reconstruction(num_tokens: int): + _skip_if_unavailable() + device = torch.device("cuda") + + key = torch.randn((num_tokens, HEAD_DIM), device=device, dtype=torch.bfloat16) + loc = torch.arange(num_tokens, device=device, dtype=torch.int64) + num_pages = _num_pages(loc, PAGE_SIZE) + + buf = _make_buffer(num_pages) + fused_store_index_k_cache(key, buf, loc, page_size=PAGE_SIZE) + torch.cuda.synchronize() + + fp8_f32, scales = _gather_tokens(buf, loc) + reconstructed = fp8_f32 * scales.unsqueeze(-1) + original = key.float() + + torch.testing.assert_close(reconstructed, original, rtol=0.15, atol=5e-2) + + per_row_energy = reconstructed.abs().sum(dim=-1) + orig_energy = original.abs().sum(dim=-1) + mask = orig_energy > 0.1 + assert ( + per_row_energy[mask] > 0.01 + ).all(), "Some tokens have zero reconstruction — kernel may not be writing output" + + +# TEST 4: Boundary conditions +def test_single_token(): + _skip_if_unavailable() + device = torch.device("cuda") + + key = torch.randn((1, HEAD_DIM), device=device, dtype=torch.bfloat16) + loc = torch.tensor([0], device=device, dtype=torch.int64) + + buf = _make_buffer(1) + fused_store_index_k_cache(key, buf, loc, page_size=PAGE_SIZE) + torch.cuda.synchronize() + + fp8_f32, scales = _gather_tokens(buf, loc) + reconstructed = fp8_f32 * scales.unsqueeze(-1) + torch.testing.assert_close(reconstructed, key.float(), rtol=0.15, atol=5e-2) + + +# TEST 5: Zero input conditions +def test_zero_input(): + _skip_if_unavailable() + device = torch.device("cuda") + + key = torch.zeros((4, HEAD_DIM), device=device, dtype=torch.bfloat16) + loc = torch.arange(4, device=device, dtype=torch.int64) + + buf = _make_buffer(1) + fused_store_index_k_cache(key, buf, loc, page_size=PAGE_SIZE) + torch.cuda.synchronize() + + fp8_f32, scales = _gather_tokens(buf, loc) + + expected_scale = 1e-4 / FP8_E4M3_MAX + torch.testing.assert_close( + scales, + torch.full_like(scales, expected_scale), + rtol=1e-5, + atol=1e-10, + ) + assert (fp8_f32 == 0).all() + + +# TEST 6: Sanity check — verify reference itself writes non-zero data +def test_reference_writes_nonzero(): + _skip_if_unavailable() + device = torch.device("cuda") + + key = torch.randn((8, HEAD_DIM), device=device, dtype=torch.bfloat16) + loc = torch.arange(8, device=device, dtype=torch.int64) + + buf = _reference_quantize_and_store(key, loc, num_pages=1) + + fp8_f32, scales = _gather_tokens(buf, loc) + deq = fp8_f32 * scales.unsqueeze(-1) + + assert deq.abs().sum().item() > 0, "Reference buffer is all zeros — error!" + torch.testing.assert_close(deq, key.float(), rtol=0.15, atol=5e-2) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_fused_verify_triton_gdn.py b/asian_ai/performance/SGLang/test/registered/jit/test_fused_verify_triton_gdn.py new file mode 100644 index 0000000000000000000000000000000000000000..b036421c638d368a205797df847641194f30c812 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_fused_verify_triton_gdn.py @@ -0,0 +1,239 @@ +"""Tests for fused sigmoid gating delta rule MTP kernel (GDN target_verify). + +Compares the fused kernel `fused_sigmoid_gating_delta_rule_update` against +the reference two-step implementation: + 1. g, beta = fused_gdn_gating(A_log, a, b, dt_bias) + 2. o = fused_recurrent_gated_delta_rule_update(q, k, v, g, beta, ...) +""" + +import sys + +import pytest +import torch + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +try: + from sglang.srt.layers.attention.fla.fused_gdn_gating import fused_gdn_gating + from sglang.srt.layers.attention.fla.fused_recurrent import ( + fused_recurrent_gated_delta_rule_update, + ) + from sglang.srt.layers.attention.fla.fused_sigmoid_gating_recurrent import ( + fused_sigmoid_gating_delta_rule_update, + ) + + KERNELS_AVAILABLE = True +except ImportError: + KERNELS_AVAILABLE = False + +register_cuda_ci(est_time=6, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=10, suite="nightly-amd-kernel-1-gpu", nightly=True) + + +def _make_tensors(N, T, H, HV, K, V, device="cuda", seed=2025): + """Create input tensors for GDN target_verify.""" + torch.manual_seed(seed) + A_log = torch.randn(HV, dtype=torch.float32, device=device) + dt_bias = torch.randn(HV, dtype=torch.bfloat16, device=device) + a = torch.randn(1, N * T, HV, dtype=torch.bfloat16, device=device) + b = torch.randn(1, N * T, HV, dtype=torch.bfloat16, device=device) + q = torch.randn(1, N * T, H, K, dtype=torch.bfloat16, device=device) + k = torch.randn(1, N * T, H, K, dtype=torch.bfloat16, device=device) + v = torch.randn(1, N * T, HV, V, dtype=torch.bfloat16, device=device) + indices = torch.arange(N, dtype=torch.int32, device=device) + initial_state = torch.randn(N, HV, K, V, dtype=torch.float, device=device) + cu_seqlens = torch.arange(0, N * T + 1, T, dtype=torch.int32, device=device) + return A_log, dt_bias, a, b, q, k, v, initial_state, indices, cu_seqlens + + +def run_reference( + A_log, + dt_bias, + q, + k, + v, + a, + b, + initial_state_source, + initial_state_indices, + cu_seqlens, + disable_state_update=True, + intermediate_states_buffer=None, + intermediate_state_indices=None, + cache_steps=None, + retrieve_parent_token=None, +): + """Reference: fused_gdn_gating + fused_recurrent_gated_delta_rule_update.""" + # fused_gdn_gating expects 2D [seq_len, HV] + a_2d = a.view(-1, a.shape[-1]) + b_2d = b.view(-1, b.shape[-1]) + g, beta = fused_gdn_gating(A_log, a_2d, b_2d, dt_bias) + # fused_recurrent expects 3D [B, T, HV] + g = g.view(a.shape) + beta = beta.view(b.shape) + + # fused_recurrent requires intermediate_state_indices when cu_seqlens is used + if cu_seqlens is not None and intermediate_state_indices is None: + N = len(cu_seqlens) - 1 + intermediate_state_indices = torch.arange(N, dtype=torch.int32, device=q.device) + + return fused_recurrent_gated_delta_rule_update( + q=q, + k=k, + v=v, + g=g, + beta=beta, + initial_state_source=initial_state_source, + initial_state_indices=initial_state_indices, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True, + disable_state_update=disable_state_update, + intermediate_states_buffer=intermediate_states_buffer, + intermediate_state_indices=intermediate_state_indices, + cache_steps=cache_steps, + retrieve_parent_token=retrieve_parent_token, + ) + + +def run_fused_mtp( + A_log, + dt_bias, + q, + k, + v, + a, + b, + initial_state_source, + initial_state_indices, + cu_seqlens, + disable_state_update=True, + intermediate_states_buffer=None, + intermediate_state_indices=None, + cache_steps=None, + retrieve_parent_token=None, +): + """Fused: fused_sigmoid_gating_delta_rule_update.""" + return fused_sigmoid_gating_delta_rule_update( + A_log=A_log, + dt_bias=dt_bias, + q=q, + k=k, + v=v, + a=a, + b=b, + initial_state_source=initial_state_source, + initial_state_indices=initial_state_indices, + cu_seqlens=cu_seqlens, + use_qk_l2norm_in_kernel=True, + softplus_beta=1.0, + softplus_threshold=20.0, + is_kda=False, + disable_state_update=disable_state_update, + intermediate_states_buffer=intermediate_states_buffer, + intermediate_state_indices=intermediate_state_indices, + cache_steps=cache_steps, + retrieve_parent_token=retrieve_parent_token, + ) + + +@pytest.mark.skipif(not KERNELS_AVAILABLE, reason="Kernel not available") +@pytest.mark.parametrize("N", [1, 8, 16]) +@pytest.mark.parametrize("T", [1, 4, 8]) +def test_fused_gdn_mtp_precision(N: int, T: int): + """Compare fused MTP output against reference.""" + H, HV, K, V = 16, 32, 128, 128 + + A_log, dt_bias, a, b, q, k, v, state, indices, cu_seqlens = _make_tensors( + N, T, H, HV, K, V + ) + + state_ref = state.clone() + state_fused = state.clone() + + out_ref = run_reference( + A_log, + dt_bias, + q, + k, + v, + a, + b, + state_ref, + indices, + cu_seqlens, + disable_state_update=True, + ) + out_fused = run_fused_mtp( + A_log, + dt_bias, + q, + k, + v, + a, + b, + state_fused, + indices, + cu_seqlens, + disable_state_update=True, + ) + + torch.testing.assert_close(out_ref, out_fused, rtol=1e-2, atol=1e-2) + + +@pytest.mark.skipif(not KERNELS_AVAILABLE, reason="Kernels not available") +@pytest.mark.parametrize("N", [1, 16, 128]) +def test_mtp_single_step_decode(N: int): + """Verify MTP kernel matches reference for T=1 (decode scenario).""" + T = 1 + H, HV, K, V = 16, 32, 128, 128 + + A_log, dt_bias, a, b, q, k, v, state, indices, cu_seqlens = _make_tensors( + N, T, H, HV, K, V + ) + + state_ref = state.clone() + state_fused = state.clone() + + out_ref = run_reference( + A_log, + dt_bias, + q, + k, + v, + a, + b, + state_ref, + indices, + cu_seqlens, + disable_state_update=False, + ) + out_fused = run_fused_mtp( + A_log, + dt_bias, + q, + k, + v, + a, + b, + state_fused, + indices, + cu_seqlens, + disable_state_update=False, + ) + + torch.testing.assert_close(out_ref, out_fused, rtol=1e-2, atol=1e-2) + + # Also verify states match after update + state_diff = (state_ref.float() - state_fused.float()).abs() + state_max_diff = state_diff.max().item() + state_fail_rate = (state_diff > 0.1).float().mean().item() * 100 + print( + f" single_step state N={N}: max_diff={state_max_diff:.2e}, " + f"fail_rate={state_fail_rate:.2f}%" + ) + assert state_fail_rate < 0.01, f"State mismatch: fail_rate={state_fail_rate:.2f}%" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_gptq_marlin.py b/asian_ai/performance/SGLang/test/registered/jit/test_gptq_marlin.py new file mode 100644 index 0000000000000000000000000000000000000000..6e818e38a388ad4378fa050fdc648f35c4c42b06 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_gptq_marlin.py @@ -0,0 +1,192 @@ +import sys +from types import SimpleNamespace + +import pytest +import torch +from sgl_kernel.scalar_type import scalar_types + +from sglang.jit_kernel.gptq_marlin import gptq_marlin_gemm +from sglang.srt.layers.quantization.marlin_utils import ( + check_marlin_supported, + marlin_make_workspace, +) +from sglang.srt.layers.quantization.marlin_utils_fp4 import ( + apply_fp4_marlin_linear, + nvfp4_marlin_process_global_scale, + prepare_nvfp4_layer_for_marlin, +) +from sglang.srt.utils.common import is_sm80_supported, is_sm90_supported +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_marlin_utils import ( + awq_marlin_quantize, + make_nvfp4_weight_and_ref, + marlin_quantize, +) + +register_cuda_ci(est_time=13, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +MNK_FACTORS = [ + (1, 1, 1), + (1, 4, 8), + (13, 17, 67), + (257, 13, 11), +] + + +@pytest.mark.parametrize("k_chunk", [128]) +@pytest.mark.parametrize("n_chunk", [64, 256]) +@pytest.mark.parametrize("quant_type", [scalar_types.uint4, scalar_types.uint4b8]) +@pytest.mark.parametrize("group_size", [-1, 128]) +@pytest.mark.parametrize("mnk_factors", MNK_FACTORS) +@pytest.mark.parametrize("act_order", [False, True]) +def test_gptq_marlin_gemm( + k_chunk, + n_chunk, + quant_type, + group_size, + mnk_factors, + act_order, +): + m_factor, n_factor, k_factor = mnk_factors + has_zp = quant_type in [scalar_types.uint4, scalar_types.uint8] + + size_m = m_factor + size_k = k_chunk * k_factor + size_n = n_chunk * n_factor + + if act_order: + if group_size == -1: + return + if group_size == size_k: + return + if has_zp: + return + + if size_k % group_size != 0: + return + + a_input = torch.randn((size_m, size_k), dtype=torch.float16, device="cuda") + b_weight = torch.randn((size_k, size_n), dtype=torch.float16, device="cuda") + + if has_zp: + w_ref, marlin_q_w, marlin_s, marlin_zp = awq_marlin_quantize( + b_weight, quant_type, group_size + ) + g_idx = None + sort_indices = None + marlin_s2 = None + else: + w_ref, marlin_q_w, marlin_s, g_idx, sort_indices, _ = marlin_quantize( + b_weight, quant_type, group_size, act_order + ) + marlin_zp = None + marlin_s2 = None + + workspace = marlin_make_workspace(w_ref.device) + + output = gptq_marlin_gemm( + a_input, + None, + marlin_q_w, + marlin_s, + marlin_s2, + marlin_zp, + g_idx, + sort_indices, + workspace, + quant_type, + a_input.shape[0], + b_weight.shape[1], + a_input.shape[1], + is_k_full=True, + use_atomic_add=False, + use_fp32_reduce=False, + is_zp_float=False, + ) + + output_ref = torch.matmul(a_input, w_ref) + torch.cuda.synchronize() + + # JIT kernel should produce approximately correct results vs torch.matmul + max_diff = torch.mean(torch.abs(output - output_ref)) / torch.mean( + torch.abs(output_ref) + ) + assert max_diff < 0.04 + + +@pytest.mark.skipif( + not (is_sm80_supported() or is_sm90_supported()), + reason="NVFP4 Marlin fallback tests require CUDA SM8X/SM9X", +) +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_nvfp4_marlin_support_and_scale_transforms_sm80_sm90(dtype): + major, minor = torch.cuda.get_device_capability() + capability = major * 10 + minor + assert check_marlin_supported( + scalar_types.float4_e2m1f, + group_size=16, + has_zp=False, + device_capability=capability, + ) + + global_scale = torch.tensor(1.0, dtype=dtype, device="cuda") + actual_global_scale = nvfp4_marlin_process_global_scale(global_scale) + assert actual_global_scale.is_cuda + assert actual_global_scale.ndim == 1 + assert actual_global_scale.numel() == 1 + if dtype == torch.float16: + assert actual_global_scale.item() == 128.0 + else: + assert actual_global_scale.item() == 2.0**119 + + +@pytest.mark.skipif( + not (is_sm80_supported() or is_sm90_supported()), + reason="NVFP4 Marlin dense numeric test requires CUDA SM80, SM86, or SM90", +) +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_nvfp4_marlin_dense_matches_dequant_reference(dtype): + torch.manual_seed(0) + + size_m = 17 + size_k = 256 + size_n = 192 + group_size = 16 + + a_input = torch.randn((size_m, size_k), dtype=dtype, device="cuda") / 10 + fp4_weight, scales, global_scale, weight_ref = make_nvfp4_weight_and_ref( + size_n, size_k, dtype, group_size=group_size + ) + + layer = torch.nn.Module() + layer.quant_config = SimpleNamespace(group_size=group_size) + layer.output_size_per_partition = size_n + layer.input_size_per_partition = size_k + layer.params_dtype = dtype + layer.weight = torch.nn.Parameter(fp4_weight, requires_grad=False) + layer.weight_scale = torch.nn.Parameter(scales, requires_grad=False) + layer.weight_global_scale = torch.nn.Parameter( + global_scale.reshape(1), requires_grad=False + ) + prepare_nvfp4_layer_for_marlin(layer) + + output = apply_fp4_marlin_linear( + a_input, + layer.weight, + layer.weight_scale, + layer.weight_global_scale, + layer.workspace, + size_n, + size_k, + use_fp32_reduce=True, + ) + + output_ref = torch.matmul(a_input, weight_ref.T) + torch.cuda.synchronize() + + torch.testing.assert_close(output, output_ref, rtol=0.04, atol=0.04) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_gptq_marlin_repack.py b/asian_ai/performance/SGLang/test/registered/jit/test_gptq_marlin_repack.py new file mode 100644 index 0000000000000000000000000000000000000000..0401d31fd55c7e1289c6e4731d6a94ff32f1fd11 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_gptq_marlin_repack.py @@ -0,0 +1,96 @@ +import sys + +import pytest +import torch +from sgl_kernel.scalar_type import scalar_types + +from sglang.jit_kernel.gptq_marlin_repack import gptq_marlin_repack +from sglang.srt.layers.quantization.utils import ( + gptq_quantize_weights, + pack_rows, + sort_weights, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_marlin_utils import get_weight_perm, marlin_weights + +register_cuda_ci(est_time=16, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +MARLIN_K_CHUNKS = [128] +MARLIN_N_CHUNKS = [64, 256] + +MNK_FACTORS = [ + (1, 1, 1), + (1, 4, 8), + (1, 7, 5), + (13, 17, 67), + (26, 37, 13), + (67, 13, 11), + (257, 13, 11), + (658, 13, 11), +] + + +@pytest.mark.parametrize("k_chunk", MARLIN_K_CHUNKS) +@pytest.mark.parametrize("n_chunk", MARLIN_N_CHUNKS) +@pytest.mark.parametrize("quant_type", [scalar_types.uint4b8]) +@pytest.mark.parametrize("group_size", [-1, 32, 64, 128]) +@pytest.mark.parametrize("act_order", [False, True]) +@pytest.mark.parametrize("mnk_factors", MNK_FACTORS) +def test_gptq_marlin_repack( + k_chunk, n_chunk, quant_type, group_size, act_order, mnk_factors +): + m_factor, n_factor, k_factor = mnk_factors + + size_k = k_chunk * k_factor + size_n = n_chunk * n_factor + + # Filter act_order + if act_order: + if group_size == -1: + return + if group_size == size_k: + return + + # Normalize group_size + if group_size == -1: + group_size = size_k + assert group_size <= size_k + + if size_k % group_size != 0: + pytest.skip("size_k must be divisible by group_size") + + # Create input + b_weight = torch.randn((size_k, size_n), dtype=torch.float16, device="cuda") + + # Quantize (and apply act_order if provided) + w_ref, q_w, s, g_idx, rand_perm = gptq_quantize_weights( + b_weight, quant_type, group_size, act_order + ) + + q_w_gptq = pack_rows(q_w, quant_type.size_bits, size_k, size_n) + + # For act_order, sort the "weights" and "g_idx" so that group ids are + # increasing + sort_indices = torch.empty(0, dtype=torch.int, device=b_weight.device) + if act_order: + q_w, g_idx, sort_indices = sort_weights(q_w, g_idx) + + marlin_layout_perm = get_weight_perm(quant_type.size_bits) + q_w_marlin_ref = marlin_weights( + q_w, size_k, size_n, quant_type.size_bits, marlin_layout_perm + ) + + # Run JIT repack kernel + jit_output = gptq_marlin_repack( + q_w_gptq, sort_indices, size_k, size_n, quant_type.size_bits + ) + + torch.cuda.synchronize() + + # JIT should match the reference (computed from CPU marlin_weights) + torch.testing.assert_close(jit_output, q_w_marlin_ref) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_hadamard_jit.py b/asian_ai/performance/SGLang/test/registered/jit/test_hadamard_jit.py new file mode 100644 index 0000000000000000000000000000000000000000..621446f8420e9a9a89f6a0498825970c803f6b12 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_hadamard_jit.py @@ -0,0 +1,428 @@ +import math +import sys + +import numpy as np +import pytest +import torch +import torch.nn.functional as F +from scipy.linalg import hadamard + +from sglang.jit_kernel.hadamard import ( + hadamard_transform, + hadamard_transform_12n, + hadamard_transform_20n, + hadamard_transform_28n, + hadamard_transform_40n, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=128, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=512, suite="nightly-kernel-1-gpu", nightly=True) + +# Exact M×N Hadamard matrices (±1 entries) copied from +# python/sglang/jit_kernel/csrc/fast-hadamard-transform/code_gen.py. +# These are non-power-of-2 Hadamard matrices constructed via Paley/Williamson methods. +# "+" = +1, "-" = -1. Used by the _12n/_20n/_28n/_40n kernel variants. + +_HAD_12_STR = """ ++-++++++++++ +--+-+-+-+-+- ++++-++----++ ++---+--+-++- ++++++-++---- ++-+---+--+-+ +++--+++-++-- ++--++---+--+ +++----+++-++ ++--+-++---+- +++++----+++- ++-+--+-++--- +""" + +_HAD_20_STR = """ ++----+----++--++-++- +-+----+---+++---+-++ +--+----+---+++-+-+-+ +---+----+---+++++-+- +----+----++--++-++-+ +-+++++-----+--+++--+ ++-+++-+---+-+--+++-- +++-++--+---+-+--+++- ++++-+---+---+-+--+++ +++++-----++--+-+--++ +--++-+-++-+-----++++ +---++-+-++-+---+-+++ ++---++-+-+--+--++-++ +++---++-+----+-+++-+ +-++---++-+----+++++- +-+--+--++-+----+---- ++-+-----++-+----+--- +-+-+-+---+--+----+-- +--+-+++------+----+- ++--+--++------+----+ +""" + +_HAD_28_STR = """ ++------++----++-+--+-+--++-- +-+-----+++-----+-+--+-+--++- +--+-----+++---+-+-+----+--++ +---+-----+++---+-+-+-+--+--+ +----+-----+++---+-+-+++--+-- +-----+-----++++--+-+--++--+- +------++----++-+--+-+--++--+ +--++++-+-------++--+++-+--+- +---++++-+-----+-++--+-+-+--+ ++---+++--+----++-++--+-+-+-- +++---++---+----++-++--+-+-+- ++++---+----+----++-++--+-+-+ +++++--------+-+--++-++--+-+- +-++++--------+++--++--+--+-+ +-+-++-++--++--+--------++++- ++-+-++--+--++--+--------++++ +-+-+-++--+--++--+----+---+++ ++-+-+-++--+--+---+---++---++ +++-+-+-++--+------+--+++---+ +-++-+-+-++--+------+-++++--- ++-++-+---++--+------+-++++-- +-++--++-+-++-+++----++------ ++-++--++-+-++-+++-----+----- +++-++---+-+-++-+++-----+---- +-++-++-+-+-+-+--+++-----+--- +--++-++++-+-+----+++-----+-- ++--++-+-++-+-+----+++-----+- +++--++-+-++-+-+----++------+ +""" + +_HAD_40_STR = """ ++-------------------+------------------- +++-++----+-+-++++--+++-++----+-+-++++--+ ++++-++----+-+-++++--+++-++----+-+-++++-- ++-++-++----+-+-++++-+-++-++----+-+-++++- ++--++-++----+-+-+++++--++-++----+-+-++++ +++--++-++----+-+-+++++--++-++----+-+-+++ ++++--++-++----+-+-+++++--++-++----+-+-++ +++++--++-++----+-+-+++++--++-++----+-+-+ ++++++--++-++----+-+-+++++--++-++----+-+- ++-++++--++-++----+-++-++++--++-++----+-+ +++-++++--++-++----+-++-++++--++-++----+- ++-+-++++--++-++----++-+-++++--++-++----+ +++-+-++++--++-++----++-+-++++--++-++---- ++-+-+-++++--++-++---+-+-+-++++--++-++--- ++--+-+-++++--++-++--+--+-+-++++--++-++-- ++---+-+-++++--++-++-+---+-+-++++--++-++- ++----+-+-++++--++-+++----+-+-++++--++-++ +++----+-+-++++--++-+++----+-+-++++--++-+ ++++----+-+-++++--++-+++----+-+-++++--++- ++-++----+-+-++++--+++-++----+-+-++++--++ ++--------------------+++++++++++++++++++ +++-++----+-+-++++--+--+--++++-+-+----++- ++++-++----+-+-++++-----+--++++-+-+----++ ++-++-++----+-+-++++--+--+--++++-+-+----+ ++--++-++----+-+-++++-++--+--++++-+-+---- +++--++-++----+-+-+++--++--+--++++-+-+--- ++++--++-++----+-+-++---++--+--++++-+-+-- +++++--++-++----+-+-+----++--+--++++-+-+- ++++++--++-++----+-+------++--+--++++-+-+ ++-++++--++-++----+-+-+----++--+--++++-+- +++-++++--++-++----+---+----++--+--++++-+ ++-+-++++--++-++----+-+-+----++--+--++++- +++-+-++++--++-++------+-+----++--+--++++ ++-+-+-++++--++-++----+-+-+----++--+--+++ ++--+-+-++++--++-++---++-+-+----++--+--++ ++---+-+-++++--++-++--+++-+-+----++--+--+ ++----+-+-++++--++-++-++++-+-+----++--+-- +++----+-+-++++--++-+--++++-+-+----++--+- ++++----+-+-++++--++----++++-+-+----++--+ ++-++----+-+-++++--++-+--++++-+-+----++-- +""" + + +def _parse_hadamard_str(s): + """Parse a ±1 string matrix definition into a numpy array.""" + s = s.strip().replace("+", "1").replace("-", "-1").split() + return np.stack( + [np.fromstring(" ".join(s[i]), dtype=np.int32, sep=" ") for i in range(len(s))] + ) + + +# Parsed M×M special Hadamard matrices, keyed by M (the "multiple"). +# Copied from python/sglang/jit_kernel/csrc/fast-hadamard-transform/code_gen.py +# (had_12_paley, had_20_will, had_28_will, had_40_tpal) +_SPECIAL_MATRICES = { + 12: _parse_hadamard_str(_HAD_12_STR), + 20: _parse_hadamard_str(_HAD_20_STR), + 28: _parse_hadamard_str(_HAD_28_STR), + 40: _parse_hadamard_str(_HAD_40_STR), +} + + +def hadamard_transform_ref(x, scale=1.0): + """Reference impl for the general (power-of-2) hadamard_transform. + + Pads dim to the next power of 2, multiplies by the full H matrix + via F.linear, then truncates back to the original dim. + """ + x_shape = x.shape + dim = x.shape[-1] + x = x.reshape(-1, dim) + log_dim = math.ceil(math.log2(dim)) if dim > 0 else 0 + dim_padded = 2**log_dim if dim > 0 else 1 + if dim != dim_padded: + x = F.pad(x, (0, dim_padded - dim)) + H = torch.tensor(hadamard(dim_padded, dtype=float), dtype=x.dtype, device=x.device) + out = F.linear(x, H) + out = out * scale + return out[..., :dim].reshape(*x_shape) + + +def hadamard_transform_mn_ref(x, multiple, scale=1.0): + """Reference impl for the M×N hadamard variants (_12n, _20n, _28n, _40n). + + The kernel computes (H_M ⊗ H_N) · x via two steps: + 1) H_N (power-of-2 Hadamard) along the N dimension + 2) H_M (special ±1 matrix) along the M dimension + where dim = M * N, M = `multiple`, N = power of 2. + """ + x_shape = x.shape + dim = x.shape[-1] + x = x.reshape(-1, dim) + + # The kernel requires dim % (4*M) == 0 (for vectorized memory access). + # See python/sglang/jit_kernel/hadamard.py: pad_multiple = 4 * 12 / 4 * 20 / etc. + pad_multiple = 4 * multiple + if dim % pad_multiple != 0: + pad_size = pad_multiple - dim % pad_multiple + x = F.pad(x, (0, pad_size)) + dim_padded = dim + pad_size + else: + dim_padded = dim + + # N = dim_padded / M, must be a power of 2 + n = dim_padded // multiple + log_n = int(math.log2(n)) + assert 2**log_n == n, f"n={n} is not a power of 2" + + batch = x.shape[0] + x = x.reshape(batch, multiple, n) # (batch, M, N) + + # Step 1: apply H_N (standard power-of-2 Hadamard) along the N dimension + H_n = torch.tensor(hadamard(n, dtype=float), dtype=x.dtype, device=x.device) + x = torch.einsum("bmn,kn->bmk", x, H_n) + + # Step 2: apply H_M (special ±1 matrix) along the M dimension + H_m = torch.tensor( + _SPECIAL_MATRICES[multiple].astype(float), dtype=x.dtype, device=x.device + ) + x = torch.einsum("bmn,km->bkn", x, H_m) + + x = x.reshape(batch, -1) * scale + return x[..., : x_shape[-1]].reshape(*x_shape) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize( + "dim", + # Power-of-2 dims from sgl-kernel/tests/test_hadamard.py (old AOT test) + [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768], +) +def test_hadamard_transform(dim, dtype): + device = "cuda" + + # Tolerances from sgl-kernel/tests/test_hadamard.py (old AOT test) + if dtype == torch.float32: + rtol, atol = 3e-4, 3e-3 + elif dtype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + else: # float16 + rtol, atol = 3e-3, 5e-3 + + torch.random.manual_seed(0) + batch_size = 15 + + x = torch.randn(batch_size, dim, device=device, dtype=dtype) + scale = 1.0 / math.sqrt(dim) + + out = hadamard_transform(x, scale=scale) + # Compute reference in float32 from a detached copy to avoid precision loss + out_ref = hadamard_transform_ref(x.detach().clone().float(), scale=scale) + + torch.testing.assert_close(out.float(), out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize( + "dim", + # Non-power-of-2 dims to test the padding path + # (137 from sgl-kernel/tests/test_hadamard.py, 500/1000 added for coverage) + [137, 500, 1000], +) +def test_hadamard_transform_non_power_of_two(dim, dtype): + device = "cuda" + + if dtype == torch.float32: + rtol, atol = 3e-4, 3e-3 + elif dtype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + else: + rtol, atol = 3e-3, 5e-3 + + torch.random.manual_seed(42) + batch_size = 15 + + x = torch.randn(batch_size, dim, device=device, dtype=dtype) + scale = 1.0 / math.sqrt(dim) + + out = hadamard_transform(x, scale=scale) + out_ref = hadamard_transform_ref(x.detach().clone().float(), scale=scale) + + torch.testing.assert_close(out.float(), out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_hadamard_transform_3d_input(dtype): + device = "cuda" + + if dtype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + else: + rtol, atol = 3e-3, 5e-3 + + torch.random.manual_seed(0) + + x = torch.randn(4, 8, 256, device=device, dtype=dtype) + scale = 1.0 / math.sqrt(256) + + out = hadamard_transform(x, scale=scale) + assert out.shape == x.shape + + out_ref = hadamard_transform_ref(x.detach().clone().float(), scale=scale) + torch.testing.assert_close(out.float(), out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_hadamard_transform_scale_one(dtype): + device = "cuda" + + if dtype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + else: + rtol, atol = 3e-3, 5e-3 + + torch.random.manual_seed(0) + + x = torch.randn(8, 64, device=device, dtype=dtype) + + out = hadamard_transform(x, scale=1.0) + out_ref = hadamard_transform_ref(x.detach().clone().float(), scale=1.0) + + torch.testing.assert_close(out.float(), out_ref, rtol=rtol, atol=atol) + + +# Test dimensions for M×N variants: dim = M * N where N = 2^k. +# M = 12/20/28/40 are the non-power-of-2 Hadamard sizes registered in +# python/sglang/jit_kernel/hadamard.py (Hadamard12NKernel, ..., Hadamard40NKernel). +# range(2,9) gives N = 4,8,...,256 so dims cover a practical range. +_12N_DIMS = [12 * (2**k) for k in range(2, 9)] # 48, 96, ... , 3072 +_20N_DIMS = [20 * (2**k) for k in range(2, 9)] # 80, 160, ... , 5120 +_28N_DIMS = [28 * (2**k) for k in range(2, 9)] # 112, 224, ... , 7168 +_40N_DIMS = [40 * (2**k) for k in range(2, 9)] # 160, 320, ... , 10240 + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("dim", _12N_DIMS) +def test_hadamard_transform_12n(dim, dtype): + device = "cuda" + + if dtype == torch.float32: + rtol, atol = 3e-4, 3e-3 + elif dtype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + else: + rtol, atol = 3e-3, 5e-3 + + torch.random.manual_seed(0) + batch_size = 15 + + x = torch.randn(batch_size, dim, device=device, dtype=dtype) + scale = 1.0 / math.sqrt(dim) + + out = hadamard_transform_12n(x, scale=scale) + out_ref = hadamard_transform_mn_ref(x.detach().clone().float(), 12, scale=scale) + + torch.testing.assert_close(out.float(), out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("dim", _20N_DIMS) +def test_hadamard_transform_20n(dim, dtype): + device = "cuda" + + if dtype == torch.float32: + rtol, atol = 3e-4, 3e-3 + elif dtype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + else: + rtol, atol = 3e-3, 5e-3 + + torch.random.manual_seed(0) + batch_size = 15 + + x = torch.randn(batch_size, dim, device=device, dtype=dtype) + scale = 1.0 / math.sqrt(dim) + + out = hadamard_transform_20n(x, scale=scale) + out_ref = hadamard_transform_mn_ref(x.detach().clone().float(), 20, scale=scale) + + torch.testing.assert_close(out.float(), out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("dim", _28N_DIMS) +def test_hadamard_transform_28n(dim, dtype): + device = "cuda" + + if dtype == torch.float32: + rtol, atol = 3e-4, 3e-3 + elif dtype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + else: + rtol, atol = 3e-3, 5e-3 + + torch.random.manual_seed(0) + batch_size = 15 + + x = torch.randn(batch_size, dim, device=device, dtype=dtype) + scale = 1.0 / math.sqrt(dim) + + out = hadamard_transform_28n(x, scale=scale) + out_ref = hadamard_transform_mn_ref(x.detach().clone().float(), 28, scale=scale) + + torch.testing.assert_close(out.float(), out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("dim", _40N_DIMS) +def test_hadamard_transform_40n(dim, dtype): + device = "cuda" + + if dtype == torch.float32: + rtol, atol = 3e-4, 3e-3 + elif dtype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + else: + rtol, atol = 3e-3, 5e-3 + + torch.random.manual_seed(0) + batch_size = 15 + + x = torch.randn(batch_size, dim, device=device, dtype=dtype) + scale = 1.0 / math.sqrt(dim) + + out = hadamard_transform_40n(x, scale=scale) + out_ref = hadamard_transform_mn_ref(x.detach().clone().float(), 40, scale=scale) + + torch.testing.assert_close(out.float(), out_ref, rtol=rtol, atol=atol) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_hicache.py b/asian_ai/performance/SGLang/test/registered/jit/test_hicache.py new file mode 100644 index 0000000000000000000000000000000000000000..badf29b8ce379cf8562c9d4f87d7243c6fbb1737 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_hicache.py @@ -0,0 +1,503 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.hicache import can_use_write_back_jit_kernel +from sglang.srt.mem_cache.memory_pool import MHATokenToKVPool, MLATokenToKVPool +from sglang.srt.mem_cache.memory_pool_host import ( + MHATokenToKVPoolHost, + MLATokenToKVPoolHost, +) +from sglang.srt.mem_cache.pool_host.common import ( + ALLOC_MEMORY_FUNCS, + alloc_with_pin_memory, +) +from sglang.srt.utils import is_cuda, is_hip, is_npu, is_xpu +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() + or is_npu() + or is_xpu() + or not (is_cuda() or is_hip()), + reason="HiCache JIT tests require CUDA/ROCm.", +) + +DEVICE = "cuda" +PAGE_SIZE = 1 if is_hip() else 16 +NUM_LAYERS = 2 +POOL_SIZE = PAGE_SIZE * 8 +MHA_ELEMENT_DIMS = [128, 256, 512, 1024] +MLA_ELEMENT_DIMS = [576] +LAYOUTS = ["layer_first", "page_first"] +STAGED_WRITE_BACK_PAGE_COUNTS = [1, 63, 64, 65, 67, 128, 129] + + +def _token_indices_for_pages( + pages: torch.Tensor, + page_size: int = PAGE_SIZE, + device: str = DEVICE, + dtype: torch.dtype = torch.int64, +) -> torch.Tensor: + parts = [ + torch.arange( + int(page) * page_size, + (int(page) + 1) * page_size, + device=device, + dtype=dtype, + ) + for page in pages.tolist() + ] + return torch.cat(parts, dim=0) + + +def _pinned_host_pool(host_pool_cls, **kwargs): + original_alloc = ALLOC_MEMORY_FUNCS[DEVICE] + ALLOC_MEMORY_FUNCS[DEVICE] = alloc_with_pin_memory + try: + return host_pool_cls( + host_to_device_ratio=2.0, + host_size=0, + page_size=PAGE_SIZE, + pin_memory=True, + device="cpu", + **kwargs, + ) + finally: + ALLOC_MEMORY_FUNCS[DEVICE] = original_alloc + + +def _copy_tensor_with_offset(tensor: torch.Tensor, offset: int) -> None: + data = torch.arange( + tensor.numel(), device=tensor.device, dtype=tensor.dtype + ).view_as(tensor) + tensor.copy_(data + offset) + + +def _assert_page_filled(tensor: torch.Tensor, page: int, value: float) -> None: + page_slice = tensor[page * PAGE_SIZE : (page + 1) * PAGE_SIZE] + expected = torch.full_like(page_slice, value) + assert torch.equal(page_slice.cpu(), expected.cpu()) + + +def _run_transfer_roundtrip_mha(layout: str, element_dim: int) -> None: + device_pool = MHATokenToKVPool( + size=POOL_SIZE, + page_size=PAGE_SIZE, + head_num=element_dim // 128, + head_dim=128, + dtype=torch.bfloat16, + layer_num=NUM_LAYERS, + device=DEVICE, + enable_memory_saver=False, + ) + host_pool = _pinned_host_pool( + MHATokenToKVPoolHost, + device_pool=device_pool, + layout=layout, + ) + assert ( + host_pool.can_use_jit + ), f"Expected JIT HiCache kernel for MHA dim={element_dim}" + + for layer_id in range(NUM_LAYERS): + _copy_tensor_with_offset(device_pool.k_buffer[layer_id], layer_id) + _copy_tensor_with_offset(device_pool.v_buffer[layer_id], layer_id + 100) + + device_pages = torch.tensor([1, 2, 3], device=DEVICE, dtype=torch.int64) + host_pages = torch.tensor([0, 1, 2], device=DEVICE, dtype=torch.int64) + device_indices = _token_indices_for_pages(device_pages) + host_indices = _token_indices_for_pages(host_pages) + host_indices_backup = ( + _token_indices_for_pages(host_pages, device="cpu") + if layout == "page_first" + else host_indices + ) + + host_pool.backup_from_device_all_layer( + device_pool, host_indices_backup, device_indices, "kernel" + ) + torch.cuda.synchronize() + + for layer_id in range(NUM_LAYERS): + for host_page, device_page in zip(host_pages.tolist(), device_pages.tolist()): + host_start = host_page * PAGE_SIZE + device_start = device_page * PAGE_SIZE + assert torch.equal( + host_pool.k_data_refs[layer_id][ + host_start : host_start + PAGE_SIZE + ].cpu(), + device_pool.k_buffer[layer_id][ + device_start : device_start + PAGE_SIZE + ].cpu(), + ) + assert torch.equal( + host_pool.v_data_refs[layer_id][ + host_start : host_start + PAGE_SIZE + ].cpu(), + device_pool.v_buffer[layer_id][ + device_start : device_start + PAGE_SIZE + ].cpu(), + ) + + for layer_id in range(NUM_LAYERS): + device_pool.k_buffer[layer_id].zero_() + device_pool.v_buffer[layer_id].zero_() + + load_pages = torch.tensor([4, 5, 6], device=DEVICE, dtype=torch.int64) + load_indices = _token_indices_for_pages(load_pages) + for layer_id in range(NUM_LAYERS): + host_pool.load_to_device_per_layer( + device_pool, host_indices, load_indices, layer_id, "kernel" + ) + torch.cuda.synchronize() + + for layer_id in range(NUM_LAYERS): + for host_page, device_page in zip(host_pages.tolist(), load_pages.tolist()): + host_start = host_page * PAGE_SIZE + device_start = device_page * PAGE_SIZE + assert torch.equal( + device_pool.k_buffer[layer_id][ + device_start : device_start + PAGE_SIZE + ].cpu(), + host_pool.k_data_refs[layer_id][ + host_start : host_start + PAGE_SIZE + ].cpu(), + ) + assert torch.equal( + device_pool.v_buffer[layer_id][ + device_start : device_start + PAGE_SIZE + ].cpu(), + host_pool.v_data_refs[layer_id][ + host_start : host_start + PAGE_SIZE + ].cpu(), + ) + + +def _run_transfer_roundtrip_mla(layout: str, element_dim: int) -> None: + device_pool = MLATokenToKVPool( + size=POOL_SIZE, + page_size=PAGE_SIZE, + kv_lora_rank=element_dim - 64, + qk_rope_head_dim=64, + dtype=torch.bfloat16, + layer_num=NUM_LAYERS, + device=DEVICE, + enable_memory_saver=False, + ) + host_pool = _pinned_host_pool( + MLATokenToKVPoolHost, + device_pool=device_pool, + layout=layout, + ) + assert ( + host_pool.can_use_jit + ), f"Expected JIT HiCache kernel for MLA dim={element_dim}" + + for layer_id in range(NUM_LAYERS): + _copy_tensor_with_offset(device_pool.kv_buffer[layer_id], layer_id) + + device_pages = torch.tensor([1, 2, 3], device=DEVICE, dtype=torch.int64) + host_pages = torch.tensor([0, 1, 2], device=DEVICE, dtype=torch.int64) + device_indices = _token_indices_for_pages(device_pages) + host_indices = _token_indices_for_pages(host_pages) + host_indices_backup = ( + _token_indices_for_pages(host_pages, device="cpu") + if layout == "page_first" + else host_indices + ) + + host_pool.backup_from_device_all_layer( + device_pool, host_indices_backup, device_indices, "kernel" + ) + torch.cuda.synchronize() + + for layer_id in range(NUM_LAYERS): + for host_page, device_page in zip(host_pages.tolist(), device_pages.tolist()): + host_start = host_page * PAGE_SIZE + device_start = device_page * PAGE_SIZE + assert torch.equal( + host_pool.data_refs[layer_id][ + host_start : host_start + PAGE_SIZE + ].cpu(), + device_pool.kv_buffer[layer_id][ + device_start : device_start + PAGE_SIZE + ].cpu(), + ) + + for layer_id in range(NUM_LAYERS): + device_pool.kv_buffer[layer_id].zero_() + + load_pages = torch.tensor([4, 5, 6], device=DEVICE, dtype=torch.int64) + load_indices = _token_indices_for_pages(load_pages) + for layer_id in range(NUM_LAYERS): + host_pool.load_to_device_per_layer( + device_pool, host_indices, load_indices, layer_id, "kernel" + ) + torch.cuda.synchronize() + + for layer_id in range(NUM_LAYERS): + for host_page, device_page in zip(host_pages.tolist(), load_pages.tolist()): + host_start = host_page * PAGE_SIZE + device_start = device_page * PAGE_SIZE + assert torch.equal( + device_pool.kv_buffer[layer_id][ + device_start : device_start + PAGE_SIZE + ].cpu(), + host_pool.data_refs[layer_id][ + host_start : host_start + PAGE_SIZE + ].cpu(), + ) + + +def _run_page_first_staged_write_back_mha( + layout: str, element_dim: int, page_count: int +) -> None: + pool_size = PAGE_SIZE * (page_count + 8) + head_num = ( + element_dim // 128 if element_dim >= 128 and element_dim % 128 == 0 else 1 + ) + head_dim = element_dim // head_num + device_pool = MHATokenToKVPool( + size=pool_size, + page_size=PAGE_SIZE, + head_num=head_num, + head_dim=head_dim, + dtype=torch.bfloat16, + layer_num=NUM_LAYERS, + device=DEVICE, + enable_memory_saver=False, + ) + host_pool = _pinned_host_pool( + MHATokenToKVPoolHost, + device_pool=device_pool, + layout=layout, + ) + assert can_use_write_back_jit_kernel( + element_size=element_dim * host_pool.dtype.itemsize, + ) + assert host_pool.can_use_write_back_jit + if element_dim * host_pool.dtype.itemsize % 128 != 0: + assert not host_pool.can_use_jit + assert host_pool.staging_page_capacity > 0 + if page_count > 64: + assert host_pool.staging_page_capacity < page_count + + for layer_id in range(NUM_LAYERS): + _copy_tensor_with_offset(device_pool.k_buffer[layer_id], layer_id) + _copy_tensor_with_offset(device_pool.v_buffer[layer_id], layer_id + 100) + host_pool.k_buffer.fill_(-7) + host_pool.v_buffer.fill_(-11) + + device_pages = torch.arange( + 2, + 2 + page_count, + device=DEVICE, + dtype=torch.int64, + ) + host_pages = torch.arange( + page_count, + 0, + -1, + dtype=torch.int64, + ) + src_index_dtype = torch.int32 if page_count == 64 else torch.int64 + device_indices = _token_indices_for_pages(device_pages, dtype=src_index_dtype) + host_indices = _token_indices_for_pages(host_pages, device="cpu") + assert not host_indices.is_cuda + expected_k = [ + device_pool.k_buffer[layer_id][device_indices.to(dtype=torch.int64)].cpu() + for layer_id in range(NUM_LAYERS) + ] + expected_v = [ + device_pool.v_buffer[layer_id][device_indices.to(dtype=torch.int64)].cpu() + for layer_id in range(NUM_LAYERS) + ] + + host_pool.backup_from_device_all_layer( + device_pool, host_indices, device_indices, "kernel" + ) + torch.cuda.synchronize() + + for layer_id in range(NUM_LAYERS): + for host_page, device_page in zip(host_pages.tolist(), device_pages.tolist()): + host_start = host_page * PAGE_SIZE + device_start = device_page * PAGE_SIZE + assert torch.equal( + host_pool.k_data_refs[layer_id][ + host_start : host_start + PAGE_SIZE + ].cpu(), + device_pool.k_buffer[layer_id][ + device_start : device_start + PAGE_SIZE + ].cpu(), + ) + assert torch.equal( + host_pool.v_data_refs[layer_id][ + host_start : host_start + PAGE_SIZE + ].cpu(), + device_pool.v_buffer[layer_id][ + device_start : device_start + PAGE_SIZE + ].cpu(), + ) + + for layer_id in range(NUM_LAYERS): + for untouched_page in [0, page_count + 1]: + _assert_page_filled(host_pool.k_data_refs[layer_id], untouched_page, -7) + _assert_page_filled(host_pool.v_data_refs[layer_id], untouched_page, -11) + + for layer_id in range(NUM_LAYERS): + device_pool.k_buffer[layer_id].zero_() + device_pool.v_buffer[layer_id].zero_() + load_indices = device_indices.to(dtype=torch.int64) + host_indices_load = _token_indices_for_pages(host_pages) + for layer_id in range(NUM_LAYERS): + host_pool.load_to_device_per_layer( + device_pool, host_indices_load, load_indices, layer_id, "kernel" + ) + torch.cuda.synchronize() + + for layer_id in range(NUM_LAYERS): + assert torch.equal( + device_pool.k_buffer[layer_id][load_indices].cpu(), expected_k[layer_id] + ) + assert torch.equal( + device_pool.v_buffer[layer_id][load_indices].cpu(), expected_v[layer_id] + ) + + +def _run_page_first_staged_write_back_mla( + layout: str, element_dim: int, page_count: int +) -> None: + pool_size = PAGE_SIZE * (page_count + 8) + device_pool = MLATokenToKVPool( + size=pool_size, + page_size=PAGE_SIZE, + kv_lora_rank=element_dim - 64, + qk_rope_head_dim=64, + dtype=torch.bfloat16, + layer_num=NUM_LAYERS, + device=DEVICE, + enable_memory_saver=False, + ) + host_pool = _pinned_host_pool( + MLATokenToKVPoolHost, + device_pool=device_pool, + layout=layout, + ) + assert can_use_write_back_jit_kernel( + element_size=element_dim * host_pool.dtype.itemsize, + ) + assert host_pool.can_use_write_back_jit + if element_dim * host_pool.dtype.itemsize % 128 != 0: + assert not host_pool.can_use_jit + assert host_pool.staging_page_capacity > 0 + if page_count > 64: + assert host_pool.staging_page_capacity < page_count + + for layer_id in range(NUM_LAYERS): + _copy_tensor_with_offset(device_pool.kv_buffer[layer_id], layer_id) + host_pool.kv_buffer.fill_(-13) + + device_pages = torch.arange( + 2, + 2 + page_count, + device=DEVICE, + dtype=torch.int64, + ) + host_pages = torch.arange( + page_count, + 0, + -1, + dtype=torch.int64, + ) + src_index_dtype = torch.int32 if page_count == 64 else torch.int64 + device_indices = _token_indices_for_pages(device_pages, dtype=src_index_dtype) + host_indices = _token_indices_for_pages(host_pages, device="cpu") + assert not host_indices.is_cuda + expected = [ + device_pool.kv_buffer[layer_id][device_indices.to(dtype=torch.int64)].cpu() + for layer_id in range(NUM_LAYERS) + ] + + host_pool.backup_from_device_all_layer( + device_pool, host_indices, device_indices, "kernel" + ) + torch.cuda.synchronize() + + for layer_id in range(NUM_LAYERS): + for host_page, device_page in zip(host_pages.tolist(), device_pages.tolist()): + host_start = host_page * PAGE_SIZE + device_start = device_page * PAGE_SIZE + assert torch.equal( + host_pool.data_refs[layer_id][ + host_start : host_start + PAGE_SIZE + ].cpu(), + device_pool.kv_buffer[layer_id][ + device_start : device_start + PAGE_SIZE + ].cpu(), + ) + + for layer_id in range(NUM_LAYERS): + for untouched_page in [0, page_count + 1]: + _assert_page_filled(host_pool.data_refs[layer_id], untouched_page, -13) + + for layer_id in range(NUM_LAYERS): + device_pool.kv_buffer[layer_id].zero_() + load_indices = device_indices.to(dtype=torch.int64) + host_indices_load = _token_indices_for_pages(host_pages) + for layer_id in range(NUM_LAYERS): + host_pool.load_to_device_per_layer( + device_pool, host_indices_load, load_indices, layer_id, "kernel" + ) + torch.cuda.synchronize() + + for layer_id in range(NUM_LAYERS): + assert torch.equal( + device_pool.kv_buffer[layer_id][load_indices].cpu(), expected[layer_id] + ) + + +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("element_dim", MHA_ELEMENT_DIMS) +def test_hicache_transfer_mha(layout: str, element_dim: int) -> None: + _run_transfer_roundtrip_mha(layout, element_dim) + + +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("element_dim", MLA_ELEMENT_DIMS) +def test_hicache_transfer_mla(layout: str, element_dim: int) -> None: + _run_transfer_roundtrip_mla(layout, element_dim) + + +@pytest.mark.parametrize("layout", ["page_first"]) +@pytest.mark.parametrize("element_dim", MHA_ELEMENT_DIMS) +@pytest.mark.parametrize("page_count", STAGED_WRITE_BACK_PAGE_COUNTS) +def test_hicache_page_first_staged_write_back_mha( + layout: str, element_dim: int, page_count: int +) -> None: + _run_page_first_staged_write_back_mha(layout, element_dim, page_count) + + +@pytest.mark.parametrize("layout", ["page_first"]) +@pytest.mark.parametrize("element_dim", MLA_ELEMENT_DIMS) +@pytest.mark.parametrize("page_count", STAGED_WRITE_BACK_PAGE_COUNTS) +def test_hicache_page_first_staged_write_back_mla( + layout: str, element_dim: int, page_count: int +) -> None: + _run_page_first_staged_write_back_mla(layout, element_dim, page_count) + + +def test_hicache_page_first_staged_write_back_mha_staged_only_alignment() -> None: + _run_page_first_staged_write_back_mha("page_first", 72, 65) + + +def test_hicache_page_first_staged_write_back_mla_staged_only_alignment() -> None: + _run_page_first_staged_write_back_mla("page_first", 72, 65) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_hisparse.py b/asian_ai/performance/SGLang/test/registered/jit/test_hisparse.py new file mode 100644 index 0000000000000000000000000000000000000000..430d1947e72e5280152d7d80dc152ce0b5baaba9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_hisparse.py @@ -0,0 +1,577 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.hisparse import ( + load_cache_to_device_buffer_dsv4_mla, + load_cache_to_device_buffer_mla, + transfer_cache_dsv4_mla, +) +from sglang.srt.utils import is_cuda, is_hip, is_npu, is_xpu +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_amd_ci(est_time=30, stage="stage-b", runner_config="1-gpu-small-amd") +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() + or is_npu() + or is_xpu() + or not (is_cuda() or is_hip()), + reason="HiSparse JIT tests require CUDA/ROCm.", +) + +DEVICE = "cuda" +DTYPE = torch.float32 +KV_DIM = 8 +HOT_BUFFER_SIZE = 4 +PADDED_BUFFER_SIZE = HOT_BUFFER_SIZE + 1 +HOST_CACHE_SIZE = 16 +DEVICE_CACHE_SIZE = 16 +ITEM_SIZE_BYTES = KV_DIM * torch.empty((), dtype=DTYPE).element_size() +DSV4_PAGE_SIZE = 64 +DSV4_VALUE_BYTES = 576 +DSV4_SCALE_BYTES = 8 +DSV4_ITEM_BYTES = DSV4_VALUE_BYTES + DSV4_SCALE_BYTES +DSV4_PAGE_BYTES = ((DSV4_ITEM_BYTES * DSV4_PAGE_SIZE + 575) // 576) * 576 +DSV4_SCALE_OFFSET = DSV4_VALUE_BYTES * DSV4_PAGE_SIZE + + +def _host_cache() -> torch.Tensor: + host_cache = torch.empty( + (HOST_CACHE_SIZE, 1, KV_DIM), dtype=DTYPE, device="cpu", pin_memory=True + ) + host_cache.copy_(torch.arange(host_cache.numel(), dtype=DTYPE).view_as(host_cache)) + return host_cache + + +def _dsv4_token_pattern(seed: int) -> tuple[torch.Tensor, torch.Tensor]: + value = ( + (torch.arange(DSV4_VALUE_BYTES, dtype=torch.int16) + seed) + .remainder(256) + .to(torch.uint8) + ) + scale = ( + (torch.arange(DSV4_SCALE_BYTES, dtype=torch.int16) + seed + 17) + .remainder(256) + .to(torch.uint8) + ) + return value, scale + + +def _write_dsv4_token(cache: torch.Tensor, loc: int, seed: int) -> None: + page = loc // DSV4_PAGE_SIZE + offset = loc % DSV4_PAGE_SIZE + value, scale = _dsv4_token_pattern(seed) + cache[page, offset * DSV4_VALUE_BYTES : (offset + 1) * DSV4_VALUE_BYTES].copy_( + value.to(cache.device) + ) + scale_start = DSV4_SCALE_OFFSET + offset * DSV4_SCALE_BYTES + cache[page, scale_start : scale_start + DSV4_SCALE_BYTES].copy_( + scale.to(cache.device) + ) + + +def _read_dsv4_token(cache: torch.Tensor, loc: int) -> torch.Tensor: + page = loc // DSV4_PAGE_SIZE + offset = loc % DSV4_PAGE_SIZE + value = cache[page, offset * DSV4_VALUE_BYTES : (offset + 1) * DSV4_VALUE_BYTES] + scale_start = DSV4_SCALE_OFFSET + offset * DSV4_SCALE_BYTES + scale = cache[page, scale_start : scale_start + DSV4_SCALE_BYTES] + return torch.cat([value, scale]) + + +def _dsv4_ptrs(cache: torch.Tensor) -> torch.Tensor: + return torch.tensor([cache.data_ptr()], dtype=torch.uint64, device=DEVICE) + + +def _run_kernel( + *, + top_k_tokens: torch.Tensor, + device_buffer_tokens: torch.Tensor, + host_cache_locs: torch.Tensor, + device_buffer_locs: torch.Tensor, + host_cache: torch.Tensor, + device_buffer: torch.Tensor, + lru_slots: torch.Tensor, + seq_len: int | None = None, + seq_lens: torch.Tensor | None = None, + seq_lens_dtype: torch.dtype = torch.int32, + req_pool_indices: torch.Tensor | None = None, + num_real_reqs: int | None = None, +) -> torch.Tensor: + batch_size = top_k_tokens.shape[0] + if req_pool_indices is None: + req_pool_indices = torch.arange(batch_size, dtype=torch.int64, device=DEVICE) + if seq_lens is None: + seq_lens = torch.full( + (batch_size,), seq_len, dtype=seq_lens_dtype, device=DEVICE + ) + if num_real_reqs is None: + num_real_reqs = batch_size + + out = torch.full_like(top_k_tokens, -1) + load_cache_to_device_buffer_mla( + top_k_tokens=top_k_tokens, + device_buffer_tokens=device_buffer_tokens, + host_cache_locs=host_cache_locs, + device_buffer_locs=device_buffer_locs, + host_cache=host_cache, + device_buffer=device_buffer, + top_k_device_locs=out, + req_pool_indices=req_pool_indices, + seq_lens=seq_lens, + lru_slots=lru_slots, + item_size_bytes=ITEM_SIZE_BYTES, + num_top_k=top_k_tokens.shape[1], + hot_buffer_size=HOT_BUFFER_SIZE, + page_size=1, + block_size=256, + num_real_reqs=torch.tensor([num_real_reqs], dtype=torch.int32, device=DEVICE), + ) + torch.cuda.synchronize() + return out + + +def _make_state( + device_buffer_locs_rows: list[list[int]], + device_buffer_tokens_rows: list[list[int]], + newest_tokens: list[int], +): + host_cache = _host_cache() + device_buffer = torch.full( + (DEVICE_CACHE_SIZE, 1, KV_DIM), -1, dtype=DTYPE, device=DEVICE + ) + device_buffer_locs = torch.tensor( + device_buffer_locs_rows, dtype=torch.int32, device=DEVICE + ) + device_buffer_tokens = torch.tensor( + device_buffer_tokens_rows, dtype=torch.int32, device=DEVICE + ) + lru_slots = ( + torch.arange(HOT_BUFFER_SIZE, dtype=torch.int16, device=DEVICE) + .view(1, -1) + .repeat(device_buffer_locs.shape[0], 1) + ) + host_cache_locs = ( + torch.arange(HOST_CACHE_SIZE, dtype=torch.int64, device=DEVICE) + .view(1, -1) + .repeat(device_buffer_locs.shape[0], 1) + ) + + # Slots 0..3 participate in LRU; slot 4 is the reserved newest slot. + for rid, newest_token in enumerate(newest_tokens): + for slot, token in enumerate(device_buffer_tokens_rows[rid][:HOT_BUFFER_SIZE]): + if token >= 0: + device_buffer[device_buffer_locs[rid, slot]].copy_( + host_cache[token].to(DEVICE, non_blocking=True) + ) + device_buffer[device_buffer_locs[rid, HOT_BUFFER_SIZE]].copy_( + host_cache[newest_token].to(DEVICE, non_blocking=True) + ) + torch.cuda.synchronize() + + return { + "host_cache": host_cache, + "device_buffer": device_buffer, + "device_buffer_locs": device_buffer_locs, + "device_buffer_tokens": device_buffer_tokens, + "lru_slots": lru_slots, + "host_cache_locs": host_cache_locs, + } + + +@pytest.mark.skipif(is_hip(), reason="DSV4 paged-layout HiSparse test is CUDA-only.") +def test_transfer_cache_dsv4_mla_copies_paged_token() -> None: + src_cache = torch.zeros((2, DSV4_PAGE_BYTES), dtype=torch.uint8, device=DEVICE) + dst_cache = torch.zeros( + (2, DSV4_PAGE_BYTES), dtype=torch.uint8, device="cpu", pin_memory=True + ) + src_loc = DSV4_PAGE_SIZE + 6 + dst_loc = DSV4_PAGE_SIZE + 1 + _write_dsv4_token(src_cache, src_loc, seed=41) + + transfer_cache_dsv4_mla( + src_ptrs=_dsv4_ptrs(src_cache), + dst_ptrs=_dsv4_ptrs(dst_cache), + src_indices=torch.tensor([src_loc], dtype=torch.int64, device=DEVICE), + dst_indices=torch.tensor([dst_loc], dtype=torch.int64, device=DEVICE), + ) + torch.cuda.synchronize() + + assert torch.equal( + _read_dsv4_token(dst_cache, dst_loc).to(DEVICE), + _read_dsv4_token(src_cache, src_loc), + ) + + +@pytest.mark.skipif(is_hip(), reason="DSV4 paged-layout HiSparse test is CUDA-only.") +def test_dsv4_swap_in_reads_paged_host_layout() -> None: + host_cache = torch.zeros( + (2, DSV4_PAGE_BYTES), dtype=torch.uint8, device="cpu", pin_memory=True + ) + device_buffer = torch.zeros((2, DSV4_PAGE_BYTES), dtype=torch.uint8, device=DEVICE) + host_loc = DSV4_PAGE_SIZE + 1 + swap_loc = DSV4_PAGE_SIZE + 12 + _write_dsv4_token(host_cache, host_loc, seed=41) + + top_k_tokens = torch.tensor([[3]], dtype=torch.int32, device=DEVICE) + device_buffer_tokens = torch.full( + (1, PADDED_BUFFER_SIZE), -1, dtype=torch.int32, device=DEVICE + ) + host_cache_locs = torch.zeros((1, 8), dtype=torch.int64, device=DEVICE) + host_cache_locs[0, 3] = host_loc + device_buffer_locs = torch.tensor( + [[swap_loc, swap_loc + 1, swap_loc + 2, swap_loc + 3, swap_loc + 4]], + dtype=torch.int32, + device=DEVICE, + ) + lru_slots = torch.arange(HOT_BUFFER_SIZE, dtype=torch.int16, device=DEVICE).view( + 1, -1 + ) + out = torch.full_like(top_k_tokens, -1) + + load_cache_to_device_buffer_dsv4_mla( + top_k_tokens=top_k_tokens, + device_buffer_tokens=device_buffer_tokens, + host_cache_locs=host_cache_locs, + device_buffer_locs=device_buffer_locs, + host_cache=host_cache, + device_buffer=device_buffer, + top_k_device_locs=out, + req_pool_indices=torch.tensor([0], dtype=torch.int64, device=DEVICE), + seq_lens=torch.tensor([8], dtype=torch.int32, device=DEVICE), + lru_slots=lru_slots, + item_size_bytes=DSV4_ITEM_BYTES, + num_top_k=1, + hot_buffer_size=HOT_BUFFER_SIZE, + page_size=1, + block_size=256, + num_real_reqs=torch.tensor([1], dtype=torch.int32, device=DEVICE), + ) + torch.cuda.synchronize() + + assert out.item() == swap_loc + assert torch.equal( + _read_dsv4_token(device_buffer, swap_loc), + _read_dsv4_token(host_cache, host_loc).to(DEVICE), + ) + + +def _long_case(): + # One-request baseline used by the stateful cases below: + # req 0 LRU slots : [0, 1, 2, 3] + # req 0 cached tokens : slot0->1, slot1->4, slot2->2, slot3->5 + # req 0 physical locs : slot0->9, slot1->7, slot2->3, slot3->5 + # req 0 newest slot : slot4/newest -> token 7 at physical loc 11 + return _make_state([[9, 7, 3, 5, 11]], [[1, 4, 2, 5, -1]], [7]) + + +@pytest.mark.parametrize("seq_lens_dtype", [torch.int32, torch.int64]) +def test_load_cache_to_device_buffer_fast_path(seq_lens_dtype: torch.dtype) -> None: + host_cache = _host_cache() + device_buffer = torch.arange( + DEVICE_CACHE_SIZE * KV_DIM, dtype=DTYPE, device=DEVICE + ).view(DEVICE_CACHE_SIZE, 1, KV_DIM) + device_buffer_before = device_buffer.clone() + device_buffer_locs = torch.tensor( + [[13, 9, 5, 1, 15]], dtype=torch.int32, device=DEVICE + ) + device_buffer_tokens = torch.tensor( + [[10, 11, 12, 13, -1]], dtype=torch.int32, device=DEVICE + ) + device_buffer_tokens_before = device_buffer_tokens.clone() + lru_slots = torch.tensor([[0, 1, 2, 3]], dtype=torch.int16, device=DEVICE) + lru_slots_before = lru_slots.clone() + + # Short-sequence layout: + # token position 0 -> physical loc 13 + # token position 1 -> physical loc 9 + # token position 2 -> physical loc 5 + # + # seq_len <= HOT_BUFFER_SIZE should skip host loads and LRU mutations, + # so top_k_tokens acts like direct indexing into device_buffer_locs. + out = _run_kernel( + top_k_tokens=torch.tensor([[2, 0, 1]], dtype=torch.int32, device=DEVICE), + device_buffer_tokens=device_buffer_tokens, + host_cache_locs=torch.arange( + HOST_CACHE_SIZE, dtype=torch.int64, device=DEVICE + ).view(1, -1), + device_buffer_locs=device_buffer_locs, + host_cache=host_cache, + device_buffer=device_buffer, + lru_slots=lru_slots, + seq_len=3, + seq_lens_dtype=seq_lens_dtype, + ) + + assert torch.equal(out.cpu(), torch.tensor([[5, 13, 9]], dtype=torch.int32)) + assert torch.equal(device_buffer_tokens.cpu(), device_buffer_tokens_before.cpu()) + assert torch.equal(lru_slots.cpu(), lru_slots_before.cpu()) + assert torch.equal(device_buffer.cpu(), device_buffer_before.cpu()) + + +def test_load_cache_to_device_buffer_hits_newest_and_updates_lru() -> None: + state = _long_case() + + # Query [4, 2, 7]: + # 4 hits slot1 -> loc 7 + # 2 hits slot2 -> loc 3 + # 7 is the newest token -> reserved newest loc 11 + # + # Hits move to the MRU tail, so [0, 1, 2, 3] becomes [0, 3, 1, 2]. + out = _run_kernel( + top_k_tokens=torch.tensor([[4, 2, 7]], dtype=torch.int32, device=DEVICE), + seq_len=8, + **state, + ) + + assert torch.equal(out.cpu(), torch.tensor([[7, 3, 11]], dtype=torch.int32)) + assert torch.equal( + state["device_buffer_tokens"].cpu(), + torch.tensor([[1, 4, 2, 5, -1]], dtype=torch.int32), + ) + assert torch.equal( + state["lru_slots"].cpu(), torch.tensor([[0, 3, 1, 2]], dtype=torch.int16) + ) + + +def test_load_cache_to_device_buffer_miss_uses_updated_lru_slot() -> None: + state = _long_case() + + # Step 1: touch tokens [4, 2], so LRU becomes [0, 3, 1, 2]. + # Step 2: query token 6, which is a miss. + # The kernel should reuse the new LRU head slot0, whose physical loc is 9. + # This round has no regular hits, so the freshly loaded miss slot ends up at the tail. + _run_kernel( + top_k_tokens=torch.tensor([[4, 2]], dtype=torch.int32, device=DEVICE), + seq_len=8, + **state, + ) + out = _run_kernel( + top_k_tokens=torch.tensor([[6]], dtype=torch.int32, device=DEVICE), + seq_len=8, + **state, + ) + + assert torch.equal(out.cpu(), torch.tensor([[9]], dtype=torch.int32)) + assert torch.equal( + state["device_buffer_tokens"].cpu(), + torch.tensor([[6, 4, 2, 5, -1]], dtype=torch.int32), + ) + assert torch.equal( + state["lru_slots"].cpu(), torch.tensor([[3, 1, 2, 0]], dtype=torch.int16) + ) + assert torch.equal(state["device_buffer"][9].cpu(), state["host_cache"][6]) + + +def test_load_cache_to_device_buffer_multiple_misses_copy_all_slots() -> None: + state = _make_state( + [[9, 7, 3, 5, 11]], + [[0, 1, 2, 3, -1]], + [8], + ) + + out = _run_kernel( + top_k_tokens=torch.tensor([[4, 5, 6, 7]], dtype=torch.int32, device=DEVICE), + seq_len=9, + **state, + ) + + assert torch.equal(out.cpu(), torch.tensor([[9, 7, 3, 5]], dtype=torch.int32)) + assert torch.equal( + state["device_buffer_tokens"].cpu(), + torch.tensor([[4, 5, 6, 7, -1]], dtype=torch.int32), + ) + assert torch.equal( + state["lru_slots"].cpu(), torch.tensor([[0, 1, 2, 3]], dtype=torch.int16) + ) + for token, loc in zip([4, 5, 6, 7], [9, 7, 3, 5]): + assert torch.equal( + state["device_buffer"][loc].cpu(), state["host_cache"][token] + ) + + +def test_load_cache_to_device_buffer_batched_with_padding() -> None: + state = _make_state( + [ + [9, 7, 3, 5, 11], + [12, 10, 8, 6, 14], + [15, 4, 2, 1, 13], + ], + [ + [1, 4, 2, 5, -1], + [0, 1, 2, 3, -1], + [9, 8, 7, 6, -1], + ], + [7, 4, 5], + ) + padded_tokens_before = state["device_buffer_tokens"][2].clone() + padded_lru_before = state["lru_slots"][2].clone() + + # req 0: long path + # cached tokens/locs : 1@9, 4@7, 2@3, 5@5, newest 7@11 + # query [4, 6, 7] : hit loc 7, miss into slot0/loc 9, newest loc 11 + # LRU update : remaining evictables [2, 3], then miss [0], then hit [1] + # : [0, 1, 2, 3] -> [2, 3, 0, 1] + # + # req 1: fast path + # seq_len = 3 <= HOT_BUFFER_SIZE, so [2, 1, 0] maps directly to locs [8, 10, 12] + # + # req 2: padded block + # num_real_reqs = 2 means this row must be ignored entirely. + out = _run_kernel( + top_k_tokens=torch.tensor( + [[4, 6, 7], [2, 1, 0], [9, 8, 7]], dtype=torch.int32, device=DEVICE + ), + seq_lens=torch.tensor([8, 3, 8], dtype=torch.int32, device=DEVICE), + num_real_reqs=2, + **state, + ) + + assert torch.equal( + out.cpu(), + torch.tensor([[7, 9, 11], [8, 10, 12], [-1, -1, -1]], dtype=torch.int32), + ) + assert torch.equal( + state["device_buffer_tokens"][:2].cpu(), + torch.tensor([[6, 4, 2, 5, -1], [0, 1, 2, 3, -1]], dtype=torch.int32), + ) + assert torch.equal( + state["lru_slots"][:2].cpu(), + torch.tensor([[2, 3, 0, 1], [0, 1, 2, 3]], dtype=torch.int16), + ) + assert torch.equal( + state["device_buffer_tokens"][2].cpu(), padded_tokens_before.cpu() + ) + assert torch.equal(state["lru_slots"][2].cpu(), padded_lru_before.cpu()) + assert torch.equal(state["device_buffer"][9].cpu(), state["host_cache"][6]) + + +def test_load_cache_to_device_buffer_dsv4_mla_miss_copy_layout() -> None: + # Both the host cache and the device buffer use the page-padded C4 layout, + # matching DeepSeekV4PagedHostPool, the backup/write path, and the swap-in + # kernel on both CUDA and ROCm. The miss copy must read the host source with + # paged addressing (get_pointer_paged), not a linear per-item stride. + num_pages = (HOST_CACHE_SIZE + DSV4_PAGE_SIZE - 1) // DSV4_PAGE_SIZE + + state = _long_case() + host_cache = torch.zeros( + (num_pages, DSV4_PAGE_BYTES), + dtype=torch.uint8, + device="cpu", + pin_memory=True, + ) + for token in range(HOST_CACHE_SIZE): + _write_dsv4_token(host_cache, token, seed=token + 1) + + device_buffer = torch.full( + (num_pages, DSV4_PAGE_BYTES), + 0xFF, + dtype=torch.uint8, + device=DEVICE, + ) + out = torch.full((1, 1), -1, dtype=torch.int32, device=DEVICE) + + # Token 6 is a miss in _long_case(), so it should be copied into evict slot 0, + # whose physical device loc is 9. + load_cache_to_device_buffer_dsv4_mla( + top_k_tokens=torch.tensor([[6]], dtype=torch.int32, device=DEVICE), + device_buffer_tokens=state["device_buffer_tokens"], + host_cache_locs=state["host_cache_locs"], + device_buffer_locs=state["device_buffer_locs"], + host_cache=host_cache, + device_buffer=device_buffer, + top_k_device_locs=out, + req_pool_indices=torch.tensor([0], dtype=torch.int64, device=DEVICE), + seq_lens=torch.tensor([8], dtype=torch.int32, device=DEVICE), + lru_slots=state["lru_slots"], + item_size_bytes=DSV4_ITEM_BYTES, + num_top_k=1, + hot_buffer_size=HOT_BUFFER_SIZE, + page_size=DSV4_PAGE_SIZE, + block_size=256, + num_real_reqs=torch.tensor([1], dtype=torch.int32, device=DEVICE), + ) + torch.cuda.synchronize() + + assert torch.equal(out.cpu(), torch.tensor([[9]], dtype=torch.int32)) + + # host_cache_locs[token=6] == 6 in _long_case(); evict slot 0 -> device loc 9. + assert torch.equal( + _read_dsv4_token(device_buffer, 9).cpu(), + _read_dsv4_token(host_cache, 6), + ) + + +@pytest.mark.skipif( + not is_hip(), reason="Covers a ROCm wavefront64 LRU writeback regression." +) +def test_load_cache_to_device_buffer_rocm_large_lru_writeback() -> None: + top_k = 2048 + hot_buffer_size = 4096 + seq_len = 7299 + kv_dim = 4 + item_size_bytes = kv_dim * torch.empty((), dtype=DTYPE).element_size() + + top_k_tokens = torch.cat( + [ + torch.arange(1000, 2000, dtype=torch.int32), + torch.arange(5000, 6048, dtype=torch.int32), + ] + ).view(1, -1) + device_buffer_tokens = torch.arange(hot_buffer_size, dtype=torch.int32).view(1, -1) + device_buffer_locs = torch.arange(hot_buffer_size + 1, dtype=torch.int32).view( + 1, -1 + ) + lru_slots = torch.arange(hot_buffer_size, dtype=torch.int16).view(1, -1) + host_cache_locs = torch.arange(seq_len, dtype=torch.int64).view(1, -1) + + top_k_tokens = top_k_tokens.to(DEVICE) + device_buffer_tokens = device_buffer_tokens.to(DEVICE) + device_buffer_locs = device_buffer_locs.to(DEVICE) + lru_slots = lru_slots.to(DEVICE) + host_cache_locs = host_cache_locs.to(DEVICE) + + host_cache = torch.empty((seq_len, 1, kv_dim), dtype=DTYPE, pin_memory=True) + host_cache.zero_() + device_buffer = torch.empty( + (hot_buffer_size + 1, 1, kv_dim), dtype=DTYPE, device=DEVICE + ) + out = torch.full_like(top_k_tokens, -1) + + load_cache_to_device_buffer_mla( + top_k_tokens=top_k_tokens, + device_buffer_tokens=device_buffer_tokens, + host_cache_locs=host_cache_locs, + device_buffer_locs=device_buffer_locs, + host_cache=host_cache, + device_buffer=device_buffer, + top_k_device_locs=out, + req_pool_indices=torch.tensor([0], dtype=torch.int64, device=DEVICE), + seq_lens=torch.tensor([seq_len], dtype=torch.int32, device=DEVICE), + lru_slots=lru_slots, + item_size_bytes=item_size_bytes, + num_top_k=top_k, + hot_buffer_size=hot_buffer_size, + page_size=1, + block_size=1024, + num_real_reqs=torch.tensor([1], dtype=torch.int32, device=DEVICE), + ) + torch.cuda.synchronize() + + expected_lru = torch.cat( + [ + torch.arange(2048, 4096, dtype=torch.int16), + torch.arange(0, 1000, dtype=torch.int16), + torch.arange(2000, 2048, dtype=torch.int16), + torch.arange(1000, 2000, dtype=torch.int16), + ] + ) + assert torch.equal(lru_slots.cpu().view(-1), expected_lru) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_kpool_topk_transform.py b/asian_ai/performance/SGLang/test/registered/jit/test_kpool_topk_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7caa26fa909828175be59e3e9ea58e9556ec6f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_kpool_topk_transform.py @@ -0,0 +1,136 @@ +"""Test for the kpool top-k transform JIT kernel. + +Ported from the former AOT sgl-kernel test (sgl-kernel/tests/test_topk.py). +The kernel selects pool groups at pool granularity, expands each selected group +to ``pool_size`` token indices, and optionally transforms those token indices +through a page table or a ragged offset. +""" + +from __future__ import annotations + +import sys +from typing import Optional + +import pytest +import torch + +from sglang.jit_kernel.kpool_topk_transform import fast_kpool_topk_transform_fused +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") + + +def _ref_torch_kpool_transform_impl( + score: torch.Tensor, + lengths: torch.Tensor, + pool_size: int, + topk: int, + page_table: Optional[torch.Tensor] = None, + topk_indices_offset: Optional[torch.Tensor] = None, + seq_lens: Optional[torch.Tensor] = None, +) -> torch.Tensor: + rows = score.shape[0] + group_topk = topk // pool_size + offsets = torch.arange(pool_size, dtype=torch.int32, device=score.device) + out_cols = topk + (pool_size - 1 if seq_lens is not None else 0) + out = torch.full((rows, out_cols), -1, dtype=torch.int32, device=score.device) + for i in range(rows): + length = int(lengths[i].item()) + valid_count = min(length, group_topk) + write_pos = 0 + if valid_count == 0: + token_ids = torch.empty((0,), dtype=torch.int32, device=score.device) + elif length <= group_topk: + selected = torch.arange(length, dtype=torch.int32, device=score.device) + token_ids = (selected.unsqueeze(1) * pool_size + offsets).reshape(-1) + else: + selected = torch.topk( + score[i, :length], group_topk, dim=-1, sorted=False + ).indices.to(torch.int32) + token_ids = (selected.unsqueeze(1) * pool_size + offsets).reshape(-1) + if token_ids.numel() > 0: + if page_table is not None: + token_ids = page_table[i, token_ids.long()].to(torch.int32) + elif topk_indices_offset is not None: + token_ids = token_ids + topk_indices_offset[i].to(torch.int32) + write_pos = valid_count * pool_size + out[i, :write_pos] = token_ids[:write_pos] + if seq_lens is not None: + tail_count = int(seq_lens[i].item()) % pool_size + if tail_count > 0: + raw_tail = length * pool_size + torch.arange( + tail_count, dtype=torch.int32, device=score.device + ) + if page_table is not None: + tail = page_table[i, raw_tail.long()].to(torch.int32) + elif topk_indices_offset is not None: + tail = raw_tail + topk_indices_offset[i].to(torch.int32) + else: + tail = raw_tail + out[i, write_pos : write_pos + tail_count] = tail + return out + + +@pytest.mark.parametrize( + "pool_size,group_topk", + [(16, 128), (16, 160), (16, 192), (16, 224), (8, 256), (4, 512)], +) +@pytest.mark.parametrize("mode", ["raw", "paged", "ragged"]) +@pytest.mark.parametrize("append_tail", [False, True]) +@torch.inference_mode() +def test_kpool_topk_transform_kernel( + pool_size: int, group_topk: int, mode: str, append_tail: bool +) -> None: + torch.manual_seed(42) + bs = 17 + topk = pool_size * group_topk + num_groups = 4096 + score = torch.randn(bs, num_groups, dtype=torch.float32, device="cuda") + lengths = torch.randint( + group_topk + 1, num_groups + 1, (bs,), dtype=torch.int32, device="cuda" + ) + + page_table = None + topk_indices_offset = None + seq_lens = None + tail_counts = torch.randint(0, pool_size, (bs,), dtype=torch.int32, device="cuda") + if append_tail: + seq_lens = lengths * pool_size + tail_counts + if mode == "paged": + page_table = torch.arange( + bs * (num_groups * pool_size + pool_size), + dtype=torch.int32, + device="cuda", + ).view(bs, num_groups * pool_size + pool_size) + elif mode == "ragged": + topk_indices_offset = torch.randint( + 0, 2048, (bs,), dtype=torch.int32, device="cuda" + ) + + out_ref = _ref_torch_kpool_transform_impl( + score, + lengths, + pool_size, + topk, + page_table=page_table, + topk_indices_offset=topk_indices_offset, + seq_lens=seq_lens, + ) + out_our = fast_kpool_topk_transform_fused( + score, + lengths, + pool_size, + topk, + page_table=page_table, + topk_indices_offset=topk_indices_offset, + seq_lens=seq_lens, + ) + torch.cuda.synchronize() + + out_ref = torch.sort(out_ref, dim=-1).values + out_our = torch.sort(out_our, dim=-1).values + torch.testing.assert_close(out_our, out_ref, atol=0, rtol=0) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_kvcacheio_asymmetric.py b/asian_ai/performance/SGLang/test/registered/jit/test_kvcacheio_asymmetric.py new file mode 100644 index 0000000000000000000000000000000000000000..dd6c2464212a4d4b5c76bf2b0682c69b8d0a9fa0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_kvcacheio_asymmetric.py @@ -0,0 +1,212 @@ +import sys +from types import SimpleNamespace + +import pytest +import torch + +from sglang.srt.mem_cache.memory_pool_host import AsymmetricMHATokenToKVPoolHost +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=10, suite="nightly-amd-kernel-1-gpu", nightly=True) + +# These tests use AsymmetricMHATokenToKVPoolHost methods and let that class call +# the real sgl-kernel transfer ops. +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="asymmetric host-pool tests require CUDA." +) + +DEVICE = "cuda" +PAGE_SIZE = 16 +NUM_LAYERS = 3 +TOTAL_ITEMS = PAGE_SIZE * 8 +HEAD_NUM = 4 +K_HEAD_DIM = 192 +V_HEAD_DIM = 128 +DTYPES = [torch.float16, torch.bfloat16] + + +def token_indices_for_pages(pages, page_size=PAGE_SIZE, device=None): + indices = torch.cat( + [ + torch.arange( + int(page) * page_size, + (int(page) + 1) * page_size, + dtype=torch.int64, + ) + for page in pages.tolist() + ] + ) + return indices if device is None else indices.to(device) + + +def fill_with_offset(tensor, offset): + data = torch.arange(tensor.numel(), device=tensor.device, dtype=tensor.dtype) + tensor.copy_((data + offset).view_as(tensor)) + + +def make_host_pool(dtype, layout="page_first"): + host = AsymmetricMHATokenToKVPoolHost.__new__(AsymmetricMHATokenToKVPoolHost) + host.layout = layout + host.page_size = PAGE_SIZE + host.page_num = TOTAL_ITEMS // PAGE_SIZE + host.layer_num = NUM_LAYERS + host.head_num = HEAD_NUM + host.head_dim = K_HEAD_DIM + host.v_head_dim = V_HEAD_DIM + host.dtype = dtype + if layout == "page_first": + k_dims = (TOTAL_ITEMS, NUM_LAYERS, HEAD_NUM, K_HEAD_DIM) + v_dims = (TOTAL_ITEMS, NUM_LAYERS, HEAD_NUM, V_HEAD_DIM) + elif layout == "page_first_direct": + k_dims = (host.page_num, NUM_LAYERS, PAGE_SIZE, HEAD_NUM, K_HEAD_DIM) + v_dims = (host.page_num, NUM_LAYERS, PAGE_SIZE, HEAD_NUM, V_HEAD_DIM) + else: + raise ValueError(f"Unsupported layout: {layout}") + host.kv_buffer = ( + torch.zeros(k_dims, dtype=dtype).pin_memory(), + torch.zeros(v_dims, dtype=dtype).pin_memory(), + ) + return host + + +def make_device_pool(dtype): + k_buffer = [ + torch.empty(TOTAL_ITEMS, HEAD_NUM, K_HEAD_DIM, dtype=dtype, device=DEVICE) + for _ in range(NUM_LAYERS) + ] + v_buffer = [ + torch.empty(TOTAL_ITEMS, HEAD_NUM, V_HEAD_DIM, dtype=dtype, device=DEVICE) + for _ in range(NUM_LAYERS) + ] + for layer_id in range(NUM_LAYERS): + fill_with_offset(k_buffer[layer_id], layer_id * 1000) + fill_with_offset(v_buffer[layer_id], layer_id * 1000 + 100) + + return SimpleNamespace( + k_buffer=k_buffer, + v_buffer=v_buffer, + k_data_ptrs=torch.tensor( + [x.data_ptr() for x in k_buffer], dtype=torch.uint64, device=DEVICE + ), + v_data_ptrs=torch.tensor( + [x.data_ptr() for x in v_buffer], dtype=torch.uint64, device=DEVICE + ), + ) + + +def _host_k_tokens(host, indices, layer_id): + if host.layout == "page_first": + return host.k_buffer[indices, layer_id] + pages = indices[::PAGE_SIZE] // PAGE_SIZE + return host.k_buffer[pages, layer_id].reshape(-1, HEAD_NUM, K_HEAD_DIM) + + +def _host_v_tokens(host, indices, layer_id): + if host.layout == "page_first": + return host.v_buffer[indices, layer_id] + pages = indices[::PAGE_SIZE] // PAGE_SIZE + return host.v_buffer[pages, layer_id].reshape(-1, HEAD_NUM, V_HEAD_DIM) + + +def assert_backup_matches_device(host, device_pool, host_indices_host, device_indices): + for layer_id in range(NUM_LAYERS): + torch.testing.assert_close( + _host_k_tokens(host, host_indices_host, layer_id), + device_pool.k_buffer[layer_id][device_indices].cpu(), + ) + torch.testing.assert_close( + _host_v_tokens(host, host_indices_host, layer_id), + device_pool.v_buffer[layer_id][device_indices].cpu(), + ) + + +def assert_load_matches_host(host, device_pool, host_indices_host, load_indices): + for layer_id in range(NUM_LAYERS): + torch.testing.assert_close( + device_pool.k_buffer[layer_id][load_indices], + _host_k_tokens(host, host_indices_host, layer_id).to(DEVICE), + ) + torch.testing.assert_close( + device_pool.v_buffer[layer_id][load_indices], + _host_v_tokens(host, host_indices_host, layer_id).to(DEVICE), + ) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_asymmetric_mha_kernel_page_first_roundtrip(dtype): + # Covers D2H backup + H2D load through AsymmetricMHATokenToKVPoolHost using + # MiMoV2's real K/V head dims and the real MLA single-buffer kernels. + host = make_host_pool(dtype) + device_pool = make_device_pool(dtype) + + device_pages = torch.tensor([1, 2, 3], dtype=torch.int64) + host_pages = torch.tensor([0, 1, 2], dtype=torch.int64) + load_pages = torch.tensor([4, 5, 6], dtype=torch.int64) + device_indices_host = token_indices_for_pages(device_pages) + host_indices_host = token_indices_for_pages(host_pages) + load_indices_host = token_indices_for_pages(load_pages) + device_indices = device_indices_host.to(DEVICE) + host_indices = host_indices_host.to(DEVICE) + load_indices = load_indices_host.to(DEVICE) + + host.backup_from_device_all_layer( + device_pool, host_indices, device_indices, io_backend="kernel" + ) + torch.cuda.synchronize() + assert_backup_matches_device( + host, device_pool, host_indices_host, device_indices_host + ) + + for layer_id in range(NUM_LAYERS): + device_pool.k_buffer[layer_id].zero_() + device_pool.v_buffer[layer_id].zero_() + host.load_to_device_per_layer( + device_pool, host_indices, load_indices, layer_id, io_backend="kernel" + ) + torch.cuda.synchronize() + assert_load_matches_host(host, device_pool, host_indices_host, load_indices_host) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_asymmetric_mha_direct_page_first_direct_roundtrip(dtype): + # Covers D2H backup + H2D load through AsymmetricMHATokenToKVPoolHost using + # page_first_direct/direct. K and V are copied through separate direct calls + # because their per-token strides differ. + host = make_host_pool(dtype, layout="page_first_direct") + device_pool = make_device_pool(dtype) + direct_stream = torch.cuda.Stream() + + device_pages = torch.tensor([1, 2, 3], dtype=torch.int64) + host_pages = torch.tensor([0, 1, 2], dtype=torch.int64) + load_pages = torch.tensor([4, 5, 6], dtype=torch.int64) + device_indices_host = token_indices_for_pages(device_pages) + host_indices_host = token_indices_for_pages(host_pages) + load_indices_host = token_indices_for_pages(load_pages) + + with torch.cuda.stream(direct_stream): + host.backup_from_device_all_layer( + device_pool, host_indices_host, device_indices_host, io_backend="direct" + ) + direct_stream.synchronize() + assert_backup_matches_device( + host, device_pool, host_indices_host, device_indices_host + ) + + with torch.cuda.stream(direct_stream): + for layer_id in range(NUM_LAYERS): + device_pool.k_buffer[layer_id].zero_() + device_pool.v_buffer[layer_id].zero_() + host.load_to_device_per_layer( + device_pool, + host_indices_host, + load_indices_host, + layer_id, + io_backend="direct", + ) + direct_stream.synchronize() + assert_load_matches_host(host, device_pool, host_indices_host, load_indices_host) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_minimax_m3_qk_norm_rope.py b/asian_ai/performance/SGLang/test/registered/jit/test_minimax_m3_qk_norm_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..c856c589ad2bb7caacd919f531c411fb7b7206b0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_minimax_m3_qk_norm_rope.py @@ -0,0 +1,334 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Reference tests for MiniMax-M3 fused Q/K Gemma RMSNorm + RoPE.""" + +import pytest +import torch + +from sglang.srt.utils import is_hip + +if not is_hip(): + pytest.skip( + "MiniMax-M3 fused Q/K norm + RoPE kernel is ROCm-only.", + allow_module_level=True, + ) +if not torch.cuda.is_available(): + pytest.skip("Requires a GPU.", allow_module_level=True) + +from sglang.jit_kernel.minimax_m3.qk_norm_rope import ( # noqa: E402 + qk_gemma_rmsnorm_rope, + sparse_qk_index_gemma_rmsnorm_rope, + sparse_qk_index_gemma_rmsnorm_rope_cache, +) +from sglang.test.ci.ci_register import register_amd_ci # noqa: E402 + +# ROCm-only fused kernel; runs in the AMD jit-kernel unit suite. +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + +DEVICE = "cuda" +EPS = 1e-6 + + +def _gemma_norm_by_head(x: torch.Tensor, weight: torch.Tensor, head_dim: int): + orig_shape = x.shape + orig_dtype = x.dtype + xh = x.view(x.shape[0], -1, head_dim).float() + var = xh.pow(2).mean(dim=-1, keepdim=True) + out = xh * torch.rsqrt(var + EPS) * (1.0 + weight.float()) + return out.to(orig_dtype).reshape(orig_shape) + + +def _apply_rope_ref( + x: torch.Tensor, + positions: torch.Tensor, + cos_sin_cache: torch.Tensor, + head_dim: int, + rotary_dim: int, + is_neox_style: bool, +): + orig_shape = x.shape + xh = x.view(x.shape[0], -1, head_dim) + x_rot = xh[..., :rotary_dim].float() + x_pass = xh[..., rotary_dim:] + cos_sin = cos_sin_cache.index_select(0, positions) + cos, sin = cos_sin.chunk(2, dim=-1) + cos = cos[:, None, :].float() + sin = sin[:, None, :].float() + + if is_neox_style: + x1, x2 = x_rot.chunk(2, dim=-1) + y_rot = torch.cat((x1 * cos - x2 * sin, x2 * cos + x1 * sin), dim=-1) + else: + x1 = x_rot[..., ::2] + x2 = x_rot[..., 1::2] + y_rot = torch.stack((x1 * cos - x2 * sin, x2 * cos + x1 * sin), dim=-1) + y_rot = y_rot.flatten(-2) + + return torch.cat((y_rot.to(x.dtype), x_pass), dim=-1).reshape(orig_shape) + + +def _reference( + q, + k, + q_weight, + k_weight, + positions, + cos_sin_cache, + head_dim, + rotary_dim, + is_neox_style, +): + q_norm = _gemma_norm_by_head(q, q_weight, head_dim) + k_norm = _gemma_norm_by_head(k, k_weight, head_dim) + q_ref = _apply_rope_ref( + q_norm, positions, cos_sin_cache, head_dim, rotary_dim, is_neox_style + ) + k_ref = _apply_rope_ref( + k_norm, positions, cos_sin_cache, head_dim, rotary_dim, is_neox_style + ) + return q_ref, k_ref + + +def _sparse_reference( + q, + k, + idx_q, + idx_k, + q_weight, + k_weight, + idx_q_weight, + idx_k_weight, + positions, + cos_sin_cache, + head_dim, + rotary_dim, + is_neox_style, +): + q_ref, k_ref = _reference( + q, + k, + q_weight, + k_weight, + positions, + cos_sin_cache, + head_dim, + rotary_dim, + is_neox_style, + ) + idx_q_norm = _gemma_norm_by_head(idx_q, idx_q_weight, head_dim) + idx_k_norm = _gemma_norm_by_head(idx_k, idx_k_weight, head_dim) + idx_q_ref = _apply_rope_ref( + idx_q_norm, positions, cos_sin_cache, head_dim, rotary_dim, is_neox_style + ) + idx_k_ref = _apply_rope_ref( + idx_k_norm, positions, cos_sin_cache, head_dim, rotary_dim, is_neox_style + ) + return q_ref, k_ref, idx_q_ref, idx_k_ref + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("is_neox_style", [True, False]) +@pytest.mark.parametrize( + "num_tokens,q_heads,k_heads,head_dim,rotary_dim", + [(1, 16, 1, 128, 64), (17, 16, 1, 128, 64), (64, 4, 1, 128, 64)], +) +@torch.inference_mode() +def test_qk_gemma_rmsnorm_rope_matches_reference( + dtype, is_neox_style, num_tokens, q_heads, k_heads, head_dim, rotary_dim +): + torch.manual_seed(0) + q_dim = q_heads * head_dim + k_dim = k_heads * head_dim + padding_dim = 37 + qkv = torch.randn( + num_tokens, q_dim + k_dim + padding_dim, device=DEVICE, dtype=dtype + ) + q, k, _ = qkv.split([q_dim, k_dim, padding_dim], dim=-1) + if num_tokens > 1: + assert not q.is_contiguous() + assert not k.is_contiguous() + + q_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + k_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + positions = torch.randint(0, 512, (num_tokens,), device=DEVICE, dtype=torch.long) + cos_sin_cache = torch.randn(512, rotary_dim, device=DEVICE, dtype=dtype) + + got_q, got_k = qk_gemma_rmsnorm_rope( + q, + k, + q_weight, + k_weight, + positions, + cos_sin_cache, + EPS, + head_dim, + rotary_dim, + is_neox_style, + ) + ref_q, ref_k = _reference( + q, + k, + q_weight, + k_weight, + positions, + cos_sin_cache, + head_dim, + rotary_dim, + is_neox_style, + ) + + torch.testing.assert_close(got_q, ref_q, atol=3e-2, rtol=3e-2) + torch.testing.assert_close(got_k, ref_k, atol=3e-2, rtol=3e-2) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("is_neox_style", [True, False]) +@pytest.mark.parametrize( + "num_tokens,q_heads,k_heads,idx_q_heads,head_dim,rotary_dim", + [(1, 16, 1, 16, 128, 64), (19, 16, 1, 16, 128, 64)], +) +@torch.inference_mode() +def test_sparse_qk_index_gemma_rmsnorm_rope_matches_reference( + dtype, + is_neox_style, + num_tokens, + q_heads, + k_heads, + idx_q_heads, + head_dim, + rotary_dim, +): + torch.manual_seed(1) + q = torch.randn(num_tokens, q_heads * head_dim, device=DEVICE, dtype=dtype) + k = torch.randn(num_tokens, k_heads * head_dim, device=DEVICE, dtype=dtype) + idx_q = torch.randn(num_tokens, idx_q_heads * head_dim, device=DEVICE, dtype=dtype) + idx_k = torch.randn(num_tokens, head_dim, device=DEVICE, dtype=dtype) + q_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + k_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + idx_q_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + idx_k_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + positions = torch.randint(0, 512, (num_tokens,), device=DEVICE, dtype=torch.long) + cos_sin_cache = torch.randn(512, rotary_dim, device=DEVICE, dtype=dtype) + + got = sparse_qk_index_gemma_rmsnorm_rope( + q, + k, + idx_q, + idx_k, + q_weight, + k_weight, + idx_q_weight, + idx_k_weight, + positions, + cos_sin_cache, + EPS, + head_dim, + rotary_dim, + is_neox_style, + ) + ref = _sparse_reference( + q, + k, + idx_q, + idx_k, + q_weight, + k_weight, + idx_q_weight, + idx_k_weight, + positions, + cos_sin_cache, + head_dim, + rotary_dim, + is_neox_style, + ) + for got_tensor, ref_tensor in zip(got, ref): + torch.testing.assert_close(got_tensor, ref_tensor, atol=3e-2, rtol=3e-2) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("is_neox_style", [True, False]) +@torch.inference_mode() +def test_sparse_qk_index_gemma_rmsnorm_rope_cache_matches_reference( + dtype, is_neox_style +): + torch.manual_seed(2) + num_tokens, q_heads, k_heads, idx_q_heads = 11, 16, 1, 16 + head_dim, rotary_dim = 128, 64 + q = torch.randn(num_tokens, q_heads * head_dim, device=DEVICE, dtype=dtype) + k = torch.randn(num_tokens, k_heads * head_dim, device=DEVICE, dtype=dtype) + v = torch.randn(num_tokens, k_heads * head_dim, device=DEVICE, dtype=dtype) + idx_q = torch.randn(num_tokens, idx_q_heads * head_dim, device=DEVICE, dtype=dtype) + idx_k = torch.randn(num_tokens, head_dim, device=DEVICE, dtype=dtype) + q_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + k_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + idx_q_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + idx_k_weight = torch.randn(head_dim, device=DEVICE, dtype=torch.float32) + positions = torch.randint(0, 512, (num_tokens,), device=DEVICE, dtype=torch.long) + cos_sin_cache = torch.randn(512, rotary_dim, device=DEVICE, dtype=dtype) + out_cache_loc = torch.randperm(64, device=DEVICE, dtype=torch.int64)[:num_tokens] + k_cache = torch.empty(64, k_heads, head_dim, device=DEVICE, dtype=dtype) + v_cache = torch.empty(64, k_heads, head_dim, device=DEVICE, dtype=dtype) + idx_k_cache = torch.empty(64, 1, head_dim, device=DEVICE, dtype=dtype) + + got = sparse_qk_index_gemma_rmsnorm_rope_cache( + q, + k, + v, + idx_q, + idx_k, + k_cache, + v_cache, + idx_k_cache, + out_cache_loc, + q_weight, + k_weight, + idx_q_weight, + idx_k_weight, + positions, + cos_sin_cache, + EPS, + head_dim, + rotary_dim, + is_neox_style, + ) + ref = _sparse_reference( + q, + k, + idx_q, + idx_k, + q_weight, + k_weight, + idx_q_weight, + idx_k_weight, + positions, + cos_sin_cache, + head_dim, + rotary_dim, + is_neox_style, + ) + for got_tensor, ref_tensor in zip(got, ref): + torch.testing.assert_close(got_tensor, ref_tensor, atol=3e-2, rtol=3e-2) + + torch.testing.assert_close( + k_cache.index_select(0, out_cache_loc), + ref[1].view(num_tokens, k_heads, head_dim), + atol=3e-2, + rtol=3e-2, + ) + torch.testing.assert_close( + v_cache.index_select(0, out_cache_loc), + v.view(num_tokens, k_heads, head_dim), + atol=0, + rtol=0, + ) + torch.testing.assert_close( + idx_k_cache.index_select(0, out_cache_loc), + ref[3].view(num_tokens, 1, head_dim), + atol=3e-2, + rtol=3e-2, + ) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_mla_kv_pack_quantize_fp8.py b/asian_ai/performance/SGLang/test/registered/jit/test_mla_kv_pack_quantize_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c739e0c79ea25dc7bc68c993cced8ef382bfcf --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_mla_kv_pack_quantize_fp8.py @@ -0,0 +1,105 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.mla_kv_pack_quantize_fp8 import mla_kv_pack_quantize_fp8 +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=60, suite="nightly-amd-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" + +SHAPES = get_ci_test_range( + [(128, 64, 128), (64, 32, 64)], + [(128, 64, 128)], +) +NUM_HEADS = get_ci_test_range([8, 16, 32, 64], [16, 32]) +BATCH_SIZES = get_ci_test_range( + [1, 4, 17, 64, 257, 1024, 4096, 16384], + [1, 64, 1024, 16384], +) + + +def _ref(k_nope, k_pe, v, k_scale_inv, v_scale_inv, fp8_dtype): + s, h, qk_nope = k_nope.shape + qk_rope = k_pe.shape[-1] + v_head = v.shape[-1] + if k_pe.dim() == 3: + k_pe = k_pe.squeeze(1) + + k_bf16 = torch.empty( + (s, h, qk_nope + qk_rope), dtype=k_nope.dtype, device=k_nope.device + ) + k_bf16[..., :qk_nope] = k_nope + k_bf16[..., qk_nope:] = k_pe.unsqueeze(1).expand(-1, h, -1) + + k_fp8 = (k_bf16.float() * k_scale_inv).to(fp8_dtype) + v_fp8 = (v.float() * v_scale_inv).to(fp8_dtype) + return k_fp8, v_fp8 + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("shape", SHAPES) +@pytest.mark.parametrize("num_heads", NUM_HEADS) +@pytest.mark.parametrize("batch_size", BATCH_SIZES) +def test_correctness(dtype, shape, num_heads, batch_size): + qk_nope, qk_rope, v_head = shape + + torch.manual_seed(0) + k_nope = torch.randn((batch_size, num_heads, qk_nope), dtype=dtype, device=DEVICE) + k_pe = torch.randn((batch_size, 1, qk_rope), dtype=dtype, device=DEVICE) + v = torch.randn((batch_size, num_heads, v_head), dtype=dtype, device=DEVICE) + + k_scale_inv = 0.7 + v_scale_inv = 1.3 + + k_fp8, v_fp8 = mla_kv_pack_quantize_fp8( + k_nope, k_pe, v, k_scale_inv=k_scale_inv, v_scale_inv=v_scale_inv + ) + + k_ref, v_ref = _ref(k_nope, k_pe, v, k_scale_inv, v_scale_inv, torch.float8_e4m3fn) + + torch.testing.assert_close(k_fp8.float(), k_ref.float(), rtol=1e-2, atol=0.5) + torch.testing.assert_close(v_fp8.float(), v_ref.float(), rtol=1e-2, atol=0.5) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16]) +def test_strided_inputs(dtype): + s, h = 16, 32 + qk_nope, qk_rope, v_head = 128, 64, 128 + + full = torch.randn( + (s, h, qk_nope * 2), dtype=dtype, device=DEVICE, requires_grad=False + ) + k_nope = full[..., qk_nope:] + assert k_nope.stride(-1) == 1 + + k_pe = torch.randn((s, 1, qk_rope), dtype=dtype, device=DEVICE) + v = torch.randn((s, h, v_head), dtype=dtype, device=DEVICE) + + k_fp8, v_fp8 = mla_kv_pack_quantize_fp8(k_nope, k_pe, v) + k_ref, v_ref = _ref(k_nope, k_pe, v, 1.0, 1.0, torch.float8_e4m3fn) + torch.testing.assert_close(k_fp8.float(), k_ref.float(), rtol=1e-2, atol=0.5) + torch.testing.assert_close(v_fp8.float(), v_ref.float(), rtol=1e-2, atol=0.5) + + +def test_kpe_2d_accepted(): + s, h = 8, 16 + qk_nope, qk_rope, v_head = 128, 64, 128 + dtype = torch.bfloat16 + + k_nope = torch.randn((s, h, qk_nope), dtype=dtype, device=DEVICE) + k_pe = torch.randn((s, qk_rope), dtype=dtype, device=DEVICE) + v = torch.randn((s, h, v_head), dtype=dtype, device=DEVICE) + + k_fp8, v_fp8 = mla_kv_pack_quantize_fp8(k_nope, k_pe, v) + k_ref, v_ref = _ref(k_nope, k_pe.unsqueeze(1), v, 1.0, 1.0, torch.float8_e4m3fn) + torch.testing.assert_close(k_fp8.float(), k_ref.float(), rtol=1e-2, atol=0.5) + torch.testing.assert_close(v_fp8.float(), v_ref.float(), rtol=1e-2, atol=0.5) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_moe_align_block_size.py b/asian_ai/performance/SGLang/test/registered/jit/test_moe_align_block_size.py new file mode 100644 index 0000000000000000000000000000000000000000..d98316261ccd1435b1ba43fc6f37bd24b5ebffe0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_moe_align_block_size.py @@ -0,0 +1,362 @@ +import itertools +import sys + +import pytest +import torch +import triton +import triton.language as tl + +from sglang.jit_kernel.moe_align import moe_align_block_size +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=28, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def ceil_div(a, b): + return (a + b - 1) // b + + +@triton.jit +def moe_align_block_size_stage1( + topk_ids_ptr, + tokens_cnts_ptr, + num_experts: tl.constexpr, + numel: tl.constexpr, + tokens_per_thread: tl.constexpr, +): + pid = tl.program_id(0) + start_idx = pid * tokens_per_thread + off_c = (pid + 1) * num_experts + + for i in range(tokens_per_thread): + if start_idx + i < numel: + idx = tl.load(topk_ids_ptr + start_idx + i) + token_cnt = tl.load(tokens_cnts_ptr + off_c + idx) + tl.store(tokens_cnts_ptr + off_c + idx, token_cnt + 1) + + +@triton.jit +def moe_align_block_size_stage2( + tokens_cnts_ptr, + num_experts: tl.constexpr, +): + pid = tl.program_id(0) + last_cnt = 0 + for i in range(1, num_experts + 1): + token_cnt = tl.load(tokens_cnts_ptr + i * num_experts + pid) + last_cnt = last_cnt + token_cnt + tl.store(tokens_cnts_ptr + i * num_experts + pid, last_cnt) + + +@triton.jit +def moe_align_block_size_stage3( + total_tokens_post_pad_ptr, + tokens_cnts_ptr, + cumsum_ptr, + num_experts: tl.constexpr, + block_size: tl.constexpr, +): + last_cumsum = 0 + off_cnt = num_experts * num_experts + for i in range(1, num_experts + 1): + token_cnt = tl.load(tokens_cnts_ptr + off_cnt + i - 1) + last_cumsum = last_cumsum + tl.cdiv(token_cnt, block_size) * block_size + tl.store(cumsum_ptr + i, last_cumsum) + tl.store(total_tokens_post_pad_ptr, last_cumsum) + + +@triton.jit +def moe_align_block_size_stage4( + topk_ids_ptr, + sorted_token_ids_ptr, + expert_ids_ptr, + tokens_cnts_ptr, + cumsum_ptr, + num_experts: tl.constexpr, + block_size: tl.constexpr, + numel: tl.constexpr, + tokens_per_thread: tl.constexpr, +): + pid = tl.program_id(0) + start_idx = tl.load(cumsum_ptr + pid) + end_idx = tl.load(cumsum_ptr + pid + 1) + + for i in range(start_idx, end_idx, block_size): + tl.store(expert_ids_ptr + i // block_size, pid) + + start_idx = pid * tokens_per_thread + off_t = pid * num_experts + + for i in range(start_idx, tl.minimum(start_idx + tokens_per_thread, numel)): + expert_id = tl.load(topk_ids_ptr + i) + token_cnt = tl.load(tokens_cnts_ptr + off_t + expert_id) + rank_post_pad = token_cnt + tl.load(cumsum_ptr + expert_id) + tl.store(sorted_token_ids_ptr + rank_post_pad, i) + tl.store(tokens_cnts_ptr + off_t + expert_id, token_cnt + 1) + + +def moe_align_block_size_triton( + topk_ids: torch.Tensor, + num_experts: int, + block_size: int, + sorted_token_ids: torch.Tensor, + expert_ids: torch.Tensor, + num_tokens_post_pad: torch.Tensor, +) -> None: + numel = topk_ids.numel() + grid = (num_experts,) + tokens_cnts = torch.zeros( + (num_experts + 1, num_experts), dtype=torch.int32, device=topk_ids.device + ) + cumsum = torch.zeros((num_experts + 1,), dtype=torch.int32, device=topk_ids.device) + tokens_per_thread = ceil_div(numel, num_experts) + + moe_align_block_size_stage1[grid]( + topk_ids, + tokens_cnts, + num_experts, + numel, + tokens_per_thread, + ) + moe_align_block_size_stage2[grid]( + tokens_cnts, + num_experts, + ) + moe_align_block_size_stage3[(1,)]( + num_tokens_post_pad, + tokens_cnts, + cumsum, + num_experts, + block_size, + ) + moe_align_block_size_stage4[grid]( + topk_ids, + sorted_token_ids, + expert_ids, + tokens_cnts, + cumsum, + num_experts, + block_size, + numel, + tokens_per_thread, + ) + + +MOE_ALIGN_CASES = get_ci_test_range( + list( + itertools.product( + [32, 64, 128, 256], # block_size + [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096], # num_tokens + [1, 2, 4, 8, 16, 32, 64], # topk + [64, 128, 160, 256, 257, 260, 264], # num_experts + [True, False], # pad_sorted_token_ids + ) + ), + [ + (32, 1, 1, 64, True), + (128, 48, 1, 128, True), + (256, 103, 4, 256, False), + (128, 128, 1, 256, True), + (256, 4096, 8, 256, False), + ], +) + + +@pytest.mark.parametrize( + "block_size,num_tokens,topk,num_experts,pad_sorted_token_ids", + MOE_ALIGN_CASES, +) +def test_moe_align_block_size_compare_implementations( + block_size, num_tokens, topk, num_experts, pad_sorted_token_ids +): + topk_ids = torch.argsort(torch.rand(num_tokens, num_experts, device="cuda"), dim=1)[ + :, :topk + ] + + max_num_tokens_padded = topk_ids.numel() + (num_experts + 1) * (block_size - 1) + if topk_ids.numel() < num_experts + 1: + max_num_tokens_padded = topk_ids.numel() * block_size + + sorted_ids_cuda = torch.empty( + (max_num_tokens_padded,), dtype=torch.int32, device=topk_ids.device + ) + if not pad_sorted_token_ids: + sorted_ids_cuda.fill_(topk_ids.numel()) + max_num_m_blocks = max_num_tokens_padded // block_size + expert_ids_cuda = torch.zeros( + (max_num_m_blocks,), dtype=torch.int32, device=topk_ids.device + ) + num_tokens_post_pad_cuda = torch.empty( + (1), dtype=torch.int32, device=topk_ids.device + ) + cumsum_buffer = torch.empty( + num_experts + 2, dtype=torch.int32, device=topk_ids.device + ) + + sorted_ids_triton = torch.empty_like(sorted_ids_cuda) + sorted_ids_triton.fill_(topk_ids.numel()) + expert_ids_triton = torch.zeros_like(expert_ids_cuda) + num_tokens_post_pad_triton = torch.empty_like(num_tokens_post_pad_cuda) + + moe_align_block_size( + topk_ids, + num_experts + 1, + block_size, + sorted_ids_cuda, + expert_ids_cuda, + num_tokens_post_pad_cuda, + cumsum_buffer, + pad_sorted_token_ids, + ) + + moe_align_block_size_triton( + topk_ids, + num_experts + 1, + block_size, + sorted_ids_triton, + expert_ids_triton, + num_tokens_post_pad_triton, + ) + + assert torch.allclose(expert_ids_cuda, expert_ids_triton, atol=0, rtol=0), ( + f"Expert IDs mismatch for block_size={block_size}, " + f"num_tokens={num_tokens}, topk={topk}\n" + f"CUDA expert_ids: {expert_ids_cuda}\n" + f"Triton expert_ids: {expert_ids_triton}" + ) + + assert torch.allclose( + num_tokens_post_pad_cuda, num_tokens_post_pad_triton, atol=0, rtol=0 + ), ( + f"Num tokens post pad mismatch for block_size={block_size}, " + f"num_tokens={num_tokens}, topk={topk}\n" + f"CUDA num_tokens_post_pad: {num_tokens_post_pad_cuda}\n" + f"Triton num_tokens_post_pad: {num_tokens_post_pad_triton}" + ) + + # Select an expert to check + expert_idx = expert_ids_cuda.max().item() + + # Get the first and last block id where expert_ids_cuda == expert_idx + matching_indices = torch.where(expert_ids_cuda == expert_idx)[0] + block_sorted_start = matching_indices[0].item() * block_size + block_sorted_end = min( + (matching_indices[-1].item() + 1) * block_size, + num_tokens_post_pad_cuda.item(), + ) + + selected_sorted_ids_cuda = sorted_ids_cuda[ + block_sorted_start:block_sorted_end + ].sort()[0] + selected_sorted_ids_triton = sorted_ids_triton[ + block_sorted_start:block_sorted_end + ].sort()[0] + + assert torch.allclose( + selected_sorted_ids_cuda, + selected_sorted_ids_triton, + atol=0, + rtol=0, + ), ( + f"Sorted IDs mismatch for block_size={block_size}, " + f"num_tokens={num_tokens}, topk={topk}\n" + f"CUDA sorted_ids: {selected_sorted_ids_cuda}\n" + f"Triton sorted_ids: {selected_sorted_ids_triton}" + ) + + +@pytest.mark.parametrize( + "block_size,num_tokens,topk,num_experts", + list( + itertools.product( + [64, 128], # block_size + [1, 8, 32, 256], # num_tokens + [8], # topk + [ + 1025, + 2048, + 4095, + ], # num_experts (>1024 to exercise v2 kernel, max 4095 real experts) + ) + ), +) +def test_moe_align_block_size_v2_large_num_experts( + block_size, num_tokens, topk, num_experts +): + """Test moe_align_block_size v2 kernel for >1024 experts against Triton reference.""" + topk_ids = torch.randint( + 0, num_experts, (num_tokens, topk), dtype=torch.int32, device="cuda" + ) + + max_num_tokens_padded = topk_ids.numel() + (num_experts + 1) * (block_size - 1) + if topk_ids.numel() < num_experts + 1: + max_num_tokens_padded = topk_ids.numel() * block_size + + sorted_ids_cuda = torch.empty( + (max_num_tokens_padded,), dtype=torch.int32, device=topk_ids.device + ) + sorted_ids_cuda.fill_(topk_ids.numel()) + max_num_m_blocks = max_num_tokens_padded // block_size + expert_ids_cuda = torch.zeros( + (max_num_m_blocks,), dtype=torch.int32, device=topk_ids.device + ) + num_tokens_post_pad_cuda = torch.empty( + (1), dtype=torch.int32, device=topk_ids.device + ) + cumsum_buffer = torch.empty( + num_experts + 2, dtype=torch.int32, device=topk_ids.device + ) + + sorted_ids_triton = torch.empty_like(sorted_ids_cuda) + sorted_ids_triton.fill_(topk_ids.numel()) + expert_ids_triton = torch.zeros_like(expert_ids_cuda) + num_tokens_post_pad_triton = torch.empty_like(num_tokens_post_pad_cuda) + + moe_align_block_size( + topk_ids, + num_experts + 1, + block_size, + sorted_ids_cuda, + expert_ids_cuda, + num_tokens_post_pad_cuda, + cumsum_buffer, + True, + ) + + moe_align_block_size_triton( + topk_ids, + num_experts + 1, + block_size, + sorted_ids_triton, + expert_ids_triton, + num_tokens_post_pad_triton, + ) + + assert torch.equal(num_tokens_post_pad_cuda, num_tokens_post_pad_triton), ( + f"Num tokens post pad mismatch: CUDA={num_tokens_post_pad_cuda.item()}, " + f"Triton={num_tokens_post_pad_triton.item()}" + ) + + ntp = num_tokens_post_pad_cuda.item() + num_blocks = ntp // block_size + + assert torch.equal(expert_ids_cuda[:num_blocks], expert_ids_triton[:num_blocks]), ( + f"Expert IDs mismatch for block_size={block_size}, " + f"num_tokens={num_tokens}, topk={topk}, num_experts={num_experts}" + ) + + # Compare sorted_token_ids per expert block (order within block may differ) + for b in range(num_blocks): + s, e = b * block_size, (b + 1) * block_size + block_cuda = sorted_ids_cuda[s:e].sort().values + block_triton = sorted_ids_triton[s:e].sort().values + assert torch.equal(block_cuda, block_triton), ( + f"Block {b} sorted_ids mismatch for num_experts={num_experts}, " + f"num_tokens={num_tokens}" + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_moe_fused_gate.py b/asian_ai/performance/SGLang/test/registered/jit/test_moe_fused_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..40f960e5f9e5d239ce95c8ad32e1fadc758a6141 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_moe_fused_gate.py @@ -0,0 +1,472 @@ +"""Correctness tests for the Triton :func:`moe_fused_gate` router. + +The Triton kernel is a drop-in reimplementation of the CUDA fused gate for the +ungrouped case (``num_expert_group == 1``). We validate it three ways: + +* against an explicit, definition-based torch reference (documents the math), +* against the CUDA JIT kernel it mirrors (:func:`moe_fused_gate_jit`), and +* against the production ``biased_grouped_topk_impl`` for the sigmoid / no-shared + path that the kernel actually replaces in ``topk.py``. + +Comparisons are order-independent: weights are scattered back to a dense +``[M, num_experts + num_shared]`` layout so the per-row column order (and any +tie-break choice) does not matter. +""" + +from __future__ import annotations + +import sys +from typing import Tuple + +import pytest +import torch + +from sglang.jit_kernel.moe_fused_gate import moe_fused_gate, moe_fused_gate_jit +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.srt.layers.moe.topk import biased_grouped_topk_impl +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=8, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +DEVICE = "cuda" + + +def _scatter_by_expert( + weights: torch.Tensor, indices: torch.Tensor, num_columns: int +) -> torch.Tensor: + """Scatter (weight, id) pairs into a dense ``[M, num_columns]`` tensor. + + Makes the comparison independent of the per-row slot order, so the test does + not depend on how ties between equal scores are broken. + """ + dense = torch.zeros( + (weights.shape[0], num_columns), dtype=torch.float32, device=weights.device + ) + dense.scatter_(1, indices.long(), weights.float()) + return dense + + +def _reference_gate( + scores: torch.Tensor, + bias: torch.Tensor, + topk: int, + scoring_func: str, + num_fused_shared_experts: int, + renormalize: bool, + routed_scaling_factor: float, + apply_routed_scaling_factor_on_output: bool, +) -> Tuple[torch.Tensor, torch.Tensor]: + """Definition-based eager reference matching the CUDA fused-gate semantics.""" + if scoring_func == "sigmoid": + activated = scores.sigmoid() + else: + activated = torch.nn.functional.softplus(scores).sqrt() + + biased = activated + bias.unsqueeze(0) + num_experts = scores.size(1) + num_routed = topk - num_fused_shared_experts + + # Top-k_routed by biased score; lowest expert id wins on ties (matches kernel). + bs = biased.size(0) + work = biased.clone() + arange = torch.arange(num_experts, device=scores.device).unsqueeze(0) + routed_idx = torch.empty(bs, num_routed, dtype=torch.int32, device=scores.device) + routed_wgt = torch.empty(bs, num_routed, dtype=torch.float32, device=scores.device) + for k in range(num_routed): + vals, _ = work.max(dim=1, keepdim=True) + lane = torch.where(work == vals, arange, num_experts + 1) + winner = lane.min(dim=1).values.to(torch.int32) + routed_idx[:, k] = winner + routed_wgt[:, k] = activated.gather(1, winner.long().unsqueeze(1)).squeeze(1) + work.scatter_(1, winner.long().unsqueeze(1), float("-inf")) + + routed_sum = routed_wgt.sum(dim=1, keepdim=True) + weights = torch.empty(bs, topk, dtype=torch.float32, device=scores.device) + indices = torch.empty(bs, topk, dtype=torch.int32, device=scores.device) + weights[:, :num_routed] = routed_wgt + indices[:, :num_routed] = routed_idx + if num_fused_shared_experts > 0: + weights[:, num_routed:] = routed_sum / routed_scaling_factor + for j in range(num_fused_shared_experts): + indices[:, num_routed + j] = num_experts + j + + if renormalize: + norm = torch.where(routed_sum > 0.0, routed_sum, torch.ones_like(routed_sum)) + weights = weights / norm + if apply_routed_scaling_factor_on_output: + weights = weights * routed_scaling_factor + return weights, indices + + +def _make_inputs(M: int, num_experts: int, seed: int): + torch.manual_seed(seed) + scores = torch.randn(M, num_experts, dtype=torch.float32, device=DEVICE) * 2.0 + bias = torch.randn(num_experts, dtype=torch.float32, device=DEVICE) * 0.5 + return scores, bias + + +_NUM_EXPERTS = get_ci_test_range([128, 256, 384, 512], [128, 384, 512]) +_M = get_ci_test_range([1, 7, 64, 256, 1024], [1, 64, 1024]) + + +@pytest.mark.parametrize("M", _M) +@pytest.mark.parametrize("num_experts", _NUM_EXPERTS) +@pytest.mark.parametrize("topk", [4, 6, 8]) +@pytest.mark.parametrize("scoring_func", ["sigmoid", "sqrtsoftplus"]) +@pytest.mark.parametrize("num_shared", [0, 1]) +@pytest.mark.parametrize("renormalize", [True, False]) +@pytest.mark.parametrize("apply_scale", [True, False]) +def test_moe_fused_gate_matches_reference( + M: int, + num_experts: int, + topk: int, + scoring_func: str, + num_shared: int, + renormalize: bool, + apply_scale: bool, +) -> None: + scores, bias = _make_inputs(M, num_experts, seed=num_experts * 100 + topk) + scale = 2.5 + + kwargs = dict( + topk=topk, + scoring_func=scoring_func, + num_fused_shared_experts=num_shared, + renormalize=renormalize, + routed_scaling_factor=scale, + apply_routed_scaling_factor_on_output=apply_scale, + ) + triton_w, triton_i = moe_fused_gate(scores, bias, **kwargs) + ref_w, ref_i = _reference_gate(scores, bias, **kwargs) + torch.cuda.synchronize() + + num_columns = num_experts + num_shared + torch.testing.assert_close( + _scatter_by_expert(triton_w, triton_i, num_columns), + _scatter_by_expert(ref_w, ref_i, num_columns), + rtol=1e-4, + atol=1e-5, + ) + + +@pytest.mark.parametrize( + "M,num_experts,topk,num_shared,scoring_func", + [ + # DeepSeek-V4-ish: sqrtsoftplus, ungrouped + (8192, 256, 6, 0, "sqrtsoftplus"), + (8192, 384, 6, 0, "sqrtsoftplus"), + # Kimi-K2 family: 384 experts, sigmoid, ungrouped + (8192, 384, 8, 0, "sigmoid"), + # Generic large MoE with a fused shared expert + (8192, 512, 8, 1, "sigmoid"), + ], +) +def test_moe_fused_gate_matches_cuda_jit( + M: int, num_experts: int, topk: int, num_shared: int, scoring_func: str +) -> None: + """Triton output must match the CUDA JIT kernel it reimplements.""" + scores, bias = _make_inputs(M, num_experts, seed=123) + + kwargs = dict( + topk=topk, + scoring_func=scoring_func, + num_fused_shared_experts=num_shared, + renormalize=True, + routed_scaling_factor=2.5, + apply_routed_scaling_factor_on_output=True, + ) + triton_w, triton_i = moe_fused_gate(scores, bias, **kwargs) + cuda_w, cuda_i = moe_fused_gate_jit(scores, bias, **kwargs) + torch.cuda.synchronize() + + num_columns = num_experts + num_shared + torch.testing.assert_close( + _scatter_by_expert(triton_w, triton_i, num_columns), + _scatter_by_expert(cuda_w, cuda_i, num_columns), + rtol=1e-4, + atol=1e-5, + ) + + +@pytest.mark.parametrize("num_experts,topk", [(256, 6), (384, 8), (512, 8)]) +@pytest.mark.parametrize("apply_scale", [True, False]) +def test_moe_fused_gate_matches_production_impl( + num_experts: int, topk: int, apply_scale: bool +) -> None: + """Match production ``biased_grouped_topk_impl`` on the path it replaces. + + The kernel supersedes the ungrouped sigmoid CUDA path in ``topk.py``; that + reference hardcodes sigmoid and no fused shared expert, and the production + path always renormalizes (the impl only applies the scaling factor when + ``renormalize`` is set), so we compare on the renormalized path. + """ + M = 128 + scores, bias = _make_inputs(M, num_experts, seed=7) + scale = 2.5 + + triton_w, triton_i = moe_fused_gate( + scores, + bias, + topk=topk, + scoring_func="sigmoid", + renormalize=True, + routed_scaling_factor=scale, + apply_routed_scaling_factor_on_output=apply_scale, + ) + hidden_states = torch.empty((M, 1), dtype=torch.float32, device=DEVICE) + ref_w, ref_i = biased_grouped_topk_impl( + hidden_states, + scores, + bias, + topk, + True, + num_expert_group=1, + topk_group=1, + routed_scaling_factor=scale, + apply_routed_scaling_factor_on_output=apply_scale, + ) + torch.cuda.synchronize() + + torch.testing.assert_close( + _scatter_by_expert(triton_w, triton_i, num_experts), + _scatter_by_expert(ref_w, ref_i, num_experts), + rtol=1e-4, + atol=1e-5, + ) + + +def test_moe_fused_gate_shapes_and_dtypes() -> None: + """Output shapes/dtypes and renormalized weights for a DeepSeek-V4 config.""" + M, N, K = 64, 256, 8 + scores, bias = _make_inputs(M, N, seed=0) + + w, i = moe_fused_gate(scores, bias, topk=K, scoring_func="sqrtsoftplus") + assert w.shape == (M, K) + assert i.shape == (M, K) + assert w.dtype == torch.float32 + assert i.dtype == torch.int32 + + # Selected expert ids are valid (no shared experts here). + assert (i >= 0).all() and (i < N).all() + # Renormalized weights sum to 1 per row. + torch.testing.assert_close( + w.sum(dim=1), torch.ones(M, device=DEVICE), rtol=1e-4, atol=1e-5 + ) + + +def _reference_softmax( + gating: torch.Tensor, topk: int, renormalize: bool +) -> Tuple[torch.Tensor, torch.Tensor]: + """Plain-softmax topk reference (the AOT ``topk_softmax`` semantics).""" + num_experts = gating.size(1) + probs = torch.softmax(gating.float(), dim=-1) + work = gating.float().clone() + arange = torch.arange(num_experts, device=gating.device).unsqueeze(0) + M = gating.size(0) + idx = torch.empty(M, topk, dtype=torch.int32, device=gating.device) + wgt = torch.empty(M, topk, dtype=torch.float32, device=gating.device) + for k in range(topk): + vals, _ = work.max(dim=1, keepdim=True) + lane = torch.where(work == vals, arange, num_experts + 1) + winner = lane.min(dim=1).values.to(torch.int32) + idx[:, k] = winner + wgt[:, k] = probs.gather(1, winner.long().unsqueeze(1)).squeeze(1) + work.scatter_(1, winner.long().unsqueeze(1), float("-inf")) + if renormalize: + wgt = wgt / wgt.sum(dim=1, keepdim=True) + return wgt, idx + + +@pytest.mark.parametrize("M", [1, 200, 1024]) +@pytest.mark.parametrize("num_experts,topk", [(128, 4), (256, 8), (512, 6)]) +@pytest.mark.parametrize("renormalize", [True, False]) +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_moe_fused_gate_softmax_matches_aot( + M: int, num_experts: int, topk: int, renormalize: bool, dtype: torch.dtype +) -> None: + """Triton softmax path matches the AOT ``topk_softmax`` it replaces in fused_topk.""" + sgl_kernel = pytest.importorskip("sgl_kernel") + torch.manual_seed(num_experts * 13 + topk) + gating = torch.randn(M, num_experts, dtype=dtype, device=DEVICE) * 2.0 + zero_bias = torch.zeros(num_experts, dtype=torch.float32, device=DEVICE) + + tri_w, tri_i = moe_fused_gate( + gating, zero_bias, topk=topk, scoring_func="softmax", renormalize=renormalize + ) + ref_w, ref_i = _reference_softmax(gating, topk, renormalize) + + aot_w = torch.empty(M, topk, dtype=torch.float32, device=DEVICE) + aot_i = torch.empty(M, topk, dtype=torch.int32, device=DEVICE) + sgl_kernel.topk_softmax(aot_w, aot_i, gating, renormalize) + torch.cuda.synchronize() + + dense_tri = _scatter_by_expert(tri_w, tri_i, num_experts) + torch.testing.assert_close( + dense_tri, _scatter_by_expert(ref_w, ref_i, num_experts), rtol=1e-3, atol=1e-3 + ) + torch.testing.assert_close( + dense_tri, _scatter_by_expert(aot_w, aot_i, num_experts), rtol=1e-3, atol=1e-3 + ) + + +@pytest.mark.parametrize("M", [1, 200, 1024]) +@pytest.mark.parametrize("num_experts,topk", [(128, 4), (256, 8)]) +@pytest.mark.parametrize("renormalize", [True, False]) +@pytest.mark.parametrize("with_bias", [True, False]) +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_moe_fused_gate_sigmoid_matches_aot( + M: int, + num_experts: int, + topk: int, + renormalize: bool, + with_bias: bool, + dtype: torch.dtype, +) -> None: + """Triton sigmoid path matches the AOT ``topk_sigmoid`` it replaces in fused_topk.""" + sgl_kernel = pytest.importorskip("sgl_kernel") + torch.manual_seed(num_experts * 17 + topk) + gating = torch.randn(M, num_experts, dtype=dtype, device=DEVICE) * 2.0 + bias = ( + torch.randn(num_experts, dtype=torch.float32, device=DEVICE) * 0.5 + if with_bias + else torch.zeros(num_experts, dtype=torch.float32, device=DEVICE) + ) + + tri_w, tri_i = moe_fused_gate( + gating, bias, topk=topk, scoring_func="sigmoid", renormalize=renormalize + ) + aot_w = torch.empty(M, topk, dtype=torch.float32, device=DEVICE) + aot_i = torch.empty(M, topk, dtype=torch.int32, device=DEVICE) + sgl_kernel.topk_sigmoid( + aot_w, aot_i, gating, renormalize, bias if with_bias else None + ) + torch.cuda.synchronize() + + torch.testing.assert_close( + _scatter_by_expert(tri_w, tri_i, num_experts), + _scatter_by_expert(aot_w, aot_i, num_experts), + rtol=1e-3, + atol=1e-3, + ) + + +@pytest.mark.parametrize( + "num_experts,num_expert_group,topk_group,topk", + [ + (256, 8, 4, 8), # DeepSeek-V3 + (128, 8, 4, 6), + (256, 4, 2, 8), + ], +) +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_moe_fused_gate_grouped_matches_production_impl( + num_experts: int, + num_expert_group: int, + topk_group: int, + topk: int, + dtype: torch.dtype, +) -> None: + """Grouped Triton routing must match the definitional biased_grouped_topk_impl. + + The kernel adds DeepSeek-V3 grouped routing (per-group top-2-sum group scores, + keep topk_group groups, then top-k within). biased_grouped_topk_impl is the + eager reference the production grouped path is defined against. + """ + M = 256 + torch.manual_seed(num_experts * 7 + num_expert_group * 13 + topk) + gating = torch.randn(M, num_experts, dtype=dtype, device=DEVICE) * 2.0 + bias = torch.randn(num_experts, dtype=torch.float32, device=DEVICE) * 0.5 + hidden = torch.randn(M, 16, dtype=dtype, device=DEVICE) + + tri_w, tri_i = moe_fused_gate( + gating, + bias, + topk=topk, + scoring_func="sigmoid", + renormalize=True, + num_expert_group=num_expert_group, + topk_group=topk_group, + ) + ref_w, ref_i = biased_grouped_topk_impl( + hidden, + gating, + bias, + topk, + True, + num_expert_group=num_expert_group, + topk_group=topk_group, + num_fused_shared_experts=0, + routed_scaling_factor=1.0, + apply_routed_scaling_factor_on_output=False, + ) + torch.cuda.synchronize() + + torch.testing.assert_close( + _scatter_by_expert(tri_w, tri_i, num_experts), + _scatter_by_expert(ref_w, ref_i, num_experts), + rtol=1e-3, + atol=1e-3, + ) + + +@pytest.mark.parametrize( + "num_experts,num_expert_group,topk_group,topk,num_fused_shared_experts", + [ + (256, 8, 4, 8, 0), # DeepSeek-V3 + (256, 8, 4, 9, 1), # DeepSeek-V3 + one fused shared expert + ], +) +def test_grouped_dispatch_flag_matches_default( + num_experts: int, + num_expert_group: int, + topk_group: int, + topk: int, + num_fused_shared_experts: int, +) -> None: + """The opt-in SGLANG_OPT_USE_JIT_KERNEL_GROUPED_TOPK dispatch must match the + default grouped path (flashinfer/AOT) that biased_grouped_topk_gpu selects when + the flag is off. This covers the wiring, not just the raw kernel — validated + bit-exact on DeepSeek-V3.2 e2e; here we assert parity against the default path. + """ + from sglang.srt.environ import envs + from sglang.srt.layers.moe.topk import biased_grouped_topk_gpu + + M = 256 + torch.manual_seed(num_experts * 3 + num_expert_group * 5 + topk) + # fp32 gating: both the default (flashinfer upcasts to fp32) and the Triton + # dispatch (also upcasts) operate on the same fp32 scores, so no bf16 + # borderline-expert divergence is expected. + gating = torch.randn(M, num_experts, dtype=torch.float32, device=DEVICE) * 2.0 + bias = torch.randn(num_experts, dtype=torch.float32, device=DEVICE) * 0.5 + hidden = torch.randn(M, 16, dtype=torch.float32, device=DEVICE) + + kwargs = dict( + num_expert_group=num_expert_group, + topk_group=topk_group, + num_fused_shared_experts=num_fused_shared_experts, + routed_scaling_factor=2.5, + apply_routed_scaling_factor_on_output=False, + ) + with envs.SGLANG_OPT_USE_JIT_KERNEL_GROUPED_TOPK.override(False): + def_w, def_i = biased_grouped_topk_gpu( + hidden, gating, bias, topk, True, **kwargs + ) + with envs.SGLANG_OPT_USE_JIT_KERNEL_GROUPED_TOPK.override(True): + jit_w, jit_i = biased_grouped_topk_gpu( + hidden, gating, bias, topk, True, **kwargs + ) + torch.cuda.synchronize() + + # Compare routed experts only (shared-expert slot ids are placeholders the + # downstream fusion overwrites; the routed selection + weights are what matter). + topk_routed = topk - num_fused_shared_experts + torch.testing.assert_close( + _scatter_by_expert(def_w[:, :topk_routed], def_i[:, :topk_routed], num_experts), + _scatter_by_expert(jit_w[:, :topk_routed], jit_i[:, :topk_routed], num_experts), + rtol=1e-3, + atol=1e-3, + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_moe_lora_align_block_size.py b/asian_ai/performance/SGLang/test/registered/jit/test_moe_lora_align_block_size.py new file mode 100644 index 0000000000000000000000000000000000000000..88fff4b7076aa5dec2a4aebfb37d8cbb8ac8f9d3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_moe_lora_align_block_size.py @@ -0,0 +1,168 @@ +# Temporarily adapted from https://github.com/vllm-project/vllm/blob/main/tests/lora/test_moe_lora_align_sum.py, will optimize in future refactor +import random +import sys + +import pytest +import torch + +# --------------------------------------------------------- +# IMPORT PREBUILT KERNEL +# --------------------------------------------------------- +from sglang.jit_kernel.moe_lora_align import moe_lora_align_block_size +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=28, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def round_up(x, base): + return ((x + base - 1) // base) * base + + +def CEILDIV(x, y): + return (x + y - 1) // y + + +def sample_data(num_experts, max_loras, num_tokens, topk_num): + # 1. Generate TopK IDs (Flattened tokens) + topk_ids = torch.zeros((num_tokens, topk_num), dtype=torch.int32) + for i in range(num_tokens): + pool = list(range(num_experts)) + random.shuffle(pool) + for j in range(topk_num): + topk_ids[i, j] = pool[j] + + # 2. Generate Random Requests (Segments) + # We split num_tokens into random chunks to simulate a batch of requests + remaining_tokens = num_tokens + seg_lens = [] + while remaining_tokens > 0: + # Random length between 1 and remaining + length = random.randint(1, min(32, remaining_tokens)) + if remaining_tokens - length < 0: + length = remaining_tokens + seg_lens.append(length) + remaining_tokens -= length + + # Ensure we cover the full range exactly (cleanup last segment) + if sum(seg_lens) < num_tokens: + seg_lens.append(num_tokens - sum(seg_lens)) + + # 3. Build seg_indptr [0, len1, len1+len2, ...] + seg_indptr = torch.cumsum( + torch.tensor([0] + seg_lens, dtype=torch.int32), dim=0 + ).to(dtype=torch.int32) + + # 4. Assign a LoRA ID to each Request + num_reqs = len(seg_lens) + req_to_lora = torch.randint(0, max_loras, (num_reqs,), dtype=torch.int32) + + return (topk_ids.to("cuda"), seg_indptr.to("cuda"), req_to_lora.to("cuda")) + + +@pytest.mark.parametrize("num_tokens", [100, 200, 1024, 4096]) +@pytest.mark.parametrize("topk_num", [6]) +@pytest.mark.parametrize("num_experts", [64, 128, 256, 512]) +@pytest.mark.parametrize("max_loras", [2, 32]) +@pytest.mark.parametrize("block_size", [16]) +def test_moe_lora_align_block_size( + num_tokens, topk_num, num_experts, max_loras, block_size +): + # sample data + random.seed(1) + torch.manual_seed(1) + + if not torch.cuda.is_available(): + pytest.skip("CUDA is not available, skipping moe_lora_align_block_size test.") + # UPDATED: Get the new 3-step mapping tensors + topk_ids, seg_indptr, req_to_lora = sample_data( + num_experts, max_loras, num_tokens, topk_num + ) + + # compute paddings + max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1) + max_num_tokens_padded = round_up(max_num_tokens_padded, block_size) + max_num_m_blocks = CEILDIV(max_num_tokens_padded, block_size) + + # init output tensors + sorted_token_ids = torch.full( + (max_loras * max_num_tokens_padded,), + topk_ids.numel(), + dtype=torch.int32, + device="cuda", + ) + expert_ids = torch.full( + (max_loras * max_num_m_blocks,), num_experts, dtype=torch.int32, device="cuda" + ) + num_tokens_post_pad = torch.zeros((max_loras,), dtype=torch.int32, device="cuda") + adapter_enabled = torch.ones((max_loras + 1,), dtype=torch.int32, device="cuda") + lora_ids = torch.arange(max_loras, dtype=torch.int32, device="cuda") + + # UPDATED: Call kernel with new signature + moe_lora_align_block_size( + topk_ids, + seg_indptr, # Arg 2: Pointers + req_to_lora, # Arg 3: Request Map + num_experts, + block_size, + max_loras, + max_num_tokens_padded, + max_num_m_blocks, + sorted_token_ids, + expert_ids, + num_tokens_post_pad, + adapter_enabled, + lora_ids, + None, + ) + + # verify values + expert_ids = expert_ids.view(max_loras, -1) + sorted_token_ids = sorted_token_ids.view(max_loras, -1, block_size) + + # Reconstruct token-level ownership for verification logic + # We expand req_to_lora back to [num_tokens] on CPU just to check correctness + # This proves the kernel (which used the compressed format) produced the right result + cpu_seg_indptr = seg_indptr.cpu() + cpu_req_to_lora = req_to_lora.cpu() + token_ownership = torch.zeros(num_tokens, dtype=torch.int32) + + for r in range(len(cpu_req_to_lora)): + start = cpu_seg_indptr[r] + end = cpu_seg_indptr[r + 1] + token_ownership[start:end] = cpu_req_to_lora[r] + + token_ownership = token_ownership.to("cuda") + + for lora_idx in range(max_loras): + # Count how many tokens actually belong to this LoRA + expected_count = (token_ownership == lora_idx).sum().item() + + # Verify the kernel processed a reasonable number of tokens (sanity check) + # Note: num_tokens_post_pad includes padding, so it might be larger than expected_count + assert num_tokens_post_pad[lora_idx].item() >= expected_count * topk_num + + for token_idx in range(sorted_token_ids.size(1)): + block = sorted_token_ids[lora_idx][token_idx] + # Valid indices are those less than total numel + indices = block[block != topk_ids.numel()] + + if indices.numel() > 0: + # 1. Verify routing: Does the token actually route to this expert? + expert_id = expert_ids[lora_idx][token_idx] + assert torch.all(topk_ids.view(-1)[indices] == expert_id) + + # 2. Verify ownership: Did the kernel grab the correct tokens for this LoRA? + # The indices in 'sorted_token_ids' point to the flattened [token, topk] array. + # We divide by topk_num to get the original token index. + original_token_indices = indices // topk_num + + # Check that all tokens in this block truly belong to 'lora_idx' + actual_owners = token_ownership[original_token_indices] + assert torch.all( + actual_owners == lora_idx + ), f"Kernel put tokens from LoRA {actual_owners} into block for LoRA {lora_idx}" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_moe_wna16_marlin.py b/asian_ai/performance/SGLang/test/registered/jit/test_moe_wna16_marlin.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a952aaa04f531c170475e4825b85626476d7e7 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_moe_wna16_marlin.py @@ -0,0 +1,612 @@ +import itertools +import sys +from types import SimpleNamespace + +import pytest +import torch +from sgl_kernel.scalar_type import scalar_types + +from sglang.jit_kernel.moe_wna16_marlin import moe_wna16_marlin_gemm +from sglang.srt.layers.moe.fused_moe_triton import moe_align_block_size +from sglang.srt.layers.moe.fused_moe_triton.fused_marlin_moe import fused_marlin_moe +from sglang.srt.layers.quantization.marlin_utils_fp4 import ( + prepare_moe_nvfp4_layer_for_marlin, +) +from sglang.srt.utils.common import is_sm80_supported, is_sm90_supported +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_marlin_utils import ( + awq_marlin_quantize, + make_nvfp4_weight_and_ref, + marlin_quantize, +) + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def _has_aot_moe_wna16_marlin_gemm() -> bool: + return hasattr(torch.ops.sgl_kernel, "moe_wna16_marlin_gemm") and hasattr( + torch.ops.sgl_kernel.moe_wna16_marlin_gemm, "default" + ) + + +AOT_AVAILABLE = _has_aot_moe_wna16_marlin_gemm() + + +def stack_and_dev(tensors: list[torch.Tensor]): + dev = tensors[0].device + return torch.stack(tensors, dim=0).to(dev) + + +def _get_scalar_type(num_bits: int, has_zp: bool): + if has_zp: + assert num_bits == 4 + return scalar_types.uint4 + else: + return scalar_types.uint4b8 if num_bits == 4 else scalar_types.uint8b128 + + +def _setup_moe_weights(e, n, k, quant_type, group_size, act_order, dtype): + """Set up quantized MoE weights for a single gate (e experts, output n, input k).""" + has_zp = quant_type in [scalar_types.uint4, scalar_types.uint8] + + w = torch.randn((e, n, k), device="cuda", dtype=dtype) / 20 + + w_ref_l = [] + qweight_l = [] + scales_l = [] + zeros_l = [] + g_idx_l = [] + sort_indices_l = [] + + for i in range(e): + if has_zp: + w_ref, qweight, scales, zeros = awq_marlin_quantize( + w[i].transpose(1, 0), quant_type, group_size + ) + w_ref_l.append(w_ref.T) + qweight_l.append(qweight) + scales_l.append(scales) + zeros_l.append(zeros) + else: + test_perm = torch.randperm(k) + w_ref, qweight, scales, g_idx, sort_indices, _ = marlin_quantize( + w[i].transpose(1, 0), quant_type, group_size, act_order, test_perm + ) + w_ref_l.append(w_ref.T) + qweight_l.append(qweight) + scales_l.append(scales) + g_idx_l.append(g_idx) + sort_indices_l.append(sort_indices) + + w_ref = stack_and_dev(w_ref_l) + qweight = stack_and_dev(qweight_l).contiguous() + scales = stack_and_dev(scales_l) + g_idx = stack_and_dev(g_idx_l) if g_idx_l else None + sort_indices = stack_and_dev(sort_indices_l) if sort_indices_l else None + zeros = stack_and_dev(zeros_l) if zeros_l else None + + return w_ref, qweight, scales, zeros, g_idx, sort_indices + + +def _run_single_gemm( + fn, + a, + c, + qweight, + scales, + zeros, + g_idx, + sort_indices, + workspace, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + topk_weights, + quant_type, + block_size_m, + topk, + size_m, + size_n, + size_k, + mul_topk_weights, + is_k_full, + use_atomic_add, +): + return fn( + a, + c, + qweight, + None, # b_bias + scales, + None, # global_scale + zeros, + g_idx, + sort_indices, + workspace, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + topk_weights, + moe_block_size=block_size_m, + top_k=topk, + mul_topk_weights=mul_topk_weights, + is_ep=False, + b_q_type=quant_type, + size_m=size_m, + size_n=size_n, + size_k=size_k, + is_k_full=is_k_full, + use_atomic_add=use_atomic_add, + use_fp32_reduce=True, + is_zp_float=False, + ) + + +def _run_single_gemm_aot( + a, + c, + qweight, + scales, + zeros, + g_idx, + sort_indices, + workspace, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + topk_weights, + quant_type, + block_size_m, + topk, + size_m, + size_n, + size_k, + mul_topk_weights, + is_k_full, + use_atomic_add, +): + return torch.ops.sgl_kernel.moe_wna16_marlin_gemm.default( + a, + c, + qweight, + None, # b_bias + scales, + None, # global_scale + zeros, + g_idx, + sort_indices, + workspace, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + topk_weights, + moe_block_size=block_size_m, + top_k=topk, + mul_topk_weights=mul_topk_weights, + is_ep=False, + b_q_type_id=quant_type.id, + size_m=size_m, + size_n=size_n, + size_k=size_k, + is_k_full=is_k_full, + use_atomic_add=use_atomic_add, + use_fp32_reduce=True, + is_zp_float=False, + ) + + +def generate_test_cases(): + m_list = [1, 123] + n_list = [128, 1024] + k_list = [256] + e_list = [4] + topk_list = [2] + dtype_list = [torch.float16, torch.bfloat16] + group_size_list = [128] + act_order_list = [False, True] + quant_type_list = [scalar_types.uint4, scalar_types.uint4b8] + + all_combinations = itertools.product( + m_list, + n_list, + k_list, + e_list, + topk_list, + dtype_list, + group_size_list, + act_order_list, + quant_type_list, + ) + + def is_valid(m, n, k, e, topk, dtype, group_size, act_order, quant_type): + has_zp = quant_type in [scalar_types.uint4, scalar_types.uint8] + if act_order: + if group_size == -1 or group_size == k: + return False + if has_zp: + return False + if group_size > 0 and k % group_size != 0: + return False + return True + + return [case for case in all_combinations if is_valid(*case)] + + +TEST_CASES = generate_test_cases() + + +@pytest.mark.parametrize( + "m,n,k,e,topk,dtype,group_size,act_order,quant_type", + TEST_CASES, + ids=[ + f"m{c[0]}_n{c[1]}_k{c[2]}_e{c[3]}_t{c[4]}_{c[5].__name__ if hasattr(c[5], '__name__') else str(c[5]).split('.')[-1]}_g{c[6]}_act{c[7]}_{c[8]}" + for c in TEST_CASES + ], +) +def test_moe_wna16_marlin_gemm( + m, n, k, e, topk, dtype, group_size, act_order, quant_type +): + if not AOT_AVAILABLE: + pytest.skip("sgl_kernel moe_wna16_marlin_gemm AOT op not available") + + torch.manual_seed(0) + + has_zp = quant_type in [scalar_types.uint4, scalar_types.uint8] + + a = torch.randn((m, k), device="cuda", dtype=dtype) / 10 + + # Set up quantized weights for first gemm (gate_up: output 2*n, input k) + w_ref1, qweight1, scales1, zeros1, g_idx1, sort_indices1 = _setup_moe_weights( + e, 2 * n, k, quant_type, group_size, act_order, dtype + ) + + # Compute block_size_m + for block_size_m in [8, 16, 32, 48, 64]: + if m * topk / e / block_size_m < 0.9: + break + + # Align tokens + score = torch.randn((m, e), device="cuda", dtype=dtype) + score_softmax = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weights, topk_ids = torch.topk(score_softmax, topk) + + sorted_token_ids, expert_ids, num_tokens_post_padded = moe_align_block_size( + topk_ids, block_size_m, e + ) + + # Workspace + sms = torch.cuda.get_device_properties("cuda").multi_processor_count + max_workspace_size = (max(2 * n, k) // 64) * ( + sorted_token_ids.size(0) // block_size_m + ) + max_workspace_size = min(max_workspace_size, sms * 4) + workspace = torch.zeros( + max_workspace_size, dtype=torch.int, device="cuda", requires_grad=False + ) + + use_atomic_add = ( + dtype == torch.half or torch.cuda.get_device_capability("cuda")[0] >= 9 + ) + + scalar_type = _get_scalar_type(4, has_zp) + + # --- Run JIT kernel --- + c_jit = torch.empty((m * topk, 2 * n), dtype=dtype, device="cuda") + c_jit = _run_single_gemm( + moe_wna16_marlin_gemm, + a, + c_jit, + qweight1, + scales1, + zeros1, + g_idx1, + sort_indices1, + workspace, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + topk_weights, + scalar_type, + block_size_m, + topk, + m, + 2 * n, + k, + False, + True, + use_atomic_add, + ) + + torch.cuda.synchronize() + + # --- Check bitwise equality with AOT kernel --- + c_aot = torch.empty((m * topk, 2 * n), dtype=dtype, device="cuda") + c_aot = _run_single_gemm_aot( + a, + c_aot, + qweight1, + scales1, + zeros1, + g_idx1, + sort_indices1, + workspace, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + topk_weights, + scalar_type, + block_size_m, + topk, + m, + 2 * n, + k, + False, + True, + use_atomic_add, + ) + torch.cuda.synchronize() + torch.testing.assert_close(c_jit, c_aot, rtol=0, atol=0) + + +@pytest.mark.skipif( + not (is_sm80_supported() or is_sm90_supported()), + reason="Non-gated NVFP4 Marlin fallback test requires CUDA SM8X/SM9X", +) +def test_fused_marlin_moe_non_gated_relu2(): + torch.manual_seed(0) + + m = 17 + n = 128 + k = 256 + e = 4 + topk = 2 + dtype = torch.float16 + group_size = 128 + quant_type = scalar_types.uint4b8 + + hidden_states = torch.randn((m, k), device="cuda", dtype=dtype) / 10 + w_ref1, qweight1, scales1, zeros1, g_idx1, sort_indices1 = _setup_moe_weights( + e, n, k, quant_type, group_size, False, dtype + ) + w_ref2, qweight2, scales2, zeros2, g_idx2, sort_indices2 = _setup_moe_weights( + e, k, n, quant_type, group_size, False, dtype + ) + + router_logits = torch.randn((m, e), device="cuda", dtype=dtype) + score_softmax = torch.softmax(router_logits, dim=-1, dtype=torch.float32) + topk_weights, topk_ids = torch.topk(score_softmax, topk) + + output = fused_marlin_moe( + hidden_states=hidden_states, + w1=qweight1, + w2=qweight2, + w1_scale=scales1, + w2_scale=scales2, + gating_output=router_logits, + topk_weights=topk_weights, + topk_ids=topk_ids, + g_idx1=g_idx1, + g_idx2=g_idx2, + sort_indices1=sort_indices1, + sort_indices2=sort_indices2, + w1_zeros=zeros1, + w2_zeros=zeros2, + num_bits=4, + is_k_full=True, + routed_scaling_factor=1.0, + activation="relu2", + is_gated=False, + ) + + output_ref = torch.zeros_like(hidden_states) + for token_idx in range(m): + for route_idx in range(topk): + expert_id = topk_ids[token_idx, route_idx] + intermediate = hidden_states[token_idx] @ w_ref1[expert_id].T + intermediate = torch.square(torch.relu(intermediate)) + routed = intermediate @ w_ref2[expert_id].T + output_ref[token_idx] += routed * topk_weights[token_idx, route_idx] + + torch.cuda.synchronize() + torch.testing.assert_close(output, output_ref, rtol=0.04, atol=0.04) + + +@pytest.mark.skipif( + not (is_sm80_supported() or is_sm90_supported()), + reason="NVFP4 Marlin MoE padding test requires CUDA SM8X/SM9X", +) +def test_fused_marlin_moe_nvfp4_non_gated_padded_intermediate_launches(): + torch.manual_seed(0) + + m = 17 + intermediate_size = 192 + hidden_size = 256 + e = 4 + topk = 2 + dtype = torch.bfloat16 + nvfp4_group_size = 16 + + layer = torch.nn.Module() + layer.quant_config = SimpleNamespace(group_size=nvfp4_group_size) + layer.moe_runner_config = SimpleNamespace(is_gated=False) + layer.params_dtype = dtype + layer.intermediate_size_per_partition = intermediate_size + layer.w13_weight = torch.nn.Parameter( + torch.randint( + 0, + 256, + (e, intermediate_size, hidden_size // 2), + device="cuda", + dtype=torch.uint8, + ), + requires_grad=False, + ) + layer.w2_weight = torch.nn.Parameter( + torch.randint( + 0, + 256, + (e, hidden_size, intermediate_size // 2), + device="cuda", + dtype=torch.uint8, + ), + requires_grad=False, + ) + layer.w13_weight_scale = torch.nn.Parameter( + torch.rand( + (e, intermediate_size, hidden_size // nvfp4_group_size), + device="cuda", + dtype=dtype, + ), + requires_grad=False, + ) + layer.w2_weight_scale = torch.nn.Parameter( + torch.rand( + (e, hidden_size, intermediate_size // nvfp4_group_size), + device="cuda", + dtype=dtype, + ), + requires_grad=False, + ) + layer.w13_weight_scale_2 = torch.nn.Parameter( + torch.ones((e,), device="cuda", dtype=dtype), requires_grad=False + ) + layer.w2_weight_scale_2 = torch.nn.Parameter( + torch.ones((e,), device="cuda", dtype=dtype), requires_grad=False + ) + prepare_moe_nvfp4_layer_for_marlin(layer) + + assert layer.w13_weight.shape[1] * 16 == 256 + assert layer.w2_weight.shape[1] * 16 == 256 + + hidden_states = torch.randn((m, hidden_size), device="cuda", dtype=dtype) / 10 + + score = torch.randn((m, e), device="cuda", dtype=dtype) + score_softmax = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weights, topk_ids = torch.topk(score_softmax, topk) + + out = fused_marlin_moe( + hidden_states=hidden_states, + w1=layer.w13_weight, + w2=layer.w2_weight, + w1_scale=layer.w13_weight_scale, + w2_scale=layer.w2_weight_scale, + gating_output=score, + topk_weights=topk_weights, + topk_ids=topk_ids, + w1_global_scale=layer.w13_weight_scale_2, + w2_global_scale=layer.w2_weight_scale_2, + workspace=layer.workspace, + num_bits=4, + is_k_full=True, + routed_scaling_factor=1.0, + activation="relu2", + is_gated=False, + ) + + torch.cuda.synchronize() + assert out.shape == (m, hidden_size) + + +@pytest.mark.skipif( + not (is_sm80_supported() or is_sm90_supported()), + reason="NVFP4 Marlin MoE numeric test requires CUDA SM80, SM86, or SM90", +) +def test_fused_marlin_moe_nvfp4_non_gated_matches_dequant_reference(): + torch.manual_seed(0) + + m = 17 + intermediate_size = 192 + hidden_size = 256 + e = 4 + topk = 2 + dtype = torch.bfloat16 + group_size = 16 + routed_scaling_factor = 1.0 + + w13_packed_l, w13_scales_l, w13_gscale_l, w13_ref_l = [], [], [], [] + w2_packed_l, w2_scales_l, w2_gscale_l, w2_ref_l = [], [], [], [] + for _ in range(e): + packed, scales, gscale, ref = make_nvfp4_weight_and_ref( + intermediate_size, hidden_size, dtype, group_size=group_size + ) + w13_packed_l.append(packed) + w13_scales_l.append(scales) + w13_gscale_l.append(gscale) + w13_ref_l.append(ref) + + packed, scales, gscale, ref = make_nvfp4_weight_and_ref( + hidden_size, intermediate_size, dtype, group_size=group_size + ) + w2_packed_l.append(packed) + w2_scales_l.append(scales) + w2_gscale_l.append(gscale) + w2_ref_l.append(ref) + + layer = torch.nn.Module() + layer.quant_config = SimpleNamespace(group_size=group_size) + layer.moe_runner_config = SimpleNamespace(is_gated=False) + layer.params_dtype = dtype + layer.intermediate_size_per_partition = intermediate_size + layer.w13_weight = torch.nn.Parameter( + torch.stack(w13_packed_l), requires_grad=False + ) + layer.w2_weight = torch.nn.Parameter(torch.stack(w2_packed_l), requires_grad=False) + layer.w13_weight_scale = torch.nn.Parameter( + torch.stack(w13_scales_l), requires_grad=False + ) + layer.w2_weight_scale = torch.nn.Parameter( + torch.stack(w2_scales_l), requires_grad=False + ) + layer.w13_weight_scale_2 = torch.nn.Parameter( + torch.stack(w13_gscale_l), requires_grad=False + ) + layer.w2_weight_scale_2 = torch.nn.Parameter( + torch.stack(w2_gscale_l), requires_grad=False + ) + prepare_moe_nvfp4_layer_for_marlin(layer) + + # Scale activations down so relu² doesn't blow up intermediate magnitudes; + # this keeps output values small so tighter element-wise tolerance is realistic. + hidden_states = torch.randn((m, hidden_size), device="cuda", dtype=dtype) / 20 + router_logits = torch.randn((m, e), device="cuda", dtype=dtype) + score_softmax = torch.softmax(router_logits, dim=-1, dtype=torch.float32) + topk_weights, topk_ids = torch.topk(score_softmax, topk) + + output = fused_marlin_moe( + hidden_states=hidden_states, + w1=layer.w13_weight, + w2=layer.w2_weight, + w1_scale=layer.w13_weight_scale, + w2_scale=layer.w2_weight_scale, + gating_output=router_logits, + topk_weights=topk_weights, + topk_ids=topk_ids, + w1_global_scale=layer.w13_weight_scale_2, + w2_global_scale=layer.w2_weight_scale_2, + workspace=layer.workspace, + num_bits=4, + is_k_full=True, + routed_scaling_factor=routed_scaling_factor, + activation="relu2", + is_gated=False, + ) + + w13_ref = torch.stack(w13_ref_l) + w2_ref = torch.stack(w2_ref_l) + output_ref = torch.zeros_like(hidden_states) + for token_idx in range(m): + for route_idx in range(topk): + expert_id = topk_ids[token_idx, route_idx] + intermediate = hidden_states[token_idx] @ w13_ref[expert_id].T + intermediate = torch.square(torch.relu(intermediate)) + routed = intermediate @ w2_ref[expert_id].T + output_ref[token_idx] += routed * topk_weights[token_idx, route_idx] + output_ref *= routed_scaling_factor + + torch.cuda.synchronize() + torch.testing.assert_close(output, output_ref, rtol=0.05, atol=0.25) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_mxfp8_moe.py b/asian_ai/performance/SGLang/test/registered/jit/test_mxfp8_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..8f08be4390f861c460dc0a26dc2581fd906397e4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_mxfp8_moe.py @@ -0,0 +1,153 @@ +import random +import sys + +import pytest +import torch + +from sglang.jit_kernel.mxfp8 import ( + es_sm100_mxfp8_blockscaled_grouped_quant, + es_sm100_mxfp8_blockscaled_moe_grouped_gemm, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=5, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def align(val: int, alignment: int = 128) -> int: + return int((val + alignment - 1) // alignment * alignment) + + +# Copy from: https://github.com/deepseek-ai/DeepGEMM/blob/main/deep_gemm/utils.py +def calc_diff(x, y): + x, y = x.double(), y.double() + denominator = (x * x + y * y).sum() + sim = 2 * (x * y).sum() / denominator + return 1 - sim + + +def is_sm100_supported(device=None) -> bool: + return (torch.cuda.get_device_capability(device)[0] == 10) and ( + torch.version.cuda >= "12.8" + ) + + +@pytest.mark.skipif( + not is_sm100_supported(), + reason="test_mxfp8_moe at jit kernen is only supported on sm100", +) +@pytest.mark.parametrize("num_experts", [8, 16, 32, 64]) +@pytest.mark.parametrize("out_dtype", [torch.half, torch.bfloat16]) +def test_es_sm100_mxfp8_blockscaled_grouped_mm(num_experts, out_dtype): + device = "cuda" + alignment = 128 + n_g = random.randint(1, 64) * alignment + k_g = random.randint(1, 64) * alignment + + expert_offset = 0 + expert_offsets = [] + aux_expert_offset = 0 + aux_expert_offsets = [] + a_blockscale_offset = 0 + a_blockscale_offsets = [] + b_blockscale_offset = 0 + b_blockscale_offsets = [] + a_list = [] + b_list = [] + ref_d_list = [] + tokens_per_expert = [] + + for g in range(num_experts): + m_g = random.randint(1, 512) + tokens_per_expert.append(m_g) + expert_offsets.append(expert_offset) + expert_offset += m_g + aux_expert_offsets.append(aux_expert_offset) + aux_expert_offset += n_g + a_blockscale_offsets.append(a_blockscale_offset) + a_blockscale_offset += align(m_g, 128) + b_blockscale_offsets.append(b_blockscale_offset) + b_blockscale_offset += n_g # n_g already align to 128 + + a = torch.normal( + 0.0, std=1.0, size=(m_g, k_g), device=device, dtype=out_dtype + ) # (M, K):(K, 1) + b = torch.normal( + 0.0, std=1.0, size=(n_g, k_g), device=device, dtype=out_dtype + ) # (N, K):(K, 1) + + a_list.append(a) + b_list.append(b) + ref_d = a @ b.T + ref_d_list.append(ref_d) + a = torch.concat(a_list, dim=0) + b = torch.concat(b_list, dim=0) + + _expert_offsets = torch.tensor(expert_offsets).to(device=device, dtype=torch.int32) + _aux_expert_offsets = torch.tensor(aux_expert_offsets).to( + device=device, dtype=torch.int32 + ) + _a_blockscale_offsets = torch.tensor(a_blockscale_offsets).to( + device=device, dtype=torch.int32 + ) + _b_blockscale_offsets = torch.tensor(b_blockscale_offsets).to( + device=device, dtype=torch.int32 + ) + + a_quant = torch.zeros_like(a, dtype=torch.float8_e4m3fn, device=device) + a_scale_factor = torch.zeros( + (a_blockscale_offset, k_g // 32), dtype=torch.uint8, device=device + ) + + b_quant = torch.zeros_like(b, dtype=torch.float8_e4m3fn, device=device) + b_scale_factor = torch.zeros( + (num_experts * n_g, k_g // 32), dtype=torch.uint8, device=device + ) + tokens_per_expert = torch.tensor(tokens_per_expert).to( + device=device, dtype=torch.int32 + ) + workspace = torch.empty((1024, 1024, 1024), dtype=torch.uint8, device=device) + + es_sm100_mxfp8_blockscaled_grouped_quant( + a, + tokens_per_expert, + _expert_offsets, + _a_blockscale_offsets, + a_quant, + a_scale_factor, + ) + es_sm100_mxfp8_blockscaled_grouped_quant( + b, + torch.ones_like(tokens_per_expert) * n_g, + _aux_expert_offsets, + _b_blockscale_offsets, + b_quant, + b_scale_factor, + ) + + b_quant = b_quant.view(num_experts, n_g, k_g) + b_scale_factor = b_scale_factor.view(num_experts, n_g, k_g // 32) + d = es_sm100_mxfp8_blockscaled_moe_grouped_gemm( + b_quant, + a_quant, + b_scale_factor, + a_scale_factor, + _expert_offsets, + _a_blockscale_offsets, + tokens_per_expert, + workspace, + a.dtype, + ) + + for g in range(num_experts): + baseline = ref_d_list[g] + actual = d[expert_offsets[g] : (expert_offsets[g] + tokens_per_expert[g])] + diff = calc_diff(actual, baseline) + assert diff < 0.001 + print( + f"m_g={baseline.shape[0]} n_g={n_g} k_g={k_g} num_experts={num_experts}, out_dtype={out_dtype}, diff={diff:.5f}: OK" + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_ngram_embedding.py b/asian_ai/performance/SGLang/test/registered/jit/test_ngram_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..125ba3a3d3a76c21f91c6ce2df5667d47ce5bfd0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_ngram_embedding.py @@ -0,0 +1,136 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.ngram_embedding import ( + compute_n_gram_ids, + compute_n_gram_ids_decode, + update_token_table, + update_token_table_decode, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=8, stage="jit-kernel-unit", runner_config="amd") + + +def _make_ngram_params(ne_n: int, ne_k: int, vocab_size: int): + ne_weights = torch.zeros([ne_n - 1, ne_k, ne_n], dtype=torch.int32) + ne_mods = torch.zeros([ne_n - 1, ne_k], dtype=torch.int32) + exclusive_sums = torch.zeros([(ne_n - 1) * ne_k + 1], dtype=torch.int32) + + for n in range(2, ne_n + 1): + for k in range(ne_k): + config_id = (n - 2) * ne_k + k + mod = 65537 + 2 * config_id + ne_mods[n - 2][k] = mod + exclusive_sums[config_id + 1] = exclusive_sums[config_id] + mod + for delta in range(ne_n): + ne_weights[n - 2][k][delta] = pow(vocab_size, delta, mod) + + return ( + ne_weights.cuda(), + ne_mods.cuda(), + exclusive_sums.cuda(), + ) + + +@pytest.mark.parametrize("batch_size", [1, 2, 17, 128, 1024]) +def test_compute_n_gram_ids_decode_matches_general(batch_size: int) -> None: + ne_n = 8 + ne_k = 2 + vocab_size = 32000 + max_context_len = 1024 + max_running_reqs = batch_size + 8 + num_configs = (ne_n - 1) * ne_k + + ne_weights, ne_mods, exclusive_sums = _make_ngram_params(ne_n, ne_k, vocab_size) + ne_token_table = torch.randint( + 0, + vocab_size, + (max_running_reqs, max_context_len), + dtype=torch.int32, + device="cuda", + ) + row_indices = torch.randperm(max_running_reqs, device="cuda")[:batch_size].to( + torch.int64 + ) + column_starts = torch.randint( + 0, max_context_len, (batch_size,), dtype=torch.int32, device="cuda" + ) + tokens = torch.empty(batch_size, dtype=torch.int32, device="cuda") + exclusive_req_len_sums = torch.arange( + batch_size + 1, dtype=torch.int32, device="cuda" + ) + n_gram_ids_general = torch.empty( + (batch_size, num_configs), dtype=torch.int32, device="cuda" + ) + n_gram_ids_decode = torch.empty_like(n_gram_ids_general) + + compute_n_gram_ids( + ne_n=ne_n, + ne_k=ne_k, + ne_weights=ne_weights, + ne_mods=ne_mods, + exclusive_ne_embedder_size_sums=exclusive_sums, + tokens=tokens, + exclusive_req_len_sums=exclusive_req_len_sums, + ne_token_table=ne_token_table, + row_indices=row_indices, + column_starts=column_starts, + n_gram_ids=n_gram_ids_general, + ) + compute_n_gram_ids_decode( + ne_n=ne_n, + ne_k=ne_k, + ne_weights=ne_weights, + ne_mods=ne_mods, + exclusive_ne_embedder_size_sums=exclusive_sums, + ne_token_table=ne_token_table, + row_indices=row_indices, + column_starts=column_starts, + n_gram_ids=n_gram_ids_decode, + ) + + torch.testing.assert_close(n_gram_ids_decode, n_gram_ids_general, atol=0, rtol=0) + + +@pytest.mark.parametrize("batch_size", [1, 2, 17, 128, 1024]) +def test_update_token_table_decode_matches_general(batch_size: int) -> None: + max_context_len = 4096 + max_running_reqs = batch_size + 8 + tokens = torch.arange(batch_size, dtype=torch.int32, device="cuda") + 100 + row_indices = torch.randperm(max_running_reqs, device="cuda")[:batch_size].to( + torch.int64 + ) + column_starts = torch.randint( + 0, max_context_len, (batch_size,), dtype=torch.int32, device="cuda" + ) + req_lens = torch.ones(batch_size, dtype=torch.int32, device="cuda") + + token_table_general = torch.full( + (max_running_reqs, max_context_len), -1, dtype=torch.int32, device="cuda" + ) + token_table_decode = token_table_general.clone() + + update_token_table( + tokens=tokens, + ne_token_table=token_table_general, + row_indices=row_indices, + column_starts=column_starts, + req_lens=req_lens, + ignore_tokens=None, + ) + update_token_table_decode( + tokens=tokens, + ne_token_table=token_table_decode, + row_indices=row_indices, + column_starts=column_starts, + ) + + torch.testing.assert_close(token_table_decode, token_table_general, atol=0, rtol=0) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_nvfp4_blockwise_moe.py b/asian_ai/performance/SGLang/test/registered/jit/test_nvfp4_blockwise_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..5a30b851cf12f80cd50f3e6616c483e4935e229b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_nvfp4_blockwise_moe.py @@ -0,0 +1,137 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.nvfp4 import ( + cutlass_fp4_group_mm, + scaled_fp4_experts_quant, + scaled_fp4_quant, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=5, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +FLOAT4_E2M1_MAX = 6.0 +FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max + + +def _nvfp4_supported() -> bool: + return torch.cuda.is_available() and torch.cuda.get_device_capability() >= (10, 0) + + +def _round_up(x: int, y: int) -> int: + return ((x + y - 1) // y) * y + + +def _build_expert_offsets( + m_per_expert: list[int], device: torch.device +) -> torch.Tensor: + offsets = [0] + for m in m_per_expert: + offsets.append(offsets[-1] + m) + return torch.tensor(offsets, dtype=torch.int32, device=device) + + +def _build_blockscale_offsets( + m_per_expert: list[int], device: torch.device +) -> torch.Tensor: + offsets = [0] + for m in m_per_expert: + offsets.append(offsets[-1] + _round_up(m, 128)) + return torch.tensor(offsets, dtype=torch.int32, device=device) + + +@pytest.mark.skipif( + not _nvfp4_supported(), reason="NVFP4 requires compute capability >= 10.0" +) +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_nvfp4_blockwise_moe_grouped_mm(dtype: torch.dtype) -> None: + torch.manual_seed(0) + device = torch.device("cuda") + + num_experts = 4 + m_per_expert = [33, 17, 48, 29] + n = 256 + k = 128 + + expert_offsets_full = _build_expert_offsets(m_per_expert, device) + blockscale_offsets_full = _build_blockscale_offsets(m_per_expert, device) + + total_m = int(expert_offsets_full[-1].item()) + a = torch.randn((total_m, k), device=device, dtype=dtype) * 0.1 + b = torch.randn((num_experts, n, k), device=device, dtype=dtype) * 0.1 + + a_global_scale = torch.empty((num_experts,), device=device, dtype=torch.float32) + for i in range(num_experts): + start = int(expert_offsets_full[i].item()) + end = int(expert_offsets_full[i + 1].item()) + amax = a[start:end].abs().max().to(torch.float32) + a_global_scale[i] = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / amax + + b_global_scale = torch.empty((num_experts,), device=device, dtype=torch.float32) + for i in range(num_experts): + bmax = b[i].abs().max().to(torch.float32) + b_global_scale[i] = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / bmax + + a_fp4, a_blockscale = scaled_fp4_experts_quant( + a, + a_global_scale, + expert_offsets_full, + blockscale_offsets_full, + topk=1, + ) + + b_fp4 = torch.empty((num_experts, n, k // 2), device=device, dtype=torch.uint8) + b_blockscale = torch.empty( + (num_experts, _round_up(n, 128), _round_up(k // 16, 4)), + device=device, + dtype=torch.float8_e4m3fn, + ) + for i in range(num_experts): + b_fp4_i, b_scale_i = scaled_fp4_quant(b[i], b_global_scale[i]) + b_fp4[i].copy_(b_fp4_i) + b_blockscale[i].copy_(b_scale_i) + + alphas = (1.0 / (a_global_scale * b_global_scale)).to(torch.float32) + + params = { + "ab_strides": torch.full((num_experts,), k, dtype=torch.int64, device=device), + "c_strides": torch.full((num_experts,), n, dtype=torch.int64, device=device), + "problem_sizes": torch.tensor( + [[m, n, k] for m in m_per_expert], dtype=torch.int32, device=device + ), + "expert_offsets": expert_offsets_full[:-1].contiguous(), + "blockscale_offsets": blockscale_offsets_full[:-1].contiguous(), + "a_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "b_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "out_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "a_scales_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "b_scales_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "alpha_ptrs": torch.empty((num_experts,), dtype=torch.int64, device=device), + "layout_sfa": torch.empty((num_experts, 5), dtype=torch.int64, device=device), + "layout_sfb": torch.empty((num_experts, 5), dtype=torch.int64, device=device), + } + + out = cutlass_fp4_group_mm( + a_fp4, + b_fp4, + a_blockscale, + b_blockscale, + alphas, + dtype, + params, + ) + + ref = torch.empty((total_m, n), device=device, dtype=dtype) + for i in range(num_experts): + start = int(expert_offsets_full[i].item()) + end = int(expert_offsets_full[i + 1].item()) + ref[start:end] = torch.matmul(a[start:end], b[i].t()) + + torch.testing.assert_close(out, ref, atol=1e-1, rtol=1e-1) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_nvfp4_gemm.py b/asian_ai/performance/SGLang/test/registered/jit/test_nvfp4_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..fe420880aa5de2a0361a9907b1a836d9b6a47558 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_nvfp4_gemm.py @@ -0,0 +1,152 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.nvfp4 import cutlass_scaled_fp4_mm, scaled_fp4_quant +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=5, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def _nvfp4_supported() -> bool: + return torch.cuda.is_available() and torch.cuda.get_device_capability() >= (10, 0) + + +DTYPES = [torch.float16, torch.bfloat16] +SHAPES = [ + (128, 128, 64), + (128, 128, 128), + (256, 128, 64), + (128, 256, 128), + (150, 128, 64), +] + +FLOAT4_E2M1_MAX = 6.0 +FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max + +K_E2M1_TO_FLOAT = [ + 0.0, + 0.5, + 1.0, + 1.5, + 2.0, + 3.0, + 4.0, + 6.0, +] + + +def e2m1_to_fp32(int4_value: int) -> float: + sign_bit = int4_value & 0x8 + int4_abs_value = int4_value & 0x7 + float_result = K_E2M1_TO_FLOAT[int4_abs_value] + return -float_result if sign_bit else float_result + + +def break_fp4_bytes(a: torch.Tensor) -> torch.Tensor: + assert a.dtype == torch.uint8 + m, n = a.shape + a = a.flatten() + high_half_byte = (a & 0xF0) >> 4 + low_half_byte = a & 0x0F + f_h = torch.tensor([e2m1_to_fp32(x) for x in high_half_byte], device=a.device) + f_l = torch.tensor([e2m1_to_fp32(x) for x in low_half_byte], device=a.device) + return torch.stack((f_l, f_h), dim=-1).reshape(m, n * 2) + + +def convert_swizzled_to_linear( + a_sf_swizzled: torch.Tensor, m: int, k: int, block_size: int +) -> torch.Tensor: + sf_m, sf_k = a_sf_swizzled.shape + del sf_m, sf_k + m_tiles = (m + 128 - 1) // 128 + f = block_size * 4 + k_tiles = (k + f - 1) // f + tmp = torch.reshape(a_sf_swizzled, (1, m_tiles, k_tiles, 32, 4, 4)) + tmp = torch.permute(tmp, (0, 1, 4, 3, 2, 5)) + out = tmp.reshape(m_tiles * 128, k_tiles * f // block_size) + return out[0:m, 0 : k // block_size] + + +def dequantize_to_dtype( + tensor_fp4: torch.Tensor, + tensor_sf: torch.Tensor, + global_scale: torch.Tensor, + block_size: int = 16, +) -> torch.Tensor: + assert tensor_fp4.dtype == torch.uint8 + m, packed_k = tensor_fp4.shape + k = packed_k * 2 + tensor_f32 = break_fp4_bytes(tensor_fp4) + tensor_f32 = tensor_f32.reshape(m, k // block_size, block_size) + tensor_sf = tensor_sf.view(torch.float8_e4m3fn) + tensor_sf = convert_swizzled_to_linear(tensor_sf, m, k, block_size) + tensor_sf_dtype = tensor_sf.to(torch.float32) / global_scale + return (tensor_f32 * tensor_sf_dtype.unsqueeze(-1)).reshape(m, k) + + +def get_ref_results( + a_fp4: torch.Tensor, + b_fp4: torch.Tensor, + a_sf: torch.Tensor, + b_sf: torch.Tensor, + a_global_scale: torch.Tensor, + b_global_scale: torch.Tensor, + block_size: int, +) -> torch.Tensor: + a_in_dtype = dequantize_to_dtype(a_fp4, a_sf, a_global_scale, block_size=block_size) + b_in_dtype = dequantize_to_dtype(b_fp4, b_sf, b_global_scale, block_size=block_size) + return torch.matmul(a_in_dtype, b_in_dtype.t()) + + +@pytest.mark.skipif( + not _nvfp4_supported(), reason="NVFP4 requires compute capability >= 10.0" +) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("shape", SHAPES) +def test_nvfp4_gemm(dtype: torch.dtype, shape: tuple[int, int, int]) -> None: + m, n, packed_k = shape + k = packed_k * 2 + block_size = 16 + + a_dtype = torch.randn((m, k), dtype=dtype, device="cuda") + b_dtype = torch.randn((n, k), dtype=dtype, device="cuda") + + a_global_scale = ( + (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(a_dtype.flatten(), dim=-1) + ).to(torch.float32) + b_global_scale = ( + (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(b_dtype.flatten(), dim=-1) + ).to(torch.float32) + + alpha = 1.0 / (a_global_scale * b_global_scale) + + a_fp4, a_scale_interleaved = scaled_fp4_quant(a_dtype, a_global_scale) + b_fp4, b_scale_interleaved = scaled_fp4_quant(b_dtype, b_global_scale) + + expected_out = get_ref_results( + a_fp4, + b_fp4, + a_scale_interleaved, + b_scale_interleaved, + a_global_scale, + b_global_scale, + block_size, + ) + + out = cutlass_scaled_fp4_mm( + a_fp4, + b_fp4, + a_scale_interleaved, + b_scale_interleaved, + alpha, + dtype, + ) + + torch.testing.assert_close(out, expected_out.to(dtype=dtype), atol=1e-1, rtol=1e-1) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_nvfp4_quant.py b/asian_ai/performance/SGLang/test/registered/jit/test_nvfp4_quant.py new file mode 100644 index 0000000000000000000000000000000000000000..505a8e760b57f87d0e9b7ae8beb5187a2bfc1ca9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_nvfp4_quant.py @@ -0,0 +1,225 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.nvfp4 import ( + scaled_fp4_grouped_quant, + scaled_fp4_quant, + silu_and_mul_scaled_fp4_grouped_quant, +) + +try: + from sgl_kernel import silu_and_mul as _sgl_silu_and_mul +except Exception: + _sgl_silu_and_mul = None + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=5, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def _nvfp4_supported() -> bool: + return torch.cuda.is_available() and torch.cuda.get_device_capability() >= (10, 0) + + +def _silu_and_mul_reference(x: torch.Tensor) -> torch.Tensor: + if _sgl_silu_and_mul is not None: + return _sgl_silu_and_mul(x) + k = x.shape[-1] // 2 + return torch.nn.functional.silu(x[:, :, :k]) * x[:, :, k:] + + +DTYPES = [torch.float16, torch.bfloat16] +SHAPES = [(128, 64), (128, 128), (256, 64), (256, 128)] +PAD_SHAPES = [ + (90, 64), + (150, 64), + (128, 48), + (128, 80), +] + +FLOAT4_E2M1_MAX = 6.0 +FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max +BLOCK_SIZE = 16 + +E2M1_TO_FLOAT32 = [ + 0.0, + 0.5, + 1.0, + 1.5, + 2.0, + 3.0, + 4.0, + 6.0, + 0.0, + -0.5, + -1.0, + -1.5, + -2.0, + -3.0, + -4.0, + -6.0, +] + + +def cast_from_fp4(x: torch.Tensor, m: int, n: int) -> torch.Tensor: + v_2nd = (x & 0xF).to(torch.long) + v_1st = ((x >> 4) & 0xF).to(torch.long) + c = torch.stack((v_2nd, v_1st), dim=-1).flatten() + lut = torch.tensor(E2M1_TO_FLOAT32, device=x.device, dtype=torch.float32) + return lut[c].reshape(m, n) + + +def cast_to_fp4(x: torch.Tensor) -> torch.Tensor: + sign = torch.sign(x) + x = torch.abs(x) + x[(x >= 0.0) & (x <= 0.25)] = 0.0 + x[(x > 0.25) & (x < 0.75)] = 0.5 + x[(x >= 0.75) & (x <= 1.25)] = 1.0 + x[(x > 1.25) & (x < 1.75)] = 1.5 + x[(x >= 1.75) & (x <= 2.5)] = 2.0 + x[(x > 2.5) & (x < 3.5)] = 3.0 + x[(x >= 3.5) & (x <= 5.0)] = 4.0 + x[x > 5.0] = 6.0 + return x * sign + + +def get_reciprocal(x): + if isinstance(x, torch.Tensor): + return torch.where(x == 0, torch.tensor(0.0, dtype=x.dtype), 1.0 / x) + return 0.0 if x == 0 else 1.0 / x + + +def ref_nvfp4_quant(x: torch.Tensor, global_scale: torch.Tensor): + assert global_scale.dtype == torch.float32 + assert x.ndim == 2 + m, n = x.shape + x = torch.reshape(x, (m, n // BLOCK_SIZE, BLOCK_SIZE)) + vec_max = torch.max(torch.abs(x), dim=-1, keepdim=True)[0].to(torch.float32) + scale = global_scale * (vec_max * get_reciprocal(FLOAT4_E2M1_MAX)) + scale = scale.to(torch.float8_e4m3fn).to(torch.float32) + output_scale = get_reciprocal(scale * get_reciprocal(global_scale)) + + scaled_x = x.to(torch.float32) * output_scale + clipped_x = torch.clamp(scaled_x, -6.0, 6.0).reshape(m, n) + return cast_to_fp4(clipped_x), scale.squeeze(-1) + + +def recover_swizzled_scales(scale: torch.Tensor, m: int, n: int) -> torch.Tensor: + rounded_m = ((m + 128 - 1) // 128) * 128 + scale_n = n // BLOCK_SIZE + rounded_n = ((scale_n + 4 - 1) // 4) * 4 + tmp = torch.reshape(scale, (1, rounded_m // 128, rounded_n // 4, 32, 4, 4)) + tmp = torch.permute(tmp, (0, 1, 4, 3, 2, 5)) + result = torch.reshape(tmp, (rounded_m, rounded_n)).to(torch.float32) + return result[:m, :scale_n] + + +@pytest.mark.skipif( + not _nvfp4_supported(), reason="NVFP4 requires compute capability >= 10.0" +) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("shape", SHAPES) +def test_quantize_to_fp4(dtype: torch.dtype, shape: tuple[int, int]) -> None: + torch.manual_seed(42) + m, n = shape + + x = torch.randn((m, n), dtype=dtype, device="cuda") + tensor_amax = torch.abs(x).max().to(torch.float32) + global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / tensor_amax + out_ref, scale_ref = ref_nvfp4_quant(x, global_scale) + + out, out_scale = scaled_fp4_quant(x, global_scale) + scale_ans = recover_swizzled_scales(out_scale, m, n) + out_ans = cast_from_fp4(out, m, n) + + torch.testing.assert_close(out_ans, out_ref) + torch.testing.assert_close(scale_ans, scale_ref) + + +@pytest.mark.skipif( + not _nvfp4_supported(), reason="NVFP4 requires compute capability >= 10.0" +) +@pytest.mark.parametrize("shape", PAD_SHAPES) +def test_quantize_to_fp4_padded(shape: tuple[int, int]) -> None: + torch.manual_seed(42) + m, n = shape + x = torch.randn((m, n), dtype=torch.float16, device="cuda") + + tensor_amax = torch.abs(x).max().to(torch.float32) + global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / tensor_amax + out_ref, scale_ref = ref_nvfp4_quant(x, global_scale) + + out, out_scale = scaled_fp4_quant(x, global_scale) + scale_ans = recover_swizzled_scales(out_scale, m, n) + out_ans = cast_from_fp4(out, m, n) + + torch.testing.assert_close(out_ans, out_ref) + torch.testing.assert_close(scale_ans, scale_ref) + + +@pytest.mark.skipif( + not _nvfp4_supported(), reason="NVFP4 requires compute capability >= 10.0" +) +@pytest.mark.parametrize("shape", [(2, 128, 512), (2, 100, 128)]) +def test_quantize_to_fp4_grouped(shape: tuple[int, int, int]) -> None: + torch.manual_seed(42) + l, m, k = shape + + x = torch.randn((l, m, k), dtype=torch.bfloat16, device="cuda") + mask = torch.randint(1, max(2, m // 2), (l,), dtype=torch.int32, device="cuda") + tensor_amax = x.abs().amax(dim=(1, 2)).to(torch.float32) + x_sf_global = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / tensor_amax + + output, output_scales = scaled_fp4_grouped_quant(x, x_sf_global, mask) + output = output.permute(2, 0, 1) + padded_m = ((m + 128 - 1) // 128) * 128 + output_scales = output_scales.permute(5, 2, 4, 0, 1, 3).view(l, padded_m, -1) + + for i in range(l): + a_fp4, a_scale_interleaved = scaled_fp4_quant(x[i], x_sf_global[i]) + torch.testing.assert_close(a_fp4[: mask[i]], output[i][: mask[i]]) + scale_ref = recover_swizzled_scales(a_scale_interleaved, m, k) + scale_ans = recover_swizzled_scales(output_scales[i], m, k) + torch.testing.assert_close(scale_ref[: mask[i]], scale_ans[: mask[i]]) + + +@pytest.mark.skipif( + not _nvfp4_supported(), reason="NVFP4 requires compute capability >= 10.0" +) +@pytest.mark.parametrize("shape", [(4, 96, 256), (8, 128, 512)]) +def test_silu_and_mul_quantize_to_fp4_grouped(shape: tuple[int, int, int]) -> None: + torch.manual_seed(42) + l, m, k = shape + + x = torch.randn((l, m, k * 2), dtype=torch.bfloat16, device="cuda") + mask = torch.randint(1, max(2, m // 2), (l,), dtype=torch.int32, device="cuda") + + ref_y = _silu_and_mul_reference(x) + + tensor_amax = ref_y.abs().amax(dim=(1, 2)).to(torch.float32) + y_sf_global = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / tensor_amax + + ref_output, ref_output_scales = scaled_fp4_grouped_quant(ref_y, y_sf_global, mask) + output, output_scales = silu_and_mul_scaled_fp4_grouped_quant(x, y_sf_global, mask) + + output = output.permute(2, 0, 1) + ref_output = ref_output.permute(2, 0, 1) + + padded_m = ((m + 128 - 1) // 128) * 128 + output_scales = output_scales.permute(5, 2, 4, 0, 1, 3).view(l, padded_m, -1) + ref_output_scales = ref_output_scales.permute(5, 2, 4, 0, 1, 3).view( + l, padded_m, -1 + ) + + for i in range(l): + torch.testing.assert_close(ref_output[i, : mask[i]], output[i, : mask[i]]) + scale_ref = recover_swizzled_scales(ref_output_scales[i], m, k) + scale_ans = recover_swizzled_scales(output_scales[i], m, k) + torch.testing.assert_close(scale_ref[: mask[i]], scale_ans[: mask[i]]) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_per_tensor_quant_fp8.py b/asian_ai/performance/SGLang/test/registered/jit/test_per_tensor_quant_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..1d9fb40f25c00bf3c7545c11d2c2e4c319584781 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_per_tensor_quant_fp8.py @@ -0,0 +1,100 @@ +import itertools +import sys +from typing import Optional, Tuple + +import pytest +import torch + +from sglang.jit_kernel.per_tensor_quant_fp8 import per_tensor_quant_fp8 +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=16, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +try: + from sglang.srt.utils import is_hip + + _is_hip = is_hip() +except ImportError: + _is_hip = False + +fp8_type_ = torch.float8_e4m3fnuz if _is_hip else torch.float8_e4m3fn + + +def sglang_scaled_fp8_quant( + input: torch.Tensor, + scale: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor]: + fp8_type_: torch.dtype = torch.float8_e4m3fn + output = torch.empty_like(input, device=input.device, dtype=fp8_type_) + is_static = True + if scale is None: + scale = torch.zeros(1, device=input.device, dtype=torch.float32) + is_static = False + per_tensor_quant_fp8(input, output, scale, is_static) + + return output, scale + + +def torch_scaled_fp8_quant(tensor, inv_scale): + finfo = torch.finfo(torch.float8_e4m3fn) + scale = inv_scale.reciprocal() + qweight = (tensor.to(torch.float32) * scale).clamp(min=finfo.min, max=finfo.max) + qweight = qweight.to(torch.float8_e4m3fn) + return qweight + + +PER_TENSOR_QUANT_CASES = get_ci_test_range( + list( + itertools.product( + [38, 39, 128, 256, 512, 1392], + [512, 1536, 2048, 4096, 7168], + ) + ), + [(38, 7168), (39, 1536), (128, 512), (512, 4096), (1392, 1536)], +) + + +@pytest.mark.parametrize("num_tokens,hidden_dim", PER_TENSOR_QUANT_CASES) +def test_jit_per_tensor_quant_compare_implementations( + num_tokens: int, + hidden_dim: int, +): + device = torch.device("cuda") + x = torch.rand((num_tokens, hidden_dim), dtype=torch.float16, device=device) + + sglang_out, sglang_scale = sglang_scaled_fp8_quant(x) + torch_out = torch_scaled_fp8_quant(x, sglang_scale) + + torch.testing.assert_close( + sglang_out.float(), torch_out.float(), rtol=1e-3, atol=1e-3 + ) + + +@pytest.mark.parametrize("shape", [(4, 8, 64), (2, 16, 128), (19260817, 1, 1)]) +def test_jit_per_tensor_quant_supports_3d(shape): + device = torch.device("cuda") + x = torch.rand(shape, dtype=torch.bfloat16, device=device) + out = torch.empty_like(x, device=x.device, dtype=fp8_type_) + scale = torch.zeros(1, device=x.device, dtype=torch.float32) + + per_tensor_quant_fp8(x, out, scale, is_static=False) + + x_2d = x.flatten(0, -2) + out_ref_2d = torch_scaled_fp8_quant(x_2d, scale) + out_ref = out_ref_2d.reshape(shape) + + torch.testing.assert_close(out.float(), out_ref.float(), rtol=1e-3, atol=1e-3) + + scale = torch.rand(1, dtype=torch.float32, device=device) + sglang_out, _ = sglang_scaled_fp8_quant(x, scale) + torch_out = torch_scaled_fp8_quant(x, scale) + + torch.testing.assert_close( + sglang_out.float(), torch_out.float(), rtol=1e-3, atol=1e-3 + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_per_token_group_quant_8bit.py b/asian_ai/performance/SGLang/test/registered/jit/test_per_token_group_quant_8bit.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2f96a71669f9f1dde4c72064bfa0f2c1b1263f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_per_token_group_quant_8bit.py @@ -0,0 +1,228 @@ +import itertools +import sys + +import pytest +import torch + +from sglang.jit_kernel.per_token_group_quant_8bit import ( + per_token_group_quant_8bit as sglang_per_token_group_quant_8bit, +) +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.srt.utils import is_hip +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=16, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +if not torch.cuda.is_available(): + pytest.skip("CUDA required", allow_module_level=True) + +from sgl_kernel.test_utils import ( # noqa: E402 + assert_all_close_or_tiny_diff, + create_per_token_group_quant_test_data, +) + +from sglang.srt.layers.quantization.fp8_kernel import ( # noqa: E402 + create_per_token_group_quant_fp8_output_scale, +) +from sglang.srt.layers.quantization.fp8_kernel import ( # noqa: E402 + per_token_group_quant_8bit as triton_per_token_group_quant_8bit, +) + +_is_hip = is_hip() +fp8_type_ = torch.float8_e4m3fnuz if _is_hip else torch.float8_e4m3fn + +BASE_FLAGS = [ + dict( + column_major_scales=False, + scale_tma_aligned=False, + scale_ue8m0=False, + fuse_silu_and_mul=False, + masked_layout_mode=None, + ), + dict( + column_major_scales=True, + scale_tma_aligned=False, + scale_ue8m0=False, + fuse_silu_and_mul=False, + masked_layout_mode=None, + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=False, + fuse_silu_and_mul=False, + masked_layout_mode=None, + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=False, + masked_layout_mode=None, + ), +] +FUSED_FLAGS = [ + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=True, + masked_layout_mode=None, + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=True, + masked_layout_mode="balanced", + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=True, + masked_layout_mode="imbalanced", + ), + dict( + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=True, + fuse_silu_and_mul=True, + masked_layout_mode="extreme", + ), +] + +configs = get_ci_test_range( + list( + itertools.product( + [1, 4, 16, 17, 38, 51, 64, 127, 128, 512, 1024, 4096, 8192], + [128, 256, 384, 512, 768, 1024, 1536, 1664, 2048, 4096, 7168, 16384], + [16, 32, 64, 128], + [None], + [fp8_type_], + BASE_FLAGS, + ) + ) + + list( + itertools.product( + [1, 4, 1 * 8, 4 * 8, 64 * 8, 256 * 8, 768 * 8], + [2048], + [128], + [8, 16, 32, 48], + [fp8_type_], + FUSED_FLAGS, + ) + ), + [ + (1, 128, 128, None, fp8_type_, BASE_FLAGS[0]), + (17, 1536, 128, None, fp8_type_, BASE_FLAGS[2]), + (38, 4096, 128, None, fp8_type_, BASE_FLAGS[2]), + (51, 4096, 128, None, fp8_type_, BASE_FLAGS[2]), + (512, 2048, 128, 8, fp8_type_, FUSED_FLAGS[0]), + (2048, 2048, 128, 16, fp8_type_, FUSED_FLAGS[1]), + ], +) + + +@pytest.mark.parametrize( + "num_tokens, hidden_dim, group_size, num_ranks, dst_dtype, flags", configs +) +def test_per_token_group_quant_with_column_major( + num_tokens, + hidden_dim, + group_size, + num_ranks, + dst_dtype, + flags, +): + arch_major, _ = torch.cuda.get_device_capability(torch.cuda.current_device()) + if flags["scale_ue8m0"] and (arch_major <= 9): + pytest.skip("Only Blackwell need ue8m0 fusion") + return + + if (flags["scale_ue8m0"] and (group_size != 128)) or ( + (dst_dtype == torch.int8) and flags["column_major_scales"] + ): + pytest.skip() + return + + x, masked_m = create_per_token_group_quant_test_data( + num_tokens=num_tokens, hidden_dim=hidden_dim, num_ranks=num_ranks, flags=flags + ) + + execute_kwargs = dict( + x=x, + masked_m=masked_m, + group_size=group_size, + eps=1e-10, + dst_dtype=dst_dtype, + **{k: v for k, v in flags.items() if k not in ["masked_layout_mode"]}, + ) + + def _postprocess(x_q, x_s): + if masked_m is not None: + print(f"Mask tokens after {masked_m} to be zero") + for i in range(len(masked_m)): + x_q[i, masked_m[i] :, :] = 0 + x_s[i, masked_m[i] :, :] = 0 + return x_q, x_s + + x_q_triton, x_s_triton = _postprocess( + *triton_per_token_group_quant_8bit(**execute_kwargs) + ) + + fuse_silu_and_mul = False + out_shape = (*x.shape[:-1], x.shape[-1] // (2 if fuse_silu_and_mul else 1)) + + fp8_dtype = torch.float8_e4m3fn + fp8_max = torch.finfo(fp8_dtype).max + fp8_min = -fp8_max + x_q = torch.empty(out_shape, device=x.device, dtype=fp8_dtype) + x_s = create_per_token_group_quant_fp8_output_scale( + x_shape=out_shape, + device=x.device, + group_size=group_size, + column_major_scales=False, + scale_tma_aligned=False, + scale_ue8m0=False, + ) + + execute_kwargs = dict( + input=x, + output_q=x_q, + output_s=x_s, + group_size=group_size, + eps=1e-10, + fp8_max=fp8_max, + fp8_min=fp8_min, + ) + x_q_sglang, x_s_sglang = _postprocess( + *sglang_per_token_group_quant_8bit(**execute_kwargs) + ) + + try: + assert_all_close_or_tiny_diff(x_q_triton, x_q_sglang) + torch.testing.assert_close( + x_s_triton.contiguous(), + x_s_sglang.contiguous(), + rtol=1e-3, + atol=1e-5, + msg=lambda message: message + f" {x_s_triton=} {x_s_sglang=}", + ) + except AssertionError: + print( + f"{x.shape=} {x_q_triton.shape=} {x_s_triton.shape=} {x_q_sglang.shape=} {x_s_sglang.shape=}" + ) + print(f"{x=}") + print(f"{masked_m=}") + print(f"{x_q_triton=}") + print(f"{x_s_triton=}") + print(f"{x_q_sglang=}") + print(f"{x_s_sglang=}") + + raise + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_per_token_group_quant_8bit_v2.py b/asian_ai/performance/SGLang/test/registered/jit/test_per_token_group_quant_8bit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..5a3073af01afc816dde37d49b29e4d2c0fde91bc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_per_token_group_quant_8bit_v2.py @@ -0,0 +1,219 @@ +import itertools + +import pytest +import torch + +from sglang.jit_kernel.per_token_group_quant_8bit_v2 import ( + per_token_group_quant_8bit_v2, +) +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=90, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +try: + from sgl_kernel import sgl_per_token_group_quant_8bit # AOT v2 reference op +except ImportError: + sgl_per_token_group_quant_8bit = None + +if sgl_per_token_group_quant_8bit is None and not torch.cuda.is_available(): + pytest.skip("sgl_kernel AOT reference op is unavailable", allow_module_level=True) +if sgl_per_token_group_quant_8bit is None: + raise ImportError("sgl_kernel AOT reference op is unavailable") + +from sglang.srt.layers.quantization.fp8_kernel import ( # noqa: E402 + create_per_token_group_quant_fp8_output_scale, + fp8_dtype, + fp8_max, + fp8_min, + sglang_per_token_group_quant_fp8, +) + +G = 128 + + +def _alloc(x_shape, scale_ue8m0): + """Pre-allocated (zeroed) output_q + output_s for a given input/output shape. + Zeroing makes the unwritten (padding / aligned) regions compare equal.""" + x_q = torch.zeros(x_shape, device="cuda", dtype=fp8_dtype) + x_s = create_per_token_group_quant_fp8_output_scale( + x_shape=x_shape, + device="cuda", + group_size=G, + column_major_scales=True, + scale_tma_aligned=True, + scale_ue8m0=scale_ue8m0, + ) + x_s.zero_() + return x_q, x_s + + +V2_QUANT_CASES = get_ci_test_range( + list( + itertools.product( + [torch.bfloat16, torch.float16], + [1, 7, 38, 64, 333], + [128, 2048, 4096, 7168], + [False, True], + [False, True], + ) + ), + [ + (torch.bfloat16, 1, 128, False, False), + (torch.bfloat16, 17, 1536, False, False), + (torch.bfloat16, 38, 7168, False, True), + (torch.bfloat16, 38, 4096, False, True), + (torch.bfloat16, 64, 4096, True, True), + (torch.float16, 333, 2048, True, False), + ], +) + + +@pytest.mark.parametrize( + "dtype,num_tokens,hidden,fuse_silu_and_mul,scale_ue8m0", V2_QUANT_CASES +) +def test_v2_jit_matches_aot(dtype, num_tokens, hidden, fuse_silu_and_mul, scale_ue8m0): + """JIT v2 must be bit-exact with the AOT v2 across vanilla/silu and float/ue8m0 + scales (NaiveScheduler).""" + torch.manual_seed( + hidden + num_tokens + int(fuse_silu_and_mul) + 7 * int(scale_ue8m0) + ) + in_hidden = hidden * (2 if fuse_silu_and_mul else 1) + x = torch.randn(num_tokens, in_hidden, device="cuda", dtype=dtype) + out_shape = (num_tokens, hidden) + + q_ref, s_ref = _alloc(out_shape, scale_ue8m0) + sgl_per_token_group_quant_8bit( + x, + q_ref, + s_ref, + G, + 1e-10, + float(fp8_min), + float(fp8_max), + scale_ue8m0, + fuse_silu_and_mul, + None, + enable_v2=True, + ) + + x_q, x_s = _alloc(out_shape, scale_ue8m0) + per_token_group_quant_8bit_v2( + x, + x_q, + x_s, + G, + 1e-10, + float(fp8_min), + float(fp8_max), + scale_ue8m0=scale_ue8m0, + fuse_silu_and_mul=fuse_silu_and_mul, + ) + torch.cuda.synchronize() + + assert torch.equal(x_q.view(torch.int8), q_ref.view(torch.int8)), "fp8 codes differ" + assert torch.equal(x_s, s_ref), "scales differ" + + +ROW_MAJOR_UE8M0_CASES = get_ci_test_range( + list( + itertools.product( + [torch.bfloat16, torch.float16], [1, 33, 128], [128, 512, 4096, 7168] + ) + ), + [ + (torch.bfloat16, 1, 128), + (torch.bfloat16, 17, 1536), + (torch.bfloat16, 33, 7168), + (torch.bfloat16, 38, 4096), + (torch.float16, 128, 4096), + ], +) + + +@pytest.mark.parametrize("dtype,num_tokens,hidden", ROW_MAJOR_UE8M0_CASES) +def test_sglang_per_token_group_quant_fp8_row_major_ue8m0(dtype, num_tokens, hidden): + """Row-major scale_ue8m0=True quantizes WITH the rounded (power-of-2) scale. + Verify: (1) scales are exact powers of 2, (2) dequant ≈ original within FP8 tolerance. + """ + torch.manual_seed(num_tokens * 1000 + hidden) + x = torch.randn(num_tokens, hidden, device="cuda", dtype=dtype) + + x_q, x_s = sglang_per_token_group_quant_fp8(x, G, scale_ue8m0=True) + torch.cuda.synchronize() + + # Scales must be exact powers of 2 + log2_s = torch.log2(x_s.abs()) + assert torch.equal(log2_s, log2_s.round()), "scales are not power-of-2" + + # Dequant should approximate original within FP8 precision + x_deq = x_q.float().view(num_tokens, -1, G) * x_s.unsqueeze(-1) + x_deq = x_deq.view(num_tokens, hidden) + rel_err = (x.float() - x_deq).abs() / (x.float().abs() + 1e-6) + assert ( + rel_err.mean() < 0.05 + ), f"mean relative dequant error too large: {rel_err.mean():.4f}" + + +# Masked (EP-MoE) path: the v2 op only has a masked scheduler for the +# column-major + ue8m0 + fused-silu+mul + masked combination. Input is 3D +# [num_experts, tokens_padded, hidden*2]; only tokens < masked_m[e] are processed +# (padding left untouched → zeros in both). Compare JIT vs AOT bit-exact. +MASKED_V2_CASES = get_ci_test_range( + # MaskedLayoutScheduler requires hidden / group_size to be divisible by 16. + list(itertools.product([2, 5], [2048, 4096, 8192], [128, 384])), + [(2, 2048, 128), (5, 4096, 384), (2, 8192, 128)], +) + + +@pytest.mark.parametrize("num_experts,hidden,tokens_pad", MASKED_V2_CASES) +def test_v2_jit_masked_matches_aot(num_experts, hidden, tokens_pad): + torch.manual_seed(num_experts * 1000 + hidden + tokens_pad) + x = torch.randn( + num_experts, tokens_pad, hidden * 2, device="cuda", dtype=torch.bfloat16 + ) + masked_m = torch.randint( + 0, tokens_pad + 1, (num_experts,), device="cuda", dtype=torch.int32 + ) + out_shape = (num_experts, tokens_pad, hidden) + + q_ref, s_ref = _alloc(out_shape, scale_ue8m0=True) + sgl_per_token_group_quant_8bit( + x, + q_ref, + s_ref, + G, + 1e-10, + float(fp8_min), + float(fp8_max), + True, + True, + masked_m, + enable_v2=True, + ) + + x_q, x_s = _alloc(out_shape, scale_ue8m0=True) + per_token_group_quant_8bit_v2( + x, + x_q, + x_s, + G, + 1e-10, + float(fp8_min), + float(fp8_max), + scale_ue8m0=True, + fuse_silu_and_mul=True, + masked_m=masked_m, + ) + torch.cuda.synchronize() + + assert torch.equal( + x_q.view(torch.int8), q_ref.view(torch.int8) + ), "masked fp8 differ" + assert torch.equal(x_s, s_ref), "masked scales differ" + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_pos_enc.py b/asian_ai/performance/SGLang/test/registered/jit/test_pos_enc.py new file mode 100644 index 0000000000000000000000000000000000000000..f7ec78302aa35c5b19789e93a207adc0cda8d8b7 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_pos_enc.py @@ -0,0 +1,494 @@ +import sys +import time +from typing import Optional, Tuple, Union + +import pytest +import torch +import triton +import triton.language as tl + +from sglang.jit_kernel.rope import rotary_embedding +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=18, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +@triton.jit +def burn_kernel(out_ptr, iters: tl.constexpr): + pid = tl.program_id(0) + x = tl.full((), pid + 1, dtype=tl.uint32) + + a = tl.full((), 1664525, dtype=tl.uint32) + c = tl.full((), 1013904223, dtype=tl.uint32) + sh = tl.full((), 13, dtype=tl.uint32) + + for _ in range(iters): + x = x * a + c + x = x ^ (x >> sh) + + if pid == 0: + tl.store(out_ptr, x) + + +def triton_burn(ms: float, grid=(256,)): + iters = int(ms * 20000) + out = torch.empty((), device="cuda", dtype=torch.uint32) + burn_kernel[grid](out, iters=iters) + return out + + +def create_test_inputs( + head_size, batch_size, seq_len, device, dtype, num_q_heads, num_kv_heads +): + """Create test inputs.""" + total_tokens = batch_size * seq_len + + query = torch.randn( + batch_size, seq_len, num_q_heads, head_size, dtype=dtype, device=device + ) + key = torch.randn( + batch_size, seq_len, num_kv_heads, head_size, dtype=dtype, device=device + ) + + pos_ids = torch.randint( + 0, min(seq_len * 2, 100), (total_tokens,), dtype=torch.long, device=device + ) + + query = query.view(total_tokens, num_q_heads, head_size) + key = key.view(total_tokens, num_kv_heads, head_size) + + return query, key, pos_ids + + +def create_cos_sin_cache(rotary_dim, max_position_embeddings, base, dtype, device): + """Create cos/sin cache for rotary embedding.""" + max_pos = max_position_embeddings + extended_max_pos = max(max_pos, 100) + cos_sin_cache = torch.zeros( + extended_max_pos, rotary_dim, dtype=dtype, device=device + ) + + inv_freq = 1.0 / ( + base + ** ( + torch.arange(0, rotary_dim, 2, dtype=torch.float32, device=device) + / rotary_dim + ) + ) + t = torch.arange(extended_max_pos, dtype=torch.float32, device=device) + freqs = torch.outer(t, inv_freq) + cos_cache = torch.cos(freqs).to(dtype) + sin_cache = torch.sin(freqs).to(dtype) + + cos_sin_cache[:, : rotary_dim // 2] = cos_cache + cos_sin_cache[:, rotary_dim // 2 :] = sin_cache + + return cos_sin_cache + + +# vLLM torch native +def _apply_rotary_emb( + x: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + is_neox_style: bool, +) -> torch.Tensor: + """ + Args: + x: [num_tokens, num_heads, head_size] + cos: [num_tokens, head_size // 2] + sin: [num_tokens, head_size // 2] + is_neox_style: Whether to use the Neox-style or GPT-J-style rotary + positional embeddings. + """ + cos = cos.unsqueeze(-2).to(x.dtype) + sin = sin.unsqueeze(-2).to(x.dtype) + if is_neox_style: + x1, x2 = torch.chunk(x, 2, dim=-1) + else: + x1 = x[..., ::2] + x2 = x[..., 1::2] + o1 = x1 * cos - x2 * sin + o2 = x2 * cos + x1 * sin + if is_neox_style: + return torch.cat((o1, o2), dim=-1) + else: + return torch.stack((o1, o2), dim=-1).flatten(-2) + + +class RotaryEmbedding(torch.nn.Module): + # Reference: https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/rotary_embedding.py + def __init__( + self, + head_size: int, + rotary_dim: int, + max_position_embeddings: int, + base: int, + is_neox_style: bool, + dtype: torch.dtype, + ) -> None: + super().__init__() + self.head_size = head_size + self.rotary_dim = rotary_dim + self.max_position_embeddings = max_position_embeddings + self.base = base + self.is_neox_style = is_neox_style + self.dtype = dtype + + cache = self._compute_cos_sin_cache() + self.cos_sin_cache: torch.Tensor + self.register_buffer("cos_sin_cache", cache, persistent=False) + + def _compute_inv_freq(self, base: Union[int, float]) -> torch.Tensor: + inv_freq = 1.0 / ( + base + ** ( + torch.arange(0, self.rotary_dim, 2, dtype=torch.float) / self.rotary_dim + ) + ) + return inv_freq + + def _compute_cos_sin_cache(self) -> torch.Tensor: + """Compute the cos and sin cache.""" + inv_freq = self._compute_inv_freq(self.base) + t = torch.arange(self.max_position_embeddings, dtype=torch.float) + + freqs = torch.einsum("i,j -> ij", t, inv_freq) + cos = freqs.cos() + sin = freqs.sin() + cache = torch.cat((cos, sin), dim=-1) + return cache + + def forward_native( + self, + positions: torch.Tensor, + query: torch.Tensor, + key: Optional[torch.Tensor] = None, + offsets: Optional[torch.Tensor] = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """A PyTorch-native implementation of forward().""" + + if offsets is not None: + positions = positions + offsets + + positions = positions.flatten() + num_tokens = positions.shape[0] + cos_sin = self.cos_sin_cache.index_select(0, positions) + + cos, sin = cos_sin.chunk(2, dim=-1) + + query_shape = query.shape + query = query.view(num_tokens, -1, self.head_size) + query_rot = query[..., : self.rotary_dim] + query_pass = query[..., self.rotary_dim :] + query_rot = _apply_rotary_emb(query_rot, cos, sin, self.is_neox_style) + query = torch.cat((query_rot, query_pass), dim=-1).reshape(query_shape) + + # Modification: convert to the correct dtype + query = query.to(self.dtype) + + if key is not None: + key_shape = key.shape + key = key.view(num_tokens, -1, self.head_size) + key_rot = key[..., : self.rotary_dim] + key_pass = key[..., self.rotary_dim :] + key_rot = _apply_rotary_emb(key_rot, cos, sin, self.is_neox_style) + key = torch.cat((key_rot, key_pass), dim=-1).reshape(key_shape) + + key = key.to(self.dtype) + + return query, key + + +def get_torch_rotary_embedding( + head_size, rotary_dim, max_position_embeddings, base, is_neox_style, dtype, device +): + """Initialize Torch Native RotaryEmbedding based on vLLM implementation.""" + return RotaryEmbedding( + head_size=head_size, + rotary_dim=rotary_dim, + max_position_embeddings=max_position_embeddings, + base=base, + is_neox_style=is_neox_style, + dtype=dtype, + ).to(device) + + +def get_sgl_rotary_embedding( + head_size, rotary_dim, max_position_embeddings, base, is_neox_style, dtype, device +): + """Initialize SglKernelRotaryEmbedding.""" + try: + from sgl_kernel.testing.rotary_embedding import SglKernelRotaryEmbedding + except ImportError: + pytest.skip( + "SglKernelRotaryEmbedding is not available. Test case can be removed." + ) + + return SglKernelRotaryEmbedding( + head_size=head_size, + rotary_dim=rotary_dim, + max_position_embeddings=max_position_embeddings, + base=base, + is_neox_style=is_neox_style, + dtype=dtype, + ).to(device) + + +def compare_results(jit_out, sgl_out, dtype): + """Compare results between JIT and SGL implementations.""" + if jit_out is None: + assert sgl_out is None + return + + assert sgl_out is not None + + # Check for NaN values + assert not torch.isnan(jit_out).any(), "NaN in JIT results" + assert not torch.isnan(sgl_out).any(), "NaN in SGL results" + + # Compare results + atol = 4e-2 if dtype != torch.float32 else 1e-5 + rtol = 4e-2 if dtype != torch.float32 else 1e-5 + + torch.testing.assert_close(jit_out, sgl_out, atol=atol, rtol=rtol) + + +@pytest.mark.parametrize( + "head_size, rotary_dim, max_position_embeddings, base, is_neox_style, dtype, device, batch_size, seq_len, num_q_heads, num_kv_heads", + [ + # GPT-OSS cases + *[ + (64, 64, 4096, 8000, True, torch.bfloat16, "cuda", bs, sl, 8, 8) + for bs, sl in [(1, 1), (32, 1), (128, 1), (512, 1), (2, 512), (4, 4096)] + ], + # Other cases + (64, 64, 32, 8000, True, torch.bfloat16, "cuda", 32, 32, 1, 1), + (256, 128, 4096, 10000, True, torch.bfloat16, "cuda", 2, 512, 4, 2), + (512, 128, 311, 10000, True, torch.bfloat16, "cuda", 3, 39, 4, 2), + (128, 128, 2048, 10000, False, torch.bfloat16, "cuda", 2, 512, 32, 8), + (128, 128, 2048, 10000, False, torch.bfloat16, "cuda", 2, 512, 16, 4), + (512, 128, 311, 10000, False, torch.bfloat16, "cuda", 3, 39, 4, 2), + (64, 64, 32, 8000, True, torch.float32, "cuda", 32, 32, 1, 1), + (256, 128, 4096, 10000, True, torch.float32, "cuda", 2, 512, 4, 2), + (512, 128, 311, 10000, True, torch.float32, "cuda", 3, 39, 4, 2), + (128, 128, 2048, 10000, False, torch.float32, "cuda", 2, 512, 32, 8), + (128, 128, 2048, 10000, False, torch.float32, "cuda", 2, 512, 16, 4), + (512, 128, 311, 10000, False, torch.float32, "cuda", 3, 39, 4, 2), + # Additional test cases for different head sizes and dtypes + (64, 32, 1024, 10000, True, torch.float16, "cuda", 16, 64, 8, 4), + (128, 64, 2048, 10000, True, torch.float16, "cuda", 8, 128, 16, 8), + (256, 128, 4096, 10000, True, torch.float16, "cuda", 4, 256, 8, 4), + ], +) +@pytest.mark.parametrize( + "key_is_none", + [True, False], +) +def test_correctness( + head_size, + rotary_dim, + max_position_embeddings, + base, + is_neox_style, + dtype, + device, + batch_size, + seq_len, + num_q_heads, + num_kv_heads, + key_is_none, +): + """Test correctness of JIT rotary embedding implementation.""" + # Create inputs and caches + query, key, pos_ids = create_test_inputs( + head_size, batch_size, seq_len, device, dtype, num_q_heads, num_kv_heads + ) + cos_sin_cache = create_cos_sin_cache( + rotary_dim, max_position_embeddings, base, dtype, device + ) + + # Initialize torch kernel + torch_rotary_emb = get_torch_rotary_embedding( + head_size, + rotary_dim, + max_position_embeddings, + base, + is_neox_style, + dtype, + device, + ) + torch_rotary_emb.cos_sin_cache = cos_sin_cache + r = torch.randn_like(query) + + # Apply rotary embeddings + query_jit, key_jit = query.clone(), key.clone() + query_torch, key_torch = query.clone(), key.clone() + stream_jit = torch.get_device_module("cuda").Stream() + stream_kernel = torch.get_device_module("cuda").Stream() + + if key_is_none: + key_jit = None + key_torch = None + triton_burn(100.0, grid=(1024,)) + + r_jit, r_torch = r.clone(), r.clone() + torch.cuda.synchronize() + + with torch.cuda.stream(stream_jit): + # Test if rotary_embedding runs on stream_jit + triton_burn(100.0, grid=(1024,)) + query_jit = query_jit + r_jit + query_jit_out, key_jit_out = rotary_embedding( + positions=pos_ids, + query=query_jit, + key=key_jit, + head_size=head_size, + cos_sin_cache=cos_sin_cache, + is_neox=is_neox_style, + ) + + with torch.cuda.stream(stream_kernel): + triton_burn(100.0, grid=(1024,)) + query_torch = query_torch + r_torch + query_torch_out, key_torch_out = torch_rotary_emb.forward_native( + positions=pos_ids, query=query_torch, key=key_torch + ) + + torch.cuda.synchronize() + compare_results(query_jit_out, query_torch_out, dtype) + compare_results(key_jit_out, key_torch_out, dtype) + + +@pytest.mark.parametrize( + "head_size, rotary_dim, max_position_embeddings, base, is_neox_style, dtype, device, batch_size, seq_len, num_q_heads, num_kv_heads", + [ + # Small scale + (64, 64, 4096, 8000, True, torch.bfloat16, "cuda", 1, 1, 8, 8), + (64, 64, 4096, 8000, True, torch.bfloat16, "cuda", 4, 16, 8, 8), + # Medium scale + (64, 64, 4096, 8000, True, torch.bfloat16, "cuda", 8, 64, 8, 8), + (64, 64, 4096, 8000, True, torch.bfloat16, "cuda", 16, 128, 8, 8), + # Large scale + (64, 64, 4096, 8000, True, torch.bfloat16, "cuda", 32, 512, 8, 8), + (64, 64, 4096, 8000, True, torch.bfloat16, "cuda", 64, 1024, 8, 8), + ], +) +def test_performance( + head_size: int, + rotary_dim: int, + max_position_embeddings: int, + base: int, + is_neox_style, + dtype, + device, + batch_size, + seq_len, + num_q_heads, + num_kv_heads, +): + """Performance test comparing JIT and SGL implementations with accuracy validation.""" + # Create inputs and caches + query, key, pos_ids = create_test_inputs( + head_size, batch_size, seq_len, device, dtype, num_q_heads, num_kv_heads + ) + cos_sin_cache = create_cos_sin_cache( + rotary_dim, max_position_embeddings, base, dtype, device + ) + + # Initialize SGL kernel + sgl_rotary_emb = get_sgl_rotary_embedding( + head_size, + rotary_dim, + max_position_embeddings, + base, + is_neox_style, + dtype, + device, + ) + sgl_rotary_emb.cos_sin_cache = cos_sin_cache + + warmup = 3 + + # Warmup runs + for _ in range(warmup): + query_warm, key_warm = query.clone(), key.clone() + rotary_embedding( + positions=pos_ids, + query=query_warm, + key=key_warm, + head_size=head_size, + cos_sin_cache=cos_sin_cache, + is_neox=is_neox_style, + ) + + query_sgl_warm, key_sgl_warm = query.clone(), key.clone() + sgl_rotary_emb.forward_cuda( + positions=pos_ids, query=query_sgl_warm, key=key_sgl_warm + ) + + iteration = 100 + + # Time JIT implementation + torch.cuda.synchronize() + start_time = time.time() + for _ in range(iteration): + query_jit, key_jit = query.clone(), key.clone() + rotary_embedding( + positions=pos_ids, + query=query_jit, + key=key_jit, + head_size=head_size, + cos_sin_cache=cos_sin_cache, + is_neox=is_neox_style, + ) + torch.cuda.synchronize() + jit_time = (time.time() - start_time) / iteration + + # Time SGL implementation + torch.cuda.synchronize() + start_time = time.time() + for _ in range(iteration): + query_sgl, key_sgl = query.clone(), key.clone() + sgl_rotary_emb.forward_cuda(positions=pos_ids, query=query_sgl, key=key_sgl) + torch.cuda.synchronize() + sgl_time = (time.time() - start_time) / iteration + + # Accuracy validation during performance test + # Run one more time to get outputs for comparison + query_jit_final, key_jit_final = query.clone(), key.clone() + query_sgl_final, key_sgl_final = query.clone(), key.clone() + + query_jit_out, key_jit_out = rotary_embedding( + positions=pos_ids, + query=query_jit_final, + key=key_jit_final, + head_size=head_size, + cos_sin_cache=cos_sin_cache, + is_neox=is_neox_style, + ) + + query_sgl_out, key_sgl_out = sgl_rotary_emb.forward_cuda( + positions=pos_ids, query=query_sgl_final, key=key_sgl_final + ) + + # Validate accuracy + compare_results(query_jit_out, query_sgl_out, dtype) + compare_results(key_jit_out, key_sgl_out, dtype) + + # Print results + total_tokens = batch_size * seq_len + print( + f"\nPerformance Test - Batch={batch_size}, SeqLen={seq_len}, Tokens={total_tokens}" + ) + print(f"JIT: {jit_time*1000:.9f}ms, SGL: {sgl_time*1000:.9f}ms") + if sgl_time > 0: + speedup = sgl_time / jit_time if jit_time > 0 else float("inf") + print(f"Speedup (SGL/JIT): {speedup:.2f}x") + + assert jit_time >= 0 and sgl_time >= 0 + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_qknorm.py b/asian_ai/performance/SGLang/test/registered/jit/test_qknorm.py new file mode 100644 index 0000000000000000000000000000000000000000..efd56c88a6d8f0fc584feeac488473f080af91a0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_qknorm.py @@ -0,0 +1,101 @@ +import itertools +import sys + +import pytest +import torch +import triton + +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=37, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=148, suite="nightly-kernel-1-gpu", nightly=True) + + +def sglang_aot_qknorm( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, +) -> None: + from sgl_kernel import rmsnorm + + head_dim = q.shape[-1] + q = q.view(-1, head_dim) + k = k.view(-1, head_dim) + rmsnorm(q, q_weight, out=q) + rmsnorm(k, k_weight, out=k) + + +def sglang_jit_qknorm( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, +) -> None: + from sglang.jit_kernel.norm import fused_inplace_qknorm + + fused_inplace_qknorm(q, k, q_weight, k_weight) + + +def flashinfer_qknorm( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, +) -> None: + from flashinfer.norm import rmsnorm + + rmsnorm(q, q_weight, out=q) + rmsnorm(k, k_weight, out=k) + + +@torch.compile() +def torch_impl_qknorm( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + eps: float = 1e-6, +) -> None: + q_mean = q.float().pow(2).mean(dim=-1, keepdim=True) + k_mean = k.float().pow(2).mean(dim=-1, keepdim=True) + q_norm = (q_mean + eps).rsqrt() + k_norm = (k_mean + eps).rsqrt() + q.copy_(q.float() * q_norm * q_weight.float()) + k.copy_(k.float() * k_norm * k_weight.float()) + + +BS_LIST = [2**n for n in range(0, 14)] +BS_LIST += [x + 1 + i for i, x in enumerate(BS_LIST)] +BS_LIST = get_ci_test_range(BS_LIST, [1, 9, 256, 4109]) +N_K_LIST = get_ci_test_range([2, 4], [2, 4]) +N_Q_LIST = get_ci_test_range([8, 16], [8, 16]) +HEAD_DIM_LIST = get_ci_test_range([64, 128, 256, 512, 1024], [64, 256, 1024]) +DEVICE = "cuda" +DTYPE = torch.bfloat16 + +# NOTE(dark): sgl_kernel use flashinfer template, which is bitwise identical to flashinfer impl. +# However, sgl-jit-kernel, flashinfer, torch_impl, may have small numerical differences. +# so we allow a small rel/abs tolerance in correctness test. + + +@pytest.mark.parametrize( + "batch_size,n_k,n_q,head_dim", + list(itertools.product(BS_LIST, N_K_LIST, N_Q_LIST, HEAD_DIM_LIST)), +) +def test_qknorm(batch_size: int, n_k: int, n_q: int, head_dim: int) -> None: + q = torch.randn(batch_size, n_q, head_dim, device=DEVICE, dtype=DTYPE) + k = torch.randn(batch_size, n_k, head_dim, device=DEVICE, dtype=DTYPE) + q_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + k_weight = torch.randn(head_dim, device=DEVICE, dtype=DTYPE) + q_k_aot = (q.clone(), k.clone()) + q_k_jit = (q.clone(), k.clone()) + sglang_aot_qknorm(q_k_aot[0], q_k_aot[1], q_weight, k_weight) + sglang_jit_qknorm(q_k_jit[0], q_k_jit[1], q_weight, k_weight) + triton.testing.assert_close(q_k_aot[0], q_k_jit[0], atol=1e-2, rtol=1e-2) + triton.testing.assert_close(q_k_aot[1], q_k_jit[1], atol=1e-2, rtol=1e-2) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_qknorm_across_heads.py b/asian_ai/performance/SGLang/test/registered/jit/test_qknorm_across_heads.py new file mode 100644 index 0000000000000000000000000000000000000000..c216470e270e59ab89b7353a0d789f0fa4ced6ce --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_qknorm_across_heads.py @@ -0,0 +1,83 @@ +import itertools +import sys + +import pytest +import torch +import triton + +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=15, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +def sglang_jit_qknorm_across_heads( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, +) -> None: + from sglang.jit_kernel.norm import fused_inplace_qknorm_across_heads + + fused_inplace_qknorm_across_heads(q, k, q_weight, k_weight) + + +def sglang_aot_qknorm_across_heads( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, +) -> None: + from sgl_kernel import rmsnorm + + rmsnorm(q, q_weight, out=q) + rmsnorm(k, k_weight, out=k) + + +@torch.compile() +def torch_impl_qknorm_across_heads( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + eps: float = 1e-6, +) -> None: + q_mean = q.float().pow(2).mean(dim=-1, keepdim=True) + k_mean = k.float().pow(2).mean(dim=-1, keepdim=True) + q_norm = (q_mean + eps).rsqrt() + k_norm = (k_mean + eps).rsqrt() + q.copy_(q.float() * q_norm * q_weight.float()) + k.copy_(k.float() * k_norm * k_weight.float()) + + +BS_LIST = [2**n for n in range(0, 14)] +BS_LIST += [x + 1 + i for i, x in enumerate(BS_LIST)] +BS_LIST = get_ci_test_range(BS_LIST, [1, 9, 256, 4109]) +HIDDEN_DIM_LIST = get_ci_test_range([512, 1024, 2048, 4096], [512, 2048, 4096]) +DEVICE = "cuda" +DTYPE = torch.bfloat16 + + +@pytest.mark.parametrize( + "batch_size,hidden_dim", + list(itertools.product(BS_LIST, HIDDEN_DIM_LIST)), +) +def test_qknorm_across_heads(batch_size: int, hidden_dim: int) -> None: + q = torch.randn(batch_size, hidden_dim, device=DEVICE, dtype=DTYPE) + k = torch.randn(batch_size, hidden_dim, device=DEVICE, dtype=DTYPE) + q_weight = torch.randn(hidden_dim, device=DEVICE, dtype=DTYPE) + k_weight = torch.randn(hidden_dim, device=DEVICE, dtype=DTYPE) + + q_k_jit = (q.clone(), k.clone()) + q_k_aot = (q.clone(), k.clone()) + + sglang_jit_qknorm_across_heads(q_k_jit[0], q_k_jit[1], q_weight, k_weight) + sglang_aot_qknorm_across_heads(q_k_aot[0], q_k_aot[1], q_weight, k_weight) + + triton.testing.assert_close(q_k_jit[0], q_k_aot[0], atol=1e-2, rtol=1e-2) + triton.testing.assert_close(q_k_jit[1], q_k_aot[1], atol=1e-2, rtol=1e-2) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_renorm.py b/asian_ai/performance/SGLang/test/registered/jit/test_renorm.py new file mode 100644 index 0000000000000000000000000000000000000000..21565b585f4dac232f3ee4e6095942480fa562a9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_renorm.py @@ -0,0 +1,86 @@ +# Adapted from https://github.com/flashinfer-ai/flashinfer/blob/main/tests/test_sampling.py +# and /sgl-workspace/sglang/sgl-kernel/tests/test_sampling.py + +import sys + +import pytest +import sgl_kernel +import torch + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=6, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + + +@pytest.mark.parametrize("batch_size", [1, 99, 989]) +@pytest.mark.parametrize("vocab_size", [111, 32000, 128256]) +@pytest.mark.parametrize("k", [10, 100, 500]) +def test_top_k_renorm_probs(batch_size, vocab_size, k): + """Test top_k_renorm_probs kernel for correctness. + + This test validates that the kernel correctly: + 1. Identifies the top-k probabilities + 2. Masks out non-top-k values + 3. Renormalizes the remaining probabilities to sum to 1 + """ + if k > vocab_size: + pytest.skip("k should be less than vocab_size") + torch.manual_seed(42) + pre_norm_prob = torch.rand(batch_size, vocab_size, device="cuda:0") + normalized_prob = pre_norm_prob / pre_norm_prob.sum(dim=-1, keepdim=True) + sorted_prob, _ = torch.sort(normalized_prob, descending=True) + pivot = sorted_prob[:, k - 1] + mask = (normalized_prob >= pivot.unsqueeze(-1)).int() + renorm_prob_ground_truth = normalized_prob.clone() + renorm_prob_ground_truth[mask == 0] = 0 + renorm_prob_ground_truth = renorm_prob_ground_truth / renorm_prob_ground_truth.sum( + dim=-1, keepdim=True + ) + + renorm_prob = sgl_kernel.top_k_renorm_prob(normalized_prob, k) + for i in range(batch_size): + torch.testing.assert_close( + renorm_prob_ground_truth[i], + renorm_prob[i], + rtol=1e-3, + atol=1e-3, + ) + + +@pytest.mark.parametrize("batch_size", [1, 99, 989]) +@pytest.mark.parametrize("vocab_size", [111, 32000, 128256]) +@pytest.mark.parametrize("p", [0.1, 0.5, 0.9]) +def test_top_p_renorm_probs(batch_size, vocab_size, p): + """Test top_p_renorm_probs kernel for correctness. + + This test validates that the kernel correctly: + 1. Computes the cumulative probability distribution + 2. Identifies tokens in the top-p threshold + 3. Masks out tokens outside the threshold + 4. Renormalizes the remaining probabilities to sum to 1 + """ + torch.manual_seed(42) + pre_norm_prob = torch.rand(batch_size, vocab_size, device="cuda:0") + normalized_prob = pre_norm_prob / pre_norm_prob.sum(dim=-1, keepdim=True) + sorted_prob, indices = torch.sort(normalized_prob, descending=False) + cdf = torch.cumsum(sorted_prob, dim=-1) + mask = torch.zeros(batch_size, vocab_size, dtype=torch.int32, device="cuda:0") + mask.scatter_add_(1, indices, (cdf >= (1 - p)).int()) + renorm_prob_ground_truth = normalized_prob.clone() + renorm_prob_ground_truth[mask == 0] = 0 + renorm_prob_ground_truth = renorm_prob_ground_truth / renorm_prob_ground_truth.sum( + dim=-1, keepdim=True + ) + + renorm_prob = sgl_kernel.top_p_renorm_prob(normalized_prob, p) + torch.testing.assert_close( + renorm_prob_ground_truth, + renorm_prob, + rtol=1e-3, + atol=1e-3, + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_resolve_future_token_ids.py b/asian_ai/performance/SGLang/test/registered/jit/test_resolve_future_token_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..9b3a1830787fc59f5bfe926867b427e91a632832 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_resolve_future_token_ids.py @@ -0,0 +1,70 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.resolve_future_token_ids import resolve_future_token_ids_cuda +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=9, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=9, stage="jit-kernel-unit", runner_config="amd") + + +def _reference_resolve(input_ids, future_map): + """Reference implementation using plain torch.""" + result = input_ids.clone() + result[:] = torch.where( + result < 0, + future_map[torch.clamp(-result, min=0)], + result, + ) + return result + + +@pytest.mark.parametrize("size", [1, 2, 127, 128, 255, 256, 1024, 4097]) +@pytest.mark.parametrize("dtype", [torch.int32, torch.int64]) +class TestResolveFutureTokenIds: + def test_all_negative(self, size: int, dtype: torch.dtype) -> None: + map_size = 8192 + future_map = torch.randint(0, 50000, (map_size,), dtype=dtype, device="cuda") + # Negative indices in range [-map_size+1, -1] + input_ids = -torch.randint(1, map_size, (size,), dtype=dtype, device="cuda") + + expected = _reference_resolve(input_ids, future_map) + resolve_future_token_ids_cuda(input_ids, future_map) + assert torch.equal(input_ids, expected) + + def test_all_non_negative(self, size: int, dtype: torch.dtype) -> None: + map_size = 16 + future_map = torch.randint(0, 50000, (map_size,), dtype=dtype, device="cuda") + input_ids = torch.randint(0, 50000, (size,), dtype=dtype, device="cuda") + + expected = input_ids.clone() + resolve_future_token_ids_cuda(input_ids, future_map) + assert torch.equal(input_ids, expected) + + def test_mixed(self, size: int, dtype: torch.dtype) -> None: + map_size = 8192 + future_map = torch.randint(0, 50000, (map_size,), dtype=dtype, device="cuda") + # Mix of negative and non-negative + input_ids = torch.randint( + -map_size + 1, 50000, (size,), dtype=dtype, device="cuda" + ) + + expected = _reference_resolve(input_ids, future_map) + resolve_future_token_ids_cuda(input_ids, future_map) + assert torch.equal(input_ids, expected) + + def test_zeros(self, size: int, dtype: torch.dtype) -> None: + map_size = 16 + future_map = torch.randint(0, 50000, (map_size,), dtype=dtype, device="cuda") + input_ids = torch.zeros(size, dtype=dtype, device="cuda") + + expected = input_ids.clone() + resolve_future_token_ids_cuda(input_ids, future_map) + assert torch.equal(input_ids, expected) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_rmsnorm.py b/asian_ai/performance/SGLang/test/registered/jit/test_rmsnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..9b1c444df5e5fce2364a8f9a748352d1f5d0e384 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_rmsnorm.py @@ -0,0 +1,127 @@ +import itertools +import sys + +import pytest +import torch + +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=240, suite="nightly-kernel-1-gpu", nightly=True) + + +EPS = 1e-6 +DEVICE = "cuda" +DTYPES = [torch.float16, torch.bfloat16] + + +def sglang_jit_rmsnorm( + input: torch.Tensor, + weight: torch.Tensor, + *, + output: torch.Tensor | None = None, + eps: float = EPS, +) -> None: + from sglang.jit_kernel.norm import rmsnorm + + rmsnorm(input, weight, out=output, eps=eps) + + +def flashinfer_rmsnorm( + input: torch.Tensor, + weight: torch.Tensor, + *, + output: torch.Tensor, + eps: float = EPS, +) -> None: + from flashinfer.norm import rmsnorm + + rmsnorm(input, weight, out=output, eps=eps) + + +BS_LIST = [2**n for n in range(0, 14)] +BS_LIST += [x + 1 + i for i, x in enumerate(BS_LIST)] +SUPPORTED_HIDDEN_SIZE_LIST = [ + 64, + 128, + 256, + 512, + *range(1024, 8192 + 1, 1024), + 1536, + 2304, + 2560, + 8704, + 12288, + 16384, +] +RMSNORM_CASES = get_ci_test_range( + list(itertools.product(BS_LIST, SUPPORTED_HIDDEN_SIZE_LIST)), + [ + (1, 256), + (18, 1024), + (38, 4096), + (1240, 1536), + (2500, 1024), + (4109, 1024), + (7807, 128), + ], +) + + +@pytest.mark.parametrize( + "batch_size,hidden_size", + RMSNORM_CASES, +) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("specify_out", [True, False]) +def test_rmsnorm( + batch_size: int, hidden_size: int, dtype: torch.dtype, specify_out: bool +) -> None: + input = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=dtype) + weight = torch.randn(hidden_size, device=DEVICE, dtype=dtype) + + input_flashinfer = input.clone() + output_flashinfer = torch.empty_like(input) + flashinfer_rmsnorm(input_flashinfer, weight, output=output_flashinfer) + + if specify_out: + output_sglang = torch.empty_like(input) + sglang_jit_rmsnorm(input, weight, output=output_sglang) + else: + output_sglang = input.clone() + sglang_jit_rmsnorm(output_sglang, weight, output=output_sglang) + + torch.testing.assert_close(output_sglang, output_flashinfer, atol=1e-2, rtol=1e-2) + + +@pytest.mark.parametrize("hidden_size", [64, 128, 256, 512, 8192, 8704, 16384]) +def test_rmsnorm_hidden_size_support(hidden_size: int) -> None: + from sglang.jit_kernel.norm import _is_supported_rmsnorm_hidden_size + + assert _is_supported_rmsnorm_hidden_size(hidden_size) + + +@pytest.mark.parametrize( + ("hidden_size", "expected"), + [ + (64, "RMSNormWarpKernel"), + (128, "RMSNormWarpKernel"), + (256, "RMSNormWarpKernel"), + (512, "RMSNormHalfKernel"), + (1536, "RMSNormKernel"), + (2048, "RMSNormHalfKernel"), + (2304, "RMSNormKernel"), # NOTE: not 512 aligned + (8192, "RMSNormHalfKernel"), + (8704, "RMSNormHalfKernel"), + (16384, "RMSNormHalfKernel"), + ], +) +def test_rmsnorm_kernel_dispatch(hidden_size: int, expected: str) -> None: + from sglang.jit_kernel.norm import _rmsnorm_kernel_class + + assert _rmsnorm_kernel_class(hidden_size) == expected + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_rmsnorm_hf.py b/asian_ai/performance/SGLang/test/registered/jit/test_rmsnorm_hf.py new file mode 100644 index 0000000000000000000000000000000000000000..cbd7375c9c95548e00d690f81ac987b707d8e48f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_rmsnorm_hf.py @@ -0,0 +1,137 @@ +"""Tests for the JIT rmsnorm_hf kernel (HF LlamaRMSNorm semantics).""" + +import itertools +import sys + +import pytest +import torch + +from sglang.jit_kernel.rmsnorm_hf import ( + is_supported_rmsnorm_hf_hidden_size, + rmsnorm_hf, +) +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=30, stage="jit-kernel-unit", runner_config="amd") + +EPS = 1e-5 +DEVICE = "cuda" +DTYPES = [torch.float16, torch.bfloat16] + + +def hf_rmsnorm_reference(x: torch.Tensor, w: torch.Tensor, eps: float) -> torch.Tensor: + """HF LlamaRMSNorm: normalize fp32, cast normalized x to dtype, then multiply weight.""" + x_fp32 = x.to(torch.float32) + variance = x_fp32.pow(2).mean(-1, keepdim=True) + x_normed = x_fp32 * torch.rsqrt(variance + eps) + return w * x_normed.to(x.dtype) + + +def sgl_rmsnorm_reference(x: torch.Tensor, w: torch.Tensor, eps: float) -> torch.Tensor: + """Old sgl_kernel.rmsnorm semantics — weight multiply in fp32, cast at the end.""" + x_fp32 = x.to(torch.float32) + variance = x_fp32.pow(2).mean(-1, keepdim=True) + x_normed = x_fp32 * torch.rsqrt(variance + eps) + return (x_normed * w.to(torch.float32)).to(x.dtype) + + +BS_LIST = get_ci_test_range( + [1, 2, 4, 7, 16, 64, 128, 512, 1024, 4096], + [1, 16, 1024], +) +HIDDEN_SIZE_LIST = get_ci_test_range( + # Warp-kernel shapes (q/k RMSNorm head dims) + CTA-kernel shapes. + [32, 64, 96, 128, 256, 512, 1024, 2048, 3072, 4096, 8192, 16384], + [128, 512, 4096, 16384], +) + + +@pytest.mark.parametrize( + "batch_size,hidden_size", + list(itertools.product(BS_LIST, HIDDEN_SIZE_LIST)), +) +@pytest.mark.parametrize("dtype", DTYPES) +def test_rmsnorm_hf_correctness( + batch_size: int, hidden_size: int, dtype: torch.dtype +) -> None: + torch.manual_seed(0) + x = torch.randn(batch_size, hidden_size, device=DEVICE, dtype=dtype) + w = torch.randn(hidden_size, device=DEVICE, dtype=dtype) + out = rmsnorm_hf(x, w, EPS) + ref = hf_rmsnorm_reference(x, w, EPS) + # Loose atol — the kernel's block-reduce order differs from PyTorch's + # `mean`, producing ~1 fp16 ULP of drift on some shapes. + # The SGL-semantics regression guard below is what catches the cast-order + # bug this PR fixes; it's reduction-order-invariant. + torch.testing.assert_close(out, ref, atol=1e-2, rtol=1e-2) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_rmsnorm_hf_out_param(dtype: torch.dtype) -> None: + torch.manual_seed(0) + x = torch.randn(8, 4096, device=DEVICE, dtype=dtype) + w = torch.randn(4096, device=DEVICE, dtype=dtype) + out = torch.empty_like(x) + result = rmsnorm_hf(x, w, EPS, out=out) + assert result.data_ptr() == out.data_ptr() + torch.testing.assert_close( + out, hf_rmsnorm_reference(x, w, EPS), atol=1e-2, rtol=1e-2 + ) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_rmsnorm_hf_matches_hf_not_sgl(dtype: torch.dtype) -> None: + """Regression guard: kernel must follow HF (cast-before-mul), not the old + sgl_kernel.rmsnorm semantics (fp32-mul-then-cast). Reduction-order drift + prevents a bit-exact assert against HF, so instead assert the kernel is + strictly closer to HF than to the SGL reference.""" + torch.manual_seed(0) + x = torch.randn(64, 4096, device=DEVICE, dtype=dtype) + w = torch.randn(4096, device=DEVICE, dtype=dtype) + out = rmsnorm_hf(x, w, EPS).float() + hf_ref = hf_rmsnorm_reference(x, w, EPS).float() + sgl_ref = sgl_rmsnorm_reference(x, w, EPS).float() + assert (sgl_ref - hf_ref).abs().max() > 0, "inputs don't exercise the difference" + diff_hf = (out - hf_ref).abs().max().item() + diff_sgl = (out - sgl_ref).abs().max().item() + assert ( + diff_hf < diff_sgl + ), f"kernel closer to SGL than HF (hf={diff_hf}, sgl={diff_sgl})" + + +def test_rmsnorm_hf_empty_input() -> None: + """Empty input must short-circuit: the C++ launcher rejects num_tokens=0.""" + x = torch.empty(0, 4096, device=DEVICE, dtype=torch.float16) + w = torch.randn(4096, device=DEVICE, dtype=torch.float16) + out = rmsnorm_hf(x, w, EPS) + assert out.shape == x.shape and out.numel() == 0 + + +@pytest.mark.parametrize( + ("hidden_size", "expected"), + [ + (16, False), + (32, True), + (64, True), + (96, True), + (128, True), + (256, True), + (288, True), + (384, True), + (500, False), + (512, True), + (3072, True), + (4096, True), + (8192, True), + (4097, False), + ], +) +def test_is_supported_hidden_size(hidden_size: int, expected: bool) -> None: + assert is_supported_rmsnorm_hf_hidden_size(hidden_size) is expected + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_rope.py b/asian_ai/performance/SGLang/test/registered/jit/test_rope.py new file mode 100644 index 0000000000000000000000000000000000000000..55d399312cd2b7f298c3c5222ffaa0f689ce45fb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_rope.py @@ -0,0 +1,257 @@ +import sys + +import pytest +import torch +import triton + +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=64, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=256, suite="nightly-kernel-1-gpu", nightly=True) + +DEVICE = "cuda" +DTYPE = torch.bfloat16 +MAX_SEQ_LEN = 131072 # common seq length +ROPE_BASE = 10000.0 +CACHE_SIZE = 1024 * 128 + + +def create_cos_sin_cache( + rotary_dim: int, + max_position: int = MAX_SEQ_LEN, + base: float = ROPE_BASE, +) -> torch.Tensor: + """Create cos/sin cache compatible with SGLang layout: [max_pos, rotary_dim].""" + inv_freq = 1.0 / ( + base + ** ( + torch.arange(0, rotary_dim, 2, dtype=torch.float32, device=DEVICE) + / rotary_dim + ) + ) + t = torch.arange(max_position, dtype=torch.float32, device=DEVICE) + freqs = torch.einsum("i,j->ij", t, inv_freq) + cos = freqs.cos() + sin = freqs.sin() + cache = torch.cat((cos, sin), dim=-1) # [max_pos, rotary_dim] + return cache + + +# --------------------------------------------------------------------------- +# Implementation wrappers +# --------------------------------------------------------------------------- + + +def sglang_jit_rope( + q: torch.Tensor, + k: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + is_neox: bool, +) -> None: + from sglang.jit_kernel.rope import apply_rope_inplace + + apply_rope_inplace(q, k, cos_sin_cache, positions, is_neox=is_neox) + + +def flashinfer_rope( + q: torch.Tensor, + k: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + is_neox: bool, +) -> None: + from flashinfer.rope import apply_rope_with_cos_sin_cache_inplace + + head_size = q.shape[-1] + # flashinfer expects [nnz, num_heads * head_size] + q_2d = q.view(q.shape[0], -1) + k_2d = k.view(k.shape[0], -1) + apply_rope_with_cos_sin_cache_inplace( + positions=positions, + query=q_2d, + key=k_2d, + head_size=head_size, + cos_sin_cache=cos_sin_cache, + is_neox=is_neox, + ) + + +def torch_impl_rope( + q: torch.Tensor, + k: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + is_neox: bool, +) -> None: + # TODO: implement a pure-PyTorch reference for extra coverage + pass + + +# --------------------------------------------------------------------------- +# Test parameters +# --------------------------------------------------------------------------- + +BS_LIST = [2**x for x in range(12)] +BS_LIST += [x + 1 for x in BS_LIST] # odd sizes to stress non-aligned paths +BS_LIST = get_ci_test_range(BS_LIST, [1, 129, 2048, 2049]) +NUM_KV_HEADS_LIST = get_ci_test_range([1, 2, 8], [1, 8]) +GQA_RATIO = get_ci_test_range([1, 4, 8], [1, 8]) +ROPE_DIM_LIST = get_ci_test_range([64, 128, 256, 512], [64, 256]) +IS_NEOX_LIST = [False, True] +DTYPE_LIST = get_ci_test_range( + [torch.bfloat16, torch.float16], [torch.bfloat16, torch.float16] +) +PARTIAL_ROPE_DIM_LIST = get_ci_test_range([64, 80, 96, 128], [64, 96]) +HEAD_DIM_LIST = get_ci_test_range([64, 128, 256], [64, 256]) + + +@pytest.mark.parametrize("batch_size", BS_LIST) +@pytest.mark.parametrize("gqa_ratio", GQA_RATIO) +@pytest.mark.parametrize("num_kv_heads", NUM_KV_HEADS_LIST) +@pytest.mark.parametrize("rope_dim", ROPE_DIM_LIST) +@pytest.mark.parametrize("is_neox", IS_NEOX_LIST) +@pytest.mark.parametrize("dtype", DTYPE_LIST) +def test_rope( + batch_size: int, + gqa_ratio: int, + num_kv_heads: int, + rope_dim: int, + is_neox: bool, + dtype: torch.dtype, +) -> None: + num_qo_heads = num_kv_heads * gqa_ratio + q = torch.randn(batch_size, num_qo_heads, rope_dim, device=DEVICE, dtype=dtype) + k = torch.randn(batch_size, num_kv_heads, rope_dim, device=DEVICE, dtype=dtype) + positions = torch.randint( + 0, MAX_SEQ_LEN, (batch_size,), device=DEVICE, dtype=torch.int64 + ) + cos_sin_cache = create_cos_sin_cache(rope_dim) + + q_fi, k_fi = q.clone(), k.clone() + q_jit, k_jit = q.clone(), k.clone() + + flashinfer_rope(q_fi, k_fi, cos_sin_cache, positions, is_neox) + sglang_jit_rope(q_jit, k_jit, cos_sin_cache, positions, is_neox) + + atol = rtol = 1e-2 + triton.testing.assert_close(q_fi, q_jit, atol=atol, rtol=rtol) + triton.testing.assert_close(k_fi, k_jit, atol=atol, rtol=rtol) + + +@pytest.mark.parametrize("dtype", [torch.int32, torch.int64]) +def test_rope_position_dtypes(dtype: torch.dtype) -> None: + """Ensure both int32 and int64 position tensors work correctly.""" + batch_size, num_qo_heads, num_kv_heads, rope_dim = 16384, 16, 2, 128 + is_neox = True + + q = torch.randn(batch_size, num_qo_heads, rope_dim, device=DEVICE, dtype=DTYPE) + k = torch.randn(batch_size, num_kv_heads, rope_dim, device=DEVICE, dtype=DTYPE) + positions = torch.randint(0, MAX_SEQ_LEN, (batch_size,), device=DEVICE, dtype=dtype) + cos_sin_cache = create_cos_sin_cache(rope_dim) + + q_fi, k_fi = q.clone(), k.clone() + q_jit, k_jit = q.clone(), k.clone() + + flashinfer_rope(q_fi, k_fi, cos_sin_cache, positions.long(), is_neox) + sglang_jit_rope(q_jit, k_jit, cos_sin_cache, positions, is_neox) + + atol = rtol = 1e-2 + triton.testing.assert_close(q_fi, q_jit, atol=atol, rtol=rtol) + triton.testing.assert_close(k_fi, k_jit, atol=atol, rtol=rtol) + + +@pytest.mark.parametrize("batch_size", BS_LIST) +@pytest.mark.parametrize("is_neox", IS_NEOX_LIST) +@pytest.mark.parametrize("rope_dim", PARTIAL_ROPE_DIM_LIST) +@pytest.mark.parametrize("head_dim", HEAD_DIM_LIST) +def test_partial_rope(batch_size: int, is_neox: bool, rope_dim: int, head_dim: int): + if head_dim < rope_dim: + pytest.skip("Invalid config: head_dim must be >= rope_dim.") + num_qo_heads, num_kv_heads = 8, 2 + + q = torch.randn(batch_size, num_qo_heads, head_dim, device=DEVICE, dtype=DTYPE) + k = torch.randn(batch_size, num_kv_heads, head_dim, device=DEVICE, dtype=DTYPE) + positions = torch.randint(0, MAX_SEQ_LEN, (batch_size,), device=DEVICE) + cos_sin_cache = create_cos_sin_cache(rope_dim) + + q_fi, k_fi = q.clone(), k.clone() + q_jit, k_jit = q.clone(), k.clone() + rope = ..., slice(rope_dim) # NOTE: flashinfer by default apply to first rope_dim + + flashinfer_rope(q_fi, k_fi, cos_sin_cache, positions.long(), is_neox) + sglang_jit_rope(q_jit[rope], k_jit[rope], cos_sin_cache, positions, is_neox) + + atol = rtol = 1e-2 + triton.testing.assert_close(q_fi, q_jit, atol=atol, rtol=rtol) + triton.testing.assert_close(k_fi, k_jit, atol=atol, rtol=rtol) + + +@pytest.mark.parametrize("batch_size", BS_LIST) +@pytest.mark.parametrize("gqa_ratio", GQA_RATIO) +@pytest.mark.parametrize("num_kv_heads", NUM_KV_HEADS_LIST) +@pytest.mark.parametrize("rope_dim", ROPE_DIM_LIST) +@pytest.mark.parametrize("is_neox", IS_NEOX_LIST) +def test_fused_rope_store( + batch_size: int, + gqa_ratio: int, + num_kv_heads: int, + rope_dim: int, + is_neox: bool, +) -> None: + """Test fused RoPE + KV cache store against separate RoPE + manual store.""" + from sglang.jit_kernel.rope import apply_rope_inplace_with_kvcache + + num_qo_heads = num_kv_heads * gqa_ratio + dtype = DTYPE + + q = torch.randn(batch_size, num_qo_heads, rope_dim, device=DEVICE, dtype=dtype) + k = torch.randn(batch_size, num_kv_heads, rope_dim, device=DEVICE, dtype=dtype) + v = torch.randn(batch_size, num_kv_heads, rope_dim, device=DEVICE, dtype=dtype) + positions = torch.randint( + 0, MAX_SEQ_LEN, (batch_size,), device=DEVICE, dtype=torch.int64 + ) + out_loc = torch.randperm(CACHE_SIZE, device=DEVICE, dtype=torch.int64)[:batch_size] + cos_sin_cache = create_cos_sin_cache(rope_dim) + + row_size = num_kv_heads * rope_dim + k_cache_ref = torch.zeros(CACHE_SIZE, row_size, device=DEVICE, dtype=dtype) + v_cache_ref = torch.zeros(CACHE_SIZE, row_size, device=DEVICE, dtype=dtype) + k_cache_fused = torch.zeros(CACHE_SIZE, row_size, device=DEVICE, dtype=dtype) + v_cache_fused = torch.zeros(CACHE_SIZE, row_size, device=DEVICE, dtype=dtype) + + # --- reference: separate RoPE then manual scatter --- + q_ref, k_ref = q.clone(), k.clone() + flashinfer_rope(q_ref, k_ref, cos_sin_cache, positions, is_neox) + k_cache_ref[out_loc] = k_ref.view(batch_size, -1) + v_cache_ref[out_loc] = v.view(batch_size, -1) + + # --- fused kernel --- + q_fused, k_fused = q.clone(), k.clone() + v_fused = v.clone() + apply_rope_inplace_with_kvcache( + q_fused, + k_fused, + v_fused, + k_cache_fused, + v_cache_fused, + cos_sin_cache, + positions, + out_loc, + is_neox=is_neox, + ) + + atol = rtol = 1e-2 + # q should match RoPE-only result + triton.testing.assert_close(q_ref, q_fused, atol=atol, rtol=rtol) + # k_cache should contain the rotated k + triton.testing.assert_close( + k_cache_ref[out_loc], k_cache_fused[out_loc], atol=atol, rtol=rtol + ) + # v_cache should be an exact copy + assert torch.all(v_cache_ref[out_loc] == v_cache_fused[out_loc]), "v_cache mismatch" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_set_mla_kv_buffer.py b/asian_ai/performance/SGLang/test/registered/jit/test_set_mla_kv_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..a8617e0ac8499e2870f911f52f72d2ed52ac673c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_set_mla_kv_buffer.py @@ -0,0 +1,126 @@ +import sys + +import pytest +import torch + +from sglang.jit_kernel.set_mla_kv_buffer import ( + can_use_set_mla_kv_buffer, + set_mla_kv_buffer, +) +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +DEVICE = "cuda" +CACHE_SIZE = 4096 + +# (nope_dim, rope_dim) pairs: standard MLA, MLA scale buffer, FP8 nope-extended layout. +SHAPES = get_ci_test_range( + [(512, 64), (512, 32), (256, 64), (128, 64), (528, 64)], + [(512, 64), (528, 64)], +) +BATCH_SIZES = get_ci_test_range([1, 7, 64, 257, 1024], [1, 64, 1024]) + + +def _ref(kv_buffer, loc, cache_k_nope, cache_k_rope): + nope_dim = cache_k_nope.shape[-1] + n_loc = loc.shape[0] + src_nope = cache_k_nope.reshape(n_loc, -1) + src_rope = cache_k_rope.reshape(n_loc, -1) + kv_view = kv_buffer.view(kv_buffer.shape[0], -1) + kv_view[loc.long(), :nope_dim] = src_nope + kv_view[loc.long(), nope_dim : nope_dim + src_rope.shape[-1]] = src_rope + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("shape", SHAPES) +@pytest.mark.parametrize("batch_size", BATCH_SIZES) +def test_set_mla_kv_buffer_correctness(dtype, shape, batch_size): + nope_dim, rope_dim = shape + total_dim = nope_dim + rope_dim + + cache_k_nope = torch.randn((batch_size, 1, nope_dim), dtype=dtype, device=DEVICE) + cache_k_rope = torch.randn((batch_size, 1, rope_dim), dtype=dtype, device=DEVICE) + kv_buffer = torch.randn((CACHE_SIZE, 1, total_dim), dtype=dtype, device=DEVICE) + kv_ref = kv_buffer.clone() + + loc = torch.randperm(CACHE_SIZE, device=DEVICE)[:batch_size] + + set_mla_kv_buffer(kv_buffer, loc, cache_k_nope, cache_k_rope) + _ref(kv_ref, loc, cache_k_nope, cache_k_rope) + + assert torch.equal(kv_buffer, kv_ref) + + +@pytest.mark.parametrize("loc_dtype", [torch.int32, torch.int64]) +def test_set_mla_kv_buffer_loc_dtypes(loc_dtype): + nope_dim, rope_dim = 512, 64 + batch_size = 128 + dtype = torch.bfloat16 + + cache_k_nope = torch.randn((batch_size, 1, nope_dim), dtype=dtype, device=DEVICE) + cache_k_rope = torch.randn((batch_size, 1, rope_dim), dtype=dtype, device=DEVICE) + kv_buffer = torch.randn( + (CACHE_SIZE, 1, nope_dim + rope_dim), dtype=dtype, device=DEVICE + ) + kv_ref = kv_buffer.clone() + + loc = torch.randperm(CACHE_SIZE, device=DEVICE)[:batch_size].to(loc_dtype) + + set_mla_kv_buffer(kv_buffer, loc, cache_k_nope, cache_k_rope) + _ref(kv_ref, loc, cache_k_nope, cache_k_rope) + + assert torch.equal(kv_buffer, kv_ref) + + +def test_set_mla_kv_buffer_uint8_byte_layout(): + """FP8 DSA byte-layout: cache_k_nope is uint8 with [fp8(512) | scales(16)] = 528, + cache_k_rope is uint8 [128]; total payload = 656 bytes.""" + nope_bytes, rope_bytes = 528, 128 + batch_size = 64 + dtype = torch.uint8 + + cache_k_nope = torch.randint( + 0, 256, (batch_size, 1, nope_bytes), dtype=dtype, device=DEVICE + ) + cache_k_rope = torch.randint( + 0, 256, (batch_size, 1, rope_bytes), dtype=dtype, device=DEVICE + ) + kv_buffer = torch.randint( + 0, 256, (CACHE_SIZE, 1, nope_bytes + rope_bytes), dtype=dtype, device=DEVICE + ) + kv_ref = kv_buffer.clone() + + loc = torch.randperm(CACHE_SIZE, device=DEVICE)[:batch_size] + + set_mla_kv_buffer(kv_buffer, loc, cache_k_nope, cache_k_rope) + _ref(kv_ref, loc, cache_k_nope, cache_k_rope) + + assert torch.equal(kv_buffer, kv_ref) + + +def test_set_mla_kv_buffer_empty_loc(): + nope_dim, rope_dim = 512, 64 + dtype = torch.bfloat16 + cache_k_nope = torch.empty((0, 1, nope_dim), dtype=dtype, device=DEVICE) + cache_k_rope = torch.empty((0, 1, rope_dim), dtype=dtype, device=DEVICE) + kv_buffer = torch.randn( + (CACHE_SIZE, 1, nope_dim + rope_dim), dtype=dtype, device=DEVICE + ) + kv_before = kv_buffer.clone() + + loc = torch.empty((0,), dtype=torch.int64, device=DEVICE) + set_mla_kv_buffer(kv_buffer, loc, cache_k_nope, cache_k_rope) + + assert torch.equal(kv_buffer, kv_before) + + +def test_can_use_set_mla_kv_buffer(): + assert can_use_set_mla_kv_buffer(1024, 128) # bf16 (512,64) + assert can_use_set_mla_kv_buffer(528, 128) # fp8 byte layout + assert not can_use_set_mla_kv_buffer(13, 8) # not multiple of 4 + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_sigmoid_gate_mul.py b/asian_ai/performance/SGLang/test/registered/jit/test_sigmoid_gate_mul.py new file mode 100644 index 0000000000000000000000000000000000000000..dec636b9d10310c6dcb5c149773098289c4c0a98 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_sigmoid_gate_mul.py @@ -0,0 +1,81 @@ +import sys + +import pytest +import torch + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=4, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=4, stage="jit-kernel-unit", runner_config="amd") + +DEVICE = "cuda" + + +def reference_sigmoid_gate_mul(x, gate): + return x * torch.sigmoid(gate) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32]) +@pytest.mark.parametrize( + "shape", + [ + (1, 4096), + (4, 4096), + (8, 4096), + (32, 8192), + (1, 128), + (16, 16384), + ], +) +def test_sigmoid_gate_mul_correctness(shape, dtype): + from sglang.jit_kernel.triton.sigmoid_gate_mul import sigmoid_gate_mul + + torch.manual_seed(42) + x = torch.randn(shape, dtype=dtype, device=DEVICE) + gate = torch.randn(shape, dtype=dtype, device=DEVICE) + + ref = reference_sigmoid_gate_mul(x, gate) + out = sigmoid_gate_mul(x, gate) + + rtol = 1e-2 if dtype == torch.bfloat16 else 1e-3 + atol = 2e-2 if dtype == torch.bfloat16 else 1e-3 + torch.testing.assert_close(out, ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("shape", [(4, 4096), (1, 128)]) +def test_sigmoid_gate_mul_does_not_modify_inputs(shape): + from sglang.jit_kernel.triton.sigmoid_gate_mul import sigmoid_gate_mul + + torch.manual_seed(42) + x = torch.randn(shape, dtype=torch.bfloat16, device=DEVICE) + gate = torch.randn(shape, dtype=torch.bfloat16, device=DEVICE) + x_orig = x.clone() + gate_orig = gate.clone() + + sigmoid_gate_mul(x, gate) + + torch.testing.assert_close(x, x_orig, rtol=0, atol=0) + torch.testing.assert_close(gate, gate_orig, rtol=0, atol=0) + + +def test_sigmoid_gate_mul_output_dtype(): + from sglang.jit_kernel.triton.sigmoid_gate_mul import sigmoid_gate_mul + + for dtype in [torch.bfloat16, torch.float16, torch.float32]: + x = torch.randn(4, 4096, dtype=dtype, device=DEVICE) + gate = torch.randn(4, 4096, dtype=dtype, device=DEVICE) + out = sigmoid_gate_mul(x, gate) + assert out.dtype == dtype, f"Expected {dtype}, got {out.dtype}" + + +def test_sigmoid_gate_mul_contiguous_output(): + from sglang.jit_kernel.triton.sigmoid_gate_mul import sigmoid_gate_mul + + x = torch.randn(4, 4096, dtype=torch.bfloat16, device=DEVICE) + gate = torch.randn(4, 4096, dtype=torch.bfloat16, device=DEVICE) + out = sigmoid_gate_mul(x, gate) + assert out.is_contiguous() + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_silu_and_mul_scaled_fp4_experts_quant_packed.py b/asian_ai/performance/SGLang/test/registered/jit/test_silu_and_mul_scaled_fp4_experts_quant_packed.py new file mode 100644 index 0000000000000000000000000000000000000000..a14d8b33e8b5ccf1e652ab5874d8e31e12a88306 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_silu_and_mul_scaled_fp4_experts_quant_packed.py @@ -0,0 +1,337 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Unit test for the fused JIT op ``silu_and_mul_scaled_fp4_experts_quant_packed`` +(introduced in PR #18612). + +On the CUTLASS NVFP4 MoE intermediate, the op fuses the previous two-step path + + intermediate = silu_and_mul(c1) # SiLU(gate) * up + fp4, sf = scaled_fp4_experts_quant(intermediate) # NVFP4 expert quant + +into a single kernel + + fp4, sf = silu_and_mul_scaled_fp4_experts_quant_packed(c1, ...) + +This test compares the fused op against that exact unfused +``silu_and_mul`` + ``scaled_fp4_experts_quant`` path **with uneven expert offsets**: +experts deliberately receive very different token counts, including tiny experts and +experts whose row count is not a multiple of the 128-row block-scale padding. That is +precisely the regime that stresses the per-expert ``expert_offsets`` / +``blockscale_offsets`` indexing the fusion has to get right. + +It follows the two existing siblings: + * ``test_silu_and_mul_quantize_to_fp4_grouped`` (the grouped/masked variant) -- the + unfused path is the reference, and the fused output must match it bit-exactly + (packed FP4 nibbles + recovered block scales), and + * ``test_nvfp4_blockwise_moe`` (the expert-offset variant) -- offsets are built from + an explicit, non-uniform per-expert token list. + +A high-precision ``F.silu(gate) * up`` check additionally grounds the unfused path so a +bug shared by both kernels cannot produce a false (vacuous) pass. + + pytest python/sglang/jit_kernel/tests/test_silu_and_mul_scaled_fp4_experts_quant_packed.py -v +""" + +import sys + +import pytest +import torch +import triton +from torch.nn import functional as F + +from sglang.jit_kernel.activation import silu_and_mul +from sglang.jit_kernel.nvfp4 import ( + scaled_fp4_experts_quant, + silu_and_mul_scaled_fp4_experts_quant_packed, +) +from sglang.test.ci.ci_register import register_cuda_ci + +# The NVFP4 expert-quant kernels are Blackwell-only (sm100a), so this runs on +# the B200 unit suite. +register_cuda_ci(est_time=20, stage="base-b-kernel-unit", runner_config="4-gpu-b200") + +FLOAT8_E4M3_MAX = 448.0 +FLOAT4_E2M1_MAX = 6.0 +BLOCK_SIZE = 16 +kE2M1ToFloat = torch.tensor( + [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], dtype=torch.float32 +) + + +def _nvfp4_supported() -> bool: + return torch.cuda.is_available() and torch.cuda.get_device_capability() >= (10, 0) + + +def _round_up(x: int, y: int) -> int: + return ((x + y - 1) // y) * y + + +# --------------------------------------------------------------------------- # +# Offset builders (mirror test_nvfp4_blockwise_moe.py). +# expert_offsets: cumulative *actual* per-expert rows ([E+1] int32) +# blockscale_offsets: cumulative rows padded up to 128 per expert ([E+1] int32) +# A non-uniform ``m_per_expert`` makes both offset tensors uneven. +# --------------------------------------------------------------------------- # +def _build_expert_offsets(m_per_expert, device) -> torch.Tensor: + offsets = [0] + for m in m_per_expert: + offsets.append(offsets[-1] + m) + return torch.tensor(offsets, dtype=torch.int32, device=device) + + +def _build_blockscale_offsets(m_per_expert, device) -> torch.Tensor: + offsets = [0] + for m in m_per_expert: + offsets.append(offsets[-1] + _round_up(m, 128)) + return torch.tensor(offsets, dtype=torch.int32, device=device) + + +# --------------------------------------------------------------------------- # +# FP4 dequant / scale-recovery helpers (mirror test/registered/kernels/test_fp4_moe.py) +# --------------------------------------------------------------------------- # +def break_fp4_bytes(a: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: + assert a.dtype == torch.uint8 + m, n = a.shape + a_flat = a.flatten() + high = (a_flat & 0xF0) >> 4 + low = a_flat & 0x0F + combined = torch.stack((low, high), dim=1).flatten() + signs = (combined & 0x08).to(torch.bool) + abs_vals = (combined & 0x07).to(torch.long) + kE2M1 = kE2M1ToFloat.to(device=a.device) + values = kE2M1[abs_vals] * torch.where(signs, -1.0, 1.0) + return values.reshape(m, n * 2).to(dtype=dtype) + + +def convert_swizzled_to_linear( + a_sf_swizzled: torch.Tensor, m: int, k: int, block_size: int +) -> torch.Tensor: + """De-swizzle one expert's block-scale region and drop the 128-row padding tail.""" + m_tiles = (m + 128 - 1) // 128 + f = block_size * 4 + k_tiles = (k + f - 1) // f + tmp = torch.reshape(a_sf_swizzled, (1, m_tiles, k_tiles, 32, 4, 4)) + tmp = torch.permute(tmp, (0, 1, 4, 3, 2, 5)) + out = tmp.reshape(m_tiles * 128, k_tiles * f // block_size) + return out[0:m, 0:k] + + +def dequantize_nvfp4_to_dtype( + tensor_fp4: torch.Tensor, + tensor_sf: torch.Tensor, + global_scale: torch.Tensor, + dtype: torch.dtype, + device: torch.device, + block_size: int = 16, +) -> torch.Tensor: + """Dequantize one expert's packed FP4 (m, k//2) + swizzled block scales.""" + assert tensor_fp4.dtype == torch.uint8 + m, packed_k = tensor_fp4.shape + k = packed_k * 2 + tensor_f32 = break_fp4_bytes(tensor_fp4, dtype) + tensor_f32 = tensor_f32.reshape(m, k // block_size, block_size) + tensor_sf = tensor_sf.view(torch.float8_e4m3fn) + tensor_sf = convert_swizzled_to_linear(tensor_sf, m, k, block_size) + tensor_sf_dtype = tensor_sf.to(torch.float32) / global_scale + out = (tensor_f32 * tensor_sf_dtype.unsqueeze(-1)).reshape(m, k) + return out.to(dtype=dtype) + + +def _recover_block_scales( + sf: torch.Tensor, s0: int, s1: int, m_e: int, n: int +) -> torch.Tensor: + """De-swizzled, un-padded block scales (float32) for one expert's region.""" + block = sf[s0:s1].contiguous().view(torch.float8_e4m3fn) + return convert_swizzled_to_linear(block, m_e, n, BLOCK_SIZE).to(torch.float32) + + +def _rel_l2(a: torch.Tensor, b: torch.Tensor) -> float: + return (a.float() - b.float()).norm().item() / b.float().norm().clamp_min( + 1e-9 + ).item() + + +# --------------------------------------------------------------------------- # +# Uneven per-expert token counts. Each list is deliberately NON-uniform so that +# expert_offsets / blockscale_offsets are uneven, exercising: +# * tiny experts (1, 5, 7 tokens), +# * an exactly-128 expert (no padding), +# * experts straddling the 128-row block-scale padding (130, 200, 384). +# --------------------------------------------------------------------------- # +UNEVEN_M_PER_EXPERT = [ + [33, 17, 48, 29], # all < 128 (matches test_nvfp4_blockwise_moe) + [1, 128, 200, 5, 64], # tiny + exactly-128 + cross-128 + [130, 1, 384, 17, 96, 7], # heavy skew, large dynamic range +] +NS = [256, 768] # 768 == Qwen3-30B-A3B moe_intermediate_size +DTYPES = [torch.bfloat16, torch.float16] + + +@pytest.mark.skipif( + not _nvfp4_supported(), + reason="NVFP4 fused expert-quant kernel requires compute capability >= 10.0 (B200/SM100).", +) +@pytest.mark.parametrize("m_per_expert", UNEVEN_M_PER_EXPERT) +@pytest.mark.parametrize("n", NS) +@pytest.mark.parametrize("dtype", DTYPES) +@torch.inference_mode() +def test_fused_matches_unfused_uneven_offsets(m_per_expert, n, dtype): + torch.manual_seed(0) + device = torch.device("cuda") + num_experts = len(m_per_expert) + + # --- uneven expert offsets --- + expert_offsets = _build_expert_offsets(m_per_expert, device) + blockscale_offsets = _build_blockscale_offsets(m_per_expert, device) + total_m = int(expert_offsets[-1].item()) + counts = torch.tensor(m_per_expert) + assert ( + counts.max() >= 2 * counts.min() + ), "expert offsets must be uneven for this test" + + # gate+up concatenated input (m, 2n); /5 keeps values in a sane FP4 range. + c1 = torch.randn((total_m, 2 * n), dtype=dtype, device=device) / 5.0 + gate, up = c1[:, :n].float(), c1[:, n:].float() + ref = F.silu(gate) * up # high-precision SiLU(gate) * up, (total_m, n) fp32 + + # Per-expert global scale, exactly like cutlass_moe builds a2_gscale. + gscale = torch.empty(num_experts, dtype=torch.float32, device=device) + for e in range(num_experts): + r0, r1 = int(expert_offsets[e]), int(expert_offsets[e + 1]) + amax = ref[r0:r1].abs().max().clamp_min(1e-6) + gscale[e] = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / amax + + # topk only gates the buffer-size assertion in the wrapper; the per-expert + # layout is driven entirely by the offsets. Both paths use the same value. + topk = 1 + + # ---- fused (new op) ---- + fused_fp4, fused_sf = silu_and_mul_scaled_fp4_experts_quant_packed( + c1, gscale, expert_offsets, blockscale_offsets, topk + ) + + # ---- unfused (the exact path the op replaced) ---- + intermediate = torch.empty((total_m, n), dtype=dtype, device=device) + silu_and_mul(c1, intermediate) + unf_fp4, unf_sf = scaled_fp4_experts_quant( + intermediate, gscale, expert_offsets, blockscale_offsets, topk + ) + + assert fused_fp4.shape == unf_fp4.shape == (total_m, n // 2) + + # Per-expert, bit-exact comparison honoring the uneven offsets. + for e in range(num_experts): + r0, r1 = int(expert_offsets[e]), int(expert_offsets[e + 1]) + s0, s1 = int(blockscale_offsets[e]), int(blockscale_offsets[e + 1]) + m_e = r1 - r0 + + # (1) Packed FP4 nibbles are identical: same NVFP4 quantizer, same fused + # SiLU(gate)*up rounded to the storage dtype before quantization. + torch.testing.assert_close( + fused_fp4[r0:r1], unf_fp4[r0:r1], msg=f"FP4 bytes differ for expert {e}" + ) + + # (2) Recovered (de-swizzled, un-padded) block scales are identical. + torch.testing.assert_close( + _recover_block_scales(fused_sf, s0, s1, m_e, n), + _recover_block_scales(unf_sf, s0, s1, m_e, n), + msg=f"block scales differ for expert {e}", + ) + + # (3) Grounding: the unfused path really reproduces SiLU(gate)*up within FP4 + # error, so (1)/(2) cannot pass vacuously on a bug shared by both kernels. + deq = dequantize_nvfp4_to_dtype( + unf_fp4[r0:r1].contiguous(), + unf_sf[s0:s1].contiguous(), + gscale[e], + dtype, + device, + BLOCK_SIZE, + ) + assert ( + _rel_l2(deq, ref[r0:r1]) < 0.2 + ), f"expert {e}: unfused dequant does not match SiLU(gate)*up reference" + + +# --------------------------------------------------------------------------- # +# Performance. The fusion removes, on the MoE down-projection input, one +# intermediate buffer allocation, one extra kernel launch, and a full HBM +# round-trip of the SiLU(gate)*up result. The speedup is measured under CUDA +# graphs -- the steady-state GPU memory-traffic saving, matching how SGLang +# executes graphed decode (the credible, low-noise number; eager wall-clock is +# dominated by launch/dispatch overhead and is too noisy to assert on). The +# assert is only a conservative regression floor; the printed speedup is the real +# result. Mirrors test_cutedsl_gdn_performance, in the same kernel unit suite. +# +# Tokens are spread evenly across experts here (the representative throughput +# case) at realistic Qwen3-30B-A3B MoE dims (n=768, 128 experts), swept from a +# decode batch up to a prefill chunk; the uneven-offset corner cases are covered +# by the correctness test above. +# --------------------------------------------------------------------------- # +PERF_SHAPES = [ + (1024, 768, 128), + (4096, 768, 128), + (16384, 768, 128), +] + + +def _even_offsets(total_tokens, num_experts, device): + base, rem = divmod(total_tokens, num_experts) + m_per_expert = [base + (1 if i < rem else 0) for i in range(num_experts)] + return ( + _build_expert_offsets(m_per_expert, device), + _build_blockscale_offsets(m_per_expert, device), + ) + + +@pytest.mark.skipif( + not _nvfp4_supported(), + reason="NVFP4 fused expert-quant kernel requires compute capability >= 10.0 (B200/SM100).", +) +@pytest.mark.parametrize("total_tokens,n,num_experts", PERF_SHAPES) +@torch.inference_mode() +def test_fused_perf_not_regressed(total_tokens, n, num_experts): + device = torch.device("cuda") + dtype = torch.bfloat16 + expert_offsets, blockscale_offsets = _even_offsets( + total_tokens, num_experts, device + ) + c1 = torch.randn((total_tokens, 2 * n), dtype=dtype, device=device) / 5.0 + gscale = torch.empty(num_experts, dtype=torch.float32, device=device) + for e in range(num_experts): + r0, r1 = int(expert_offsets[e]), int(expert_offsets[e + 1]) + amax = c1[r0:r1].abs().max().to(torch.float32).clamp_min(1e-6) + gscale[e] = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / amax + topk = 1 + + def fused(): + silu_and_mul_scaled_fp4_experts_quant_packed( + c1, gscale, expert_offsets, blockscale_offsets, topk + ) + + def unfused(): + # The exact path the op replaced: alloc the intermediate, SiLU*mul into + # it, then quantize it -- one extra buffer + kernel + HBM round-trip. + intermediate = torch.empty((total_tokens, n), dtype=dtype, device=device) + silu_and_mul(c1, intermediate) + scaled_fp4_experts_quant( + intermediate, gscale, expert_offsets, blockscale_offsets, topk + ) + + g_f = triton.testing.do_bench_cudagraph(fused) # ms, median + g_u = triton.testing.do_bench_cudagraph(unfused) + cuda_graph_speedup = g_u / g_f + print( + f"\n [PERF] tokens={total_tokens:>6} n={n} E={num_experts}: " + f"unfused {g_u * 1e3:6.1f}us fused {g_f * 1e3:6.1f}us " + f"cuda-graph speedup = {cuda_graph_speedup:.2f}x" + ) + # Regression guard only: the fusion must not make this op slower. The actual + # win carries a wide margin over this floor, so shared-runner noise cannot + # flake it. + assert ( + cuda_graph_speedup >= 1.05 + ), f"fused regressed under cuda-graph: {cuda_graph_speedup:.2f}x" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_sparse_mla_q8kv8_prefill_sm90.py b/asian_ai/performance/SGLang/test/registered/jit/test_sparse_mla_q8kv8_prefill_sm90.py new file mode 100644 index 0000000000000000000000000000000000000000..8c76ad90f3c4260c1d38c6fe508a34727077ee8e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_sparse_mla_q8kv8_prefill_sm90.py @@ -0,0 +1,422 @@ +from __future__ import annotations + +import math +import sys + +import pytest +import torch + +from sglang.srt.utils import is_sm90_supported +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=120, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=300, suite="nightly-kernel-1-gpu", nightly=True) + + +DTYPE_FP8 = torch.float8_e4m3fn +D_V = 512 +H_Q = 64 +H_KV = 1 +TOPK = 128 +S_KV = 256 + +# DeepSeek NSA E2E currently does not plumb a per-head attention sink into +# sparse MLA. No-sink cases are the E2E proxy; sink cases below exercise the +# optional kernel full path and partial topk_length handling. + + +def _sm90_available() -> bool: + return is_sm90_supported() + + +def _make_fp8_tensor(shape: tuple[int, ...], seed: int) -> torch.Tensor: + generator = torch.Generator(device="cuda") + generator.manual_seed(seed) + tensor = torch.randn(shape, device="cuda", generator=generator, dtype=torch.float32) + return (tensor * 0.05).to(DTYPE_FP8) + + +def _make_case( + d_qk: int, + with_sink: bool, + s_q: int = 2, + topk: int = TOPK, + s_kv: int = S_KV, +): + q = _make_fp8_tensor((s_q, H_Q, d_qk), seed=1000 + d_qk + s_q * 13 + topk) + kv = torch.zeros((s_kv + 1, H_KV, d_qk), dtype=DTYPE_FP8, device="cuda") + kv[:s_kv] = _make_fp8_tensor((s_kv, H_KV, d_qk), seed=2000 + d_qk + s_kv) + + generator = torch.Generator(device="cuda") + generator.manual_seed(3000 + d_qk + s_q * 17 + topk) + indices = torch.randint( + 0, + s_kv, + (s_q, H_KV, topk), + dtype=torch.int32, + device="cuda", + generator=generator, + ) + + q_scale = torch.tensor([1.0], dtype=torch.float32, device="cuda") + kv_scale = torch.tensor([1.0], dtype=torch.float32, device="cuda") + sm_scale = 1.0 / math.sqrt(d_qk) + + if not with_sink: + return q, kv, indices, sm_scale, q_scale, kv_scale, None, None + + attn_sink = torch.linspace(-0.05, 0.05, H_Q, dtype=torch.float32, device="cuda") + # Vary topk_length per query row to exercise the partial-topk path. + lengths = [topk if i % 2 == 0 else max(topk - 32, topk // 2) for i in range(s_q)] + topk_length = torch.tensor(lengths, dtype=torch.int32, device="cuda") + for q_idx, valid_topk in enumerate(lengths): + if valid_topk < topk: + indices[q_idx, 0, valid_topk:] = -1 + return q, kv, indices, sm_scale, q_scale, kv_scale, attn_sink, topk_length + + +def _torch_sparse_attention_ref( + q: torch.Tensor, + kv: torch.Tensor, + indices: torch.Tensor, + sm_scale: float, + q_scale: torch.Tensor, + kv_scale: torch.Tensor, + attn_sink: torch.Tensor | None, + topk_length: torch.Tensor | None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + topk = indices.shape[-1] + q_f32 = q.float() * q_scale.item() + kv_f32 = kv.float() * kv_scale.item() + out = torch.empty( + (q.shape[0], q.shape[1], D_V), dtype=torch.float32, device=q.device + ) + max_logits = torch.empty( + (q.shape[0], q.shape[1]), dtype=torch.float32, device=q.device + ) + lse = torch.empty_like(max_logits) + + for q_idx in range(q.shape[0]): + valid_topk = topk if topk_length is None else int(topk_length[q_idx].item()) + token_ids = indices[q_idx, 0, :valid_topk].to(torch.long) + keys = kv_f32[token_ids, 0, :] + values = kv_f32[token_ids, 0, :D_V] + scores = torch.matmul(q_f32[q_idx], keys.transpose(0, 1)) * sm_scale + score_max = scores.max(dim=-1, keepdim=True).values + exp_scores = torch.exp(scores - score_max) + denom = exp_scores.sum(dim=-1, keepdim=True) + max_logits[q_idx] = score_max.squeeze(-1) + lse[q_idx] = torch.log(denom.squeeze(-1)) + score_max.squeeze(-1) + if attn_sink is not None: + denom = denom + torch.exp(attn_sink[:, None] - score_max) + out[q_idx] = torch.matmul(exp_scores, values) / denom + + return out, max_logits, lse + + +def _run_and_check(d_qk, with_sink, s_q=2, topk=TOPK, s_kv=S_KV): + from sglang.jit_kernel.sparse_mla_q8kv8_prefill_sm90 import ( + sparse_mla_q8kv8_prefill_fwd, + ) + + q, kv, indices, sm_scale, q_scale, kv_scale, attn_sink, topk_length = _make_case( + d_qk, with_sink, s_q=s_q, topk=topk, s_kv=s_kv + ) + + out, max_logits, lse = sparse_mla_q8kv8_prefill_fwd( + q=q, + kv=kv, + indices=indices, + sm_scale=sm_scale, + q_scale=q_scale, + kv_scale=kv_scale, + d_v=D_V, + attn_sink=attn_sink, + topk_length=topk_length, + ) + torch.cuda.synchronize() + + ref, ref_max_logits, ref_lse = _torch_sparse_attention_ref( + q=q, + kv=kv, + indices=indices, + sm_scale=sm_scale, + q_scale=q_scale, + kv_scale=kv_scale, + attn_sink=attn_sink, + topk_length=topk_length, + ) + + assert out.shape == (q.shape[0], H_Q, D_V) + assert out.dtype == torch.bfloat16 + assert max_logits.shape == (q.shape[0], H_Q) + assert lse.shape == (q.shape[0], H_Q) + assert torch.isfinite(out.float()).all() + assert torch.isfinite(max_logits.float()).all() + assert torch.isfinite(lse.float()).all() + torch.testing.assert_close(out.float(), ref, atol=8e-2, rtol=8e-2) + if attn_sink is None: + torch.testing.assert_close( + max_logits.float(), ref_max_logits, atol=1e-2, rtol=1e-2 + ) + torch.testing.assert_close(lse.float(), ref_lse, atol=2e-3, rtol=2e-3) + + +@pytest.mark.skipif( + not _sm90_available(), reason="Q8KV8 sparse prefill requires SM90 CUDA" +) +@pytest.mark.parametrize("d_qk,with_sink", [(512, False), (576, False)]) +def test_sparse_mla_q8kv8_prefill_matches_reference(d_qk: int, with_sink: bool): + _run_and_check(d_qk, with_sink) + + +# Corner cases: minimal s_q, larger s_q, larger topk/s_kv, crossed d_qk +# configurations, and optional sink+topk_length feature coverage. The kernel +# requires topk to be a multiple of 128, so 128 is the minimum supported. +@pytest.mark.skipif( + not _sm90_available(), reason="Q8KV8 sparse prefill requires SM90 CUDA" +) +@pytest.mark.parametrize( + "d_qk,with_sink,s_q,topk,s_kv", + [ + (576, True, 1, TOPK, S_KV), + (576, True, 8, TOPK, S_KV), + (576, True, 2, 256, 512), + (512, False, 65, 256, 592), + (512, True, 2, TOPK, S_KV), + (576, False, 65, 256, 592), + ], +) +def test_sparse_mla_q8kv8_prefill_corner_cases( + d_qk: int, with_sink: bool, s_q: int, topk: int, s_kv: int +): + _run_and_check(d_qk, with_sink, s_q=s_q, topk=topk, s_kv=s_kv) + + +# Precision / accuracy: no-sink only because these metrics are intended to +# approximate the current DeepSeek NSA E2E path. Sink behavior is still covered +# above as kernel feature coverage, but sink-enabled precision numbers should +# not be used as E2E proxy results until the E2E pipeline wires attn_sink. +@pytest.mark.skipif( + not _sm90_available(), reason="Q8KV8 sparse prefill requires SM90 CUDA" +) +@pytest.mark.parametrize( + "d_qk,s_q,topk,s_kv", + [ + (512, 4, 256, 512), + (576, 4, 256, 512), + (512, 64, 256, 1024), + (576, 64, 256, 1024), + ], +) +def test_sparse_mla_q8kv8_prefill_precision(d_qk: int, s_q: int, topk: int, s_kv: int): + """Demonstrate that Q8KV8 kernel precision is near-lossless versus the + fp32 reference: max/mean/p99 absolute error are small and the fraction + of elements exceeding 0.1 absolute error is under 1%.""" + from sglang.jit_kernel.sparse_mla_q8kv8_prefill_sm90 import ( + sparse_mla_q8kv8_prefill_fwd, + ) + + with_sink = False + q, kv, indices, sm_scale, q_scale, kv_scale, attn_sink, topk_length = _make_case( + d_qk, with_sink, s_q=s_q, topk=topk, s_kv=s_kv + ) + + out, max_logits, lse = sparse_mla_q8kv8_prefill_fwd( + q=q, + kv=kv, + indices=indices, + sm_scale=sm_scale, + q_scale=q_scale, + kv_scale=kv_scale, + d_v=D_V, + attn_sink=attn_sink, + topk_length=topk_length, + ) + torch.cuda.synchronize() + + ref, ref_max_logits, ref_lse = _torch_sparse_attention_ref( + q=q, + kv=kv, + indices=indices, + sm_scale=sm_scale, + q_scale=q_scale, + kv_scale=kv_scale, + attn_sink=attn_sink, + topk_length=topk_length, + ) + + out_f32 = out.float() + abs_diff = (out_f32 - ref).abs() + max_diff = abs_diff.max().item() + mean_diff = abs_diff.mean().item() + p99_diff = torch.quantile(abs_diff.flatten(), 0.99).item() + fail_rate = (abs_diff > 0.1).float().mean().item() * 100 + has_bad = bool(torch.isnan(out_f32).any() or torch.isinf(out_f32).any()) + ref_abs_mean = ref.abs().mean().clamp_min(1e-12).item() + rel_mean = mean_diff / ref_abs_mean + cos_diff = 1 - 2 * (out_f32.double() * ref.double()).sum().item() / max( + (out_f32.double().square() + ref.double().square()).sum().item(), 1e-12 + ) + max_logits_diff = (max_logits.float() - ref_max_logits).abs().max().item() + lse_diff = (lse.float() - ref_lse).abs().max().item() + + print( + f"\n d_qk={d_qk} with_sink={with_sink} s_q={s_q} topk={topk} s_kv={s_kv}: " + f"max_diff={max_diff:.2e}, p99_diff={p99_diff:.2e}, " + f"mean_diff={mean_diff:.2e}, rel_mean={rel_mean:.2e}, " + f"cos_diff={cos_diff:.2e}, fail_rate(>0.1)={fail_rate:.3f}%, " + f"max_logits_diff={max_logits_diff:.2e}, lse_diff={lse_diff:.2e}" + ) + + assert not has_bad, "Q8KV8 output contains NaN/Inf" + assert fail_rate < 1.0, f"fail_rate {fail_rate:.3f}% exceeds 1% threshold" + # Tight bounds on aggregate error to lock in near-lossless behavior. + assert max_diff < 1e-3, f"max_diff {max_diff:.2e} exceeds 1e-3" + assert mean_diff < 5e-3, f"mean_diff {mean_diff:.2e} exceeds 5e-3" + assert p99_diff < 5e-2, f"p99_diff {p99_diff:.2e} exceeds 5e-2" + assert cos_diff < 1e-4, f"cos_diff {cos_diff:.2e} exceeds 1e-4" + assert max_logits_diff < 1e-2, f"max_logits_diff {max_logits_diff:.2e} exceeds 1e-2" + assert lse_diff < 2e-3, f"lse_diff {lse_diff:.2e} exceeds 2e-3" + + +@pytest.mark.skipif( + not _sm90_available(), reason="Q8KV8 sparse prefill requires SM90 CUDA" +) +def test_sparse_mla_q8kv8_prefill_no_alias_between_calls(): + """Two default-allocation calls with the same shape must return independent + storage. This guards against regressing to a module-scope output cache.""" + from sglang.jit_kernel.sparse_mla_q8kv8_prefill_sm90 import ( + sparse_mla_q8kv8_prefill_fwd, + ) + + q, kv, indices, sm_scale, q_scale, kv_scale, attn_sink, topk_length = _make_case( + d_qk=576, with_sink=False + ) + + out1, ml1, lse1 = sparse_mla_q8kv8_prefill_fwd( + q=q, + kv=kv, + indices=indices, + sm_scale=sm_scale, + q_scale=q_scale, + kv_scale=kv_scale, + d_v=D_V, + attn_sink=attn_sink, + topk_length=topk_length, + ) + snapshot = out1.clone() + + out2, ml2, lse2 = sparse_mla_q8kv8_prefill_fwd( + q=q, + kv=kv, + indices=indices, + sm_scale=sm_scale, + q_scale=q_scale, + kv_scale=kv_scale, + d_v=D_V, + attn_sink=attn_sink, + topk_length=topk_length, + ) + torch.cuda.synchronize() + + assert out1.data_ptr() != out2.data_ptr() + assert ml1.data_ptr() != ml2.data_ptr() + assert lse1.data_ptr() != lse2.data_ptr() + # The first call's output must not be overwritten by the second call. + torch.testing.assert_close(out1, snapshot) + + +@pytest.mark.skipif( + not _sm90_available(), reason="Q8KV8 sparse prefill requires SM90 CUDA" +) +def test_sparse_mla_q8kv8_prefill_caller_owned_buffers(): + """Caller-provided ``out`` / ``max_logits`` / ``lse`` tensors must be + written into in-place and returned as-is.""" + from sglang.jit_kernel.sparse_mla_q8kv8_prefill_sm90 import ( + sparse_mla_q8kv8_prefill_fwd, + ) + + q, kv, indices, sm_scale, q_scale, kv_scale, attn_sink, topk_length = _make_case( + d_qk=576, with_sink=False + ) + s_q = q.shape[0] + out_buf = torch.empty((s_q, H_Q, D_V), dtype=torch.bfloat16, device="cuda") + ml_buf = torch.empty((s_q, H_Q), dtype=torch.float32, device="cuda") + lse_buf = torch.empty((s_q, H_Q), dtype=torch.float32, device="cuda") + + out, ml, lse = sparse_mla_q8kv8_prefill_fwd( + q=q, + kv=kv, + indices=indices, + sm_scale=sm_scale, + q_scale=q_scale, + kv_scale=kv_scale, + d_v=D_V, + attn_sink=attn_sink, + topk_length=topk_length, + out=out_buf, + max_logits=ml_buf, + lse=lse_buf, + ) + torch.cuda.synchronize() + + assert out.data_ptr() == out_buf.data_ptr() + assert ml.data_ptr() == ml_buf.data_ptr() + assert lse.data_ptr() == lse_buf.data_ptr() + assert torch.isfinite(out.float()).all() + assert torch.isfinite(ml.float()).all() + assert torch.isfinite(lse.float()).all() + + +@pytest.mark.skipif( + not _sm90_available(), reason="Q8KV8 sparse prefill requires SM90 CUDA" +) +def test_sparse_mla_q8kv8_prefill_rejects_bad_buffers(): + """Validation: wrong shape/dtype and aliasing must raise ValueError.""" + from sglang.jit_kernel.sparse_mla_q8kv8_prefill_sm90 import ( + sparse_mla_q8kv8_prefill_fwd, + ) + + q, kv, indices, sm_scale, q_scale, kv_scale, attn_sink, topk_length = _make_case( + d_qk=576, with_sink=False + ) + s_q = q.shape[0] + + def _call(**overrides): + kwargs = dict( + q=q, + kv=kv, + indices=indices, + sm_scale=sm_scale, + q_scale=q_scale, + kv_scale=kv_scale, + d_v=D_V, + attn_sink=attn_sink, + topk_length=topk_length, + ) + kwargs.update(overrides) + return sparse_mla_q8kv8_prefill_fwd(**kwargs) + + # Wrong dtype. + bad_out = torch.empty((s_q, H_Q, D_V), dtype=torch.float16, device="cuda") + with pytest.raises(ValueError): + _call(out=bad_out) + + # Wrong shape. + bad_ml = torch.empty((s_q + 1, H_Q), dtype=torch.float32, device="cuda") + with pytest.raises(ValueError): + _call(max_logits=bad_ml) + + # Aliased max_logits / lse. + shared = torch.empty((s_q, H_Q), dtype=torch.float32, device="cuda") + with pytest.raises(ValueError): + _call(max_logits=shared, lse=shared) + + # d_v != 512. + with pytest.raises(ValueError): + _call(d_v=256) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_store_cache.py b/asian_ai/performance/SGLang/test/registered/jit/test_store_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..917977f2e682a62ed43fcd6b3441688b4ff6760c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_store_cache.py @@ -0,0 +1,133 @@ +import itertools +import sys + +import pytest +import torch + +from sglang.jit_kernel.kvcache import can_use_store_cache, store_cache +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=28, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) +register_amd_ci(est_time=55, stage="jit-kernel-unit", runner_config="amd") + +BS_LIST = [2**n for n in range(0, 15)] +BS_LIST += [x + 1 + i for i, x in enumerate(BS_LIST)] +BS_LIST = get_ci_test_range(BS_LIST, [1, 9, 256, 16399]) +HIDDEN_DIMS = get_ci_test_range( + [64, 128, 256, 512, 1024, 96, 98, 100], [64, 512, 1024, 98] +) +CACHE_SIZE = 1024 * 1024 +DTYPE = torch.bfloat16 +DEVICE = "cuda" + + +@pytest.mark.parametrize( + "batch_size,element_dim", + list(itertools.product(BS_LIST, HIDDEN_DIMS)), +) +def test_store_cache(batch_size: int, element_dim: int) -> None: + k = torch.randn((batch_size, element_dim), dtype=DTYPE, device=DEVICE) + v = torch.randn((batch_size, element_dim), dtype=DTYPE, device=DEVICE) + k_cache = torch.randn((CACHE_SIZE, element_dim), dtype=DTYPE, device=DEVICE) + v_cache = torch.randn((CACHE_SIZE, element_dim), dtype=DTYPE, device=DEVICE) + indices = torch.randperm(CACHE_SIZE, device=DEVICE)[:batch_size] + + # AOT store cache + store_cache(k, v, k_cache, v_cache, indices) + + assert torch.all(k_cache[indices] == k) + assert torch.all(v_cache[indices] == v) + + +# Smaller subset for targeted tests below +REPR_BS = get_ci_test_range([1, 7, 128], [1, 128]) +REPR_DIMS = get_ci_test_range([64, 128, 512, 1024, 96], [64, 1024, 96]) +SMALL_CACHE = 4096 + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32]) +@pytest.mark.parametrize( + "batch_size,element_dim", + list(itertools.product(REPR_BS, REPR_DIMS)), +) +def test_store_cache_dtypes( + batch_size: int, element_dim: int, dtype: torch.dtype +) -> None: + k = torch.randn((batch_size, element_dim), dtype=dtype, device=DEVICE) + v = torch.randn((batch_size, element_dim), dtype=dtype, device=DEVICE) + k_cache = torch.randn((SMALL_CACHE, element_dim), dtype=dtype, device=DEVICE) + v_cache = torch.randn((SMALL_CACHE, element_dim), dtype=dtype, device=DEVICE) + indices = torch.randperm(SMALL_CACHE, device=DEVICE)[:batch_size] + + store_cache(k, v, k_cache, v_cache, indices) + + assert torch.all(k_cache[indices] == k) + assert torch.all(v_cache[indices] == v) + + +@pytest.mark.parametrize( + "batch_size,element_dim", + list(itertools.product(REPR_BS, REPR_DIMS)), +) +def test_store_cache_int32_indices(batch_size: int, element_dim: int) -> None: + k = torch.randn((batch_size, element_dim), dtype=DTYPE, device=DEVICE) + v = torch.randn((batch_size, element_dim), dtype=DTYPE, device=DEVICE) + k_cache = torch.randn((SMALL_CACHE, element_dim), dtype=DTYPE, device=DEVICE) + v_cache = torch.randn((SMALL_CACHE, element_dim), dtype=DTYPE, device=DEVICE) + # int32 indices exercise a different CUDA template instantiation than default int64 + indices = torch.randperm(SMALL_CACHE, device=DEVICE)[:batch_size].to(torch.int32) + + store_cache(k, v, k_cache, v_cache, indices) + + assert torch.all(k_cache[indices.long()] == k) + assert torch.all(v_cache[indices.long()] == v) + + +def _valid_num_splits(element_dim: int, dtype: torch.dtype) -> list: + """Return the list of valid num_split values for a given element_dim/dtype.""" + row_bytes = element_dim * dtype.itemsize + splits = [1] + if row_bytes % (2 * 128) == 0: + splits.append(2) + if row_bytes % (4 * 128) == 0: + splits.append(4) + return splits + + +_NUM_SPLIT_CASES = [ + (_dim, _ns, _dtype) + for _dtype in [torch.float16, torch.bfloat16, torch.float32] + for _dim in REPR_DIMS + for _ns in _valid_num_splits(_dim, _dtype) +] + + +@pytest.mark.parametrize("element_dim,num_split,dtype", _NUM_SPLIT_CASES) +def test_store_cache_num_split( + element_dim: int, num_split: int, dtype: torch.dtype +) -> None: + batch_size = 128 + k = torch.randn((batch_size, element_dim), dtype=dtype, device=DEVICE) + v = torch.randn((batch_size, element_dim), dtype=dtype, device=DEVICE) + k_cache = torch.randn((SMALL_CACHE, element_dim), dtype=dtype, device=DEVICE) + v_cache = torch.randn((SMALL_CACHE, element_dim), dtype=dtype, device=DEVICE) + indices = torch.randperm(SMALL_CACHE, device=DEVICE)[:batch_size] + + # Verify each num_split kernel path (1, 2, 4) produces correct results + store_cache(k, v, k_cache, v_cache, indices, num_split=num_split) + + assert torch.all(k_cache[indices] == k) + assert torch.all(v_cache[indices] == v) + + +def test_can_use_store_cache() -> None: + assert can_use_store_cache(128) + assert can_use_store_cache(256) + assert can_use_store_cache(1024) + assert can_use_store_cache(2048) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_symm_mem_all_gather.py b/asian_ai/performance/SGLang/test/registered/jit/test_symm_mem_all_gather.py new file mode 100644 index 0000000000000000000000000000000000000000..5aad3ed9244c5b9725453bfd3e5495facdab8669 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_symm_mem_all_gather.py @@ -0,0 +1,166 @@ +"""Correctness test for the symmetric-memory multimem all-gather kernel. + +Compares ``all_gather_inner`` (concat-along-hidden multimem.st gather) against +NCCL all-gather for a sweep of token counts, hidden widths, and the +``safe`` / ``skip_entry_sync`` knobs, in both eager and CUDA-graph modes. + +Usage:: + + # Run on the default world sizes (2, 4, 8 GPUs): + python test/registered/jit/test_symm_mem_all_gather.py + # Pick a specific world size (or comma-separated list): + python test/registered/jit/test_symm_mem_all_gather.py --num-gpu 4 + python test/registered/jit/test_symm_mem_all_gather.py --num-gpu 2,4,8 + # Extra pytest args (forwarded to each torchrun worker): + python test/registered/jit/test_symm_mem_all_gather.py -k 16384 +""" + +from __future__ import annotations + +import atexit +import logging +import os + +import pytest +import torch +import torch.distributed as dist + +import sglang.srt.distributed.parallel_state as ps +from sglang.jit_kernel.tests.utils import multigpu_pytest_main +from sglang.jit_kernel.utils import cache_once, get_ci_test_range +from sglang.srt.distributed.device_communicators.triton_symm_mem_ag import ( + all_gather_inner, + create_state, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=240, stage="base-b-kernel-unit", runner_config="8-gpu-h200") +register_cuda_ci(est_time=240, suite="nightly-kernel-8-gpu-h200", nightly=True) + +# --------------------------------------------------------------------------- +# Test parameters +# --------------------------------------------------------------------------- + +# Full gathered hidden width H (per-rank shard is H / world_size). Each value +# is a multiple of 8 * 8 so it stays valid for world sizes 2 / 4 / 8. +TEST_HIDDEN = [2048, 7168, 16384] +TEST_NUM_TOKENS = [1, 8, 16, 128] +TEST_LOOP = 8 + +TEST_HIDDEN = get_ci_test_range(TEST_HIDDEN, [7168]) +TEST_NUM_TOKENS = get_ci_test_range(TEST_NUM_TOKENS, [16]) + +MAX_HIDDEN = max(TEST_HIDDEN) +MAX_TOKENS = max(TEST_NUM_TOKENS) + +# --------------------------------------------------------------------------- +# Per-rank distributed setup (run once per torchrun worker) +# --------------------------------------------------------------------------- + + +@cache_once +def _init_cpu_group_once() -> dist.ProcessGroup: + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + torch.cuda.set_device(local_rank) + dist.init_process_group(backend="gloo") + ps._WORLD = ps.init_world_group( + ranks=list(range(world_size)), + local_rank=local_rank, + backend="nccl", + ) + atexit.register(dist.destroy_process_group) + logging.disable(logging.INFO) + torch.cuda.set_stream(torch.cuda.Stream()) + cpu_group = ps._WORLD.cpu_group + assert isinstance(cpu_group, dist.ProcessGroup) + return cpu_group + + +@cache_once +def _init_nccl_group_once() -> dist.ProcessGroup: + _init_cpu_group_once() + coord = ps._WORLD + assert coord is not None and coord.device_group is not None + return coord.device_group + + +@cache_once +def _init_state_once(): + _init_cpu_group_once() + coord = ps._WORLD + return create_state( + group=coord.device_group, + rank_in_group=coord.rank_in_group, + max_tokens=MAX_TOKENS, + hidden_size=MAX_HIDDEN, + ) + + +def _nccl_all_gather(x: torch.Tensor, group: dist.ProcessGroup, world_size: int): + """Reference gather matching ``tensor_model_parallel_all_gather(dim=-1)``: + concat per-rank ``[T, H/W]`` shards in rank order into ``[T, H]``.""" + num_tokens, local_hidden = x.shape + gathered = torch.empty( + world_size * num_tokens, local_hidden, dtype=x.dtype, device=x.device + ) + dist.all_gather_into_tensor(gathered, x.contiguous(), group=group) + return ( + gathered.reshape(world_size, num_tokens, local_hidden) + .movedim(0, 1) + .reshape(num_tokens, world_size * local_hidden) + ) + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("skip_entry_sync", [False, True]) +@pytest.mark.parametrize("safe", [False, True]) +@pytest.mark.parametrize("hidden", TEST_HIDDEN) +@pytest.mark.parametrize("num_tokens", TEST_NUM_TOKENS) +@torch.inference_mode() +def test_symm_mem_all_gather( + num_tokens: int, + hidden: int, + safe: bool, + skip_entry_sync: bool, +) -> None: + nccl_group = _init_nccl_group_once() + state = _init_state_once() + world_size = state.world_size + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + + if state.symm_mem_hdl.multicast_ptr == 0: + pytest.skip(f"multimem multicast unavailable for world_size={world_size}") + + local_hidden = hidden // world_size + if hidden % world_size != 0 or local_hidden % 8 != 0: + pytest.skip(f"hidden={hidden} incompatible with world_size={world_size}") + + def gather(x: torch.Tensor) -> torch.Tensor: + return all_gather_inner( + state, + x, + tp_hidden_dim=hidden, + skip_entry_sync=skip_entry_sync, + safe=safe, + ).clone() + + for _ in range(TEST_LOOP): + # Entry barrier may be skipped on the kernel side; make sure every rank's + # input is ready and the buffer is free before the next gather. + dist.barrier(nccl_group) + x = torch.randn(num_tokens, local_hidden, dtype=torch.bfloat16, device=device) + ref = _nccl_all_gather(x, nccl_group, world_size) + out = gather(x) + # Pure copy gather: exact bitwise equality. + torch.testing.assert_close(out, ref, atol=0, rtol=0) + + +if __name__ == "__main__": + # multimem multicast needs world_size in {4, 6, 8} (cc9) or {6, 8} (cc10); + # unsupported sizes self-skip via the multicast_ptr guard above. + multigpu_pytest_main(__name__, __file__, num_gpus=(4, 8)) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_timestep_embedding.py b/asian_ai/performance/SGLang/test/registered/jit/test_timestep_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..260c1c183281964b69469ac8f3531a76a58e5296 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_timestep_embedding.py @@ -0,0 +1,183 @@ +import os +import sys + +import numpy as np +import pytest +import torch + +try: + import tabulate +except Exception: + tabulate = None + +from sglang.jit_kernel.timestep_embedding import ( + timestep_embedding as timestep_embedding_cuda, +) +from sglang.jit_kernel.utils import get_ci_test_range +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=16, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=120, suite="nightly-kernel-1-gpu", nightly=True) + +CORRECTNESS_BATCH_SIZES = get_ci_test_range( + [1, 2, 8, 128, 256, 512, 1536, 2048, 4096, 11008, 16384], + [1, 128, 2048, 16384], +) +CORRECTNESS_DIMS = get_ci_test_range( + [32, 128, 256, 512, 1536, 2048, 4096, 8192], + [32, 512, 8192], +) +DIFFUSERS_BATCH_SIZES = get_ci_test_range( + [1, 2, 8, 128, 256, 512, 1536, 2048, 16384], + [1, 512, 16384], +) +DIFFUSERS_DIMS = get_ci_test_range([32, 256, 512, 1536, 8192], [32, 512, 8192]) +DTYPES = get_ci_test_range( + [torch.float16, torch.bfloat16, torch.float32], + [torch.float16, torch.bfloat16], +) +SCALES = get_ci_test_range([1, 0.01], [1, 0.01]) + + +def get_timestep_embedding_reference( + timesteps: torch.Tensor, + dim: int, + *, + flip_sin_to_cos: bool = False, + downscale_freq_shift: float = 1, + scale: float = 1, + max_period: int = 10000, +): + assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array" + + timesteps = timesteps.to(torch.float32) + half_dim = dim // 2 + exponent = -torch.log( + torch.tensor(max_period, dtype=torch.float32, device=timesteps.device) + ) * torch.arange( + start=0, end=half_dim, dtype=torch.float32, device=timesteps.device + ) + exponent = exponent / (half_dim - downscale_freq_shift) + + emb = torch.exp(exponent) + emb = timesteps[:, None].float() * emb[None, :] + + emb = scale * emb + + emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1) + if flip_sin_to_cos: + emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1) + if dim % 2 == 1: + emb = torch.nn.functional.pad(emb, (0, 1, 0, 0)) + return emb + + +@pytest.mark.parametrize("batch_size", CORRECTNESS_BATCH_SIZES) +@pytest.mark.parametrize("dim", CORRECTNESS_DIMS) +@pytest.mark.parametrize("dtype", DTYPES) +def test_timestep_embedding_correctness_with_sgld(batch_size, dim, dtype): + device = "cuda" + t = torch.randint(low=0, high=1000, size=(batch_size,), device=device).to(dtype) + torch_output = get_timestep_embedding_reference( + t, dim, flip_sin_to_cos=True, downscale_freq_shift=0 + ) + cuda_output = timestep_embedding_cuda( + t, dim, flip_sin_to_cos=True, downscale_freq_shift=0 + ) + torch.testing.assert_close(torch_output, cuda_output, atol=1e-3, rtol=1e-3) + + +@pytest.mark.parametrize("batch_size", DIFFUSERS_BATCH_SIZES) +@pytest.mark.parametrize("dim", DIFFUSERS_DIMS) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("flip_sin_to_cos", [False, True]) +@pytest.mark.parametrize("downscale_freq_shift", [0, 1]) +@pytest.mark.parametrize("scale", SCALES) +def test_timestep_embedding_correctness_with_diffusers( + batch_size, dim, flip_sin_to_cos, downscale_freq_shift, scale, dtype +): + device = "cuda" + t = torch.randint(low=0, high=1000, size=(batch_size,), device=device).to(dtype) + torch_output = get_timestep_embedding_reference( + t, + dim, + flip_sin_to_cos=flip_sin_to_cos, + downscale_freq_shift=downscale_freq_shift, + scale=scale, + max_period=10000, + ) + cuda_output = timestep_embedding_cuda( + t, + dim, + flip_sin_to_cos=flip_sin_to_cos, + downscale_freq_shift=downscale_freq_shift, + scale=scale, + max_period=10000, + ) + torch.testing.assert_close(torch_output, cuda_output, atol=1e-3, rtol=1e-3) + + +def test_timestep_embedding_perf(): + if os.environ.get("SGLANG_RUN_JIT_KERNEL_PERF_TESTS") != "1": + pytest.skip("Perf test disabled by default") + if tabulate is None: + pytest.skip("Optional dependency 'tabulate' is not installed") + + NUM_BATCH = [1, 2, 8, 63, 256, 512, 613, 1024, 1536] + NUM_DIM = [32, 64, 128, 256, 512, 1024, 2048, 4096] + + def perf_kernel_fn(kernel_fn: callable, *args, **kwargs): + warmup_times = 4 + repeat_times = 20 + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + + for _ in range(warmup_times): + output_fn = kernel_fn(*args, **kwargs) + torch.cuda.synchronize() + + start.record() + for _ in range(repeat_times): + output_fn = kernel_fn(*args, **kwargs) + end.record() + end.synchronize() + return start.elapsed_time(end) / repeat_times + + device = "cuda" + results = [] + + cuda_speedups = [] + for B in NUM_BATCH: + for dim in NUM_DIM: + t = torch.linspace(0, max(100000, B), steps=B, device=device).to( + torch.float32 + ) + time_torch = perf_kernel_fn(get_timestep_embedding_reference, t, dim) + time_cuda = perf_kernel_fn(timestep_embedding_cuda, t, dim) + speedup_cuda = time_torch / time_cuda + + results.append( + { + "Batch Size": B, + "Dimension": dim, + "Torch Time (ms)": time_torch, + "CUDA Time (ms)": time_cuda, + "Speedup (CUDA)": speedup_cuda, + } + ) + cuda_speedups.append(speedup_cuda) + + print("=== Timestep Embedding Benchmark Results ===") + print( + tabulate.tabulate( + results, + headers="keys", + tablefmt="fancy_grid", + floatfmt=(".0f", ".0f", ".6f", ".6f", ".5f"), + ) + ) + print(f"Average Speedup(cuda): {np.mean(cuda_speedups):.4f}") + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/asian_ai/performance/SGLang/test/registered/jit/test_tp_qknorm.py b/asian_ai/performance/SGLang/test/registered/jit/test_tp_qknorm.py new file mode 100644 index 0000000000000000000000000000000000000000..ca6441c28bfede9297e75a59ce785b6e0a06902c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/jit/test_tp_qknorm.py @@ -0,0 +1,197 @@ +from __future__ import annotations + +import atexit +import itertools +import logging +import multiprocessing +import os +from multiprocessing.context import SpawnProcess +from typing import List + +import pytest +import torch +import torch.distributed as dist +import triton + +import sglang.srt.distributed.parallel_state as ps +from sglang.jit_kernel.all_reduce import ( + _jit_custom_all_reduce_push_module, + _jit_fused_parallel_qknorm_module, + fused_parallel_qknorm, +) +from sglang.jit_kernel.mp import register_comm_cleanup +from sglang.jit_kernel.tests.utils import multigpu_pytest_main +from sglang.jit_kernel.utils import cache_once +from sglang.srt.distributed.device_communicators.custom_all_reduce_v2 import ( + CustomAllReduceV2, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=300, + stage="base-b-kernel-unit", + runner_config="8-gpu-h200", +) +register_cuda_ci( + est_time=300, + suite="nightly-kernel-8-gpu-h200", + nightly=True, +) + + +# --------------------------------------------------------------------------- +# Test parameters +# --------------------------------------------------------------------------- + +Q_K_DIMS = [(6144, 1024)] +EPS = 1e-6 +BATCH_SIZES = [2**n for n in range(0, 14)] +DTYPES = [torch.float16, torch.bfloat16, torch.float32] + + +# --------------------------------------------------------------------------- +# Parallel JIT precompile (outer process, before any torchrun child starts) +# --------------------------------------------------------------------------- + + +def _compile_one(dtype: torch.dtype, world_size: int) -> None: + """Compile every kernel this test touches for one (dtype, world_size). + + Top-level so it survives ``spawn`` pickling. Compiled artifacts are + cached on disk by ``tvm_ffi``; torchrun children will reuse them. + """ + _jit_custom_all_reduce_push_module(dtype, world_size) + for q_dim, k_dim in Q_K_DIMS: + _jit_fused_parallel_qknorm_module(dtype, world_size, q_dim, k_dim) + + +def _precompile_kernels(num_gpus: List[int]) -> None: + ctx = multiprocessing.get_context("spawn") + procs: list[tuple[torch.dtype, int, SpawnProcess]] = [] + for dtype, world_size in itertools.product(DTYPES, num_gpus): + p = ctx.Process(target=_compile_one, args=(dtype, world_size)) + p.start() + procs.append((dtype, world_size, p)) + for dtype, world_size, p in procs: + p.join() + if p.exitcode != 0: + raise RuntimeError( + f"TP QKNorm precompile failed for {dtype=} {world_size=} " + f"(exit {p.exitcode})" + ) + + +# --------------------------------------------------------------------------- +# Per-rank distributed setup (run once per torchrun worker) +# --------------------------------------------------------------------------- + + +@cache_once +def _init_cpu_group_once() -> dist.ProcessGroup: + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + torch.cuda.set_device(local_rank) + dist.init_process_group(backend="gloo") + ps._WORLD = coord = ps.init_world_group( + ranks=list(range(world_size)), + local_rank=local_rank, + backend="nccl", + ) + atexit.register(dist.destroy_process_group) + cpu_group = coord.cpu_group + assert isinstance(cpu_group, dist.ProcessGroup) + logging.disable(logging.INFO) + torch.cuda.set_stream(torch.cuda.Stream()) + return cpu_group + + +@cache_once +def _init_nccl_group_once() -> dist.ProcessGroup: + _init_cpu_group_once() + coord = ps._WORLD + assert coord is not None and coord.device_group is not None + return coord.device_group + + +@cache_once +def _init_comm_once() -> CustomAllReduceV2: + cpu_group = _init_cpu_group_once() + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + max_pull_size = 0 + max_push_size = 8 * max(BATCH_SIZES) + comm = CustomAllReduceV2(cpu_group, device, max_pull_size, max_push_size) + if comm.disabled: + raise RuntimeError("JIT CustomAllReduceV2 is disabled on this system") + register_comm_cleanup(comm) + return comm + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _all_gather_cat(x: torch.Tensor, group: dist.ProcessGroup) -> torch.Tensor: + gathered = [torch.empty_like(x) for _ in range(dist.get_world_size(group=group))] + dist.all_gather(gathered, x, group=group) + return torch.cat(gathered, dim=-1) + + +def _rmsnorm_ref(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: + x_fp32 = x.float() + scale = (x_fp32.pow(2).mean(dim=-1, keepdim=True) + eps).rsqrt() + return (x_fp32 * scale * weight.float()).to(x.dtype) + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("batch_size", BATCH_SIZES) +@pytest.mark.parametrize("q_k_dim", Q_K_DIMS) +@torch.inference_mode() +def test_tp_qknorm( + q_k_dim: tuple[int, int], + batch_size: int, + dtype: torch.dtype, +) -> None: + nccl_group = _init_nccl_group_once() + comm = _init_comm_once() + rank = dist.get_rank(group=nccl_group) + world_size = dist.get_world_size(group=nccl_group) + device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}") + + q_dim, k_dim = q_k_dim + local_q_dim = q_dim // world_size + local_k_dim = k_dim // world_size + + q = torch.randn(batch_size, local_q_dim, device=device, dtype=dtype) + k = torch.randn(batch_size, local_k_dim, device=device, dtype=dtype) + q_weight = torch.randn(local_q_dim, device=device, dtype=dtype) + k_weight = torch.randn(local_k_dim, device=device, dtype=dtype) + + q_ref = _all_gather_cat(q, nccl_group) + k_ref = _all_gather_cat(k, nccl_group) + q_weight_ref = _all_gather_cat(q_weight.unsqueeze(0), nccl_group).squeeze(0) + k_weight_ref = _all_gather_cat(k_weight.unsqueeze(0), nccl_group).squeeze(0) + + q_expected = _rmsnorm_ref(q_ref, q_weight_ref, EPS) + k_expected = _rmsnorm_ref(k_ref, k_weight_ref, EPS) + q_expected = q_expected[:, rank * local_q_dim : (rank + 1) * local_q_dim] + k_expected = k_expected[:, rank * local_k_dim : (rank + 1) * local_k_dim] + + fused_parallel_qknorm(comm.obj, q, k, q_weight, k_weight, EPS) + + triton.testing.assert_close(q, q_expected, atol=1e-2, rtol=1e-2) + triton.testing.assert_close(k, k_expected, atol=1e-2, rtol=1e-2) + + +if __name__ == "__main__": + multigpu_pytest_main( + __name__, + __file__, + num_gpus=(2, 4, 8), + pre_launch_fn=_precompile_kernels, + ) diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_cp_prefix_len_fa3_parity.py b/asian_ai/performance/SGLang/test/registered/kernels/test_cp_prefix_len_fa3_parity.py new file mode 100644 index 0000000000000000000000000000000000000000..f8585a904c69ee5a33f2eaf0c1f827b1fc60bccf --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_cp_prefix_len_fa3_parity.py @@ -0,0 +1,143 @@ +""" +FA3 parity test for `prepare_context_parallel_metadata`. + +Drives the real function and feeds its `kv_len_prev/next_tensor` into FA3 +via `flash_attn_with_kvcache`. Compares per-rank CP output against a +full-sequence FA3 reference computed over the unpadded `(prefix + extend)` +KV. Any discrepancy indicates the metadata function emitted wrong +`cache_seqlens` for at least one rank. +""" + +import unittest +from unittest.mock import patch + +import torch + +from sglang.srt.layers.utils.cp_utils import prepare_context_parallel_metadata +from sglang.srt.utils.common import ceil_align +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=5, stage="extra-a", runner_config="1-gpu-large") + +_DSA_UTILS = "sglang.srt.layers.attention.dsa.utils" +_DEVICE = "cuda" +_DTYPE = torch.bfloat16 +_HEAD_NUM = 8 +_HEAD_DIM = 128 +_SCALE = _HEAD_DIM**-0.5 + + +class TestCPPrefixLenFA3Parity(CustomTestCase): + """Per-rank FA3 output under CP must match a full-sequence reference.""" + + def _run_parity(self, prefix_len: int, extend_len: int, cp_size: int): + from sgl_kernel.flash_attn import flash_attn_with_kvcache + + torch.manual_seed(extend_len * 1_000_003 + prefix_len * 101 + cp_size) + + padded_extend = ceil_align(extend_len, cp_size) + pad = padded_extend - extend_len + self.assertGreaterEqual( + padded_extend, + 2 * cp_size, + "runtime `can_cp_split` would skip this case; pick a larger extend", + ) + + # Reference: one full-sequence FA3 call over the unpadded KV. + q_full = torch.randn( + extend_len, _HEAD_NUM, _HEAD_DIM, device=_DEVICE, dtype=_DTYPE + ) + k_full = torch.randn( + prefix_len + extend_len, _HEAD_NUM, _HEAD_DIM, device=_DEVICE, dtype=_DTYPE + ) + v_full = torch.randn( + prefix_len + extend_len, _HEAD_NUM, _HEAD_DIM, device=_DEVICE, dtype=_DTYPE + ) + ref = flash_attn_with_kvcache( + q=q_full.unsqueeze(0), + k_cache=k_full.unsqueeze(0), + v_cache=v_full.unsqueeze(0), + cache_seqlens=torch.tensor( + [k_full.shape[0]], dtype=torch.int32, device=_DEVICE + ), + softmax_scale=_SCALE, + causal=True, + ).squeeze(0) + + # CP path sees tensors padded to `ceil_align(extend, cp_size)`, + # matching what `prepare_mlp_sync_batch` does in production. + zeros = torch.zeros(pad, _HEAD_NUM, _HEAD_DIM, device=_DEVICE, dtype=_DTYPE) + q_padded = torch.cat([q_full, zeros], dim=0) + k_padded = torch.cat([k_full, zeros], dim=0) + v_padded = torch.cat([v_full, zeros], dim=0) + + seqs_len = [prefix_len + extend_len] + extend_lens = [extend_len] + + def _call_meta(rank: int): + return prepare_context_parallel_metadata( + padded_extend, rank, cp_size, seqs_len, extend_seqs_len=extend_lens + ) + + # Exercise the non-DSA branch; the DSA branch uses a separate + # `prefix_len` pathway re-added by `_get_topk_ragged_with_cp`. + with ( + patch(f"{_DSA_UTILS}.is_dsa_enable_prefill_cp", return_value=False), + patch( + f"{_DSA_UTILS}.is_dsa_prefill_cp_round_robin_split", + return_value=False, + ), + ): + meta0 = _call_meta(0) + cp_segment_num = 2 * cp_size + blocks_q = list(torch.split(q_padded, meta0.split_list, dim=0)) + outs = [None] * cp_segment_num + + for rank in range(cp_size): + meta = meta0 if rank == 0 else _call_meta(rank) + for idx, cs_tensor in ( + (rank, meta.kv_len_prev_tensor), + (cp_size * 2 - rank - 1, meta.kv_len_next_tensor), + ): + if meta0.split_list[idx] == 0: + outs[idx] = torch.empty( + 0, _HEAD_NUM, _HEAD_DIM, device=_DEVICE, dtype=_DTYPE + ) + continue + outs[idx] = flash_attn_with_kvcache( + q=blocks_q[idx].unsqueeze(0), + k_cache=k_padded.unsqueeze(0), + v_cache=v_padded.unsqueeze(0), + cache_seqlens=cs_tensor, + softmax_scale=_SCALE, + causal=True, + ).squeeze(0) + + cp_out = torch.cat(outs, dim=0) + err = (cp_out[:extend_len].float() - ref.float()).abs().max().item() + + self.assertLess( + err, + 1e-2, + f"CP output diverges from full-sequence FA3 reference by " + f"max_err={err:.5f} " + f"(prefix_len={prefix_len}, extend_len={extend_len}, " + f"cp_size={cp_size}, pad={pad})", + ) + + def test_cp2_prefix1_extend3(self): + """cp_size=2, prefix_len=1, extend_len=3 (pad=1).""" + self._run_parity(prefix_len=1, extend_len=3, cp_size=2) + + def test_cp4_prefix1_extend7(self): + """cp_size=4, prefix_len=1, extend_len=7 (pad=1).""" + self._run_parity(prefix_len=1, extend_len=7, cp_size=4) + + def test_cp8_prefix1_extend17(self): + """cp_size=8, prefix_len=1, extend_len=17 (pad=7).""" + self._run_parity(prefix_len=1, extend_len=17, cp_size=8) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_dsa_indexer.py b/asian_ai/performance/SGLang/test/registered/kernels/test_dsa_indexer.py new file mode 100644 index 0000000000000000000000000000000000000000..339ad19ba33ef3979d2ada84e09320477b54d36a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_dsa_indexer.py @@ -0,0 +1,1046 @@ +import unittest +from typing import List, Optional, Tuple +from unittest.mock import MagicMock, patch + +import torch + +from sglang.srt.environ import envs +from sglang.srt.runtime_context import get_parallel +from sglang.test.ci.ci_register import register_cuda_ci + +_parallel_override = get_parallel().override(attn_tp_size=1) +_parallel_override.__enter__() + +from sglang.srt.configs.model_config import AttentionArch +from sglang.srt.layers.attention.dsa.dsa_indexer import ( + BaseIndexerMetadata, + Indexer, + rotate_activation, +) +from sglang.srt.layers.attention.dsa.dsa_topk_backend import ( + DSATopKBackend, + TopkTransformMethod, +) +from sglang.srt.layers.attention.dsa_backend import ( + DeepseekSparseAttnBackend, + DSAIndexerMetadata, + DSAMetadata, +) +from sglang.srt.layers.layernorm import LayerNorm +from sglang.srt.layers.linear import LinearBase +from sglang.srt.mem_cache.memory_pool import DSATokenToKVPool +from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode +from sglang.srt.server_args import ServerArgs, set_global_server_args_for_scheduler +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=18, stage="base-b", runner_config="1-gpu-large") + +# Global configuration for all indexer tests +DEFAULT_CONFIG = { + "device": "cuda", + "dtype": torch.bfloat16, + "kv_cache_dtype": torch.float8_e4m3fn, + "context_len": 2048, + "max_bs": 64, + "hidden_size": 5120, + "index_n_heads": 32, + "index_head_dim": 128, + "rope_head_dim": 64, + "index_topk": 64, + "q_lora_rank": 1536, + "kv_lora_rank": 512, + "qk_rope_head_dim": 64, + "qk_nope_head_dim": 128, + "max_position_embeddings": 163840, + "rope_theta": 10000.0, + "layer_id": 0, + "page_size": 64, +} + + +class MockIndexerMetadata(BaseIndexerMetadata): + """Mock implementation of BaseIndexerMetadata for testing.""" + + def __init__(self, batch_size, seq_lens, page_table=None): + self.batch_size = batch_size + self.seq_lens = seq_lens + self.page_table = page_table + self.device = "cuda" + + def get_seqlens_int32(self) -> torch.Tensor: + """Return: (batch_size,) int32 tensor""" + return torch.tensor(self.seq_lens, dtype=torch.int32, device=self.device) + + def get_page_table_64(self) -> torch.Tensor: + """Return: (batch_size, num_blocks) int32, page table with page size 64.""" + if self.page_table is not None: + return self.page_table + # Create a simple page table for testing + max_seq_len = max(self.seq_lens) + num_blocks = (max_seq_len + 63) // 64 # Round up to page size 64 + page_table = torch.zeros( + (self.batch_size, num_blocks), dtype=torch.int32, device=self.device + ) + for i in range(self.batch_size): + # Simple linear mapping: block i maps to page i + num_blocks_needed = (self.seq_lens[i] + 63) // 64 + page_table[i, :num_blocks_needed] = torch.arange( + num_blocks_needed, device=self.device + ) + return page_table + + def get_page_table_1(self) -> torch.Tensor: + """Return: (batch_size, num_blocks) int32, page table with page size 1.""" + # Create a simple page table for testing with page size 1 + max_seq_len = max(self.seq_lens) + num_blocks = max_seq_len # Page size 1 means num_blocks == max_seq_len + page_table = torch.zeros( + (self.batch_size, num_blocks), dtype=torch.int32, device=self.device + ) + for i in range(self.batch_size): + # Simple linear mapping: block i maps to page i + num_blocks_needed = self.seq_lens[i] + page_table[i, :num_blocks_needed] = torch.arange( + num_blocks_needed, device=self.device + ) + return page_table + + def get_seqlens_expanded(self) -> torch.Tensor: + """Return: (sum_extend_seq_len,) int32 tensor""" + # For extend mode, each new token attends to progressively more tokens + # For a sequence being extended from position 0 to seq_len, token i attends to i+1 tokens + result = [] + for seq_len in self.seq_lens: + result.extend(range(1, seq_len + 1)) + return torch.tensor(result, dtype=torch.int32, device=self.device) + + def get_indexer_kvcache_range(self) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Return: (tokens, ), (tokens, ) int32, k_start and k_end in kv cache for each token. + For extend mode, token i attends to tokens [0, i]. + """ + ks_list = [] + ke_list = [] + k_offset = 0 + for seq_len in self.seq_lens: + # For a sequence being extended from position 0 to seq_len + # Token i attends to [k_offset, k_offset + i + 1) + ks = torch.full((seq_len,), k_offset, dtype=torch.int32, device=self.device) + ke = torch.arange( + k_offset + 1, + k_offset + seq_len + 1, + dtype=torch.int32, + device=self.device, + ) + ks_list.append(ks) + ke_list.append(ke) + k_offset += seq_len + return torch.cat(ks_list, dim=0), torch.cat(ke_list, dim=0) + + def get_indexer_seq_len_cpu(self) -> torch.Tensor: + """Return: seq lens for each batch.""" + return torch.tensor(self.seq_lens, dtype=torch.int32, device="cpu") + + def get_indexer_seq_len(self) -> torch.Tensor: + """Return: seq lens for each batch.""" + return torch.tensor(self.seq_lens, dtype=torch.int32, device=self.device) + + def get_dsa_extend_len_cpu(self) -> List[int]: + """ + Return: extend seq lens for each batch. + """ + return list(self.seq_lens) + + def get_token_to_batch_idx(self) -> torch.Tensor: + """Return: batch idx for each token.""" + result = [] + for batch_idx, seq_len in enumerate(self.seq_lens): + result.extend([batch_idx] * seq_len) + return torch.tensor(result, dtype=torch.int32, device=self.device) + + def topk_transform( + self, + logits: torch.Tensor, + topk: int, + ks: Optional[torch.Tensor] = None, + cu_seqlens_q: Optional[torch.Tensor] = None, + ke_offset: Optional[torch.Tensor] = None, + batch_idx_list: Optional[torch.Tensor] = None, + topk_indices_offset_override: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """ + Perform topk selection on the logits. + For testing, just return the topk indices. + """ + return torch.topk(logits, k=topk, dim=-1).indices + + +class MockModelRunner: + def __init__(self, config=None): + self.device = "cuda" + self.config = {**DEFAULT_CONFIG, **(config or {})} + self.dtype = self.config["dtype"] + self.kv_cache_dtype = self.config["kv_cache_dtype"] + self.is_hybrid_swa = False + + # Model configuration + attention_arch = AttentionArch.MLA + max_context_len = self.config["context_len"] + max_batch_size = self.config["max_bs"] + + # Create mock hf_config for DSA - instantiate it as an object, not a type + hf_config = type( + "HfConfig", + (), + { + "architectures": ["DeepseekV3ForCausalLM"], + "index_topk": self.config["index_topk"], + "index_head_dim": self.config["index_head_dim"], + "index_n_heads": self.config["index_n_heads"], + }, + )() + + self.model_config = type( + "ModelConfig", + (), + { + "context_len": max_context_len, + "is_multimodal": False, + "attention_arch": attention_arch, + "num_attention_heads": 128, + "kv_lora_rank": self.config["kv_lora_rank"], + "qk_rope_head_dim": self.config["qk_rope_head_dim"], + "qk_nope_head_dim": self.config["qk_nope_head_dim"], + "hf_config": hf_config, + }, + )() + + self.sliding_window_size = None + self.page_size = self.config["page_size"] + + # Create req_to_token_pool + self.req_to_token_pool = type( + "TokenPool", + (), + { + "size": max_batch_size, + "req_to_token": torch.zeros( + max_batch_size, + max_context_len, + dtype=torch.int32, + device=self.device, + ), + }, + )() + + # Create DSATokenToKVPool + max_total_num_tokens = max_batch_size * max_context_len + self.token_to_kv_pool = DSATokenToKVPool( + size=max_total_num_tokens, + page_size=self.config["page_size"], + dtype=self.config["kv_cache_dtype"], + kv_lora_rank=self.config["kv_lora_rank"], + qk_rope_head_dim=self.config["qk_rope_head_dim"], + layer_num=1, + device=self.device, + index_head_dim=self.config["index_head_dim"], + enable_memory_saver=False, + kv_cache_dim=self.config["kv_lora_rank"] + self.config["qk_rope_head_dim"], + ) + + # Required by backend with DSA-specific attributes + self.server_args = type( + "ServerArgs", + (), + { + "kv_cache_dtype": "auto", + "speculative_eagle_topk": None, + "speculative_num_draft_tokens": 0, + "enable_deterministic_inference": False, + "dsa_prefill_backend": "flashmla_sparse", + "dsa_decode_backend": "fa3", + "dsa_topk_backend": "sgl-kernel", + }, + )() + self.hisparse_coordinator = None + + +@unittest.skipIf(not torch.cuda.is_available(), "Test requires CUDA") +class TestDSAIndexer(CustomTestCase): + @classmethod + def setUpClass(cls): + """Set up global server args for testing.""" + server_args = ServerArgs(model_path="dummy") + server_args.enable_dp_attention = False + server_args.dsa_prefill_backend = "flashmla_sparse" + server_args.dsa_decode_backend = "flashmla_sparse" + set_global_server_args_for_scheduler(server_args) + + # Check GPU capability for FP8 + if torch.cuda.is_available(): + compute_capability = torch.cuda.get_device_capability() + cls.supports_fp8 = compute_capability[0] >= 9 # Hopper or newer + + @classmethod + def tearDownClass(cls): + """Clean up after all tests.""" + pass + + def setUp(self): + # Test parameters + self.batch_size = 2 + self.seq_len = 128 + self.config = DEFAULT_CONFIG.copy() + self.device = "cuda" + self.dtype = torch.bfloat16 + + def _init_model_runner(self, config_override=None): + """Initialize model runner with optional config override.""" + config = self.config.copy() + if config_override: + config.update(config_override) + self.model_runner = MockModelRunner(config) + self.backend = DeepseekSparseAttnBackend(self.model_runner) + + def _create_indexer(self, **kwargs): + """Create an Indexer instance with default parameters.""" + params = { + "hidden_size": self.config["hidden_size"], + "index_n_heads": self.config["index_n_heads"], + "index_head_dim": self.config["index_head_dim"], + "rope_head_dim": self.config["rope_head_dim"], + "index_topk": self.config["index_topk"], + "q_lora_rank": self.config["q_lora_rank"], + "max_position_embeddings": self.config["max_position_embeddings"], + "rope_theta": self.config["rope_theta"], + "layer_id": self.config["layer_id"], + "scale_fmt": "ue8m0", + "block_size": 128, + "quant_config": None, # No quantization for testing + } + params.update(kwargs) + + torch.set_default_dtype(self.dtype) + with torch.device(self.device): + indexer = Indexer(**params) + indexer = indexer.to(device=self.device) + + # Convert linear layer weights to bfloat16 (but preserve LayerNorm's float32 + # and weights_proj's float32 - it uses params_dtype=torch.float32 in production) + # Need to recursively convert LinearBase submodules (like ReplicatedLinear) + for name, module in indexer.named_modules(): + # Check for LinearBase (parent of ReplicatedLinear) but exclude LayerNorm + # Also exclude weights_proj which uses float32 params in production + if isinstance(module, LinearBase) and not isinstance(module, LayerNorm): + if "weights_proj" not in name: + module.to(dtype=self.dtype) + + return indexer + + def _create_forward_batch( + self, mode, batch_size=None, seq_len=None, extend_len=None + ): + """Create a forward batch for testing.""" + batch_size = batch_size or self.batch_size + seq_len = seq_len or self.seq_len + + if mode == ForwardMode.EXTEND: + q_len = extend_len or seq_len + total_len = seq_len + + forward_batch = ForwardBatch( + batch_size=batch_size, + input_ids=torch.randint( + 0, 100, (batch_size, q_len), device=self.device + ), + out_cache_loc=torch.arange( + batch_size * (total_len - q_len), + batch_size * total_len, + device=self.device, + ), + seq_lens_sum=batch_size * total_len, + forward_mode=mode, + req_pool_indices=torch.arange(batch_size, device=self.device), + seq_lens=torch.tensor([total_len] * batch_size, device=self.device), + seq_lens_cpu=torch.tensor([total_len] * batch_size, device="cpu"), + extend_prefix_lens=torch.tensor( + [total_len - q_len] * batch_size, device=self.device + ), + extend_prefix_lens_cpu=torch.tensor( + [total_len - q_len] * batch_size, device="cpu" + ), + extend_seq_lens=torch.tensor([q_len] * batch_size, device=self.device), + extend_seq_lens_cpu=torch.tensor([q_len] * batch_size, device="cpu"), + ) + else: # ForwardMode.DECODE + decode_len = 1 + total_len = seq_len + decode_len + + forward_batch = ForwardBatch( + batch_size=batch_size, + input_ids=torch.randint( + 0, 100, (batch_size, decode_len), device=self.device + ), + out_cache_loc=torch.arange( + batch_size * seq_len, batch_size * total_len, device=self.device + ), + seq_lens_sum=batch_size * total_len, + forward_mode=mode, + req_pool_indices=torch.arange(batch_size, device=self.device), + seq_lens=torch.tensor([total_len] * batch_size, device=self.device), + seq_lens_cpu=torch.tensor([total_len] * batch_size, device="cpu"), + ) + + # Pool refs + attn_backend are now resolved via the ForwardContext; + # publish ``self.backend`` for the duration of this fixture call so + # ``get_attn_backend()`` / ``get_token_to_kv_pool()`` / + # ``get_req_to_token_pool()`` resolve correctly. + from sglang.srt.model_executor.forward_context import ( + ForwardContext, + set_forward_context, + ) + + set_forward_context(ForwardContext(attn_backend=self.backend)) + + # Mock write to req_to_token_pool + page_size = self.model_runner.page_size + for i in range(batch_size): + seq_length = total_len + for j in range(seq_length): + self.model_runner.req_to_token_pool.req_to_token[i, j] = ( + i * seq_length + j + page_size + ) + + return forward_batch + + def _verify_topk_output(self, topk_indices, batch_size, q_len, topk): + """Verify the topk indices output shape and basic properties.""" + self.assertIsNotNone(topk_indices) + self.assertEqual(topk_indices.device.type, "cuda") + + # Check shape - should be (total_q_len, topk_padded) + # where topk_padded is aligned to 2048 + self.assertEqual(len(topk_indices.shape), 2) + self.assertEqual(topk_indices.shape[0], batch_size * q_len) + + # Check that topk is padded to at least topk + self.assertGreaterEqual(topk_indices.shape[1], topk) + + # Check for padding values (-1) + has_padding = (topk_indices == -1).any() + self.assertTrue( + has_padding or topk_indices.shape[1] == topk, + "Output should have padding or exact topk size", + ) + + def _make_tie_free_logits( + self, batch_size: int, max_score_len: int + ) -> torch.Tensor: + perm = torch.argsort( + torch.randn( + batch_size, max_score_len, dtype=torch.float32, device=self.device + ), + dim=-1, + ) + return torch.gather( + torch.arange(max_score_len, device=self.device, dtype=torch.float32) + .unsqueeze(0) + .expand(batch_size, -1), + dim=1, + index=perm, + ) + + def _run_unfused_topk_backend_validity_test( + self, + batch_size: int, + max_score_len: int, + topk: int, + topk_backend: DSATopKBackend, + with_row_starts: bool, + ): + logits = self._make_tie_free_logits(batch_size, max_score_len) + + if with_row_starts: + row_starts = torch.randint( + 0, + max_score_len - 1, + (batch_size,), + dtype=torch.int32, + device=self.device, + ) + max_lengths = max_score_len - row_starts + random_lengths = torch.randint( + 0, + max_score_len - 1, + (batch_size,), + dtype=torch.int32, + device=self.device, + ) + seq_lens_expanded = torch.minimum(max_lengths, random_lengths) + else: + row_starts = None + seq_lens_expanded = torch.randint( + 0, + max_score_len - 1, + (batch_size,), + dtype=torch.int32, + device=self.device, + ) + + seq_lens_expanded = seq_lens_expanded.to(dtype=torch.int32, device=self.device) + max_seq_len_k = int(seq_lens_expanded.max().item()) + cu_seqlens_q = torch.arange( + batch_size + 1, dtype=torch.int32, device=self.device + ) + dsa_cu_seqlens_k = torch.zeros( + batch_size + 1, dtype=torch.int32, device=self.device + ) + dsa_cu_seqlens_k[1:] = torch.cumsum(seq_lens_expanded, dim=0) + page_table_1 = ( + torch.arange(max_seq_len_k, dtype=torch.int32, device=self.device) + .unsqueeze(0) + .expand(batch_size, -1) + .contiguous() + ) + metadata = DSAIndexerMetadata( + attn_metadata=DSAMetadata( + page_size=1, + cache_seqlens_int32=seq_lens_expanded.clone(), + max_seq_len_q=1, + max_seq_len_k=max_seq_len_k, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_q.clone(), + page_table_1=page_table_1, + real_page_table=page_table_1, + dsa_cache_seqlens_int32=seq_lens_expanded.clone(), + dsa_cu_seqlens_q=cu_seqlens_q.clone(), + dsa_cu_seqlens_k=dsa_cu_seqlens_k, + dsa_extend_seq_lens_list=seq_lens_expanded.cpu().tolist(), + dsa_seqlens_expanded=seq_lens_expanded, + ), + topk_transform_method=TopkTransformMethod.PAGED, + topk_backend=topk_backend, + ) + + with envs.SGLANG_DSA_FUSE_TOPK.override(False): + topk_test = metadata.topk_transform(logits, topk, ks=row_starts) + self.assertEqual(topk_test.shape, (batch_size, topk)) + self.assertEqual(topk_test.dtype, torch.int32) + expected_valid = torch.minimum( + seq_lens_expanded, + torch.full_like(seq_lens_expanded, topk), + ) + actual_valid = (topk_test >= 0).sum(dim=-1).to(torch.int32) + self.assertTrue(torch.equal(actual_valid, expected_valid)) + + starts = ( + row_starts.to(torch.int32) + if row_starts is not None + else torch.zeros( + (topk_test.shape[0],), dtype=torch.int32, device=topk_test.device + ) + ) + for row in range(topk_test.shape[0]): + test_row = topk_test[row] + valid_test = test_row[test_row >= 0] + expected_k = int(expected_valid[row].item()) + self.assertEqual(valid_test.numel(), expected_k) + if expected_k == 0: + continue + start = int(starts[row].item()) + row_len = int(seq_lens_expanded[row].item()) + self.assertTrue(torch.all((valid_test >= 0) & (valid_test < row_len))) + self.assertEqual(torch.unique(valid_test).numel(), valid_test.numel()) + + row_scores = logits[row, start : start + row_len] + ref_topk = torch.topk(row_scores, expected_k, dim=-1, sorted=False).indices + self.assertTrue( + torch.equal( + torch.sort(valid_test.to(torch.int32)).values, + torch.sort(ref_topk.to(torch.int32)).values, + ) + ) + + def _run_fused_topk_backend_equivalence_test( + self, + batch_size: int, + max_score_len: int, + topk: int, + topk_transform_method: TopkTransformMethod, + with_row_starts: bool, + query_lens: Optional[List[int]] = None, + ): + num_rows = sum(query_lens) if query_lens is not None else batch_size + logits = self._make_tie_free_logits(num_rows, max_score_len) + + if with_row_starts: + row_starts = torch.randint( + 0, + max_score_len - 1, + (num_rows,), + dtype=torch.int32, + device=self.device, + ) + max_lengths = max_score_len - row_starts + random_lengths = torch.randint( + 1, + max_score_len, + (num_rows,), + dtype=torch.int32, + device=self.device, + ) + seq_lens_expanded = torch.minimum(max_lengths, random_lengths) + else: + row_starts = None + seq_lens_expanded = torch.randint( + 1, + max_score_len, + (num_rows,), + dtype=torch.int32, + device=self.device, + ) + + topk_indices_offset = ( + torch.arange(num_rows, dtype=torch.int32, device=self.device) + * max_score_len + ) + if query_lens is None: + cu_seqlens_q = torch.arange( + batch_size + 1, dtype=torch.int32, device=self.device + ) + q_lens = None + batch_idx_list = None + else: + q_lens = torch.tensor(query_lens, dtype=torch.int32, device=self.device) + cu_seqlens_q = torch.zeros( + batch_size + 1, dtype=torch.int32, device=self.device + ) + cu_seqlens_q[1:] = torch.cumsum(q_lens, dim=0) + batch_idx_list = list(range(batch_size)) + cu_seqlens_k = torch.zeros( + batch_size + 1, dtype=torch.int32, device=self.device + ) + dsa_cu_seqlens_k = torch.zeros( + num_rows + 1, dtype=torch.int32, device=self.device + ) + dsa_cu_seqlens_k[1:] = torch.cumsum(seq_lens_expanded, dim=0) + + page_table_1 = ( + ( + torch.arange(max_score_len, dtype=torch.int32, device=self.device) + .unsqueeze(0) + .expand(batch_size, -1) + ) + + ( + torch.arange( + batch_size, dtype=torch.int32, device=self.device + ).unsqueeze(1) + * max_score_len + ) + ).contiguous() + + attn_metadata = DSAMetadata( + page_size=1, + cache_seqlens_int32=seq_lens_expanded.clone(), + max_seq_len_q=1, + max_seq_len_k=max_score_len, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + page_table_1=page_table_1, + real_page_table=page_table_1, + dsa_cache_seqlens_int32=seq_lens_expanded.clone(), + dsa_cu_seqlens_q=cu_seqlens_q.clone(), + dsa_cu_seqlens_k=dsa_cu_seqlens_k, + dsa_extend_seq_lens_list=seq_lens_expanded.cpu().tolist(), + dsa_seqlens_expanded=seq_lens_expanded, + topk_indices_offset=( + topk_indices_offset + if topk_transform_method == TopkTransformMethod.RAGGED + else None + ), + ) + + metadata_sgl = DSAIndexerMetadata( + attn_metadata=attn_metadata, + topk_transform_method=topk_transform_method, + topk_backend=DSATopKBackend.SGL_KERNEL, + ) + metadata_flashinfer = DSAIndexerMetadata( + attn_metadata=attn_metadata, + topk_transform_method=topk_transform_method, + topk_backend=DSATopKBackend.FLASHINFER, + ) + + with envs.SGLANG_DSA_FUSE_TOPK.override(True): + out_sgl = metadata_sgl.topk_transform( + logits, + topk, + ks=row_starts, + cu_seqlens_q=q_lens, + batch_idx_list=batch_idx_list, + ) + out_flashinfer = metadata_flashinfer.topk_transform( + logits, + topk, + ks=row_starts, + cu_seqlens_q=q_lens, + batch_idx_list=batch_idx_list, + ) + + self.assertEqual(out_sgl.shape, out_flashinfer.shape) + self.assertEqual(out_sgl.dtype, out_flashinfer.dtype) + self.assertEqual(out_sgl.dtype, torch.int32) + + self.assertTrue( + torch.equal( + torch.sort(out_sgl, dim=-1).values, + torch.sort(out_flashinfer, dim=-1).values, + ) + ) + + @patch("sglang.srt.layers.attention.dsa.dsa_indexer.deep_gemm") + def test_indexer_basic_creation(self, mock_deep_gemm): + """Test basic indexer creation and initialization.""" + mock_deep_gemm.get_num_sms.return_value = 132 + + indexer = self._create_indexer() + + self.assertEqual(indexer.hidden_size, self.config["hidden_size"]) + self.assertEqual(indexer.n_heads, self.config["index_n_heads"]) + self.assertEqual(indexer.head_dim, self.config["index_head_dim"]) + self.assertEqual(indexer.rope_head_dim, self.config["rope_head_dim"]) + self.assertEqual(indexer.index_topk, self.config["index_topk"]) + self.assertEqual(indexer.layer_id, self.config["layer_id"]) + + @patch("sglang.srt.layers.attention.dsa.dsa_indexer.deep_gemm") + @patch("sglang.srt.layers.attention.dsa.triton_kernel.act_quant") + def test_forward_extend_mode(self, mock_act_quant, mock_deep_gemm): + """Test indexer forward pass in extend mode.""" + if not self.supports_fp8: + self.skipTest("FP8 requires Hopper GPU or newer") + + # Setup mocks + mock_deep_gemm.get_num_sms.return_value = 132 + mock_deep_gemm.get_paged_mqa_logits_metadata.return_value = MagicMock() + + def mock_quant(x, *args, **kwargs): + # Return FP8 tensor and scale + return x.to(torch.float8_e4m3fn), torch.ones( + x.shape[0], dtype=torch.float32, device=x.device + ) + + mock_act_quant.side_effect = mock_quant + + # Mock deep_gemm.fp8_mqa_logits to return logits (ragged path) + def mock_mqa_logits(q, kv, weights, ks, ke, *args, **kwargs): + # q shape: (sum_extend_seq_len, ...), return logits for each query token + num_queries = q.shape[0] + # kv is a tuple (k_fp8, k_scale), get total number of keys from k_fp8 + k_fp8, k_scale = kv + max_kv_len = k_fp8.shape[0] # Total keys across all batches (k_offset) + return torch.randn( + num_queries, max_kv_len, dtype=torch.float32, device="cuda" + ) + + mock_deep_gemm.fp8_mqa_logits.side_effect = mock_mqa_logits + + # Also mock the paged version for completeness + def mock_paged_mqa_logits(q, kv, weights, *args, **kwargs): + batch_size = q.shape[0] + seq_len = 128 + return torch.randn(batch_size, seq_len, dtype=torch.float32, device="cuda") + + mock_deep_gemm.fp8_paged_mqa_logits.side_effect = mock_paged_mqa_logits + + self._init_model_runner() + + indexer = self._create_indexer() + forward_batch = self._create_forward_batch(ForwardMode.EXTEND) + + # Create input tensors + total_tokens = self.batch_size * self.seq_len + hidden_states = torch.randn( + total_tokens, + self.config["hidden_size"], + dtype=self.dtype, + device=self.device, + ) + q_lora = torch.randn( + total_tokens, + self.config["q_lora_rank"], + dtype=self.dtype, + device=self.device, + ) + positions = torch.arange(total_tokens, device=self.device) + + # Run forward pass + with patch.object( + self.backend, + "get_indexer_metadata", + return_value=MockIndexerMetadata( + self.batch_size, [self.seq_len] * self.batch_size + ), + ): + topk_indices = indexer( + x=hidden_states, + q_lora=q_lora, + positions=positions, + forward_batch=forward_batch, + layer_id=self.config["layer_id"], + ) + + # Verify output + self._verify_topk_output( + topk_indices, self.batch_size, self.seq_len, self.config["index_topk"] + ) + + @patch("sglang.srt.layers.attention.dsa.dsa_indexer.deep_gemm") + @patch("sglang.srt.layers.attention.dsa.triton_kernel.act_quant") + def test_forward_decode_mode(self, mock_act_quant, mock_deep_gemm): + """Test indexer forward pass in decode mode.""" + if not self.supports_fp8: + self.skipTest("FP8 requires Hopper GPU or newer") + + # Setup mocks + mock_deep_gemm.get_num_sms.return_value = 132 + mock_deep_gemm.get_paged_mqa_logits_metadata.return_value = MagicMock() + + def mock_quant(x, *args, **kwargs): + return x.to(torch.float8_e4m3fn), torch.ones( + x.shape[0], dtype=torch.float32, device=x.device + ) + + mock_act_quant.side_effect = mock_quant + + def mock_paged_mqa_logits(q, kv, weights, *args, **kwargs): + batch_size = q.shape[0] + seq_len = 128 + return torch.randn(batch_size, seq_len, dtype=torch.float32, device="cuda") + + mock_deep_gemm.fp8_paged_mqa_logits.side_effect = mock_paged_mqa_logits + + self._init_model_runner() + + indexer = self._create_indexer() + forward_batch = self._create_forward_batch(ForwardMode.DECODE) + + # Create input tensors for decode (batch_size tokens only) + hidden_states = torch.randn( + self.batch_size, + self.config["hidden_size"], + dtype=self.dtype, + device=self.device, + ) + q_lora = torch.randn( + self.batch_size, + self.config["q_lora_rank"], + dtype=self.dtype, + device=self.device, + ) + positions = torch.arange(self.batch_size, device=self.device) + + # Run forward pass + with patch.object( + self.backend, + "get_indexer_metadata", + return_value=MockIndexerMetadata( + self.batch_size, [self.seq_len + 1] * self.batch_size + ), + ): + topk_indices = indexer( + x=hidden_states, + q_lora=q_lora, + positions=positions, + forward_batch=forward_batch, + layer_id=self.config["layer_id"], + ) + + # Verify output - decode mode has q_len=1 + self._verify_topk_output( + topk_indices, self.batch_size, 1, self.config["index_topk"] + ) + + def test_rotate_activation(self): + """Test the Hadamard transform (rotate_activation) function.""" + # Test with power-of-2 hidden size + hidden_size = 128 + x = torch.randn(16, hidden_size, dtype=torch.bfloat16, device=self.device) + + try: + output = rotate_activation(x) + self.assertEqual(output.shape, x.shape) + self.assertEqual(output.dtype, torch.bfloat16) + except Exception: + self.skipTest("hadamard JIT kernel not available") + + def test_rotate_activation_invalid_size(self): + """Test that rotate_activation fails with non-power-of-2 size.""" + # Test with non-power-of-2 hidden size + hidden_size = 129 # Not a power of 2 + x = torch.randn(16, hidden_size, dtype=torch.bfloat16, device=self.device) + + with self.assertRaises(AssertionError): + rotate_activation(x) + + def test_indexer_metadata_interface(self): + """Test the BaseIndexerMetadata interface implementation.""" + batch_size = 4 + seq_lens = [64, 128, 96, 112] + + metadata = MockIndexerMetadata(batch_size, seq_lens) + + # Test get_seqlens_int32 + seqlens = metadata.get_seqlens_int32() + self.assertEqual(seqlens.shape, (batch_size,)) + self.assertEqual(seqlens.dtype, torch.int32) + self.assertTrue(torch.all(seqlens == torch.tensor(seq_lens, device="cuda"))) + + # Test get_page_table_64 + page_table = metadata.get_page_table_64() + self.assertEqual(len(page_table.shape), 2) + self.assertEqual(page_table.shape[0], batch_size) + self.assertEqual(page_table.dtype, torch.int32) + + # Test topk_transform + logits = torch.randn(batch_size, 128, device="cuda") + topk = 64 + topk_indices = metadata.topk_transform(logits, topk) + self.assertEqual(topk_indices.shape, (batch_size, topk)) + + def test_topk_unfused_backends_valid_selection(self): + batch_size = 8 + max_score_len = 16 * 1024 + topk = 2048 + for topk_backend in [ + DSATopKBackend.SGL_KERNEL, + DSATopKBackend.TORCH, + DSATopKBackend.FLASHINFER, + ]: + tie_break_values = ( + [None, "small", "large"] + if topk_backend == DSATopKBackend.FLASHINFER + else [None] + ) + for tie_break in tie_break_values: + for with_row_starts in [False, True]: + with self.subTest( + topk_backend=topk_backend.value, + tie_break=tie_break, + with_row_starts=with_row_starts, + ): + with envs.SGLANG_DSA_TOPK_FLASHINFER_TIE_BREAK.override( + tie_break + ): + self._run_unfused_topk_backend_validity_test( + batch_size, + max_score_len, + topk, + topk_backend=topk_backend, + with_row_starts=with_row_starts, + ) + + def test_topk_fused_backends_equivalence(self): + batch_size = 8 + max_score_len = 16 * 1024 + topk = 2048 + for tie_break in [None, "small", "large"]: + for topk_transform_method in [ + TopkTransformMethod.PAGED, + TopkTransformMethod.RAGGED, + ]: + for with_row_starts in [False, True]: + if ( + topk_transform_method == TopkTransformMethod.PAGED + and with_row_starts + ): + # The synthetic paged fixture uses the decode-like row mapping. + # Ragged fused and unfused cases cover shifted row windows. + continue + with self.subTest( + tie_break=tie_break, + topk_transform_method=topk_transform_method.name, + with_row_starts=with_row_starts, + ): + with envs.SGLANG_DSA_TOPK_FLASHINFER_TIE_BREAK.override( + tie_break + ): + self._run_fused_topk_backend_equivalence_test( + batch_size=batch_size, + max_score_len=max_score_len, + topk=topk, + topk_transform_method=topk_transform_method, + with_row_starts=with_row_starts, + ) + with self.subTest( + tie_break=tie_break, + topk_transform_method=TopkTransformMethod.PAGED.name, + with_row_starts=False, + query_lens="multi", + ): + with envs.SGLANG_DSA_TOPK_FLASHINFER_TIE_BREAK.override(tie_break): + self._run_fused_topk_backend_equivalence_test( + batch_size=batch_size, + max_score_len=max_score_len, + topk=topk, + topk_transform_method=TopkTransformMethod.PAGED, + with_row_starts=False, + query_lens=[1, 2, 3, 1, 2, 1, 3, 2], + ) + + # TODO: enable this test after indexer accuracy aligned + # @patch("sglang.srt.layers.attention.dsa.dsa_indexer.deep_gemm") + # def test_indexer_with_different_topk(self, mock_deep_gemm): + # """Test indexer with different topk values.""" + # mock_deep_gemm.get_num_sms.return_value = 132 + + # for topk in [32, 64, 128]: + # with self.subTest(topk=topk): + # indexer = self._create_indexer(index_topk=topk) + # self.assertEqual(indexer.index_topk, topk) + + @patch("sglang.srt.layers.attention.dsa.dsa_indexer.deep_gemm") + def test_indexer_with_fused_wk(self, mock_deep_gemm): + """Test indexer creation with fused wk and weights projection.""" + mock_deep_gemm.get_num_sms.return_value = 132 + + # Note: fuse_wk_and_weights_proj feature is not currently implemented + # This test verifies basic indexer creation still works + indexer = self._create_indexer() + self.assertIsNotNone(indexer) + + @patch("sglang.srt.layers.attention.dsa.dsa_indexer.deep_gemm") + def test_indexer_with_alt_stream(self, mock_deep_gemm): + """Test indexer creation with alternative CUDA stream.""" + mock_deep_gemm.get_num_sms.return_value = 132 + + alt_stream = torch.cuda.Stream() + indexer = self._create_indexer(alt_stream=alt_stream) + self.assertEqual(indexer.alt_stream, alt_stream) + + def test_shape_sanity_checks(self): + """Test various shape combinations for consistency.""" + test_configs = [ + {"batch_size": 1, "seq_len": 64}, + {"batch_size": 4, "seq_len": 128}, + {"batch_size": 8, "seq_len": 256}, + ] + + for config in test_configs: + with self.subTest(**config): + batch_size = config["batch_size"] + seq_len = config["seq_len"] + + # Test metadata shapes + metadata = MockIndexerMetadata(batch_size, [seq_len] * batch_size) + + seqlens = metadata.get_seqlens_int32() + self.assertEqual(seqlens.shape, (batch_size,)) + + page_table = metadata.get_page_table_64() + expected_blocks = (seq_len + 63) // 64 + self.assertEqual(page_table.shape[0], batch_size) + self.assertGreaterEqual(page_table.shape[1], expected_blocks) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_dsa_metadata.py b/asian_ai/performance/SGLang/test/registered/kernels/test_dsa_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..272e8166e9cf390ecd39c3861c216106e00eabcb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_dsa_metadata.py @@ -0,0 +1,474 @@ +import unittest + +import torch + +from sglang.srt.layers.attention.triton_ops.dsa_metadata import ( + fused_dsa_decode_metadata, + fused_dsa_draft_extend_metadata, + fused_dsa_target_verify_metadata, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=15, stage="base-b", runner_config="1-gpu-large") + + +def _cu_seqlens(seqlens: torch.Tensor) -> torch.Tensor: + out = torch.empty(seqlens.numel() + 1, dtype=torch.int32, device=seqlens.device) + out[:1].zero_() + out[1:].copy_(torch.cumsum(seqlens.to(torch.int32), dim=0, dtype=torch.int32)) + return out + + +def _dsa_seqlens(seqlens: torch.Tensor, topk: int) -> torch.Tensor: + return torch.minimum( + seqlens.to(torch.int32), torch.tensor(topk, device=seqlens.device) + ) + + +def _real_page_table(page_table_1: torch.Tensor, real_page_size: int) -> torch.Tensor: + if real_page_size == 1: + return page_table_1 + return page_table_1[:, ::real_page_size] // real_page_size + + +def _make_req_to_token( + pool_size: int, max_len: int, device: torch.device +) -> torch.Tensor: + # Row-dependent values catch accidental row reuse, while monotonic columns make + # real-page-table checks easy to reason about. + cols = torch.arange(max_len, dtype=torch.int32, device=device) + rows = torch.arange(pool_size, dtype=torch.int32, device=device).view(-1, 1) + return rows * (max_len + 17) + cols + + +def _assert_equal(actual: torch.Tensor, expected: torch.Tensor, name: str) -> None: + torch.testing.assert_close(actual, expected, rtol=0, atol=0, msg=name) + + +@unittest.skipUnless(torch.cuda.is_available(), "CUDA is required for this test.") +class TestDSAMetadataKernels(CustomTestCase): + def setUp(self): + super().setUp() + self.device = torch.device("cuda") + + def _check_decode( + self, + seq_lens_values, + *, + max_len: int, + dsa_index_topk: int, + real_page_size: int, + ): + bs = len(seq_lens_values) + pool_size = max(bs + 3, 8) + seq_lens = torch.tensor(seq_lens_values, dtype=torch.int64, device=self.device) + req_pool_indices = torch.arange(bs, dtype=torch.int64, device=self.device) * 2 + req_to_token = _make_req_to_token(pool_size * 2, max_len, self.device) + + cache_seqlens = torch.empty(bs, dtype=torch.int32, device=self.device) + cu_seqlens_k = torch.empty(bs + 1, dtype=torch.int32, device=self.device) + page_table_1 = torch.empty((bs, max_len), dtype=torch.int32, device=self.device) + dsa_cache_seqlens = torch.empty(bs, dtype=torch.int32, device=self.device) + dsa_cu_seqlens_k = torch.empty(bs + 1, dtype=torch.int32, device=self.device) + real_page_table = ( + torch.empty( + (bs, (max_len + real_page_size - 1) // real_page_size), + dtype=torch.int32, + device=self.device, + ) + if real_page_size > 1 + else page_table_1 + ) + + fused_dsa_decode_metadata( + seq_lens=seq_lens, + req_pool_indices=req_pool_indices, + req_to_token=req_to_token, + cache_seqlens=cache_seqlens, + cu_seqlens_k=cu_seqlens_k, + page_table_1=page_table_1, + dsa_cache_seqlens=dsa_cache_seqlens, + dsa_cu_seqlens_k=dsa_cu_seqlens_k, + real_page_table=real_page_table, + bs=bs, + max_len=max_len, + dsa_index_topk=dsa_index_topk, + real_page_size=real_page_size, + ) + + expected_cache = seq_lens.to(torch.int32) + expected_page_table = req_to_token[req_pool_indices, :max_len].contiguous() + expected_dsa = _dsa_seqlens(expected_cache, dsa_index_topk) + + _assert_equal(cache_seqlens, expected_cache, "decode cache_seqlens") + _assert_equal(cu_seqlens_k, _cu_seqlens(expected_cache), "decode cu_seqlens_k") + _assert_equal(page_table_1, expected_page_table, "decode page_table_1") + _assert_equal(dsa_cache_seqlens, expected_dsa, "decode dsa_cache_seqlens") + _assert_equal( + dsa_cu_seqlens_k, _cu_seqlens(expected_dsa), "decode dsa_cu_seqlens_k" + ) + if real_page_size > 1: + _assert_equal( + real_page_table, + _real_page_table(expected_page_table, real_page_size), + "decode real_page_table", + ) + + def _check_target_verify( + self, + seq_lens_values, + *, + max_seqlen_k: int, + dsa_index_topk: int, + real_page_size: int, + next_n: int, + fill_ctx_lens: bool, + ): + bs = len(seq_lens_values) + expanded_size = bs * next_n + pool_size = max(bs + 5, 8) + seq_lens = torch.tensor(seq_lens_values, dtype=torch.int64, device=self.device) + req_pool_indices = torch.arange(bs, dtype=torch.int64, device=self.device) + 1 + req_to_token = _make_req_to_token(pool_size + 2, max_seqlen_k, self.device) + + cache_seqlens = torch.empty(bs, dtype=torch.int32, device=self.device) + cu_seqlens_k = torch.empty(bs + 1, dtype=torch.int32, device=self.device) + page_table_1 = torch.empty( + (expanded_size, max_seqlen_k), dtype=torch.int32, device=self.device + ) + seqlens_expanded = torch.empty( + expanded_size, dtype=torch.int32, device=self.device + ) + dsa_cache_seqlens = torch.empty( + expanded_size, dtype=torch.int32, device=self.device + ) + dsa_cu_seqlens_k = torch.empty( + expanded_size + 1, dtype=torch.int32, device=self.device + ) + real_page_table = ( + torch.empty( + ( + expanded_size, + (max_seqlen_k + real_page_size - 1) // real_page_size, + ), + dtype=torch.int32, + device=self.device, + ) + if real_page_size > 1 + else page_table_1 + ) + paged_mqa_ctx_lens_2d = ( + torch.empty((bs, next_n), dtype=torch.int32, device=self.device) + if fill_ctx_lens + else None + ) + + fused_dsa_target_verify_metadata( + seq_lens=seq_lens, + req_pool_indices=req_pool_indices, + req_to_token=req_to_token, + cache_seqlens=cache_seqlens, + cu_seqlens_k=cu_seqlens_k, + page_table_1=page_table_1, + seqlens_expanded=seqlens_expanded, + dsa_cache_seqlens=dsa_cache_seqlens, + dsa_cu_seqlens_k=dsa_cu_seqlens_k, + real_page_table=real_page_table, + bs=bs, + max_seqlen_k=max_seqlen_k, + dsa_index_topk=dsa_index_topk, + real_page_size=real_page_size, + next_n=next_n, + paged_mqa_ctx_lens_2d=paged_mqa_ctx_lens_2d, + ) + + expected_cache = (seq_lens + next_n).to(torch.int32) + base_page_table = req_to_token[req_pool_indices, :max_seqlen_k].contiguous() + expected_page_table = torch.repeat_interleave( + base_page_table, repeats=next_n, dim=0 + ).contiguous() + draft_offsets = torch.arange(next_n, dtype=torch.int32, device=self.device) + expected_expanded = seq_lens.to(torch.int32).view(-1, 1) + draft_offsets + 1 + expected_expanded = expected_expanded.reshape(-1).contiguous() + expected_dsa = _dsa_seqlens(expected_expanded, dsa_index_topk) + + _assert_equal(cache_seqlens, expected_cache, "target cache_seqlens") + _assert_equal(cu_seqlens_k, _cu_seqlens(expected_cache), "target cu_seqlens_k") + _assert_equal(page_table_1, expected_page_table, "target page_table_1") + _assert_equal(seqlens_expanded, expected_expanded, "target seqlens_expanded") + _assert_equal(dsa_cache_seqlens, expected_dsa, "target dsa_cache_seqlens") + _assert_equal( + dsa_cu_seqlens_k, _cu_seqlens(expected_dsa), "target dsa_cu_seqlens_k" + ) + if real_page_size > 1: + _assert_equal( + real_page_table, + _real_page_table(expected_page_table, real_page_size), + "target real_page_table", + ) + if fill_ctx_lens: + expected_ctx = expected_cache.view(bs, 1).expand(bs, next_n).contiguous() + _assert_equal( + paged_mqa_ctx_lens_2d, expected_ctx, "target paged_mqa_ctx_lens_2d" + ) + + def _check_draft_extend( + self, + seq_lens_values, + extend_seq_lens_values, + *, + max_seqlen_k: int, + dsa_index_topk: int, + real_page_size: int, + max_extend_len: int, + max_total_len: int, + static_extend_len: bool, + ): + bs = len(seq_lens_values) + total_len = sum(extend_seq_lens_values) + pool_size = max(bs + 4, 8) + seq_lens = torch.tensor(seq_lens_values, dtype=torch.int64, device=self.device) + extend_seq_lens = torch.tensor( + extend_seq_lens_values, dtype=torch.int32, device=self.device + ) + req_pool_indices = torch.arange(bs, dtype=torch.int64, device=self.device) + 2 + req_to_token = _make_req_to_token(pool_size + 4, max_seqlen_k, self.device) + + cache_seqlens = torch.empty(bs, dtype=torch.int32, device=self.device) + cu_seqlens_k = torch.empty(bs + 1, dtype=torch.int32, device=self.device) + page_table_1 = torch.empty( + (max_total_len, max_seqlen_k), dtype=torch.int32, device=self.device + ) + seqlens_expanded = torch.empty( + max_total_len, dtype=torch.int32, device=self.device + ) + dsa_cache_seqlens = torch.empty( + max_total_len, dtype=torch.int32, device=self.device + ) + dsa_cu_seqlens_k = torch.empty( + max_total_len + 1, dtype=torch.int32, device=self.device + ) + real_page_table = ( + torch.empty( + (max_total_len, (max_seqlen_k + real_page_size - 1) // real_page_size), + dtype=torch.int32, + device=self.device, + ) + if real_page_size > 1 + else page_table_1 + ) + + fused_dsa_draft_extend_metadata( + seq_lens=seq_lens, + extend_seq_lens=extend_seq_lens, + req_pool_indices=req_pool_indices, + req_to_token=req_to_token, + cache_seqlens=cache_seqlens, + cu_seqlens_k=cu_seqlens_k, + page_table_1=page_table_1, + seqlens_expanded=seqlens_expanded, + dsa_cache_seqlens=dsa_cache_seqlens, + dsa_cu_seqlens_k=dsa_cu_seqlens_k, + real_page_table=real_page_table, + bs=bs, + total_len=total_len, + max_seqlen_k=max_seqlen_k, + dsa_index_topk=dsa_index_topk, + real_page_size=real_page_size, + max_extend_len=max_extend_len, + max_total_len=max_total_len, + static_extend_len=static_extend_len, + ) + + expected_cache = seq_lens.to(torch.int32) + base_page_table = req_to_token[req_pool_indices, :max_seqlen_k].contiguous() + expected_page_table = torch.repeat_interleave( + base_page_table, repeats=extend_seq_lens, dim=0 + ).contiguous() + expanded_parts = [] + for seq_len, qo_len in zip(seq_lens, extend_seq_lens, strict=True): + expanded_parts.append( + torch.arange( + seq_len.item() - qo_len.item() + 1, + seq_len.item() + 1, + dtype=torch.int32, + device=self.device, + ) + ) + expected_expanded = ( + torch.cat(expanded_parts, dim=0) + if expanded_parts + else torch.empty(0, dtype=torch.int32, device=self.device) + ) + expected_dsa = _dsa_seqlens(expected_expanded, dsa_index_topk) + + _assert_equal(cache_seqlens, expected_cache, "draft cache_seqlens") + _assert_equal(cu_seqlens_k, _cu_seqlens(expected_cache), "draft cu_seqlens_k") + _assert_equal( + page_table_1[:total_len], expected_page_table, "draft page_table_1" + ) + _assert_equal( + seqlens_expanded[:total_len], expected_expanded, "draft seqlens_expanded" + ) + _assert_equal( + dsa_cache_seqlens[:total_len], expected_dsa, "draft dsa_cache_seqlens" + ) + _assert_equal( + dsa_cu_seqlens_k[: total_len + 1], + _cu_seqlens(expected_dsa), + "draft dsa_cu_seqlens_k", + ) + if real_page_size > 1: + _assert_equal( + real_page_table[:total_len], + _real_page_table(expected_page_table, real_page_size), + "draft real_page_table", + ) + + def test_decode_matches_eager_reference(self): + for real_page_size in (1, 64): + with self.subTest(real_page_size=real_page_size): + self._check_decode( + [1, 7, 65, 513], + max_len=769, + dsa_index_topk=64, + real_page_size=real_page_size, + ) + + def test_target_verify_matches_eager_reference(self): + for real_page_size, fill_ctx_lens in ((1, False), (64, True)): + with self.subTest( + real_page_size=real_page_size, fill_ctx_lens=fill_ctx_lens + ): + self._check_target_verify( + [5, 63, 128], + max_seqlen_k=257, + dsa_index_topk=64, + real_page_size=real_page_size, + next_n=4, + fill_ctx_lens=fill_ctx_lens, + ) + + def test_draft_extend_static_width_matches_eager_reference(self): + self._check_draft_extend( + [16, 31, 80], + [4, 4, 4], + max_seqlen_k=193, + dsa_index_topk=64, + real_page_size=1, + max_extend_len=4, + max_total_len=12, + static_extend_len=True, + ) + + def test_draft_extend_variable_width_defensive_path(self): + # The production draft-extend-v2 replay path uses static_extend_len=True. + # Keep this case to guard the generic variable-width kernel branch. + self._check_draft_extend( + [12, 31, 80], + [3, 5, 2], + max_seqlen_k=193, + dsa_index_topk=64, + real_page_size=64, + max_extend_len=5, + max_total_len=10, + static_extend_len=False, + ) + + def test_draft_extend_partial_fill(self): + self._check_draft_extend( + [12, 31, 80], + [3, 5, 2], + max_seqlen_k=193, + dsa_index_topk=64, + real_page_size=64, + max_extend_len=5, + max_total_len=16, + static_extend_len=False, + ) + + def test_empty_batch(self): + self._check_decode( + [], + max_len=8, + dsa_index_topk=64, + real_page_size=64, + ) + self._check_target_verify( + [], + max_seqlen_k=8, + dsa_index_topk=64, + real_page_size=64, + next_n=4, + fill_ctx_lens=True, + ) + self._check_draft_extend( + [], + [], + max_seqlen_k=8, + dsa_index_topk=64, + real_page_size=64, + max_extend_len=1, + max_total_len=0, + static_extend_len=True, + ) + + def test_large_shape_coverage(self): + max_len = 1_000_003 + self._check_decode( + [1_000_000, 999_983], + max_len=max_len, + dsa_index_topk=4096, + real_page_size=64, + ) + self._check_target_verify( + [1_000_000], + max_seqlen_k=max_len, + dsa_index_topk=4096, + real_page_size=64, + next_n=2, + fill_ctx_lens=True, + ) + self._check_draft_extend( + [1_000_000], + [4], + max_seqlen_k=max_len, + dsa_index_topk=4096, + real_page_size=64, + max_extend_len=4, + max_total_len=4, + static_extend_len=True, + ) + + def test_large_batch_coverage(self): + bs = 16 * 1024 + seq_lens = (torch.arange(bs, dtype=torch.int64) % 257 + 1).tolist() + self._check_decode( + seq_lens, + max_len=1, + dsa_index_topk=64, + real_page_size=1, + ) + self._check_target_verify( + seq_lens, + max_seqlen_k=1, + dsa_index_topk=64, + real_page_size=1, + next_n=1, + fill_ctx_lens=False, + ) + self._check_draft_extend( + seq_lens, + [1] * bs, + max_seqlen_k=1, + dsa_index_topk=64, + real_page_size=1, + max_extend_len=1, + max_total_len=bs, + static_extend_len=True, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_flash_mla_backends.py b/asian_ai/performance/SGLang/test/registered/kernels/test_flash_mla_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..7695e434004b0f2b44cffcd363c787ab5510fb3e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_flash_mla_backends.py @@ -0,0 +1,505 @@ +"""SM120 FlashMLA sparse decode unit tests. + +Validates the SM120-specific FlashMLA implementation that replaces the upstream +`flash_mla` CUDA kernel (unavailable on SM120 / RTX PRO 6000): + +- ``_gather_and_dequant``: byte-precise dequant of paged FP8 + BF16 + UE8M0 KV + cache. Covers the dtype-reinterpretation surface that caused the historic + uint8 garbled-output regression (see progress doc §4). +- ``_sm120_sparse_decode_fwd``: pure-PyTorch reference path. +- ``flash_mla_sparse_decode_triton``: tiled Triton kernel. +- ``_apply_attn_sink`` / ``_merge_partial_attn``: post-processing helpers. +- ``flash_mla_with_kvcache_sm120``: entry-point dispatch on + ``SGLANG_SM120_TRITON_FLASHMLA`` selects torch/triton paths and both yield + matching output. + +DSv4 cache layout (per page): + data section: page_size * 576 bytes = 64 tokens * (448 nope + 128 rope) + scale section: page_size * 8 bytes = 64 tokens * (7 UE8M0 scales + 1 pad) + total bytes: page_size * 584 = stride(0) of k_cache +""" + +from __future__ import annotations + +import unittest +from unittest import mock + +import torch + +from sglang.srt.layers.attention import flash_mla_sm120 as fmod +from sglang.srt.layers.attention.flash_mla_sm120 import ( + _D, + _NOPE_DIM, + _NOPE_ROPE_STRIDE, + _NUM_TILES, + _ROPE_DIM, + _SCALE_STRIDE, + _TILE_SIZE, + _gather_and_dequant, + _sm120_sparse_decode_fwd, + flash_mla_with_kvcache_sm120, +) +from sglang.srt.layers.attention.flash_mla_sm120_triton import ( + _apply_attn_sink, + _merge_partial_attn, + flash_mla_sparse_decode_triton, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=45, stage="base-b", runner_config="1-gpu-large") + + +# Per-token byte layout +_BYTES_PER_TOKEN = _NOPE_ROPE_STRIDE + _SCALE_STRIDE # 576 + 8 = 584 + +_IS_SM120 = torch.cuda.is_available() and torch.cuda.get_device_capability() == (12, 0) + + +def _build_kvcache( + num_pages: int, + page_size: int, + *, + device: torch.device, + seed: int = 0, +): + """Build a synthetic FP8/BF16/UE8M0 KV cache. + + Returns the (num_pages, page_size, 1, bpt) FP8-viewed cache plus the raw + nope FP8 (float), rope BF16 (float), and UE8M0 scale (float) reference + tensors for verification. + """ + g = torch.Generator(device="cpu").manual_seed(seed) + bpt = _BYTES_PER_TOKEN # 584 — also satisfies k_cache.stride(0) requirement + raw = torch.zeros(num_pages, page_size, bpt, dtype=torch.uint8, device=device) + + # ---- Nope FP8 region: per-token bytes [0:448] ---- + # Stay in [0, 0x6F] to avoid NaN/Inf in float8_e4m3fn. + nope_bytes = torch.randint( + 0, 0x70, (num_pages, page_size, _NOPE_DIM), generator=g, dtype=torch.uint8 + ).to(device) + raw[:, :, :_NOPE_DIM] = nope_bytes + + # ---- Rope BF16 region: per-token bytes [448:576] = 64 bf16 values ---- + rope_bf16_vals = ( + torch.randn((num_pages, page_size, _ROPE_DIM), generator=g, dtype=torch.float32) + .clamp(-2.0, 2.0) + .to(torch.bfloat16) + .to(device) + ) + # View bf16 as 2 bytes per value -> 128 bytes per token rope region + rope_as_uint8 = rope_bf16_vals.contiguous().view( + torch.uint8 + ) # (num_pages, page_size, 128) + raw[:, :, _NOPE_DIM : _NOPE_DIM + _ROPE_DIM * 2] = rope_as_uint8 + + # ---- Scale section: starts at page_size * 576 ---- + # 7 UE8M0 bytes per token + 1 pad. Keep exponents in a sane range + # (UE8M0 byte 'b' decodes to 2**(b-127)), so 120..130 gives ~[1/128, 8]. + scale_bytes = torch.randint( + 120, + 131, + (num_pages, page_size, _NUM_TILES), + generator=g, + dtype=torch.uint8, + ).to(device) + # raw is (num_pages, page_size, bpt) with bpt=584; data ends at 576, scale region 576..584 + # Per-token scale offset relative to scale section: token_idx * 8. + # Note: the scale region in raw memory is at the END of the page after the + # data section. Since raw shape is (num_pages, page_size, bpt), where + # bpt=584, scale lives in raw[:, :, _NOPE_ROPE_STRIDE : _NOPE_ROPE_STRIDE+8]. + # BUT the gather code expects layout + # raw_pages: (num_pages, page_bytes) + # scale_section_offset = page_size * 576 + # i.e. data for ALL tokens first, then scale for ALL tokens. So we need + # the flat per-page layout: [tok0_data(576), tok1_data, ..., tokN-1_data, + # tok0_scale(8), tok1_scale, ...]. + # We constructed raw as (num_pages, page_size, bpt) which interleaves data + # and scales per token. Build a fresh buffer with the correct flat order. + flat = torch.zeros(num_pages, page_size * bpt, dtype=torch.uint8, device=device) + # Data: per-token 576 bytes contiguous + flat_data = raw[:, :, :_NOPE_ROPE_STRIDE].reshape( + num_pages, page_size * _NOPE_ROPE_STRIDE + ) + flat[:, : page_size * _NOPE_ROPE_STRIDE] = flat_data + # Scales: per-token 8 bytes (only first 7 written) + scale_block = torch.zeros( + num_pages, page_size, _SCALE_STRIDE, dtype=torch.uint8, device=device + ) + scale_block[:, :, :_NUM_TILES] = scale_bytes + flat[:, page_size * _NOPE_ROPE_STRIDE :] = scale_block.reshape( + num_pages, page_size * _SCALE_STRIDE + ) + + # View as (num_pages, page_size, 1, bpt) float8_e4m3fn + k_cache = flat.view(num_pages, page_size, 1, bpt).view(torch.float8_e4m3fn) + # The Triton kernel expects k_cache.stride(0) == page_size * bpt. + assert k_cache.stride(0) == page_size * bpt + + # Reference dequant per token (matches what _gather_and_dequant should produce): + nope_fp8 = nope_bytes.view( + torch.float8_e4m3fn + ).float() # (num_pages, page_size, 448) + scale_e8m0 = scale_bytes.view( + torch.float8_e8m0fnu + ).float() # (num_pages, page_size, 7) + nope_dequant = ( + nope_fp8.view(num_pages, page_size, _NUM_TILES, _TILE_SIZE) + * scale_e8m0.view(num_pages, page_size, _NUM_TILES, 1) + ).view( + num_pages, page_size, _NOPE_DIM + ) # float32 + ref_per_token = torch.cat( + [nope_dequant.to(torch.bfloat16), rope_bf16_vals], dim=-1 + ) # (num_pages, page_size, 512) bf16 + return k_cache, ref_per_token + + +def _build_q_indices( + batch_size: int, + num_heads: int, + topk: int, + num_pages: int, + page_size: int, + *, + device: torch.device, + seed: int = 1, +): + g = torch.Generator(device="cpu").manual_seed(seed) + q = ( + torch.randn((batch_size, 1, num_heads, _D), generator=g, dtype=torch.float32) + .clamp(-1.5, 1.5) + .to(torch.bfloat16) + .to(device) + ) + # Each batch picks `topk` random valid token-level indices into the pool + pool_size = num_pages * page_size + indices = torch.zeros((batch_size, 1, topk), dtype=torch.int32, device=device) + for b in range(batch_size): + perm = torch.randperm(pool_size, generator=g)[:topk] + indices[b, 0] = perm.to(device=device, dtype=torch.int32) + return q, indices + + +@unittest.skipUnless(_IS_SM120, "SM120 (compute capability 12.0) required") +class TestGatherAndDequant(CustomTestCase): + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA required") + cls.device = torch.device("cuda") + + def test_basic_dequant_matches_manual(self): + """Per-token output equals nope_fp8 * scale concatenated with rope_bf16.""" + num_pages, page_size = 3, 64 + k_cache, ref_per_token = _build_kvcache( + num_pages, page_size, device=self.device, seed=42 + ) + # Pick 1 index per page (positions 0, 32, 63) + token_ids = torch.tensor( + [[0, 1 * page_size + 32, 2 * page_size + 63]], + dtype=torch.int32, + device=self.device, + ) + out = _gather_and_dequant(k_cache, token_ids, page_size) + self.assertEqual(out.shape, (1, 3, _D)) + # Expected entries + expected = torch.stack( + [ + ref_per_token[0, 0], + ref_per_token[1, 32], + ref_per_token[2, 63], + ], + dim=0, + ).unsqueeze(0) + # bf16 dequant: allow up to 1 ULP per element. Scales are integral + # powers of 2 so the only loss is the fp8 -> bf16 mantissa rounding. + torch.testing.assert_close(out, expected, atol=1e-2, rtol=1e-2) + + def test_dequant_handles_full_page_range(self): + """All token positions in a single page produce correct output.""" + num_pages, page_size = 2, 64 + k_cache, ref_per_token = _build_kvcache( + num_pages, page_size, device=self.device, seed=7 + ) + token_ids = torch.arange(page_size, dtype=torch.int32, device=self.device).view( + 1, page_size + ) + out = _gather_and_dequant(k_cache, token_ids, page_size) + torch.testing.assert_close( + out, ref_per_token[0].unsqueeze(0), atol=1e-2, rtol=1e-2 + ) + + +@unittest.skipUnless(_IS_SM120, "SM120 (compute capability 12.0) required") +class TestSparseDecodeTritonVsTorch(CustomTestCase): + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA required") + cls.device = torch.device("cuda") + + def _run( + self, + batch_size: int = 2, + num_heads: int = 4, + topk: int = 64, + page_size: int = 64, + num_pages: int = 4, + seed: int = 11, + with_topk_length: bool = True, + with_attn_sink: bool = False, + ): + k_cache, _ = _build_kvcache(num_pages, page_size, device=self.device, seed=seed) + q, indices = _build_q_indices( + batch_size, + num_heads, + topk, + num_pages, + page_size, + device=self.device, + seed=seed + 100, + ) + topk_length = None + if with_topk_length: + topk_length = torch.tensor( + [topk // 2, topk] if batch_size == 2 else [topk] * batch_size, + dtype=torch.int32, + device=self.device, + ) + attn_sink = None + if with_attn_sink: + attn_sink = torch.full( + (num_heads,), -1.5, dtype=torch.float32, device=self.device + ) + softmax_scale = _D ** (-0.5) + # Production passes config.v_head_dim == _D (512). Both impls return + # (B, 1, H, _D); the Triton kernel always computes the full nope+rope. + head_dim_v = _D + + # PyTorch reference + ref_out, ref_lse = _sm120_sparse_decode_fwd( + q, + k_cache, + indices, + topk_length, + attn_sink, + head_dim_v=head_dim_v, + softmax_scale=softmax_scale, + ) + + # Triton + tri_out, tri_lse = flash_mla_sparse_decode_triton( + q, + k_cache, + indices, + topk_length, + attn_sink, + head_dim_v=head_dim_v, + softmax_scale=softmax_scale, + ) + + # Outputs both bf16, allow drift from online softmax base-2 vs base-e + # math + bf16 mantissa precision (~7 bits). 5e-2 abs/rel is generous + # but accounts for accumulated rounding across topk tokens. + torch.testing.assert_close( + tri_out.to(torch.float32), + ref_out.to(torch.float32), + atol=5e-2, + rtol=5e-2, + ) + return ref_out, tri_out, ref_lse, tri_lse + + def test_triton_vs_torch_basic(self): + self._run() + + def test_triton_vs_torch_no_topk_length(self): + self._run(with_topk_length=False) + + def test_triton_vs_torch_with_attn_sink(self): + self._run(with_attn_sink=True) + + def test_triton_vs_torch_small_topk(self): + self._run(topk=32, num_heads=2) + + def test_triton_vs_torch_negative_indices_are_masked(self): + """Indices < 0 are 'invalid' and must contribute zero to output.""" + k_cache, _ = _build_kvcache(4, 64, device=self.device, seed=3) + q, indices = _build_q_indices(2, 4, 32, 4, 64, device=self.device, seed=99) + # Half of each batch's indices set to -1 + indices[:, :, 16:] = -1 + topk_length = torch.tensor([32, 32], dtype=torch.int32, device=self.device) + + ref_out, _ = _sm120_sparse_decode_fwd( + q, k_cache, indices, topk_length, None, _D, _D**-0.5 + ) + tri_out, _ = flash_mla_sparse_decode_triton( + q, k_cache, indices, topk_length, None, _D, _D**-0.5 + ) + torch.testing.assert_close( + tri_out.to(torch.float32), + ref_out.to(torch.float32), + atol=5e-2, + rtol=5e-2, + ) + + +@unittest.skipUnless(_IS_SM120, "SM120 (compute capability 12.0) required") +class TestApplyAttnSink(CustomTestCase): + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA required") + cls.device = torch.device("cuda") + + def test_sink_zero_means_full_dampen_to_half(self): + """attn_sink == lse implies sink contributes equal weight: output halves.""" + B, H, D = 1, 2, 8 + lse = torch.zeros(B, 1, H, device=self.device, dtype=torch.float32) + attn_sink = torch.zeros(H, device=self.device, dtype=torch.float32) + out = torch.ones(B, 1, H, D, device=self.device, dtype=torch.bfloat16) + new_out, new_lse = _apply_attn_sink(out, lse, attn_sink) + # combined_lse = logaddexp(0, 0) = log(2). w = exp(-log2) = 0.5. + torch.testing.assert_close( + new_out.float(), + torch.full_like(new_out.float(), 0.5), + atol=2e-3, + rtol=2e-3, + ) + torch.testing.assert_close( + new_lse, + torch.full_like(new_lse, 0.6931472), # log(2) + atol=1e-5, + rtol=1e-5, + ) + + def test_sink_dead_lse_stays_zero(self): + """lse == -inf (no valid tokens) -> output stays zero (weight=0).""" + B, H, D = 1, 2, 4 + lse = torch.full( + (B, 1, H), float("-inf"), device=self.device, dtype=torch.float32 + ) + attn_sink = torch.zeros(H, device=self.device, dtype=torch.float32) + out = torch.ones(B, 1, H, D, device=self.device, dtype=torch.bfloat16) + new_out, _ = _apply_attn_sink(out, lse, attn_sink) + torch.testing.assert_close( + new_out.float(), torch.zeros_like(new_out.float()), atol=0, rtol=0 + ) + + +@unittest.skipUnless(_IS_SM120, "SM120 (compute capability 12.0) required") +class TestMergePartialAttn(CustomTestCase): + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA required") + cls.device = torch.device("cuda") + + def test_equal_lse_arithmetic_mean(self): + """lse1 == lse2 -> merged output is the arithmetic mean of out1, out2.""" + B, H, D = 1, 2, 4 + lse = torch.zeros(B, 1, H, device=self.device, dtype=torch.float32) + out1 = torch.ones(B, 1, H, D, device=self.device, dtype=torch.bfloat16) + out2 = torch.full((B, 1, H, D), 3.0, device=self.device, dtype=torch.bfloat16) + merged, merged_lse = _merge_partial_attn(out1, lse, out2, lse) + torch.testing.assert_close( + merged.float(), + torch.full_like(merged.float(), 2.0), + atol=1e-2, + rtol=1e-2, + ) + torch.testing.assert_close( + merged_lse, + torch.full_like(merged_lse, 0.6931472), # log(2) + atol=1e-5, + rtol=1e-5, + ) + + def test_one_dead_branch_passes_through(self): + """If lse2 == -inf, merged equals out1.""" + B, H, D = 1, 1, 4 + lse1 = torch.zeros(B, 1, H, device=self.device, dtype=torch.float32) + lse2 = torch.full( + (B, 1, H), float("-inf"), device=self.device, dtype=torch.float32 + ) + out1 = torch.full((B, 1, H, D), 2.5, device=self.device, dtype=torch.bfloat16) + out2 = torch.full((B, 1, H, D), 99.0, device=self.device, dtype=torch.bfloat16) + merged, merged_lse = _merge_partial_attn(out1, lse1, out2, lse2) + torch.testing.assert_close(merged.float(), out1.float(), atol=1e-3, rtol=1e-3) + torch.testing.assert_close(merged_lse, lse1, atol=1e-5, rtol=1e-5) + + +@unittest.skipUnless(_IS_SM120, "SM120 (compute capability 12.0) required") +class TestEntryPointDispatch(CustomTestCase): + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA required") + cls.device = torch.device("cuda") + + def test_torch_backend_matches_triton_backend(self): + """SGLANG_SM120_TRITON_FLASHMLA toggles backend; both return matching out.""" + k_cache, _ = _build_kvcache(4, 64, device=self.device, seed=5) + q, indices = _build_q_indices(1, 4, 32, 4, 64, device=self.device, seed=13) + topk_length = torch.tensor([32], dtype=torch.int32, device=self.device) + + kwargs = dict( + q=q, + k_cache=k_cache, + indices=indices, + topk_length=topk_length, + attn_sink=None, + head_dim_v=_D, + softmax_scale=_D**-0.5, + ) + + with mock.patch.object(fmod, "_sm120_default_backend", "torch"): + out_torch, _ = flash_mla_with_kvcache_sm120(**kwargs) + with mock.patch.object(fmod, "_sm120_default_backend", "triton"): + out_triton, _ = flash_mla_with_kvcache_sm120(**kwargs) + + torch.testing.assert_close( + out_torch.to(torch.float32), + out_triton.to(torch.float32), + atol=5e-2, + rtol=5e-2, + ) + + def test_flashinfer_backend_matches_triton(self): + """FlashInfer SM120 sparse MLA decode matches Triton reference.""" + import importlib + + if importlib.util.find_spec("flashinfer.sparse_mla_sm120") is None: + self.skipTest("FlashInfer SM120 sparse MLA not available") + + k_cache, _ = _build_kvcache(4, 64, device=self.device, seed=5) + q, indices = _build_q_indices(1, 4, 32, 4, 64, device=self.device, seed=13) + topk_length = torch.tensor([32], dtype=torch.int32, device=self.device) + + kwargs = dict( + q=q, + k_cache=k_cache, + indices=indices, + topk_length=topk_length, + attn_sink=None, + head_dim_v=_D, + softmax_scale=_D**-0.5, + ) + + with mock.patch.object(fmod, "_sm120_default_backend", "triton"): + out_triton, _ = flash_mla_with_kvcache_sm120(**kwargs) + with mock.patch.object(fmod, "_sm120_default_backend", "flashinfer"): + out_fi, _ = flash_mla_with_kvcache_sm120(**kwargs) + + torch.testing.assert_close( + out_fi.to(torch.float32), + out_triton.to(torch.float32), + atol=5e-2, + rtol=5e-2, + ) + + +if __name__ == "__main__": + import sys + + sys.exit(unittest.main()) diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_fp4_moe.py b/asian_ai/performance/SGLang/test/registered/kernels/test_fp4_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..78cffc004de781e132beba82be7d8cfb5a7c0bca --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_fp4_moe.py @@ -0,0 +1,458 @@ +# SPDX-License-Identifier: Apache-2.0 +from typing import Callable + +import pytest +import torch +from flashinfer import fp4_quantize, scaled_fp4_grouped_quantize +from flashinfer.fused_moe import cutlass_fused_moe as flashinfer_cutlass_fused_moe +from sgl_kernel import silu_and_mul +from torch.nn import functional as F + +from sglang.jit_kernel.nvfp4 import scaled_fp4_quant +from sglang.srt.layers.moe.cutlass_moe import cutlass_moe_fp4 +from sglang.srt.layers.moe.cutlass_moe_params import CutlassMoEParams, CutlassMoEType +from sglang.srt.layers.moe.topk import TopKConfig, select_experts +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=300, suite="nightly-4-gpu-b200", nightly=True) + +if torch.cuda.get_device_capability() < (10, 0): + pytest.skip( + reason="Nvfp4 Requires compute capability of 10 or above.", + allow_module_level=True, + ) + +kE2M1ToFloat = torch.tensor( + [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], dtype=torch.float32 +) + +FLOAT8_E4M3_MAX = 448.0 +FLOAT4_E2M1_MAX = 6.0 + + +def convert_swizzled_to_linear(a_sf_swizzled: torch.Tensor, m, k, block_size): + m_tiles = (m + 128 - 1) // 128 + f = block_size * 4 + k_tiles = (k + f - 1) // f + tmp = torch.reshape(a_sf_swizzled, (1, m_tiles, k_tiles, 32, 4, 4)) + tmp = torch.permute(tmp, (0, 1, 4, 3, 2, 5)) + out = tmp.reshape(m_tiles * 128, k_tiles * f // block_size) + return out[0:m, 0:k] + + +def dequantize_nvfp4_to_dtype( + tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16 +): + """Dequantize the fp4 tensor back to high precision.""" + # Two fp4 values are packed into one uint8. + assert tensor_fp4.dtype == torch.uint8 + m, packed_k = tensor_fp4.shape + k = packed_k * 2 + tensor_f32 = break_fp4_bytes(tensor_fp4, dtype) + tensor_f32 = tensor_f32.reshape(m, k // block_size, block_size) + tensor_sf = tensor_sf.view(torch.float8_e4m3fn) + tensor_sf = convert_swizzled_to_linear(tensor_sf, m, k, block_size) + tensor_sf_dtype = tensor_sf.to(torch.float32) / global_scale + + # scale the tensor + out = (tensor_f32 * tensor_sf_dtype.unsqueeze(-1)).reshape(m, k) + return out.to(dtype=dtype) + + +def break_fp4_bytes(a, dtype): + assert a.dtype == torch.uint8 + m, n = a.shape + + # Vectorized nibble processing + a_flat = a.flatten() + high = (a_flat & 0xF0) >> 4 # Upper nibbles + low = a_flat & 0x0F # Lower nibbles + + # Combine nibbles for batch processing + combined = torch.stack((low, high), dim=1).flatten() + + # Vectorized sign and magnitude extraction + signs = (combined & 0x08).to(torch.bool) # Sign bits + abs_vals = (combined & 0x07).to(torch.long) # Magnitude indices + + # Device-aware lookup and sign application + kE2M1 = kE2M1ToFloat.to(device=a.device) + values = kE2M1[abs_vals] * torch.where(signs, -1.0, 1.0) + + # Reshape to final form + return values.reshape(m, n * 2).to(dtype=dtype) + + +def compute_routing(router_logits: torch.Tensor, top_k: int): + routing_weights = torch.softmax(router_logits, dim=1, dtype=torch.float) + routing_weights, selected_experts = torch.topk(routing_weights, top_k, dim=-1) + routing_weights /= routing_weights.sum(dim=-1, keepdim=True) + routing_weights = routing_weights.float() + return routing_weights, selected_experts + + +def prepare_inputs( + hidden_states: torch.Tensor, + router_logits: torch.Tensor, + num_experts: int, + topk: int, +): + routing_weights, topk_idx = compute_routing(router_logits, topk) + + masked_m = [] + for i in range(num_experts): + mask = topk_idx.view(-1) == i + masked_m.append(mask.sum()) + + masked_m = torch.tensor(masked_m, dtype=torch.int32) + hidden_states_3d = torch.empty( + (num_experts, max(masked_m), hidden_states.shape[1]), dtype=hidden_states.dtype + ) + for i in range(num_experts): + hidden_states_3d[i, : masked_m[i], :] = hidden_states[topk_idx.view(-1) == i] + + return hidden_states_3d, masked_m, topk_idx, routing_weights + + +MNK_FACTORS = [ + (2, 1024, 1024), + (2, 1024, 1536), + (2, 3072, 1024), + (2, 3072, 1536), + (64, 1024, 1024), + (64, 1024, 1536), + (64, 3072, 1024), + (64, 2048, 1024), + (224, 1024, 1024), + (224, 1024, 1536), +] + + +# Reference implementation of torch_moe +def torch_moe(a, w1, w2, score, topk, expert_map): + B, D = a.shape + a = a.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D) + out = torch.zeros(B * topk, w2.shape[1], dtype=a.dtype, device=a.device) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + topk_weight = topk_weight.view(-1) + topk_ids = topk_ids.view(-1) + if expert_map is not None: + topk_ids = expert_map[topk_ids] + for i in range(w1.shape[0]): + mask = topk_ids == i + if mask.sum(): + out[mask] = silu_and_mul(a[mask] @ w1[i].transpose(0, 1)) @ w2[i].transpose( + 0, 1 + ) + return ( + out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype) + ).sum(dim=1) + + +def torch_moe_nvfp4(a, w1, w2, topk, topk_weight, topk_ids): + B, D = a.shape + a = a.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D) + out = torch.zeros(B * topk, w2.shape[1], dtype=a.dtype, device=a.device) + + topk_weight = topk_weight.view(-1) + topk_ids = topk_ids.view(-1) + + for i in range(w1.shape[0]): + mask = topk_ids == i + if mask.sum(): + m = w1[i].shape[0] + assert m % 2 == 0 + # Note: w1 and w3 are swapped! + w3_expert, w1_expert = w1[i][m // 2 :, :], w1[i][: m // 2, :] + inter = F.silu(a[mask] @ w1_expert.t()) * (a[mask] @ w3_expert.t()) + inter_gs = torch.tensor(1.0).cuda() + inter_q, inter_blockscale = fp4_quantize(inter, inter_gs) + inter = dequantize_nvfp4_to_dtype( + inter_q, + inter_blockscale, + inter_gs, + dtype=inter.dtype, + device=inter.device, + block_size=16, + ).cuda() + out[mask] = inter @ w2[i].transpose(0, 1) + return ( + out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype) + ).sum(dim=1) + + +def flashinfer_cutedsl_grouped_gemm_nt_masked( + hidden_states: torch.Tensor, # 3d + input_global_scale: torch.Tensor, # (l,) + weights: torch.Tensor, + w_global_scale: torch.Tensor, # (l,) + masked_m: torch.Tensor, +): + from flashinfer.cute_dsl.blockscaled_gemm import grouped_gemm_nt_masked + + # hidden_states: [l, m, k] + # weights: [l, n, k] + aq, aq_sf = scaled_fp4_grouped_quantize( + hidden_states, + masked_m.to(hidden_states.device), + input_global_scale, + ) + num_experts, n, k = weights.shape + bq, bq_sf = scaled_fp4_grouped_quantize( + weights, + torch.ones(num_experts, device=weights.device, dtype=torch.int32) * n, + w_global_scale, + ) + + out = torch.zeros( + (num_experts, max(masked_m), n), dtype=weights.dtype, device=aq.device + ) + out = out.permute(1, 2, 0) # requirement of kernel + sf_vec_size = 16 + ab_dtype = "float4_e2m1fn" + sf_dtype = "float8_e4m3fn" + c_dtype = "bfloat16" + alpha = 1.0 / (input_global_scale * w_global_scale).to(out.dtype).view( + 1, 1, num_experts + ) + + def get_cute_dtype(input: torch.Tensor) -> str: + if input.dtype == torch.bfloat16: + return "bfloat16" + elif input.dtype == torch.float16: + return "float16" + elif input.dtype == torch.float32: + return "float32" + else: + raise ValueError(f"Unsupported cute dtype {input.dtype}") + + grouped_gemm_nt_masked( + (aq, aq_sf), + (bq, bq_sf), + out, + masked_m.to(aq.device), + ab_dtype=ab_dtype, + sf_dtype=sf_dtype, + c_dtype=c_dtype, + sf_vec_size=sf_vec_size, + alpha=alpha, + alpha_dtype=get_cute_dtype(alpha), + ) + + return out + + +def check_moe( + m: int, + n: int, + k: int, + e: int, + topk: int, + dtype: torch.dtype, + moe_impl: Callable, + flip_w13: bool, +): + torch.manual_seed(7) + a = torch.randn((m, k), device="cuda", dtype=dtype) / 10 + w1 = torch.randn((e, 2 * n, k), device="cuda", dtype=dtype) / 10 + quant_blocksize = 16 + round_up = lambda x, y: (x + y - 1) // y * y + sf_w1_2n = round_up(2 * n, 128) + sf_w1_k = round_up(k // quant_blocksize, 4) + w1_blockscale = torch.empty( + (e, sf_w1_2n, sf_w1_k), device="cuda", dtype=torch.float8_e4m3fn + ) + + w2 = torch.randn((e, k, n), device="cuda", dtype=dtype) / 10 + sf_w2_k = round_up(k, 128) + sf_w2_n = round_up(n // quant_blocksize, 4) + w2_blockscale = torch.empty( + (e, sf_w2_k, sf_w2_n), device="cuda", dtype=torch.float8_e4m3fn + ) + + w1_q = torch.empty((e, 2 * n, k // 2), device="cuda", dtype=torch.uint8) + w2_q = torch.empty((e, k, n // 2), device="cuda", dtype=torch.uint8) + w1_gs = torch.empty((e,), device="cuda", dtype=torch.float32) + w2_gs = torch.empty((e,), device="cuda", dtype=torch.float32) + + for expert in range(e): + w1_amax = torch.abs(w1).max().to(torch.float32) + w2_amax = torch.abs(w2).max().to(torch.float32) + w1_gs[expert] = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w1_amax + w2_gs[expert] = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w2_amax + + w1_q[expert], w1_blockscale[expert] = scaled_fp4_quant( + w1[expert], w1_gs[expert] + ) + + w2_q[expert], w2_blockscale[expert] = scaled_fp4_quant( + w2[expert], w2_gs[expert] + ) + + score = torch.randn((m, e), device="cuda", dtype=dtype) + + topk_output = select_experts( + hidden_states=a, + router_logits=score, + topk_config=TopKConfig(top_k=topk, renormalize=False), + ) + topk_weights, topk_ids, _ = topk_output + + a1_gs = torch.ones((e,), device="cuda", dtype=torch.float32) + a2_gs = torch.ones((e,), device="cuda", dtype=torch.float32) + test_output = moe_impl( + a=a, + topk_weights=topk_weights, + topk_ids=topk_ids, + w1_q=w1_q, + w2_q=w2_q, + a1_gs=a1_gs, + w1_blockscale=w1_blockscale, + w1_alphas=(1 / w1_gs), + a2_gs=a2_gs, + w2_blockscale=w2_blockscale, + w2_alphas=(1 / w2_gs), + ) + + # Reference check: + a_global_scale = ( + (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(a.flatten(), dim=-1) + ).to(torch.float32) + a_fp4, a_scale_interleaved = scaled_fp4_quant(a, a_global_scale) + _, m_k = a_fp4.shape + a_in_dtype = dequantize_nvfp4_to_dtype( + a_fp4, + a_scale_interleaved, + a_global_scale, + dtype=a.dtype, + device=a.device, + block_size=quant_blocksize, + ) + + w1_d = torch.empty((e, 2 * n, k), device="cuda", dtype=dtype) + w2_d = torch.empty((e, k, n), device="cuda", dtype=dtype) + + for idx in range(0, e): + w1_d[idx] = dequantize_nvfp4_to_dtype( + w1_q[idx], + w1_blockscale[idx], + w1_gs[idx], + dtype=w1.dtype, + device=w1.device, + block_size=quant_blocksize, + ) + w2_d[idx] = dequantize_nvfp4_to_dtype( + w2_q[idx], + w2_blockscale[idx], + w2_gs[idx], + dtype=w2.dtype, + device=w2.device, + block_size=quant_blocksize, + ) + + if flip_w13: + dim = -2 + size = w1_d.size(dim) + assert size % 2 == 0, f"Expected even size in dim {dim}, got {size}" + half = size // 2 + # Reorder weight + w1, w3 = w1_d.split(half, dim=dim) + w1_d = torch.cat([w3, w1], dim=dim).contiguous() + + torch_output = torch_moe(a_in_dtype, w1_d, w2_d, score, topk, None) + + torch.testing.assert_close(torch_output, test_output, atol=1e-1, rtol=1e-1) + + +@pytest.mark.parametrize("m,n,k", MNK_FACTORS) +@pytest.mark.parametrize("e", [40, 64, 256]) +@pytest.mark.parametrize("topk", [1, 6, 8]) +@pytest.mark.parametrize("dtype", [torch.half, torch.bfloat16]) +@torch.inference_mode() +def test_cutlass_fp4_moe_no_graph( + m: int, n: int, k: int, e: int, topk: int, dtype: torch.dtype +): + def cutlass_moe_impl( + a, + topk_weights, + topk_ids, + w1_q, + w2_q, + a1_gs, + w1_blockscale, + w1_alphas, + a2_gs, + w2_blockscale, + w2_alphas, + ): + params = CutlassMoEParams( + CutlassMoEType.BlockscaledFP4, + device=a.device, + num_experts=e, + intermediate_size_per_partition=n, # n + hidden_size=k, + ) # k + return cutlass_moe_fp4( + a=a, + a1_gscale=a1_gs, + w1_fp4=w1_q, + w1_blockscale=w1_blockscale, + w1_alphas=w1_alphas, + a2_gscale=a2_gs, + w2_fp4=w2_q, + w2_blockscale=w2_blockscale, + w2_alphas=w2_alphas, + topk_weights=topk_weights, + topk_ids=topk_ids, + params=params, + apply_router_weight_on_input=False, + ) + + check_moe(m, n, k, e, topk, dtype, cutlass_moe_impl, flip_w13=False) + + +@pytest.mark.parametrize("m,n,k", MNK_FACTORS) +@pytest.mark.parametrize("e", [40, 64, 256]) +@pytest.mark.parametrize("topk", [1, 6, 8]) +@pytest.mark.parametrize("dtype", [torch.half, torch.bfloat16]) +@torch.inference_mode() +def test_flashinfer_fp4_moe_no_graph( + m: int, n: int, k: int, e: int, topk: int, dtype: torch.dtype +): + def flashinfer_moe_impl( + a, + topk_weights, + topk_ids, + w1_q, + w2_q, + a1_gs, + w1_blockscale, + w1_alphas, + a2_gs, + w2_blockscale, + w2_alphas, + ): + return flashinfer_cutlass_fused_moe( + a, + topk_ids.to(torch.int), + topk_weights, + w1_q.view(torch.long), + w2_q.view(torch.long), + a.dtype, + quant_scales=[ + a1_gs, + w1_blockscale.view(torch.int32), + w1_alphas, + a2_gs, + w2_blockscale.view(torch.int32), + w2_alphas, + ], + )[0] + + check_moe(m, n, k, e, topk, dtype, flashinfer_moe_impl, flip_w13=True) + + +if __name__ == "__main__": + test_cutlass_fp4_moe_no_graph(224, 1024, 1024, 256, 8, torch.half) + test_flashinfer_fp4_moe_no_graph(224, 1024, 1024, 256, 8, torch.half) diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_fused_topk_deepseek.py b/asian_ai/performance/SGLang/test/registered/kernels/test_fused_topk_deepseek.py new file mode 100644 index 0000000000000000000000000000000000000000..829c140e02bde3bd94f80f2018d523e21b7c24e3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_fused_topk_deepseek.py @@ -0,0 +1,99 @@ +import sys + +import pytest +import torch + +from sglang.srt.layers.moe.topk import biased_grouped_topk_gpu, biased_grouped_topk_impl +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=2, suite="nightly-1-gpu", nightly=True) + + +@pytest.mark.parametrize( + "seq_length", + list(range(1, 10)) + + [16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536], +) +@pytest.mark.parametrize( + "params", + [ + (128, 4, 2, 4), # 128 experts configuration + (256, 8, 4, 8), # DeepSeek V3 config - most important to test + (64, 2, 2, 4), # Smaller configuration + ], +) +@pytest.mark.parametrize("apply_routed_scaling_factor_on_output", [False, True]) +def test_fused_topk_deepseek(seq_length, params, apply_routed_scaling_factor_on_output): + """ + Test the fused_topk_deepseek code path in biased_grouped_topk_gpu. + """ + num_experts, num_expert_group, topk_group, topk = params + dtype = torch.float32 + + torch.manual_seed(seq_length) + hidden_states = torch.randn(seq_length, 128, dtype=dtype, device="cuda") + gating_output = torch.randn(seq_length, num_experts, dtype=dtype, device="cuda") + correction_bias = torch.randn(num_experts, dtype=dtype, device="cuda") + + routed_scaling_factor = 2.5 if apply_routed_scaling_factor_on_output else None + + # Fused implementation (uses fused_topk_deepseek when conditions are met) + output, indices = biased_grouped_topk_gpu( + hidden_states, + gating_output, + correction_bias, + topk=topk, + renormalize=True, + num_expert_group=num_expert_group, + topk_group=topk_group, + num_fused_shared_experts=0, + routed_scaling_factor=routed_scaling_factor, + apply_routed_scaling_factor_on_output=apply_routed_scaling_factor_on_output, + ) + + # Reference implementation (pure PyTorch) + ref_output, ref_indices = biased_grouped_topk_impl( + hidden_states, + gating_output, + correction_bias, + topk=topk, + renormalize=True, + num_expert_group=num_expert_group, + topk_group=topk_group, + num_fused_shared_experts=0, + routed_scaling_factor=routed_scaling_factor, + apply_routed_scaling_factor_on_output=apply_routed_scaling_factor_on_output, + ) + + # Check 1: Row-wise sums should match (invariant to tie-breaking) + output_sum = output.sum(dim=-1) + ref_output_sum = ref_output.sum(dim=-1) + sum_check = torch.allclose(output_sum, ref_output_sum, rtol=1e-03, atol=1e-04) + + # Check 2: Scatter-based comparison with allowance for tie-breaking + res = torch.zeros(seq_length, num_experts, dtype=torch.float32, device="cuda") + ref = torch.zeros(seq_length, num_experts, dtype=torch.float32, device="cuda") + + res.scatter_(1, indices.long(), output) + ref.scatter_(1, ref_indices.long(), ref_output) + + diff = torch.abs(ref - res) + atol = ( + 5e-03 + if (seq_length >= 4096 and apply_routed_scaling_factor_on_output) + else 1e-03 + ) + num_large_diffs = (diff > atol).sum().item() + + # Allow a small number of differences for tie-breaking situations + max_allowed_diffs = max(16, seq_length // 500) + scatter_check = num_large_diffs <= max_allowed_diffs + + assert sum_check and scatter_check, ( + f"Output mismatch at seq_length {seq_length}, params {params}, " + f"apply_routed_scaling_factor_on_output {apply_routed_scaling_factor_on_output}" + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_gather_spec_extras.py b/asian_ai/performance/SGLang/test/registered/kernels/test_gather_spec_extras.py new file mode 100644 index 0000000000000000000000000000000000000000..5b960df6ea51900f00bc845367823be7596d7c08 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_gather_spec_extras.py @@ -0,0 +1,215 @@ +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=10, suite="nightly-amd-kernel-1-gpu", nightly=True) + +import unittest + +import torch + +from sglang.srt.speculative.triton_ops.gather_spec_extras import gather_spec_extras +from sglang.test.test_utils import CustomTestCase + +_OUTPUT_NAMES = ("topk_p", "topk_index", "bonus_tokens", "hidden_states") + + +def _ref_gather( + indices, topk_p_buf, topk_index_buf, output_tokens_buf, hidden_states_buf +): + """Reference oracle: the exact torch.compile'd advanced-index gather that the + fused Triton kernel replaced (see overlap_utils._gather_spec_extras pre-fusion). + A gather is a pure copy, so the kernel must match this bit-for-bit.""" + topk_p = topk_p_buf[indices] + topk_index = topk_index_buf[indices] + bonus_tokens = output_tokens_buf[indices] + hidden_states = ( + hidden_states_buf[indices] if hidden_states_buf is not None else None + ) + return topk_p, topk_index, bonus_tokens, hidden_states + + +def _make_buffers( + pool_size, + topk, + hidden_dim, + *, + with_hidden, + hidden_dtype=torch.bfloat16, + device="cuda", + seed=0, +): + """Build FutureMap-shaped relay buffers. + + Mirrors overlap_utils.FutureMap: topk_p / topk_index / hidden_states are + 2-D (pool_size, width) while output_tokens is 1-D (pool_size,). The width + mix (incl. the 1-D buffer -> row width 1) exercises the kernel's per-buffer + masking. + """ + g = torch.Generator(device=device).manual_seed(seed) + topk_p_buf = torch.rand( + (pool_size, topk), dtype=torch.float32, device=device, generator=g + ) + topk_index_buf = torch.randint( + 0, 32000, (pool_size, topk), dtype=torch.int64, device=device, generator=g + ) + output_tokens_buf = torch.randint( + 0, 32000, (pool_size,), dtype=torch.int64, device=device, generator=g + ) + hidden_states_buf = ( + torch.randn( + (pool_size, hidden_dim), dtype=hidden_dtype, device=device, generator=g + ) + if with_hidden + else None + ) + return topk_p_buf, topk_index_buf, output_tokens_buf, hidden_states_buf + + +@unittest.skipUnless(torch.cuda.is_available(), "CUDA is required for this test.") +class TestGatherSpecExtras(CustomTestCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.device = torch.device("cuda") + + def _assert_matches_reference(self, indices, bufs): + """Run fused kernel + reference on the same inputs and assert every + output is identical (dtype, shape, exact values) and that the source + buffers are never mutated.""" + src_snapshots = [None if b is None else b.clone() for b in bufs] + + ref = _ref_gather(indices, *bufs) + got = gather_spec_extras(indices, *bufs) + + self.assertEqual(len(got), len(ref)) + for name, r, o in zip(_OUTPUT_NAMES, ref, got): + if r is None: + self.assertIsNone(o, f"{name} should be None when buffer is None") + continue + self.assertIsNotNone(o, f"{name} unexpectedly None") + self.assertEqual(o.dtype, r.dtype, f"{name} dtype mismatch") + self.assertEqual(tuple(o.shape), tuple(r.shape), f"{name} shape mismatch") + self.assertEqual(o.device.type, r.device.type, f"{name} device mismatch") + # Pure gather == bit-exact copy, so require zero tolerance. + torch.testing.assert_close( + o, r, rtol=0, atol=0, msg=f"{name} value mismatch" + ) + + # The kernel only reads sources; it must not scribble into them. + for name, before, buf in zip(_OUTPUT_NAMES, src_snapshots, bufs): + if before is None: + continue + torch.testing.assert_close( + buf, before, rtol=0, atol=0, msg=f"source buffer {name} was mutated" + ) + + def test_matches_reference_across_shapes(self): + # (pool_size, m, topk, hidden_dim). Covers: m many duplicates + self._assert_matches_reference(indices, bufs) + + def test_index_dtype_variants(self): + pool_size, m = 128, 50 + bufs = _make_buffers(pool_size, 8, 1024, with_hidden=True, device=self.device) + base = torch.randint(0, pool_size, (m,), device=self.device) + for idx_dtype in (torch.int32, torch.int64): + with self.subTest(idx_dtype=idx_dtype): + self._assert_matches_reference(base.to(idx_dtype), bufs) + + def test_hidden_dtype_variants(self): + pool_size, m = 96, 40 + indices = torch.randint( + 0, pool_size, (m,), dtype=torch.int64, device=self.device + ) + for hidden_dtype in (torch.bfloat16, torch.float16, torch.float32): + with self.subTest(hidden_dtype=hidden_dtype): + bufs = _make_buffers( + pool_size, + 8, + 2048, + with_hidden=True, + hidden_dtype=hidden_dtype, + device=self.device, + ) + self._assert_matches_reference(indices, bufs) + + def test_outputs_do_not_alias_source_buffers(self): + pool_size, m = 64, 32 + bufs = _make_buffers(pool_size, 8, 512, with_hidden=True, device=self.device) + indices = torch.randint( + 0, pool_size, (m,), dtype=torch.int64, device=self.device + ) + outputs = gather_spec_extras(indices, *bufs) + for name, out, buf in zip(_OUTPUT_NAMES, outputs, bufs): + if out is None or buf is None: + continue + self.assertNotEqual( + out.data_ptr(), + buf.data_ptr(), + f"{name} output aliases its source buffer", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_gemma4_fused_routing.py b/asian_ai/performance/SGLang/test/registered/kernels/test_gemma4_fused_routing.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c42b98bb555d68fb14d96d0938aabcafd4a48e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_gemma4_fused_routing.py @@ -0,0 +1,106 @@ +"""Correctness tests for ``gemma4_fused_routing``. + +Compares the Triton-fused routing kernel against the original SGLang +``Gemma4MoE.routing_function`` reference (softmax-of-topk * per_expert_scale). +Run with:: + + pytest test/registered/kernels/test_gemma4_fused_routing.py -v + +Requires a CUDA-capable GPU; skips otherwise. +""" + +from __future__ import annotations + +import pytest +import torch + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b", runner_config="1-gpu-small") + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), + reason="gemma4_fused_routing is a CUDA-only Triton kernel", +) + + +@pytest.fixture(scope="module") +def fused_routing(): + from sglang.srt.layers.gemma4_fused_ops import gemma4_fused_routing + + return gemma4_fused_routing + + +def _reference(gating_output: torch.Tensor, per_expert_scale: torch.Tensor, topk: int): + """The previous (now fallback) torch routing function from gemma4_causal.py.""" + topk_logits, topk_ids = torch.topk(gating_output, k=topk, dim=-1) + topk_weights = torch.nn.functional.softmax(topk_logits, dim=-1) + topk_weights = topk_weights * per_expert_scale[topk_ids].to(topk_weights.dtype) + return topk_weights.to(torch.float32), topk_ids.to(torch.int32) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32]) +@pytest.mark.parametrize("T", [1, 7, 64, 128, 1024]) +@pytest.mark.parametrize("E,K", [(128, 8), (64, 4), (256, 8)]) +def test_matches_reference(fused_routing, dtype, T, E, K): + torch.manual_seed(0) + g = torch.randn(T, E, dtype=dtype, device="cuda") + s = torch.rand(E, dtype=dtype, device="cuda") * 2.0 + + ref_w, ref_i = _reference(g, s, K) + out_w, out_i = fused_routing(g, s, K) + + assert out_w.dtype == torch.float32 + assert out_i.dtype == torch.int32 + assert out_w.shape == (T, K) + assert out_i.shape == (T, K) + + # The fused kernel does softmax in fp32 while the torch fallback uses the + # input dtype, so tolerances are set to roughly the input-dtype eps. + if dtype == torch.bfloat16: + atol, rtol = 5e-3, 5e-3 + elif dtype == torch.float16: + atol, rtol = 1e-3, 1e-3 + else: + atol, rtol = 1e-5, 1e-5 + + if (out_i != ref_i).any(): + # Tie-break order may differ; require the same top-K set and weight sum. + ref_set = ref_i.sort(dim=-1).values + out_set = out_i.sort(dim=-1).values + assert torch.equal( + out_set, ref_set + ), "fused routing picked a different top-K set than reference" + torch.testing.assert_close( + out_w.sum(dim=-1).to(torch.float32), + ref_w.sum(dim=-1).to(torch.float32), + atol=atol, + rtol=rtol, + ) + else: + torch.testing.assert_close(out_w, ref_w, atol=atol, rtol=rtol) + + +def test_zero_tokens(fused_routing): + g = torch.empty(0, 128, dtype=torch.bfloat16, device="cuda") + s = torch.ones(128, dtype=torch.bfloat16, device="cuda") + w, i = fused_routing(g, s, 8) + assert w.shape == (0, 8) and i.shape == (0, 8) + assert w.dtype == torch.float32 and i.dtype == torch.int32 + + +def test_scale_applied(fused_routing): + """Weights must include per_expert_scale[topk_ids].""" + torch.manual_seed(1) + T, E, K = 4, 128, 8 + g = torch.randn(T, E, dtype=torch.bfloat16, device="cuda") + s = torch.rand(E, dtype=torch.bfloat16, device="cuda") * 3.0 + + out_w, out_i = fused_routing(g, s, K) + ref_w, ref_i = _reference(g, s, K) + torch.testing.assert_close(out_w, ref_w, atol=5e-3, rtol=5e-3) + assert torch.equal(out_i, ref_i) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_mhc_kernels.py b/asian_ai/performance/SGLang/test/registered/kernels/test_mhc_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d360a4dd148b3f8cedb868586581c62351d019 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_mhc_kernels.py @@ -0,0 +1,120 @@ +import pytest +import torch + +import sglang.srt.layers.mhc as mhc +from sglang.srt.layers.mhc import mhc_fused_post_pre, mhc_post, mhc_pre +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b", runner_config="1-gpu-large") + + +@pytest.mark.parametrize("hidden_size", [4096, 7168]) +@pytest.mark.parametrize("num_tokens", [0, 1, 8, 17, 32, 64]) +@pytest.mark.parametrize("use_norm", [False, True]) +def test_mhc_fused_post_pre_matches_unfused( + monkeypatch, hidden_size, num_tokens, use_norm +): + if not torch.cuda.is_available(): + pytest.skip("CUDA is required for TileLang mHC kernels") + + monkeypatch.setattr(mhc, "is_dsa_prefill_cp_round_robin_split", lambda: False) + torch.manual_seed(0) + device = torch.device("cuda") + hc_mult = 4 + hc_mult3 = hc_mult * 2 + hc_mult * hc_mult + hc_hidden_size = hc_mult * hidden_size + + x = torch.randn(num_tokens, hidden_size, device=device, dtype=torch.bfloat16) * 0.1 + residual = ( + torch.randn( + num_tokens, hc_mult, hidden_size, device=device, dtype=torch.bfloat16 + ) + * 0.1 + ) + post_prev = torch.rand(num_tokens, hc_mult, 1, device=device, dtype=torch.float32) + comb_prev = ( + torch.rand(num_tokens, hc_mult, hc_mult, device=device, dtype=torch.float32) + * 0.25 + ) + fn = ( + torch.randn(hc_mult3, hc_hidden_size, device=device, dtype=torch.float32) * 0.01 + ) + hc_scale = torch.tensor([0.5, 0.25, 0.25], device=device, dtype=torch.float32) + hc_base = torch.zeros(hc_mult3, device=device, dtype=torch.float32) + norm_weight = ( + torch.ones(hidden_size, device=device, dtype=torch.bfloat16) + if use_norm + else None + ) + norm_eps = 1e-6 if use_norm else None + + rms_eps = 1e-6 + hc_eps = 1e-6 + sinkhorn_repeat = 2 + + residual_ref = post_ref = comb_ref = layer_ref = None + if num_tokens > 0: + residual_ref = mhc_post(x, residual, post_prev, comb_prev) + post_ref, comb_ref, layer_ref = mhc_pre( + residual_ref, + fn, + hc_scale, + hc_base, + rms_eps, + hc_eps, + hc_eps, + 2.0, + sinkhorn_repeat, + norm_weight=norm_weight, + norm_eps=norm_eps, + ) + residual_out, post_out, comb_out, layer_out = mhc_fused_post_pre( + x, + residual, + post_prev, + comb_prev, + fn, + hc_scale, + hc_base, + rms_eps, + hc_eps, + hc_eps, + 2.0, + sinkhorn_repeat, + norm_weight=norm_weight, + norm_eps=norm_eps, + ) + + torch.cuda.synchronize() + if num_tokens == 0: + assert residual_out.shape == residual.shape + assert post_out.shape == (0, hc_mult, 1) + assert comb_out.shape == (0, hc_mult, hc_mult) + assert layer_out.shape == (0, hidden_size) + assert residual_out.dtype == torch.bfloat16 + assert post_out.dtype == torch.float32 + assert comb_out.dtype == torch.float32 + assert layer_out.dtype == torch.bfloat16 + return + + assert residual_ref is not None + assert post_ref is not None + assert comb_ref is not None + assert layer_ref is not None + assert residual_out.shape == residual_ref.shape + assert post_out.shape == post_ref.shape + assert comb_out.shape == comb_ref.shape + assert layer_out.shape == layer_ref.shape + + torch.testing.assert_close(residual_out, residual_ref, atol=0, rtol=0) + torch.testing.assert_close(post_out, post_ref, atol=1e-3, rtol=1e-3) + torch.testing.assert_close(comb_out, comb_ref, atol=1e-3, rtol=1e-3) + layer_atol = 2e-2 if use_norm else 2e-3 + layer_rtol = 2e-2 if use_norm else 2e-3 + torch.testing.assert_close(layer_out, layer_ref, atol=layer_atol, rtol=layer_rtol) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_mla_cp_fa3_parity.py b/asian_ai/performance/SGLang/test/registered/kernels/test_mla_cp_fa3_parity.py new file mode 100644 index 0000000000000000000000000000000000000000..f38882c5ae35d3bd64ac792abfde2777a9402017 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_mla_cp_fa3_parity.py @@ -0,0 +1,210 @@ +"""FA3 numerical parity for MLA prefill CP. + +Verifies the rank-local zigzag-split FA3 path (``_mla_cp_attn`` + +``cp_attn_forward_extend`` in ``flashattention_backend.py``) matches a +single non-CP ``flash_attn_with_kvcache`` over the full sequence. + +Single-process, single-layer, pre-populated paged KV cache. Requires +FA3 ver=3 (Hopper+). +""" + +import math +import sys +from types import SimpleNamespace + +import pytest +import torch + +from sglang.srt.layers.utils.cp_utils import ( + ContextParallelMetadata, + cp_attn_forward_extend, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=30, stage="extra-a", runner_config="1-gpu-large") + +if not torch.cuda.is_available(): + pytest.skip(reason="CUDA required for FA3", allow_module_level=True) + +_cap = torch.cuda.get_device_capability(0) +if _cap[0] < 9: + pytest.skip( + reason=f"FA3 ver=3 requires Hopper (sm90+); got sm{_cap[0]}{_cap[1]}", + allow_module_level=True, + ) + +try: + from sgl_kernel.flash_attn import flash_attn_with_kvcache +except ImportError as e: + pytest.skip( + reason=f"sgl_kernel.flash_attn unavailable: {e}", + allow_module_level=True, + ) + +DEVICE = torch.device("cuda") +DTYPE = torch.bfloat16 + +# Default shape is DeepSeek V3/R1 TP=8 MLA: 16 heads, v=512, rope=64. +NUM_HEADS = 16 +V_HEAD_DIM = 512 +QK_ROPE_HEAD_DIM = 64 +PAGE_SIZE = 1 + + +def _build_cache_and_q(seq_len): + """Pre-populated paged KV cache + full-sequence q. + + Pre-population mirrors upstream ``rebuild_cp_kv_cache``, which all-gathers + rank-local KV into the global pool before the attention call, so each + rank's FA3 invocation sees the same fully-populated cache. + """ + num_pages = (seq_len + PAGE_SIZE - 1) // PAGE_SIZE + c_kv_cache = torch.randn( + num_pages, PAGE_SIZE, 1, V_HEAD_DIM, dtype=DTYPE, device=DEVICE + ) + k_rope_cache = torch.randn( + num_pages, PAGE_SIZE, 1, QK_ROPE_HEAD_DIM, dtype=DTYPE, device=DEVICE + ) + q_nope = torch.randn(seq_len, NUM_HEADS, V_HEAD_DIM, dtype=DTYPE, device=DEVICE) + q_rope = torch.randn( + seq_len, NUM_HEADS, QK_ROPE_HEAD_DIM, dtype=DTYPE, device=DEVICE + ) + page_table = torch.arange(num_pages, dtype=torch.int32, device=DEVICE).unsqueeze(0) + return c_kv_cache, k_rope_cache, q_nope, q_rope, page_table + + +def _full_seq_attn( + seq_len, q_nope, q_rope, c_kv_cache, k_rope_cache, page_table, softmax_scale +): + """Non-CP reference: single flash_attn_with_kvcache over the full seq.""" + return flash_attn_with_kvcache( + q=q_rope, + qv=q_nope, + k_cache=k_rope_cache, + v_cache=c_kv_cache, + page_table=page_table, + cache_seqlens=torch.tensor([seq_len], dtype=torch.int32, device=DEVICE), + cu_seqlens_q=torch.tensor([0, seq_len], dtype=torch.int32, device=DEVICE), + cu_seqlens_k_new=None, + max_seqlen_q=seq_len, + softmax_scale=softmax_scale, + causal=True, + ver=3, + ) + + +def _cp_attn_for_rank( + rank, + cp_size, + block_size, + q_nope, + q_rope, + c_kv_cache, + k_rope_cache, + page_table, + softmax_scale, +): + """Run the rank-local CP closure from ``flashattention_backend.py``. + + Zigzag layout: rank r gets blocks [r, num_blocks - 1 - r] where + num_blocks = cp_size * 2. kv_len for each half is the cumulative KV + extent through the end of that block. + """ + num_blocks = cp_size * 2 + b_prev, b_next = rank, num_blocks - 1 - rank + prev_slice = slice(b_prev * block_size, (b_prev + 1) * block_size) + next_slice = slice(b_next * block_size, (b_next + 1) * block_size) + + q_nope_local = torch.cat([q_nope[prev_slice], q_nope[next_slice]], dim=0) + q_rope_local = torch.cat([q_rope[prev_slice], q_rope[next_slice]], dim=0) + q_fused = torch.cat([q_nope_local, q_rope_local], dim=-1) + + cp_meta = ContextParallelMetadata( + kv_len_prev_tensor=torch.tensor( + [(b_prev + 1) * block_size], dtype=torch.int32, device=DEVICE + ), + kv_len_next_tensor=torch.tensor( + [(b_next + 1) * block_size], dtype=torch.int32, device=DEVICE + ), + cu_seqlens_q_prev_tensor=torch.tensor( + [0, block_size], dtype=torch.int32, device=DEVICE + ), + cu_seqlens_q_next_tensor=torch.tensor( + [0, block_size], dtype=torch.int32, device=DEVICE + ), + max_seqlen_q_prev=block_size, + max_seqlen_q_next=block_size, + total_q_prev_tokens=block_size, + ) + fb = SimpleNamespace(attn_cp_metadata=cp_meta) + + def _mla_cp_attn(q_chunk, cu_seqlens_q_cp, cache_seqlens_cp, max_seqlen_q_cp): + q_nope_chunk = q_chunk[..., :V_HEAD_DIM] + q_rope_chunk = q_chunk[..., V_HEAD_DIM:] + return flash_attn_with_kvcache( + q=q_rope_chunk, + qv=q_nope_chunk, + k_cache=k_rope_cache, + v_cache=c_kv_cache, + page_table=page_table, + cache_seqlens=cache_seqlens_cp, + cu_seqlens_q=cu_seqlens_q_cp, + cu_seqlens_k_new=None, + max_seqlen_q=max_seqlen_q_cp, + softmax_scale=softmax_scale, + causal=True, + ver=3, + ) + + local_out = cp_attn_forward_extend(fb, q_fused, DEVICE, _mla_cp_attn) + return local_out, prev_slice, next_slice + + +@pytest.mark.parametrize( + "cp_size, block_size", + [ + (2, 64), # DSv3 TP=8 baseline + (2, 128), # longer per-block seq + (4, 32), # multi-rank zigzag: rank r gets blocks [r, 7-r] + ], +) +def test_cp_parity(cp_size, block_size): + torch.manual_seed(0) + seq_len = block_size * cp_size * 2 + softmax_scale = 1.0 / math.sqrt(V_HEAD_DIM + QK_ROPE_HEAD_DIM) + + c_kv_cache, k_rope_cache, q_nope, q_rope, page_table = _build_cache_and_q(seq_len) + ref_out = _full_seq_attn( + seq_len, q_nope, q_rope, c_kv_cache, k_rope_cache, page_table, softmax_scale + ) + + for rank in range(cp_size): + local_out, prev_slice, next_slice = _cp_attn_for_rank( + rank, + cp_size, + block_size, + q_nope, + q_rope, + c_kv_cache, + k_rope_cache, + page_table, + softmax_scale, + ) + torch.testing.assert_close( + local_out[:block_size], + ref_out[prev_slice], + rtol=1e-3, + atol=5e-3, + msg=f"rank={rank} prev-half mismatch", + ) + torch.testing.assert_close( + local_out[block_size:], + ref_out[next_slice], + rtol=1e-3, + atol=5e-3, + msg=f"rank={rank} next-half mismatch", + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_sigmoid_gate_mul.py b/asian_ai/performance/SGLang/test/registered/kernels/test_sigmoid_gate_mul.py new file mode 100644 index 0000000000000000000000000000000000000000..7838029d5478edd2bda656fb18c7b10dd2c9f84c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_sigmoid_gate_mul.py @@ -0,0 +1,123 @@ +import sys + +import pytest +import torch + +from sglang.test.ci.ci_register import register_amd_ci + +register_amd_ci(est_time=4, suite="jit-kernel-unit-test-amd") + +DEVICE = "cuda" + + +def reference_sigmoid_gate_mul(x, gate): + return x * torch.sigmoid(gate) + + +# ── element-wise variant ── + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32]) +@pytest.mark.parametrize( + "shape", + [ + (1, 4096), + (4, 4096), + (8, 4096), + (32, 8192), + (1, 128), + (16, 16384), + ], +) +def test_sigmoid_gate_mul_correctness(shape, dtype): + from sglang.jit_kernel.triton.sigmoid_gate_mul import sigmoid_gate_mul + + torch.manual_seed(42) + x = torch.randn(shape, dtype=dtype, device=DEVICE) + gate = torch.randn(shape, dtype=dtype, device=DEVICE) + + ref = reference_sigmoid_gate_mul(x, gate) + out = sigmoid_gate_mul(x, gate) + + rtol = 1e-2 if dtype == torch.bfloat16 else 1e-3 + atol = 2e-2 if dtype == torch.bfloat16 else 1e-3 + torch.testing.assert_close(out, ref, rtol=rtol, atol=atol) + + +# ── broadcast variant ── + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32]) +@pytest.mark.parametrize( + "shape", + [ + (1, 4096), + (4, 4096), + (8, 4096), + (32, 8192), + (1, 128), + (16, 16384), + ], +) +def test_sigmoid_gate_mul_broadcast_correctness(shape, dtype): + from sglang.jit_kernel.triton.sigmoid_gate_mul import ( + sigmoid_gate_mul_broadcast, + ) + + torch.manual_seed(42) + bs, hidden_dim = shape + x = torch.randn(shape, dtype=dtype, device=DEVICE) + gate = torch.randn(bs, 1, dtype=dtype, device=DEVICE) + + ref = x * torch.sigmoid(gate.float()).to(dtype) + out = sigmoid_gate_mul_broadcast(x, gate) + + rtol = 1e-2 if dtype == torch.bfloat16 else 1e-3 + atol = 2e-2 if dtype == torch.bfloat16 else 1e-3 + torch.testing.assert_close(out, ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("shape", [(4, 4096), (1, 128)]) +def test_sigmoid_gate_mul_broadcast_does_not_modify_inputs(shape): + from sglang.jit_kernel.triton.sigmoid_gate_mul import ( + sigmoid_gate_mul_broadcast, + ) + + torch.manual_seed(42) + bs, hidden_dim = shape + x = torch.randn(shape, dtype=torch.bfloat16, device=DEVICE) + gate = torch.randn(bs, 1, dtype=torch.bfloat16, device=DEVICE) + x_orig = x.clone() + gate_orig = gate.clone() + + sigmoid_gate_mul_broadcast(x, gate) + + torch.testing.assert_close(x, x_orig, rtol=0, atol=0) + torch.testing.assert_close(gate, gate_orig, rtol=0, atol=0) + + +def test_sigmoid_gate_mul_broadcast_output_dtype(): + from sglang.jit_kernel.triton.sigmoid_gate_mul import ( + sigmoid_gate_mul_broadcast, + ) + + for dtype in [torch.bfloat16, torch.float16, torch.float32]: + x = torch.randn(4, 4096, dtype=dtype, device=DEVICE) + gate = torch.randn(4, 1, dtype=dtype, device=DEVICE) + out = sigmoid_gate_mul_broadcast(x, gate) + assert out.dtype == dtype, f"Expected {dtype}, got {out.dtype}" + + +def test_sigmoid_gate_mul_broadcast_contiguous_output(): + from sglang.jit_kernel.triton.sigmoid_gate_mul import ( + sigmoid_gate_mul_broadcast, + ) + + x = torch.randn(4, 4096, dtype=torch.bfloat16, device=DEVICE) + gate = torch.randn(4, 1, dtype=torch.bfloat16, device=DEVICE) + out = sigmoid_gate_mul_broadcast(x, gate) + assert out.is_contiguous() + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/kernels/test_sm120_paged_mqa_logits.py b/asian_ai/performance/SGLang/test/registered/kernels/test_sm120_paged_mqa_logits.py new file mode 100644 index 0000000000000000000000000000000000000000..aaddbe168f6576cb3ea0e4eee44b939c3d76a48a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kernels/test_sm120_paged_mqa_logits.py @@ -0,0 +1,314 @@ +"""SM120 fp8_paged_mqa_logits_torch_sm120 vectorized PyTorch fallback tests. + +Validates that the vectorized SM120-specific implementation matches the loopy +reference (`fp8_paged_mqa_logits_torch`) and is CUDA-graph compatible. + +Coverage: +- Numeric equivalence vs reference at small shapes +- Both KV-cache dtype views (uint8 raw / float8_e4m3fn) — guards against the + historic garbled-output bug where Triton kernels treated uint8 bytes as raw + integers instead of FP8 (dsv4_sm120_progress.md §4) +- Variable per-batch seq_lens with -inf masking semantics +- CUDA graph capture + replay equivalence (no .item() / data-dependent shapes) +- Shape-assertion guards + +Pure-PyTorch implementations on any CUDA GPU — no SM120 hardware required. +""" + +from __future__ import annotations + +import unittest + +import torch + +from sglang.srt.layers.attention.dsv4.indexer import ( + FP8_DTYPE, + fp8_paged_mqa_logits_torch, + fp8_paged_mqa_logits_torch_sm120, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-small") + + +# DSv4 indexer cache layout (fixed by deepseek_v4_memory_pool.DeepSeekV4IndexerPool): +# page_size = 64 tokens +# head_dim = 128 (FP8 values per token) +# quant_block_size = 128 -> num_scales_per_token = 1 (fp32 scale) +# per-page memory: [page_size*head_dim FP8 bytes][page_size*4 scale bytes] +# = [8192][256] = 8448 bytes +# The (block_size, 1, head_dim+4) shape is a fiction for downstream consumers. +PAGE_SIZE = 64 +HEAD_DIM = 128 +SCALE_BYTES_PER_TOKEN = 4 +HEAD_DIM_WITH_SF = HEAD_DIM + SCALE_BYTES_PER_TOKEN # 132 +PAGE_BYTES = PAGE_SIZE * HEAD_DIM + PAGE_SIZE * SCALE_BYTES_PER_TOKEN # 8448 + + +def _build_kvcache( + num_pages: int, + *, + dtype_view: torch.dtype, + device: torch.device, + seed: int = 0, +) -> torch.Tensor: + """Construct a paged KV cache matching the production layout. + + Returns a tensor shaped (num_pages, PAGE_SIZE, 1, HEAD_DIM_WITH_SF) whose + underlying memory is the same regardless of `dtype_view`: + - [0 : PAGE_SIZE*HEAD_DIM) : random FP8 bit patterns (values) + - [PAGE_SIZE*HEAD_DIM : PAGE_BYTES) : random positive fp32 scales (bytes) + """ + g = torch.Generator(device="cpu").manual_seed(seed) + raw = torch.empty(num_pages, PAGE_BYTES, dtype=torch.uint8, device=device) + + # Random FP8 byte pattern for the value section. Bias away from extreme + # bit patterns that map to NaN/Inf in float8_e4m3fn (sign|exp4|mantissa3; + # exp=0xF mantissa!=0 -> NaN). Restricting to [0, 0x6F] keeps |x| < 256. + val_bytes = torch.randint( + 0, 0x70, (num_pages, PAGE_SIZE * HEAD_DIM), generator=g, dtype=torch.uint8 + ).to(device) + raw[:, : PAGE_SIZE * HEAD_DIM] = val_bytes + + # Positive fp32 scales in [0.05, 0.55]. Byte-view into the trailing region. + scales = ( + torch.rand((num_pages, PAGE_SIZE), generator=g, dtype=torch.float32).to(device) + * 0.5 + + 0.05 + ) + raw[:, PAGE_SIZE * HEAD_DIM :] = scales.contiguous().view(torch.uint8) + + kv = raw.view(num_pages, PAGE_SIZE, 1, HEAD_DIM_WITH_SF) + return kv if dtype_view == torch.uint8 else kv.view(dtype=dtype_view) + + +def _build_inputs( + batch_size: int, + seq_lens: list[int], + *, + kv_dtype_view: torch.dtype, + num_heads: int = 32, + device: torch.device = torch.device("cuda"), + seed: int = 0, +): + assert len(seq_lens) == batch_size + max_seq_len = max(seq_lens) + max_pages = (max_seq_len + PAGE_SIZE - 1) // PAGE_SIZE + # One global page pool, batch picks its own page ids. + num_pages_total = batch_size * max_pages + 1 + + kvcache = _build_kvcache( + num_pages_total, dtype_view=kv_dtype_view, device=device, seed=seed + ) + + g = torch.Generator(device="cpu").manual_seed(seed + 1) + # Construct query as random bf16->fp8 to keep values inside fp8 range. + q_bf16 = torch.randn( + (batch_size, 1, num_heads, HEAD_DIM), generator=g, dtype=torch.float32 + ).to(device) + q_bf16 = q_bf16.clamp_(-2.0, 2.0) + q_fp8 = q_bf16.to(FP8_DTYPE) + if kv_dtype_view == torch.uint8: + # Query dtype isn't toggled — only kvcache. q always fp8. + pass + + weight = ( + torch.rand((batch_size, num_heads), generator=g, dtype=torch.float32).to(device) + * 0.5 + ) + + seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device) + + # Each batch occupies its own slice of pages, randomized for realism. + page_table = torch.zeros((batch_size, max_pages), dtype=torch.int32, device=device) + for i in range(batch_size): + page_table[i] = torch.arange( + 1 + i * max_pages, 1 + (i + 1) * max_pages, dtype=torch.int32, device=device + ) + + return q_fp8, kvcache, weight, seq_lens_t, page_table, max_seq_len + + +def _compare( + ref: torch.Tensor, + sm120: torch.Tensor, + seq_lens: torch.Tensor, + *, + atol: float = 1e-3, + rtol: float = 1e-3, +): + """Compare reference (uninitialized beyond seq_len) vs SM120 (-inf beyond).""" + # Valid positions must match + batch_size, max_seq_len = ref.shape + for i in range(batch_size): + sl = int(seq_lens[i].item()) + torch.testing.assert_close( + ref[i, :sl], sm120[i, :sl], atol=atol, rtol=rtol, equal_nan=False + ) + # Invalid positions in SM120 output must be -inf + positions = torch.arange(max_seq_len, device=sm120.device) + invalid = positions.unsqueeze(0) >= seq_lens.unsqueeze(1) + assert torch.all( + torch.isinf(sm120[invalid]) & (sm120[invalid] < 0) + ), "SM120 output must fill invalid positions with -inf" + + +class TestSM120PagedMqaLogitsTorch(CustomTestCase): + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA required") + cls.device = torch.device("cuda") + + def _run_one( + self, + batch_size: int, + seq_lens: list[int], + kv_dtype_view: torch.dtype, + num_heads: int = 32, + ): + q, kv, w, sl, pt, msl = _build_inputs( + batch_size, + seq_lens, + kv_dtype_view=kv_dtype_view, + num_heads=num_heads, + device=self.device, + ) + # Reference (loopy) + ref = fp8_paged_mqa_logits_torch( + q, + kv, + w, + sl, + pt, + deep_gemm_metadata=None, + max_seq_len=msl, + clean_logits=False, + ) + # SM120 vectorized + sm120 = fp8_paged_mqa_logits_torch_sm120( + q, + kv, + w, + sl, + pt, + deep_gemm_metadata=None, + max_seq_len=msl, + clean_logits=False, + ) + _compare(ref, sm120, sl) + + def test_equiv_fp8_view_bs1(self): + self._run_one(1, [128], FP8_DTYPE) + + def test_equiv_fp8_view_bs4_uniform(self): + self._run_one(4, [128, 128, 128, 128], FP8_DTYPE) + + def test_equiv_fp8_view_bs4_variable(self): + self._run_one(4, [40, 96, 200, 256], FP8_DTYPE) + + def test_equiv_uint8_view_bs1(self): + """Regression guard: KV cache viewed as raw uint8 (no FP8 dtype hint). + + Historic bug (progress doc §4): some kernels treated uint8 bytes as raw + integers, producing garbled attention output. The vectorized impl must + produce the same numbers as the loopy reference regardless of the + caller's KV view dtype. + """ + self._run_one(1, [128], torch.uint8) + + def test_equiv_uint8_view_bs4_variable(self): + self._run_one(4, [40, 96, 200, 256], torch.uint8) + + def test_seq_lens_zero_remainder(self): + """seq_len not aligned to page_size — last partial page must mask correctly.""" + self._run_one(2, [65, 129], FP8_DTYPE) # 65 = 1 full page + 1 token + + def test_seq_lens_full_pages(self): + self._run_one(2, [64, 192], FP8_DTYPE) + + def test_seq_lens_2d_input_accepted(self): + """SM120 impl squeezes seq_lens if dim>1 (matches indexer.py call site).""" + q, kv, w, sl, pt, msl = _build_inputs( + 2, [64, 128], kv_dtype_view=FP8_DTYPE, device=self.device + ) + sl_2d = sl.unsqueeze(-1) # (B, 1) + ref = fp8_paged_mqa_logits_torch( + q, kv, w, sl, pt, None, max_seq_len=msl, clean_logits=False + ) + sm120 = fp8_paged_mqa_logits_torch_sm120( + q, kv, w, sl_2d, pt, None, max_seq_len=msl, clean_logits=False + ) + _compare(ref, sm120, sl) + + def test_cuda_graph_capture_and_replay(self): + """No .item() / data-dependent control flow — must be CUDA-graph safe.""" + batch_size = 2 + seq_lens = [128, 192] + q, kv, w, sl, pt, msl = _build_inputs( + batch_size, seq_lens, kv_dtype_view=FP8_DTYPE, device=self.device + ) + + # Warmup outside graph + for _ in range(2): + _ = fp8_paged_mqa_logits_torch_sm120( + q, kv, w, sl, pt, None, max_seq_len=msl, clean_logits=False + ) + torch.cuda.synchronize() + + # Pre-allocated output (graph replay reuses this buffer) + static_logits_holder = {} + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + out = fp8_paged_mqa_logits_torch_sm120( + q, kv, w, sl, pt, None, max_seq_len=msl, clean_logits=False + ) + static_logits_holder["out"] = out + + # Eager reference using the same inputs + ref = fp8_paged_mqa_logits_torch_sm120( + q, kv, w, sl, pt, None, max_seq_len=msl, clean_logits=False + ) + + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close( + static_logits_holder["out"], ref, atol=1e-5, rtol=1e-5 + ) + + # Replay with a different seq_lens (in-place edit of the captured tensor) + sl_new = torch.tensor([64, 256], dtype=torch.int32, device=self.device) + sl.copy_(sl_new) + graph.replay() + torch.cuda.synchronize() + ref_new = fp8_paged_mqa_logits_torch_sm120( + q, kv, w, sl, pt, None, max_seq_len=msl, clean_logits=False + ) + torch.testing.assert_close( + static_logits_holder["out"], ref_new, atol=1e-5, rtol=1e-5 + ) + + def test_shape_assertions(self): + """Wrong head_dim or block_size must raise.""" + q, kv, w, sl, pt, msl = _build_inputs( + 1, [64], kv_dtype_view=FP8_DTYPE, device=self.device + ) + # head_dim != 128 + bad_q = q[..., :64] + with self.assertRaises(AssertionError): + fp8_paged_mqa_logits_torch_sm120( + bad_q, kv, w, sl, pt, None, max_seq_len=msl, clean_logits=False + ) + # clean_logits=True not supported + with self.assertRaises(AssertionError): + fp8_paged_mqa_logits_torch_sm120( + q, kv, w, sl, pt, None, max_seq_len=msl, clean_logits=True + ) + + +if __name__ == "__main__": + import sys + + sys.exit(unittest.main()) diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_e2e_base.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_e2e_base.py new file mode 100644 index 0000000000000000000000000000000000000000..7d250e4cee191602ac7fe902bda890d1f74f510c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_e2e_base.py @@ -0,0 +1,31 @@ +import unittest + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.kv_canary.e2e_base import ( + _LONG_PROMPT_BODY, + _UNIQUE_PROMPT_FIRST_CHARS, + _make_unique_prompts, +) +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=1, suite="base-c-test-cpu") + + +class TestCanaryE2EBase(CustomTestCase): + def test_make_unique_prompts_have_distinct_first_characters(self) -> None: + """Verify generated prompts use distinct first characters and all end with the shared long body.""" + prompts = _make_unique_prompts(8) + + self.assertEqual(len({prompt[0] for prompt in prompts}), len(prompts)) + self.assertTrue(all(prompt.endswith(_LONG_PROMPT_BODY) for prompt in prompts)) + + def test_make_unique_prompts_rejects_more_prompts_than_distinct_first_characters( + self, + ) -> None: + """Verify prompt generation rejects requests beyond the unique prefix budget.""" + with self.assertRaisesRegex(ValueError, "unique prompt count"): + _make_unique_prompts(len(_UNIQUE_PROMPT_FIRST_CHARS) + 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_baseline.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..4184d1363df06f626cc7a37a74624b953ccc26c4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_baseline.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import unittest + +from sglang.srt.kv_canary.config import CanaryMode +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.consts import SWA_POOL_SERVER_ARGS +from sglang.test.kv_canary.e2e_base import CanaryE2EBase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=236, stage="extra-a", runner_config="1-gpu-small-amd") + + +class _BaselineBase(CanaryE2EBase): + """No perturb, kv-canary=log, sweep off. Server should run clean with no canary + violations and every request must come back 200.""" + + kv_canary_mode = CanaryMode.LOG + extra_env = {} + + @classmethod + def setUpClass(cls) -> None: + if cls is _BaselineBase: + raise unittest.SkipTest("abstract base; concrete subclasses set model_mode") + super().setUpClass() + + def test_no_violation(self) -> None: + """Verify the baseline canary run completes without violations.""" + for _ in range(self.workload_n_batches): + self.send_parallel_requests() + self.assert_no_violation(wait_seconds=2.0) + self.maybe_assert_swa_divergence_observed() + + +class TestBaselineMha(_BaselineBase): + model_mode = "mha" + + +class TestBaselineSwa(_BaselineBase): + model_mode = "swa" + extra_server_args = SWA_POOL_SERVER_ARGS + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_bench_speed.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_bench_speed.py new file mode 100644 index 0000000000000000000000000000000000000000..31fde4c3c4e57ecf87fb4af4b08a42afeada6297 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_bench_speed.py @@ -0,0 +1,259 @@ +from __future__ import annotations + +import argparse +import dataclasses +import os +import unittest +from pathlib import Path +from typing import ClassVar, Optional + +from sglang.bench_one_batch_server import ( + BenchArgs, + BenchOneCaseResult, + run_benchmark_internal, +) +from sglang.srt.entrypoints.http_server import launch_server +from sglang.srt.server_args import ServerArgs +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import DEFAULT_PORT_FOR_SRT_TEST_RUNNER + +# CUDA-only: this self-bench asserts a 1.0% kv_canary overhead budget tuned on +# the CUDA (H100) runner. On ROCm the measured overhead is ~1.26%, so the +# benchmark is not portable as-is; keep it off AMD CI rather than register-and-skip. +register_cuda_ci(est_time=600, stage="extra-a", runner_config="1-gpu-large") + + +_QWEN3_MODEL = "Qwen/Qwen3-30B-A3B" +_QWEN3_SCENARIO_MODEL = "qwen3-30b-a3b" + +_PROFILE_DIR_ENV = "SGLANG_KV_CANARY_PROFILE_DIR" +_PROFILE_STEPS = 30 +_PROFILE_NO_GRAPH_OUTPUT_LEN = 3 +# start_profile blocks until num_steps server steps complete, so it must be <= actual decode steps. +_PROFILE_NO_GRAPH_STEPS = 3 + + +def _make_server_args( + *, canary_on: bool, disable_cuda_graph: bool = False +) -> ServerArgs: + # install_canary asserts --disable-piecewise-cuda-graph; pass on both sides for apples-to-apples. + extra = [ + "--model-path", + _QWEN3_MODEL, + "--disable-piecewise-cuda-graph", + ] + if disable_cuda_graph: + extra.append("--disable-cuda-graph") + if canary_on: + extra += ["--kv-canary", "raise"] + extra += ["--port", str(DEFAULT_PORT_FOR_SRT_TEST_RUNNER)] + + parser = argparse.ArgumentParser() + ServerArgs.add_cli_args(parser) + namespace = parser.parse_args(extra) + return ServerArgs.from_cli_args(namespace) + + +def _make_bench_args(*, batch_size: int, input_len: int, output_len: int) -> BenchArgs: + return BenchArgs( + run_name=f"canary_self_bench_bs{batch_size}_isl{input_len}_osl{output_len}", + batch_size=(batch_size,), + input_len=(input_len,), + output_len=(output_len,), + temperature=0.0, + skip_warmup=False, + show_report=True, + dataset_name="random", + seed=42, + ) + + +def _run_one_canary_setting( + *, + canary_on: bool, + batch_size: int, + input_len: int, + output_len: int, + disable_cuda_graph: bool = False, + profile_output_dir: Optional[Path] = None, + profile_steps: int = _PROFILE_STEPS, +) -> BenchOneCaseResult: + server_args = _make_server_args( + canary_on=canary_on, disable_cuda_graph=disable_cuda_graph + ) + bench_args = _make_bench_args( + batch_size=batch_size, input_len=input_len, output_len=output_len + ) + if profile_output_dir is not None: + profile_output_dir.mkdir(parents=True, exist_ok=True) + bench_args = dataclasses.replace( + bench_args, + profile=True, + profile_steps=profile_steps, + profile_output_dir=str(profile_output_dir), + ) + + results, _server_info = run_benchmark_internal( + server_args=server_args, + bench_args=bench_args, + launch_server_func=launch_server, + ) + if not results: + # run_benchmark_internal returns no rows when the bench was skipped + # at the token-capacity guard inside it (the Qwen3-30B-A3B model + # leaves only ~12GB for KV cache on an H100; this test's bs128 + + # 1024 osl needs more than that). Treat that as a hardware-level + # skip rather than a test failure: the canary overhead claim is + # still meaningful when the runner has enough memory. + raise unittest.SkipTest( + f"run_benchmark_internal returned no rows (canary_on={canary_on}, " + f"bs={batch_size}, isl={input_len}, osl={output_len}); the runner's " + f"KV cache is too small to fit this configuration -- nothing to measure." + ) + return results[0] + + +def _make_scenario_key(*, batch_size: int, input_len: int, output_len: int) -> str: + workload = "prefill" if output_len == 1 else "decode" + return ( + f"{_QWEN3_SCENARIO_MODEL}/{workload}_bs{batch_size}" + f"_isl{input_len}_osl{output_len}" + ) + + +def _resolve_profile_root() -> Optional[Path]: + raw = os.getenv(_PROFILE_DIR_ENV) + return Path(raw).expanduser().resolve() if raw else None + + +class TestCanarySelfBenchSpeed(unittest.TestCase): + bench_timeout: ClassVar[float] = 1800.0 + + def _capture_profiles( + self, + *, + scenario_key: str, + profile_root: Path, + batch_size: int, + input_len: int, + output_len: int, + ) -> None: + scenario_slug = scenario_key.replace("/", "_") + scenario_root = profile_root / f"{scenario_slug}_on" + + graph_dir = scenario_root / "cuda_graph" + # +3 to cover prefill chunks + tail; capped so long decode runs still stop after 30 steps. + graph_profile_steps = min(_PROFILE_STEPS, output_len + 3) + graph_run = _run_one_canary_setting( + canary_on=True, + batch_size=batch_size, + input_len=input_len, + output_len=output_len, + profile_output_dir=graph_dir, + profile_steps=graph_profile_steps, + ) + print( + f"[canary self-bench] {scenario_key} profile cuda_graph: " + f"on={graph_run.latency:.4f}s (trace under {graph_dir})", + flush=True, + ) + + no_graph_dir = scenario_root / "no_cuda_graph_osl3" + no_graph_run = _run_one_canary_setting( + canary_on=True, + batch_size=batch_size, + input_len=input_len, + output_len=_PROFILE_NO_GRAPH_OUTPUT_LEN, + disable_cuda_graph=True, + profile_output_dir=no_graph_dir, + profile_steps=_PROFILE_NO_GRAPH_STEPS, + ) + print( + f"[canary self-bench] {scenario_key} profile no_cuda_graph_osl3: " + f"on={no_graph_run.latency:.4f}s (trace under {no_graph_dir}); " + f"off baseline + overhead assertion skipped.", + flush=True, + ) + + def _measure_overhead( + self, + *, + batch_size: int, + input_len: int, + output_len: int, + max_overhead_pct: float, + ) -> None: + scenario_key = _make_scenario_key( + batch_size=batch_size, input_len=input_len, output_len=output_len + ) + profile_root = _resolve_profile_root() + + if profile_root is not None: + self._capture_profiles( + scenario_key=scenario_key, + profile_root=profile_root, + batch_size=batch_size, + input_len=input_len, + output_len=output_len, + ) + return + + off = _run_one_canary_setting( + canary_on=False, + batch_size=batch_size, + input_len=input_len, + output_len=output_len, + ) + on = _run_one_canary_setting( + canary_on=True, + batch_size=batch_size, + input_len=input_len, + output_len=output_len, + ) + overhead_pct = ((on.latency - off.latency) / off.latency) * 100.0 + summary = ( + f"[canary self-bench] {scenario_key}: " + f"off={off.latency:.4f}s on={on.latency:.4f}s overhead={overhead_pct:.2f}%" + ) + print(summary, flush=True) + self.assertLess( + overhead_pct, + max_overhead_pct, + msg=(f"{summary} — exceeds {max_overhead_pct:.1f}% budget"), + ) + + def test_qwen3_prefill_overhead_bs32_isl16384_osl1(self) -> None: + # TODO: tighten further once the per-forward elementwise glue + plan_offsets + # single-program kernel are optimized (observed ~2.17% on Qwen3-30B-A3B, H200). + self._measure_overhead( + batch_size=32, + input_len=16384, + output_len=1, + max_overhead_pct=3.0, + ) + + def test_qwen3_decode_overhead_bs64_isl256_osl512(self) -> None: + # TODO: tighten further once per-forward canary glue is reduced (observed ~0.52% on + # Qwen3-30B-A3B, H200 — already amortizes well at large bs). The smaller + # 64 * (256+512) = 49K-token budget fits the ~94K KV-cache slice that + # extra-a-test-1-gpu-large (H100) leaves after loading the 30B MoE. + self._measure_overhead( + batch_size=64, + input_len=256, + output_len=512, + max_overhead_pct=1.0, + ) + + def test_qwen3_decode_overhead_bs1_isl512_osl1024(self) -> None: + # TODO: tighten further once the per-forward elementwise glue + plan_offsets + # single-program kernel are optimized (observed ~2.10% on Qwen3-30B-A3B, H200). + self._measure_overhead( + batch_size=1, + input_len=512, + output_len=1024, + max_overhead_pct=3.0, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pd_baseline.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pd_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..ba52df700f1f237436e2db5dbacda34259b0261e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pd_baseline.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import unittest + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.pd_fixture import CanaryPDFixture + +register_cuda_ci(est_time=180, stage="extra-a", runner_config="2-gpu-large") +register_amd_ci(est_time=106, stage="extra-a", runner_config="2-gpu-large-amd") + + +class TestPDBaselineMha(CanaryPDFixture): + model_mode = "mha" + + def test_clean_pd_run_produces_no_canary_violation_on_either_side(self) -> None: + self.send_parallel_short_requests(n=4) + self.assert_no_violation(side="prefill") + self.assert_no_violation(side="decode") + + +class TestPDBaselineSwa(CanaryPDFixture): + model_mode = "swa" + + def test_clean_pd_run_produces_no_canary_violation_on_either_side(self) -> None: + self.send_parallel_short_requests(n=4) + self.assert_no_violation(side="prefill") + self.assert_no_violation(side="decode") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pd_perturb.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pd_perturb.py new file mode 100644 index 0000000000000000000000000000000000000000..1b133967d60099b601ab149e4d3c22b9354c4398 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pd_perturb.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import unittest +from typing import ClassVar + +from sglang.srt.kv_canary.perturb.config import TargetGroupKind +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.pd_fixture import CanaryPDFixture + +register_cuda_ci(est_time=180, stage="extra-a", runner_config="2-gpu-large") +register_amd_ci(est_time=231, stage="extra-a", runner_config="2-gpu-large-amd") + + +class _PDPerturbBase(CanaryPDFixture): + target_group: ClassVar[TargetGroupKind] + + @classmethod + def setUpClass(cls) -> None: + if cls is _PDPerturbBase: + raise unittest.SkipTest( + "abstract base; concrete subclasses set model_mode + target_group" + ) + cls.extra_prefill_env = { + "SGLANG_KV_CANARY_PERTURB_REAL_KV_POST_FORWARD_PROB": "1.0", + "SGLANG_KV_CANARY_PERTURB_TARGET_GROUP": str(cls.target_group), + "SGLANG_KV_CANARY_PERTURB_WARMUP_STEPS": "0", + } + cls.extra_decode_env = { + "SGLANG_KV_CANARY_PERTURB_REAL_KV_POST_FORWARD_PROB": "0", + "SGLANG_KV_CANARY_PERTURB_REAL_KV_USED_PROB": "0", + "SGLANG_KV_CANARY_PERTURB_REAL_KV_UNUSED_CACHE_PROB": "0", + "SGLANG_KV_CANARY_PERTURB_REQ_TO_TOKEN_PROB": "0", + } + super().setUpClass() + + def test_p_side_perturb_surfaces_real_kv_hash_violation_on_decode_side( + self, + ) -> None: + # send_parallel_short_requests defaults to max_new_tokens=100 so D-side runs + # decode forwards that exercise canary verify on the transferred prefix. + # + # distinct_prompts is required for the violation to surface reliably: + # with a shared prompt, P-side radix caching rewrites each request's + # req_to_token row to the first-inserted (canonical) copy's slots in + # cache_unfinished_req BEFORE send_kv_chunk snapshots the indices, so a + # flip on a deduped duplicate slot is freed untransferred and never + # re-verified on either side. + self.send_parallel_short_requests(n=4, distinct_prompts=True) + # D-side: first decode forward re-verifies the transferred prefix slots, + # so the flip MUST surface as real_kv_hash violation. + self.assert_per_forward_violation_reported( + fail_reason="verify_real_kv_hash", + target_group=self.target_group, + side="decode", + flush_wait_seconds=4.0, + ) + # P-side: flip happens post-TAIL of the prefill forward, and PD prefill + # does not run another forward on P that would verify the perturbed slot, + # so P MUST stay silent (no false-positive violations) for this perturb + # point. If a future canary feature adds post-prefill verify on P, this + # assert will start failing and should be upgraded to assert the + # violation on P-side too. + self.assert_no_violation(side="prefill", wait_seconds=0.5) + + +class TestPDPerturbMhaFull(_PDPerturbBase): + model_mode = "mha" + target_group = TargetGroupKind.FULL + + +class TestPDPerturbSwaFull(_PDPerturbBase): + model_mode = "swa" + target_group = TargetGroupKind.FULL + + +class TestPDPerturbSwaSwa(_PDPerturbBase): + model_mode = "swa" + target_group = TargetGroupKind.SWA + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_raise.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_raise.py new file mode 100644 index 0000000000000000000000000000000000000000..4ac5f3051540a53e9378f3711efd3bf1c9ebc018 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_raise.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import unittest + +from sglang.srt.kv_canary.config import CanaryMode +from sglang.srt.kv_canary.perturb.config import TargetGroupKind +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.e2e_base import CanaryE2EBase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=50, stage="extra-a", runner_config="1-gpu-small-amd") + + +class TestPerturbRaiseMha(CanaryE2EBase): + model_mode = "mha" + kv_canary_mode = CanaryMode.RAISE + extra_server_args = ("--kv-canary-real-data", "partial", "--skip-server-warmup") + extra_env = { + "SGLANG_KV_CANARY_PERTURB_REAL_KV_USED_PROB": "0.1", + "SGLANG_KV_CANARY_PERTURB_TARGET_GROUP": "full", + "SGLANG_KV_CANARY_PERTURB_WARMUP_STEPS": "0", + } + + def test_real_kv_used_perturbation_raises_in_raise_mode(self) -> None: + """Verify raise mode surfaces real KV perturbation as a logged violation.""" + try: + self.send_parallel_requests( + n=4, + assert_all_success=False, + timeout=30.0, + ) + except Exception: + pass + self.assert_per_forward_violation_reported( + fail_reason="verify_real_kv_hash", + target_group=TargetGroupKind.FULL, + flush_wait_seconds=3.0, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_real_kv_unused_cache.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_real_kv_unused_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e5bd7d71cd21473ff3135cfab5d972861b1102a5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_real_kv_unused_cache.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import unittest +from typing import ClassVar + +from sglang.srt.kv_canary.config import CanaryMode +from sglang.srt.kv_canary.perturb.config import TargetGroupKind +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.consts import SWA_POOL_SERVER_ARGS +from sglang.test.kv_canary.e2e_base import CanaryE2EBase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=503, stage="extra-a", runner_config="1-gpu-small-amd") + + +class _PerturbRealKvUnusedCacheBase(CanaryE2EBase): + kv_canary_mode = CanaryMode.LOG + extra_server_args = ( + "--kv-canary-real-data", + "partial", + "--kv-canary-sweep-interval", + "4", + ) + use_unique_prompts = True + + target_group: ClassVar[TargetGroupKind] + + @classmethod + def setUpClass(cls) -> None: + if cls is _PerturbRealKvUnusedCacheBase: + raise unittest.SkipTest( + "abstract base; concrete subclasses set model_mode + target_group" + ) + cls.extra_env = { + "SGLANG_KV_CANARY_PERTURB_REAL_KV_UNUSED_CACHE_PROB": "0.1", + "SGLANG_KV_CANARY_PERTURB_TARGET_GROUP": str(cls.target_group), + "SGLANG_KV_CANARY_PERTURB_WARMUP_STEPS": "0", + } + super().setUpClass() + + def test_real_kv_unused_cache_perturbation_reports_sweep_real_kv_hash_violation( + self, + ) -> None: + """Verify cached unused KV perturbation is caught by sweep verification.""" + # Step 1: first batch builds radix entries that will become orphans once finished. + self.send_parallel_requests(n=8) + # Step 2: second batch drives more forward passes so the sweep cadence fires + # while the orphan slots are still cached. + self.send_parallel_requests(n=8) + self.assert_sweep_violation_reported( + fail_reason="verify_real_kv_hash", + target_group=self.target_group, + flush_wait_seconds=5.0, + ) + self.maybe_assert_swa_divergence_observed() + + +class TestPerturbRealKvUnusedCacheMhaFull(_PerturbRealKvUnusedCacheBase): + model_mode = "mha" + target_group = TargetGroupKind.FULL + + +class TestPerturbRealKvUnusedCacheSwaFull(_PerturbRealKvUnusedCacheBase): + model_mode = "swa" + target_group = TargetGroupKind.FULL + extra_server_args = ( + *_PerturbRealKvUnusedCacheBase.extra_server_args, + *SWA_POOL_SERVER_ARGS, + ) + + +class TestPerturbRealKvUnusedCacheSwaSwa(_PerturbRealKvUnusedCacheBase): + model_mode = "swa" + target_group = TargetGroupKind.SWA + extra_server_args = ( + *_PerturbRealKvUnusedCacheBase.extra_server_args, + *SWA_POOL_SERVER_ARGS, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_real_kv_used.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_real_kv_used.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf98416a039aadd33a93ec4da3fa07641710fdc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_real_kv_used.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +import unittest +from typing import ClassVar + +from sglang.srt.kv_canary.config import CanaryMode +from sglang.srt.kv_canary.perturb.config import TargetGroupKind +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.consts import SWA_POOL_SERVER_ARGS +from sglang.test.kv_canary.e2e_base import CanaryE2EBase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=256, stage="extra-a", runner_config="1-gpu-small-amd") + + +class _PerturbRealKvUsedBase(CanaryE2EBase): + kv_canary_mode = CanaryMode.LOG + extra_server_args = ("--kv-canary-real-data", "partial") + + target_group: ClassVar[TargetGroupKind] + + @classmethod + def setUpClass(cls) -> None: + if cls is _PerturbRealKvUsedBase: + raise unittest.SkipTest( + "abstract base; concrete subclasses set model_mode + target_group" + ) + cls.extra_env = { + "SGLANG_KV_CANARY_PERTURB_REAL_KV_USED_PROB": "0.1", + "SGLANG_KV_CANARY_PERTURB_TARGET_GROUP": str(cls.target_group), + "SGLANG_KV_CANARY_PERTURB_WARMUP_STEPS": "0", + } + super().setUpClass() + + def test_real_kv_used_perturbation_reports_real_kv_hash_violation(self) -> None: + """Verify active real KV perturbation reports a real KV hash violation.""" + for _ in range(self.workload_n_batches): + self.send_parallel_requests() + self.assert_per_forward_violation_reported( + fail_reason="verify_real_kv_hash", + target_group=self.target_group, + ) + self.maybe_assert_swa_divergence_observed() + + +class TestPerturbRealKvUsedMhaFull(_PerturbRealKvUsedBase): + model_mode = "mha" + target_group = TargetGroupKind.FULL + + +class TestPerturbRealKvUsedSwaFull(_PerturbRealKvUsedBase): + model_mode = "swa" + target_group = TargetGroupKind.FULL + extra_server_args = ( + *_PerturbRealKvUsedBase.extra_server_args, + *SWA_POOL_SERVER_ARGS, + ) + + +class TestPerturbRealKvUsedSwaSwa(_PerturbRealKvUsedBase): + model_mode = "swa" + target_group = TargetGroupKind.SWA + extra_server_args = ( + *_PerturbRealKvUsedBase.extra_server_args, + *SWA_POOL_SERVER_ARGS, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_req_to_token.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_req_to_token.py new file mode 100644 index 0000000000000000000000000000000000000000..738e381ee0254667d09412f00c36a800c74e8502 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_perturb_req_to_token.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import unittest + +from sglang.srt.kv_canary.config import CanaryMode +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.consts import SWA_POOL_SERVER_ARGS +from sglang.test.kv_canary.e2e_base import CanaryE2EBase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=175, stage="extra-a", runner_config="1-gpu-small-amd") + + +class _PerturbReqToTokenBase(CanaryE2EBase): + kv_canary_mode = CanaryMode.LOG + extra_env = { + "SGLANG_KV_CANARY_PERTURB_REQ_TO_TOKEN_PROB": "0.1", + "SGLANG_KV_CANARY_PERTURB_WARMUP_STEPS": "0", + # req_to_token perturbation deliberately corrupts the slot mapping + # by design, which the scheduler's on-idle invariant checker reports + # as a pool memory leak (perturbed slot is freed, original slot + # still looks busy). That's expected for this test; disable strict + # mode so the leak warning doesn't crash the scheduler. + "SGLANG_ENABLE_STRICT_MEM_CHECK_DURING_IDLE": "0", + } + + @classmethod + def setUpClass(cls) -> None: + if cls is _PerturbReqToTokenBase: + raise unittest.SkipTest("abstract base; concrete subclasses set model_mode") + super().setUpClass() + + def test_req_to_token_perturbation_reports_chain_hash_violation(self) -> None: + """Verify req_to_token perturbation reports a chain hash violation.""" + for _ in range(self.workload_n_batches): + self.send_parallel_requests() + self.assert_per_forward_violation_reported(fail_reason="verify_chain_hash") + self.maybe_assert_swa_divergence_observed() + + +class TestPerturbReqToTokenMha(_PerturbReqToTokenBase): + model_mode = "mha" + + +class TestPerturbReqToTokenSwa(_PerturbReqToTokenBase): + model_mode = "swa" + extra_server_args = SWA_POOL_SERVER_ARGS + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pp_baseline.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pp_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..702353706642cb73e0d4212ae6cb221b826e8f11 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pp_baseline.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +import unittest + +from sglang.srt.kv_canary.config import CanaryMode +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.pp_fixture import CanaryPPFixture + +register_cuda_ci(est_time=220, stage="extra-a", runner_config="2-gpu-large") +register_amd_ci(est_time=243, stage="extra-a", runner_config="2-gpu-large-amd") + + +class TestPPBaselineSwa(CanaryPPFixture): + + kv_canary_mode = CanaryMode.LOG + + def test_no_violation(self) -> None: + for _ in range(self.workload_n_batches): + self.send_parallel_requests() + self.assert_no_violation(wait_seconds=2.0) + self.maybe_assert_swa_divergence_observed() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pp_perturb.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pp_perturb.py new file mode 100644 index 0000000000000000000000000000000000000000..32f43252c9c45262c7689dc60e7e35602482571f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pp_perturb.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import unittest +from typing import ClassVar + +from sglang.srt.kv_canary.config import CanaryMode +from sglang.srt.kv_canary.perturb.config import TargetGroupKind +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.pp_fixture import CanaryPPFixture + +register_cuda_ci(est_time=220, stage="extra-a", runner_config="2-gpu-large") +register_amd_ci(est_time=298, stage="extra-a", runner_config="2-gpu-large-amd") + + +class TestPPPerturbSwaSwa(CanaryPPFixture): + + kv_canary_mode = CanaryMode.LOG + target_group: ClassVar[TargetGroupKind] = TargetGroupKind.SWA + extra_server_args = ("--kv-canary-real-data", "partial") + + @classmethod + def setUpClass(cls) -> None: + cls.extra_env = { + "SGLANG_KV_CANARY_PERTURB_REAL_KV_USED_PROB": "0.1", + "SGLANG_KV_CANARY_PERTURB_TARGET_GROUP": str(cls.target_group), + "SGLANG_KV_CANARY_PERTURB_WARMUP_STEPS": "0", + } + super().setUpClass() + + def test_real_kv_used_perturbation_reports_real_kv_hash_violation(self) -> None: + for _ in range(self.workload_n_batches): + self.send_parallel_requests() + self.assert_per_forward_violation_reported( + fail_reason="verify_real_kv_hash", + target_group=self.target_group, + ) + self.maybe_assert_swa_divergence_observed() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pr_25015.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pr_25015.py new file mode 100644 index 0000000000000000000000000000000000000000..58301cc8f46204a895a8e44953aadb826e7ebcc1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pr_25015.py @@ -0,0 +1,88 @@ +"""Regression for PR #25015 EAGLE positions misalign: revert the fix and expect canary fire.""" + +from __future__ import annotations + +import unittest +from typing import ClassVar + +from sglang.srt.kv_canary.config import CanaryMode +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.e2e_base import CanaryE2EBase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=101, stage="extra-a", runner_config="1-gpu-small-amd") + +_SPEC_EAGLE_TOKEN_ORACLE_ENV = { + "SGLANG_KV_CANARY_ENABLE_WRITE_INPUT_ASSERT": "0", + "SGLANG_KV_CANARY_ENABLE_TOKEN_ORACLE": "1", + "SGLANG_KV_CANARY_ENABLE_VERIFY_TOKEN_ASSERT": "0", +} +_SPEC_EAGLE_REVERT_PR_ENV = { + **_SPEC_EAGLE_TOKEN_ORACLE_ENV, + "SGLANG_DEBUG_REVERT_PR": "25015", +} +_CUDA_GRAPH_MAX_BS = 1 +_EAGER_DRAFT_REQUEST_COUNT = 20 +assert _EAGER_DRAFT_REQUEST_COUNT > _CUDA_GRAPH_MAX_BS + +_SPEC_EAGLE_SERVER_ARGS = ( + "--sampling-backend", + "token_oracle", + "--speculative-algorithm", + "EAGLE", + "--cuda-graph-max-bs-decode", + str(_CUDA_GRAPH_MAX_BS), + "--max-running-requests", + "32", +) + + +class _EaglePositionsBase(CanaryE2EBase): + model_mode = "mha" + # LOG mode keeps the server alive after the first violation so server warmup + this test's + # parallel requests both run; we then read the violation log to assert the position bit fired. + kv_canary_mode = CanaryMode.LOG + extra_server_args = _SPEC_EAGLE_SERVER_ARGS + revert_pr: ClassVar[bool] + + @classmethod + def setUpClass(cls) -> None: + if cls is _EaglePositionsBase: + raise unittest.SkipTest("abstract base; concrete subclasses set revert_pr") + cls.extra_env = ( + _SPEC_EAGLE_REVERT_PR_ENV if cls.revert_pr else _SPEC_EAGLE_TOKEN_ORACLE_ENV + ) + super().setUpClass() + + def test_pr_25015_eagle_positions(self) -> None: + self.send_parallel_requests( + n=_EAGER_DRAFT_REQUEST_COUNT, + assert_all_success=not self.revert_pr, + max_new_tokens=32, + timeout=60.0, + ) + + if self.revert_pr: + self.assert_violation_logged_any( + launch_tag_patterns=("*",), + fail_reason="verify_position", + flush_wait_seconds=0.0, + ) + else: + self.assert_no_violation(wait_seconds=2.0) + + +class TestEaglePositionsMisalignRegression(_EaglePositionsBase): + """Revert PR #25015 fix and expect canary to fire a position-mismatch violation.""" + + revert_pr = True + + +class TestEaglePositionsMatchWithFix(_EaglePositionsBase): + """With the PR #25015 fix in place, no canary fires.""" + + revert_pr = False + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pr_26329.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pr_26329.py new file mode 100644 index 0000000000000000000000000000000000000000..3a512ddca5721546db4bffb909f9af30e8ef45ac --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_e2e_pr_26329.py @@ -0,0 +1,85 @@ +"""Regression for PR #26329 EAGLE chunked-prefill rotation.""" + +from __future__ import annotations + +import random +import string +import unittest +from typing import ClassVar + +from sglang.srt.kv_canary.config import CanaryMode +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.e2e_base import CanaryE2EBase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=99, stage="extra-a", runner_config="1-gpu-small-amd") + + +_CHUNKED_PREFILL_SIZE = 2048 +_EAGLE_CHUNKED_SERVER_ARGS = ( + "--speculative-algorithm", + "EAGLE", + "--chunked-prefill-size", + str(_CHUNKED_PREFILL_SIZE), + "--cuda-graph-max-bs-decode", + "1", + "--max-running-requests", + "4", +) + + +class _EagleChunkedRotationBase(CanaryE2EBase): + model_mode = "mha" + kv_canary_mode = CanaryMode.LOG + extra_server_args = _EAGLE_CHUNKED_SERVER_ARGS + + revert_pr: ClassVar[bool] + + @classmethod + def setUpClass(cls) -> None: + if cls is _EagleChunkedRotationBase: + raise unittest.SkipTest("abstract base; concrete subclasses set revert_pr") + cls.extra_env = {"SGLANG_DEBUG_REVERT_PR": "26329"} if cls.revert_pr else {} + super().setUpClass() + + def make_prompts(self, n: int) -> list[str]: + # Seeded random ASCII so the model can't predict the next prompt token + # — otherwise target's bonus token can accidentally match prompt[K1] + # at the chunk boundary and the validator never fires. + rng = random.Random(0) + # ~3K tokens after BPE — spans 2+ chunks at chunked_prefill_size=2048. + body = "".join(rng.choices(string.ascii_letters + string.digits + " ", k=8000)) + return [body] * n + + def test_chunked_rotation_token_id_mismatch(self) -> None: + self.send_parallel_requests( + n=1, + assert_all_success=not self.revert_pr, + max_new_tokens=8, + timeout=60.0, + ) + + if self.revert_pr: + self.assert_violation_logged_any( + launch_tag_patterns=("*",), + fail_reason="verify_token", + flush_wait_seconds=3.0, + ) + else: + self.assert_no_violation(wait_seconds=2.0) + + +class TestEagleChunkedRotationRegression(_EagleChunkedRotationBase): + """Revert PR #26329 fix; expect canary to fire a verify_token violation.""" + + revert_pr = True + + +class TestEagleChunkedRotationClean(_EagleChunkedRotationBase): + """With the PR #26329 fix in place, the same request runs clean.""" + + revert_pr = False + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_buffer_alloc.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_buffer_alloc.py new file mode 100644 index 0000000000000000000000000000000000000000..b6800acbb370309ced3a1914d4f4af142c13cedd --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_buffer_alloc.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +import sys +import unittest + +import torch + +from sglang.jit_kernel.kv_canary.consts import RealKvHashMode +from sglang.srt.kv_canary.config import CanaryConfig, CanaryMode +from sglang.srt.kv_canary.pool_patcher.buffer_alloc import ( + make_packed_source, + make_row_source, + resolve_real_kv_read_bytes, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=10, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=10, suite="extra-a-test-1-gpu-small-amd") + + +def _config(mode: RealKvHashMode) -> CanaryConfig: + return CanaryConfig( + mode=CanaryMode.RAISE, + ring_capacity=1024, + sweep_interval=0, + real_kv_hash_mode=mode, + enable_write_input_assert=False, + enable_verify_token_assert=False, + stats_print_every_n_steps=100, + ) + + +class TestResolveRealKvReadBytes(CustomTestCase): + def test_resolve_real_kv_read_bytes_off_returns_zero(self) -> None: + """Verify NONE mode disables real KV byte reads.""" + self.assertEqual(resolve_real_kv_read_bytes(_config(RealKvHashMode.NONE)), 0) + + def test_resolve_real_kv_read_bytes_partial_returns_16(self) -> None: + """Verify PARTIAL mode reads the fixed byte prefix.""" + self.assertEqual( + resolve_real_kv_read_bytes(_config(RealKvHashMode.PARTIAL)), 16 + ) + + def test_resolve_real_kv_read_bytes_all_returns_sentinel_so_full_stride_used( + self, + ) -> None: + """Verify ALL mode requests the full token stride.""" + self.assertEqual( + resolve_real_kv_read_bytes(_config(RealKvHashMode.ALL)), sys.maxsize + ) + + +class TestMakeRowSource(CustomTestCase): + def test_make_row_source_large_stride(self) -> None: + """Verify row sources with 128-byte stride return the requested clip / full stride.""" + bytes_per_token = 128 + layer_buf = torch.zeros(4, bytes_per_token, dtype=torch.uint8) + cases = [ + ("partial", 32, 32), + ("all", sys.maxsize, bytes_per_token), + ] + for label, read_bytes, expected_read in cases: + with self.subTest(label=label): + sources = make_row_source(layer_buffer=layer_buf, read_bytes=read_bytes) + self.assertEqual(len(sources), 1) + self.assertEqual(sources[0].read_bytes, expected_read) + self.assertEqual(sources[0].num_bytes_per_token, bytes_per_token) + + def test_make_row_source_small_stride_raises(self) -> None: + """Verify row sources reject 8-byte strides (cannot satisfy 16-byte aligned loads).""" + layer_buf = torch.zeros(4, 8, dtype=torch.uint8) + for label, read_bytes in [("partial", 32), ("all", sys.maxsize)]: + with self.subTest(label=label): + with self.assertRaisesRegex(ValueError, "num_bytes_per_token"): + make_row_source(layer_buffer=layer_buf, read_bytes=read_bytes) + + +class TestMakePackedSource(CustomTestCase): + def test_make_packed_source_large_stride(self) -> None: + """Verify packed sources with 128-byte stride return the requested clip / full stride.""" + bytes_per_token = 128 + page_size = 2 + page_buffer = torch.zeros(4, bytes_per_token * page_size, dtype=torch.uint8) + cases = [ + ("partial", 32, 32), + ("all", sys.maxsize, bytes_per_token), + ] + for label, read_bytes, expected_read in cases: + with self.subTest(label=label): + sources = make_packed_source( + page_buffer=page_buffer, + page_size=page_size, + bytes_per_token=bytes_per_token, + read_bytes=read_bytes, + ) + self.assertEqual(len(sources), 1) + self.assertEqual(sources[0].read_bytes, expected_read) + self.assertEqual(sources[0].num_bytes_per_token, bytes_per_token) + + def test_make_packed_source_small_stride_raises(self) -> None: + """Verify packed sources reject 8-byte strides (cannot satisfy 16-byte aligned loads).""" + bytes_per_token = 8 + page_size = 1 + page_buffer = torch.zeros(4, bytes_per_token, dtype=torch.uint8) + for label, read_bytes in [("partial", 32), ("all", sys.maxsize)]: + with self.subTest(label=label): + with self.assertRaisesRegex(ValueError, "num_bytes_per_token"): + make_packed_source( + page_buffer=page_buffer, + page_size=page_size, + bytes_per_token=bytes_per_token, + read_bytes=read_bytes, + ) + + def test_make_packed_source_unaligned_read_bytes_raises(self) -> None: + """Verify packed sources reject unaligned explicit reads.""" + bytes_per_token = 128 + page_size = 1 + page_buffer = torch.zeros(4, bytes_per_token, dtype=torch.uint8) + with self.assertRaisesRegex(ValueError, "multiple of 16"): + make_packed_source( + page_buffer=page_buffer, + page_size=page_size, + bytes_per_token=bytes_per_token, + read_bytes=24, + ) + + def test_make_packed_source_oversized_read_bytes_raises(self) -> None: + """Verify packed sources reject oversized explicit reads.""" + bytes_per_token = 128 + page_size = 1 + page_buffer = torch.zeros(4, bytes_per_token, dtype=torch.uint8) + with self.assertRaisesRegex(ValueError, "<= num_bytes_per_token"): + make_packed_source( + page_buffer=page_buffer, + page_size=page_size, + bytes_per_token=bytes_per_token, + read_bytes=256, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_capacities.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_capacities.py new file mode 100644 index 0000000000000000000000000000000000000000..4876af6aebd0065a75020edf7ed857e491d1e296 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_capacities.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +import unittest +from types import SimpleNamespace + +from sglang.srt.kv_canary.capacities import CanaryLaunchCapacities +from sglang.srt.model_executor.cuda_graph_config import ( + Backend, + CudaGraphConfig, + PhaseConfig, +) +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class TestComputeLaunchCapacities(CustomTestCase): + @staticmethod + def _make_server_args(*, max_bs: int) -> SimpleNamespace: + return SimpleNamespace( + cuda_graph_config=CudaGraphConfig( + decode=PhaseConfig(backend=Backend.FULL, max_bs=max_bs) + ), + speculative_num_draft_tokens=0, + chunked_prefill_size=None, + max_prefill_tokens=128, + ) + + @staticmethod + def _from_args( + *, + max_bs: int, + max_seq_len: int, + max_total_num_tokens: int | None = None, + ) -> CanaryLaunchCapacities: + if max_total_num_tokens is None: + max_total_num_tokens = max_bs * max_seq_len + return CanaryLaunchCapacities.from_args( + server_args=TestComputeLaunchCapacities._make_server_args(max_bs=max_bs), + req_to_token_pool_size=max_bs, + max_seq_len_per_req=max_seq_len, + pool_slot_count=max_total_num_tokens, + ) + + def test_per_forward_verify_capacity_covers_multi_req_prefix_sum(self) -> None: + """Verify per-forward verify capacity equals max_total_num_tokens * 3.""" + max_bs = 8 + max_seq_len = 64 + max_total_num_tokens = 1024 + capacities = self._from_args( + max_bs=max_bs, + max_seq_len=max_seq_len, + max_total_num_tokens=max_total_num_tokens, + ) + self.assertEqual( + capacities.per_forward_verify_capacity, + int(max_total_num_tokens * 3), + ) + + def test_from_args_treats_missing_speculative_draft_tokens_as_zero(self) -> None: + """per_forward_write_entry_capacity is floored by max_prefill_tokens when batch * tokens_per_bs is smaller.""" + server_args = self._make_server_args(max_bs=2) + server_args.speculative_num_draft_tokens = None + + capacities = CanaryLaunchCapacities.from_args( + server_args=server_args, + req_to_token_pool_size=2, + max_seq_len_per_req=32, + pool_slot_count=64, + ) + + self.assertEqual(capacities.per_forward_write_entry_capacity, 128) + + def test_manual_capacities_reject_non_positive_fields(self) -> None: + """Verify manual launch capacities fail instead of being clamped.""" + with self.assertRaisesRegex(ValueError, "per_forward_verify_capacity"): + CanaryLaunchCapacities( + per_forward_verify_capacity=0, + per_forward_write_req_capacity=1, + per_forward_write_entry_capacity=1, + ) + + def test_from_args_rejects_empty_pool_capacity(self) -> None: + """Verify derived launch capacities reject invalid pool sizing.""" + with self.assertRaisesRegex(ValueError, "pool_slot_count"): + CanaryLaunchCapacities.from_args( + server_args=self._make_server_args(max_bs=1), + req_to_token_pool_size=1, + max_seq_len_per_req=1, + pool_slot_count=0, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_e2e_base.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_e2e_base.py new file mode 100644 index 0000000000000000000000000000000000000000..6789a898013f79c23fa4eb866b16227887d7461f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_e2e_base.py @@ -0,0 +1,204 @@ +from __future__ import annotations + +import unittest +from unittest.mock import patch + +from sglang.srt.kv_canary.runner.swa_divergence import SwaDivergenceLog +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.kv_canary.e2e_base import CanaryE2EBase +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=5, suite="base-c-test-cpu") + + +_GOOD_LINE: str = SwaDivergenceLog( + forward_ct=120, + verify_full=10000, + verify_swa=4200, + swa_full_idx_divergence=512, + swa_out_of_window_tokens=8192, +).format() +_LATER_LINE: str = SwaDivergenceLog( + forward_ct=240, + verify_full=20000, + verify_swa=8400, + swa_full_idx_divergence=1024, + swa_out_of_window_tokens=16384, +).format() + + +class _DummyHarness(CanaryE2EBase): + model_mode = "swa" + kv_canary_mode = "log" + + @classmethod + def setUpClass(cls) -> None: + return + + @classmethod + def tearDownClass(cls) -> None: + return + + +class TestAssertSwaDivergenceObserved(CustomTestCase): + def _make_harness( + self, log_text_or_sequence + ) -> tuple[_DummyHarness, patch._patch[None]]: + harness = _DummyHarness() + harness._stderr_buf = None + harness._stdout_buf = None + if isinstance(log_text_or_sequence, list): + patcher = patch.object( + _DummyHarness, "_captured_log_text", side_effect=log_text_or_sequence + ) + else: + patcher = patch.object( + _DummyHarness, + "_captured_log_text", + return_value=log_text_or_sequence, + ) + return harness, patcher + + def test_assert_swa_divergence_observed_passes_when_above_threshold(self) -> None: + harness, patcher = self._make_harness(_LATER_LINE + "\n" + _GOOD_LINE + "\n") + with patcher: + harness.assert_swa_divergence_observed( + min_swa_full_idx_divergence=100, + require_verify_lag=True, + flush_wait_seconds=0.0, + max_retries=1, + ) + + def test_assert_swa_divergence_observed_uses_peak_out_of_window(self) -> None: + diverged = SwaDivergenceLog( + forward_ct=120, + verify_full=10000, + verify_swa=4200, + swa_full_idx_divergence=512, + swa_out_of_window_tokens=8192, + ).format() + trailing_zero = SwaDivergenceLog( + forward_ct=240, + verify_full=20000, + verify_swa=8400, + swa_full_idx_divergence=0, + swa_out_of_window_tokens=0, + ).format() + harness, patcher = self._make_harness(diverged + "\n" + trailing_zero + "\n") + with patcher: + harness.assert_swa_divergence_observed( + min_swa_out_of_window_tokens=1, + min_swa_full_idx_divergence=1, + require_verify_lag=True, + flush_wait_seconds=0.0, + max_retries=1, + ) + + def test_assert_swa_divergence_observed_checks_verify_lag_on_latest_line( + self, + ) -> None: + lagging = SwaDivergenceLog( + forward_ct=120, + verify_full=10000, + verify_swa=4200, + swa_full_idx_divergence=512, + swa_out_of_window_tokens=8192, + ).format() + no_lag = SwaDivergenceLog( + forward_ct=240, + verify_full=20000, + verify_swa=20000, + swa_full_idx_divergence=1024, + swa_out_of_window_tokens=16384, + ).format() + harness, patcher = self._make_harness(lagging + "\n" + no_lag + "\n") + with patcher: + with self.assertRaisesRegex(AssertionError, "verify_swa=20000"): + harness.assert_swa_divergence_observed( + min_swa_full_idx_divergence=1, + require_verify_lag=True, + flush_wait_seconds=0.0, + max_retries=1, + ) + + def test_assert_swa_divergence_observed_raises_when_below_threshold(self) -> None: + zero_mapping_line = SwaDivergenceLog( + forward_ct=100, + verify_full=5000, + verify_swa=2000, + swa_full_idx_divergence=0, + swa_out_of_window_tokens=8192, + ).format() + harness, patcher = self._make_harness(zero_mapping_line + "\n") + with patcher: + with self.assertRaisesRegex(AssertionError, "swa_full_idx_divergence=0"): + harness.assert_swa_divergence_observed( + min_swa_full_idx_divergence=1, + require_verify_lag=False, + flush_wait_seconds=0.0, + max_retries=1, + ) + + def test_assert_swa_divergence_observed_raises_when_no_verify_lag(self) -> None: + equal_verify_line = SwaDivergenceLog( + forward_ct=100, + verify_full=5000, + verify_swa=5000, + swa_full_idx_divergence=200, + swa_out_of_window_tokens=8192, + ).format() + harness, patcher = self._make_harness(equal_verify_line + "\n") + with patcher: + with self.assertRaisesRegex(AssertionError, "verify_swa=5000"): + harness.assert_swa_divergence_observed( + min_swa_full_idx_divergence=1, + require_verify_lag=True, + flush_wait_seconds=0.0, + max_retries=1, + ) + + def test_assert_swa_divergence_observed_retries_until_stats_emitted(self) -> None: + sequence = ["", "", "", _GOOD_LINE + "\n", _GOOD_LINE + "\n"] + harness, patcher = self._make_harness(sequence) + with patcher: + harness.assert_swa_divergence_observed( + min_swa_full_idx_divergence=1, + require_verify_lag=True, + flush_wait_seconds=0.0, + max_retries=5, + ) + + def test_assert_swa_divergence_observed_raises_when_no_stats_emitted(self) -> None: + harness, patcher = self._make_harness("nothing here\n") + with patcher: + with self.assertRaisesRegex(AssertionError, "No kv_canary swa_divergence"): + harness.assert_swa_divergence_observed( + min_swa_full_idx_divergence=1, + require_verify_lag=True, + flush_wait_seconds=0.0, + max_retries=2, + ) + + def test_assert_swa_divergence_observed_catches_zero_swa_full_idx_divergence( + self, + ) -> None: + zero_divergence_line = SwaDivergenceLog( + forward_ct=200, + verify_full=10000, + verify_swa=2000, + swa_full_idx_divergence=0, + swa_out_of_window_tokens=8192, + ).format() + harness, patcher = self._make_harness(zero_divergence_line + "\n") + with patcher: + with self.assertRaisesRegex(AssertionError, "swa_full_idx_divergence=0"): + harness.assert_swa_divergence_observed( + min_swa_full_idx_divergence=1, + require_verify_lag=True, + flush_wait_seconds=0.0, + max_retries=1, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_endpoint.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..bfd5afb14e0ab7176e2d2038deb26e899c319a76 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_endpoint.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import torch + +from sglang.jit_kernel.kv_canary.consts import RealKvHashMode +from sglang.jit_kernel.kv_canary.verify import ( + CANARY_SLOT_BYTES, + CanaryLaunchTag, + VerifyPlan, +) +from sglang.jit_kernel.kv_canary.write import WritePlan +from sglang.srt.kv_canary import endpoint as endpoint_module +from sglang.srt.kv_canary.endpoint import ( + CanaryEndpoint, +) +from sglang.srt.kv_canary.expected_inputs import ExpectedInputs +from sglang.srt.kv_canary.state import ( + ViolationLog, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import DEFAULT_DEVICE +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=20, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=20, suite="extra-a-test-1-gpu-small-amd") + + +def _make_endpoint(*, device, kernel_kind=CanaryLaunchTag.HEAD_K_FULL, swa_lut=None): + canary_buf = torch.zeros(4, CANARY_SLOT_BYTES, dtype=torch.uint8, device=device) + slot_view = torch.zeros(1, dtype=torch.int64, device=device) + kernel_view = torch.zeros(1, dtype=torch.int64, device=device) + enable_chain_position_assert = torch.ones(1, dtype=torch.int32, device=device) + return CanaryEndpoint( + kernel_kind=kernel_kind, + canary_buf=canary_buf, + full_to_swa_index_mapping=swa_lut, + real_kv_sources=(), + slot_run_counter_view=slot_view, + kernel_run_counter_view=kernel_view, + enable_chain_position_assert=enable_chain_position_assert, + ) + + +def _make_kernel_args(device): + verify_plan = VerifyPlan.allocate(verify_capacity=1, device=device) + write_plan = WritePlan.allocate(write_req_capacity=1, device=device) + log = ViolationLog.allocate(ring_capacity=2, device=device) + return SimpleNamespace( + verify_plan=verify_plan, + write_plan=write_plan, + violation_log=log, + input_ids=torch.zeros(1, dtype=torch.int64, device=device), + positions=torch.zeros(1, dtype=torch.int64, device=device), + out_cache_loc=torch.zeros(1, dtype=torch.int64, device=device), + enable_write_input_assert=False, + enable_verify_token_assert=False, + expected_inputs=ExpectedInputs.allocate(capacity=1, device=device), + real_kv_hash_mode=RealKvHashMode.NONE, + ) + + +class TestSelfUnitEndpoint(CustomTestCase): + def setUp(self): + self.device = DEFAULT_DEVICE + + def test_launch_sweep_only_calls_verify(self): + """Verify sweep launch invokes only the verify kernel.""" + calls: list[str] = [] + with patch.object( + endpoint_module, + "launch_canary_verify_kernel", + lambda **kwargs: calls.append("verify"), + ), patch.object( + endpoint_module, + "launch_canary_write_kernel", + lambda **kwargs: calls.append("write"), + ): + ep = _make_endpoint( + device=self.device, kernel_kind=CanaryLaunchTag.SWEEP_K_FULL + ) + args = _make_kernel_args(self.device) + ep.launch_sweep( + verify_plan=args.verify_plan, + violation_log=args.violation_log, + real_kv_hash_mode=args.real_kv_hash_mode, + ) + self.assertEqual(calls, ["verify"]) + + def test_launch_per_forward_passes_kernel_kind(self): + """Verify per-forward launch passes the endpoint kernel kind.""" + captured: list[tuple[str, CanaryLaunchTag]] = [] + with patch.object( + endpoint_module, + "launch_canary_verify_kernel", + lambda **kwargs: captured.append(("verify", kwargs["context"].kernel_kind)), + ), patch.object( + endpoint_module, + "launch_canary_write_kernel", + lambda **kwargs: captured.append(("write", kwargs["context"].kernel_kind)), + ): + ep = _make_endpoint( + device=self.device, kernel_kind=CanaryLaunchTag.TAIL_V_SWA + ) + args = _make_kernel_args(self.device) + ep.launch_per_forward( + verify_plan=args.verify_plan, + write_plan=args.write_plan, + input_ids=args.input_ids, + positions=args.positions, + out_cache_loc=args.out_cache_loc, + enable_write_input_assert=args.enable_write_input_assert, + enable_verify_token_assert=args.enable_verify_token_assert, + expected_inputs=args.expected_inputs, + violation_log=args.violation_log, + real_kv_hash_mode=args.real_kv_hash_mode, + ) + self.assertIn(("verify", CanaryLaunchTag.TAIL_V_SWA), captured) + self.assertIn(("write", CanaryLaunchTag.TAIL_V_SWA), captured) + + def test_endpoint_shares_violation_log_across_launches(self): + """Verify endpoints can reuse the same violation log.""" + captured_rings: list[int] = [] + with patch.object( + endpoint_module, + "launch_canary_verify_kernel", + lambda **kwargs: captured_rings.append( + kwargs["context"].violation_ring.data_ptr() + ), + ), patch.object( + endpoint_module, + "launch_canary_write_kernel", + lambda **kwargs: None, + ): + shared_log = ViolationLog.allocate(ring_capacity=2, device=self.device) + ep_a = _make_endpoint( + device=self.device, kernel_kind=CanaryLaunchTag.SWEEP_K_FULL + ) + ep_b = _make_endpoint( + device=self.device, kernel_kind=CanaryLaunchTag.SWEEP_V_FULL + ) + + plan = VerifyPlan.allocate(verify_capacity=1, device=self.device) + ep_a.launch_sweep( + verify_plan=plan, + violation_log=shared_log, + real_kv_hash_mode=RealKvHashMode.NONE, + ) + ep_b.launch_sweep( + verify_plan=plan, + violation_log=shared_log, + real_kv_hash_mode=RealKvHashMode.NONE, + ) + self.assertEqual(captured_rings[0], captured_rings[1]) + self.assertEqual(captured_rings[0], shared_log.violation_ring.data_ptr()) + + def test_swa_endpoint_pre_translates_out_cache_loc(self): + """Verify SWA endpoints translate cache locations before write launch.""" + captured: list[torch.Tensor] = [] + with patch.object( + endpoint_module, "launch_canary_verify_kernel", lambda **kwargs: None + ), patch.object( + endpoint_module, + "launch_canary_write_kernel", + lambda **kwargs: captured.append(kwargs["out_cache_loc"]), + ): + # LUT maps full slot i → swa slot (i + 100) so we can verify the gather happened. + lut = torch.arange(8, dtype=torch.int64, device=self.device) + 100 + swa_ep = _make_endpoint( + device=self.device, + kernel_kind=CanaryLaunchTag.HEAD_K_SWA, + swa_lut=lut, + ) + full_ep = _make_endpoint( + device=self.device, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + swa_lut=None, + ) + args = _make_kernel_args(self.device) + + swa_ep.launch_per_forward( + verify_plan=args.verify_plan, + write_plan=args.write_plan, + input_ids=args.input_ids, + positions=args.positions, + out_cache_loc=args.out_cache_loc, + enable_write_input_assert=args.enable_write_input_assert, + enable_verify_token_assert=args.enable_verify_token_assert, + expected_inputs=args.expected_inputs, + violation_log=args.violation_log, + real_kv_hash_mode=args.real_kv_hash_mode, + ) + full_ep.launch_per_forward( + verify_plan=args.verify_plan, + write_plan=args.write_plan, + input_ids=args.input_ids, + positions=args.positions, + out_cache_loc=args.out_cache_loc, + enable_write_input_assert=args.enable_write_input_assert, + enable_verify_token_assert=args.enable_verify_token_assert, + expected_inputs=args.expected_inputs, + violation_log=args.violation_log, + real_kv_hash_mode=args.real_kv_hash_mode, + ) + # SWA call: out_cache_loc was rewritten via lut gather (so identity-shifted by +100 here). + expected_swa = lut[args.out_cache_loc] + self.assertTrue(torch.equal(captured[0], expected_swa)) + # FULL call: out_cache_loc keeps the same values and dtype. + self.assertIs(captured[1], args.out_cache_loc) + + def test_swa_endpoint_trailing_sentinel_row_yields_skip(self): + """Verify SWA sentinel cache rows become write-skip markers.""" + captured: list[torch.Tensor] = [] + with patch.object( + endpoint_module, "launch_canary_verify_kernel", lambda **kwargs: None + ), patch.object( + endpoint_module, + "launch_canary_write_kernel", + lambda **kwargs: captured.append(kwargs["out_cache_loc"]), + ): + # 8 in-window rows + 1 trailing sentinel row at index 8. + lut = torch.arange(8, dtype=torch.int64, device=self.device) + lut = torch.cat( + [lut, torch.tensor([-1], dtype=torch.int64, device=self.device)] + ) + swa_ep = _make_endpoint( + device=self.device, kernel_kind=CanaryLaunchTag.HEAD_K_SWA, swa_lut=lut + ) + args = _make_kernel_args(self.device) + # Point out_cache_loc at the trailing-sentinel-row index — this is how sglang signals + # "this token is out-of-window for the SWA group" pre-cleanup, and the new host gather must + # produce -1 here. + args.out_cache_loc.fill_(8) + + swa_ep.launch_per_forward( + verify_plan=args.verify_plan, + write_plan=args.write_plan, + input_ids=args.input_ids, + positions=args.positions, + out_cache_loc=args.out_cache_loc, + enable_write_input_assert=args.enable_write_input_assert, + enable_verify_token_assert=args.enable_verify_token_assert, + expected_inputs=args.expected_inputs, + violation_log=args.violation_log, + real_kv_hash_mode=args.real_kv_hash_mode, + ) + + self.assertTrue( + torch.equal( + captured[0], + torch.tensor([-1], dtype=torch.int64, device=self.device), + ) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_future_tensor.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_future_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..1a04c5ba26c43cbd4538850acc27d3de4f699646 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_future_tensor.py @@ -0,0 +1,181 @@ +from __future__ import annotations + +import unittest +from typing import cast + +import torch + +from sglang.srt.kv_canary.runner.future_tensor import FutureTensors +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=20, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=20, suite="extra-a-test-1-gpu-small-amd") + + +class _FakeEvent: + def __init__(self) -> None: + self.synchronize_count = 0 + + def synchronize(self) -> None: + self.synchronize_count += 1 + + +class TestFutureTensors(CustomTestCase): + def test_cuda_stage_then_wait_returns_host_copy(self) -> None: + """Verify staged CUDA tensors are copied back on wait.""" + device = torch.device("cuda") + alt_stream = torch.cuda.Stream(device=device) + default_stream = torch.cuda.current_stream(device) + self.assertNotEqual(alt_stream.stream_id, default_stream.stream_id) + + src_first = torch.tensor([41], dtype=torch.int32, device=device) + future_first = FutureTensors.device_to_host( + xs_device=src_first, d2h_stream=alt_stream + ) + result_first = future_first.wait() + self.assertEqual(int(result_first.item()), 41) + + src_second = torch.tensor([97], dtype=torch.int32, device=device) + future_second = FutureTensors.device_to_host( + xs_device=src_second, d2h_stream=alt_stream + ) + result_second = future_second.wait() + self.assertEqual(int(result_second.item()), 97) + + def test_cuda_pinned_when_stream_is_provided(self) -> None: + """Verify CUDA staging uses pinned host memory with a stream.""" + device = torch.device("cuda") + alt_stream = torch.cuda.Stream(device=device) + src = torch.tensor([5], dtype=torch.int32, device=device) + future = FutureTensors.device_to_host(xs_device=src, d2h_stream=alt_stream) + staged_tensors = [ + v for v in future._data.values() if isinstance(v, torch.Tensor) + ] + self.assertTrue(staged_tensors) + self.assertTrue(all(t.is_pinned() for t in staged_tensors)) + self.assertEqual(int(future.wait().item()), 5) + + def test_cuda_each_call_allocates_fresh_host(self) -> None: + """Verify each CUDA staging call owns a fresh host buffer.""" + device = torch.device("cuda") + alt_stream = torch.cuda.Stream(device=device) + src_a = torch.tensor([13], dtype=torch.int32, device=device) + src_b = torch.tensor([29], dtype=torch.int32, device=device) + future_a = FutureTensors.device_to_host(xs_device=src_a, d2h_stream=alt_stream) + future_b = FutureTensors.device_to_host(xs_device=src_b, d2h_stream=alt_stream) + ptrs_a = { + v.data_ptr() for v in future_a._data.values() if isinstance(v, torch.Tensor) + } + ptrs_b = { + v.data_ptr() for v in future_b._data.values() if isinstance(v, torch.Tensor) + } + self.assertTrue(ptrs_a and ptrs_b) + self.assertFalse(ptrs_a & ptrs_b) + self.assertEqual(int(future_a.wait().item()), 13) + self.assertEqual(int(future_b.wait().item()), 29) + + def test_dict_of_all_tensors_roundtrip(self) -> None: + """Verify a dict of multiple tensors round-trips entry-by-entry.""" + device = torch.device("cuda") + stream = torch.cuda.Stream(device=device) + src = { + "x": torch.tensor([11, 22], dtype=torch.int64, device=device), + "y": torch.tensor([99], dtype=torch.int32, device=device), + } + future = FutureTensors.device_to_host(xs_device=src, d2h_stream=stream) + out = future.wait() + self.assertIsInstance(out, dict) + self.assertEqual(out["x"].tolist(), [11, 22]) + self.assertEqual(int(out["y"].item()), 99) + self.assertTrue(out["x"].is_pinned()) + self.assertTrue(out["y"].is_pinned()) + + def test_dict_mixes_tensor_and_passthrough(self) -> None: + """Verify non-tensor dict entries ride through verbatim alongside staging.""" + device = torch.device("cuda") + stream = torch.cuda.Stream(device=device) + sentinel_obj = {"nested": [1, 2, 3]} + src = { + "step": 42, + "label": "decode", + "extra": sentinel_obj, + "counter": torch.tensor([7], dtype=torch.int32, device=device), + } + future = FutureTensors.device_to_host(xs_device=src, d2h_stream=stream) + out = future.wait() + self.assertEqual(out["step"], 42) + self.assertEqual(out["label"], "decode") + # Identity (not deep-copy) — callers can rely on shared mutable references. + self.assertIs(out["extra"], sentinel_obj) + self.assertEqual(int(out["counter"].item()), 7) + self.assertTrue(out["counter"].is_pinned()) + + def test_dict_passthrough_preserves_tensor_value(self) -> None: + """Verify tensors share device memory but non-tensor types are not staged.""" + device = torch.device("cuda") + stream = torch.cuda.Stream(device=device) + src_tensor = torch.tensor([3], dtype=torch.int32, device=device) + src = {"step": 100, "buf": src_tensor} + future = FutureTensors.device_to_host(xs_device=src, d2h_stream=stream) + out = future.wait() + # Tensor is staged to a fresh pinned-host buffer (different storage from src). + self.assertNotEqual(out["buf"].data_ptr(), src_tensor.data_ptr()) + self.assertTrue(out["buf"].is_pinned()) + # Non-tensor passes through with no copy. + self.assertEqual(out["step"], 100) + self.assertIsInstance(out["step"], int) + + def test_dict_without_tensor_raises(self) -> None: + """Verify a tensor-less dict raises (no device to anchor the d2h sync).""" + device = torch.device("cuda") + stream = torch.cuda.Stream(device=device) + with self.assertRaises(ValueError): + FutureTensors.device_to_host( + xs_device={"step": 0, "label": "decode"}, d2h_stream=stream + ) + + def test_wait_called_twice_raises(self) -> None: + """Verify wait() after the first drain raises (state cleared).""" + device = torch.device("cuda") + stream = torch.cuda.Stream(device=device) + src = torch.tensor([3], dtype=torch.int32, device=device) + future = FutureTensors.device_to_host(xs_device=src, d2h_stream=stream) + self.assertEqual(int(future.wait().item()), 3) + with self.assertRaises(RuntimeError): + future.wait() + + def test_wait_clears_fields_and_rejects_second_wait(self) -> None: + """Verify wait() syncs the event exactly once and clears internal state.""" + tensor = torch.tensor([1, 2, 3]) + event = _FakeEvent() + future = FutureTensors( + _data={"x": tensor}, _event=cast(torch.cuda.Event, event) + ) + + result = future.wait() + self.assertIs(result["x"], tensor) + self.assertEqual(event.synchronize_count, 1) + self.assertIsNone(future._data) + self.assertIsNone(future._event) + + with self.assertRaisesRegex(RuntimeError, "called more than once"): + future.wait() + # Failed wait must not re-trigger event.synchronize. + self.assertEqual(event.synchronize_count, 1) + + def test_dict_anchor_picked_from_first_tensor(self) -> None: + """Verify staging works when the first key is a non-tensor (anchor must scan).""" + device = torch.device("cuda") + stream = torch.cuda.Stream(device=device) + src = { + "step": 5, + "buf": torch.tensor([17], dtype=torch.int32, device=device), + } + out = FutureTensors.device_to_host(xs_device=src, d2h_stream=stream).wait() + self.assertEqual(out["step"], 5) + self.assertEqual(int(out["buf"].item()), 17) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_perturb.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_perturb.py new file mode 100644 index 0000000000000000000000000000000000000000..e32ed69f39930dd8b612120993c847f53ce90eb8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_perturb.py @@ -0,0 +1,542 @@ +from __future__ import annotations + +import os +import unittest +from typing import TYPE_CHECKING, cast +from unittest.mock import patch + +import torch + +from sglang.jit_kernel.kv_canary.verify import RealKvSource +from sglang.srt.kv_canary.buffer_group import PoolKind +from sglang.srt.kv_canary.perturb import ( + real_kv_post_forward, +) +from sglang.srt.kv_canary.perturb import ( + real_kv_unused_cache as real_kv_unused_cache_module, +) +from sglang.srt.kv_canary.perturb.config import ( + PerturbConfig, + TargetGroupKind, + _parse_target_group_kind, +) +from sglang.srt.kv_canary.perturb.manager import PerturbManager +from sglang.srt.kv_canary.perturb.slot_picker import collect_active_slots +from sglang.srt.kv_canary.perturb.utils import ( + WarmupGate, + flip_first_byte_in_source, + pick_target_group, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import ( + DEFAULT_DEVICE, + make_buffer_group, + make_forward_batch, + make_radix_cache, + make_req_to_token_pool, +) +from sglang.test.test_utils import CustomTestCase + +if TYPE_CHECKING: + from sglang.srt.mem_cache.base_prefix_cache import BasePrefixCache + +register_cuda_ci(est_time=10, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=10, suite="extra-a-test-1-gpu-small-amd") + + +class TestParseTargetGroupKind(CustomTestCase): + def test_parse_target_group_kind_accepts_valid_values_case_insensitively( + self, + ) -> None: + """Verify target group kind parsing accepts valid names case-insensitively.""" + cases = [ + ("full", TargetGroupKind.FULL), + ("FULL", TargetGroupKind.FULL), + (" swa ", TargetGroupKind.SWA), + ] + + for raw, expected in cases: + with self.subTest(raw=raw): + self.assertEqual(_parse_target_group_kind(raw), expected) + + def test_parse_target_group_kind_rejects_invalid_value(self) -> None: + """Verify target group kind parsing rejects unknown names.""" + with self.assertRaisesRegex(ValueError, "must be one of"): + _parse_target_group_kind("prefix") + + def test_parse_target_group_kind_rejects_missing_or_any(self) -> None: + """Verify target group kind parsing requires an explicit concrete group.""" + for raw in [None, "", "any", " Any "]: + with self.subTest(raw=raw): + with self.assertRaisesRegex( + ValueError, "SGLANG_KV_CANARY_PERTURB_TARGET_GROUP" + ): + _parse_target_group_kind(raw) + + def test_from_env_allows_missing_target_when_real_kv_perturb_is_disabled( + self, + ) -> None: + """Verify normal canary startup does not require a perturb target group.""" + with patch.dict( + os.environ, + { + "SGLANG_KV_CANARY_PERTURB_REQ_TO_TOKEN_PROB": "0", + "SGLANG_KV_CANARY_PERTURB_REAL_KV_USED_PROB": "0", + "SGLANG_KV_CANARY_PERTURB_REAL_KV_UNUSED_CACHE_PROB": "0", + "SGLANG_KV_CANARY_PERTURB_REAL_KV_POST_FORWARD_PROB": "0", + }, + clear=False, + ): + os.environ.pop("SGLANG_KV_CANARY_PERTURB_TARGET_GROUP", None) + config = PerturbConfig.from_env() + + self.assertIsNone(config.target_group_kind) + + +class TestPickTargetGroup(CustomTestCase): + def test_pick_target_group_filters_exact_kind(self) -> None: + """Verify target group selection returns only the requested pool kind.""" + cases = [ + (TargetGroupKind.FULL, PoolKind.FULL), + (TargetGroupKind.SWA, PoolKind.SWA), + ] + + for target_kind, expected_kind in cases: + with self.subTest(target_kind=target_kind): + full_group = make_buffer_group(kind=PoolKind.FULL, has_real_kv=True) + swa_group = make_buffer_group(kind=PoolKind.SWA, has_real_kv=True) + + group = pick_target_group( + buffer_groups=(full_group, swa_group), + target_kind=target_kind, + ) + + self.assertIsNotNone(group) + self.assertEqual(group.kind, expected_kind) + + def test_pick_target_group_rejects_unsupported_kind(self) -> None: + """Verify target group selection rejects unsupported enum values.""" + full_group = make_buffer_group(kind=PoolKind.FULL, has_real_kv=True) + + with self.assertRaisesRegex(ValueError, "Unsupported target_group_kind"): + pick_target_group( + buffer_groups=(full_group,), + target_kind=cast(TargetGroupKind, 2), + ) + + def test_pick_target_group_ignores_groups_without_real_kv_sources(self) -> None: + """Verify target group selection skips groups without real KV sources.""" + full_group = make_buffer_group(kind=PoolKind.FULL, has_real_kv=False) + swa_group = make_buffer_group(kind=PoolKind.SWA, has_real_kv=True) + + group = pick_target_group( + buffer_groups=(full_group, swa_group), + target_kind=TargetGroupKind.FULL, + ) + + self.assertIsNone(group) + + +class TestPerturbManager(CustomTestCase): + def test_perturb_manager_perturb_post_forward_dispatches_real_kv_post_forward( + self, + ) -> None: + """Verify perturb_post_forward() routes only to the post_forward dispatch.""" + device = DEFAULT_DEVICE + manager = PerturbManager( + config=PerturbConfig( + req_to_token_prob=0.0, + real_kv_used_prob=0.0, + real_kv_unused_cache_prob=0.0, + real_kv_post_forward_prob=0.0, + target_group_kind=TargetGroupKind.FULL, + warmup_steps=0, + ), + req_to_token_pool=make_req_to_token_pool(device, max_reqs=4, max_seq_len=8), + buffer_groups=(), + outer_step_counter_getter=lambda: 10, + ) + forward_batch = make_forward_batch(device, bs=1, seq_lens_list=(1,)) + calls: list[str] = [] + + with patch.object( + manager, + "perturb_real_kv_post_forward", + lambda batch: calls.append("real_kv_post_forward"), + ), patch.object( + manager, + "perturb_req_to_token", + lambda batch: calls.append("req_to_token"), + ), patch.object( + manager, + "perturb_real_kv_used", + lambda batch: calls.append("real_kv_used"), + ), patch.object( + manager, + "perturb_real_kv_unused_cache", + lambda batch: calls.append("real_kv_unused_cache"), + ): + manager.perturb_post_forward(maybe_inaccurate_forward_batch=forward_batch) + + self.assertEqual(calls, ["real_kv_post_forward"]) + + +class TestRealKvPostForwardPerturb(CustomTestCase): + def test_real_kv_post_forward_flips_a_byte_in_out_cache_loc_slot(self) -> None: + """Verify post-forward perturbation flips one real-KV byte and leaves canary buffers untouched.""" + device = DEFAULT_DEVICE + group = make_buffer_group(kind=PoolKind.FULL, has_real_kv=True) + source = group.real_kv_sources_k[0] + config = PerturbConfig( + req_to_token_prob=0.0, + real_kv_used_prob=0.0, + real_kv_unused_cache_prob=0.0, + real_kv_post_forward_prob=1.0, + target_group_kind=TargetGroupKind.FULL, + warmup_steps=0, + ) + warmup_gate = WarmupGate(config=config, outer_step_counter_getter=lambda: 10) + + forward_batch = make_forward_batch(device, bs=1, seq_lens_list=(1,)) + forward_batch.out_cache_loc = torch.tensor( + [2], dtype=torch.int32, device=device + ) + forward_batch.num_token_non_padded_cpu = 1 + + head_snapshot = group.k_head.clone() + v_head_snapshot = group.v_head.clone() + k_tail_snapshot = group.k_tail.clone() + v_tail_snapshot = group.v_tail.clone() + source_snapshot = source.tensor.clone() + + with patch.object(torch, "rand", return_value=torch.tensor(0.0)): + real_kv_post_forward.run( + maybe_inaccurate_forward_batch=forward_batch, + config=config, + buffer_groups=(group,), + warmup_gate=warmup_gate, + ) + + diff = source.tensor != source_snapshot + self.assertEqual(int(diff.sum().item()), 1) + self.assertTrue(bool(diff[2, 0].item())) + self.assertEqual(int(source.tensor[2, 0].item()), 0 ^ 0xFF) + self.assertTrue(torch.equal(group.k_head, head_snapshot)) + self.assertTrue(torch.equal(group.v_head, v_head_snapshot)) + self.assertTrue(torch.equal(group.k_tail, k_tail_snapshot)) + self.assertTrue(torch.equal(group.v_tail, v_tail_snapshot)) + + +class TestReqToTokenPerturb(CustomTestCase): + def test_req_to_token_perturb_uses_live_slot_as_replacement(self) -> None: + """Verify req_to_token perturbation replaces a slot with another live slot.""" + device = DEFAULT_DEVICE + pool = make_req_to_token_pool(device, max_reqs=4, max_seq_len=8) + pool.req_to_token[1, :3] = torch.tensor( + [11, 22, 33], dtype=torch.int32, device=device + ) + pool.req_to_token[2, :3] = torch.tensor( + [44, 55, 66], dtype=torch.int32, device=device + ) + manager = PerturbManager( + config=PerturbConfig( + req_to_token_prob=1.0, + real_kv_used_prob=0.0, + real_kv_unused_cache_prob=0.0, + real_kv_post_forward_prob=0.0, + target_group_kind=TargetGroupKind.FULL, + warmup_steps=0, + ), + req_to_token_pool=pool, + buffer_groups=(), + outer_step_counter_getter=lambda: 10, + ) + forward_batch = make_forward_batch(device, bs=2, seq_lens_list=(3, 3)) + forward_batch.out_cache_loc = torch.tensor( + [11], dtype=torch.int32, device=device + ) + + snapshot = pool.req_to_token.clone() + with patch.object(torch, "rand", return_value=torch.tensor(0.0)): + manager.perturb_req_to_token(forward_batch) + + diff = pool.req_to_token != snapshot + self.assertEqual(int(diff.sum().item()), 1) + rows, cols = torch.nonzero(diff, as_tuple=True) + row, col = int(rows[0].item()), int(cols[0].item()) + original = int(snapshot[row, col].item()) + replacement = int(pool.req_to_token[row, col].item()) + live_slots = {11, 22, 33, 44, 55, 66} + self.assertIn(original, live_slots) + self.assertIn(replacement, live_slots) + self.assertNotEqual(replacement, original) + self.assertFalse(bool(diff[1, 0].item())) + + def test_collect_active_slots_ignores_padded_out_cache_loc(self) -> None: + """Verify out_cache_loc padding does not exclude a live slot.""" + device = DEFAULT_DEVICE + pool = make_req_to_token_pool(device, max_reqs=4, max_seq_len=8) + pool.req_to_token[1, :2] = torch.tensor( + [0, 7], dtype=torch.int32, device=device + ) + forward_batch = make_forward_batch(device, bs=1, seq_lens_list=(2,)) + forward_batch.out_cache_loc = torch.tensor( + [7, 0, 0], dtype=torch.int32, device=device + ) + forward_batch.num_token_non_padded_cpu = 1 + + targets = collect_active_slots( + maybe_inaccurate_forward_batch=forward_batch, + req_to_token_pool=pool, + ) + + self.assertEqual([target.value for target in targets], [0]) + + +class TestRealKvUsedPerturb(CustomTestCase): + def test_real_kv_used_flips_first_real_kv_byte_for_active_full_slot( + self, + ) -> None: + """Verify real_kv_used flips only the first real KV byte for an active FULL slot.""" + device = DEFAULT_DEVICE + pool = make_req_to_token_pool(device, max_reqs=4, max_seq_len=8) + pool.req_to_token.fill_(-1) + pool.req_to_token[1, 0] = 2 + group = make_buffer_group(kind=PoolKind.FULL, has_real_kv=True) + source = group.real_kv_sources_k[0] + source.tensor.copy_( + torch.arange(source.tensor.numel(), dtype=torch.uint8).view_as( + source.tensor + ) + ) + manager = PerturbManager( + config=PerturbConfig( + req_to_token_prob=0.0, + real_kv_used_prob=1.0, + real_kv_unused_cache_prob=0.0, + real_kv_post_forward_prob=0.0, + target_group_kind=TargetGroupKind.FULL, + warmup_steps=0, + ), + req_to_token_pool=pool, + buffer_groups=(group,), + outer_step_counter_getter=lambda: 10, + ) + forward_batch = make_forward_batch(device, bs=1, seq_lens_list=(1,)) + forward_batch.out_cache_loc = torch.tensor( + [99], dtype=torch.int32, device=device + ) + + snapshot = source.tensor.clone() + with patch.object(torch, "rand", return_value=torch.tensor(0.0)): + manager.perturb_real_kv_used(forward_batch) + + expected = snapshot.clone() + expected[2, 0] = int(snapshot[2, 0].item()) ^ 0xFF + self.assertTrue(torch.equal(source.tensor, expected)) + + def test_flip_first_byte_in_source_maps_swa_logical_slot_through_lut( + self, + ) -> None: + """Verify SWA groups map logical slots through swa_index_lut before flipping bytes.""" + source = RealKvSource( + tensor=torch.arange(64, dtype=torch.uint8).view(2, 32), + page_size=2, + num_bytes_per_token=16, + read_bytes=16, + ) + group = make_buffer_group( + kind=PoolKind.SWA, + has_real_kv=True, + real_kv_source=source, + swa_index_lut=torch.tensor([0, 3], dtype=torch.int32), + ) + + snapshot = source.tensor.clone() + result = flip_first_byte_in_source(group=group, source=source, slot_idx=1) + + self.assertEqual(result, (1, 16, int(snapshot[1, 16].item()))) + expected = snapshot.clone() + expected[1, 16] = int(snapshot[1, 16].item()) ^ 0xFF + self.assertTrue(torch.equal(source.tensor, expected)) + + def test_warmup_gate_prevents_perturbation_when_probabilities_are_one(self) -> None: + """Verify warmup prevents all perturbations even when every probability is one.""" + device = DEFAULT_DEVICE + pool = make_req_to_token_pool(device, max_reqs=4, max_seq_len=8) + pool.req_to_token.fill_(-1) + pool.req_to_token[1, 0] = 2 + group = make_buffer_group(kind=PoolKind.FULL, has_real_kv=True) + source = group.real_kv_sources_k[0] + source.tensor.copy_( + torch.arange(source.tensor.numel(), dtype=torch.uint8).view_as( + source.tensor + ) + ) + manager = PerturbManager( + config=PerturbConfig( + req_to_token_prob=1.0, + real_kv_used_prob=1.0, + real_kv_unused_cache_prob=1.0, + real_kv_post_forward_prob=0.0, + target_group_kind=TargetGroupKind.FULL, + warmup_steps=20, + ), + req_to_token_pool=pool, + buffer_groups=(group,), + outer_step_counter_getter=lambda: 10, + ) + manager.attach_radix_cache(cast("BasePrefixCache", object())) + forward_batch = make_forward_batch(device, bs=1, seq_lens_list=(1,)) + forward_batch.out_cache_loc = torch.tensor( + [99], dtype=torch.int32, device=device + ) + + pool_snapshot = pool.req_to_token.clone() + source_snapshot = source.tensor.clone() + with patch.object(torch, "rand", return_value=torch.tensor(0.0)), patch.object( + real_kv_unused_cache_module, + "_pick_sweep_slot_for_group", + return_value=3, + ): + manager.perturb(maybe_inaccurate_forward_batch=forward_batch) + + self.assertTrue(torch.equal(pool.req_to_token, pool_snapshot)) + self.assertTrue(torch.equal(source.tensor, source_snapshot)) + + +class TestRealKvUnusedCachePerturb(CustomTestCase): + def test_real_kv_unused_cache_flips_first_real_kv_byte_for_orphan_slot( + self, + ) -> None: + """Verify real_kv_unused_cache flips only the first real KV byte for an orphan slot.""" + device = DEFAULT_DEVICE + pool = make_req_to_token_pool(device, max_reqs=4, max_seq_len=8) + group = make_buffer_group(kind=PoolKind.FULL, has_real_kv=True) + source = group.real_kv_sources_k[0] + source.tensor.copy_( + torch.arange(source.tensor.numel(), dtype=torch.uint8).view_as( + source.tensor + ) + ) + manager = PerturbManager( + config=PerturbConfig( + req_to_token_prob=0.0, + real_kv_used_prob=0.0, + real_kv_unused_cache_prob=1.0, + real_kv_post_forward_prob=0.0, + target_group_kind=TargetGroupKind.FULL, + warmup_steps=0, + ), + req_to_token_pool=pool, + buffer_groups=(group,), + outer_step_counter_getter=lambda: 10, + sweep_interval=1, + ) + manager.attach_radix_cache(make_radix_cache([[], [3]], device=device)) + + snapshot = source.tensor.clone() + with patch.object(torch, "rand", return_value=torch.tensor(0.0)), patch.object( + torch, + "randint", + return_value=torch.tensor(0), + ): + manager.perturb_real_kv_unused_cache(None) + + expected = snapshot.clone() + expected[3, 0] = int(snapshot[3, 0].item()) ^ 0xFF + self.assertTrue(torch.equal(source.tensor, expected)) + + def test_pick_sweep_slot_for_group_skips_locked_radix_nodes(self) -> None: + """Verify unused-cache perturbation chooses only unlocked radix-cache slots.""" + device = DEFAULT_DEVICE + group = make_buffer_group(kind=PoolKind.FULL, has_real_kv=True) + cache = make_radix_cache([[], [1, 2], [3]], device=device) + locked_node = next(iter(cache.root_node.children.values())) + locked_node.lock_ref = 1 + + with patch.object(torch, "randint", return_value=torch.tensor(0)): + slot = real_kv_unused_cache_module._pick_sweep_slot_for_group( + radix_cache=cache, + group=group, + swa_window_size=0, + ) + + self.assertEqual(slot, 3) + + def test_pick_sweep_slot_for_group_translates_swa_slots(self) -> None: + """Verify unused-cache SWA perturbation translates full slots to physical SWA slots.""" + device = DEFAULT_DEVICE + lut = torch.tensor([-1, 2], dtype=torch.int64, device=device) + group = make_buffer_group( + kind=PoolKind.SWA, has_real_kv=True, swa_index_lut=lut + ) + cache = make_radix_cache([[], [1]], device=device) + + with patch.object(torch, "randint", return_value=torch.tensor(0)): + slot = real_kv_unused_cache_module._pick_sweep_slot_for_group( + radix_cache=cache, + group=group, + swa_window_size=4, + ) + + self.assertEqual(slot, 2) + + def test_real_kv_unused_cache_skips_without_radix_cache_when_forward_batch_is_none( + self, + ) -> None: + """Verify unused-cache perturbation accepts no forward batch but skips without radix_cache.""" + device = DEFAULT_DEVICE + group = make_buffer_group(kind=PoolKind.FULL, has_real_kv=True) + source = group.real_kv_sources_k[0] + source.tensor.copy_( + torch.arange(source.tensor.numel(), dtype=torch.uint8).view_as( + source.tensor + ) + ) + manager = PerturbManager( + config=PerturbConfig( + req_to_token_prob=0.0, + real_kv_used_prob=0.0, + real_kv_unused_cache_prob=1.0, + real_kv_post_forward_prob=0.0, + target_group_kind=TargetGroupKind.FULL, + warmup_steps=0, + ), + req_to_token_pool=make_req_to_token_pool(device, max_reqs=4, max_seq_len=8), + buffer_groups=(group,), + outer_step_counter_getter=lambda: 10, + sweep_interval=1, + ) + + snapshot = source.tensor.clone() + with patch.object(torch, "rand", return_value=torch.tensor(0.0)): + manager.perturb_real_kv_unused_cache(None) + + self.assertTrue(torch.equal(source.tensor, snapshot)) + + +class TestPerturbUtils(CustomTestCase): + def test_flip_first_byte_in_physical_swa_slot_does_not_translate_twice( + self, + ) -> None: + """Verify a physical SWA slot selected from sweep is not LUT-translated again.""" + group = make_buffer_group(kind=PoolKind.SWA, has_real_kv=True) + source = group.real_kv_sources_k[0] + source.tensor[2, 0] = 0x12 + source.tensor[3, 0] = 0x34 + + result = flip_first_byte_in_source( + group=group, + source=source, + slot_idx=2, + slot_is_physical=True, + ) + + self.assertEqual(result, (2, 0, 0x12)) + self.assertEqual(int(source.tensor[2, 0].item()), 0xED) + self.assertEqual(int(source.tensor[3, 0].item()), 0x34) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_plan_input.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_plan_input.py new file mode 100644 index 0000000000000000000000000000000000000000..200d7ce2c52fd50a3002ce5f68f7f357849c7350 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_plan_input.py @@ -0,0 +1,151 @@ +from __future__ import annotations + +import unittest +from types import SimpleNamespace + +import torch + +from sglang.srt.kv_canary.plan_input import PlanInput +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import ( + DEFAULT_DEVICE, + make_forward_batch, +) +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=30, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=30, suite="extra-a-test-1-gpu-small-amd") + + +def _make_static_plan_input(*, bs_capacity: int, device) -> PlanInput: + return PlanInput( + req_pool_indices=torch.zeros(bs_capacity, dtype=torch.int64, device=device), + prefix_lens=torch.zeros(bs_capacity, dtype=torch.int64, device=device), + extend_seq_lens=torch.zeros(bs_capacity, dtype=torch.int64, device=device), + req_to_verify_expected_tokens_valid_lens=torch.zeros( + bs_capacity, dtype=torch.int64, device=device + ), + ) + + +class TestSelfUnitPlanInput(CustomTestCase): + def setUp(self): + self.device = DEFAULT_DEVICE + + def test_plan_input_fill_from_forward_batch_extend(self): + """Verify extend batches populate per-forward plan inputs.""" + fb = make_forward_batch( + self.device, + req_pool_indices=torch.tensor( + [1, 2], dtype=torch.int64, device=self.device + ), + seq_lens=torch.tensor([10, 12], dtype=torch.int32, device=self.device), + extend_prefix_lens=torch.tensor( + [3, 5], dtype=torch.int32, device=self.device + ), + extend_seq_lens=torch.tensor([7, 7], dtype=torch.int32, device=self.device), + is_extend=True, + ) + plan = _make_static_plan_input(bs_capacity=4, device=self.device) + plan.fill_from_forward_batch(forward_batch=fb) + self.assertEqual(plan.req_pool_indices[:2].tolist(), [1, 2]) + self.assertEqual(plan.req_pool_indices[2:].tolist(), [0, 0]) + self.assertEqual(plan.prefix_lens[:2].tolist(), [3, 5]) + self.assertEqual(plan.extend_seq_lens[:2].tolist(), [7, 7]) + self.assertEqual(plan.prefix_lens.dtype, torch.int64) + self.assertEqual(plan.extend_seq_lens.dtype, torch.int64) + + def test_plan_input_fill_from_forward_batch_target_verify(self): + """Verify target-verify batches derive draft verification spans.""" + # TARGET_VERIFY writes spec_info.draft_token_num positions per req starting at the + # current (un-bumped) seq_lens; extend_prefix_lens / extend_seq_lens are deliberately + # NOT supplied because init_new does not populate them for this mode. + spec_info = SimpleNamespace(draft_token_num=4) + fb = make_forward_batch( + self.device, + req_pool_indices=torch.tensor( + [6, 7], dtype=torch.int64, device=self.device + ), + seq_lens=torch.tensor([10, 14], dtype=torch.int32, device=self.device), + is_target_verify=True, + spec_info=spec_info, + ) + plan = _make_static_plan_input(bs_capacity=4, device=self.device) + plan.fill_from_forward_batch(forward_batch=fb) + self.assertEqual(plan.prefix_lens[:2].tolist(), [10, 14]) + self.assertEqual(plan.extend_seq_lens[:2].tolist(), [4, 4]) + + def test_plan_input_fill_from_forward_batch_draft_extend_v2(self): + """Verify draft-extend-v2 batches derive prefix lengths from sequence lengths.""" + # DRAFT_EXTEND_V2 has seq_lens already bumped by the per-req draft refill length; + # extend_prefix_lens is intentionally absent (cuda-graph replay does not set it). The + # builder must derive prefix as seq_lens - extend_seq_lens. + fb = make_forward_batch( + self.device, + req_pool_indices=torch.tensor( + [4, 5], dtype=torch.int64, device=self.device + ), + seq_lens=torch.tensor([14, 18], dtype=torch.int32, device=self.device), + extend_seq_lens=torch.tensor([4, 4], dtype=torch.int32, device=self.device), + is_draft_extend_v2=True, + ) + plan = _make_static_plan_input(bs_capacity=4, device=self.device) + plan.fill_from_forward_batch(forward_batch=fb) + self.assertEqual(plan.prefix_lens[:2].tolist(), [10, 14]) + self.assertEqual(plan.extend_seq_lens[:2].tolist(), [4, 4]) + + def test_plan_input_fill_from_forward_batch_decode(self): + """Verify decode batches populate one-token verification spans.""" + fb = make_forward_batch( + self.device, + req_pool_indices=torch.tensor( + [1, 2, 3], dtype=torch.int64, device=self.device + ), + seq_lens=torch.tensor([4, 7, 1], dtype=torch.int32, device=self.device), + is_extend=False, + ) + plan = _make_static_plan_input(bs_capacity=4, device=self.device) + plan.fill_from_forward_batch(forward_batch=fb) + self.assertEqual(plan.prefix_lens[:3].tolist(), [3, 6, 0]) + self.assertEqual(plan.extend_seq_lens[:3].tolist(), [1, 1, 1]) + + def test_plan_input_mirrors_req_all_ids_lens(self): + """req_to_verify_expected_tokens_valid_lens copies forward_batch.req_all_ids_lens for active rows.""" + fb = make_forward_batch( + self.device, + req_pool_indices=torch.tensor( + [1, 2], dtype=torch.int64, device=self.device + ), + seq_lens=torch.tensor([10, 12], dtype=torch.int32, device=self.device), + is_extend=False, + ) + fb.req_all_ids_lens = torch.tensor([7, 9], dtype=torch.int64, pin_memory=True) + plan = _make_static_plan_input(bs_capacity=4, device=self.device) + plan.fill_from_forward_batch(forward_batch=fb) + torch.cuda.synchronize() + self.assertEqual( + plan.req_to_verify_expected_tokens_valid_lens[:2].tolist(), [7, 9] + ) + # Padding tail stays at zero so the plan kernel reads "no in-range positions" for it. + self.assertEqual( + plan.req_to_verify_expected_tokens_valid_lens[2:].tolist(), [0, 0] + ) + + def test_plan_input_padding_dummy_sentinel(self): + """Verify padding sentinel rows remain valid plan input entries.""" + fb = make_forward_batch( + self.device, + req_pool_indices=torch.tensor( + [0, 5, 0], dtype=torch.int64, device=self.device + ), + seq_lens=torch.tensor([0, 3, 0], dtype=torch.int32, device=self.device), + is_extend=False, + ) + plan = _make_static_plan_input(bs_capacity=4, device=self.device) + plan.fill_from_forward_batch(forward_batch=fb) + self.assertEqual(plan.req_pool_indices[:3].tolist(), [0, 5, 0]) + self.assertEqual(plan.req_pool_indices.dtype, torch.int64) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_pool_patcher.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_pool_patcher.py new file mode 100644 index 0000000000000000000000000000000000000000..aac3263a5e8d8f492fdc74348ebbb99ea7fe39fb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_pool_patcher.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +import unittest + +import torch + +from sglang.jit_kernel.kv_canary.consts import MAX_REAL_KV_SOURCES, RealKvHashMode +from sglang.jit_kernel.kv_canary.verify import ( + CANARY_SLOT_BYTES, + CanaryLaunchTag, + RealKvSource, + VerifyOrWriteContext, + VerifyPlan, + launch_canary_verify_kernel, +) +from sglang.srt.kv_canary.buffer_group import PoolKind +from sglang.srt.kv_canary.pool_patcher.api import attach_canary_buffers +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import ( + DEFAULT_DEVICE, + make_base_config, + make_mha_pool, + make_swa_pool, +) +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=45, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=45, suite="extra-a-test-1-gpu-small-amd") + + +class PoolPatcherHelper: + def setUp(self): + self.device = DEFAULT_DEVICE + self.config = make_base_config() + + +class TestAttachCanaryBuffers(PoolPatcherHelper, CustomTestCase): + def test_canary_buffer_group_allocate_full_only(self): + """Verify MHA pools allocate only full canary buffers.""" + pool = make_mha_pool(self.device, num_slots=16, dim=8, layer_num=2) + groups_tuple = attach_canary_buffers( + pool=pool, + config=self.config, + device=self.device, + kv_token_id_vs_position_offset=0, + ) + groups = {g.kind: g for g in groups_tuple} + self.assertEqual(set(groups.keys()), {PoolKind.FULL}) + group = groups[PoolKind.FULL] + self.assertEqual(group.k_head.shape, (16, CANARY_SLOT_BYTES)) + self.assertEqual(group.k_tail.shape, (16, CANARY_SLOT_BYTES)) + self.assertIsNotNone(group.v_head) + self.assertIsNotNone(group.v_tail) + self.assertEqual(group.v_head.shape, (16, CANARY_SLOT_BYTES)) + + def test_canary_buffer_group_allocate_full_and_swa(self): + """Verify SWA pools allocate full and SWA canary buffers.""" + pool = make_swa_pool(self.device, full_slots=16, swa_slots=8) + groups_tuple = attach_canary_buffers( + pool=pool, + config=self.config, + device=self.device, + kv_token_id_vs_position_offset=0, + ) + groups = {g.kind: g for g in groups_tuple} + self.assertEqual(set(groups.keys()), {PoolKind.FULL, PoolKind.SWA}) + self.assertEqual(groups[PoolKind.FULL].k_head.shape[0], 16) + self.assertEqual(groups[PoolKind.SWA].k_head.shape[0], 8) + self.assertIsNotNone(groups[PoolKind.SWA].swa_index_lut) + self.assertIsNone(groups[PoolKind.FULL].swa_index_lut) + + +class TestRealKvSources(PoolPatcherHelper, CustomTestCase): + def test_real_kv_sources_above_4_raises(self): + """Verify too many real KV sources are rejected.""" + tensor = torch.zeros(4, 16, dtype=torch.uint8, device=self.device) + sources = tuple( + RealKvSource( + tensor=tensor, page_size=1, num_bytes_per_token=16, read_bytes=16 + ) + for _ in range(MAX_REAL_KV_SOURCES + 1) + ) + canary_buf = torch.zeros( + 4, CANARY_SLOT_BYTES, dtype=torch.uint8, device=self.device + ) + plan = VerifyPlan.allocate(verify_capacity=1, device=self.device) + violation_ring = torch.zeros(2, 8, dtype=torch.int64, device=self.device) + violation_write_index = torch.zeros(1, dtype=torch.int32, device=self.device) + slot_run_counter = torch.zeros(1, dtype=torch.int64, device=self.device) + kernel_run_counter = torch.zeros(1, dtype=torch.int64, device=self.device) + + enable_chain_position_assert = torch.ones( + 1, dtype=torch.int32, device=self.device + ) + + with self.assertRaises(ValueError): + launch_canary_verify_kernel( + context=VerifyOrWriteContext( + canary_buf=canary_buf, + kernel_kind=CanaryLaunchTag.HEAD_K_FULL, + violation_ring=violation_ring, + violation_write_index=violation_write_index, + slot_run_counter=slot_run_counter, + kernel_run_counter=kernel_run_counter, + real_kv_sources=sources, + real_kv_hash_mode=RealKvHashMode.NONE, + enable_chain_position_assert=enable_chain_position_assert, + ), + plan=plan, + check_verify_expected_token=True, + ) + + +class TestPoolPatcherBufferInfos(PoolPatcherHelper, CustomTestCase): + def test_get_contiguous_buf_infos_inserts_canary_entries(self): + """Verify contiguous buffer metadata includes canary entries after patching.""" + for patched in (False, True): + with self.subTest(patched=patched): + pool = make_mha_pool(self.device, num_slots=16, dim=8, layer_num=2) + ptrs_before, _, _ = pool.get_contiguous_buf_infos() + n_before = len(ptrs_before) + + if patched: + attach_canary_buffers( + pool=pool, + config=self.config, + device=self.device, + kv_token_id_vs_position_offset=0, + ) + ptrs_after, _, _ = pool.get_contiguous_buf_infos() + self.assertEqual(len(ptrs_after), n_before + 4) + else: + ptrs_after, _, _ = pool.get_contiguous_buf_infos() + self.assertEqual(ptrs_after, ptrs_before) + + def test_swa_attach_splices_full_into_contiguous_and_swa_into_state(self): + """Verify SWA patching splices canary buffers into both buffer lists.""" + pool = make_swa_pool(self.device, full_slots=16, swa_slots=8) + contiguous_before, _, _ = pool.get_contiguous_buf_infos() + state_before, _, _ = pool.get_state_buf_infos() + + attach_canary_buffers( + pool=pool, + config=self.config, + device=self.device, + kv_token_id_vs_position_offset=0, + ) + + contiguous_after, _, _ = pool.get_contiguous_buf_infos() + state_after, _, _ = pool.get_state_buf_infos() + self.assertEqual(len(contiguous_after), len(contiguous_before) + 4) + self.assertEqual(len(state_after), len(state_before) + 4) + + def test_pd_layout_canary_inserted_correctly(self): + """Verify PD (prefill-decode disaggregation) canary buffers are inserted in layout order.""" + pool = make_mha_pool(self.device, num_slots=16, dim=8, layer_num=2) + k_ptrs_orig = [b.data_ptr() for b in pool.k_buffer] + v_ptrs_orig = [b.data_ptr() for b in pool.v_buffer] + + groups_tuple = attach_canary_buffers( + pool=pool, + config=self.config, + device=self.device, + kv_token_id_vs_position_offset=0, + ) + group = {g.kind: g for g in groups_tuple}[PoolKind.FULL] + ptrs_after, _, _ = pool.get_contiguous_buf_infos() + + canary_k_ptrs = [group.k_head.data_ptr(), group.k_tail.data_ptr()] + canary_v_ptrs = [group.v_head.data_ptr(), group.v_tail.data_ptr()] + self.assertEqual(ptrs_after[0], canary_k_ptrs[0]) + self.assertEqual(ptrs_after[1 : 1 + len(k_ptrs_orig)], k_ptrs_orig) + k_tail_idx = 1 + len(k_ptrs_orig) + self.assertEqual(ptrs_after[k_tail_idx], canary_k_ptrs[1]) + self.assertEqual(ptrs_after[k_tail_idx + 1], canary_v_ptrs[0]) + v_start = k_tail_idx + 2 + self.assertEqual(ptrs_after[v_start : v_start + len(v_ptrs_orig)], v_ptrs_orig) + self.assertEqual(ptrs_after[-1], canary_v_ptrs[1]) + + +class TestCanaryBufferBudget(PoolPatcherHelper, CustomTestCase): + def test_canary_buf_per_token_bytes_within_budget(self): + """Verify canary per-token storage stays below the real KV budget.""" + pool = make_mha_pool(self.device, num_slots=16, dim=64, layer_num=2) + groups_tuple = attach_canary_buffers( + pool=pool, + config=self.config, + device=self.device, + kv_token_id_vs_position_offset=0, + ) + group = {g.kind: g for g in groups_tuple}[PoolKind.FULL] + + slot_stride_bytes = group.k_head.stride(0) * group.k_head.element_size() + self.assertLessEqual(slot_stride_bytes, CANARY_SLOT_BYTES) + + real_kv_per_token_bytes = ( + pool.k_buffer[0].stride(0) * pool.k_buffer[0].element_size() + ) + self.assertLess(slot_stride_bytes, real_kv_per_token_bytes) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_pool_patcher_utils.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_pool_patcher_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..559712c1b30fe8c21752cce6972dfd450336d69b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_pool_patcher_utils.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import unittest + +from sglang.srt.kv_canary.pool_patcher.utils import wrap_method +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=10, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=10, suite="extra-a-test-1-gpu-small-amd") + + +class _FakeObj: + def greet(self, name: str) -> str: + return f"hello {name}" + + +class TestPoolPatcherUtils(CustomTestCase): + def test_wrap_method_delegates_to_wrapper(self) -> None: + """Verify wrapped methods delegate through the wrapper.""" + obj = _FakeObj() + + def _with_validation(original, name: str) -> str: + return original(name) + "!" + + wrap_method(obj, "greet", wrapper=_with_validation) + self.assertEqual(obj.greet("world"), "hello world!") + + def test_wrap_method_missing_method_raises_attribute_error(self) -> None: + """Verify wrapping a missing method raises AttributeError.""" + obj = _FakeObj() + with self.assertRaisesRegex(AttributeError, "missing required method"): + wrap_method( + obj, "nonexistent", wrapper=lambda orig, *a, **kw: orig(*a, **kw) + ) + + def test_wrap_method_double_wrap_raises_runtime_error(self) -> None: + """Verify wrapping the same method twice raises RuntimeError.""" + obj = _FakeObj() + wrap_method(obj, "greet", wrapper=lambda orig, *a, **kw: orig(*a, **kw)) + with self.assertRaisesRegex(RuntimeError, "already wrapped by kv-canary"): + wrap_method(obj, "greet", wrapper=lambda orig, *a, **kw: orig(*a, **kw)) + + def test_wrap_method_preserves_functools_wraps_metadata(self) -> None: + """Verify wrapping preserves method metadata.""" + obj = _FakeObj() + original_name = obj.greet.__name__ + wrap_method(obj, "greet", wrapper=lambda orig, *a, **kw: orig(*a, **kw)) + self.assertEqual(obj.greet.__name__, original_name) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_radix_walker.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_radix_walker.py new file mode 100644 index 0000000000000000000000000000000000000000..ec2b12de19fa9fa524562ee02916d1cc3f67d6ee --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_radix_walker.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import unittest + +import torch + +from sglang.srt.kv_canary.radix_cache_walker import walk_radix_cache_for_canary +from sglang.srt.mem_cache.swa_radix_cache import SWARadixCache, TreeNode +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import DEFAULT_DEVICE, make_radix_cache +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=30, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=30, suite="extra-a-test-1-gpu-small-amd") + + +class TestSelfUnitRadixWalker(CustomTestCase): + def setUp(self): + self.device = DEFAULT_DEVICE + + def test_single_node_chain_positions_increase(self): + """Verify a single radix chain emits increasing positions.""" + chain = [10, 20, 30, 40] + cache = make_radix_cache([[], chain], device=self.device) + result = walk_radix_cache_for_canary(radix_cache=cache) + self.assertEqual(result.slot_indices.tolist(), chain) + self.assertEqual(result.positions.tolist(), [0, 1, 2, 3]) + self.assertEqual(result.prev_slot_indices.tolist(), [-1, 10, 20, 30]) + + def test_child_node_first_slot_prev_is_parent_last(self): + """Verify child chains link their first slot to the parent tail.""" + parent = [7, 8] + child = [9, 10] + cache = make_radix_cache([[], parent, child], device=self.device) + result = walk_radix_cache_for_canary(radix_cache=cache) + self.assertEqual(result.slot_indices.tolist(), parent + child) + self.assertEqual(result.prev_slot_indices.tolist()[len(parent)], parent[-1]) + + def test_root_child_first_slot_prev_minus_one(self): + """Verify root child chains use -1 as the initial previous slot.""" + cache = make_radix_cache([[], [42, 43]], device=self.device) + result = walk_radix_cache_for_canary(radix_cache=cache) + self.assertEqual(int(result.prev_slot_indices[0]), -1) + + def test_position_equals_depth_from_root(self): + """Verify emitted positions match depth from the radix root.""" + cache = make_radix_cache([[], [1, 2], [3], [4, 5]], device=self.device) + result = walk_radix_cache_for_canary(radix_cache=cache) + self.assertEqual(result.positions.tolist(), [0, 1, 2, 3, 4]) + self.assertEqual(result.slot_indices.tolist(), [1, 2, 3, 4, 5]) + + def test_walk_includes_locked_nodes_by_default(self): + """Verify radix walking includes locked nodes by default.""" + cache = make_radix_cache([[], [1, 2], [3, 4]], device=self.device) + locked_node = next(iter(cache.root_node.children.values())) + locked_node.lock_ref = 1 + result = walk_radix_cache_for_canary(radix_cache=cache) + self.assertEqual(result.slot_indices.tolist(), [1, 2, 3, 4]) + + def test_walk_unlocked_only_skips_locked(self): + """Verify unlocked-only radix walking skips locked nodes.""" + cache = make_radix_cache([[], [1, 2], [3, 4]], device=self.device) + locked_node = next(iter(cache.root_node.children.values())) + locked_node.lock_ref = 1 + result = walk_radix_cache_for_canary(radix_cache=cache, unlocked_only=True) + self.assertEqual(result.slot_indices.tolist(), [3, 4]) + + def test_walk_unlocked_only_uses_swa_full_lock_ref(self): + """Verify SWA radix walking honors full-pool lock references.""" + cache = SWARadixCache.__new__(SWARadixCache) + cache.device = self.device + cache.page_size = 1 + cache.disable = False + + root = TreeNode() + root.value = torch.tensor([], dtype=torch.int32, device=self.device) + cache.root_node = root + + locked_child = TreeNode() + locked_child.value = torch.tensor([1, 2], dtype=torch.int32, device=self.device) + locked_child.parent = root + locked_child.full_lock_ref = 1 + root.children[locked_child.id] = locked_child + + unlocked_child = TreeNode() + unlocked_child.value = torch.tensor( + [3, 4], dtype=torch.int32, device=self.device + ) + unlocked_child.parent = root + root.children[unlocked_child.id] = unlocked_child + + result = walk_radix_cache_for_canary(radix_cache=cache, unlocked_only=True) + self.assertEqual(result.slot_indices.tolist(), [3, 4]) + + def test_swa_resident_only_skips_tombstoned_nodes(self): + """Verify SWA radix walking skips nodes whose SWA storage was evicted.""" + cache = SWARadixCache.__new__(SWARadixCache) + cache.device = self.device + cache.page_size = 1 + cache.disable = False + + root = TreeNode() + root.value = torch.tensor([], dtype=torch.int32, device=self.device) + cache.root_node = root + + tombstoned_child = TreeNode() + tombstoned_child.value = torch.tensor( + [1, 2], dtype=torch.int32, device=self.device + ) + tombstoned_child.parent = root + tombstoned_child.swa_tombstone = True + root.children[tombstoned_child.id] = tombstoned_child + + resident_child = TreeNode() + resident_child.value = torch.tensor( + [3, 4], dtype=torch.int32, device=self.device + ) + resident_child.parent = root + root.children[resident_child.id] = resident_child + + result = walk_radix_cache_for_canary( + radix_cache=cache, + swa_resident_only=True, + ) + self.assertEqual(result.slot_indices.tolist(), [3, 4]) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_req_to_expected_token_ids_manager.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_req_to_expected_token_ids_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..743018ba0a4db4be9d3cb72120e4916e8a26a3da --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_req_to_expected_token_ids_manager.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +import unittest +from array import array +from types import SimpleNamespace + +import torch + +from sglang.srt.kv_canary.req_to_expected_token_ids_manager import ( + compute_req_all_ids_info, + populate_req_to_expected_token_ids, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import DEFAULT_DEVICE, make_forward_batch +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=15, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=15, suite="extra-a-test-1-gpu-small-amd") + + +def _make_req(*, origin: list[int], output: list[int]) -> SimpleNamespace: + return SimpleNamespace( + origin_input_ids=array("q", origin), + output_ids=array("q", output), + ) + + +class TestComputeReqAllIdsInfo(CustomTestCase): + def test_single_req_concatenates_origin_then_output(self) -> None: + """One req's flat is origin_input_ids followed by output_ids in that order.""" + req = _make_req(origin=[10, 20, 30], output=[40, 50]) + flat, lens = compute_req_all_ids_info([req]) + self.assertEqual(flat.tolist(), [10, 20, 30, 40, 50]) + self.assertEqual(lens.tolist(), [5]) + + def test_multi_req_flat_is_concat_across_reqs(self) -> None: + """Multi-req flat is per-req (origin+output) concatenated in req order.""" + reqs = [ + _make_req(origin=[1, 2], output=[3]), + _make_req(origin=[100], output=[]), + _make_req(origin=[7, 8, 9], output=[10, 11]), + ] + flat, lens = compute_req_all_ids_info(reqs) + self.assertEqual(flat.tolist(), [1, 2, 3, 100, 7, 8, 9, 10, 11]) + self.assertEqual(lens.tolist(), [3, 1, 5]) + + def test_returned_cpu_tensors_are_pinned(self) -> None: + """Snapshot tensors live on pinned CPU memory so the manager's async H2D actually overlaps.""" + req = _make_req(origin=[1, 2, 3], output=[4]) + flat, lens = compute_req_all_ids_info([req]) + self.assertTrue(flat.is_pinned()) + self.assertTrue(lens.is_pinned()) + self.assertEqual(flat.device, torch.device("cpu")) + self.assertEqual(lens.device, torch.device("cpu")) + + +class TestPopulateReqToExpectedTokenIds(CustomTestCase): + def setUp(self) -> None: + self.device = DEFAULT_DEVICE + + def _make_pool(self, *, max_reqs: int, max_context_len: int) -> torch.Tensor: + return torch.full( + (max_reqs, max_context_len), + -999, + dtype=torch.int32, + device=self.device, + ) + + def _fb_with_snapshot( + self, + *, + req_pool_indices: list[int], + lens: list[int], + flat: list[int], + ) -> SimpleNamespace: + fb = make_forward_batch( + self.device, + bs=len(req_pool_indices), + req_pool_indices=torch.tensor( + req_pool_indices, dtype=torch.int64, device=self.device + ), + ) + fb.req_all_ids_flat = torch.tensor(flat, dtype=torch.int64, pin_memory=True) + fb.req_all_ids_lens = torch.tensor(lens, dtype=torch.int64, pin_memory=True) + return fb + + def test_no_op_when_snapshot_is_none(self) -> None: + """Cuda-graph capture's dry-run leaves snapshot fields as None; manager must early-return.""" + fb = make_forward_batch(self.device, bs=2) + pool = self._make_pool(max_reqs=4, max_context_len=8) + original = pool.clone() + populate_req_to_expected_token_ids( + forward_batch=fb, req_to_verify_expected_tokens=pool + ) + torch.cuda.synchronize() + self.assertTrue(torch.equal(pool, original)) + + def test_no_op_when_pool_is_none(self) -> None: + """When the validator is off the device pool is None; manager must early-return without touching anything.""" + fb = self._fb_with_snapshot(req_pool_indices=[1], lens=[3], flat=[10, 20, 30]) + populate_req_to_expected_token_ids( + forward_batch=fb, req_to_verify_expected_tokens=None + ) + + def test_no_op_when_bs_zero(self) -> None: + """Empty batch (bs == 0) must early-return; no kernel launch.""" + fb = make_forward_batch( + self.device, + bs=0, + req_pool_indices=torch.zeros(0, dtype=torch.int64, device=self.device), + seq_lens=torch.zeros(0, dtype=torch.int32, device=self.device), + ) + fb.req_all_ids_flat = torch.zeros(0, dtype=torch.int64, pin_memory=True) + fb.req_all_ids_lens = torch.zeros(0, dtype=torch.int64, pin_memory=True) + pool = self._make_pool(max_reqs=4, max_context_len=8) + original = pool.clone() + populate_req_to_expected_token_ids( + forward_batch=fb, req_to_verify_expected_tokens=pool + ) + torch.cuda.synchronize() + self.assertTrue(torch.equal(pool, original)) + + def test_raises_when_lens_length_mismatches_batch_size(self) -> None: + """req_all_ids_lens length must equal forward_batch batch size; mismatch indicates a corrupted snapshot.""" + fb = self._fb_with_snapshot( + req_pool_indices=[1, 2], lens=[3], flat=[10, 20, 30] + ) + pool = self._make_pool(max_reqs=4, max_context_len=8) + with self.assertRaisesRegex(RuntimeError, "req_all_ids_lens length"): + populate_req_to_expected_token_ids( + forward_batch=fb, req_to_verify_expected_tokens=pool + ) + + def test_raises_when_cumsum_does_not_match_flat_numel(self) -> None: + """cumsum(lens) must equal flat.numel(); inconsistent snapshot raises.""" + fb = self._fb_with_snapshot( + req_pool_indices=[1, 2], lens=[3, 4], flat=[10, 20, 30, 40] + ) + pool = self._make_pool(max_reqs=4, max_context_len=8) + with self.assertRaisesRegex(RuntimeError, "snapshot inconsistent"): + populate_req_to_expected_token_ids( + forward_batch=fb, req_to_verify_expected_tokens=pool + ) + + def test_happy_path_scatters_each_req_into_its_pool_row(self) -> None: + """Scatter populates pool[rp, :len_r] = req_r's flattened tokens; other rows untouched.""" + fb = self._fb_with_snapshot( + req_pool_indices=[1, 3], + lens=[3, 2], + flat=[10, 20, 30, 40, 50], + ) + pool = self._make_pool(max_reqs=5, max_context_len=8) + original = pool.clone() + populate_req_to_expected_token_ids( + forward_batch=fb, req_to_verify_expected_tokens=pool + ) + torch.cuda.synchronize() + + pool_cpu = pool.cpu() + self.assertEqual(pool_cpu[1, :3].tolist(), [10, 20, 30]) + self.assertEqual(pool_cpu[3, :2].tolist(), [40, 50]) + # Other rows must be left at their pre-scatter sentinel. + for untouched in (0, 2, 4): + self.assertTrue( + torch.equal(pool_cpu[untouched], original[untouched].cpu()), + f"row {untouched} was unexpectedly modified", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_health.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_health.py new file mode 100644 index 0000000000000000000000000000000000000000..9841938fee0cf89fbddfccd1166058218d1bb3a0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_health.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import logging +import unittest +from unittest.mock import Mock + +import torch + +from sglang.jit_kernel.kv_canary.verify import CanaryLaunchTag +from sglang.srt.kv_canary.config import CanaryConfig +from sglang.srt.kv_canary.runner import stats_logger as stats_logger_module +from sglang.srt.kv_canary.runner.health_checker import KernelRunCounterHealthChecker +from sglang.srt.kv_canary.state import CanaryDeviceState +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.runner_test_base import ( + CanaryManagerTestCase, + make_config, + make_manager, +) +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=45, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=45, suite="extra-a-test-1-gpu-small-amd") + + +class TestSelfUnitManagerHealth(CanaryManagerTestCase): + def test_kernel_run_counter_watchdog_raises_on_zero(self) -> None: + """Verify the kernel watchdog raises when counters stop advancing.""" + manager = make_manager(device=self.device) + manager._outer_step_counter = 1000 + manager._device_state.kernel_run_counters.zero_() + manager._health_checker.step() + manager._outer_step_counter = 2000 + with self.assertRaises(RuntimeError): + manager._health_checker.step() + + def test_kernel_run_counter_watchdog_ignores_sweep_when_sweep_is_disabled( + self, + ) -> None: + """Verify the watchdog ignores disabled sweep counters.""" + config = make_config(sweep_interval=0) + manager = make_manager(device=self.device, config=config) + manager._device_state.kernel_run_counters.zero_() + for tag in ( + CanaryLaunchTag.HEAD_K_FULL, + CanaryLaunchTag.HEAD_V_FULL, + CanaryLaunchTag.TAIL_K_FULL, + CanaryLaunchTag.TAIL_V_FULL, + ): + manager._device_state.kernel_run_counters[tag.value] = 1 + + manager._outer_step_counter = 1000 + manager._health_checker.step() + manager._outer_step_counter = 2000 + manager._health_checker.step() + + def test_periodic_stats_log_every_n_step(self) -> None: + """Verify periodic stats are logged at the configured interval.""" + config = make_config(stats_print_every_n_steps=5) + manager = make_manager(device=self.device, config=config) + manager._device_state.slot_run_counters.fill_(7) + + with self.assertLogs(stats_logger_module.logger.name, level=logging.INFO) as cm: + for _ in range(11): + manager._stats_logger.step() + manager._outer_step_counter += 1 + log_text = "\n".join(cm.output) + self.assertIn("protected_tokens=", log_text) + self.assertTrue("step=5" in log_text or "step=10" in log_text) + + +class TestKernelRunCounterDeltaCheck(CustomTestCase): + """Pure host-side regression tests for the watchdog's delta semantics.""" + + def _make_checker( + self, + *, + active_tags: tuple[CanaryLaunchTag, ...], + outer_step: int, + ) -> KernelRunCounterHealthChecker: + config = Mock(spec=CanaryConfig) + config.sweep_interval = 0 + num_tags = len(CanaryLaunchTag) + device_state = Mock(spec=CanaryDeviceState) + device_state.kernel_run_counters = torch.zeros(num_tags, dtype=torch.int64) + return KernelRunCounterHealthChecker( + config=config, + device_state=device_state, + active_tags=active_tags, + outer_step_counter_getter=lambda: outer_step, + d2h_stream=Mock(), + ) + + def _host_tensor(self, value: int) -> torch.Tensor: + return torch.full((len(CanaryLaunchTag),), value, dtype=torch.int64) + + def test_first_check_raises_when_counter_never_incremented(self) -> None: + active_tags = (CanaryLaunchTag.HEAD_K_FULL, CanaryLaunchTag.TAIL_K_FULL) + checker = self._make_checker(active_tags=active_tags, outer_step=100) + + host_counters = torch.zeros(len(CanaryLaunchTag), dtype=torch.int64) + with self.assertRaises(RuntimeError) as cm: + checker._postprocess_on_host(host_counters) + message = str(cm.exception) + self.assertIn(CanaryLaunchTag.HEAD_K_FULL.name, message) + self.assertIn(CanaryLaunchTag.TAIL_K_FULL.name, message) + self.assertIn("did not increase", message) + + def test_second_check_raises_when_delta_is_zero(self) -> None: + active_tags = (CanaryLaunchTag.HEAD_K_FULL,) + checker = self._make_checker(active_tags=active_tags, outer_step=100) + + checker._postprocess_on_host(self._host_tensor(1)) + with self.assertRaises(RuntimeError) as cm: + checker._postprocess_on_host(self._host_tensor(1)) + message = str(cm.exception) + self.assertIn(CanaryLaunchTag.HEAD_K_FULL.name, message) + self.assertIn("did not increase", message) + + def test_no_raise_when_counter_increases(self) -> None: + active_tags = (CanaryLaunchTag.HEAD_K_FULL, CanaryLaunchTag.TAIL_K_FULL) + checker = self._make_checker(active_tags=active_tags, outer_step=100) + + for value in (1, 5, 12, 100): + checker._postprocess_on_host(self._host_tensor(value)) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_per_forward.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_per_forward.py new file mode 100644 index 0000000000000000000000000000000000000000..6e9fada04412845ed5c980f9bb7126a5bb763125 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_per_forward.py @@ -0,0 +1,300 @@ +from __future__ import annotations + +import unittest +from unittest.mock import patch + +import torch + +from sglang.jit_kernel.kv_canary.consts import RealKvHashMode +from sglang.jit_kernel.kv_canary.verify import CanaryLaunchTag, VerifyPlan +from sglang.jit_kernel.kv_canary.write import WritePlan +from sglang.srt.kv_canary import endpoint as endpoint_module +from sglang.srt.kv_canary.expected_inputs import ExpectedInputs +from sglang.srt.kv_canary.runner import kernel_launcher as kernel_launcher_module +from sglang.srt.kv_canary.state import ViolationLog +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import make_buffer_group, make_forward_batch +from sglang.test.kv_canary.runner_test_base import ( + CanaryManagerTestCase, + RecordingEndpoint, + make_manager, +) + +register_cuda_ci(est_time=45, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=45, suite="extra-a-test-1-gpu-small-amd") + + +class TestManagerPerForward(CanaryManagerTestCase): + def test_per_forward_orchestrates_plan_head_tail(self) -> None: + """Verify per-forward execution launches plan, head/tail verify kernels, and write kernels in order.""" + calls: list[object] = [] + with patch.object( + kernel_launcher_module, + "launch_canary_plan_kernels", + lambda **kwargs: calls.append("plan"), + ), patch.object( + endpoint_module, + "launch_canary_verify_kernel", + lambda **kwargs: calls.append( + ("verify", kwargs["context"].kernel_kind.name) + ), + ), patch.object( + endpoint_module, + "launch_canary_write_kernel", + lambda **kwargs: calls.append( + ("write", kwargs["context"].kernel_kind.name) + ), + ): + manager = make_manager(device=self.device) + forward_batch = make_forward_batch(self.device) + with manager.with_ops_outside_graph( + single_forward_indices=[0], + maybe_inaccurate_forward_batch=forward_batch, + ): + with manager.with_active_single_forward_manager(0): + pre_ops_output = manager.pre_ops_maybe_inside_graph(forward_batch) + manager.post_ops_maybe_inside_graph(forward_batch, pre_ops_output) + + self.assertEqual(calls[0], "plan") + self.assertTrue( + any( + call[0] == "verify" and "HEAD" in call[1] + for call in calls[1:] + if isinstance(call, tuple) + ) + ) + self.assertTrue( + any( + call[0] == "verify" and "TAIL" in call[1] + for call in calls[1:] + if isinstance(call, tuple) + ) + ) + + +class TestLaunchEndpointsPerForward(CanaryManagerTestCase): + def test_launch_endpoints_per_forward_keeps_padded_token_tensors(self) -> None: + """Verify endpoint launch preserves contiguous int64 tensor shapes/values through the canonicalizer.""" + group = make_buffer_group(device=self.device) + endpoint = RecordingEndpoint(kernel_kind=CanaryLaunchTag.HEAD_K_FULL) + forward_batch = make_forward_batch(self.device, bs=1, seq_lens_list=(1,)) + forward_batch.input_ids = torch.tensor( + [101, 0, 0], dtype=torch.int64, device=self.device + ) + forward_batch.positions = torch.tensor( + [10, 0, 0], dtype=torch.int64, device=self.device + ) + forward_batch.out_cache_loc = torch.tensor( + [7, 0, 0], dtype=torch.int64, device=self.device + ) + forward_batch.num_token_non_padded_cpu = 1 + + kernel_launcher_module.launch_endpoints_per_forward( + endpoints=(endpoint,), + group=group, + tag_filter=lambda tag: True, + verify_plan=VerifyPlan.allocate(verify_capacity=1, device=self.device), + write_plan=WritePlan.allocate(write_req_capacity=1, device=self.device), + forward_batch=forward_batch, + expected_inputs=ExpectedInputs.allocate(capacity=3, device=self.device), + violation_log=ViolationLog.allocate(ring_capacity=2, device=self.device), + real_kv_hash_mode=RealKvHashMode.NONE, + enable_write_input_assert=False, + enable_verify_token_assert=False, + ) + + self.assertEqual(len(endpoint.calls), 1) + call = endpoint.calls[0] + self.assertTrue( + torch.equal( + call["input_ids"], + torch.tensor([101, 0, 0], dtype=torch.int64, device=self.device), + ) + ) + self.assertTrue( + torch.equal( + call["positions"], + torch.tensor([10, 0, 0], dtype=torch.int64, device=self.device), + ) + ) + self.assertTrue( + torch.equal( + call["out_cache_loc"], + torch.tensor([7, 0, 0], dtype=torch.int64, device=self.device), + ) + ) + + def test_launch_endpoints_per_forward_promotes_int32_boundary_tensors_to_int64( + self, + ) -> None: + """Verify int32 boundary tensors are promoted to int64 at the launch boundary.""" + group = make_buffer_group(device=self.device) + endpoint = RecordingEndpoint(kernel_kind=CanaryLaunchTag.HEAD_K_FULL) + forward_batch = make_forward_batch(self.device, bs=1, seq_lens_list=(1,)) + forward_batch.input_ids = torch.tensor( + [101], dtype=torch.int32, device=self.device + ) + forward_batch.positions = torch.tensor( + [10], dtype=torch.int32, device=self.device + ) + forward_batch.out_cache_loc = torch.tensor( + [7], dtype=torch.int32, device=self.device + ) + forward_batch.num_token_non_padded_cpu = 1 + + kernel_launcher_module.launch_endpoints_per_forward( + endpoints=(endpoint,), + group=group, + tag_filter=lambda tag: True, + verify_plan=VerifyPlan.allocate(verify_capacity=1, device=self.device), + write_plan=WritePlan.allocate(write_req_capacity=1, device=self.device), + forward_batch=forward_batch, + expected_inputs=ExpectedInputs.allocate(capacity=1, device=self.device), + violation_log=ViolationLog.allocate(ring_capacity=2, device=self.device), + real_kv_hash_mode=RealKvHashMode.NONE, + enable_write_input_assert=False, + enable_verify_token_assert=False, + ) + + self.assertEqual(len(endpoint.calls), 1) + call = endpoint.calls[0] + self.assertEqual(call["input_ids"].dtype, torch.int64) + self.assertEqual(call["positions"].dtype, torch.int64) + self.assertEqual(call["out_cache_loc"].dtype, torch.int64) + + def test_launch_endpoints_per_forward_propagates_enable_verify_token_assert_true( + self, + ) -> None: + """Verify enable_verify_token_assert=True is plumbed through to the endpoint kwargs.""" + group = make_buffer_group(device=self.device) + endpoint = RecordingEndpoint(kernel_kind=CanaryLaunchTag.HEAD_K_FULL) + forward_batch = make_forward_batch(self.device, bs=1, seq_lens_list=(1,)) + forward_batch.input_ids = torch.tensor( + [101, 0, 0], dtype=torch.int64, device=self.device + ) + forward_batch.positions = torch.tensor( + [10, 0, 0], dtype=torch.int64, device=self.device + ) + forward_batch.out_cache_loc = torch.tensor( + [7, 0, 0], dtype=torch.int64, device=self.device + ) + forward_batch.num_token_non_padded_cpu = 1 + + kernel_launcher_module.launch_endpoints_per_forward( + endpoints=(endpoint,), + group=group, + tag_filter=lambda tag: True, + verify_plan=VerifyPlan.allocate(verify_capacity=1, device=self.device), + write_plan=WritePlan.allocate(write_req_capacity=1, device=self.device), + forward_batch=forward_batch, + expected_inputs=ExpectedInputs.allocate(capacity=3, device=self.device), + violation_log=ViolationLog.allocate(ring_capacity=2, device=self.device), + real_kv_hash_mode=RealKvHashMode.NONE, + enable_write_input_assert=False, + enable_verify_token_assert=True, + ) + + self.assertEqual(len(endpoint.calls), 1) + call = endpoint.calls[0] + self.assertEqual(call["enable_verify_token_assert"], True) + + def test_launch_endpoints_per_forward_materializes_strided_boundary_tensors( + self, + ) -> None: + """Verify non-contiguous boundary views are materialized contiguous at launch.""" + group = make_buffer_group(device=self.device) + endpoint = RecordingEndpoint(kernel_kind=CanaryLaunchTag.HEAD_K_FULL) + forward_batch = make_forward_batch(self.device, bs=1, seq_lens_list=(1,)) + forward_batch.input_ids = torch.tensor( + [[101, 102]], dtype=torch.int64, device=self.device + )[:, 0] + forward_batch.positions = torch.tensor( + [[10, 11]], dtype=torch.int64, device=self.device + )[:, 0] + forward_batch.out_cache_loc = torch.tensor( + [[7, 8]], dtype=torch.int64, device=self.device + )[:, 0] + forward_batch.num_token_non_padded_cpu = 1 + + kernel_launcher_module.launch_endpoints_per_forward( + endpoints=(endpoint,), + group=group, + tag_filter=lambda tag: True, + verify_plan=VerifyPlan.allocate(verify_capacity=1, device=self.device), + write_plan=WritePlan.allocate(write_req_capacity=1, device=self.device), + forward_batch=forward_batch, + expected_inputs=ExpectedInputs.allocate(capacity=1, device=self.device), + violation_log=ViolationLog.allocate(ring_capacity=2, device=self.device), + real_kv_hash_mode=RealKvHashMode.NONE, + enable_write_input_assert=False, + enable_verify_token_assert=False, + ) + + self.assertEqual(len(endpoint.calls), 1) + call = endpoint.calls[0] + self.assertTrue(call["input_ids"].is_contiguous()) + self.assertTrue(call["positions"].is_contiguous()) + self.assertTrue(call["out_cache_loc"].is_contiguous()) + + +class TestManagerBeforeForward(CanaryManagerTestCase): + def test_before_forward_does_not_throw_on_oversized_prefix_sum(self) -> None: + """Verify oversized prefix sums are handled without host-side errors.""" + manager = make_manager(device=self.device, per_forward_verify_capacity=4) + forward_batch = make_forward_batch(self.device, bs=2, seq_lens_list=(5, 5)) + _drive_one_cycle(manager, forward_batch) + + def test_before_forward_passes_when_sum_prefix_lens_fits(self) -> None: + """Verify prefix sums within capacity pass before-forward handling.""" + manager = make_manager(device=self.device, per_forward_verify_capacity=16) + forward_batch = make_forward_batch(self.device, bs=2, seq_lens_list=(5, 5)) + _drive_one_cycle(manager, forward_batch) + + +def _drive_one_cycle(manager, forward_batch) -> None: + with manager.with_ops_outside_graph( + single_forward_indices=[0], + maybe_inaccurate_forward_batch=forward_batch, + ): + with manager.with_active_single_forward_manager(0): + pre_ops_output = manager.pre_ops_maybe_inside_graph(forward_batch) + manager.post_ops_maybe_inside_graph(forward_batch, pre_ops_output) + + +class TestCanaryManagerActiveSingleForwardManagerDispatch(CanaryManagerTestCase): + def test_pre_ops_maybe_inside_graph_dispatches_to_bracketed_sfm( + self, + ) -> None: + """Verify the dispatcher routes phase 2 to the bracketed SingleForwardManager.""" + manager = make_manager(device=self.device, speculative_num_steps=3) + forward_batch = make_forward_batch(self.device) + target_sfm = manager._single_forward_managers[1] + observed: list[object] = [] + original_phase_2 = target_sfm.pre_ops_maybe_inside_graph + + def _record(fb): + observed.append(fb) + return original_phase_2(fb) + + target_sfm.pre_ops_maybe_inside_graph = _record + manager._single_forward_managers[0].pre_ops_outside_graph( + maybe_inaccurate_forward_batch=forward_batch + ) + manager._single_forward_managers[1].pre_ops_outside_graph( + maybe_inaccurate_forward_batch=forward_batch + ) + with manager.with_active_single_forward_manager(1): + manager.pre_ops_maybe_inside_graph(forward_batch) + self.assertEqual(observed, [forward_batch]) + + def test_pre_ops_maybe_inside_graph_asserts_outside_bracket( + self, + ) -> None: + manager = make_manager(device=self.device) + forward_batch = make_forward_batch(self.device) + with self.assertRaises(AssertionError): + manager.pre_ops_maybe_inside_graph(forward_batch) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_swa_divergence.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_swa_divergence.py new file mode 100644 index 0000000000000000000000000000000000000000..d3366d14bd1afb9b512e4f1172455a58e4490cb9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_swa_divergence.py @@ -0,0 +1,466 @@ +from __future__ import annotations + +import logging +import unittest +from types import SimpleNamespace + +import torch + +from sglang.jit_kernel.kv_canary.verify import VerifyPlan +from sglang.srt.environ import envs +from sglang.srt.kv_canary.buffer_group import PoolKind +from sglang.srt.kv_canary.runner import swa_divergence as swa_div_module +from sglang.srt.kv_canary.runner.swa_divergence import ( + SwaDivergenceLog, + SwaDivergenceReporter, + compute_swa_full_idx_divergence, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import make_buffer_group +from sglang.test.kv_canary.runner_test_base import CanaryManagerTestCase, make_manager +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=45, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=45, suite="extra-a-test-1-gpu-small-amd") + +_DEVICE = torch.device("cuda") + +_EMPTY_FORWARD_BATCH = SimpleNamespace( + req_pool_indices=torch.empty(0, dtype=torch.int64, device=_DEVICE), + seq_lens=torch.empty(0, dtype=torch.int64, device=_DEVICE), +) + + +def _make_verify_plan(value: int) -> VerifyPlan: + plan = VerifyPlan.allocate(verify_capacity=4, device=_DEVICE) + plan.verify_num_valid.copy_(torch.tensor([value], dtype=torch.int32)) + return plan + + +def _make_allocator_stub(mapping: torch.Tensor) -> SimpleNamespace: + return SimpleNamespace(full_to_swa_index_mapping=mapping) + + +def _make_req_to_token_pool_stub(req_to_token: torch.Tensor) -> SimpleNamespace: + return SimpleNamespace(req_to_token=req_to_token) + + +def _make_identity_mapping(size: int) -> torch.Tensor: + return torch.arange(size, dtype=torch.int64, device=_DEVICE) + + +def _make_identity_req_to_token(num_reqs: int, max_seq_len: int) -> torch.Tensor: + base = torch.arange(num_reqs * max_seq_len, dtype=torch.int64, device=_DEVICE) + return base.view(num_reqs, max_seq_len) + + +def _make_forward_batch( + *, req_pool_indices: torch.Tensor, seq_lens: torch.Tensor +) -> SimpleNamespace: + return SimpleNamespace(req_pool_indices=req_pool_indices, seq_lens=seq_lens) + + +def _parse_swa_divergence_line(line: str) -> SwaDivergenceLog: + parsed = SwaDivergenceLog.parse(line) + if parsed is None: + raise AssertionError(f"line does not match swa_divergence format: {line!r}") + return parsed + + +def _run_compute( + *, + swa_allocator: SimpleNamespace, + req_to_token_pool: SimpleNamespace, + forward_batch: SimpleNamespace, +) -> int: + count = compute_swa_full_idx_divergence( + swa_allocator=swa_allocator, + req_to_token_pool=req_to_token_pool, + maybe_inaccurate_forward_batch=forward_batch, + ) + return int(count.item()) + + +class TestSwaDivergenceReporter(CustomTestCase): + def test_swa_divergence_log_emitted(self) -> None: + d2h_stream = torch.cuda.Stream(device=_DEVICE) + stats = SwaDivergenceReporter( + device=_DEVICE, + d2h_stream=d2h_stream, + interval=10, + swa_allocator=None, + req_to_token_pool=None, + ) + # First 3 forwards stay below the interval trigger (1, 2, 3 % 10 != 0) so + # step() just bumps forward_ct and stages nothing. + for forward_idx in range(3): + stats.observe_after_invoke_plan( + group=make_buffer_group( + device=_DEVICE, kind=PoolKind.FULL, has_v=False, num_slots=1 + ), + verify_plan=_make_verify_plan(10), + ) + stats.observe_after_invoke_plan( + group=make_buffer_group( + device=_DEVICE, kind=PoolKind.SWA, has_v=False, num_slots=1 + ), + verify_plan=_make_verify_plan(3), + ) + stats.step( + outer_step_counter=forward_idx + 1, + maybe_inaccurate_forward_batch=_EMPTY_FORWARD_BATCH, + ) + # 4th forward lands on outer_step_counter=10 = interval, so compute_on_device + # snapshots {forward_ct:4, verify_full:40, verify_swa:12} into the dict and + # the staged future hangs onto it. forward_ct is now 4. + stats.observe_after_invoke_plan( + group=make_buffer_group( + device=_DEVICE, kind=PoolKind.FULL, has_v=False, num_slots=1 + ), + verify_plan=_make_verify_plan(10), + ) + stats.observe_after_invoke_plan( + group=make_buffer_group( + device=_DEVICE, kind=PoolKind.SWA, has_v=False, num_slots=1 + ), + verify_plan=_make_verify_plan(3), + ) + stats.step( + outer_step_counter=10, maybe_inaccurate_forward_batch=_EMPTY_FORWARD_BATCH + ) + + # 5th step drains the previous stage and emits the log; forward_ct is now 5 + # but the staged dict still carries the snapshot forward_ct=4 from step 4. + with self.assertLogs( + swa_div_module.logger.name, level=logging.INFO + ) as captured: + stats.step( + outer_step_counter=11, + maybe_inaccurate_forward_batch=_EMPTY_FORWARD_BATCH, + ) + + lines = [ + line for line in captured.output if SwaDivergenceLog.parse(line) is not None + ] + self.assertEqual(len(lines), 1, lines) + fields = _parse_swa_divergence_line(lines[0]) + self.assertEqual(fields.forward_ct, 4) + self.assertEqual(fields.verify_full, 40) + self.assertEqual(fields.verify_swa, 12) + self.assertEqual(fields.swa_full_idx_divergence, 0) + + def test_swa_divergence_counts_monotonic_increasing(self) -> None: + d2h_stream = torch.cuda.Stream(device=_DEVICE) + stats = SwaDivergenceReporter( + device=_DEVICE, + d2h_stream=d2h_stream, + interval=10, + swa_allocator=None, + req_to_token_pool=None, + ) + + snapshots: list[SwaDivergenceLog] = [] + + def _take_snapshot(stage_step: int, drain_step: int) -> None: + # Stage the dict at the interval-aligned step (no log emitted yet, + # DelayedDeviceHostHandler still has nothing to drain), then call + # step() again at the next counter to drain and emit the log. + stats.step( + outer_step_counter=stage_step, + maybe_inaccurate_forward_batch=_EMPTY_FORWARD_BATCH, + ) + with self.assertLogs( + swa_div_module.logger.name, level=logging.INFO + ) as captured: + stats.step( + outer_step_counter=drain_step, + maybe_inaccurate_forward_batch=_EMPTY_FORWARD_BATCH, + ) + matching = [ + line + for line in captured.output + if SwaDivergenceLog.parse(line) is not None + ] + self.assertTrue(matching, captured.output) + snapshots.append(_parse_swa_divergence_line(matching[-1])) + + for batch in range(3): + for _ in range(5): + stats.observe_after_invoke_plan( + group=make_buffer_group( + device=_DEVICE, kind=PoolKind.FULL, has_v=False, num_slots=1 + ), + verify_plan=_make_verify_plan(7), + ) + stats.observe_after_invoke_plan( + group=make_buffer_group( + device=_DEVICE, kind=PoolKind.SWA, has_v=False, num_slots=1 + ), + verify_plan=_make_verify_plan(2), + ) + stage_step = 10 + 20 * batch + _take_snapshot(stage_step=stage_step, drain_step=stage_step + 1) + + for idx in range(1, len(snapshots)): + self.assertGreaterEqual( + snapshots[idx].verify_full, snapshots[idx - 1].verify_full + ) + self.assertGreaterEqual( + snapshots[idx].verify_swa, snapshots[idx - 1].verify_swa + ) + + +class TestSwaFullIdxDivergenceCompute(CustomTestCase): + def test_compute_returns_zero_when_empty_batch(self) -> None: + mapping = _make_identity_mapping(size=64) + req_to_token = _make_identity_req_to_token(num_reqs=4, max_seq_len=16) + + forward_batch = _make_forward_batch( + req_pool_indices=torch.empty(0, dtype=torch.int64, device=_DEVICE), + seq_lens=torch.empty(0, dtype=torch.int64, device=_DEVICE), + ) + + self.assertEqual( + _run_compute( + swa_allocator=_make_allocator_stub(mapping), + req_to_token_pool=_make_req_to_token_pool_stub(req_to_token), + forward_batch=forward_batch, + ), + 0, + ) + + def test_compute_returns_zero_when_all_identity(self) -> None: + mapping = _make_identity_mapping(size=64) + req_to_token = _make_identity_req_to_token(num_reqs=4, max_seq_len=16) + + forward_batch = _make_forward_batch( + req_pool_indices=torch.tensor([0, 2], dtype=torch.int64, device=_DEVICE), + seq_lens=torch.tensor([8, 5], dtype=torch.int64, device=_DEVICE), + ) + + self.assertEqual( + _run_compute( + swa_allocator=_make_allocator_stub(mapping), + req_to_token_pool=_make_req_to_token_pool_stub(req_to_token), + forward_batch=forward_batch, + ), + 0, + ) + + def test_compute_counts_swa_full_idx_divergence_in_live_range(self) -> None: + mapping = _make_identity_mapping(size=64) + req_to_token = _make_identity_req_to_token(num_reqs=4, max_seq_len=16) + + mapping[0] = 50 + mapping[1] = 51 + mapping[17] = 60 + + forward_batch = _make_forward_batch( + req_pool_indices=torch.tensor([0, 1], dtype=torch.int64, device=_DEVICE), + seq_lens=torch.tensor([8, 8], dtype=torch.int64, device=_DEVICE), + ) + + self.assertEqual( + _run_compute( + swa_allocator=_make_allocator_stub(mapping), + req_to_token_pool=_make_req_to_token_pool_stub(req_to_token), + forward_batch=forward_batch, + ), + 3, + ) + + def test_compute_ignores_swa_mapping_zero(self) -> None: + # SWATokenToKVPoolAllocator writes 0 into full_to_swa_index_mapping for + # FULL pool slots beyond the sliding window. Those entries are expected, + # not real divergence, so the count must skip them. + mapping = _make_identity_mapping(size=64) + req_to_token = _make_identity_req_to_token(num_reqs=4, max_seq_len=16) + + mapping[3] = 0 + mapping[5] = 0 + mapping[7] = 42 + + forward_batch = _make_forward_batch( + req_pool_indices=torch.tensor([0], dtype=torch.int64, device=_DEVICE), + seq_lens=torch.tensor([8], dtype=torch.int64, device=_DEVICE), + ) + + self.assertEqual( + _run_compute( + swa_allocator=_make_allocator_stub(mapping), + req_to_token_pool=_make_req_to_token_pool_stub(req_to_token), + forward_batch=forward_batch, + ), + 1, + ) + + def test_compute_ignores_writes_outside_seq_lens(self) -> None: + mapping = _make_identity_mapping(size=128) + req_to_token = _make_identity_req_to_token(num_reqs=4, max_seq_len=32) + + mapping[20] = 99 + mapping[28] = 77 + + forward_batch = _make_forward_batch( + req_pool_indices=torch.tensor([0], dtype=torch.int64, device=_DEVICE), + seq_lens=torch.tensor([10], dtype=torch.int64, device=_DEVICE), + ) + + self.assertEqual( + _run_compute( + swa_allocator=_make_allocator_stub(mapping), + req_to_token_pool=_make_req_to_token_pool_stub(req_to_token), + forward_batch=forward_batch, + ), + 0, + ) + + def test_compute_reflects_current_forward_batch(self) -> None: + mapping = _make_identity_mapping(size=64) + req_to_token = _make_identity_req_to_token(num_reqs=4, max_seq_len=16) + + mapping[0] = 41 + mapping[1] = 42 + mapping[32] = 99 + mapping[33] = 100 + + fb_req0 = _make_forward_batch( + req_pool_indices=torch.tensor([0], dtype=torch.int64, device=_DEVICE), + seq_lens=torch.tensor([4], dtype=torch.int64, device=_DEVICE), + ) + fb_req2 = _make_forward_batch( + req_pool_indices=torch.tensor([2], dtype=torch.int64, device=_DEVICE), + seq_lens=torch.tensor([4], dtype=torch.int64, device=_DEVICE), + ) + + self.assertEqual( + _run_compute( + swa_allocator=_make_allocator_stub(mapping), + req_to_token_pool=_make_req_to_token_pool_stub(req_to_token), + forward_batch=fb_req0, + ), + 2, + ) + self.assertEqual( + _run_compute( + swa_allocator=_make_allocator_stub(mapping), + req_to_token_pool=_make_req_to_token_pool_stub(req_to_token), + forward_batch=fb_req2, + ), + 2, + ) + + +class TestSwaDivergenceReporterWithCompute(CustomTestCase): + def test_swa_divergence_report_emits_swa_full_idx_divergence_from_compute( + self, + ) -> None: + mapping = _make_identity_mapping(size=64) + req_to_token = _make_identity_req_to_token(num_reqs=4, max_seq_len=16) + + mapping[0] = 50 + mapping[1] = 51 + mapping[2] = 52 + + forward_batch = _make_forward_batch( + req_pool_indices=torch.tensor([0], dtype=torch.int64, device=_DEVICE), + seq_lens=torch.tensor([8], dtype=torch.int64, device=_DEVICE), + ) + + swa_allocator = _make_allocator_stub(mapping) + req_to_token_pool = _make_req_to_token_pool_stub(req_to_token) + d2h_stream = torch.cuda.Stream(device=_DEVICE) + stats = SwaDivergenceReporter( + device=_DEVICE, + d2h_stream=d2h_stream, + interval=10, + swa_allocator=swa_allocator, + req_to_token_pool=req_to_token_pool, + ) + stats.observe_after_invoke_plan( + group=make_buffer_group( + device=_DEVICE, kind=PoolKind.FULL, has_v=False, num_slots=1 + ), + verify_plan=_make_verify_plan(11), + ) + stats.observe_after_invoke_plan( + group=make_buffer_group( + device=_DEVICE, kind=PoolKind.SWA, has_v=False, num_slots=1 + ), + verify_plan=_make_verify_plan(3), + ) + + # Stage at the interval-aligned step, then drain on the next step so the + # DelayedDeviceHostHandler has a pending future to postprocess. + stats.step(outer_step_counter=10, maybe_inaccurate_forward_batch=forward_batch) + with self.assertLogs( + swa_div_module.logger.name, level=logging.INFO + ) as captured: + stats.step( + outer_step_counter=11, maybe_inaccurate_forward_batch=forward_batch + ) + + matching = [ + line for line in captured.output if SwaDivergenceLog.parse(line) is not None + ] + self.assertEqual(len(matching), 1, matching) + parsed = SwaDivergenceLog.parse(matching[0]) + assert parsed is not None + self.assertEqual(parsed.swa_full_idx_divergence, 3) + self.assertEqual(parsed.verify_full, 11) + self.assertEqual(parsed.verify_swa, 3) + + +class TestSwaDivergenceLogFindAll(CustomTestCase): + def test_find_all_returns_every_sample_in_order(self) -> None: + text = "\n".join( + SwaDivergenceLog( + forward_ct=ct, + verify_full=100 * ct, + verify_swa=10 * ct, + swa_full_idx_divergence=ct, + swa_out_of_window_tokens=0, + ).format() + for ct in (20, 40, 60) + ) + parsed = SwaDivergenceLog.find_all(text) + self.assertEqual([p.forward_ct for p, _ in parsed], [20, 40, 60]) + + def test_find_all_peak_survives_trailing_zero_sample(self) -> None: + text = "\n".join( + SwaDivergenceLog( + forward_ct=ct, + verify_full=1, + verify_swa=0, + swa_full_idx_divergence=1, + swa_out_of_window_tokens=oow, + ).format() + for ct, oow in ((20, 0), (40, 4080), (60, 0)) + ) + parsed = SwaDivergenceLog.find_all(text) + self.assertEqual(max(p.swa_out_of_window_tokens for p, _ in parsed), 4080) + self.assertEqual(parsed[-1][0].swa_out_of_window_tokens, 0) + + def test_find_all_returns_empty_list_when_no_lines(self) -> None: + self.assertEqual(SwaDivergenceLog.find_all("nothing here\n"), []) + + +class TestCanaryManagerSwaDivergenceWiring(CanaryManagerTestCase): + def test_swa_divergence_report_is_none_when_env_disabled(self) -> None: + with envs.SGLANG_KV_CANARY_SWA_DIVERGENCE_STATS_INTERVAL.override( + 0 + ), envs.SGLANG_KV_CANARY_PERTURB_TARGET_GROUP.override("full"): + manager = make_manager(device=self.device) + self.assertIsNone(manager._swa_divergence_report) + + def test_swa_divergence_report_present_when_env_enabled(self) -> None: + with envs.SGLANG_KV_CANARY_SWA_DIVERGENCE_STATS_INTERVAL.override( + 20 + ), envs.SGLANG_KV_CANARY_PERTURB_TARGET_GROUP.override("full"): + manager = make_manager(device=self.device) + self.assertIsNotNone(manager._swa_divergence_report) + self.assertIsInstance(manager._swa_divergence_report, SwaDivergenceReporter) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_sweep.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..71f5b04faa7031e7b946b2844e720a04d673c9d3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_runner_sweep.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +import unittest +from unittest.mock import patch + +from sglang.srt.kv_canary import endpoint as endpoint_module +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import ( + make_forward_batch, + make_radix_cache, + make_req_to_token_pool, +) +from sglang.test.kv_canary.runner_test_base import ( + CanaryManagerTestCase, + make_config, + make_manager, +) + +register_cuda_ci(est_time=45, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=45, suite="extra-a-test-1-gpu-small-amd") + + +def _run_one_cycle(manager, forward_batch) -> None: + with manager.with_ops_outside_graph( + single_forward_indices=[0], + maybe_inaccurate_forward_batch=forward_batch, + ): + with manager.with_active_single_forward_manager(0): + pre_ops_output = manager.pre_ops_maybe_inside_graph(forward_batch) + manager.post_ops_maybe_inside_graph(forward_batch, pre_ops_output) + + +class TestSelfUnitManagerSweep(CanaryManagerTestCase): + def test_sweep_every_n_cadence(self) -> None: + """Verify sweep execution follows the configured step cadence.""" + config = make_config(sweep_interval=4) + manager = make_manager(device=self.device, config=config) + forward_batch = make_forward_batch(self.device) + + sweep_calls: list[int] = [] + real_maybe = manager._sweep_orchestrator.maybe_run_sweep + + def _spy() -> None: + before = manager._sweep_orchestrator._last_sweep_step + real_maybe() + if manager._sweep_orchestrator._last_sweep_step != before: + sweep_calls.append(manager._outer_step_counter) + + with patch.object(manager._sweep_orchestrator, "maybe_run_sweep", _spy): + for _ in range(12): + _run_one_cycle(manager, forward_batch) + self.assertEqual(sweep_calls, [0, 4, 8]) + + def test_sweep_path_launches_sweep_kernels(self) -> None: + """Verify sweep paths launch sweep verify kernels.""" + config = make_config(sweep_interval=1) + manager = make_manager(device=self.device, config=config) + forward_batch = make_forward_batch(self.device) + manager._single_forward_managers[0].pre_ops_outside_graph( + maybe_inaccurate_forward_batch=forward_batch + ) + with manager.with_active_single_forward_manager(0): + manager.pre_ops_maybe_inside_graph(forward_batch) + + cache = make_radix_cache([[], [10, 11, 12]], device=self.device) + cache.req_to_token_pool = make_req_to_token_pool(self.device) + manager.attach_radix_cache(cache) + + sweep_kernel_kinds: list[str] = [] + with patch.object( + endpoint_module, + "launch_canary_verify_kernel", + lambda **kwargs: sweep_kernel_kinds.append( + kwargs["context"].kernel_kind.name + ), + ): + manager._sweep_orchestrator.maybe_run_sweep() + self.assertTrue(any("SWEEP" in kind for kind in sweep_kernel_kinds)) + + def test_sweep_allocates_verify_plan_from_walker_output(self) -> None: + """Verify sweep planning sizes the verify plan from walker output.""" + manager = make_manager(device=self.device) + cache = make_radix_cache([[], [10, 11], [12, 13, 14]], device=self.device) + cache.req_to_token_pool = make_req_to_token_pool(self.device) + manager.attach_radix_cache(cache) + + valid_counts: list[int] = [] + with patch.object( + endpoint_module, + "launch_canary_verify_kernel", + lambda **kwargs: valid_counts.append( + int(kwargs["plan"].verify_num_valid.item()) + ), + ): + manager._sweep_orchestrator.maybe_run_sweep() + self.assertTrue(all(count == 5 for count in valid_counts)) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_sweep_plan_builder.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_sweep_plan_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6e3f95dcdeae516e0a1ff84c0d2c73f4c2a622 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_sweep_plan_builder.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import unittest + +import torch + +from sglang.srt.kv_canary.sweep_plan_builder import build_verify_plan_radix_sweep +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import ( + DEFAULT_DEVICE, + make_radix_cache, + make_req_to_token_pool, +) +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=30, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=30, suite="extra-a-test-1-gpu-small-amd") + + +class TestSelfUnitSweepPlanBuilder(CustomTestCase): + def setUp(self) -> None: + self.device = DEFAULT_DEVICE + + def test_build_verify_plan_radix_sweep(self) -> None: + """Verify radix sweep verify plans include cached slot chains.""" + empty_cache = make_radix_cache([[]], device=self.device) + empty_cache.req_to_token_pool = make_req_to_token_pool(self.device) + empty_out = build_verify_plan_radix_sweep( + radix_cache=empty_cache, + swa_window_size=0, + full_to_swa_index_mapping=None, + ) + self.assertEqual(int(empty_out.verify_num_valid.item()), 0) + + cache = make_radix_cache([[], [100, 101, 102]], device=self.device) + cache.req_to_token_pool = make_req_to_token_pool(self.device) + out = build_verify_plan_radix_sweep( + radix_cache=cache, + swa_window_size=0, + full_to_swa_index_mapping=None, + ) + self.assertEqual(int(out.verify_num_valid.item()), 3) + self.assertEqual(out.verify_slot_indices.dtype, torch.int64) + self.assertEqual(out.verify_expected_positions.dtype, torch.int64) + self.assertEqual(out.verify_prev_slot_indices.dtype, torch.int64) + self.assertEqual(out.verify_slot_indices[:3].tolist(), [100, 101, 102]) + self.assertEqual(out.verify_expected_positions[:3].tolist(), [0, 1, 2]) + self.assertEqual(out.verify_prev_slot_indices[:3].tolist(), [-1, 100, 101]) + + def test_radix_held_slot_still_swept(self) -> None: + """Verify held radix slots are still included in sweep plans.""" + cache = make_radix_cache([[], [42, 43, 44]], device=self.device) + cache.req_to_token_pool = make_req_to_token_pool(self.device) + out = build_verify_plan_radix_sweep( + radix_cache=cache, + swa_window_size=0, + full_to_swa_index_mapping=None, + ) + num_valid = int(out.verify_num_valid.item()) + self.assertEqual(num_valid, 3) + self.assertEqual( + set(out.verify_slot_indices[:num_valid].tolist()), {42, 43, 44} + ) + + def test_truly_free_slot_not_swept(self) -> None: + """Verify free radix slots are excluded from sweep plans.""" + empty_cache = make_radix_cache([[]], device=self.device) + empty_cache.req_to_token_pool = make_req_to_token_pool(self.device) + out = build_verify_plan_radix_sweep( + radix_cache=empty_cache, + swa_window_size=0, + full_to_swa_index_mapping=None, + ) + self.assertEqual(int(out.verify_num_valid.item()), 0) + + def test_swa_translate_preserves_evicted_as_padding_sentinel(self) -> None: + """Evicted (LUT=0) slots stay in the plan as the padding sentinel; the kernel does the skipping.""" + cache = make_radix_cache([[], [100, 101, 102]], device=self.device) + cache.req_to_token_pool = make_req_to_token_pool(self.device) + + lut = torch.zeros(200, dtype=torch.int64, device=self.device) + lut[100] = 500 + lut[101] = 0 + lut[102] = 502 + + out = build_verify_plan_radix_sweep( + radix_cache=cache, + swa_window_size=128, + full_to_swa_index_mapping=lut, + ) + num_valid = int(out.verify_num_valid.item()) + self.assertEqual(num_valid, 3) + self.assertEqual(out.verify_slot_indices[:num_valid].tolist(), [500, 0, 502]) + self.assertEqual( + out.verify_prev_slot_indices[:num_valid].tolist(), [-1, 500, 0] + ) + self.assertEqual(out.verify_expected_positions[:num_valid].tolist(), [0, 1, 2]) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_token_oracle.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_token_oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..045d3e6e440edae4889cca42a0b38d95717cd944 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_token_oracle.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import unittest +from types import SimpleNamespace + +import torch + +from sglang.srt.kv_canary.expected_inputs import ExpectedInputs +from sglang.srt.kv_canary.token_oracle.oracle import HashOracle +from sglang.srt.kv_canary.token_oracle.oracle_manager import TokenOracleManager +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.fixtures import DEFAULT_DEVICE +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=1, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=1, suite="extra-a-test-1-gpu-small-amd") + + +class TestTokenOracleManager(CustomTestCase): + def setUp(self) -> None: + self.device = DEFAULT_DEVICE + + def test_fill_expected_inputs_expands_draft_extend_generalized_req_ids_per_token( + self, + ) -> None: + """Verify EAGLE draft extend maps one request row to every draft token.""" + forward_batch = SimpleNamespace( + forward_mode=ForwardMode.DRAFT_EXTEND_V2, + spec_info=SimpleNamespace(num_tokens_per_req=4), + rids_int=torch.tensor([3, 7], dtype=torch.int64, device=self.device), + bootstrap_room_ids_int=None, + input_ids=torch.tensor( + [101, 102, 103, 104, 201, 202, 203, 204], + dtype=torch.int64, + device=self.device, + ), + positions=torch.arange(8, dtype=torch.int64, device=self.device), + extend_seq_lens=torch.tensor([1, 1], dtype=torch.int64, device=self.device), + ) + expected_inputs = ExpectedInputs.allocate(capacity=8, device=self.device) + manager = TokenOracleManager(oracle=HashOracle(vocab_size=32000)) + + manager.fill_expected_inputs( + forward_batch=forward_batch, + expected_inputs_out=expected_inputs, + ) + + # draft-extend-v2 is not an extend mode, so fill_expected_inputs records + # deterministic oracle tokens (not input_ids). The req row [3, 7] expands + # to num_tokens_per_req=4 draft tokens each -> one row per draft token. + expected_generalized_req_ids = torch.tensor( + [3, 3, 3, 3, 7, 7, 7, 7], dtype=torch.int64, device=self.device + ) + expected_tokens = manager.oracle.expected_tokens( + generalized_req_ids=expected_generalized_req_ids, + positions=forward_batch.positions.to(torch.int64), + ) + self.assertTrue( + torch.equal(expected_inputs.tokens[:8], expected_tokens.to(torch.int64)) + ) + self.assertTrue( + torch.equal(expected_inputs.positions[:8], forward_batch.positions) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_violation.py b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_violation.py new file mode 100644 index 0000000000000000000000000000000000000000..a20356cfb26146e161a802b3285d5ca4b703a489 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/kv_canary/test_self_unit_violation.py @@ -0,0 +1,366 @@ +from __future__ import annotations + +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import torch + +from sglang.jit_kernel.kv_canary import consts +from sglang.jit_kernel.kv_canary.consts import FailReason +from sglang.jit_kernel.kv_canary.verify import CanaryLaunchTag +from sglang.srt.kv_canary.config import CanaryMode +from sglang.srt.kv_canary.runner import violation_reporter as violation_reporter_module +from sglang.srt.kv_canary.runner.violation_reporter import ( + ViolationReporter, + _format_violation, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=5, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=5, suite="extra-a-test-1-gpu-small-amd") + + +def _make_row( + *, + kernel_kind: CanaryLaunchTag = CanaryLaunchTag.HEAD_K_FULL, + slot_idx: int = 17, + position: int = 42, + stored_token: int = 111, + expected_token: int = 0, + stored_chain_hash: int = 0, + expected_aux: int = 0, + fail_reason_bits: int = 0, +) -> list[int]: + row = [0] * consts.VIOLATION_FIELDS + row[consts.VIOLATION_FIELD_KERNEL_KIND] = int(kernel_kind) + row[consts.VIOLATION_FIELD_SLOT_IDX] = slot_idx + row[consts.VIOLATION_FIELD_POSITION] = position + row[consts.VIOLATION_FIELD_STORED_TOKEN] = stored_token + row[consts.VIOLATION_FIELD_EXPECTED_TOKEN] = expected_token + row[consts.VIOLATION_FIELD_STORED_CHAIN_HASH] = stored_chain_hash + row[consts.VIOLATION_FIELD_EXPECTED_AUX] = expected_aux + row[consts.VIOLATION_FIELD_FAIL_REASON_BITS] = fail_reason_bits + return row + + +class TestViolationReporter(CustomTestCase): + def test_format_violation_verify_path_labels_each_bit(self) -> None: + """Verify verify-path violations render each fail-reason bit.""" + row = _make_row( + stored_chain_hash=0x1111111111111111, + expected_aux=0x2222222222222222, + fail_reason_bits=int( + FailReason.VERIFY_CHAIN_HASH_MISMATCH + | FailReason.VERIFY_POSITION_MISMATCH + | FailReason.VERIFY_REAL_KV_HASH_MISMATCH + ), + ) + out = _format_violation( + row=row, total=1, ring_overflow=False, step_when_pumped=7 + ) + self.assertEqual( + out, + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=verify_chain_hash+verify_position+verify_real_kv_hash " + "slot_idx=17 position=42 stored_token=111 expected_token=0 stored_chain_hash=0x1111111111111111 " + "expected_aux=0x2222222222222222\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=17, position=42)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: verify_chain_hash verify_position verify_real_kv_hash\n" + " stored: token_id=111 position=42 prev_hash=0x1111111111111111\n" + " expected: prev_hash=0x2222222222222222\n" + " total_violations=1 ring_overflow=False step_when_pumped=7", + ) + + def test_format_violation_write_token_mismatch_labels_and_position(self) -> None: + """Verify write-token violations render token and position details.""" + row = _make_row( + position=42, + stored_token=999, + expected_token=888, + stored_chain_hash=0xDEADBEEFCAFEBABE, + expected_aux=43, + fail_reason_bits=int(FailReason.WRITE_TOKEN_MISMATCH), + ) + out = _format_violation( + row=row, total=1, ring_overflow=False, step_when_pumped=0 + ) + self.assertEqual( + out, + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=write_token slot_idx=17 position=42 " + "stored_token=999 expected_token=888 stored_chain_hash=0xdeadbeefcafebabe " + "expected_aux=0x000000000000002b\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=17, position=42)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: write_token\n" + " actual: token_id=999 position=42 prev_hash=0xdeadbeefcafebabe\n" + " expected: token_id=888 position=43\n" + " total_violations=1 ring_overflow=False step_when_pumped=0", + ) + + def test_format_violation_write_position_mismatch_uses_expected_aux_as_position( + self, + ) -> None: + """Verify write-position violations render expected_aux as a position.""" + row = _make_row( + position=42, + stored_token=111, + expected_token=111, + expected_aux=99, + fail_reason_bits=int(FailReason.WRITE_POSITION_MISMATCH), + ) + out = _format_violation( + row=row, total=1, ring_overflow=False, step_when_pumped=0 + ) + self.assertEqual( + out, + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=write_position slot_idx=17 position=42 " + "stored_token=111 expected_token=111 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000063\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=17, position=42)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: write_position\n" + " actual: token_id=111 position=42 prev_hash=0x0000000000000000\n" + " expected: token_id=111 position=99\n" + " total_violations=1 ring_overflow=False step_when_pumped=0", + ) + + def test_format_violation_combined_write_bits_render_both_labels(self) -> None: + """Verify combined write violation bits render both labels.""" + row = _make_row( + fail_reason_bits=int( + FailReason.WRITE_TOKEN_MISMATCH | FailReason.WRITE_POSITION_MISMATCH + ), + ) + out = _format_violation( + row=row, total=1, ring_overflow=False, step_when_pumped=0 + ) + self.assertEqual( + out, + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=write_token+write_position " + "slot_idx=17 position=42 stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=17, position=42)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: write_token write_position\n" + " actual: token_id=111 position=42 prev_hash=0x0000000000000000\n" + " expected: token_id=0 position=0\n" + " total_violations=1 ring_overflow=False step_when_pumped=0", + ) + + def test_format_violation_unknown_kernel_kind_renders_unknown_label(self) -> None: + """Verify unknown kernel kinds render an unknown label.""" + row = _make_row(fail_reason_bits=int(FailReason.VERIFY_CHAIN_HASH_MISMATCH)) + row[consts.VIOLATION_FIELD_KERNEL_KIND] = 9999 + out = _format_violation( + row=row, total=1, ring_overflow=False, step_when_pumped=0 + ) + self.assertEqual( + out, + "kv_canary violation: launch_tag=unknown(9999) fail_reason=verify_chain_hash slot_idx=17 position=42 " + "stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=unknown(9999), slot_idx=17, position=42)\n" + "canary_kind: unknown(9999)\n" + " fail_reasons: verify_chain_hash\n" + " stored: token_id=111 position=42 prev_hash=0x0000000000000000\n" + " expected: prev_hash=0x0000000000000000\n" + " total_violations=1 ring_overflow=False step_when_pumped=0", + ) + + +def _make_reporter( + *, + rows: list[list[int]], + write_index: int, + ring_capacity: int, + mode: CanaryMode = CanaryMode.LOG, +) -> ViolationReporter: + ring = torch.zeros(ring_capacity, consts.VIOLATION_FIELDS, dtype=torch.int64) + for i, row in enumerate(rows): + ring[i] = torch.tensor(row, dtype=torch.int64) + violation_log = SimpleNamespace( + violation_ring=ring, + violation_write_index=torch.tensor([write_index], dtype=torch.int32), + ) + device_state = SimpleNamespace(violation_log=violation_log) + config = SimpleNamespace(mode=mode) + return ViolationReporter(config=config, device_state=device_state) + + +class TestLogOrRaiseViolation(CustomTestCase): + def test_log_or_raise_violation_empty_ring_is_noop(self) -> None: + """Empty ring (write_index=0) emits no warning and leaves reporter non-raised.""" + reporter = _make_reporter( + rows=[], write_index=0, ring_capacity=4, mode=CanaryMode.LOG + ) + with patch.object(violation_reporter_module.logger, "warning") as mock_warning: + reporter.log_or_raise_violation(outer_step_counter=0) + mock_warning.assert_not_called() + self.assertFalse(reporter.is_raised) + + def test_log_mode_emits_one_warning_per_violation(self) -> None: + """Log mode with 3 valid rows emits 3 warnings, each a full _format_violation snapshot for that row.""" + rows = [ + _make_row( + slot_idx=11, + position=101, + fail_reason_bits=int(FailReason.VERIFY_CHAIN_HASH_MISMATCH), + ), + _make_row( + slot_idx=22, + position=202, + fail_reason_bits=int(FailReason.VERIFY_POSITION_MISMATCH), + ), + _make_row( + slot_idx=33, + position=303, + fail_reason_bits=int(FailReason.VERIFY_REAL_KV_HASH_MISMATCH), + ), + ] + reporter = _make_reporter( + rows=rows, write_index=3, ring_capacity=4, mode=CanaryMode.LOG + ) + with patch.object(violation_reporter_module.logger, "warning") as mock_warning: + reporter.log_or_raise_violation(outer_step_counter=7) + + self.assertEqual(mock_warning.call_count, 3) + messages: list[str] = [call.args[0] for call in mock_warning.call_args_list] + self.assertEqual( + messages[0], + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=verify_chain_hash slot_idx=11 position=101 " + "stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=11, position=101)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: verify_chain_hash\n" + " stored: token_id=111 position=101 prev_hash=0x0000000000000000\n" + " expected: prev_hash=0x0000000000000000\n" + " total_violations=3 ring_overflow=False step_when_pumped=7", + ) + self.assertEqual( + messages[1], + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=verify_position slot_idx=22 position=202 " + "stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=22, position=202)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: verify_position\n" + " stored: token_id=111 position=202 prev_hash=0x0000000000000000\n" + " expected: prev_hash=0x0000000000000000\n" + " total_violations=3 ring_overflow=False step_when_pumped=7", + ) + self.assertEqual( + messages[2], + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=verify_real_kv_hash slot_idx=33 position=303 " + "stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=33, position=303)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: verify_real_kv_hash\n" + " stored: token_id=111 position=303 prev_hash=0x0000000000000000\n" + " expected: prev_hash=0x0000000000000000\n" + " total_violations=3 ring_overflow=False step_when_pumped=7", + ) + self.assertFalse(reporter.is_raised) + + def test_raise_mode_raises_one_error_containing_all_violations(self) -> None: + """Raise mode raises a single RuntimeError whose text is the 3 formatted rows joined with single newlines.""" + rows = [ + _make_row( + slot_idx=11, + position=101, + fail_reason_bits=int(FailReason.VERIFY_CHAIN_HASH_MISMATCH), + ), + _make_row( + slot_idx=22, + position=202, + fail_reason_bits=int(FailReason.VERIFY_POSITION_MISMATCH), + ), + _make_row( + slot_idx=33, + position=303, + fail_reason_bits=int(FailReason.VERIFY_REAL_KV_HASH_MISMATCH), + ), + ] + reporter = _make_reporter( + rows=rows, write_index=3, ring_capacity=4, mode=CanaryMode.RAISE + ) + with self.assertRaises(RuntimeError) as ctx: + reporter.log_or_raise_violation(outer_step_counter=5) + + self.assertEqual( + str(ctx.exception), + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=verify_chain_hash slot_idx=11 position=101 " + "stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=11, position=101)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: verify_chain_hash\n" + " stored: token_id=111 position=101 prev_hash=0x0000000000000000\n" + " expected: prev_hash=0x0000000000000000\n" + " total_violations=3 ring_overflow=False step_when_pumped=5\n" + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=verify_position slot_idx=22 position=202 " + "stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=22, position=202)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: verify_position\n" + " stored: token_id=111 position=202 prev_hash=0x0000000000000000\n" + " expected: prev_hash=0x0000000000000000\n" + " total_violations=3 ring_overflow=False step_when_pumped=5\n" + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=verify_real_kv_hash slot_idx=33 position=303 " + "stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=33, position=303)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: verify_real_kv_hash\n" + " stored: token_id=111 position=303 prev_hash=0x0000000000000000\n" + " expected: prev_hash=0x0000000000000000\n" + " total_violations=3 ring_overflow=False step_when_pumped=5", + ) + self.assertTrue(reporter.is_raised) + + def test_log_mode_ring_overflow_marks_overflow_in_each_row(self) -> None: + """Log mode with write_index=5 but ring_capacity=2 emits 2 warnings, each a full snapshot with overflow footer.""" + rows = [ + _make_row(slot_idx=11, position=101), + _make_row(slot_idx=22, position=202), + ] + reporter = _make_reporter( + rows=rows, write_index=5, ring_capacity=2, mode=CanaryMode.LOG + ) + with patch.object(violation_reporter_module.logger, "warning") as mock_warning: + reporter.log_or_raise_violation(outer_step_counter=0) + + self.assertEqual(mock_warning.call_count, 2) + messages: list[str] = [call.args[0] for call in mock_warning.call_args_list] + self.assertEqual( + messages[0], + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=none slot_idx=11 position=101 " + "stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=11, position=101)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: none\n" + " stored: token_id=111 position=101 prev_hash=0x0000000000000000\n" + " expected: prev_hash=0x0000000000000000\n" + " total_violations=5 ring_overflow=True step_when_pumped=0", + ) + self.assertEqual( + messages[1], + "kv_canary violation: launch_tag=HEAD_K_FULL fail_reason=none slot_idx=22 position=202 " + "stored_token=111 expected_token=0 stored_chain_hash=0x0000000000000000 " + "expected_aux=0x0000000000000000\n" + "KV cache canary violation detected (kernel_kind=HEAD_K_FULL, slot_idx=22, position=202)\n" + "canary_kind: per_forward_head_k_full\n" + " fail_reasons: none\n" + " stored: token_id=111 position=202 prev_hash=0x0000000000000000\n" + " expected: prev_hash=0x0000000000000000\n" + " total_violations=5 ring_overflow=True step_when_pumped=0", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/layers/mamba/conftest.py b/asian_ai/performance/SGLang/test/registered/layers/mamba/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9a5eb429b2dfc0500c943e38d602604f861bc0ae --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/layers/mamba/conftest.py @@ -0,0 +1,19 @@ +import pytest + +from sglang.srt.layers.attention.mamba.ops import ssu_dispatch +from sglang.srt.layers.attention.mamba.ops.ssu_dispatch import ( + initialize_mamba_selective_state_update_backend, +) +from sglang.srt.server_args import ServerArgs + + +@pytest.fixture(scope="session", autouse=True) +def _init_mamba_ssu_backend(): + """Initialize the Mamba SSU dispatch backend for the test session. + + In production this happens in Scheduler.init_mamba_backend(). Tests have no + scheduler, so we do it here via the same public API. + """ + initialize_mamba_selective_state_update_backend(ServerArgs(model_path="dummy")) + yield + ssu_dispatch._mamba_ssu_backend = None diff --git a/asian_ai/performance/SGLang/test/registered/layers/mamba/test_causal_conv1d.py b/asian_ai/performance/SGLang/test/registered/layers/mamba/test_causal_conv1d.py new file mode 100644 index 0000000000000000000000000000000000000000..265ec7afe3e009e95707c8dcd6955777c19714e9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/layers/mamba/test_causal_conv1d.py @@ -0,0 +1,384 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=11, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=25, suite="stage-b-test-1-gpu-small-amd") + +# Adapted from https://github.com/vllm-project/vllm/blob/main/tests/kernels/mamba/test_causal_conv1d.py + + +from typing import Optional + +import pytest +import torch +import torch.nn.functional as F +from einops import rearrange + +from sglang.srt.layers.attention.mamba.causal_conv1d_triton import ( + PAD_SLOT_ID, + causal_conv1d_fn, + causal_conv1d_update, +) +from sglang.srt.utils import get_device +from sglang.test.test_utils import empty_gpu_cache + + +def causal_conv1d_ref( + x: torch.Tensor, + weight: torch.Tensor, + bias: Optional[torch.Tensor] = None, + initial_states: Optional[torch.Tensor] = None, + return_final_states: bool = False, + final_states_out: Optional[torch.Tensor] = None, + activation: Optional[str] = "silu", +): + """ + x: (batch, dim, seqlen) + weight: (dim, width) + bias: (dim,) + initial_states: (batch, dim, width - 1) + final_states_out: (batch, dim, width - 1) + + out: (batch, dim, seqlen) + """ + if activation not in [None, "silu", "swish"]: + raise NotImplementedError("activation must be None, silu, or swish") + dtype_in = x.dtype + x = x.to(weight.dtype) + seqlen = x.shape[-1] + dim, width = weight.shape + if initial_states is None: + out = F.conv1d(x, weight.unsqueeze(1), bias, padding=width - 1, groups=dim) + else: + x = torch.cat([initial_states, x], dim=-1) + out = F.conv1d(x, weight.unsqueeze(1), bias, padding=0, groups=dim) + out = out[..., :seqlen] + if return_final_states: + final_states = F.pad(x, (width - 1 - x.shape[-1], 0)).to( + dtype_in + ) # (batch, dim, width - 1) + if final_states_out is not None: + final_states_out.copy_(final_states) + else: + final_states_out = final_states + out = (out if activation is None else F.silu(out)).to(dtype=dtype_in) + return (out, None) if not return_final_states else (out, final_states_out) + + +def causal_conv1d_update_ref( + x, conv_state, weight, bias=None, activation=None, cache_seqlens=None +): + """ + x: (batch, dim) or (batch, dim, seqlen) + conv_state: (batch, dim, state_len), where state_len >= width - 1 + weight: (dim, width) + bias: (dim,) + cache_seqlens: (batch,), dtype int32. + If not None, the conv_state is treated as a circular buffer. + The conv_state will be updated by copying x to the + conv_state starting at the index + @cache_seqlens % state_len before performing the convolution. + + out: (batch, dim) or (batch, dim, seqlen) + """ + if activation not in [None, "silu", "swish"]: + raise NotImplementedError("activation must be None, silu, or swish") + dtype_in = x.dtype + unsqueeze = x.dim() == 2 + if unsqueeze: + x = x.unsqueeze(-1) + batch, dim, seqlen = x.shape + width = weight.shape[1] + state_len = conv_state.shape[-1] + assert conv_state.shape == (batch, dim, state_len) + assert weight.shape == (dim, width) + if cache_seqlens is None: + x_new = torch.cat([conv_state, x], dim=-1).to( + weight.dtype + ) # (batch, dim, state_len + seqlen) + conv_state.copy_(x_new[:, :, -state_len:]) + else: + width_idx = torch.arange( + -(width - 1), 0, dtype=torch.long, device=x.device + ).unsqueeze(0) + cache_seqlens.unsqueeze(1) + width_idx = ( + torch.remainder(width_idx, state_len).unsqueeze(1).expand(-1, dim, -1) + ) + x_new = torch.cat([conv_state.gather(2, width_idx), x], dim=-1).to(weight.dtype) + copy_idx = torch.arange(seqlen, dtype=torch.long, device=x.device).unsqueeze( + 0 + ) + cache_seqlens.unsqueeze(1) + copy_idx = torch.remainder(copy_idx, state_len).unsqueeze(1).expand(-1, dim, -1) + conv_state.scatter_(2, copy_idx, x) + out = F.conv1d(x_new, weight.unsqueeze(1), bias, padding=0, groups=dim)[ + :, :, -seqlen: + ] + if unsqueeze: + out = out.squeeze(-1) + return (out if activation is None else F.silu(out)).to(dtype=dtype_in) + + +@pytest.mark.parametrize("itype", [torch.bfloat16, torch.float]) +@pytest.mark.parametrize("silu_activation", [True]) +@pytest.mark.parametrize("has_bias", [True]) +def causal_conv1d_opcheck_fn( + x: torch.Tensor, + weight: torch.Tensor, + bias: Optional[torch.Tensor] = None, + cu_seq_len: Optional[torch.Tensor] = None, + cache_indices: Optional[torch.Tensor] = None, + has_initial_state: Optional[torch.Tensor] = None, + conv_states: Optional[torch.Tensor] = None, + activation: Optional[str] = "silu", + pad_slot_id: int = PAD_SLOT_ID, +): + """ + x: (batch, dim, seqlen) + weight: (dim, width) + bias: (dim,) + seq_idx: (batch, seqlen) + initial_states: (batch, dim, width - 1) + final_states_out: (batch, dim, width - 1), to be written to + activation: either None or "silu" or "swish" + + out: (batch, dim, seqlen) + """ + if activation not in [None, "silu", "swish"]: + raise NotImplementedError("activation must be None, silu, or swish") + if x.stride(-1) != 1: + x = x.contiguous() + bias = bias.contiguous() if bias is not None else None + + +@pytest.mark.parametrize("itype", [torch.bfloat16]) +@pytest.mark.parametrize("silu_activation", [False, True]) +@pytest.mark.parametrize("has_bias", [False, True]) +@pytest.mark.parametrize("seqlen", [1]) +@pytest.mark.parametrize("width", [4]) +@pytest.mark.parametrize("dim", [2048, 2048 + 16, 4096]) +def test_causal_conv1d_update(dim, width, seqlen, has_bias, silu_activation, itype): + + device = get_device() + rtol, atol = (3e-4, 1e-3) if itype == torch.float32 else (3e-3, 5e-3) + if itype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + # set seed + torch.manual_seed(0) + batch = 2 + x = torch.randn(batch, dim, seqlen, device=device, dtype=itype) + x_ref = x.clone() + conv_state = torch.randn(batch, dim, width - 1, device=device, dtype=itype) + + weight = torch.randn(dim, width, device=device, dtype=itype) + bias = torch.randn(dim, device=device, dtype=itype) if has_bias else None + conv_state_ref = conv_state.detach().clone() + activation = None if not silu_activation else "silu" + out = causal_conv1d_update(x, conv_state, weight, bias, activation=activation) + out_ref = causal_conv1d_update_ref( + x_ref, conv_state_ref, weight, bias, activation=activation + ) + + assert torch.equal(conv_state, conv_state_ref) + assert torch.allclose(out, out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("itype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("silu_activation", [False, True]) +@pytest.mark.parametrize("has_bias", [False, True]) +@pytest.mark.parametrize("seqlen", [1, 3]) +@pytest.mark.parametrize("width", [3, 4]) +@pytest.mark.parametrize("dim", [2048 + 16, 4096]) +# tests correctness in case subset of the sequences are padded +@pytest.mark.parametrize("with_padding", [True, False]) +@pytest.mark.parametrize("batch_size", [3]) +def test_causal_conv1d_update_with_batch_gather( + batch_size, with_padding, dim, width, seqlen, has_bias, silu_activation, itype +): + + device = get_device() + rtol, atol = (3e-4, 1e-3) if itype == torch.float32 else (3e-3, 5e-3) + if itype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + + # set seed + torch.manual_seed(0) + + padding = 5 if with_padding else 0 + padded_batch_size = batch_size + padding + # total_entries = number of cache line + total_entries = 10 * batch_size + + # x will be (batch, dim, seqlen) with contiguous along dim-axis + x = torch.randn( + padded_batch_size, seqlen, dim, device=device, dtype=itype + ).transpose(1, 2) + + x_ref = x.clone() + + conv_state_indices = torch.randperm(total_entries)[:batch_size].to( + dtype=torch.int32, device=device + ) + unused_states_bool = torch.ones(total_entries, dtype=torch.bool, device=device) + unused_states_bool[conv_state_indices] = False + padded_state_indices = torch.concat( + [ + conv_state_indices, + torch.as_tensor([PAD_SLOT_ID] * padding, dtype=torch.int32, device=device), + ], + dim=0, + ) + + # conv_state will be (cache_lines, dim, state_len) + # with contiguous along dim-axis + conv_state = torch.randn( + total_entries, width - 1, dim, device=device, dtype=itype + ).transpose(1, 2) + + conv_state_for_padding_test = conv_state.clone() + + weight = torch.randn(dim, width, device=device, dtype=itype) + bias = torch.randn(dim, device=device, dtype=itype) if has_bias else None + conv_state_ref = conv_state[conv_state_indices, :].detach().clone() + activation = None if not silu_activation else "silu" + + out = causal_conv1d_update( + x, + conv_state, + weight, + bias, + activation=activation, + conv_state_indices=padded_state_indices, + pad_slot_id=PAD_SLOT_ID, + ) + out_ref = causal_conv1d_update_ref( + x_ref[:batch_size], conv_state_ref, weight, bias, activation=activation + ) + + assert torch.equal(conv_state[conv_state_indices, :], conv_state_ref) + assert torch.equal( + conv_state[unused_states_bool], conv_state_for_padding_test[unused_states_bool] + ) + assert torch.allclose(out[:batch_size], out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("itype", [torch.bfloat16]) +@pytest.mark.parametrize("silu_activation", [True]) +@pytest.mark.parametrize("has_bias", [True]) +@pytest.mark.parametrize("width", [4]) +@pytest.mark.parametrize("seqlen", [8, 30, 249, 2049, 4096]) +@pytest.mark.parametrize("dim", [64, 4096]) +@pytest.mark.parametrize("with_padding", [True, False]) +@pytest.mark.parametrize("batch", [4, 10]) +def test_causal_conv1d_varlen( + batch, with_padding, dim, seqlen, width, has_bias, silu_activation, itype +): + + device = get_device() + empty_gpu_cache() + rtol, atol = (3e-4, 1e-3) if itype == torch.float32 else (3e-3, 5e-3) + if itype == torch.bfloat16: + rtol, atol = 1e-2, 5e-2 + # set seed + torch.manual_seed(0) + seqlens = [] + batch_size = batch + padding = 3 if with_padding else 0 + padded_batch_size = batch_size + padding + nsplits = padded_batch_size - 1 + + eos_pos = torch.randperm(seqlen - 1)[:nsplits].sort().values + + seqlens.append( + torch.diff( + torch.cat([torch.tensor([-1]), eos_pos, torch.tensor([seqlen - 1])]) + ).tolist() + ) + assert sum(seqlens[-1]) == seqlen + assert all(s > 0 for s in seqlens[-1]) + + total_entries = batch_size * 10 + cumsum = torch.cumsum(torch.tensor(seqlens[0]), dim=0).to(torch.int32) + cumsum = torch.concat([torch.tensor([0], dtype=torch.int32), cumsum], dim=0) + x = rearrange( + torch.randn(1, seqlen, 4096 + dim + 64, device=device, dtype=itype), + "b s d -> b d s", + )[:, 4096 : 4096 + dim, :] + + weight = torch.randn(dim, width, device=device, dtype=itype) + + bias = torch.randn(dim, device=device, dtype=itype) if has_bias else None + x_ref = x.clone() + weight_ref = weight.clone() + bias_ref = bias.clone() if bias is not None else None + activation = None if not silu_activation else "silu" + final_states = torch.randn( + total_entries, width - 1, dim, device=x.device, dtype=x.dtype + ).transpose(1, 2) + final_states_ref = final_states.clone() + has_initial_states = torch.randint( + 0, 2, (cumsum.shape[0] - 1,), dtype=torch.bool, device=x.device + ) + state_indices = torch.randperm(total_entries, dtype=torch.int32, device=x.device)[ + :batch_size + ] + padded_state_indices = torch.concat( + [ + state_indices, + torch.as_tensor([PAD_SLOT_ID] * padding, dtype=torch.int32, device=device), + ], + dim=-1, + ) + out = causal_conv1d_fn( + x.squeeze(0), + weight, + bias=bias, + conv_states=final_states, + query_start_loc=cumsum.to(get_device()), + seq_lens_cpu=torch.tensor(seqlens[0]), + cache_indices=padded_state_indices, + has_initial_state=has_initial_states, + activation=activation, + pad_slot_id=PAD_SLOT_ID, + ) + + out_ref = [] + out_ref_b = [] + + splits = [torch.split(var, seqlens[0], dim=-1) for var in (x_ref)] + for i in range(len(seqlens[0])): + x_s = [v[i].unsqueeze(0) for v in splits][0] + if padded_state_indices[i] == PAD_SLOT_ID: + continue + out_ref_b.append( + causal_conv1d_ref( + x_s, + weight_ref, + bias_ref, + activation=activation, + return_final_states=True, + final_states_out=final_states_ref[padded_state_indices[i]].unsqueeze(0), + initial_states=( + final_states_ref[padded_state_indices[i]].unsqueeze(0) + if has_initial_states[i] + else None + ), + ) + ) + out_ref.append(torch.cat([t[0] for t in out_ref_b], dim=2)) + out_ref_tensor = torch.cat(out_ref, dim=0) + + assert torch.allclose( + final_states[state_indices], + final_states_ref[state_indices], + rtol=rtol, + atol=atol, + ) + unpadded_out = out[:, : out_ref_tensor.shape[-1]] + assert torch.allclose(unpadded_out, out_ref_tensor, rtol=rtol, atol=atol) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/layers/mamba/test_mamba2_mixer.py b/asian_ai/performance/SGLang/test/registered/layers/mamba/test_mamba2_mixer.py new file mode 100644 index 0000000000000000000000000000000000000000..83eec4207b8028efedeadd1004bc0917d334fffc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/layers/mamba/test_mamba2_mixer.py @@ -0,0 +1,150 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +# Adapted from https://github.com/vllm-project/vllm/blob/2c58742dff8613a3bd7496f2008ce927e18d38d1/tests/kernels/mamba/test_mamba_mixer2.py + + +import pytest +import torch + +from sglang.srt.distributed.device_communicators.custom_all_reduce_utils import ( + update_environment_variables, +) +from sglang.srt.distributed.parallel_state import ( + init_distributed_environment, + initialize_model_parallel, +) +from sglang.srt.runtime_context import get_parallel +from sglang.srt.utils import get_device, get_device_count +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=32, stage="base-b", runner_config="2-gpu-large") + +NUM_GPUS = 2 + + +@pytest.mark.parametrize("batch_size", [8]) +@pytest.mark.parametrize("seq_len", [128]) +@pytest.mark.parametrize( + "hidden_size_n_groups", + [ + (64, 1), # hidden_size be divisible by num_gpus + (100, 4), # and n_groups must divide hidden_size + ], +) +@pytest.mark.parametrize("dtype", [torch.float16]) +def test_mixer2_gated_norm_multi_gpu( + batch_size: int, + seq_len: int, + hidden_size_n_groups: tuple[int, int], + dtype: torch.dtype, + device: str = get_device(), +): + if device not in ["cuda", "xpu"]: + pytest.skip("Test only supports CUDA and XPU devices") + + assert ( + get_device_count() >= NUM_GPUS + ), f"This test requires at least {NUM_GPUS} GPUs, but only {get_device_count()} available" + + hidden_size, n_groups = hidden_size_n_groups + num_processes = NUM_GPUS + + def run_torch_spawn(fn, nprocs): + # need to use torch.mp.spawn otherwise will have problems with + # torch.distributed and cuda + torch.multiprocessing.spawn( + fn, + args=( + num_processes, + batch_size, + seq_len, + hidden_size, + n_groups, + dtype, + device, + ), + nprocs=nprocs, + ) + + run_torch_spawn(mixer2_gated_norm_tensor_parallel, NUM_GPUS) + + +def mixer2_gated_norm_tensor_parallel( + local_rank: int, + world_size: int, + batch_size: int, + seq_len: int, + hidden_size: int, + n_groups: int, + dtype: torch.dtype, + device: str, +): + torch.manual_seed(0) + + device = torch.device(get_device(local_rank)) + torch.get_device_module(device).set_device(device) + torch.set_default_device(device) + torch.set_default_dtype(dtype) + + update_environment_variables( + { + "RANK": str(local_rank), + "LOCAL_RANK": str(local_rank), + "WORLD_SIZE": str(world_size), + "MASTER_ADDR": "localhost", + "MASTER_PORT": "12345", + } + ) + + # initialize distributed + init_distributed_environment( + world_size=world_size, rank=local_rank, local_rank=local_rank + ) + initialize_model_parallel(tensor_model_parallel_size=world_size) + + # create random weights an inputs + weight = torch.rand((hidden_size,), dtype=dtype, device=device) + hidden_states = torch.randn(batch_size, seq_len, hidden_size) + gate_states = torch.randn(batch_size, seq_len, hidden_size) + + import sglang.srt.layers.attention.mamba.mixer2_rms_norm_gated as m2 + + # Force attn-TP rank through the context (the weight loader reads it via + # get_parallel().attn_tp_rank); avoids calling initialize_dp_attention. + with get_parallel().override(attn_tp_rank=local_rank): + # create gated-norm with TP + mixer = m2.Mixer2RMSNormGated( + full_hidden_size=hidden_size, + full_n_groups=n_groups, + ) + mixer.weight.weight_loader(mixer.weight, weight) + + # m2 reads tp via get_parallel().tp_size/rank — force it through the context. + with get_parallel().override(tp_size=1, tp_rank=0): + # create gated-norm without TP to compute reference + mixer_single_gpu = m2.Mixer2RMSNormGated( + full_hidden_size=hidden_size, + full_n_groups=n_groups, + ) + # assign weight to single-gpu mixer + mixer_single_gpu.weight.data = weight + + # generate and compare + N = hidden_size // world_size + output = mixer( + hidden_states[..., local_rank * N : (local_rank + 1) * N], + gate_states[..., local_rank * N : (local_rank + 1) * N], + ) + ref_output = mixer_single_gpu(hidden_states, gate_states) + torch.testing.assert_close( + output, + ref_output[..., local_rank * N : (local_rank + 1) * N], + atol=5e-3, + rtol=1e-3, + ) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/layers/mamba/test_mamba_ssm.py b/asian_ai/performance/SGLang/test/registered/layers/mamba/test_mamba_ssm.py new file mode 100644 index 0000000000000000000000000000000000000000..5010db21e38a2a62649f014ea523345f9f093ad2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/layers/mamba/test_mamba_ssm.py @@ -0,0 +1,364 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-small-amd") + +# Adapted from https://github.com/vllm-project/vllm/blob/633f943e30a4444d890d26b81850f7217736f840/tests/kernels/mamba/test_mamba_ssm_ssd.py + + +import pytest +import torch +import torch.nn.functional as F +from einops import rearrange, repeat + +from sglang.srt.layers.attention.mamba.causal_conv1d_triton import PAD_SLOT_ID +from sglang.srt.layers.attention.mamba.ops.mamba_ssm import selective_state_update +from sglang.srt.utils import get_device, is_sm100_supported + + +def selective_state_update_ref( + state, x, dt, A, B, C, D=None, z=None, dt_bias=None, dt_softplus=False +): + """ + Argument: + state: (batch, dim, dstate) or (batch, nheads, dim, dstate) + x: (batch, dim) or (batch, nheads, dim) + dt: (batch, dim) or (batch, nheads, dim) + A: (dim, dstate) or (nheads, dim, dstate) + B: (batch, dstate) or (batch, ngroups, dstate) + C: (batch, dstate) or (batch, ngroups, dstate) + D: (dim,) or (nheads, dim) + z: (batch, dim) or (batch, nheads, dim) + dt_bias: (dim,) or (nheads, dim) + Return: + out: (batch, dim) or (batch, nheads, dim) + """ + has_heads = state.dim() > 3 + if state.dim() == 3: + state = state.unsqueeze(1) + if x.dim() == 2: + x = x.unsqueeze(1) + if dt.dim() == 2: + dt = dt.unsqueeze(1) + if A.dim() == 2: + A = A.unsqueeze(0) + if B.dim() == 2: + B = B.unsqueeze(1) + if C.dim() == 2: + C = C.unsqueeze(1) + if D is not None and D.dim() == 1: + D = D.unsqueeze(0) + if z is not None and z.dim() == 2: + z = z.unsqueeze(1) + if dt_bias is not None and dt_bias.dim() == 1: + dt_bias = dt_bias.unsqueeze(0) + batch, nheads, dim, dstate = state.shape + assert x.shape == (batch, nheads, dim) + assert dt.shape == x.shape + assert A.shape == (nheads, dim, dstate) + ngroups = B.shape[1] + assert nheads % ngroups == 0, "nheads must be divisible by ngroups" + assert B.shape == (batch, ngroups, dstate) + assert C.shape == B.shape + if D is not None: + assert D.shape == (nheads, dim) + if z is not None: + assert z.shape == x.shape + if dt_bias is not None: + assert dt_bias.shape == (nheads, dim) + dt = dt + dt_bias + dt = F.softplus(dt) if dt_softplus else dt + dA = torch.exp( + rearrange(dt, "b h d -> b h d 1") * A + ) # (batch, nheads, dim, dstate) + B = repeat(B, "b g n -> b (g h) n", h=nheads // ngroups) # (batch, nheads, dstate) + C = repeat(C, "b g n -> b (g h) n", h=nheads // ngroups) # (batch, nheads, dstate) + dB = rearrange(dt, "b h d -> b h d 1") * rearrange( + B, "b h n -> b h 1 n" + ) # (batch, nheads, dim, dstate) + state.copy_( + state * dA + dB * rearrange(x, "b h d -> b h d 1") + ) # (batch, dim, dstate + out = torch.einsum("bhdn,bhn->bhd", state.to(C.dtype), C) + if D is not None: + out += (x * D).to(out.dtype) + out = (out if z is None else out * F.silu(z)).to(x.dtype) + if not has_heads: + out = out.squeeze(1) + return out + + +@pytest.mark.parametrize("itype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("has_z", [False, True]) +@pytest.mark.parametrize("dstate", [16, 32, 64]) +@pytest.mark.parametrize("dim", [2048, 2048 + 16, 4096]) +def test_selective_state_update(dim, dstate, has_z, itype): + device = get_device() + if device not in ["cuda", "xpu"]: + pytest.skip("Test only supports CUDA and XPU devices") + + rtol, atol = (3e-4, 1e-3) if itype == torch.float32 else (5e-3, 1e-2) + if itype == torch.bfloat16: + rtol, atol = 1e-2, 1e-1 + if torch.version.hip: + atol *= 2 + # set seed + torch.manual_seed(0) + batch_size = 1 + state = torch.randn(batch_size, dim, dstate, dtype=itype, device=device) + x = torch.randn(batch_size, dim, device=device, dtype=itype) + out = torch.empty_like(x) + dt = torch.randn(batch_size, dim, device=device, dtype=itype) + dt_bias = torch.rand(dim, device=device) - 4.0 + A = -torch.rand(dim, dstate, device=device) - 1.0 + B = torch.randn(batch_size, dstate, device=device) + C = torch.randn(batch_size, dstate, device=device) + D = torch.randn(dim, device=device) + z = torch.randn_like(x) if has_z else None + state_ref = state.detach().clone() + selective_state_update( + state, x, dt, A, B, C, D=D, z=z, dt_bias=dt_bias, dt_softplus=True, out=out + ) + out_ref = selective_state_update_ref( + state_ref, x, dt, A, B, C, D=D, z=z, dt_bias=dt_bias, dt_softplus=True + ) + + assert torch.allclose(state, state_ref, rtol=rtol, atol=atol) + assert torch.allclose(out, out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("itype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("has_z", [True]) +@pytest.mark.parametrize("dstate", [16, 32, 64]) +@pytest.mark.parametrize("dim", [2048, 2048 + 16, 4096]) +# tests correctness in case subset of the sequences are padded +@pytest.mark.parametrize("with_padding", [True, False]) +def test_selective_state_update_with_batch_indices( + with_padding, dim, dstate, has_z, itype +): + device = get_device() + if device not in ["cuda", "xpu"]: + pytest.skip("Test only supports CUDA and XPU devices") + rtol, atol = (3e-4, 1e-3) if itype == torch.float32 else (5e-3, 1e-2) + if itype == torch.bfloat16: + rtol, atol = 1e-1, 1e-1 + if torch.version.hip: + atol *= 2 + # set seed + torch.random.manual_seed(0) + batch_size = 3 + padding = 5 if with_padding else 0 + padded_batch_size = batch_size + padding + total_entries = 10 * batch_size + state = torch.randn(total_entries, dim, dstate, dtype=itype, device=device) + state_indices = torch.randperm(total_entries)[:batch_size].to( + dtype=torch.int32, device=device + ) + unused_states_bool = torch.ones(total_entries, dtype=torch.bool, device=device) + unused_states_bool[state_indices] = False + padded_state_indices = torch.concat( + [ + state_indices, + torch.as_tensor([PAD_SLOT_ID] * padding, dtype=torch.int32, device=device), + ], + dim=0, + ) + x = torch.randn(padded_batch_size, dim, device=device, dtype=itype) + out = torch.empty_like(x) + dt = torch.randn(padded_batch_size, dim, device=device, dtype=itype) + dt_bias = torch.rand(dim, device=device) - 4.0 + A = -torch.rand(dim, dstate, device=device) - 1.0 + B = torch.randn(padded_batch_size, dstate, device=device) + C = torch.randn(padded_batch_size, dstate, device=device) + D = torch.randn(dim, device=device) + z = torch.randn_like(x) if has_z else None + state_ref = state[state_indices, :].clone() + state_before = state.clone() + selective_state_update( + state, + x, + dt, + A, + B, + C, + D=D, + z=z, + dt_bias=dt_bias, + dt_softplus=True, + state_batch_indices=padded_state_indices, + pad_slot_id=PAD_SLOT_ID, + out=out, + ) + out_ref = selective_state_update_ref( + state_ref, + x[:batch_size], + dt[:batch_size], + A, + B[:batch_size], + C[:batch_size], + D=D, + z=z[:batch_size], + dt_bias=dt_bias, + dt_softplus=True, + ) + + print("Output diff max", (out[:batch_size] - out_ref).max()) + print("Output diff mean", (out[:batch_size] - out_ref).mean()) + print("Output state diff max", (state[state_indices, :] - state_ref).max()) + print("Output state diff mean", (state[state_indices, :] - state_ref).mean()) + # test padded entries stay the same + if with_padding: + assert torch.equal(state_before[unused_states_bool], state[unused_states_bool]) + assert torch.equal(x[batch_size + 1 :], x[batch_size + 1 :]) + assert torch.equal(dt[batch_size + 1 :], dt[batch_size + 1 :]) + assert torch.equal(B[batch_size + 1 :], B[batch_size + 1 :]) + assert torch.equal(C[batch_size + 1 :], C[batch_size + 1 :]) + + # test "real" entries + assert torch.allclose(state[state_indices, :], state_ref, rtol=rtol, atol=atol) + assert torch.allclose(out[:batch_size], out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("itype", [torch.float32, torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("has_z", [False, True]) +@pytest.mark.parametrize("tie_hdim", [False, True]) +@pytest.mark.parametrize("ngroups", [1, 2, 4]) +@pytest.mark.parametrize("dstate", [16, 32, 64]) +@pytest.mark.parametrize("dim", [2048, 4096]) +def test_selective_state_update_with_heads_with_batch_indices( + dim, dstate, ngroups, has_z, tie_hdim, itype +): + device = get_device() + if device not in ["cuda", "xpu"]: + pytest.skip("Test only supports CUDA and XPU devices") + rtol, atol = (3e-4, 1e-3) if itype == torch.float32 else (5e-3, 3e-2) + if itype == torch.bfloat16: + rtol, atol = 1e-1, 1e-1 + # set seed + torch.random.manual_seed(0) + batch_size = 3 + headdim = 64 + nheads = dim // headdim + + total_entries = 10 * batch_size + state = torch.randn( + total_entries, nheads, headdim, dstate, dtype=itype, device=device + ) + state_indices = torch.randperm(total_entries)[:batch_size].to( + dtype=torch.int32, device=device + ) + + x = torch.randn(batch_size, nheads, headdim, device=device, dtype=itype) + out = torch.empty_like(x) + if not tie_hdim: + dt = torch.randn(batch_size, nheads, headdim, device=device, dtype=itype) + dt_bias = torch.rand(nheads, headdim, device=device) - 4.0 + A = -torch.rand(nheads, headdim, dstate, device=device) - 1.0 + D = torch.randn(nheads, headdim, device=device) + else: + dt = repeat( + torch.randn(batch_size, nheads, device=device, dtype=itype), + "b h -> b h p", + p=headdim, + ) + dt_bias = repeat(torch.rand(nheads, device=device) - 4.0, "h -> h p", p=headdim) + A = repeat( + -torch.rand(nheads, device=device) - 1.0, "h -> h p n", p=headdim, n=dstate + ) + D = repeat(torch.randn(nheads, device=device), "h -> h p", p=headdim) + B = torch.randn(batch_size, ngroups, dstate, device=device) + C = torch.randn(batch_size, ngroups, dstate, device=device) + z = torch.randn_like(x) if has_z else None + state_ref = state[state_indices, :].detach().clone() + selective_state_update( + state, + x, + dt, + A, + B, + C, + D=D, + z=z, + dt_bias=dt_bias, + dt_softplus=True, + state_batch_indices=state_indices, + pad_slot_id=PAD_SLOT_ID, + out=out, + ) + out_ref = selective_state_update_ref( + state_ref, x, dt, A, B, C, D=D, z=z, dt_bias=dt_bias, dt_softplus=True + ) + + print(f"Output max diff: {(out - out_ref).abs().max().item()}") + print(f"Output mean diff: {(out - out_ref).abs().mean().item()}") + assert torch.allclose(state[state_indices, :], state_ref, rtol=rtol, atol=atol) + assert torch.allclose(out, out_ref, rtol=rtol, atol=atol) + + +@pytest.mark.skipif( + not is_sm100_supported(), + reason=( + "Triton stochastic rounding uses cvt.rs.f16x2.f32 and requires " + "SM100-family Blackwell with CUDA >= 12.8" + ), +) +@pytest.mark.parametrize("philox_rounds", [0, 4]) +@pytest.mark.parametrize("has_z", [False, True]) +@pytest.mark.parametrize("dstate", [16, 64]) +@pytest.mark.parametrize("dim", [2048, 4096]) +def test_selective_state_update_stochastic_rounding(dim, dstate, has_z, philox_rounds): + device = "cuda" + torch.manual_seed(0) + + batch_size = 2 + state = torch.randn(batch_size, dim, dstate, dtype=torch.float16, device=device) + x = torch.randn(batch_size, dim, device=device, dtype=torch.bfloat16) + out = torch.empty_like(x) + dt = torch.randn(batch_size, dim, device=device, dtype=torch.bfloat16) + dt_bias = torch.rand(dim, device=device) - 4.0 + A = -torch.rand(dim, dstate, device=device) - 1.0 + B = torch.randn(batch_size, dstate, device=device) + C = torch.randn(batch_size, dstate, device=device) + D = torch.randn(dim, device=device) + z = torch.randn_like(x) if has_z else None + state_ref = state.float() + + selective_state_update( + state, + x, + dt, + A, + B, + C, + D=D, + z=z, + dt_bias=dt_bias, + dt_softplus=True, + out=out, + enable_stochastic_rounding=True, + cache_philox_rounds=philox_rounds, + ) + out_ref = selective_state_update_ref( + state_ref, + x, + dt, + A, + B, + C, + D=D, + z=z, + dt_bias=dt_bias, + dt_softplus=True, + ) + + assert state.dtype == torch.float16 + assert torch.allclose(state, state_ref.to(torch.float16), rtol=5e-3, atol=1e-1) + assert torch.allclose(out, out_ref, rtol=5e-3, atol=1e-1) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/layers/mamba/test_mamba_ssm_ssd.py b/asian_ai/performance/SGLang/test/registered/layers/mamba/test_mamba_ssm_ssd.py new file mode 100644 index 0000000000000000000000000000000000000000..b6ad8d28d9bfe0576a64eb495080f04672c1a23d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/layers/mamba/test_mamba_ssm_ssd.py @@ -0,0 +1,701 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=34, suite="stage-b-test-1-gpu-small-amd") + +# Adapted from https://github.com/vllm-project/vllm/blob/633f943e30a4444d890d26b81850f7217736f840/tests/kernels/mamba/test_mamba_ssm_ssd.py + +import os + +import pytest +import torch +import torch.nn.functional as F +from einops import rearrange, repeat + +from sglang.srt.layers.attention.mamba.mamba2_metadata import Mamba2Metadata +from sglang.srt.layers.attention.mamba.ops import mamba_chunk_scan_combined +from sglang.srt.utils import get_device +from sglang.srt.utils.common import is_hip +from sglang.utils import is_in_ci + +if is_hip(): + os.environ["AMDGCN_USE_BUFFER_OPS"] = "0" + +# Added by the IBM Team, 2024 + +# Adapted from https://github.com/state-spaces/mamba/blob/v2.2.4/mamba_ssm/modules/ssd_minimal.py + + +# this is the segsum implementation taken from above +def segsum(x): + """Calculates segment sum.""" + T = x.size(-1) + x = repeat(x, "... d -> ... d e", e=T) + mask = torch.tril(torch.ones(T, T, device=x.device, dtype=bool), diagonal=-1) + x = x.masked_fill(~mask, 0) + x_segsum = torch.cumsum(x, dim=-2) + mask = torch.tril(torch.ones(T, T, device=x.device, dtype=bool), diagonal=0) + x_segsum = x_segsum.masked_fill(~mask, -torch.inf) + return x_segsum + + +def ssd_minimal_discrete( + X, + A, + B, + C, + block_len, + initial_states=None, + return_intermediate_states=False, +): + """ + Arguments: + X: (batch, length, n_heads, d_head) + A: (batch, length, n_heads) + B: (batch, length, n_heads, d_state) + C: (batch, length, n_heads, d_state) + Return: + Y: (batch, length, n_heads, d_head) + """ + assert X.dtype == A.dtype == B.dtype == C.dtype + assert X.shape[1] % block_len == 0 + + # Rearrange into blocks/chunks + X, A, B, C = ( + rearrange(x, "b (c l) ... -> b c l ...", l=block_len) for x in (X, A, B, C) + ) + + A = rearrange(A, "b c l h -> b h c l") + A_cumsum = torch.cumsum(A, dim=-1) + + # 1. Compute the output for each intra-chunk (diagonal blocks) + L = torch.exp(segsum(A)) + Y_diag = torch.einsum("bclhn,bcshn,bhcls,bcshp->bclhp", C, B, L, X) + + # 2. Compute the state for each intra-chunk + # (right term of low-rank factorization of off-diagonal blocks; B terms) + decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum) + states = torch.einsum("bclhn,bhcl,bclhp->bchpn", B, decay_states, X) + + # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at + # chunk boundaries + # (middle term of factorization of off-diag blocks; A terms) + if initial_states is None: + initial_states = torch.zeros_like(states[:, :1]) + states = torch.cat([initial_states, states], dim=1) + decay_chunk = torch.exp(segsum(F.pad(A_cumsum[:, :, :, -1], (1, 0)))) + new_states = torch.einsum("bhzc,bchpn->bzhpn", decay_chunk, states) + states, final_state = new_states[:, :-1], new_states[:, -1] + + # 4. Compute state -> output conversion per chunk + # (left term of low-rank factorization of off-diagonal blocks; C terms) + state_decay_out = torch.exp(A_cumsum) + Y_off = torch.einsum("bclhn,bchpn,bhcl->bclhp", C, states, state_decay_out) + + # Add output of intra-chunk and inter-chunk terms + # (diagonal and off-diagonal blocks) + Y = rearrange(Y_diag + Y_off, "b c l h p -> b (c l) h p") + if return_intermediate_states: + return Y, final_state, states + return Y, final_state + + +def generate_random_inputs(batch_size, seqlen, n_heads, d_head, itype, device=None): + + if device is None: + device = get_device() + if device not in ["cuda", "xpu"]: + pytest.skip("Test only supports CUDA and XPU devices") + + torch.manual_seed(0) + A = -torch.exp(torch.rand(n_heads, dtype=itype, device=device)) + dt = F.softplus( + torch.randn(batch_size, seqlen, n_heads, dtype=itype, device=device) - 4 + ) + X = torch.randn((batch_size, seqlen, n_heads, d_head), dtype=itype, device=device) + B = torch.randn((batch_size, seqlen, n_heads, d_head), dtype=itype, device=device) + C = torch.randn((batch_size, seqlen, n_heads, d_head), dtype=itype, device=device) + + return A, dt, X, B, C + + +def generate_continuous_batched_examples( + example_lens_by_batch, + num_examples, + full_length, + last_taken, + exhausted, + n_heads, + d_head, + itype, + device=None, + return_naive_ref=True, +): + + # this function generates a random examples of certain length + # and then cut according to "example_lens_by_batch" and feed + # them in continuous batches to the kernels. + # If if return_naive_ref=True, the naive torch implementation + # ssd_minimal_discrete will be used to compute and return + # reference output. + + # generate the full-length example + A, dt, X, B, C = generate_random_inputs( + num_examples, full_length, n_heads, d_head, itype, device + ) + # Capture the resolved device from the tensors + device = X.device + + if return_naive_ref: + Y_min, final_state_min = ssd_minimal_discrete( + X * dt.unsqueeze(-1), A * dt, B, C, block_len=full_length // 4 + ) + + # internal function that outputs a cont batch of examples + # given a tuple of lengths for each example in the batch + # e.g., example_lens=(8, 4) means take 8 samples from first eg, + # 4 examples from second eg, etc + def get_continuous_batch(example_lens: tuple[int, ...]): + + indices = [] + for i, x in enumerate(example_lens): + c = last_taken.get(i, 0) + indices.append((c, c + x)) + last_taken[i] = (c + x) % full_length + exhausted[i] = last_taken[i] == 0 + + return ( + torch.concat([x[i, s:e] for i, (s, e) in enumerate(indices)]).unsqueeze(0) + for x in (dt, X, B, C) + ) + + # internal function that maps "n" to the appropriate right boundary + # value when forming continuous batches from examples of length given + # by "full_length". + # - e.g., when n > full_length, returns n % full_length + # when n == full_length, returns full_length + def end_boundary(n: int): + return n - ((n - 1) // full_length) * full_length + + IND_E = None + for spec in example_lens_by_batch: + + # get the (maybe partial) example seen in this cont batch + dt2, X2, B2, C2 = get_continuous_batch(spec) + + # get the metadata + cu_seqlens = torch.tensor((0,) + spec, device=device).cumsum(dim=0) + seq_idx = torch.zeros( + cu_seqlens[-1], dtype=torch.int32, device=cu_seqlens.device + ) + for i, (srt, end) in enumerate( + zip( + cu_seqlens, + cu_seqlens[1:], + ) + ): + seq_idx[srt:end] = i + + # for cont batch + if IND_E is None: + IND_S = [0 for _ in range(len(spec))] + else: + IND_S = [x % full_length for x in IND_E] + IND_E = [end_boundary(x + y) for x, y in zip(IND_S, spec)] + + yield ( + ( + [Y_min[s, IND_S[s] : IND_E[s]] for s in range(num_examples)] + if return_naive_ref + else None + ), + cu_seqlens, + seq_idx.unsqueeze(0), + (A, dt2, X2, B2, C2), + ) + + +SINGLE_ITYPE = [torch.float32, torch.float16, torch.bfloat16] +SINGLE_NHEADS = [3, 4, 11, 16, 32] +SINGLE_DHEAD = [5, 8, 19, 32, 128] +SINGLE_SEQ_LEN_CHUNK_SIZE = [(112, 16), (128, 32)] + +if is_in_ci(): + SINGLE_ITYPE = [torch.float32, torch.bfloat16] + SINGLE_NHEADS = [3, 32] + SINGLE_DHEAD = [5, 128] + SINGLE_SEQ_LEN_CHUNK_SIZE = [(112, 16)] + + +@pytest.mark.parametrize("itype", SINGLE_ITYPE) +@pytest.mark.parametrize("n_heads", SINGLE_NHEADS) +@pytest.mark.parametrize("d_head", SINGLE_DHEAD) +@pytest.mark.parametrize("seq_len_chunk_size", SINGLE_SEQ_LEN_CHUNK_SIZE) +def test_mamba_chunk_scan_single_example(d_head, n_heads, seq_len_chunk_size, itype): + device = get_device() + if device not in ["cuda", "xpu"]: + pytest.skip("Test only supports CUDA and XPU devices") + + # this tests the kernels on a single example (no batching) + + # TODO: the bfloat16 case requires higher thresholds. To be investigated + + if itype == torch.bfloat16: + atol, rtol = 5e-2, 5e-2 + else: + atol, rtol = 8e-3, 5e-3 + + # set seed + batch_size = 1 # batch_size + # ssd_minimal_discrete requires chunk_size divide seqlen + # - this is only required for generating the reference seqs, + # it is not an operational limitation. + seqlen, chunk_size = seq_len_chunk_size + + A, dt, X, B, C = generate_random_inputs(batch_size, seqlen, n_heads, d_head, itype) + + Y_min, final_state_min = ssd_minimal_discrete( + X * dt.unsqueeze(-1), A * dt, B, C, chunk_size + ) + Y = torch.empty_like(X) + final_state = mamba_chunk_scan_combined( + X, dt, A, B, C, chunk_size, D=None, return_final_states=True, out=Y + ) + + # just test the last in sequence + torch.testing.assert_close(Y[:, -1], Y_min[:, -1], atol=atol, rtol=rtol) + + # just test the last head + # NOTE, in the kernel we always cast states to fp32 + torch.testing.assert_close( + final_state[:, -1], + final_state_min[:, -1].to(torch.float32), + atol=atol, + rtol=rtol, + ) + + +BATCHED_ITYPE = [torch.float32, torch.float16] +BATCHED_NHEADS = [4, 8, 13] +BATCHED_DHEAD = [5, 16, 21, 32] + +if is_in_ci(): + BATCHED_ITYPE = [torch.float32] + BATCHED_NHEADS = [4, 13] + BATCHED_DHEAD = [5, 32] + + +@pytest.mark.parametrize("itype", BATCHED_ITYPE) +@pytest.mark.parametrize("n_heads", BATCHED_NHEADS) +@pytest.mark.parametrize("d_head", BATCHED_DHEAD) +@pytest.mark.parametrize( + "seq_len_chunk_size_cases", + [ + # small-ish chunk_size (8) + (64, 8, 2, [(64, 32), (64, 32)]), + (64, 8, 2, [(32, 32), (32, 32), (32, 32)]), + (64, 8, 2, [(8, 8), (8, 8), (8, 8)]), # chunk size boundary + ( + 64, + 8, + 2, + [(4, 4), (4, 4), (4, 4), (4, 4)], + ), # chunk_size larger than cont batches + ( + 64, + 8, + 5, + [ + (64, 32, 16, 8, 8), + (8, 16, 32, 16, 8), + (8, 8, 16, 32, 16), + ], + ), # mode examples with varied lengths + # large-ish chunk_size (256) + (64, 256, 1, [(5,), (1,), (1,), (1,)]), # irregular sizes with small sequences + ( + 64, + 256, + 2, + [(5, 30), (1, 2), (1, 2), (1, 2)], + ), # irregular sizes with small sequences + # we also need to test some large seqlen + # to catch errors with init states decay + (768, 128, 2, [(138, 225), (138, 225)]), + ], +) +def test_mamba_chunk_scan_cont_batch(d_head, n_heads, seq_len_chunk_size_cases, itype): + device = get_device() + if device not in ["cuda", "xpu"]: + pytest.skip("Test only supports CUDA and XPU devices") + + # this test with multiple examples in a continuous batch + # (i.e. chunked prefill) + + seqlen, chunk_size, num_examples, cases = seq_len_chunk_size_cases + + # This test can have larger error for longer sequences + if seqlen > 256: + atol, rtol = 1e-2, 5e-3 + else: + atol, rtol = 5e-3, 5e-3 + + # hold state during the cutting process so we know if an + # example has been exhausted and needs to cycle + last_taken: dict = {} # map: eg -> pointer to last taken sample + exhausted: dict = {} # map: eg -> boolean indicating example is exhausted + + states = None + for ( + Y_min, + cu_seqlens, + seq_idx, + (A, dt, X, B, C), + ) in generate_continuous_batched_examples( + cases, num_examples, seqlen, last_taken, exhausted, n_heads, d_head, itype + ): + + chunk_indices, chunk_offsets = ( + Mamba2Metadata._query_start_loc_to_chunk_indices_offsets( + cu_seqlens, chunk_size, cu_seqlens[-1] + ) + ) + + Y = torch.empty_like(X) + new_states = mamba_chunk_scan_combined( + X, + dt, + A, + B, + C, + chunk_size, + D=None, + cu_seqlens=cu_seqlens, + seq_idx=seq_idx, + chunk_indices=chunk_indices, + chunk_offsets=chunk_offsets, + return_varlen_states=True, + initial_states=states, + out=Y, + ) + + # just test the last in sequence + for i in range(num_examples): + + # just test one dim and dstate + Y_eg = Y[0, cu_seqlens[i] : cu_seqlens[i + 1], 0, 0] + Y_min_eg = Y_min[i][:, 0, 0] + torch.testing.assert_close(Y_eg, Y_min_eg, atol=atol, rtol=rtol) + + # update states + states = new_states + for i, clear in exhausted.items(): + if clear: + states[i].fill_(0.0) + exhausted[i] = False + + +@pytest.mark.parametrize("chunk_size", [8, 256]) +@pytest.mark.parametrize( + "seqlens", + [ + (16, 2, 8, 13), + (270, 88, 212, 203), + (16, 20), + ], +) +def test_mamba_chunk_scan_cont_batch_prefill_chunking(chunk_size, seqlens): + device = get_device() + if device not in ["cuda", "xpu"]: + pytest.skip("Test only supports CUDA and XPU devices") + + # This test verifies the correctness of the chunked prefill implementation + # in the mamba2 ssd kernels, by comparing concatenation (in the sequence + # dimension) of chunked results with the full sequence result. + # It is different from test_mamba_chunk_scan_cont_batch by: + # 1. Not using the naive torch implementation (ssd_minimal_discrete) to get + # reference outputs. Instead, it compares chunked kernel outputs to full + # sequence kernel outputs. This is the most straightforward way to + # assert chunked prefill correctness. + # 2. It focuses on cases where sequences change in the middle of mamba + # chunks, and not necessarily on chunk boundaries. + + max_seqlen = max(seqlens) + # This test can have larger error for longer sequences + if max_seqlen > 256: + atol, rtol = 1e-2, 5e-3 + else: + atol, rtol = 5e-3, 5e-3 + + num_sequences = len(seqlens) + n_heads = 16 + d_head = 64 + itype = torch.float32 + + # hold state during the cutting process so we know if an + # example has been exhausted and needs to cycle + last_taken: dict = {} # map: eg -> pointer to last taken sample + exhausted: dict = {} # map: eg -> boolean indicating example is exhausted + _, cu_seqlens, seq_idx, (A, dt, X, B, C) = next( + generate_continuous_batched_examples( + [seqlens], + num_sequences, + max_seqlen, + last_taken, + exhausted, + n_heads, + d_head, + itype, + return_naive_ref=False, + ) + ) + seqlens = torch.tensor(seqlens, dtype=torch.int32, device=X.device) + device = X.device + + ## full seqlen computation + chunk_indices, chunk_offsets = ( + Mamba2Metadata._query_start_loc_to_chunk_indices_offsets( + cu_seqlens, chunk_size, cu_seqlens[-1] + ) + ) + Y_ref = torch.empty_like(X) + state_ref = mamba_chunk_scan_combined( + X, + dt, + A, + B, + C, + chunk_size, + D=None, + cu_seqlens=cu_seqlens, + seq_idx=seq_idx, + chunk_indices=chunk_indices, + chunk_offsets=chunk_offsets, + return_varlen_states=True, + initial_states=None, + out=Y_ref, + ) + + ## chunked seqlen computation + # first chunk + chunked_seqlens = seqlens // 2 + chunked_cu_seqlens = torch.cat( + [torch.tensor([0], device=device), torch.cumsum(chunked_seqlens, dim=0)], dim=0 + ) + chunked_seq_idx = ( + torch.repeat_interleave( + torch.arange(len(chunked_seqlens), device=device), + chunked_seqlens, + output_size=chunked_cu_seqlens[-1], + ) + .unsqueeze(0) + .to(torch.int32) + ) + chunked_input_seq_len = chunked_cu_seqlens[-1] + X_chunked = torch.zeros_like(X)[:, :chunked_input_seq_len, ...] + dt_chunked = torch.zeros_like(dt)[:, :chunked_input_seq_len, ...] + B_chunked = torch.zeros_like(B)[:, :chunked_input_seq_len, ...] + C_chunked = torch.zeros_like(C)[:, :chunked_input_seq_len, ...] + for i in range(num_sequences): + # fmt: off + chunk_f = lambda x, i: x[:, cu_seqlens[i]:cu_seqlens[i] + chunked_seqlens[i], ...] # noqa: E501 + + X_chunked[:, chunked_cu_seqlens[i]:chunked_cu_seqlens[i+1], ...] = chunk_f(X, i) # noqa: E501 + dt_chunked[:, chunked_cu_seqlens[i]:chunked_cu_seqlens[i+1], ...] = chunk_f(dt, i) # noqa: E501 + B_chunked[:, chunked_cu_seqlens[i]:chunked_cu_seqlens[i+1], ...] = chunk_f(B, i) # noqa: E501 + C_chunked[:, chunked_cu_seqlens[i]:chunked_cu_seqlens[i+1], ...] = chunk_f(C, i) # noqa: E501 + # fmt: on + + chunk_indices, chunk_offsets = ( + Mamba2Metadata._query_start_loc_to_chunk_indices_offsets( + chunked_cu_seqlens, chunk_size, chunked_cu_seqlens[-1] + ) + ) + Y_partial = torch.empty_like(X_chunked) + partial_state = mamba_chunk_scan_combined( + X_chunked, + dt_chunked, + A, + B_chunked, + C_chunked, + chunk_size, + D=None, + cu_seqlens=chunked_cu_seqlens, + seq_idx=chunked_seq_idx, + chunk_indices=chunk_indices, + chunk_offsets=chunk_offsets, + return_varlen_states=True, + initial_states=None, + out=Y_partial, + ) + + # remaining chunk + remaining_chunked_seqlens = seqlens - chunked_seqlens + remaining_chunked_cu_seqlens = torch.cat( + [ + torch.tensor([0], device=device), + torch.cumsum(remaining_chunked_seqlens, dim=0), + ], + dim=0, + ) + remaining_chunked_seq_idx = ( + torch.repeat_interleave( + torch.arange(len(remaining_chunked_seqlens), device=device), + remaining_chunked_seqlens, + output_size=remaining_chunked_cu_seqlens[-1], + ) + .unsqueeze(0) + .to(torch.int32) + ) + remaining_chunked_input_seq_len = remaining_chunked_cu_seqlens[-1] + # fmt: off + remaining_X_chunked = torch.zeros_like(X)[:, :remaining_chunked_input_seq_len, ...] # noqa: E501 + remaining_dt_chunked = torch.zeros_like(dt)[:, :remaining_chunked_input_seq_len, ...] # noqa: E501 + remaining_B_chunked = torch.zeros_like(B)[:, :remaining_chunked_input_seq_len, ...] # noqa: E501 + remaining_C_chunked = torch.zeros_like(C)[:, :remaining_chunked_input_seq_len, ...] # noqa: E501 + for i in range(num_sequences): + remaining_chunk_f = lambda x, i: x[:, cu_seqlens[i] + chunked_seqlens[i]:cu_seqlens[i+1], ...] # noqa: E501 + + remaining_X_chunked[:, remaining_chunked_cu_seqlens[i]:remaining_chunked_cu_seqlens[i+1], ...] = remaining_chunk_f(X, i) # noqa: E501 + remaining_dt_chunked[:, remaining_chunked_cu_seqlens[i]:remaining_chunked_cu_seqlens[i+1], ...] = remaining_chunk_f(dt, i) # noqa: E501 + remaining_B_chunked[:, remaining_chunked_cu_seqlens[i]:remaining_chunked_cu_seqlens[i+1], ...] = remaining_chunk_f(B, i) # noqa: E501 + remaining_C_chunked[:, remaining_chunked_cu_seqlens[i]:remaining_chunked_cu_seqlens[i+1], ...] = remaining_chunk_f(C, i) # noqa: E501 + + # assert input chunking is correct + concat_chunk_f = lambda pt1, pt2, i: torch.cat([ + pt1[:,chunked_cu_seqlens[i]:chunked_cu_seqlens[i+1],...], + pt2[:,remaining_chunked_cu_seqlens[i]:remaining_chunked_cu_seqlens[i+1],...], + ], + dim=1) + concat_batch_f = lambda pt1, pt2: torch.cat([concat_chunk_f(pt1, pt2, i) for i in range(num_sequences)], dim=1) # noqa: E501 + # fmt: on + + assert concat_batch_f(X_chunked, remaining_X_chunked).equal(X) + assert concat_batch_f(dt_chunked, remaining_dt_chunked).equal(dt) + assert concat_batch_f(B_chunked, remaining_B_chunked).equal(B) + assert concat_batch_f(C_chunked, remaining_C_chunked).equal(C) + + chunk_indices, chunk_offsets = ( + Mamba2Metadata._query_start_loc_to_chunk_indices_offsets( + remaining_chunked_cu_seqlens, chunk_size, remaining_chunked_cu_seqlens[-1] + ) + ) + + Y_chunked = torch.empty_like(remaining_X_chunked) + state_chunked = mamba_chunk_scan_combined( + remaining_X_chunked, + remaining_dt_chunked, + A, + remaining_B_chunked, + remaining_C_chunked, + chunk_size, + D=None, + cu_seqlens=remaining_chunked_cu_seqlens, + seq_idx=remaining_chunked_seq_idx, + chunk_indices=chunk_indices, + chunk_offsets=chunk_offsets, + return_varlen_states=True, + initial_states=partial_state, + out=Y_chunked, + ) + Y = concat_batch_f(Y_partial, Y_chunked) + + # kernel chunked is same as kernel overall + for i in range(num_sequences): + Y_seq = Y[:, cu_seqlens[i] : cu_seqlens[i + 1], ...] + Y_ref_seq = Y_ref[:, cu_seqlens[i] : cu_seqlens[i + 1], ...] + torch.testing.assert_close( + Y_seq[:, : chunked_seqlens[i], ...], + Y_ref_seq[:, : chunked_seqlens[i], ...], + atol=atol, + rtol=rtol, + msg=lambda x: f"seq{i} output part1 " + x, + ) # noqa: B023 + torch.testing.assert_close( + Y_seq[:, chunked_seqlens[i] :, ...], + Y_ref_seq[:, chunked_seqlens[i] :, ...], + atol=atol, + rtol=rtol, + msg=lambda x: f"seq{i} output part2 " + x, + ) # noqa: B023 + + state_seq = state_chunked[i] + state_seq_ref = state_ref[i] + torch.testing.assert_close( + state_seq, + state_seq_ref, + atol=atol, + rtol=rtol, + msg=lambda x: f"seq{i} state " + x, + ) # noqa: B023 + + +@pytest.mark.parametrize("itype", [torch.float32, torch.bfloat16]) +@pytest.mark.parametrize("n_heads", [4, 16]) +@pytest.mark.parametrize("d_head", [32, 64]) +@pytest.mark.parametrize("seq_len_chunk_size", [(128, 32), (256, 64)]) +def test_mamba_chunk_scan_intermediate_states( + d_head, + n_heads, + seq_len_chunk_size, + itype, +): + device = get_device() + if device not in ["cuda", "xpu"]: + pytest.skip("Test only supports CUDA and XPU devices") + + if itype == torch.bfloat16: + atol, rtol = 5e-2, 5e-2 + else: + atol, rtol = 8e-3, 5e-3 + + batch_size = 1 + seqlen, chunk_size = seq_len_chunk_size + + A, dt, X, B, C = generate_random_inputs(batch_size, seqlen, n_heads, d_head, itype) + + _, ref_final_state, ref_states = ssd_minimal_discrete( + X * dt.unsqueeze(-1), A * dt, B, C, chunk_size, return_intermediate_states=True + ) + + Y = torch.empty_like(X) + states, final_state = mamba_chunk_scan_combined( + X, + dt, + A, + B, + C, + chunk_size, + D=None, + return_intermediate_states=True, + return_final_states=True, + out=Y, + ) + + num_chunks = seqlen // chunk_size + assert states.shape == (batch_size, num_chunks, n_heads, d_head, d_head) + assert ref_states.shape == states.shape + + torch.testing.assert_close( + final_state[:, -1], + ref_final_state[:, -1].to(torch.float32), + atol=atol, + rtol=rtol, + ) + + for chunk_idx in range(num_chunks): + torch.testing.assert_close( + states[:, chunk_idx, -1], + ref_states[:, chunk_idx, -1].to(states.dtype), + atol=atol, + rtol=rtol, + msg=lambda x: f"chunk {chunk_idx} " + x, + ) + + +if __name__ == "__main__": + import sys + + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/layers/test_fla_layernorm_guard.py b/asian_ai/performance/SGLang/test/registered/layers/test_fla_layernorm_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..cde06e5da1fe621bbd0940561abffee4b8ebd18a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/layers/test_fla_layernorm_guard.py @@ -0,0 +1,396 @@ +from __future__ import annotations + +import socket +import sys +from dataclasses import dataclass + +import pytest +import torch +import torch.nn.functional as F + +from sglang.srt.layers.attention.fla.layernorm_gated import ( + _layer_norm_fwd as layer_norm_fwd, +) +from sglang.srt.layers.attention.fla.layernorm_gated import ( + layernorm_fn, + rms_norm_ref, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=60, + stage="base-b", + runner_config="2-gpu-large", + disabled="Temporarily disabled", +) + +# Optional dependency in sglang repo; skip collection cleanly if absent. +custom_all_reduce_utils = pytest.importorskip( + "sglang.srt.distributed.device_communicators.custom_all_reduce_utils" +) +parallel_state = pytest.importorskip("sglang.srt.distributed.parallel_state") + +update_environment_variables = custom_all_reduce_utils.update_environment_variables +init_distributed_environment = parallel_state.init_distributed_environment +initialize_model_parallel = parallel_state.initialize_model_parallel + +NUM_GPUS = 2 + + +def _find_free_port() -> int: + # Avoid hard-coded port collisions when pytest runs tests in parallel. + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("localhost", 0)) + s.listen(1) + return int(s.getsockname()[1]) + + +def _skip_if_no_cuda_or_not_enough_gpus(required_gpus: int = NUM_GPUS) -> None: + if not torch.cuda.is_available(): + pytest.skip("CUDA device not available") + if torch.cuda.device_count() < required_gpus: + pytest.skip(f"Need >= {required_gpus} GPUs, got {torch.cuda.device_count()}") + + +def _skip_if_dtype_unsupported(dtype: torch.dtype) -> None: + if dtype is torch.bfloat16 and not torch.cuda.is_bf16_supported(): + pytest.skip("bfloat16 not supported on this CUDA device") + + +def _setup_sglang_distributed( + local_rank: int, + world_size: int, + master_port: int, + dtype: torch.dtype, +) -> torch.device: + # Match sglang test style: set per-rank CUDA device + default dtype/device. + torch.manual_seed(0) + torch.cuda.manual_seed_all(0) + + device = torch.device(f"cuda:{local_rank}") + torch.cuda.set_device(device) + + if hasattr(torch, "set_default_device"): + torch.set_default_device(device) + if hasattr(torch, "set_default_dtype"): + torch.set_default_dtype(dtype) + + update_environment_variables( + { + "RANK": str(local_rank), + "LOCAL_RANK": str(local_rank), + "WORLD_SIZE": str(world_size), + "MASTER_ADDR": "localhost", + "MASTER_PORT": str(master_port), + } + ) + + init_distributed_environment( + world_size=world_size, rank=local_rank, local_rank=local_rank + ) + initialize_model_parallel(tensor_model_parallel_size=world_size) + + return device + + +def layer_norm_ref( + x: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None, + z: torch.Tensor | None = None, + eps: float = 1e-6, + group_size: int | None = None, + norm_before_gate: bool = True, + is_rms_norm: bool = False, +) -> torch.Tensor: + """Reference implementation for both LayerNorm and RMSNorm (supports optional gate + group norm).""" + if is_rms_norm: + return rms_norm_ref( + x, + weight, + bias, + z=z, + eps=eps, + group_size=group_size, + norm_before_gate=norm_before_gate, + upcast=True, + ) + + dtype = x.dtype + x_f = x.float() + w_f = weight.float() + b_f = bias.float() if bias is not None else None + z_f = z.float() if z is not None else None + + if z_f is not None and not norm_before_gate: + x_f = x_f * F.silu(z_f) + + if group_size is None: + mean = x_f.mean(dim=-1, keepdim=True) + var = (x_f - mean).square().mean(dim=-1, keepdim=True) + rstd = torch.rsqrt(var + eps) + out = (x_f - mean) * rstd * w_f + if b_f is not None: + out = out + b_f + else: + hidden = x_f.shape[-1] + assert hidden % group_size == 0 + ng = hidden // group_size + xg = x_f.view(*x_f.shape[:-1], ng, group_size) + mean = xg.mean(dim=-1, keepdim=True) + var = (xg - mean).square().mean(dim=-1, keepdim=True) + rstd = torch.rsqrt(var + eps) + xg = (xg - mean) * rstd + out = xg.reshape(*x_f.shape[:-1], hidden) * w_f + if b_f is not None: + out = out + b_f + + if z_f is not None and norm_before_gate: + out = out * F.silu(z_f) + + return out.to(dtype) + + +@dataclass(frozen=True) +class FwdCase: + name: str + with_gate: bool + norm_before_gate: bool + group_size: int | None + is_rms_norm: bool + + +CASES: list[FwdCase] = [ + FwdCase( + "layernorm", + with_gate=False, + norm_before_gate=True, + group_size=None, + is_rms_norm=False, + ), + FwdCase( + "rmsnorm", + with_gate=False, + norm_before_gate=True, + group_size=None, + is_rms_norm=True, + ), + FwdCase( + "layernorm_gate_pre", + with_gate=True, + norm_before_gate=True, + group_size=None, + is_rms_norm=False, + ), + FwdCase( + "layernorm_gate_post", + with_gate=True, + norm_before_gate=False, + group_size=None, + is_rms_norm=False, + ), + FwdCase( + "rmsnorm_gate_pre", + with_gate=True, + norm_before_gate=True, + group_size=None, + is_rms_norm=True, + ), + FwdCase( + "group_layernorm", + with_gate=False, + norm_before_gate=True, + group_size=128, + is_rms_norm=False, + ), + FwdCase( + "group_rmsnorm", + with_gate=False, + norm_before_gate=True, + group_size=128, + is_rms_norm=True, + ), +] + + +@pytest.mark.parametrize("num_tokens", [128]) +@pytest.mark.parametrize("hidden_size", [256]) +@pytest.mark.parametrize("dtype", [torch.bfloat16]) +@pytest.mark.parametrize("case", CASES, ids=lambda c: c.name) +def test_layernorm_guard_fwd_spawn( + num_tokens: int, + hidden_size: int, + dtype: torch.dtype, + case: FwdCase, + device: str = "cuda", +): + _skip_if_no_cuda_or_not_enough_gpus(NUM_GPUS) + _skip_if_dtype_unsupported(dtype) + + if case.group_size is not None and hidden_size % case.group_size != 0: + pytest.skip( + f"hidden_size {hidden_size} not divisible by group_size {case.group_size}" + ) + + master_port = _find_free_port() + world_size = NUM_GPUS + + torch.multiprocessing.spawn( + _layernorm_guard_fwd_worker, + args=( + world_size, + master_port, + num_tokens, + hidden_size, + dtype, + case, + device, + ), + nprocs=world_size, + join=True, + ) + + +def _layernorm_guard_fwd_worker( + local_rank: int, + world_size: int, + master_port: int, + num_tokens: int, + hidden_size: int, + dtype: torch.dtype, + case: FwdCase, + device: str, +): + device = _setup_sglang_distributed(local_rank, world_size, master_port, dtype) + + with torch.inference_mode(): + torch.manual_seed(42 + local_rank) + torch.cuda.manual_seed_all(42 + local_rank) + + x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) + z = ( + torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) + if case.with_gate + else None + ) + weight = torch.randn(hidden_size, dtype=dtype, device=device) + bias = ( + None + if case.is_rms_norm + else torch.randn(hidden_size, dtype=dtype, device=device) + ) + eps = 1e-6 + + out, mean, rstd = layer_norm_fwd( + x, + weight, + bias, + eps, + z=z, + group_size=case.group_size, + norm_before_gate=case.norm_before_gate, + is_rms_norm=case.is_rms_norm, + ) + + ref_out = layer_norm_ref( + x, + weight, + bias, + z=z, + eps=eps, + group_size=case.group_size, + norm_before_gate=case.norm_before_gate, + is_rms_norm=case.is_rms_norm, + ) + + assert out.shape == x.shape + assert out.dtype == x.dtype + torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2) + + # mean/rstd shape checks (same spirit as original vLLM tests) + if case.group_size is None: + if not case.is_rms_norm: + assert mean.shape == (num_tokens,) + assert rstd.shape == (num_tokens,) + else: + ngroups = hidden_size // case.group_size + if not case.is_rms_norm: + assert mean.shape == (ngroups * num_tokens,) + assert rstd.shape == (ngroups * num_tokens,) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16]) +def test_layernorm_guard_misc_spawn(dtype: torch.dtype, device: str = "cuda"): + _skip_if_no_cuda_or_not_enough_gpus(NUM_GPUS) + _skip_if_dtype_unsupported(dtype) + + master_port = _find_free_port() + world_size = NUM_GPUS + + torch.multiprocessing.spawn( + _layernorm_guard_misc_worker, + args=(world_size, master_port, dtype, device), + nprocs=world_size, + join=True, + ) + + +def _layernorm_guard_misc_worker( + local_rank: int, + world_size: int, + master_port: int, + dtype: torch.dtype, + device: str, +): + device = _setup_sglang_distributed(local_rank, world_size, master_port, dtype) + + with torch.inference_mode(): + torch.manual_seed(123 + local_rank) + torch.cuda.manual_seed_all(123 + local_rank) + + # 1) rows_per_block-like sizes + hidden_size = 1024 + weight = torch.randn(hidden_size, dtype=dtype, device=device) + bias = torch.randn(hidden_size, dtype=dtype, device=device) + eps = 1e-6 + for num_tokens in [513]: + x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) + out, _, _ = layer_norm_fwd(x, weight, bias, eps, z=None, is_rms_norm=False) + ref = layer_norm_ref(x, weight, bias, z=None, eps=eps, is_rms_norm=False) + torch.testing.assert_close(out, ref, atol=1e-2, rtol=1e-2) + + # 2) strided input (slice then contiguous) + num_tokens = 128 + x_large = torch.randn(num_tokens, hidden_size * 2, dtype=dtype, device=device) + x = x_large[:, :hidden_size] + x_contig = x.contiguous() + out, _, _ = layer_norm_fwd( + x_contig, weight, bias, eps, z=None, is_rms_norm=False + ) + ref = layer_norm_ref(x_contig, weight, bias, z=None, eps=eps, is_rms_norm=False) + torch.testing.assert_close(out, ref, atol=1e-2, rtol=1e-2) + + # 3) provided output buffer + num_tokens = 256 + x = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) + out_buf = torch.empty_like(x) + out, _, _ = layer_norm_fwd( + x, weight, bias, eps, z=None, out=out_buf, is_rms_norm=False + ) + assert out.data_ptr() == out_buf.data_ptr() + ref = layer_norm_ref(x, weight, bias, z=None, eps=eps, is_rms_norm=False) + torch.testing.assert_close(out, ref, atol=1e-2, rtol=1e-2) + + # 4) multidimensional input via autograd fn + for shape in [(4, 16, 1024)]: + hs = shape[-1] + x = torch.randn(*shape, dtype=dtype, device=device) + w = torch.randn(hs, dtype=dtype, device=device) + b = torch.randn(hs, dtype=dtype, device=device) + out = layernorm_fn(x, w, b, z=None, eps=eps) + ref = layer_norm_ref(x, w, b, z=None, eps=eps, is_rms_norm=False) + torch.testing.assert_close(out, ref, atol=1e-2, rtol=1e-2) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_chunked_sgmv_backend.py b/asian_ai/performance/SGLang/test/registered/lora/test_chunked_sgmv_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..daf90debe7db68722f6a7910e623b4bf3d3bef52 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_chunked_sgmv_backend.py @@ -0,0 +1,1255 @@ +import random +import unittest +from enum import Enum +from typing import List, Optional, Tuple + +import torch + +from sglang.srt.layers.logits_processor import LogitsMetadata, LogitsProcessor +from sglang.srt.lora.backend.chunked_backend import ChunkedSgmvLoRABackend +from sglang.srt.lora.triton_ops import ( + chunked_embedding_lora_a_forward, + chunked_sgmv_lora_expand_forward, + chunked_sgmv_lora_shrink_forward, + step_a_q_fwd, + step_a_v_fwd, + step_b_q_fwd, + step_b_v_fwd, +) +from sglang.srt.lora.triton_ops.chunked_sgmv_expand import _chunked_lora_expand_kernel +from sglang.srt.lora.triton_ops.chunked_sgmv_shrink import _chunked_lora_shrink_kernel +from sglang.srt.lora.utils import LoRABatchInfo, get_lm_head_pruned_lens +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.lora_utils import ( + reference_embedding_lora_a_shrink, + reference_sgmv_expand, + reference_sgmv_shrink, +) + +CHUNK_SIZE = 16 + +register_cuda_ci(est_time=60, suite="nightly-1-gpu", nightly=True) + + +def reset_kernel_cache(): + _chunked_lora_shrink_kernel._clear_cache() + _chunked_lora_expand_kernel._clear_cache() + + +class BatchComposition(Enum): + UNIFORM = "uniform" + MIXED = "mixed" + SKEWED = "skewed" + NONE = "_NO_LORA_" + + +class BatchMode(Enum): + PREFILL = "prefill" + DECODE = "decode" + TARGET_VERIFY = "verify" + + +class TestChunkedSGMV(unittest.TestCase): + + # Test configuration constants + RTOL = 1e-3 + ATOL = 1e-3 + DEFAULT_BATCH_SIZE = 8 + + def _compare_shrink_outputs( + self, + chunked_output: torch.Tensor, + reference_output: torch.Tensor, + seq_lengths: List[int], + lora_assignments: List[int], + batch_info: LoRABatchInfo, + num_slices: int, + test_name: str, + ): + """ + Compare only the valid portions of shrink outputs. + + The chunked SGMV shrink kernel only guarantees correctness for + output[seq_start:seq_end, :rank * num_slices] for each sequence. + """ + lora_ranks = batch_info.lora_ranks.cpu().numpy() + + token_offset = 0 + for seq_idx, (lora_idx, seq_len) in enumerate( + zip(lora_assignments, seq_lengths) + ): + if seq_len == 0: + continue + + rank = lora_ranks[lora_idx] + + if rank > 0: + # Only compare the valid columns for this sequence + valid_cols = num_slices * rank + + chunked_seq = chunked_output[ + token_offset : token_offset + seq_len, :valid_cols + ] + reference_seq = reference_output[ + token_offset : token_offset + seq_len, :valid_cols + ] + + torch.testing.assert_close( + chunked_seq, + reference_seq, + rtol=self.RTOL, + atol=self.ATOL, + msg=f"Shrink operation failed for {test_name}, sequence {seq_idx} ({lora_idx})", + ) + + token_offset += seq_len + + def setUp(self): + """Set up common test parameters""" + torch.manual_seed(42) + random.seed(42) + + self.device = torch.device("cuda") + self.dtype = torch.float16 + self.input_dim = 2560 # Hidden dimension + self.max_seq_len = 1024 + self.vocab_size = 32000 # Vocabulary size for embedding tests + + # LoRA configurations: name -> (rank, output_q, output_k, output_v) + self.lora_configs = { + "lora_A": (8, 4096, 1024, 1024), + "lora_B": (16, 4096, 1024, 1024), + "lora_C": (32, 4096, 1024, 1024), + "_NO_LORA_": (0, 4096, 1024, 1024), + } + + # QKV slice offsets: 4096 (Q) + 1024 (K) + 1024 (V) = 6144 total + self.slice_offsets = torch.tensor( + [0, 4096, 5120, 6144], dtype=torch.int32, device=self.device + ) + self.max_slice_size = 4096 + + def generate_sequence_lengths( + self, + batch_size: int, + batch_mode: BatchMode = BatchMode.PREFILL, + min_len: int = 1, + max_len: int = None, + ) -> List[int]: + """Generate sequence lengths for a batch based on mode""" + if batch_mode == BatchMode.DECODE: + return [1] * batch_size + else: + if max_len is None: + max_len = self.max_seq_len + return [random.randint(min_len, max_len) for _ in range(batch_size)] + + def create_lora_weights( + self, lora_name: str, include_missing_k: bool = False + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Create LoRA A and B weights for given configuration""" + rank, out_q, out_k, out_v = self.lora_configs[lora_name] + + if rank == 0: + lora_a = torch.empty( + 0, self.input_dim, dtype=self.dtype, device=self.device + ) + lora_b = torch.empty( + out_q + out_k + out_v, 0, dtype=self.dtype, device=self.device + ) + return lora_a, lora_b + + # Create LoRA A weights (3 slices for QKV) + lora_a = torch.randn( + 3 * rank, self.input_dim, dtype=self.dtype, device=self.device + ) + + if include_missing_k: + lora_a[rank : 2 * rank, :] = 0.0 + + # Create LoRA B weights (stacked Q, K, V) + total_output_dim = out_q + out_k + out_v + lora_b = torch.randn( + total_output_dim, rank, dtype=self.dtype, device=self.device + ) + + if include_missing_k: + lora_b[out_q : out_q + out_k, :] = 0.0 + + return lora_a, lora_b + + def create_batch_info( + self, + lora_names: List[str], + seq_lengths: List[int], + lora_assignments: List[Optional[int]], + batch_mode: BatchMode = BatchMode.PREFILL, + ) -> LoRABatchInfo: + """Create LoRABatchInfo using the same logic as chunked backend""" + lora_ranks = [self.lora_configs[name][0] for name in lora_names] + + def create_mock_batch(): + # Create a minimal mock ForwardBatch for the test + class MockForwardBatch: + def __init__(self, batch_size, seq_lengths, device): + self.batch_size = batch_size + self.extend_seq_lens = torch.tensor( + seq_lengths, dtype=torch.int32, device=device + ) + self.extend_seq_lens_cpu = seq_lengths + self.forward_mode = MockForwardMode() + + class MockForwardMode: + def is_extend(self): + return batch_mode == BatchMode.PREFILL + + def is_decode(self): + return batch_mode == BatchMode.DECODE + + def is_target_verify(self): + return batch_mode == BatchMode.TARGET_VERIFY + + def is_prefill(self): + return self.is_extend() + + return MockForwardBatch(len(seq_lengths), seq_lengths, self.device) + + mock_batch = create_mock_batch() + + # Use the same functions as chunked backend + permutation, weights_reordered = ChunkedSgmvLoRABackend._get_permutation( + lora_assignments, mock_batch + ) + + # Create a minimal backend instance to access _get_segments_info + mock_server_args = type( + "ServerArgs", (object,), {"max_lora_chunk_size": "MOCK_NEVER_USED"} + ) + mock_backend = ChunkedSgmvLoRABackend( + max_loras_per_batch=8, device=self.device, server_args=mock_server_args + ) + weight_indices_list, seg_indptr = mock_backend._get_segments_info( + weights_reordered, + chunk_size=CHUNK_SIZE, + ) + + scalings = [1.0] * len(lora_names) + seg_indptr_tensor = seg_indptr.to(self.device) + weight_indices_tensor = weight_indices_list.to(self.device) + lora_ranks_tensor = ( + torch.tensor(lora_ranks, dtype=torch.int32, device=self.device) + if lora_ranks + else torch.empty(0, dtype=torch.int32, device=self.device) + ) + scalings_tensor = ( + torch.tensor(scalings, dtype=torch.float32, device=self.device) + if scalings + else torch.empty(0, dtype=torch.float32, device=self.device) + ) + permutation_tensor = permutation.to( + self.device, dtype=torch.int32 + ) # Convert to int32 for LoRABatchInfo + seq_lens_tensor = torch.tensor( + seq_lengths, dtype=torch.int32, device=self.device + ) + + return LoRABatchInfo( + use_cuda_graph=False, + bs=len(seq_lengths), + num_segments=len(weight_indices_list), # Number of segments, not sequences! + seg_indptr=seg_indptr_tensor, + weight_indices=weight_indices_tensor, + lora_ranks=lora_ranks_tensor, + scalings=scalings_tensor, + seg_lens=seq_lens_tensor, # Original sequence lengths for reference + max_len=CHUNK_SIZE, + permutation=permutation_tensor, # Token reordering permutation + ) + + def stack_lora_weights( + self, weight_list: List[torch.Tensor], is_lora_a: bool + ) -> torch.Tensor: + """Stack LoRA weights from different adapters into a single tensor""" + if not weight_list: + return torch.empty(0, 0, 0, dtype=self.dtype, device=self.device) + + first_non_empty = next((w for w in weight_list if w.numel() > 0), None) + if first_non_empty is None: + return torch.empty( + len(weight_list), 0, 0, dtype=self.dtype, device=self.device + ) + if is_lora_a: + # LoRA A: (slice_num * rank, input_dim) -> (num_loras, slice_num * max_rank, input_dim) + max_rank = max(w.shape[0] // 3 if w.numel() > 0 else 0 for w in weight_list) + final_shape = (len(weight_list), 3 * max_rank, self.input_dim) + else: + # LoRA B: (output_dim, rank) -> (num_loras, output_dim, max_rank) + max_rank = max(w.shape[1] if w.numel() > 0 else 0 for w in weight_list) + output_dim = first_non_empty.shape[0] + final_shape = (len(weight_list), output_dim, max_rank) + + stacked = torch.zeros(final_shape, dtype=self.dtype, device=self.device) + + for i, weight in enumerate(weight_list): + if weight.numel() > 0: + if is_lora_a: + stacked[i, : weight.shape[0], :] = weight + else: + stacked[i, :, : weight.shape[1]] = weight + + return stacked + + def create_embedding_lora_a_weights(self, lora_ranks: torch.Tensor) -> torch.Tensor: + """Create LoRA A weights for embedding lookup. + + Args: + lora_ranks: Tensor of ranks for each LoRA adapter + + Returns: + Tensor of shape (num_loras, max_rank, vocab_size) + """ + lora_ranks_cpu = lora_ranks.cpu().numpy() + num_loras = len(lora_ranks_cpu) + max_rank = int(lora_ranks_cpu.max()) if num_loras > 0 else 0 + + if max_rank == 0: + return torch.empty( + num_loras, 0, self.vocab_size, dtype=self.dtype, device=self.device + ) + + weights = torch.zeros( + num_loras, max_rank, self.vocab_size, dtype=self.dtype, device=self.device + ) + + for i, rank in enumerate(lora_ranks_cpu): + if rank > 0: + weights[i, :rank, :] = torch.randn( + rank, self.vocab_size, dtype=self.dtype, device=self.device + ) + + return weights + + def create_test_input_ids(self, total_tokens: int) -> torch.Tensor: + """Create random token IDs for embedding test.""" + return torch.randint( + 0, self.vocab_size, (total_tokens,), dtype=torch.int64, device=self.device + ) + + def create_test_batch( + self, + batch_composition: BatchComposition, + batch_size: int, + batch_mode: BatchMode = BatchMode.PREFILL, + include_missing_k: bool = False, + ) -> Tuple[ + torch.Tensor, + List[Tuple[torch.Tensor, torch.Tensor]], + LoRABatchInfo, + List[int], + List[str], + ]: + """Create test batch with specified composition and mode""" + + # Reset kernel cache to avoid cross-test contamination + reset_kernel_cache() + + seq_lengths = self.generate_sequence_lengths( + batch_size, batch_mode, 1, self.max_seq_len + ) + if batch_composition == BatchComposition.UNIFORM: + lora_names = ["lora_A"] + lora_assignments = [lora_names.index("lora_A")] * batch_size + elif batch_composition == BatchComposition.MIXED: + lora_names = ["lora_A", "lora_B", "lora_C", None] + lora_assignments = [(i % len(lora_names)) for i in range(batch_size)] + elif batch_composition == BatchComposition.SKEWED: + lora_names = ["lora_A", "lora_B"] + num_minority = max(1, batch_size // 8) + lora_assignments = [lora_names.index("lora_A")] * num_minority + [ + lora_names.index("lora_B") + ] * (batch_size - num_minority) + random.shuffle(lora_assignments) + elif batch_composition == BatchComposition.NONE: + lora_names = [None] + lora_assignments = [0] * batch_size + else: + raise ValueError(f"Unknown batch composition: {batch_composition}") + + total_seq_len = sum(seq_lengths) + x = torch.randn( + total_seq_len, self.input_dim, dtype=self.dtype, device=self.device + ) + + normalized_lora_names = [ + "_NO_LORA_" if name is None else name for name in lora_names + ] + weights = [] + for lora_name in normalized_lora_names: + weights.append(self.create_lora_weights(lora_name, include_missing_k)) + + batch_info = self.create_batch_info( + normalized_lora_names, seq_lengths, lora_assignments, batch_mode + ) + + return x, weights, batch_info, seq_lengths, lora_assignments + + def run_test_comparison( + self, + x: torch.Tensor, + weights: List[Tuple[torch.Tensor, torch.Tensor]], + batch_info: LoRABatchInfo, + seq_lengths: List[int], + lora_assignments: List[int], + test_name: str, + ): + """Run comparison between chunked and reference implementations""" + if not weights: # Handle case with no LoRA weights + return + + lora_assignments_tensor = torch.tensor( + lora_assignments, dtype=torch.int32, device="cpu" + ) + seq_lengths_tensor = torch.tensor(seq_lengths, dtype=torch.int32, device="cpu") + lora_ranks_tensor = batch_info.lora_ranks.detach().cpu() + scalings_tensor = batch_info.scalings.detach().cpu() + + # Stack LoRA A weights + lora_a_weights = [weight[0] for weight in weights] + stacked_lora_a = self.stack_lora_weights(lora_a_weights, is_lora_a=True) + + # Stack LoRA B weights + lora_b_weights = [weight[1] for weight in weights] + stacked_lora_b = self.stack_lora_weights(lora_b_weights, is_lora_a=False) + + # Test shrink operation + chunked_shrink = chunked_sgmv_lora_shrink_forward( + x, stacked_lora_a, batch_info, num_slices=3 + ) + reference_shrink = reference_sgmv_shrink( + x, + stacked_lora_a, + lora_assignments_tensor, + seq_lengths_tensor, + lora_ranks_tensor, + scalings_tensor, + num_slices=3, + ) + + # Only compare valid portions of shrink output (first rank * num_slices columns per sequence) + self._compare_shrink_outputs( + chunked_shrink, + reference_shrink, + seq_lengths, + lora_assignments, + batch_info, + num_slices=3, + test_name=test_name, + ) + + # Test expand operation + chunked_expand = chunked_sgmv_lora_expand_forward( + reference_shrink, + stacked_lora_b, + batch_info, + self.slice_offsets, + self.max_slice_size, + base_output=None, + ) + reference_expand = reference_sgmv_expand( + reference_shrink, + stacked_lora_b, + lora_assignments_tensor, + seq_lengths_tensor, + lora_ranks_tensor, + self.slice_offsets, + ) + + torch.testing.assert_close( + chunked_expand, + reference_expand, + rtol=self.RTOL, + atol=self.ATOL, + msg=f"Expand operation failed for {test_name}", + ) + + # === Basic Operations Tests === + + def test_shrink_basic(self): + """Test basic shrink operation against PyTorch reference""" + for batch_size in [1, 2, 16, 64]: + with self.subTest(batch_size=batch_size): + x, weights, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch(BatchComposition.UNIFORM, batch_size) + ) + + lora_assignments_tensor = torch.tensor( + lora_assignments, dtype=torch.int32, device="cpu" + ) + seq_lengths_tensor = torch.tensor( + seq_lengths, dtype=torch.int32, device="cpu" + ) + lora_ranks_tensor = batch_info.lora_ranks.detach().cpu() + scalings_tensor = batch_info.scalings.detach().cpu() + + lora_a_weights = [weight[0] for weight in weights] + stacked_lora_a = self.stack_lora_weights(lora_a_weights, is_lora_a=True) + + chunked_shrink = chunked_sgmv_lora_shrink_forward( + x, stacked_lora_a, batch_info, num_slices=3 + ) + reference_shrink = reference_sgmv_shrink( + x, + stacked_lora_a, + lora_assignments_tensor, + seq_lengths_tensor, + lora_ranks_tensor, + scalings_tensor, + num_slices=3, + ) + + torch.testing.assert_close( + chunked_shrink, reference_shrink, rtol=self.RTOL, atol=self.ATOL + ) + + # Test chunked embedding LoRA A forward + # Create embedding-specific LoRA A weights with shape (num_loras, rank, vocab_size) + embedding_lora_a = self.create_embedding_lora_a_weights( + batch_info.lora_ranks + ) + + # Create input_ids (token indices) instead of hidden states + total_tokens = x.shape[0] + input_ids = self.create_test_input_ids(total_tokens) + + chunked_shrink_embeddings = chunked_embedding_lora_a_forward( + input_ids, embedding_lora_a, batch_info, self.vocab_size + ) + + reference_shrink_embeddings = reference_embedding_lora_a_shrink( + input_ids, + embedding_lora_a, + lora_assignments_tensor, + seq_lengths_tensor, + lora_ranks_tensor, + scalings_tensor, + self.vocab_size, + ) + torch.testing.assert_close( + chunked_shrink_embeddings, + reference_shrink_embeddings, + rtol=self.RTOL, + atol=self.ATOL, + msg=f"Shrink test embedding loRA A operation failed for batch_size={batch_size}", + ) + + def test_expand_basic(self): + """Test basic expand operation against PyTorch reference""" + for batch_size in [1, 2, 16, 64]: + with self.subTest(batch_size=batch_size): + x, weights, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch(BatchComposition.UNIFORM, batch_size) + ) + + lora_assignments_tensor = torch.tensor( + lora_assignments, dtype=torch.int32, device="cpu" + ) + seq_lengths_tensor = torch.tensor( + seq_lengths, dtype=torch.int32, device="cpu" + ) + lora_ranks_tensor = batch_info.lora_ranks.detach().cpu() + scalings_tensor = batch_info.scalings.detach().cpu() + + lora_a_weights = [weight[0] for weight in weights] + stacked_lora_a = self.stack_lora_weights(lora_a_weights, is_lora_a=True) + + intermediate = reference_sgmv_shrink( + x, + stacked_lora_a, + lora_assignments_tensor, + seq_lengths_tensor, + lora_ranks_tensor, + scalings_tensor, + num_slices=3, + ) + + lora_b_weights = [weight[1] for weight in weights] + stacked_lora_b = self.stack_lora_weights( + lora_b_weights, is_lora_a=False + ) + + chunked_expand = chunked_sgmv_lora_expand_forward( + intermediate, + stacked_lora_b, + batch_info, + self.slice_offsets, + self.max_slice_size, + base_output=None, + ) + reference_expand = reference_sgmv_expand( + intermediate, + stacked_lora_b, + lora_assignments_tensor, + seq_lengths_tensor, + lora_ranks_tensor, + self.slice_offsets, + ) + + torch.testing.assert_close( + chunked_expand, reference_expand, rtol=self.RTOL, atol=self.ATOL + ) + + # === QKV Operations Test === + + def test_qkv_missing_projections(self): + """Test QKV operations with missing k_proj (Qwen3 scenario)""" + for batch_size in [1, 2, 16, 64]: + with self.subTest(batch_size=batch_size): + x, weights, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch( + BatchComposition.MIXED, batch_size, include_missing_k=True + ) + ) + self.run_test_comparison( + x, + weights, + batch_info, + seq_lengths, + lora_assignments, + f"QKV missing k_proj batch_size={batch_size}", + ) + + def test_4_slice_gdn_qkvz(self): + """Test 4-slice shrink+expand operations (GDN in_proj_qkvz).""" + num_slices = 4 + # GDN-style: 4 slices with different sizes [2048, 2048, 4096, 4096] + slice_offsets = torch.tensor( + [0, 2048, 4096, 8192, 12288], dtype=torch.int32, device=self.device + ) + total_out = 12288 + max_slice_size = 4096 + + for batch_size in [1, 2, 16]: + with self.subTest(batch_size=batch_size): + # Build batch (reuse the 3-slice helper just for x, batch_info, etc.) + x, _, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch(BatchComposition.MIXED, batch_size) + ) + + # Build 4-slice LoRA weights and stack them manually + lora_names = [n for n in self.lora_configs if n != "_NO_LORA_"] + max_rank = max(self.lora_configs[n][0] for n in lora_names) + stacked_a = torch.zeros( + len(lora_names), + num_slices * max_rank, + self.input_dim, + dtype=self.dtype, + device=self.device, + ) + stacked_b = torch.zeros( + len(lora_names), + total_out, + max_rank, + dtype=self.dtype, + device=self.device, + ) + for i, name in enumerate(lora_names): + rank = self.lora_configs[name][0] + if rank > 0: + stacked_a[i, : num_slices * rank, :] = torch.randn( + num_slices * rank, + self.input_dim, + dtype=self.dtype, + device=self.device, + ) + stacked_b[i, :, :rank] = torch.randn( + total_out, rank, dtype=self.dtype, device=self.device + ) + + lora_assignments_tensor = torch.tensor( + lora_assignments, dtype=torch.int32, device="cpu" + ) + seq_lengths_tensor = torch.tensor( + seq_lengths, dtype=torch.int32, device="cpu" + ) + lora_ranks_tensor = batch_info.lora_ranks.detach().cpu() + scalings_tensor = batch_info.scalings.detach().cpu() + + # Shrink + chunked_shrink = chunked_sgmv_lora_shrink_forward( + x, stacked_a, batch_info, num_slices=num_slices + ) + reference_shrink = reference_sgmv_shrink( + x, + stacked_a, + lora_assignments_tensor, + seq_lengths_tensor, + lora_ranks_tensor, + scalings_tensor, + num_slices=num_slices, + ) + self._compare_shrink_outputs( + chunked_shrink, + reference_shrink, + seq_lengths, + lora_assignments, + batch_info, + num_slices=num_slices, + test_name=f"4-slice shrink bs={batch_size}", + ) + + # Expand + chunked_expand = chunked_sgmv_lora_expand_forward( + reference_shrink, + stacked_b, + batch_info, + slice_offsets, + max_slice_size, + base_output=None, + ) + reference_expand = reference_sgmv_expand( + reference_shrink, + stacked_b, + lora_assignments_tensor, + seq_lengths_tensor, + lora_ranks_tensor, + slice_offsets, + ) + torch.testing.assert_close( + chunked_expand, + reference_expand, + rtol=self.RTOL, + atol=self.ATOL, + msg=f"4-slice expand failed bs={batch_size}", + ) + + # === Batch Composition Tests === + + def test_uniform_lora_batch(self): + """All sequences use same LoRA, random sequence lengths""" + for batch_size in [1, 2, 16, 64]: + with self.subTest(batch_size=batch_size): + x, weights, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch(BatchComposition.UNIFORM, batch_size) + ) + self.run_test_comparison( + x, + weights, + batch_info, + seq_lengths, + lora_assignments, + f"uniform batch_size={batch_size}", + ) + + def test_evenly_mixed_lora_batch(self): + """Sequences evenly distributed across LoRAs, random lengths""" + for batch_size in [1, 2, 16, 64]: + with self.subTest(batch_size=batch_size): + x, weights, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch(BatchComposition.MIXED, batch_size) + ) + self.run_test_comparison( + x, + weights, + batch_info, + seq_lengths, + lora_assignments, + f"mixed batch_size={batch_size}", + ) + + def test_highly_skewed_lora_batch(self): + """Highly uneven LoRA distribution, random lengths""" + for batch_size in [1, 2, 16, 64]: + with self.subTest(batch_size=batch_size): + x, weights, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch(BatchComposition.SKEWED, batch_size) + ) + self.run_test_comparison( + x, + weights, + batch_info, + seq_lengths, + lora_assignments, + f"skewed batch_size={batch_size}", + ) + + # === Decode Mode Tests === + + def test_decode_uniform_lora_batch(self): + """Decode mode: All sequences use same LoRA, all length 1""" + for batch_size in [1, 2, 16, 64]: + with self.subTest(batch_size=batch_size): + x, weights, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch( + BatchComposition.UNIFORM, batch_size, BatchMode.DECODE + ) + ) + self.run_test_comparison( + x, + weights, + batch_info, + seq_lengths, + lora_assignments, + f"decode uniform batch_size={batch_size}", + ) + + def test_decode_mixed_lora_batch(self): + """Decode mode: Sequences distributed across LoRAs, all length 1""" + for batch_size in [1, 2, 16, 64]: + with self.subTest(batch_size=batch_size): + x, weights, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch( + BatchComposition.MIXED, batch_size, BatchMode.DECODE + ) + ) + self.run_test_comparison( + x, + weights, + batch_info, + seq_lengths, + lora_assignments, + f"decode mixed batch_size={batch_size}", + ) + + def test_decode_skewed_lora_batch(self): + """Decode mode: Highly uneven LoRA distribution, all length 1""" + for batch_size in [1, 2, 16, 64]: + with self.subTest(batch_size=batch_size): + x, weights, batch_info, seq_lengths, lora_assignments = ( + self.create_test_batch( + BatchComposition.SKEWED, batch_size, BatchMode.DECODE + ) + ) + self.run_test_comparison( + x, + weights, + batch_info, + seq_lengths, + lora_assignments, + f"decode skewed batch_size={batch_size}", + ) + + def _make_cuda_graph_batch_info(self, bs: int, num_loras: int) -> LoRABatchInfo: + return LoRABatchInfo( + use_cuda_graph=True, + bs=bs, + num_segments=None, + max_len=CHUNK_SIZE, + seg_lens=None, + seg_indptr=torch.zeros(bs + 1, dtype=torch.int32, device=self.device), + weight_indices=torch.zeros(bs, dtype=torch.int32, device=self.device), + lora_ranks=torch.zeros(num_loras, dtype=torch.int32, device=self.device), + scalings=torch.ones(num_loras, dtype=torch.float, device=self.device), + permutation=torch.arange(bs, dtype=torch.int32, device=self.device), + ) + + def _set_cuda_graph_segment_state( + self, + batch_info: LoRABatchInfo, + lora_ranks: List[int], + weight_indices: List[int], + seg_indptr: List[int], + ): + num_segments = len(weight_indices) + total_tokens = seg_indptr[-1] + device = batch_info.weight_indices.device + + batch_info.lora_ranks.zero_() + batch_info.lora_ranks[: len(lora_ranks)].copy_( + torch.tensor(lora_ranks, dtype=torch.int32, device=device) + ) + batch_info.weight_indices.zero_() + batch_info.weight_indices[:num_segments].copy_( + torch.tensor(weight_indices, dtype=torch.int32, device=device) + ) + batch_info.seg_indptr.fill_(total_tokens) + batch_info.seg_indptr[: num_segments + 1].copy_( + torch.tensor(seg_indptr, dtype=torch.int32, device=device) + ) + batch_info.num_segments = num_segments + + def _set_cuda_graph_capture_state(self, batch_info: LoRABatchInfo, bs: int): + self._set_cuda_graph_segment_state( + batch_info=batch_info, + lora_ranks=[0] * batch_info.lora_ranks.shape[0], + weight_indices=[0], + seg_indptr=[0, bs], + ) + + def _set_cuda_graph_replay_state( + self, batch_info: LoRABatchInfo, max_rank: int, bs: int + ): + self._set_cuda_graph_segment_state( + batch_info=batch_info, + lora_ranks=[max_rank] * batch_info.lora_ranks.shape[0], + weight_indices=[1, 2, 3, 4], + seg_indptr=[0, 2, 4, 6, bs], + ) + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA is required") + def test_cuda_graph_shrink_replay_with_more_segments_than_capture(self): + """CUDA graph replay must honor updated shrink segment metadata.""" + reset_kernel_cache() + + bs = 8 + num_loras = 5 + max_rank = 8 + input_dim = 64 + num_slices = 1 + + x = torch.randn(bs, input_dim, dtype=self.dtype, device=self.device) + weights = torch.randn( + num_loras, max_rank, input_dim, dtype=self.dtype, device=self.device + ) + batch_info = self._make_cuda_graph_batch_info(bs, num_loras) + + self._set_cuda_graph_replay_state(batch_info, max_rank, bs) + expected = chunked_sgmv_lora_shrink_forward( + x, weights, batch_info, num_slices=num_slices + ).clone() + torch.cuda.synchronize() + + self._set_cuda_graph_capture_state(batch_info, bs) + warmup_stream = torch.cuda.Stream() + warmup_stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(warmup_stream): + for _ in range(3): + chunked_sgmv_lora_shrink_forward( + x, weights, batch_info, num_slices=num_slices + ) + torch.cuda.current_stream().wait_stream(warmup_stream) + torch.cuda.synchronize() + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + captured_output = chunked_sgmv_lora_shrink_forward( + x, weights, batch_info, num_slices=num_slices + ) + + self._set_cuda_graph_replay_state(batch_info, max_rank, bs) + captured_output.zero_() + graph.replay() + torch.cuda.synchronize() + + torch.testing.assert_close( + captured_output[:, :max_rank], + expected[:, :max_rank], + rtol=self.RTOL, + atol=self.ATOL, + ) + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA is required") + def test_cuda_graph_expand_replay_with_more_segments_than_capture(self): + """CUDA graph replay must honor updated expand segment metadata.""" + reset_kernel_cache() + + bs = 8 + num_loras = 5 + max_rank = 8 + output_dim = 32 + slice_offsets = torch.tensor( + [0, output_dim], dtype=torch.int32, device=self.device + ) + + x = torch.randn(bs, max_rank, dtype=self.dtype, device=self.device) + weights = torch.randn( + num_loras, output_dim, max_rank, dtype=self.dtype, device=self.device + ) + base_output = torch.randn(bs, output_dim, dtype=self.dtype, device=self.device) + graph_base_output = base_output.clone() + batch_info = self._make_cuda_graph_batch_info(bs, num_loras) + + self._set_cuda_graph_replay_state(batch_info, max_rank, bs) + expected = chunked_sgmv_lora_expand_forward( + x, + weights, + batch_info, + slice_offsets, + output_dim, + base_output=base_output.clone(), + ).clone() + torch.cuda.synchronize() + + self._set_cuda_graph_capture_state(batch_info, bs) + warmup_stream = torch.cuda.Stream() + warmup_stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(warmup_stream): + for _ in range(3): + graph_base_output.copy_(base_output) + chunked_sgmv_lora_expand_forward( + x, + weights, + batch_info, + slice_offsets, + output_dim, + base_output=graph_base_output, + ) + torch.cuda.current_stream().wait_stream(warmup_stream) + torch.cuda.synchronize() + + graph_base_output.copy_(base_output) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + captured_output = chunked_sgmv_lora_expand_forward( + x, + weights, + batch_info, + slice_offsets, + output_dim, + base_output=graph_base_output, + ) + + self._set_cuda_graph_replay_state(batch_info, max_rank, bs) + graph_base_output.copy_(base_output) + graph.replay() + torch.cuda.synchronize() + + torch.testing.assert_close( + captured_output, + expected, + rtol=self.RTOL, + atol=self.ATOL, + ) + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA is required") + def test_prepare_lora_batch_cuda_graph_zero_length_tail(self): + """prepare_lora_batch must neutralize stale CUDA graph tail segments.""" + + class MockForwardBatch: + def __init__(self, batch_size): + self.batch_size = batch_size + self.forward_mode = ForwardMode.DECODE + + mock_server_args = type( + "ServerArgs", (object,), {"max_lora_chunk_size": CHUNK_SIZE} + ) + backend = ChunkedSgmvLoRABackend( + max_loras_per_batch=5, device=self.device, server_args=mock_server_args + ) + backend.init_cuda_graph_batch_info(max_bs_in_cuda_graph=8, num_tokens_per_bs=1) + + lora_ranks = [8] * 5 + scalings = [1.0] * 5 + backend.prepare_lora_batch( + forward_batch=MockForwardBatch(8), + weight_indices=[0, 1, 2, 3, 4, 0, 1, 2], + lora_ranks=lora_ranks, + scalings=scalings, + use_cuda_graph=True, + ) + backend.prepare_lora_batch( + forward_batch=MockForwardBatch(2), + weight_indices=[0, 0], + lora_ranks=lora_ranks, + scalings=scalings, + use_cuda_graph=True, + ) + torch.cuda.synchronize() + + batch_info = backend.batch_info + self.assertEqual(batch_info.num_segments, 1) + torch.testing.assert_close( + batch_info.weight_indices.cpu(), + torch.tensor([0] * 8, dtype=torch.int32), + ) + torch.testing.assert_close( + batch_info.seg_indptr.cpu(), + torch.tensor([0, 2, 2, 2, 2, 2, 2, 2, 2], dtype=torch.int32), + ) + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA is required") + def test_kv_b_cuda_graph_replay_with_more_segments_than_capture(self): + """Absorbed MLA kv_b LoRA kernels must replay dynamic segment metadata.""" + bs = 8 + num_loras = 5 + max_rank = 8 + num_heads = 2 + qk_nope_head_dim = 16 + v_head_dim = 16 + kv_lora_rank = 32 + full_k_per_head = qk_nope_head_dim + v_head_dim + + q_nope = torch.randn( + bs, num_heads, qk_nope_head_dim, dtype=self.dtype, device=self.device + ) + attn_output = torch.randn( + bs, num_heads, kv_lora_rank, dtype=self.dtype, device=self.device + ) + a_buf = torch.randn( + num_loras, max_rank, kv_lora_rank, dtype=self.dtype, device=self.device + ) + b_buf = torch.randn( + num_loras, + num_heads * full_k_per_head, + max_rank, + dtype=self.dtype, + device=self.device, + ) + base_q = torch.randn( + bs, num_heads, kv_lora_rank, dtype=self.dtype, device=self.device + ) + base_v = torch.randn( + bs, num_heads, v_head_dim, dtype=self.dtype, device=self.device + ) + graph_base_q = base_q.clone() + graph_base_v = base_v.clone() + batch_info = self._make_cuda_graph_batch_info(bs, num_loras) + + def run_kv_b(base_q_out, base_v_out): + q_lora_a = step_a_q_fwd(q_nope, b_buf, batch_info, full_k_per_head) + q_out = step_b_q_fwd(q_lora_a, a_buf, batch_info, base_q_out) + v_lora_a = step_a_v_fwd(attn_output, a_buf, batch_info) + v_out = step_b_v_fwd( + v_lora_a, + b_buf, + batch_info, + base_v_out, + qk_nope_head_dim, + v_head_dim, + ) + return q_out, v_out + + self._set_cuda_graph_replay_state(batch_info, max_rank, bs) + expected_q, expected_v = run_kv_b(base_q.clone(), base_v.clone()) + expected_q = expected_q.clone() + expected_v = expected_v.clone() + torch.cuda.synchronize() + + self._set_cuda_graph_capture_state(batch_info, bs) + warmup_stream = torch.cuda.Stream() + warmup_stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(warmup_stream): + for _ in range(3): + graph_base_q.copy_(base_q) + graph_base_v.copy_(base_v) + run_kv_b(graph_base_q, graph_base_v) + torch.cuda.current_stream().wait_stream(warmup_stream) + torch.cuda.synchronize() + + graph_base_q.copy_(base_q) + graph_base_v.copy_(base_v) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + captured_q, captured_v = run_kv_b(graph_base_q, graph_base_v) + + self._set_cuda_graph_replay_state(batch_info, max_rank, bs) + graph_base_q.copy_(base_q) + graph_base_v.copy_(base_v) + graph.replay() + torch.cuda.synchronize() + + torch.testing.assert_close( + captured_q, + expected_q, + rtol=self.RTOL, + atol=self.ATOL, + ) + torch.testing.assert_close( + captured_v, + expected_v, + rtol=self.RTOL, + atol=self.ATOL, + ) + + +class TestLmHeadPruningConsistency(unittest.TestCase): + """Verify get_lm_head_pruned_lens (LoRA) stays consistent with + LogitsProcessor._get_pruned_states (logits_processor). + + If this test fails, it likely means one side was changed without + updating the other. See cross-references in both functions. + """ + + def _make_mock_forward_batch( + self, + forward_mode, + extend_seq_lens_cpu, + return_logprob=False, + logprob_start_lens_cpu=None, + ): + class MockForwardBatch: + pass + + batch = MockForwardBatch() + batch.forward_mode = forward_mode + batch.batch_size = len(extend_seq_lens_cpu) + batch.return_logprob = return_logprob + batch.extend_seq_lens_cpu = extend_seq_lens_cpu + batch.extend_logprob_start_lens_cpu = logprob_start_lens_cpu + return batch + + def _count_pruned_states_tokens( + self, + forward_mode, + extend_seq_lens_cpu, + return_logprob=False, + logprob_start_lens_cpu=None, + ): + """Call _get_pruned_states and return the number of output tokens.""" + total_tokens = sum(extend_seq_lens_cpu) + hidden_states = torch.zeros(total_tokens, 4) + + logits_meta = LogitsMetadata( + forward_mode=forward_mode, + extend_return_logprob=return_logprob, + extend_seq_lens=torch.tensor(extend_seq_lens_cpu, dtype=torch.int64), + extend_seq_lens_cpu=extend_seq_lens_cpu, + extend_logprob_start_lens_cpu=logprob_start_lens_cpu, + ) + + # _get_pruned_states does not use self, so pass None + result = LogitsProcessor._get_pruned_states( + None, hidden_states, None, None, logits_meta + ) + pruned_states = result[0] + return pruned_states.shape[0] + + def _assert_consistency( + self, + forward_mode, + extend_seq_lens_cpu, + return_logprob=False, + logprob_start_lens_cpu=None, + ): + mock_batch = self._make_mock_forward_batch( + forward_mode, + extend_seq_lens_cpu, + return_logprob, + logprob_start_lens_cpu, + ) + pruned_lens = get_lm_head_pruned_lens(mock_batch) + + actual_count = self._count_pruned_states_tokens( + forward_mode, + extend_seq_lens_cpu, + return_logprob, + logprob_start_lens_cpu, + ) + + if pruned_lens is None: + expected_count = sum(extend_seq_lens_cpu) + else: + expected_count = sum(pruned_lens) + + self.assertEqual( + expected_count, + actual_count, + f"get_lm_head_pruned_lens expects {expected_count} tokens, " + f"but _get_pruned_states produces {actual_count}. " + f"These functions must stay in sync — see their cross-reference comments.", + ) + + def test_extend_no_logprob(self): + self._assert_consistency(ForwardMode.EXTEND, [4, 5, 6]) + + def test_extend_with_logprob(self): + self._assert_consistency( + ForwardMode.EXTEND, + [4, 5, 6], + return_logprob=True, + logprob_start_lens_cpu=[0, 5, 3], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_embedding_lora_support.py b/asian_ai/performance/SGLang/test/registered/lora/test_embedding_lora_support.py new file mode 100644 index 0000000000000000000000000000000000000000..b159cfd255e5509ca009041ec4918ded200656f4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_embedding_lora_support.py @@ -0,0 +1,232 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +""" +Unit tests for LoRA support in embedding models. + +Validates that EmbeddingReqInput correctly handles LoRA fields through +normalization, batching, and request splitting. +""" + +import multiprocessing as mp +import unittest + +import numpy as np +import torch + +from sglang.srt.entrypoints.openai.protocol import EmbeddingRequest +from sglang.srt.managers.io_struct import EmbeddingReqInput, TokenizedEmbeddingReqInput +from sglang.srt.sampling.sampling_params import SamplingParams +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.runners import SRTRunner +from sglang.test.test_utils import DEFAULT_PORT_FOR_SRT_TEST_RUNNER, CustomTestCase + +# Test configuration (same model/LoRA as test_lora_hf_sgl_logprob_diff.py) +MODEL_PATH = "meta-llama/Llama-2-7b-hf" +LORA_PATH = "yushengsu/sglang_lora_logprob_diff_without_tuning" +LORA_BACKEND = "triton" +SIMILARITY_THRESHOLD = 0.9999 + +register_cuda_ci( + est_time=150, + suite="nightly-1-gpu", +) + + +class TestEmbeddingLoraSupport(unittest.TestCase): + """Test LoRA support in embedding request structures.""" + + def test_engine_encode_validates_enable_lora(self): + """Test Engine.encode() validates enable_lora before processing lora_path.""" + # Use a simple non-gated model for this validation test + with SRTRunner( + MODEL_PATH, + torch_dtype=torch.float16, + model_type="embedding", + port=DEFAULT_PORT_FOR_SRT_TEST_RUNNER, + ) as runner: + # Should raise ValueError because enable_lora was not set for the server + with self.assertRaises(ValueError) as context: + runner.engine.encode(prompt="Test", lora_path="fake-adapter") + + error_msg = str(context.exception) + self.assertIn("not enabled", error_msg.lower()) + self.assertIn("--enable-lora", error_msg) + self.assertIn("fake-adapter", error_msg) + + def test_embedding_lora_fields(self): + """Test LoRA fields exist and work correctly across all embedding structures.""" + # EmbeddingReqInput: fields exist, normalization expands single to batch, indexing works + req = EmbeddingReqInput( + text=["Hello", "World"], lora_path="my-adapter", lora_id=["id1", "id2"] + ) + self.assertIsNotNone(req.lora_path) + req.normalize_batch_and_arguments() + self.assertEqual(req.lora_path, ["my-adapter", "my-adapter"]) + self.assertEqual(req[0].lora_path, "my-adapter") + self.assertEqual(req[1].lora_id, "id2") + + # EmbeddingReqInput: mismatched list length raises error + req = EmbeddingReqInput(text=["Hello", "World", "Test"], lora_path=["adapter1"]) + with self.assertRaises(ValueError): + req.normalize_batch_and_arguments() + + # TokenizedEmbeddingReqInput and EmbeddingRequest have lora fields + tokenized = TokenizedEmbeddingReqInput( + input_text="Hello", + input_ids=[1, 2, 3], + image_inputs={}, + token_type_ids=[], + sampling_params=SamplingParams(), + lora_id="my-lora-id", + ) + self.assertEqual(tokenized.lora_id, "my-lora-id") + self.assertEqual( + EmbeddingRequest( + input="Hello", model="test", lora_path="adapter" + ).lora_path, + "adapter", + ) + + +class TestEmbeddingLoraHFComparison(CustomTestCase): + """Compare HF+LoRA vs SGLang+LoRA embedding outputs.""" + + @classmethod + def get_hf_embedding_with_lora(cls, model_path, lora_path, texts, torch_dtype): + """Get embeddings from HuggingFace model with LoRA adapter.""" + from peft import PeftModel + from transformers import AutoModelForCausalLM, AutoTokenizer + + # Load base model as CausalLM to match adapter's expected structure + base_model = AutoModelForCausalLM.from_pretrained( + model_path, + torch_dtype=torch_dtype, + trust_remote_code=True, + ).cuda() + + # Load LoRA adapter + model = PeftModel.from_pretrained(base_model, lora_path) + model.eval() + + tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + with torch.no_grad(): + inputs = tokenizer( + texts, padding=True, truncation=True, return_tensors="pt" + ).to("cuda") + + # Access the inner model (CausalLM wraps the base model) + outputs = model.model(**inputs, output_hidden_states=True) + hidden_states = outputs.hidden_states[-1] + + # Last token pooling with L2 normalization (matching SGLang) + attention_mask = inputs["attention_mask"] + last_token_indices = attention_mask.sum(dim=1) - 1 + batch_size = hidden_states.shape[0] + embeddings = hidden_states[ + torch.arange(batch_size, device="cuda"), last_token_indices + ] + embeddings = embeddings / embeddings.norm(dim=1, keepdim=True) + + # Cleanup + del model, base_model + torch.cuda.empty_cache() + + return embeddings.cpu().numpy() + + @classmethod + def get_sglang_embedding_with_lora(cls, model_path, lora_path, texts, torch_dtype): + """Get embeddings from SGLang with LoRA adapter.""" + with SRTRunner( + model_path, + torch_dtype=torch_dtype, + model_type="embedding", + lora_paths=[lora_path], + lora_backend=LORA_BACKEND, + port=DEFAULT_PORT_FOR_SRT_TEST_RUNNER, + trust_remote_code=True, + mem_fraction_static=0.88, + ) as runner: + # Call engine.encode directly with lora_path + response = runner.engine.encode(prompt=texts, lora_path=lora_path) + if isinstance(response, list): + embeddings = [r["embedding"] for r in response] + else: + embeddings = [response["embedding"]] + + return np.array(embeddings) + + @staticmethod + def cosine_similarity(a, b): + """Compute cosine similarity between vectors.""" + return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) + + def test_embedding_lora_hf_sglang_similarity(self): + """Test that HF+LoRA and SGLang+LoRA produce similar embeddings.""" + test_texts = [ + "Hello world", + "This is a test sentence for embedding comparison", + ] + + print(f"\nModel: {MODEL_PATH}") + print(f"LoRA: {LORA_PATH}") + + # Get SGLang embeddings first (before HF loads model into GPU) + # This order matches test_lora_hf_sgl_logprob_diff.py and avoids OOM + print("\nGetting SGLang embeddings...") + sglang_embeddings = self.get_sglang_embedding_with_lora( + MODEL_PATH, LORA_PATH, test_texts, torch.float16 + ) + + # Clear GPU memory + torch.cuda.empty_cache() + + # Get HF embeddings + print("Getting HF embeddings...") + hf_embeddings = self.get_hf_embedding_with_lora( + MODEL_PATH, LORA_PATH, test_texts, torch.float16 + ) + + # Compare embeddings + print("\nHF vs SGLang LoRA Embedding Comparison:") + similarities = [] + for i, (hf_emb, sgl_emb) in enumerate(zip(hf_embeddings, sglang_embeddings)): + sim = self.cosine_similarity(hf_emb, sgl_emb) + similarities.append(sim) + print(f" Text {i}: cosine similarity = {sim:.6f}") + self.assertGreater( + sim, + SIMILARITY_THRESHOLD, + f"Text {i} similarity {sim:.6f} below threshold {SIMILARITY_THRESHOLD}", + ) + + avg_similarity = np.mean(similarities) + print(f" Average similarity: {avg_similarity:.6f}") + print(f" Threshold: {SIMILARITY_THRESHOLD}") + + self.assertGreater( + avg_similarity, + SIMILARITY_THRESHOLD, + f"Average similarity {avg_similarity:.4f} below threshold {SIMILARITY_THRESHOLD}", + ) + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_fused_moe_lora_kernel.py b/asian_ai/performance/SGLang/test/registered/lora/test_fused_moe_lora_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..facf31a43942c740b406dd778884a3c47881e7db --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_fused_moe_lora_kernel.py @@ -0,0 +1,381 @@ +# Temporarily adapted from https://github.com/vllm-project/vllm/blob/main/tests/lora/test_fused_moe_lora_kernel.py, will optimize in future refactor +import random +import sys + +import pytest +import torch + +# ============================================================================== +# IMPORT PREBUILT KERNEL +# ============================================================================== +from sglang.jit_kernel.moe_lora_align import moe_lora_align_block_size +from sglang.srt.lora.triton_ops import fused_moe_lora +from sglang.srt.utils import set_random_seed +from sglang.test.ci.ci_register import register_cuda_ci + +# ============================================================================== + +register_cuda_ci(est_time=28, stage="base-b", runner_config="1-gpu-large") + + +def round_up(x, base): + return ((x + base - 1) // base) * base + + +def CEILDIV(x, y): + return (x + y - 1) // y + + +def assign_loras_to_tokens(num_tokens: int, num_sequences: int, max_loras: int): + """ + Split `num_tokens` into `num_sequences` sequences. + Each sequence randomly selects 1 LoRA index from [0, max_loras), + and all tokens in that sequence are assigned this LoRA index. + + Args: + num_tokens (int): Total number of tokens. + num_sequences (int): Number of sequences to split the tokens into. + max_loras (int): Total number of available LoRA modules. + + Returns: + token_lora_mapping (torch.Tensor): 1D tensor of shape [num_tokens] + seg_indptr (torch.Tensor): 1D tensor of shape [num_sequences + 1] + req_to_lora (torch.Tensor): 1D tensor of shape [num_sequences] + """ + assert num_sequences > 0 and max_loras > 0 + assert num_tokens >= num_sequences, "num_tokens must be >= num_sequences" + + # Compute token distribution per sequence (distribute remainder evenly) + tokens_per_seq = num_tokens // num_sequences + remainder = num_tokens % num_sequences + + token_lora_mapping = torch.empty(num_tokens, dtype=torch.int32) + seg_indptr = [0] + req_to_lora = [] + + start = 0 + for seq_idx in range(num_sequences): + # Determine the token range for this sequence + end = start + tokens_per_seq + (1 if seq_idx < remainder else 0) + + # Randomly select one LoRA ID for this sequence + lora_id = random.randint(0, max_loras - 1) + + # Assign the same LoRA ID to all tokens in this sequence + token_lora_mapping[start:end] = lora_id + + seg_indptr.append(end) + req_to_lora.append(lora_id) + + start = end + + seg_indptr = torch.tensor(seg_indptr, dtype=torch.int32) + req_to_lora = torch.tensor(req_to_lora, dtype=torch.int32) + + return token_lora_mapping, seg_indptr, req_to_lora + + +def assign_experts_to_tokens(num_tokens: int, num_experts: int, top_k_num: int): + """ + For each token, randomly select `top_k_num` distinct experts out of `num_experts`, + and assign normalized random weights that sum to 1. + + Args: + num_tokens (int): Total number of tokens. + num_experts (int): Total number of available experts. + top_k_num (int): Number of experts to select per token. + + Returns: + expert_indices (torch.Tensor): shape [num_tokens, top_k_num], + expert index for each token. + expert_weights (torch.Tensor): shape [num_tokens, top_k_num], + normalized weights (sum = 1 per row). + """ + assert top_k_num <= num_experts, "top_k_num must be <= num_experts" + + # Randomly select top_k_num distinct experts for each token + expert_indices = torch.empty((num_tokens, top_k_num), dtype=torch.int32) + for i in range(num_tokens): + # Randomly choose unique expert indices + selected = torch.randperm(num_experts)[:top_k_num] + expert_indices[i] = selected + + # Generate random weights and normalize along dim=1 + expert_weights = torch.rand((num_tokens, top_k_num), dtype=torch.float32) + expert_weights = expert_weights / expert_weights.sum(dim=1, keepdim=True) + + return expert_indices, expert_weights + + +def sample_data( + num_tokens: int, + num_sequences: int, + max_loras: int, + num_experts: int, + top_k_num: int, +): + topk_ids, topk_weights = assign_experts_to_tokens( + num_tokens, num_experts, top_k_num + ) + token_lora_mapping, seg_indptr, req_to_lora = assign_loras_to_tokens( + num_tokens, num_sequences, max_loras + ) + return topk_ids, topk_weights, token_lora_mapping, seg_indptr, req_to_lora + + +def use_fused_moe_lora_kernel( + topk_ids, + topk_weights, + seg_indptr, + req_to_lora, + max_lora_rank, + top_k_num, + lora_a_stacked, + lora_b_stacked, + hidden_states, + output, + max_loras, + num_experts, + block_size, + mul_routed_weight, + fully_sharded=False, + offset=0, +): + max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1) + max_num_tokens_padded = round_up(max_num_tokens_padded, block_size) + max_num_m_blocks = CEILDIV(max_num_tokens_padded, block_size) + + # Important: Ensure output tensors are on the same device as inputs + device = topk_ids.device + + # init output tensors + sorted_token_ids = torch.empty( + (max_loras * max_num_tokens_padded,), dtype=torch.int32, device=device + ) + expert_ids = torch.empty( + (max_loras * max_num_m_blocks,), dtype=torch.int32, device=device + ) + num_tokens_post_padded = torch.empty((max_loras,), dtype=torch.int32, device=device) + adapter_enabled = torch.ones(max_loras + 1, dtype=torch.int32, device=device) + lora_ids = torch.arange(max_loras, dtype=torch.int32, device=device) + + # call kernel + moe_lora_align_block_size( + topk_ids, + seg_indptr, + req_to_lora, + num_experts, + block_size, + max_loras, + max_num_tokens_padded, + max_num_m_blocks, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + adapter_enabled, + lora_ids, + None, # maybe_expert_map + ) + + config = { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "NUM_WARPS": 4, + "NUM_STAGES": 3, + "SPLIT_K": 1, + } + + expert_ids = expert_ids.view(max_loras, -1) + sorted_token_ids = sorted_token_ids.view(max_loras, -1) + + fused_moe_lora( + output, + hidden_states, + lora_a_stacked, + lora_b_stacked, + topk_weights, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + max_lora_rank, + top_k_num, + lora_ids, + adapter_enabled, + config["BLOCK_SIZE_M"], + config["BLOCK_SIZE_N"], + config["BLOCK_SIZE_K"], + config["GROUP_SIZE_M"], + config["NUM_WARPS"], + config["NUM_STAGES"], + config["SPLIT_K"], + config["BLOCK_SIZE_M"], + config["BLOCK_SIZE_N"], + config["BLOCK_SIZE_K"], + config["GROUP_SIZE_M"], + config["NUM_WARPS"], + config["NUM_STAGES"], + config["SPLIT_K"], + mul_routed_weight, + fully_sharded=fully_sharded, + offset=offset, + ) + + +def use_torch( + hidden_states, + token_lora_mapping, + topk_ids, + topk_weights, + lora_a_stacked, + lora_b_stacked, + top_k_num, + mul_routed_weight, +): + outputs = [] + + orig_dtype = hidden_states.dtype + for i in range(hidden_states.shape[0]): + lora_idx = token_lora_mapping[i] + expert_ids = topk_ids[i] + expert_weights = topk_weights[i] + + lora_a = lora_a_stacked[0][lora_idx][expert_ids] + lora_b = lora_b_stacked[0][lora_idx][expert_ids] + + h_f32 = hidden_states[i].to(torch.float32) + la_f32 = lora_a.to(torch.float32) + lb_f32 = lora_b.to(torch.float32) + + if mul_routed_weight: + tensors = [ + ((h_f32 @ la_f32[x].T @ lb_f32[x].T) * expert_weights[x]).to(orig_dtype) + for x in range(top_k_num) + ] + else: + tensors = [ + (h_f32 @ la_f32[x].T @ lb_f32[x].T).to(orig_dtype) + for x in range(top_k_num) + ] + outputs.append(torch.stack(tensors, dim=0)) + return torch.stack(outputs, dim=0) + + +DTYPES = [torch.float32, torch.float16, torch.bfloat16] +DEVICES = [f"cuda:{0}"] +SEED = [42] + + +@pytest.mark.parametrize("mul_routed_weight", [False, True]) +@pytest.mark.parametrize("num_tokens", [100]) +@pytest.mark.parametrize("top_k_num", [6, 12]) +@pytest.mark.parametrize("num_experts", [64]) +@pytest.mark.parametrize("max_loras", [4, 6, 16]) +@pytest.mark.parametrize("N", [1408]) +@pytest.mark.parametrize("K", [2048]) +@pytest.mark.parametrize("max_lora_rank", [16, 32, 64]) +@pytest.mark.parametrize("block_size", [16]) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("device", DEVICES) +@pytest.mark.parametrize("seed", SEED) +def test_fused_moe_lora_kernel( + mul_routed_weight, + num_tokens, + top_k_num, + num_experts, + max_loras, + N, + K, + max_lora_rank, + block_size, + dtype, + device, + seed, +): + torch.set_default_device(device) + set_random_seed(seed) + # the number of randomly generated sentences. + num_sequences = 10 + # generate data + topk_ids, topk_weights, token_lora_mapping, seg_indptr, req_to_lora = sample_data( + num_tokens, num_sequences, max_loras, num_experts, top_k_num + ) + + # Ensure generated data is on the correct device + topk_ids = topk_ids.to(device) + topk_weights = topk_weights.to(device) + token_lora_mapping = token_lora_mapping.to(device) + seg_indptr = seg_indptr.to(device) + req_to_lora = req_to_lora.to(device) + + # init lora weights + lora_a_stacked = [ + torch.rand( + ( + max_loras, + num_experts, + max_lora_rank, + K, + ), + dtype=dtype, + device=device, + ) + ] + lora_b_stacked = [ + torch.rand( + ( + max_loras, + num_experts, + N, + max_lora_rank, + ), + dtype=dtype, + device=device, + ) + ] + hidden_states = torch.rand( + ( + num_tokens, + K, + ), + dtype=dtype, + device=device, + ) + + # fused_moe_lora_kernel output + output = torch.zeros((num_tokens, top_k_num, N), dtype=dtype, device=device) + + use_fused_moe_lora_kernel( + topk_ids, + topk_weights, + seg_indptr, + req_to_lora, + max_lora_rank, + top_k_num, + lora_a_stacked, + lora_b_stacked, + hidden_states, + output, + max_loras, + num_experts, + block_size, + mul_routed_weight=mul_routed_weight, + ) + # pytorch output + output2 = use_torch( + hidden_states, + token_lora_mapping, + topk_ids, + topk_weights, + lora_a_stacked, + lora_b_stacked, + top_k_num, + mul_routed_weight=mul_routed_weight, + ) + + torch.testing.assert_close(output, output2, atol=1e-2, rtol=1e-2) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_deepseek_v3_base_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_deepseek_v3_base_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..e83d01e946668372226bd8daee87985efa945957 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_deepseek_v3_base_logprob_diff.py @@ -0,0 +1,156 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Regression test for DeepSeek-V3.1-Base MLA LoRA logprob accuracy. + +Compares SGLang LoRA logprobs against reference training logprobs from a +pre-computed dataset. The LoRA adapter and reference data are downloaded from: +https://huggingface.co/datasets/yushengsu/lora-diff-DeepSeek-V3.1-Base + +Usage: + python -m unittest test_lora_deepseek_v3_base_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest + +import torch +from huggingface_hub import snapshot_download + +import sglang as sgl +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci( + est_time=300, + suite="nightly-8-gpu-b200", +) + +BASE_MODEL = "deepseek-ai/DeepSeek-V3.1-Base" +LORA_HF_REPO = "yushengsu/lora-diff-DeepSeek-V3.1-Base" +LORA_BACKEND = "triton" +MAX_LORA_RANK = 32 +TP_SIZE = 8 +MOE_RUNNER_BACKEND = "triton" +EXPERTS_SHARED_OUTER_LORAS = True +PREFILL_ATTENTION_BACKEND = "fa4" +DECODE_ATTENTION_BACKEND = "flashinfer" + +KL_THRESHOLD = 6e-3 + + +def kl_v2(a, b): + a = torch.tensor(a) if not torch.is_tensor(a) else a + b = torch.tensor(b) if not torch.is_tensor(b) else b + return (((a - b) ** 2) * 0.5).mean().item() + + +def get_prompt_logprobs(engine, input_ids, lora_path): + if isinstance(input_ids, torch.Tensor): + input_ids = [input_ids.tolist()] + elif not isinstance(input_ids[0], list): + input_ids = [input_ids] + out = engine.generate( + input_ids=input_ids, + sampling_params={"max_new_tokens": 0, "temperature": 0.0}, + return_logprob=True, + logprob_start_len=0, + lora_path=lora_path, + ) + if isinstance(out, list): + out = out[0] + return [logprob for logprob, _, _ in out["meta_info"]["input_token_logprobs"]][1:] + + +class TestLoRADeepSeekV3BaseLogprobDiff(CustomTestCase): + + def test_lora_deepseek_v3_base_logprob_accuracy(self): + adapter_path = snapshot_download( + LORA_HF_REPO, + repo_type="dataset", + ) + + engine = sgl.Engine( + model_path=BASE_MODEL, + tp_size=TP_SIZE, + enable_lora=True, + max_lora_rank=MAX_LORA_RANK, + lora_paths={"my_lora": adapter_path}, + lora_backend=LORA_BACKEND, + attention_backend="flashinfer", + moe_runner_backend=MOE_RUNNER_BACKEND, + experts_shared_outer_loras=EXPERTS_SHARED_OUTER_LORAS, + prefill_attention_backend=PREFILL_ATTENTION_BACKEND, + decode_attention_backend=DECODE_ATTENTION_BACKEND, + disable_shared_experts_fusion=True, + ) + + try: + cdata = torch.load( + os.path.join(adapter_path, "compare_sample_train_data.pt"), + weights_only=False, + ) + + base_logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path=None) + logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path="my_lora") + + base_t = torch.tensor(base_logprobs) + lora_t = torch.tensor(logprobs) + diff = (base_t - lora_t).abs() + print( + f"[VERIFY] base vs lora: mean_diff={diff.mean().item():.6f}, " + f"max_diff={diff.max().item():.6f}, " + f"identical={torch.equal(base_t, lora_t)}" + ) + + self.assertFalse( + torch.equal(base_t, lora_t), + "LoRA logprobs should differ from base model logprobs", + ) + + kl_sglang_trainer = kl_v2(cdata["training_logprobs"], logprobs) + kl_orig_trainer = kl_v2( + cdata["training_logprobs"], cdata["sampling_logprobs"] + ) + kl_sglang_orig = kl_v2(logprobs, cdata["sampling_logprobs"]) + + print(f"KL(orig_sampler, trainer) = {kl_orig_trainer:.6e}") + print(f"KL(sglang, trainer) = {kl_sglang_trainer:.6e}") + print(f"KL(sglang, orig_sampler) = {kl_sglang_orig:.6e}") + + self.assertLessEqual( + kl_sglang_trainer, + KL_THRESHOLD, + f"KL(sglang, trainer) = {kl_sglang_trainer:.6e} exceeds " + f"threshold {KL_THRESHOLD}", + ) + + finally: + engine.shutdown() + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_drainer.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_drainer.py new file mode 100644 index 0000000000000000000000000000000000000000..15857c6f3a073039aaf0748c994838373c663788 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_drainer.py @@ -0,0 +1,131 @@ +import unittest +from types import SimpleNamespace +from typing import cast +from unittest import mock + +from sglang.srt.lora.lora_drainer import LoRADrainer +from sglang.srt.managers.schedule_batch import Req +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.lora_utils import ( + CI_MULTI_LORA_MODELS, + run_lora_batch_splitting_equivalence_test, +) +from sglang.test.test_utils import is_in_ci + +register_cuda_ci(est_time=100, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=100, suite="stage-b-test-1-gpu-small-amd") + +MOCK_START_TIME = 1000.0 +LORA_DRAIN_WAIT_THRESHOLD = 3.0 + + +def make_req(lora_id, wait_queue_entry_time, max_new_tokens, output_len=0): + time_stats = SimpleNamespace(wait_queue_entry_time=wait_queue_entry_time) + sampling_params = SimpleNamespace(max_new_tokens=max_new_tokens) + req_ns = SimpleNamespace( + lora_id=lora_id, + time_stats=time_stats, + sampling_params=sampling_params, + output_ids=[0] * output_len, + ) + return cast(Req, req_ns) + + +class TestLoRADrainer(unittest.TestCase): + def test_update_draining_marks_adapter(self): + if is_in_ci(): + return + + with mock.patch("time.monotonic", return_value=MOCK_START_TIME): + drainer = LoRADrainer( + max_loras_per_batch=1, max_wait_time_secs=LORA_DRAIN_WAIT_THRESHOLD + ) + + # Waiting request for adapter 'A' that has been waiting longer than threshold + wait_entry = MOCK_START_TIME - (LORA_DRAIN_WAIT_THRESHOLD + 0.01) + waiting_req = make_req("A", wait_entry, max_new_tokens=10) + + running_req = make_req("B", wait_entry, max_new_tokens=100, output_len=0) + + drainer.update_draining_state( + waiting_queue=[waiting_req], + running_reqs=[running_req], + ) + + # Running adapter 'B' should be marked as draining for 'A' + self.assertEqual(drainer.adapter_to_stats["B"].is_draining_for, "A") + + # Once running adapter 'B' finishes running, it should no longer be draining + drainer.update_draining_state(waiting_queue=[waiting_req], running_reqs=[]) + self.assertIsNone(drainer.adapter_to_stats["B"].is_draining_for) + + with mock.patch("time.monotonic", return_value=MOCK_START_TIME): + drainer = LoRADrainer( + max_loras_per_batch=2, max_wait_time_secs=LORA_DRAIN_WAIT_THRESHOLD + ) + + # Two starving adapters should cause two running adapters to drain. + wait_entryA = MOCK_START_TIME - (LORA_DRAIN_WAIT_THRESHOLD + 0.05) + wait_entryD = MOCK_START_TIME - (LORA_DRAIN_WAIT_THRESHOLD + 0.01) + starving_a = make_req("A", wait_entryA, max_new_tokens=10) + starving_d = make_req("D", wait_entryD, max_new_tokens=10) + + # Running adapters B and C with different remaining tokens + running_b = make_req("B", wait_entryA, max_new_tokens=5, output_len=0) + running_c = make_req("C", wait_entryA, max_new_tokens=100, output_len=0) + + drainer.update_draining_state( + waiting_queue=[starving_a, starving_d], + running_reqs=[running_b, running_c], + ) + + # B (smaller remaining tokens) should be drained for the most-starved adapter 'A' + self.assertEqual(drainer.adapter_to_stats["B"].is_draining_for, "A") + + # C should be drained for the other starving adapter 'D' + self.assertEqual(drainer.adapter_to_stats["C"].is_draining_for, "D") + + def test_can_schedule_respects_draining_tolerance(self): + if is_in_ci(): + return + + with mock.patch("time.monotonic", return_value=MOCK_START_TIME): + drainer = LoRADrainer( + max_loras_per_batch=1, max_wait_time_secs=LORA_DRAIN_WAIT_THRESHOLD + ) + + wait_entry = MOCK_START_TIME - (LORA_DRAIN_WAIT_THRESHOLD + 0.01) + starving_req = make_req("A", wait_entry, max_new_tokens=10) + + running_b = make_req("B", wait_entry, max_new_tokens=15, output_len=0) + drainer.update_draining_state( + waiting_queue=[starving_req], + running_reqs=[running_b], + ) + + self.assertEqual(drainer.adapter_to_stats["B"].is_draining_for, "A") + + # max_new_tokens is less than running adapter B's max_new_tokens + req_ok = make_req( + lora_id="B", wait_queue_entry_time=0, max_new_tokens=10, output_len=0 + ) + self.assertTrue(drainer.can_schedule(req_ok)) + + # max_new_tokens is more than running adapter B's max_new_tokens + req_bad = make_req( + lora_id="B", wait_queue_entry_time=0, max_new_tokens=20, output_len=0 + ) + self.assertFalse(drainer.can_schedule(req_bad)) + + def test_batch_splitting_with_drainer(self): + run_lora_batch_splitting_equivalence_test( + model_cases=CI_MULTI_LORA_MODELS, + attention_backend="torch_native", + disable_cuda_graph=True, + disable_radix_cache=True, + lora_drain_wait_threshold=LORA_DRAIN_WAIT_THRESHOLD, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_eviction.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_eviction.py new file mode 100644 index 0000000000000000000000000000000000000000..393026dc8d2df5e3bf5984b2649f34f7d3f215ab --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_eviction.py @@ -0,0 +1,148 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import contextlib +import multiprocessing as mp +import unittest +from typing import Dict, List, Tuple + +import torch + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.runners import SRTRunner +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=263, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=224, suite="stage-b-test-1-gpu-small-amd") + +PROMPTS = [ + "AI is a field of computer science focused on", + """ + ### Instruction: + Compose a SQL query that uses the following table: users, and returns the user_id and name of all users whose name that does not have a duplicate in the table. + ### Response: + SELECT user_id, name FROM users WHERE name LIKE 'A%'; + """, +] + +ADAPTERS = [ + "faridlazuarda/valadapt-llama-3.1-8B-it-chinese", # target_modules = q, v + "philschmid/code-llama-3-1-8b-text-to-sql-lora", # target_modules = q, k, v, o, gate, up, down +] + +BASE_MODEL = "meta-llama/Meta-Llama-3.1-8B-Instruct" + + +@contextlib.contextmanager +def dynamically_loaded_adapter(runner, lora_path: str, lora_name: str): + """A context manager to load and automatically unload a LoRA adapter.""" + try: + runner.load_lora_adapter(lora_name=lora_name, lora_path=lora_path) + yield + finally: + runner.unload_lora_adapter(lora_name=lora_name) + + +class TestLoRAEviction(CustomTestCase): + def test_lora_eviction_with_different_target_modules(self): + """ + Test LoRA eviction with different target modules. + + This test runs inference against two LoRA adapters in different orders to force eviction behavior, and ensures + that the outputs of the same (adapter, prompt) pair are consistent across runs. + """ + output_history = {} + self._run_test(ADAPTERS, output_history, reverse=False) + self._run_test(ADAPTERS, output_history, reverse=True) + + def test_lora_eviction_with_reused_lora_name(self): + """ + Test LoRA eviction with reused LoRA names. + + This test runs inference against two LoRA adapters with the same name to ensure that the eviction behavior + works correctly when reusing LoRA names. + """ + output_history = {} + self._run_test(ADAPTERS, output_history, reuse_lora_name=True, repeat=1) + self._run_test(ADAPTERS, output_history, reuse_lora_name=False, repeat=1) + + def _run_test( + self, + lora_paths: List[str], + output_history: Dict[Tuple[str, str], str], + reverse: bool = False, + repeat: int = 2, + reuse_lora_name: bool = False, + ): + REUSED_LORA_NAME = "lora" + max_new_tokens = 256 + torch_dtype = torch.float16 + base_path = BASE_MODEL + assert len(lora_paths) >= 2 + + initial_lora_paths = lora_paths if not reuse_lora_name else None + # Initialize runners + with SRTRunner( + base_path, + torch_dtype=torch_dtype, + model_type="generation", + lora_paths=initial_lora_paths, + max_loras_per_batch=1, + enable_lora=True, + max_lora_rank=256, + lora_target_modules=["all"], + ) as srt_runner: + adapter_sequence = lora_paths if not reverse else lora_paths[::-1] + + for i in range(repeat): + for j, lora_path in enumerate(adapter_sequence): + print( + f"\n========== Testing LoRA eviction with adapter '{lora_path}' (#{j + 1}/{len(adapter_sequence)}), reuse_lora_name: {reuse_lora_name}, reversed: {reverse}, repeat: {i + 1}/{repeat} ---" + ) + + lora_name = REUSED_LORA_NAME if reuse_lora_name else lora_path + context = ( + dynamically_loaded_adapter(srt_runner, lora_path, lora_name) + if reuse_lora_name + else contextlib.nullcontext() + ) + with context: + for prompt in PROMPTS: + print("\nprompt:\n", prompt) + srt_outputs = srt_runner.forward( + [prompt], + max_new_tokens=max_new_tokens, + lora_paths=[lora_name], + ) + output = srt_outputs.output_strs[0].strip() + print("\noutput:\n", output) + + prev_output = output_history.get((lora_path, prompt)) + if prev_output is not None: + self.assertEqual( + prev_output, + output, + f"Output mismatch for adapter {lora_path} and prompt '{prompt}' on repeat {j + 1}, previous: '{prev_output}', current: '{output}'.", + ) + else: + output_history[(lora_path, prompt)] = output + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + unittest.main(warnings="ignore") diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_eviction_policy.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_eviction_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf929909771b4d6248339caaff00ef87f708c8c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_eviction_policy.py @@ -0,0 +1,201 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Unit tests for LoRA eviction policies. +Tests LRU and FIFO eviction behavior. +""" + +import unittest + +from sglang.srt.lora.eviction_policy import get_eviction_policy +from sglang.test.ci.ci_register import ( + register_amd_ci, + register_cpu_ci, + register_cuda_ci, + register_xpu_ci, +) + +register_cuda_ci(est_time=200, suite="nightly-1-gpu", nightly=True) +register_amd_ci(est_time=200, suite="nightly-amd-1-gpu", nightly=True) +register_cpu_ci(est_time=6, suite="base-c-test-cpu") +register_xpu_ci(est_time=10, suite="stage-a-test-1-gpu-xpu") + + +class TestLoRAEvictionPolicy(unittest.TestCase): + """Unit tests for LoRA eviction policies.""" + + def _test_eviction_policy( + self, policy_name, access_sequence, candidates, expected_victim + ): + """ + Helper to test eviction policy with given access pattern. + + Args: + policy_name: Name of eviction policy ("lru" or "fifo") + access_sequence: List of adapter IDs in access order + candidates: Set of adapter IDs that can be evicted + expected_victim: Expected adapter ID to be evicted + """ + policy = get_eviction_policy(policy_name) + + # Simulate access pattern + for adapter_id in access_sequence: + policy.mark_used(adapter_id) + + # Select victim from candidates + victim = policy.select_victim(candidates) + self.assertEqual( + victim, + expected_victim, + f"{policy_name.upper()}: Expected {expected_victim}, got {victim}", + ) + + def test_lru_basic(self): + """Test LRU selects least recently used adapter.""" + self._test_eviction_policy( + "lru", + access_sequence=["lora1", "lora2", "lora3", "lora4"], + candidates={"lora1", "lora2", "lora3", "lora4"}, + expected_victim="lora1", + ) + + def test_lru_with_reuse(self): + """Test LRU updates order on reuse.""" + self._test_eviction_policy( + "lru", + access_sequence=["lora1", "lora2", "lora3", "lora4", "lora1"], + candidates={"lora1", "lora2", "lora3", "lora4"}, + expected_victim="lora2", + ) + + def test_lru_multiple_reuse(self): + """Test LRU with multiple reuses.""" + self._test_eviction_policy( + "lru", + access_sequence=["lora1", "lora2", "lora3", "lora1", "lora2"], + candidates={"lora1", "lora2", "lora3"}, + expected_victim="lora3", + ) + + def test_lru_with_subset_candidates(self): + """Test LRU with subset of candidates.""" + self._test_eviction_policy( + "lru", + access_sequence=["lora1", "lora2", "lora3", "lora4"], + candidates={"lora2", "lora3", "lora4"}, + expected_victim="lora2", + ) + + def test_lru_base_model_evicted_last(self): + """Test LRU evicts LoRA adapters before base model (None).""" + self._test_eviction_policy( + "lru", + access_sequence=["lora1", "lora2", "lora3"], + candidates={None, "lora1", "lora2", "lora3"}, + expected_victim="lora1", + ) + + def test_fifo_basic(self): + """Test FIFO selects first inserted adapter.""" + self._test_eviction_policy( + "fifo", + access_sequence=["lora1", "lora2", "lora3", "lora4"], + candidates={"lora1", "lora2", "lora3", "lora4"}, + expected_victim="lora1", + ) + + def test_fifo_ignores_reuse(self): + """Test FIFO ignores reuse.""" + self._test_eviction_policy( + "fifo", + access_sequence=[ + "lora1", + "lora2", + "lora3", + "lora4", + "lora4", + "lora3", + "lora2", + "lora1", + ], + candidates={"lora1", "lora2", "lora3", "lora4"}, + expected_victim="lora1", + ) + + def test_fifo_with_subset_candidates(self): + """Test FIFO with subset of candidates.""" + self._test_eviction_policy( + "fifo", + access_sequence=["lora1", "lora2", "lora3", "lora4"], + candidates={"lora2", "lora3", "lora4"}, + expected_victim="lora2", + ) + + def test_fifo_base_model_evicted_last(self): + """Test FIFO evicts LoRA adapters before base model (None).""" + self._test_eviction_policy( + "fifo", + access_sequence=["lora1", "lora2", "lora3"], + candidates={None, "lora1", "lora2", "lora3"}, + expected_victim="lora1", + ) + + def test_policy_remove(self): + """Test that remove() correctly updates internal state.""" + lru = get_eviction_policy("lru") + lru.mark_used("lora1") + lru.mark_used("lora2") + lru.mark_used("lora3") + + # Remove lora1, so lora2 becomes LRU + lru.remove("lora1") + victim = lru.select_victim({"lora1", "lora2", "lora3"}) + self.assertEqual(victim, "lora2") + + def test_eviction_policy_factory(self): + """Test eviction policy factory function.""" + # Test valid policies + lru = get_eviction_policy("lru") + fifo = get_eviction_policy("fifo") + + self.assertIsNotNone(lru) + self.assertIsNotNone(fifo) + + # Test invalid policy + with self.assertRaises(ValueError): + get_eviction_policy("invalid_policy") + + def test_lru_vs_fifo_behavior(self): + """Test that LRU and FIFO behave differently.""" + access_sequence = ["lora1", "lora2", "lora3", "lora1"] + candidates = {"lora1", "lora2", "lora3"} + + lru = get_eviction_policy("lru") + for adapter_id in access_sequence: + lru.mark_used(adapter_id) + lru_victim = lru.select_victim(candidates) + + fifo = get_eviction_policy("fifo") + for adapter_id in access_sequence: + fifo.mark_used(adapter_id) + fifo_victim = fifo.select_victim(candidates) + + self.assertNotEqual(lru_victim, fifo_victim) + self.assertEqual(lru_victim, "lora2") + self.assertEqual(fifo_victim, "lora1") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_gpt_oss_20b_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_gpt_oss_20b_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..5fc4003caa248bb649a97de0265a561154ba2a67 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_gpt_oss_20b_logprob_diff.py @@ -0,0 +1,146 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Regression test for gpt-oss-20b LoRA logprob accuracy. + +Compares SGLang LoRA logprobs against reference training logprobs from a +pre-computed dataset. The LoRA adapter and reference data are downloaded from: +https://huggingface.co/datasets/yushengsu/lora-diff-gpt-oss-20b + +Usage: + python -m unittest test_lora_gpt_oss_20b_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest + +import torch +from huggingface_hub import snapshot_download + +import sglang as sgl +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=90, stage="extra-b", runner_config="4-gpu-b200") + +BASE_MODEL = "lmsys/gpt-oss-20b-bf16" +LORA_HF_REPO = "yushengsu/lora-diff-gpt-oss-20b" +LORA_BACKEND = "triton" +MAX_LORA_RANK = 32 +TP_SIZE = 4 +MOE_RUNNER_BACKEND = "triton" +EXPERTS_SHARED_OUTER_LORAS = True +PREFILL_ATTENTION_BACKEND = "fa4" +DECODE_ATTENTION_BACKEND = "fa4" + +KL_THRESHOLD = 5e-3 + + +def kl_v2(a, b): + a = torch.tensor(a) if not torch.is_tensor(a) else a + b = torch.tensor(b) if not torch.is_tensor(b) else b + return (((a - b) ** 2) * 0.5).mean().item() + + +def get_prompt_logprobs(engine, input_ids, lora_path): + out = engine.generate( + input_ids=input_ids, + sampling_params={"max_new_tokens": 0, "temperature": 0.0}, + return_logprob=True, + logprob_start_len=0, + lora_path=lora_path, + ) + return [logprob for logprob, _, _ in out["meta_info"]["input_token_logprobs"]][1:] + + +class TestLoRAGptOss20BLogprobDiff(CustomTestCase): + + def test_lora_gpt_oss_20b_logprob_accuracy(self): + adapter_path = snapshot_download( + LORA_HF_REPO, + repo_type="dataset", + ) + + engine = sgl.Engine( + model_path=BASE_MODEL, + tp_size=TP_SIZE, + enable_lora=True, + max_lora_rank=MAX_LORA_RANK, + lora_paths={"my_lora": adapter_path}, + lora_backend=LORA_BACKEND, + attention_backend="flashinfer", + moe_runner_backend=MOE_RUNNER_BACKEND, + experts_shared_outer_loras=EXPERTS_SHARED_OUTER_LORAS, + prefill_attention_backend=PREFILL_ATTENTION_BACKEND, + decode_attention_backend=DECODE_ATTENTION_BACKEND, + ) + + try: + cdata = torch.load( + os.path.join(adapter_path, "compare_sample_train_data.pt"), + weights_only=False, + ) + + base_logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path=None) + logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path="my_lora") + + base_t = torch.tensor(base_logprobs) + lora_t = torch.tensor(logprobs) + diff = (base_t - lora_t).abs() + print( + f"[VERIFY] base vs lora: mean_diff={diff.mean().item():.6f}, " + f"max_diff={diff.max().item():.6f}, " + f"identical={torch.equal(base_t, lora_t)}" + ) + + self.assertFalse( + torch.equal(base_t, lora_t), + "LoRA logprobs should differ from base model logprobs", + ) + + kl_sglang_trainer = kl_v2(cdata["training_logprobs"], logprobs) + kl_orig_trainer = kl_v2( + cdata["training_logprobs"], cdata["sampling_logprobs"] + ) + kl_sglang_orig = kl_v2(logprobs, cdata["sampling_logprobs"]) + + print(f"KL(orig_sampler, trainer) = {kl_orig_trainer:.6e}") + print(f"KL(sglang, trainer) = {kl_sglang_trainer:.6e}") + print(f"KL(sglang, orig_sampler) = {kl_sglang_orig:.6e}") + + self.assertLessEqual( + kl_sglang_trainer, + KL_THRESHOLD, + f"KL(sglang, trainer) = {kl_sglang_trainer:.6e} exceeds " + f"threshold {KL_THRESHOLD}", + ) + + finally: + engine.shutdown() + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_hf_sgl_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_hf_sgl_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..df2063b5de7834d78ea55f4bf6af9ea61f3be74e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_hf_sgl_logprob_diff.py @@ -0,0 +1,572 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Test to compare log probabilities between HuggingFace+LoRA and SGLang+LoRA. + +This test: +1. Runs SGLang with LoRA and collects log probabilities +2. Runs HuggingFace with LoRA and collects log probabilities +3. Compares the differences (max and mean) between the two implementations +4. Uses unittest framework for easy integration with test suites + +Usage: + python test_lora_hf_sgl_logprob_diff.py + or + python -m unittest test_lora_hf_sgl_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.runners import HFRunner, SRTRunner +from sglang.test.test_utils import DEFAULT_PORT_FOR_SRT_TEST_RUNNER, CustomTestCase + +register_cuda_ci( + est_time=150, + stage="base-b", + runner_config="1-gpu-small", +) +register_amd_ci( + est_time=250, + suite="stage-b-test-1-gpu-small-amd", +) +# Test configuration constants +BASE_MODEL = "meta-llama/Llama-2-7b-hf" +LORA_PATHS = ["yushengsu/sglang_lora_logprob_diff_without_tuning"] +LORA_BACKEND = "csgmv" +DISABLE_CUDA_GRAPH = False +LORA_TARGET_MODULES = None +LOGPROB_THRESHOLD = 1e-01 +MAX_NEW_TOKENS = 32 + +# Default test prompts +DEFAULT_TEST_PROMPTS = [ + "SGL is a", + "AI is a field of computer science focused on", + "Write a long story.", + "Write a short story.", + "What are the main components of a computer?", +] + +# Formatting constants +DIVIDER_WIDTH = 80 +SECTION_CHAR = "=" +SUBSECTION_CHAR = "-" + + +def print_section_header(title: str): + """Print a major section header.""" + print("\n" + SECTION_CHAR * DIVIDER_WIDTH) + print(title) + print(SECTION_CHAR * DIVIDER_WIDTH) + + +def print_subsection_header(title: str): + """Print a subsection header.""" + print(f"\n{SUBSECTION_CHAR * 40}") + print(f"{title}") + print(SUBSECTION_CHAR * 40) + + +def print_config_info(title: str, config: Dict[str, Any]): + """Print configuration information in a consistent format.""" + print_section_header(title) + for key, value in config.items(): + print(f" {key}: {value}") + + +def compare_logprobs_for_type( + sglang_logprobs: torch.Tensor, hf_logprobs: torch.Tensor, logprob_type: str +) -> Dict[str, Any]: + """ + Compare logprobs for a specific type (prefill or decode). + + Args: + sglang_logprobs: SGLang log probabilities + hf_logprobs: HuggingFace log probabilities + logprob_type: Type of logprobs ("prefill" or "decode") + + Returns: + Dictionary containing comparison statistics + """ + diff = torch.abs(sglang_logprobs - hf_logprobs) + max_diff = torch.max(diff).item() + mean_diff = torch.mean(diff).item() + shape = list(sglang_logprobs.shape) + matches_threshold = max_diff < LOGPROB_THRESHOLD + + return { + "max_diff": max_diff, + "mean_diff": mean_diff, + "shape": shape, + "matches_threshold": matches_threshold, + "type": logprob_type, + } + + +def print_logprob_comparison(comparison: Dict[str, Any]): + """Print logprob comparison results in a consistent format.""" + logprob_type = comparison["type"].capitalize() + print(f"\n{logprob_type} logprobs:") + print(f" Shape: {comparison['shape']}") + print(f" Max difference: {comparison['max_diff']:.6e}") + print(f" Mean difference: {comparison['mean_diff']:.6e}") + + status = "PASS" if comparison["matches_threshold"] else "FAIL" + print(f" Status: {status} (threshold: {LOGPROB_THRESHOLD:.0e})") + + +def compare_output_strings( + sglang_output: str, hf_output: str, max_display_len: int = 200 +) -> Dict[str, Any]: + """ + Compare output strings between SGLang and HuggingFace. + + Args: + sglang_output: SGLang generated text + hf_output: HuggingFace generated text + max_display_len: Maximum length for display + + Returns: + Dictionary containing comparison results + """ + outputs_match = sglang_output.strip() == hf_output.strip() + + # Truncate for display if needed + sglang_display = ( + sglang_output[:max_display_len] + if len(sglang_output) > max_display_len + else sglang_output + ) + hf_display = ( + hf_output[:max_display_len] if len(hf_output) > max_display_len else hf_output + ) + + return { + "match": outputs_match, + "sglang_output": sglang_output, + "hf_output": hf_output, + "sglang_display": sglang_display, + "hf_display": hf_display, + } + + +def print_output_comparison(comparison: Dict[str, Any]): + """Print output string comparison in a consistent format.""" + print(f"\nOutput strings:") + status = "MATCH" if comparison["match"] else "DIFFER" + print(f" Status: {status}") + print(f" SGLang: {comparison['sglang_display']}") + print(f" HuggingFace: {comparison['hf_display']}") + + +def prepare_lora_paths_per_prompt( + lora_paths: List[str], num_prompts: int +) -> List[Optional[str]]: + """ + Prepare LoRA paths for each prompt by cycling through available LoRAs. + + Args: + lora_paths: List of available LoRA adapter paths + num_prompts: Number of prompts to generate LoRA paths for + + Returns: + List of LoRA paths (one per prompt), or None values if no LoRAs + """ + if not lora_paths: + return [None] * num_prompts + + return [lora_paths[i % len(lora_paths)] for i in range(num_prompts)] + + +def run_sglang_with_lora( + model_path: str, + lora_paths: List[str], + prompts: List[str], + max_new_tokens: int, + torch_dtype: torch.dtype, + lora_backend: str, + port: int, + disable_cuda_graph: bool, + lora_target_modules: Optional[List[str]], + tp_size: int, +) -> Dict[str, Any]: + """Run SGLang with LoRA and return log probabilities.""" + config = { + "Model": model_path, + "LoRA paths": lora_paths, + "LoRA backend": lora_backend, + "Disable CUDA graph": disable_cuda_graph, + "Port": port, + "Number of prompts": len(prompts), + "Tensor parallel size": tp_size, + } + print_config_info("Running SGLang with LoRA", config) + + lora_paths_per_prompt = prepare_lora_paths_per_prompt(lora_paths, len(prompts)) + + with SRTRunner( + model_path, + torch_dtype=torch_dtype, + model_type="generation", + tp_size=tp_size, + lora_paths=lora_paths, + max_loras_per_batch=len(lora_paths) if lora_paths else 1, + lora_backend=lora_backend, + disable_cuda_graph=disable_cuda_graph, + disable_radix_cache=True, + port=port, + mem_fraction_static=0.88, + lora_target_modules=lora_target_modules, + ) as srt_runner: + srt_outputs = srt_runner.forward( + prompts, + max_new_tokens=max_new_tokens, + lora_paths=lora_paths_per_prompt, + ) + + return { + "top_input_logprobs": srt_outputs.top_input_logprobs, + "top_output_logprobs": srt_outputs.top_output_logprobs, + "output_strs": srt_outputs.output_strs, + "lora_paths": lora_paths_per_prompt, + } + + +def run_hf_with_lora( + model_path: str, + lora_paths: List[str], + prompts: List[str], + max_new_tokens: int, + torch_dtype: torch.dtype, +) -> Dict[str, Any]: + """Run HuggingFace with LoRA and return log probabilities.""" + config = { + "Model": model_path, + "LoRA paths": lora_paths, + "Number of prompts": len(prompts), + } + print_config_info("Running HuggingFace with LoRA", config) + + lora_paths_per_prompt = prepare_lora_paths_per_prompt(lora_paths, len(prompts)) + + with HFRunner( + model_path, + torch_dtype=torch_dtype, + model_type="generation", + patch_model_do_sample_false=True, + ) as hf_runner: + hf_outputs = hf_runner.forward( + prompts, + max_new_tokens=max_new_tokens, + lora_paths=lora_paths_per_prompt, + ) + + return { + "top_input_logprobs": hf_outputs.top_input_logprobs, + "top_output_logprobs": hf_outputs.top_output_logprobs, + "output_strs": hf_outputs.output_strs, + "lora_paths": lora_paths_per_prompt, + } + + +def compare_single_prompt( + prompt_idx: int, + sglang_data: Dict[str, Any], + hf_data: Dict[str, Any], +) -> Dict[str, Any]: + """ + Compare logprobs and outputs for a single prompt. + + Args: + prompt_idx: Index of the prompt being compared + sglang_data: SGLang results data + hf_data: HuggingFace results data + + Returns: + Dictionary containing all comparison results + """ + print_subsection_header(f"Prompt {prompt_idx + 1}") + print(f"LoRA adapter: {sglang_data['lora_paths'][prompt_idx]}") + + result = { + "prompt_idx": prompt_idx, + "lora_path": sglang_data["lora_paths"][prompt_idx], + } + + # Compare prefill (input) logprobs + sglang_prefill = torch.tensor(sglang_data["top_input_logprobs"][prompt_idx]) + hf_prefill = torch.tensor(hf_data["top_input_logprobs"][prompt_idx]) + prefill_comparison = compare_logprobs_for_type( + sglang_prefill, hf_prefill, "prefill" + ) + print_logprob_comparison(prefill_comparison) + + # Store prefill results + result["prefill_max_diff"] = prefill_comparison["max_diff"] + result["prefill_mean_diff"] = prefill_comparison["mean_diff"] + result["prefill_shape"] = prefill_comparison["shape"] + result["prefill_logprob_match"] = prefill_comparison["matches_threshold"] + + # Compare decode (output) logprobs + sglang_decode = torch.tensor(sglang_data["top_output_logprobs"][prompt_idx]) + hf_decode = torch.tensor(hf_data["top_output_logprobs"][prompt_idx]) + decode_comparison = compare_logprobs_for_type(sglang_decode, hf_decode, "decode") + print_logprob_comparison(decode_comparison) + + # Store decode results + result["decode_max_diff"] = decode_comparison["max_diff"] + result["decode_mean_diff"] = decode_comparison["mean_diff"] + result["decode_shape"] = decode_comparison["shape"] + result["decode_logprob_match"] = decode_comparison["matches_threshold"] + + # Overall logprob match + result["overall_logprob_match"] = ( + prefill_comparison["matches_threshold"] + and decode_comparison["matches_threshold"] + ) + + # Compare output strings + sglang_output = sglang_data["output_strs"][prompt_idx] + hf_output = hf_data["output_strs"][prompt_idx] + output_comparison = compare_output_strings(sglang_output, hf_output) + print_output_comparison(output_comparison) + + # Store output results + result["outputs_match"] = output_comparison["match"] + result["sglang_output"] = output_comparison["sglang_output"] + result["hf_output"] = output_comparison["hf_output"] + + return result + + +def print_overall_statistics(results: List[Dict[str, Any]]): + """Print overall statistics across all prompts.""" + print_section_header("Overall Statistics") + + # Gather statistics + prefill_max_diffs = [r["prefill_max_diff"] for r in results] + prefill_mean_diffs = [r["prefill_mean_diff"] for r in results] + decode_max_diffs = [r["decode_max_diff"] for r in results] + decode_mean_diffs = [r["decode_mean_diff"] for r in results] + + # Print logprob statistics + print("\nLogprob Differences:") + print(f" Prefill:") + print(f" Max of max: {max(prefill_max_diffs):.6e}") + print(f" Mean of max: {np.mean(prefill_max_diffs):.6e}") + print(f" Mean of mean: {np.mean(prefill_mean_diffs):.6e}") + + print(f" Decode:") + print(f" Max of max: {max(decode_max_diffs):.6e}") + print(f" Mean of max: {np.mean(decode_max_diffs):.6e}") + print(f" Mean of mean: {np.mean(decode_mean_diffs):.6e}") + + # Print match statistics + num_prompts = len(results) + logprob_match_count = sum(r["overall_logprob_match"] for r in results) + prefill_match_count = sum(r["prefill_logprob_match"] for r in results) + decode_match_count = sum(r["decode_logprob_match"] for r in results) + outputs_match_count = sum(r["outputs_match"] for r in results) + + print(f"\nLogprob Statistics (threshold: {LOGPROB_THRESHOLD:.0e}):") + overall_status = "PASSED" if logprob_match_count == num_prompts else "FAILED" + print(f" Overall logprob: {logprob_match_count}/{num_prompts} {overall_status}") + print(f" Prefill logprob: {prefill_match_count}/{num_prompts}") + print(f" Decode logprob: {decode_match_count}/{num_prompts}") + + print(f"\nString Statistics:") + print(f" Output strings: {outputs_match_count}/{num_prompts}") + + # Return overall stats for saving + return { + "logprob_differences": { + "prefill": { + "max_of_max_diffs": max(prefill_max_diffs), + "mean_of_max_diffs": float(np.mean(prefill_max_diffs)), + "mean_of_mean_diffs": float(np.mean(prefill_mean_diffs)), + }, + "decode": { + "max_of_max_diffs": max(decode_max_diffs), + "mean_of_max_diffs": float(np.mean(decode_max_diffs)), + "mean_of_mean_diffs": float(np.mean(decode_mean_diffs)), + }, + }, + "match_statistics": { + "overall_logprob_match_rate": logprob_match_count / num_prompts, + "prefill_logprob_match_rate": prefill_match_count / num_prompts, + "decode_logprob_match_rate": decode_match_count / num_prompts, + "outputs_match_rate": outputs_match_count / num_prompts, + }, + } + + +def compare_logprobs( + sglang_logprobs: Dict[str, Any], hf_logprobs: Dict[str, Any] +) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: + """Compare log probabilities and compute statistics.""" + print_section_header("Comparing Log Probabilities") + + results = [] + num_prompts = len(sglang_logprobs["top_input_logprobs"]) + + for i in range(num_prompts): + result = compare_single_prompt(i, sglang_logprobs, hf_logprobs) + results.append(result) + + overall_stats = print_overall_statistics(results) + + return results, overall_stats + + +class TestLoRAHFSGLLogprobDifference(CustomTestCase): + """ + Test case to compare log probabilities between HuggingFace+LoRA and SGLang+LoRA. + """ + + def _run_comparison_test( + self, + model_path: str, + lora_paths: List[str], + prompts: List[str], + max_new_tokens: int = MAX_NEW_TOKENS, + torch_dtype: torch.dtype = torch.float16, + lora_backend: str = LORA_BACKEND, + port: int = DEFAULT_PORT_FOR_SRT_TEST_RUNNER, + disable_cuda_graph: bool = DISABLE_CUDA_GRAPH, + lora_target_modules: Optional[List[str]] = LORA_TARGET_MODULES, + tp_size: int = 1, + ): + """ + Run comparison test between SGLang and HuggingFace with LoRA. + """ + print_section_header(f"Testing {model_path} with LoRA adapters") + + # Step 1: Run SGLang with LoRA + sglang_logprobs = run_sglang_with_lora( + model_path=model_path, + lora_paths=lora_paths, + prompts=prompts, + max_new_tokens=max_new_tokens, + torch_dtype=torch_dtype, + lora_backend=lora_backend, + port=port, + disable_cuda_graph=disable_cuda_graph, + lora_target_modules=lora_target_modules, + tp_size=tp_size, + ) + + # Clear GPU memory + print("\nClearing GPU memory...") + torch.cuda.empty_cache() + + # Step 2: Run HuggingFace with LoRA + hf_logprobs = run_hf_with_lora( + model_path=model_path, + lora_paths=lora_paths, + prompts=prompts, + max_new_tokens=max_new_tokens, + torch_dtype=torch_dtype, + ) + + # Step 3: Compare log probabilities + results, overall_stats = compare_logprobs(sglang_logprobs, hf_logprobs) + + # Assert that all prompts pass the threshold + for result in results: + self.assertTrue( + result["prefill_logprob_match"], + f"Prefill logprob mismatch for prompt {result['prompt_idx']} " + f"(max_diff={result['prefill_max_diff']:.6e}, threshold={LOGPROB_THRESHOLD:.0e})", + ) + self.assertTrue( + result["decode_logprob_match"], + f"Decode logprob mismatch for prompt {result['prompt_idx']} " + f"(max_diff={result['decode_max_diff']:.6e}, threshold={LOGPROB_THRESHOLD:.0e})", + ) + + print_section_header("Test completed successfully!") + + return results, overall_stats + + def test_lora_logprob_comparison_basic(self): + """ + Basic test comparing HF and SGLang LoRA logprobs with small model. + """ + prompts = DEFAULT_TEST_PROMPTS[:2] # Use fewer prompts for faster testing + + self._run_comparison_test( + model_path=BASE_MODEL, + lora_paths=LORA_PATHS, + prompts=prompts, + ) + + def test_lora_logprob_comparison_full(self): + """ + Full test comparing HF and SGLang LoRA logprobs with all prompts. + """ + self._run_comparison_test( + model_path=BASE_MODEL, + lora_paths=LORA_PATHS, + prompts=DEFAULT_TEST_PROMPTS, + ) + + def test_lora_logprob_comparison_chunked(self): + """ + Test with logprobs chunking enabled and a small chunk size so that + even short prompts trigger the multi-pass lm_head LoRA path. + """ + saved = {} + env_overrides = { + "SGLANG_ENABLE_LOGITS_PROCESSER_CHUNK": "true", + "SGLANG_LOGITS_PROCESSER_CHUNK_SIZE": "4", + } + for key, val in env_overrides.items(): + saved[key] = os.environ.get(key) + os.environ[key] = val + + try: + self._run_comparison_test( + model_path=BASE_MODEL, + lora_paths=LORA_PATHS, + prompts=DEFAULT_TEST_PROMPTS, + ) + finally: + for key, orig in saved.items(): + if orig is None: + os.environ.pop(key, None) + else: + os.environ[key] = orig + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + # Final cleanup + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_kimi_k25_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_kimi_k25_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..fabd9bb77ed32847a9e4d17bbedda2b138f97de1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_kimi_k25_logprob_diff.py @@ -0,0 +1,150 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Regression test for Kimi-K2.5 (VLM + MLA + MoE) LoRA logprob accuracy. + +Compares SGLang LoRA logprobs against reference training logprobs from a +pre-computed dataset. The LoRA adapter and reference data are downloaded from: +https://huggingface.co/datasets/yushengsu/lora-diff-Kimi-K2.5 + +Usage: + python -m unittest test_lora_kimi_k25_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest + +import torch +from huggingface_hub import snapshot_download + +import sglang as sgl +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci( + est_time=360, + suite="nightly-8-gpu-b200", +) + +BASE_MODEL = "moonshotai/Kimi-K2.5" +LORA_HF_REPO = "yushengsu/lora-diff-Kimi-K2.5" +LORA_BACKEND = "triton" +MAX_LORA_RANK = 32 +TP_SIZE = 8 +MOE_RUNNER_BACKEND = "triton" +EXPERTS_SHARED_OUTER_LORAS = True +PREFILL_ATTENTION_BACKEND = "fa4" +DECODE_ATTENTION_BACKEND = "flashinfer" + +KL_THRESHOLD = 1.5e-2 + + +def kl_v2(a, b): + a = torch.tensor(a) if not torch.is_tensor(a) else a + b = torch.tensor(b) if not torch.is_tensor(b) else b + return (((a - b) ** 2) * 0.5).mean().item() + + +def get_prompt_logprobs(engine, input_ids, lora_path): + out = engine.generate( + input_ids=input_ids, + sampling_params={"max_new_tokens": 0, "temperature": 0.0}, + return_logprob=True, + logprob_start_len=0, + lora_path=lora_path, + ) + return [logprob for logprob, _, _ in out["meta_info"]["input_token_logprobs"]][1:] + + +class TestLoRAKimiK25LogprobDiff(CustomTestCase): + + def test_lora_kimi_k25_logprob_accuracy(self): + adapter_path = snapshot_download( + LORA_HF_REPO, + repo_type="dataset", + ) + + engine = sgl.Engine( + model_path=BASE_MODEL, + tp_size=TP_SIZE, + enable_lora=True, + max_lora_rank=MAX_LORA_RANK, + lora_paths={"my_lora": adapter_path}, + lora_backend=LORA_BACKEND, + attention_backend="flashinfer", + moe_runner_backend=MOE_RUNNER_BACKEND, + experts_shared_outer_loras=EXPERTS_SHARED_OUTER_LORAS, + prefill_attention_backend=PREFILL_ATTENTION_BACKEND, + decode_attention_backend=DECODE_ATTENTION_BACKEND, + trust_remote_code=True, + ) + + try: + cdata = torch.load( + os.path.join(adapter_path, "compare_sample_train_data.pt"), + weights_only=False, + ) + + base_logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path=None) + logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path="my_lora") + + base_t = torch.tensor(base_logprobs) + lora_t = torch.tensor(logprobs) + diff = (base_t - lora_t).abs() + print( + f"[VERIFY] base vs lora: mean_diff={diff.mean().item():.6f}, " + f"max_diff={diff.max().item():.6f}, " + f"identical={torch.equal(base_t, lora_t)}" + ) + + self.assertFalse( + torch.equal(base_t, lora_t), + "LoRA logprobs should differ from base model logprobs", + ) + + kl_sglang_trainer = kl_v2(cdata["training_logprobs"], logprobs) + kl_orig_trainer = kl_v2( + cdata["training_logprobs"], cdata["sampling_logprobs"] + ) + kl_sglang_orig = kl_v2(logprobs, cdata["sampling_logprobs"]) + + print(f"KL(orig_sampler, trainer) = {kl_orig_trainer:.6e}") + print(f"KL(sglang, trainer) = {kl_sglang_trainer:.6e}") + print(f"KL(sglang, orig_sampler) = {kl_sglang_orig:.6e}") + + self.assertLessEqual( + kl_sglang_trainer, + KL_THRESHOLD, + f"KL(sglang, trainer) = {kl_sglang_trainer:.6e} exceeds " + f"threshold {KL_THRESHOLD}", + ) + + finally: + engine.shutdown() + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_moe_tp_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_moe_tp_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..fb3343129b444059aee57745a940f41aa4e622c4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_moe_tp_logprob_diff.py @@ -0,0 +1,169 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + + +import multiprocessing as mp +import unittest +from typing import Any, Dict, List + +import torch + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.lora_utils import ( + MOE_BASE_MODEL_PATH, + MOE_LORA_PATH, + MOE_LORA_TEST_PROMPTS, +) +from sglang.test.runners import SRTRunner +from sglang.test.test_utils import ( + DEFAULT_PORT_FOR_SRT_TEST_RUNNER, + CustomTestCase, + is_in_ci, +) + +register_cuda_ci(est_time=200, stage="extra-a", runner_config="2-gpu-large") + +LOGPROB_THRESHOLD = 5e-04 +MAX_NEW_TOKENS = 10 + + +def _run_sglang_moe_lora( + tp_size: int, + prompts: List[str], + port: int = DEFAULT_PORT_FOR_SRT_TEST_RUNNER, +) -> Dict[str, Any]: + lora_paths_per_prompt = [MOE_LORA_PATH] * len(prompts) + + with SRTRunner( + model_path=MOE_BASE_MODEL_PATH, + torch_dtype=torch.bfloat16, + model_type="generation", + tp_size=tp_size, + lora_paths=[MOE_LORA_PATH], + max_loras_per_batch=1, + trust_remote_code=True, + disable_radix_cache=True, + port=port, + attention_backend="flashinfer", + mem_fraction_static=0.80, + ) as runner: + outputs = runner.forward( + prompts, + max_new_tokens=MAX_NEW_TOKENS, + lora_paths=lora_paths_per_prompt, + ) + + return { + "top_input_logprobs": outputs.top_input_logprobs, + "top_output_logprobs": outputs.top_output_logprobs, + "output_strs": outputs.output_strs, + } + + +class TestMoELoRATP2Logprobs(CustomTestCase): + """Compare TP=1 vs TP=2 MoE LoRA: output strings must match and logprobs + must stay within threshold.""" + + def _assert_tp_parity( + self, + prompts: List[str], + label: str, + ): + print(f"\n{'=' * 100}") + print(f" {label}: running TP=1") + print(f"{'=' * 100}") + + tp1 = _run_sglang_moe_lora(tp_size=1, prompts=prompts) + torch.cuda.empty_cache() + + print(f"\n{'=' * 100}") + print(f" {label}: running TP=2") + print(f"{'=' * 100}") + + tp2 = _run_sglang_moe_lora(tp_size=2, prompts=prompts) + + print(f"\n{'=' * 100}") + print( + f"{'ID':<4} | {'String':<8} | {'Decode Max Diff':<18} | " + f"{'Decode Mean Diff':<18} | {'Status':<8} | {'Output (TP1)'}" + ) + print("-" * 100) + + for i in range(len(prompts)): + tp1_str = tp1["output_strs"][i].strip() + tp2_str = tp2["output_strs"][i].strip() + + self.assertEqual( + tp1_str, + tp2_str, + f"Output string mismatch on prompt {i}: " + f"TP1='{tp1_str}' vs TP2='{tp2_str}'", + ) + + tp1_raw = tp1["top_output_logprobs"][i] + tp2_raw = tp2["top_output_logprobs"][i] + tp1_lps = torch.tensor( + [t[0] if isinstance(t, list) else t for t in tp1_raw] + ) + tp2_lps = torch.tensor( + [t[0] if isinstance(t, list) else t for t in tp2_raw] + ) + min_len = min(tp1_lps.shape[0], tp2_lps.shape[0]) + diff = torch.abs(tp1_lps[:min_len] - tp2_lps[:min_len]) + max_diff = torch.max(diff).item() if min_len > 0 else 0.0 + mean_diff = torch.mean(diff).item() if min_len > 0 else 0.0 + + status = "PASS" if max_diff < LOGPROB_THRESHOLD else "FAIL" + print( + f"{i:<4} | {'OK':<8} | {max_diff:<18.6e} | " + f"{mean_diff:<18.6e} | {status:<8} | {tp1_str[:40]}" + ) + + self.assertLessEqual( + max_diff, + LOGPROB_THRESHOLD, + f"Decode logprob diff too large on prompt {i}: " + f"max_diff={max_diff:.6e} > threshold={LOGPROB_THRESHOLD:.0e}", + ) + + print("=" * 100) + + def test_moe_lora_tp2_vs_tp1_basic(self): + """Basic TP=1 vs TP=2 parity with a small prompt set.""" + self._assert_tp_parity( + prompts=MOE_LORA_TEST_PROMPTS[:5], + label="MoE LoRA TP parity (basic)", + ) + + @unittest.skipIf(is_in_ci(), "Skipping full test in CI") + def test_moe_lora_tp2_vs_tp1_full(self): + """Full TP=1 vs TP=2 parity across all prompts.""" + self._assert_tp_parity( + prompts=MOE_LORA_TEST_PROMPTS, + label="MoE LoRA TP parity (full)", + ) + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_moe_vllm_sgl_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_moe_vllm_sgl_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..d3ab6dbe49dbffbec8378dfb74e76e238d8e2452 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_moe_vllm_sgl_logprob_diff.py @@ -0,0 +1,368 @@ +""" +Regression test for MoE LoRA parity between SGLang and vLLM. + +This test compares SGLang's logprobs and output strings against a hardcoded +baseline (VLLM_CACHED_RESULTS) generated using vLLM. It enforces strict +numerical accuracy by asserting that the maximum and mean logprob +divergences do not exceed the reference thresholds (REFERENCE_STATS). + +Usage: + python -m unittest test_lora_moe_vllm_sgl_logprob_diff.py + +""" + +import multiprocessing as mp +import unittest + +import torch + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.lora_utils import ( + MOE_BASE_MODEL_PATH, + MOE_LORA_PATH, + MOE_LORA_TEST_PROMPTS, +) +from sglang.test.runners import SRTRunner + +register_cuda_ci( + est_time=50, + stage="base-b", + runner_config="1-gpu-large", +) + +# Format: [{"text": "result string", "lps": [0.1, 0.2, ...]}, ...] +VLLM_CACHED_RESULTS = [ + { + "text": " A0PURH0", + "lps": [ + -3.3378546504536644e-06, + -1.6331539882230572e-05, + -7.152555099310121e-07, + -5.054346183896996e-05, + -4.792098479811102e-05, + -3.302042750874534e-05, + ], + }, + { + "text": " The wild tree jumped at the cafe and found a", + "lps": [ + -9.417489309271332e-06, + -1.2636104656849056e-05, + -0.00018308870494365692, + -0.0006621075444854796, + -5.3165931603871286e-05, + -9.500529267825186e-05, + -0.0003022690652869642, + -6.9141146923357155e-06, + 0.0, + -8.22540732769994e-06, + ], + }, + { + "text": " 0SPG1V6L", + "lps": [ + -2.861018856492592e-06, + -6.8662193370983e-05, + -6.580135959666222e-05, + -5.6980417866725475e-05, + -8.916457591112703e-05, + -5.006777428206988e-06, + -1.8596476365928538e-05, + -2.396077979938127e-05, + -4.851700214203447e-05, + ], + }, + {"text": " Tango", "lps": [-5.960462772236497e-07, -9.536738616588991e-07]}, + {"text": " Tensor", "lps": [-0.0002002515539061278, -5.960462772236497e-07]}, + { + "text": " The slow cat coded in a simulation and found a", + "lps": [ + 0.0, + -4.672895011026412e-05, + -3.802703940891661e-05, + -3.1709168979432434e-05, + 0.0, + -2.145764938177308e-06, + -4.565611743601039e-05, + 0.0, + 0.0, + -2.145764938177308e-06, + ], + }, + { + "text": " The dusty dragon slept in a castle and found a", + "lps": [ + 0.0, + -3.290122185717337e-05, + -1.1444026313256472e-05, + -6.544376083184034e-05, + -8.344646857949556e-07, + -2.276871418871451e-05, + -2.1576648578047752e-05, + -5.960462772236497e-07, + 0.0, + -2.50339189733495e-06, + ], + }, + { + "text": " T4JDBF", + "lps": [ + -5.960462772236497e-07, + -3.4450891689630225e-05, + -1.1324817933200393e-05, + -1.6689160474925302e-05, + -0.00020013237372040749, + -3.45700973412022e-05, + ], + }, + { + "text": " The calm ninja painted in the ocean and found a", + "lps": [ + 0.0, + -3.731181277544238e-05, + -6.198863957251888e-06, + -3.576272320060525e-06, + -3.576278118089249e-07, + -3.814689989667386e-06, + -1.549708758830093e-05, + -1.1920928244535389e-07, + 0.0, + -4.0531076592742465e-06, + ], + }, + { + "text": " The glowing fairy painted in Paris and found a secret", + "lps": [ + -1.1920928244535389e-07, + -2.8132995794294402e-05, + -2.50339189733495e-06, + -4.446407547220588e-05, + -3.576278118089249e-07, + -8.201262971851975e-05, + -3.576278118089249e-07, + 0.0, + -4.0531076592742465e-06, + -3.4570634852570947e-06, + ], + }, + {"text": " Tensor", "lps": [-0.00014399446081370115, -2.622600959512056e-06]}, + { + "text": " WFNNORK", + "lps": [ + -0.0003231241717003286, + -3.71926071238704e-05, + -0.00011252723925281316, + -5.447716102935374e-05, + ], + }, + { + "text": " Whiskey", + "lps": [ + -5.531158240046352e-05, + -1.5497195136049413e-06, + -1.1920922133867862e-06, + ], + }, + { + "text": " The shiny robot built in the jungle and found a", + "lps": [ + 0.0, + -2.622600959512056e-06, + -5.018585216021165e-05, + -0.0015173362335190177, + 0.0, + -6.198863957251888e-06, + -0.00036769305006600916, + -1.1920928244535389e-07, + 0.0, + -3.099436753473128e-06, + ], + }, + { + "text": " XWGXRNS", + "lps": [ + -2.5629668016335927e-05, + -4.0531076592742465e-06, + -0.0001616347290109843, + -5.018585216021165e-05, + -0.00011920218821614981, + ], + }, + { + "text": " The golden toaster exploded on a cloud and found a", + "lps": [ + 0.0, + -8.630380034446716e-05, + 0.0, + -2.4676019165781327e-05, + -1.0728830375228426e-06, + -1.5497195136049413e-06, + -6.794906312279636e-06, + -4.887569048150908e-06, + 0.0, + -3.3378546504536644e-06, + ], + }, + { + "text": " Nebula", + "lps": [ + -4.410734163684538e-06, + -7.986990567587782e-06, + -1.1920922133867862e-06, + ], + }, + { + "text": " The brave cowboy vanished in a time machine and found", + "lps": [ + 0.0, + -8.475421054754406e-05, + -0.00011932138295378536, + -0.00016735584358684719, + -2.3841855067985307e-07, + -2.312633478140924e-05, + -6.5205356804654e-05, + -0.00014423283573705703, + -1.4305104514278355e-06, + 0.0, + ], + }, + { + "text": " HNKA4N3T", + "lps": [ + -2.50339189733495e-06, + -1.1920928244535389e-07, + -5.006777428206988e-06, + -7.390948667307384e-06, + -0.00014327930693980306, + -2.3841855067985307e-07, + -0.00011062010162277147, + -1.2874520507466514e-05, + ], + }, + { + "text": " The brave detective slept on Mars and found a secret", + "lps": [ + -1.7881377516459906e-06, + -1.9788545614574105e-05, + -1.883488948806189e-05, + -1.4781842764932662e-05, + -3.576278118089249e-07, + -1.2755313036905136e-05, + -5.960462772236497e-07, + 0.0, + -4.0531076592742465e-06, + -1.5497195136049413e-06, + ], + }, +] +# --------------------------------- + + +# Hardcoded reference stats from successful run. Corresponds to prompts below. +REFERENCE_STATS = { + 0: {"max": 9.29792076931335e-06, "mean": 2.8410576836298182e-06}, + 1: {"max": 1.3818731531500816e-05, "mean": 3.753847045118164e-06}, + 2: {"max": 1.1205123882973567e-05, "mean": 2.410548404441215e-06}, + 3: {"max": 1.1920923270736239e-07, "mean": 1.1920920428565296e-07}, + 4: {"max": 1.0011601261794567e-05, "mean": 5.065405247250965e-06}, + 5: {"max": 5.602585588349029e-06, "mean": 1.6569420949963388e-06}, + 6: {"max": 2.9801594791933894e-06, "mean": 8.702030129370542e-07}, + 7: {"max": 1.6685822629369795e-05, "mean": 4.608787548932014e-06}, + 8: {"max": 2.384102117503062e-06, "mean": 5.721932211599778e-07}, + 9: {"max": 1.704567694105208e-05, "mean": 1.9787427085304897e-06}, + 10: {"max": 1.2515258276835084e-05, "mean": 6.37683808690781e-06}, + 11: {"max": 1.4900237147230655e-05, "mean": 1.0101463885803241e-05}, + 12: {"max": 1.6688391042407602e-06, "mean": 5.960160933682346e-07}, + 13: {"max": 9.04605258256197e-06, "mean": 1.2144706943217897e-06}, + 14: {"max": 2.181154559366405e-05, "mean": 6.102668112362153e-06}, + 15: {"max": 5.602370947599411e-06, "mean": 6.07920344464219e-07}, + 16: {"max": 2.2649692255072296e-06, "mean": 7.549897418357432e-07}, + 17: {"max": 1.990482269320637e-05, "mean": 3.3731695992855747e-06}, + 18: {"max": 1.6567864804528654e-05, "mean": 3.307691372356203e-06}, + 19: {"max": 2.5033668862306513e-06, "mean": 3.3378251487192754e-07}, +} + + +class TestMoELoraRegression(unittest.TestCase): + + def test_sglang_moe_parity_strict(self): + + with SRTRunner( + model_path=MOE_BASE_MODEL_PATH, + torch_dtype=torch.bfloat16, + model_type="generation", + lora_paths=[MOE_LORA_PATH], + max_loras_per_batch=1, + tp_size=1, + trust_remote_code=True, + disable_radix_cache=True, + attention_backend="flashinfer", + mem_fraction_static=0.80, + ) as srt_runner: + + srt_outputs = srt_runner.forward( + MOE_LORA_TEST_PROMPTS, + max_new_tokens=10, + lora_paths=[MOE_LORA_PATH] * len(MOE_LORA_TEST_PROMPTS), + ) + + print("\n" + "=" * 140) + print( + f"{'ID':<4} | {'Max Diff':<12} | {'Mean Diff':<12} | {'Status':<8} | {'Prompt'}" + ) + print("-" * 140) + + for i, prompt in enumerate(MOE_LORA_TEST_PROMPTS): + v_data = VLLM_CACHED_RESULTS[i] + v_lps = v_data["lps"] + v_text = v_data["text"].strip() + + s_lps_raw = srt_outputs.top_output_logprobs[i] + s_lps = [ + float(token[0]) if isinstance(token, list) else float(token) + for token in s_lps_raw + ] + s_text = srt_outputs.output_strs[i].strip() + + # Calculate actual stats + min_len = min(len(v_lps), len(s_lps)) + diffs = [abs(v_lps[t] - s_lps[t]) for t in range(min_len)] + + actual_max = max(diffs) if diffs else 0.0 + actual_mean = sum(diffs) / len(diffs) if diffs else 0.0 + + ref = REFERENCE_STATS[i] + # Epsilon to allow room for different, but correct, implementations + eps = 2e-4 + + # Assertions + self.assertEqual(v_text, s_text, f"String mismatch on prompt {i}") + self.assertLessEqual( + actual_max, ref["max"] + eps, f"Max LogProb Diff exceeded on prompt {i}" + ) + self.assertLessEqual( + actual_mean, + ref["mean"] + eps, + f"Mean LogProb Diff exceeded on prompt {i}", + ) + + print( + f"{i:<4} | {actual_max:<12.6f} | {actual_mean:<12.6f} | {'✅ PASS':<8} | {prompt}" + ) + + print("=" * 140) + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + # Final cleanup + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_nemotron_3_super_120b_a12b_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_nemotron_3_super_120b_a12b_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdcf72810b188e7ebe1e6443be166be295962be --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_nemotron_3_super_120b_a12b_logprob_diff.py @@ -0,0 +1,151 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Regression test for NVIDIA-Nemotron-3-Super-120B-A12B-BF16 LoRA logprob accuracy. + +Compares SGLang LoRA logprobs against reference training logprobs from a +pre-computed dataset. The LoRA adapter and reference data are downloaded from: +https://huggingface.co/datasets/opherlie/lora-test-case-NVIDIA-Nemotron-3-Super-120B-A12B-BF16 + +Usage: + python -m unittest test_lora_nemotron_3_super_120b_a12b_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest + +import torch +from huggingface_hub import snapshot_download + +import sglang as sgl +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=100, stage="extra-b", runner_config="4-gpu-b200") + +BASE_MODEL = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16" +LORA_HF_REPO = "opherlie/lora-test-case-NVIDIA-Nemotron-3-Super-120B-A12B-BF16" +LORA_BACKEND = "triton" +MAX_LORA_RANK = 64 +TP_SIZE = 4 +MOE_RUNNER_BACKEND = "triton" +EXPERTS_SHARED_OUTER_LORAS = True +LORA_USE_VIRTUAL_EXPERTS = True +DISABLE_SHARED_EXPERTS_FUSION = True + +KL_THRESHOLD = 2.5e-3 + + +def kl_v2(a, b): + a = torch.tensor(a) if not torch.is_tensor(a) else a + b = torch.tensor(b) if not torch.is_tensor(b) else b + return (((a - b) ** 2) * 0.5).mean().item() + + +def get_prompt_logprobs(engine, input_ids, lora_path): + if isinstance(input_ids, torch.Tensor): + input_ids = [input_ids.tolist()] + elif not isinstance(input_ids[0], list): + input_ids = [input_ids] + out = engine.generate( + input_ids=input_ids, + sampling_params={"max_new_tokens": 0, "temperature": 0.0}, + return_logprob=True, + logprob_start_len=0, + lora_path=lora_path, + ) + if isinstance(out, list): + out = out[0] + return [logprob for logprob, _, _ in out["meta_info"]["input_token_logprobs"]][1:] + + +class TestLoRANemotron3Super120B_A12B_LogprobDiff(CustomTestCase): + + def test_lora_nemotron_3_super_120b_a12b_logprob_accuracy(self): + adapter_path = snapshot_download( + LORA_HF_REPO, + repo_type="dataset", + ) + + engine = sgl.Engine( + model_path=BASE_MODEL, + tp_size=TP_SIZE, + enable_lora=True, + max_lora_rank=MAX_LORA_RANK, + lora_paths={"my_lora": adapter_path}, + lora_backend=LORA_BACKEND, + moe_runner_backend=MOE_RUNNER_BACKEND, + experts_shared_outer_loras=EXPERTS_SHARED_OUTER_LORAS, + lora_use_virtual_experts=LORA_USE_VIRTUAL_EXPERTS, + disable_shared_experts_fusion=DISABLE_SHARED_EXPERTS_FUSION, + ) + + try: + cdata = torch.load( + os.path.join(adapter_path, "compare_sample_train_data.pt"), + weights_only=False, + ) + + base_logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path=None) + logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path="my_lora") + + base_t = torch.tensor(base_logprobs) + lora_t = torch.tensor(logprobs) + diff = (base_t - lora_t).abs() + print( + f"[VERIFY] base vs lora: mean_diff={diff.mean().item():.6f}, " + f"max_diff={diff.max().item():.6f}, " + f"identical={torch.equal(base_t, lora_t)}" + ) + + self.assertFalse( + torch.equal(base_t, lora_t), + "LoRA logprobs should differ from base model logprobs", + ) + + kl_sglang_trainer = kl_v2(cdata["training_logprobs"], logprobs) + kl_orig_trainer = kl_v2( + cdata["training_logprobs"], cdata["sampling_logprobs"] + ) + kl_sglang_orig = kl_v2(logprobs, cdata["sampling_logprobs"]) + + print(f"KL(orig_sampler, trainer) = {kl_orig_trainer:.6e}") + print(f"KL(sglang, trainer) = {kl_sglang_trainer:.6e}") + print(f"KL(sglang, orig_sampler) = {kl_sglang_orig:.6e}") + + self.assertLessEqual( + kl_sglang_trainer, + KL_THRESHOLD, + f"KL(sglang, trainer) = {kl_sglang_trainer:.6e} exceeds " + f"threshold {KL_THRESHOLD}", + ) + + finally: + engine.shutdown() + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_openai_api.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_openai_api.py new file mode 100644 index 0000000000000000000000000000000000000000..69c31b72c903c042cec846de8a78ed1e5aceb146 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_openai_api.py @@ -0,0 +1,262 @@ +""" +Unit tests for OpenAI-compatible LoRA API support. + +Tests the model parameter parsing and LoRA adapter resolution logic +that enables OpenAI-compatible LoRA adapter selection. +""" + +import unittest +from unittest.mock import MagicMock + +from sglang.srt.entrypoints.openai.serving_base import OpenAIServingBase +from sglang.srt.server_args import ServerArgs +from sglang.test.ci.ci_register import ( + register_amd_ci, + register_cpu_ci, + register_cuda_ci, +) + +register_cuda_ci(est_time=30, suite="nightly-1-gpu", nightly=True) +register_amd_ci(est_time=30, suite="nightly-amd-1-gpu", nightly=True) +register_cpu_ci(est_time=8, suite="base-c-test-cpu") + + +class MockTokenizerManager: + """Mock TokenizerManager for testing.""" + + def __init__(self, enable_lora=False): + self.server_args = MagicMock(spec=ServerArgs) + self.server_args.enable_lora = enable_lora + self.server_args.tokenizer_metrics_allowed_custom_labels = None + + +class ConcreteServingBase(OpenAIServingBase): + """Concrete implementation for testing abstract base class.""" + + def _request_id_prefix(self) -> str: + return "test-" + + def _convert_to_internal_request(self, request, raw_request=None): + pass + + def _validate_request(self, request): + pass + + +class TestParseModelParameter(unittest.TestCase): + """Test _parse_model_parameter method.""" + + def setUp(self): + self.tokenizer_manager = MockTokenizerManager(enable_lora=True) + self.serving = ConcreteServingBase(self.tokenizer_manager) + + def test_model_without_adapter(self): + """Test parsing model without adapter returns None for adapter.""" + base_model, adapter = self.serving._parse_model_parameter("llama-3.1-8B") + self.assertEqual(base_model, "llama-3.1-8B") + self.assertIsNone(adapter) + + def test_model_with_adapter(self): + """Test parsing model with adapter extracts both parts.""" + base_model, adapter = self.serving._parse_model_parameter( + "llama-3.1-8B:sql-expert" + ) + self.assertEqual(base_model, "llama-3.1-8B") + self.assertEqual(adapter, "sql-expert") + + def test_model_with_path_and_adapter(self): + """Test parsing model path with slashes and adapter.""" + base_model, adapter = self.serving._parse_model_parameter( + "meta-llama/Llama-3.1-8B-Instruct:adapter-name" + ) + self.assertEqual(base_model, "meta-llama/Llama-3.1-8B-Instruct") + self.assertEqual(adapter, "adapter-name") + + def test_model_with_multiple_colons(self): + """Test that only first colon is used for splitting.""" + base_model, adapter = self.serving._parse_model_parameter("model:adapter:extra") + self.assertEqual(base_model, "model") + self.assertEqual(adapter, "adapter:extra") + + def test_model_with_whitespace(self): + """Test that whitespace is stripped from both parts.""" + base_model, adapter = self.serving._parse_model_parameter( + " model-name : adapter-name " + ) + self.assertEqual(base_model, "model-name") + self.assertEqual(adapter, "adapter-name") + + def test_model_with_empty_adapter(self): + """Test model ending with colon returns None for adapter.""" + base_model, adapter = self.serving._parse_model_parameter("model-name:") + self.assertEqual(base_model, "model-name") + self.assertIsNone(adapter) + + def test_model_with_only_spaces_after_colon(self): + """Test model with only whitespace after colon returns None for adapter.""" + base_model, adapter = self.serving._parse_model_parameter("model-name: ") + self.assertEqual(base_model, "model-name") + self.assertIsNone(adapter) + + +class TestResolveLoraPath(unittest.TestCase): + """Test _resolve_lora_path method.""" + + def setUp(self): + self.tokenizer_manager = MockTokenizerManager(enable_lora=True) + self.serving = ConcreteServingBase(self.tokenizer_manager) + + def test_no_adapter_specified(self): + """Test when neither model nor explicit lora_path has adapter.""" + result = self.serving._resolve_lora_path("model-name", None) + self.assertIsNone(result) + + def test_adapter_in_model_only(self): + """Test adapter from model parameter when no explicit path.""" + result = self.serving._resolve_lora_path("model:sql-expert", None) + self.assertEqual(result, "sql-expert") + + def test_adapter_in_explicit_only(self): + """Test adapter from explicit lora_path when not in model.""" + result = self.serving._resolve_lora_path("model-name", "python-expert") + self.assertEqual(result, "python-expert") + + def test_model_parameter_takes_precedence(self): + """Test model parameter adapter takes precedence over explicit.""" + result = self.serving._resolve_lora_path("model:sql-expert", "python-expert") + self.assertEqual(result, "sql-expert") + + def test_with_list_explicit_lora_path(self): + """Test that explicit list is returned when no model adapter.""" + explicit = ["adapter1", "adapter2", None] + result = self.serving._resolve_lora_path("model-name", explicit) + self.assertEqual(result, explicit) + + def test_model_adapter_overrides_list(self): + """Test model adapter overrides even when explicit is a list.""" + result = self.serving._resolve_lora_path( + "model:sql-expert", ["adapter1", "adapter2"] + ) + self.assertEqual(result, "sql-expert") + + def test_complex_model_name_with_adapter(self): + """Test resolution with complex model name.""" + result = self.serving._resolve_lora_path( + "org/model-v2.1:adapter-name", "other-adapter" + ) + self.assertEqual(result, "adapter-name") + + +class TestIntegrationScenarios(unittest.TestCase): + """Integration tests for common usage scenarios.""" + + def setUp(self): + self.tokenizer_manager = MockTokenizerManager(enable_lora=True) + self.serving = ConcreteServingBase(self.tokenizer_manager) + + def test_openai_compatible_usage(self): + """Test typical OpenAI-compatible usage pattern.""" + # User specifies adapter in model parameter + model = "meta-llama/Llama-3.1-8B:sql-expert" + explicit_lora = None + + lora_path = self.serving._resolve_lora_path(model, explicit_lora) + self.assertEqual(lora_path, "sql-expert") + + def test_backward_compatible_usage(self): + """Test backward-compatible usage with explicit lora_path.""" + model = "meta-llama/Llama-3.1-8B" + explicit_lora = "sql-expert" + + lora_path = self.serving._resolve_lora_path(model, explicit_lora) + self.assertEqual(lora_path, "sql-expert") + + def test_base_model_usage(self): + """Test using base model without any adapter.""" + model = "meta-llama/Llama-3.1-8B" + explicit_lora = None + + lora_path = self.serving._resolve_lora_path(model, explicit_lora) + self.assertIsNone(lora_path) + + # No validation needed when no adapter + + def test_batch_request_scenario(self): + """Test batch request with list of adapters.""" + model = "meta-llama/Llama-3.1-8B" # No adapter in model + explicit_lora = ["sql-expert", "python-expert", None] + + lora_path = self.serving._resolve_lora_path(model, explicit_lora) + self.assertEqual(lora_path, explicit_lora) + + def test_adapter_in_model_overrides_batch_list(self): + """Test that adapter in model parameter overrides batch list.""" + model = "meta-llama/Llama-3.1-8B:preferred-adapter" + explicit_lora = ["adapter1", "adapter2"] + + lora_path = self.serving._resolve_lora_path(model, explicit_lora) + self.assertEqual(lora_path, "preferred-adapter") + + +class TestEdgeCases(unittest.TestCase): + """Test edge cases and error conditions.""" + + def setUp(self): + self.tokenizer_manager = MockTokenizerManager(enable_lora=True) + self.serving = ConcreteServingBase(self.tokenizer_manager) + + def test_empty_string_model(self): + """Test handling of empty string model.""" + base, adapter = self.serving._parse_model_parameter("") + self.assertEqual(base, "") + self.assertIsNone(adapter) + + def test_only_colon(self): + """Test model parameter that is just a colon.""" + base, adapter = self.serving._parse_model_parameter(":") + self.assertEqual(base, "") + self.assertIsNone(adapter) + + def test_empty_list_lora_path(self): + """Test validation with empty list doesn't crash.""" + lora_path = self.serving._resolve_lora_path("model-name", []) + # Empty list is falsy, so validation won't be called + self.assertEqual(lora_path, []) + + def test_list_with_none_first(self): + """Test validation finds first non-None adapter in list.""" + lora_path = self.serving._resolve_lora_path("model-name", [None, "adapter2"]) + self.assertEqual(lora_path, [None, "adapter2"]) + # In actual usage, validation would find "adapter2" + + def test_list_all_none(self): + """Test validation with list of all None values.""" + lora_path = self.serving._resolve_lora_path("model-name", [None, None]) + self.assertEqual(lora_path, [None, None]) + # In actual usage, no validation would occur (no non-None adapters) + + def test_unicode_in_adapter_name(self): + """Test Unicode characters in adapter name.""" + base, adapter = self.serving._parse_model_parameter("model:adapter-名前") + self.assertEqual(base, "model") + self.assertEqual(adapter, "adapter-名前") + + def test_special_characters_in_adapter(self): + """Test special characters in adapter name.""" + base, adapter = self.serving._parse_model_parameter("model:adapter_v2.1-final") + self.assertEqual(base, "model") + self.assertEqual(adapter, "adapter_v2.1-final") + + def test_none_as_explicit_lora_path(self): + """Test None as explicit lora_path is handled correctly.""" + result = self.serving._resolve_lora_path("model:adapter", None) + self.assertEqual(result, "adapter") + + def test_empty_string_as_explicit_lora_path(self): + """Test empty string as explicit lora_path.""" + result = self.serving._resolve_lora_path("model-name", "") + self.assertEqual(result, "") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_openai_compatible.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_openai_compatible.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1b409d67987dab7b55dea11ef18f6cc07d4ab6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_openai_compatible.py @@ -0,0 +1,282 @@ +""" +End-to-end tests for OpenAI-compatible LoRA adapter usage. + +Tests the model:adapter syntax and backward compatibility with explicit lora_path. + +Usage: + python3 -m unittest openai_server.features.test_lora_openai_compatible.TestLoRAOpenAICompatible.test_model_adapter_syntax + python3 -m unittest openai_server.features.test_lora_openai_compatible.TestLoRAOpenAICompatible.test_explicit_lora_path + python3 -m unittest openai_server.features.test_lora_openai_compatible.TestLoRAOpenAICompatible.test_priority_model_over_explicit + python3 -m unittest openai_server.features.test_lora_openai_compatible.TestLoRAOpenAICompatible.test_base_model_no_adapter + python3 -m unittest openai_server.features.test_lora_openai_compatible.TestLoRAOpenAICompatible.test_completions_api_with_adapter + python3 -m unittest openai_server.features.test_lora_openai_compatible.TestLoRAOpenAICompatible.test_streaming_with_adapter + python3 -m unittest openai_server.features.test_lora_openai_compatible.TestLoRADisabledError.test_lora_disabled_error +""" + +import unittest + +import openai + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=150, suite="nightly-1-gpu", nightly=True) +register_amd_ci(est_time=150, suite="nightly-amd-1-gpu", nightly=True) + + +def get_real_lora_adapter() -> str: + """Use a real LoRA adapter from Hugging Face.""" + return "codelion/Llama-3.2-1B-Instruct-tool-calling-lora" + + +def setup_class(cls, enable_lora=True): + """Setup test class with LoRA-enabled server.""" + cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + + # Use real LoRA adapter + cls.lora_adapter_path = get_real_lora_adapter() + + other_args = [ + "--max-running-requests", + "10", + "--disable-radix-cache", # Disable cache for cleaner tests + ] + + if enable_lora: + other_args.extend( + [ + "--enable-lora", + "--lora-paths", + f"tool_calling={cls.lora_adapter_path}", + ] + ) + + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + cls.client = openai.Client(api_key="EMPTY", base_url=f"{cls.base_url}/v1") + + +class TestLoRAOpenAICompatible(CustomTestCase): + """Test OpenAI-compatible LoRA adapter usage.""" + + @classmethod + def setUpClass(cls): + setup_class(cls, enable_lora=True) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_model_adapter_syntax(self): + """Test the new model:adapter syntax works correctly.""" + response = self.client.chat.completions.create( + # ← New OpenAI-compatible syntax + model=f"{self.model}:tool_calling", + messages=[{"role": "user", "content": "What tools do you have available?"}], + max_tokens=50, + temperature=0, + ) + + self.assertIsNotNone(response.choices[0].message.content) + self.assertGreater(len(response.choices[0].message.content), 0) + print(f"Model adapter syntax response: {response.choices[0].message.content}") + + def test_explicit_lora_path(self): + """Test backward compatibility with explicit lora_path via extra_body.""" + response = self.client.chat.completions.create( + model=self.model, + messages=[{"role": "user", "content": "What tools do you have available?"}], + # ← Legacy explicit method + extra_body={"lora_path": "tool_calling"}, + max_tokens=50, + temperature=0, + ) + + self.assertIsNotNone(response.choices[0].message.content) + self.assertGreater(len(response.choices[0].message.content), 0) + print(f"Explicit lora_path response: {response.choices[0].message.content}") + + def test_priority_model_over_explicit(self): + """Test that model:adapter syntax takes precedence over explicit lora_path.""" + # This test verifies the priority logic in _resolve_lora_path + response = self.client.chat.completions.create( + # ← Model specifies tool_calling adapter + model=f"{self.model}:tool_calling", + messages=[{"role": "user", "content": "What tools do you have available?"}], + # ← Both specify same adapter + extra_body={"lora_path": "tool_calling"}, + max_tokens=50, + temperature=0, + ) + + # Should use tool_calling adapter (model parameter takes precedence) + self.assertIsNotNone(response.choices[0].message.content) + self.assertGreater(len(response.choices[0].message.content), 0) + print(f"Priority test response: {response.choices[0].message.content}") + + def test_base_model_no_adapter(self): + """Test using base model without any adapter.""" + response = self.client.chat.completions.create( + model=self.model, # ← No adapter specified + messages=[{"role": "user", "content": "Hello, how are you?"}], + max_tokens=30, + temperature=0, + ) + + self.assertIsNotNone(response.choices[0].message.content) + self.assertGreater(len(response.choices[0].message.content), 0) + print(f"Base model response: {response.choices[0].message.content}") + + def test_completions_api_with_adapter(self): + """Test completions API with LoRA adapter.""" + response = self.client.completions.create( + model=f"{self.model}:tool_calling", # ← Using model:adapter syntax + prompt="What tools do you have available?", + max_tokens=50, + temperature=0, + ) + + self.assertIsNotNone(response.choices[0].text) + self.assertGreater(len(response.choices[0].text), 0) + print(f"Completions API response: {response.choices[0].text}") + + def test_streaming_with_adapter(self): + """Test streaming with LoRA adapter.""" + stream = self.client.chat.completions.create( + model=f"{self.model}:tool_calling", + messages=[{"role": "user", "content": "What tools do you have available?"}], + max_tokens=50, + temperature=0, + stream=True, + ) + + collected_content = "" + for chunk in stream: + if chunk.choices[0].delta.content: + collected_content += chunk.choices[0].delta.content + + self.assertGreater(len(collected_content), 0) + print(f"Streaming response: {collected_content}") + + def test_multiple_adapters(self): + """Test using different adapters in sequence.""" + # Test tool_calling adapter + tool_response = self.client.chat.completions.create( + model=f"{self.model}:tool_calling", + messages=[{"role": "user", "content": "What tools do you have available?"}], + max_tokens=30, + temperature=0, + ) + + # Test base model without adapter + base_response = self.client.chat.completions.create( + model=self.model, + messages=[{"role": "user", "content": "Hello, how are you?"}], + max_tokens=30, + temperature=0, + ) + + self.assertIsNotNone(tool_response.choices[0].message.content) + self.assertIsNotNone(base_response.choices[0].message.content) + print( + f"Tool calling adapter response: {tool_response.choices[0].message.content}" + ) + print(f"Base model response: {base_response.choices[0].message.content}") + + +class TestLoRADisabledError(CustomTestCase): + """Test error handling when LoRA is disabled.""" + + @classmethod + def setUpClass(cls): + setup_class(cls, enable_lora=False) # ← LoRA disabled + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_lora_disabled_error(self): + """Test that using LoRA adapter when LoRA is disabled raises appropriate error.""" + with self.assertRaises(openai.APIError) as context: + self.client.chat.completions.create( + model=f"{self.model}:tool_calling", # ← Trying to use adapter + messages=[ + {"role": "user", "content": "What tools do you have available?"} + ], + max_tokens=50, + ) + + # Verify the error message contains helpful guidance + error_message = str(context.exception) + self.assertIn("LoRA", error_message) + self.assertIn("not enabled", error_message) + print(f"Expected error message: {error_message}") + + +class TestLoRAEdgeCases(CustomTestCase): + """Test edge cases for LoRA adapter usage.""" + + @classmethod + def setUpClass(cls): + setup_class(cls, enable_lora=True) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_model_with_colon_no_adapter(self): + """Test model parameter ending with colon (empty adapter).""" + response = self.client.chat.completions.create( + model=f"{self.model}:", # ← Model ends with colon + messages=[{"role": "user", "content": "Hello!"}], + max_tokens=30, + temperature=0, + ) + + # Should work as base model (no adapter) + self.assertIsNotNone(response.choices[0].message.content) + print(f"Model with colon response: {response.choices[0].message.content}") + + def test_explicit_lora_path_none(self): + """Test explicit lora_path set to None.""" + response = self.client.chat.completions.create( + model=self.model, + messages=[{"role": "user", "content": "Hello!"}], + extra_body={"lora_path": None}, # ← Explicitly None + max_tokens=30, + temperature=0, + ) + + # Should work as base model + self.assertIsNotNone(response.choices[0].message.content) + print( + f"Explicit None lora_path response: {response.choices[0].message.content}" + ) + + def test_invalid_adapter_name(self): + """Test using non-existent adapter name.""" + with self.assertRaises(openai.APIError) as context: + self.client.chat.completions.create( + model=f"{self.model}:nonexistent", # ← Non-existent adapter + messages=[{"role": "user", "content": "Hello!"}], + max_tokens=30, + ) + + error_message = str(context.exception) + print(f"Invalid adapter error: {error_message}") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_overlap_loading.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_overlap_loading.py new file mode 100644 index 0000000000000000000000000000000000000000..861652f5c3e881caf81242e5b4e10a2dcc67134a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_overlap_loading.py @@ -0,0 +1,247 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import multiprocessing as mp +import unittest +from typing import cast +from unittest.mock import MagicMock, patch + +from torch.cuda import Event as CudaEvent +from torch.cuda import Stream as CudaStream + +from sglang.srt.lora.lora_manager import LoRAManager +from sglang.srt.lora.lora_overlap_loader import LoRAOverlapLoader, LoRAOverlapLoadStatus +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.lora_utils import ( + CI_MULTI_LORA_MODELS, + run_lora_batch_splitting_equivalence_test, +) +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=48, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=75, suite="stage-b-test-1-gpu-small-amd") + + +class TestLoRAOverlapLoading(CustomTestCase): + def test_ci_lora_models_batch_splitting(self): + run_lora_batch_splitting_equivalence_test( + CI_MULTI_LORA_MODELS, enable_lora_overlap_loading=True + ) + + +class TestLoRAOverlapLoaderUnitTests(CustomTestCase): + + mock_lora_manager: MagicMock + mock_stream: MagicMock + mock_stream_context: MagicMock + mock_device_module: MagicMock + mock_torch: MagicMock + + def setUp(self): + self.torch_patcher = patch("sglang.srt.lora.lora_overlap_loader.torch") + self.mock_torch = self.torch_patcher.start() + + self.mock_device_module = MagicMock() + self.mock_stream = MagicMock(spec=CudaStream) + self.mock_stream_context = MagicMock() + self.mock_event = MagicMock(spec=CudaEvent) + + self.mock_device_module.Stream.return_value = self.mock_stream + self.mock_device_module.stream.return_value = self.mock_stream_context + self.mock_device_module.Event.return_value = self.mock_event + self.mock_torch.get_device_module.return_value = self.mock_device_module + self.mock_torch.cuda.current_stream.return_value = MagicMock(spec=CudaStream) + + self.mock_lora_manager = MagicMock(spec=LoRAManager) + self.mock_lora_manager.device = "cuda:0" + self.mock_lora_manager.memory_pool = MagicMock() + self.mock_lora_manager.memory_pool.uid_to_buffer_id = {} + self.mock_lora_manager.validate_lora_batch.return_value = True + self.mock_lora_manager.fetch_new_loras.side_effect = self._mark_loras_loaded + + def tearDown(self): + self.torch_patcher.stop() + + def _create_loader(self) -> LoRAOverlapLoader: + return LoRAOverlapLoader(cast(LoRAManager, self.mock_lora_manager)) + + def _mark_loras_loaded(self, new_loras, _loras_to_be_loaded): + for lora_id in new_loras: + self.mock_lora_manager.memory_pool.uid_to_buffer_id[lora_id] = len( + self.mock_lora_manager.memory_pool.uid_to_buffer_id + ) + + def _create_mock_event(self, query_return: bool = False) -> MagicMock: + event = MagicMock(spec=CudaEvent) + event.query.return_value = query_return + return event + + def test_completed_stale_loads_are_reaped_before_capacity_check(self): + loader = self._create_loader() + events = [ + self._create_mock_event(query_return=True), + self._create_mock_event(query_return=False), + ] + self.mock_device_module.Event.side_effect = events + self.mock_lora_manager.validate_lora_batch.side_effect = ( + lambda lora_ids: len(lora_ids) <= 1 + ) + + self.assertTrue( + loader._try_start_overlap_load("stale_lora", running_loras=set()) + ) + self.assertIn("stale_lora", loader.lora_to_overlap_load_event) + + self.mock_lora_manager.fetch_new_loras.reset_mock() + result = loader.try_overlap_load_lora("new_lora", running_loras=set()) + + self.assertFalse(result) + self.assertNotIn("stale_lora", loader.lora_to_overlap_load_event) + self.assertIn("new_lora", loader.lora_to_overlap_load_event) + self.mock_lora_manager.fetch_new_loras.assert_called_once_with( + {"new_lora"}, set() + ) + + def test_loaded_lora_reused_after_stale_event_drain(self): + loader = self._create_loader() + self.mock_lora_manager.memory_pool = MagicMock() + self.mock_lora_manager.memory_pool.uid_to_buffer_id = {} + events = [ + self._create_mock_event(query_return=True), + self._create_mock_event(query_return=False), + ] + self.mock_device_module.Event.side_effect = events + self.mock_lora_manager.validate_lora_batch.side_effect = ( + lambda lora_ids: len(lora_ids) <= 2 + ) + + self.assertTrue(loader._try_start_overlap_load("lora_A", running_loras=set())) + self.assertIn("lora_A", loader.lora_to_overlap_load_event) + + self.mock_lora_manager.fetch_new_loras.reset_mock() + self.assertFalse(loader.try_overlap_load_lora("lora_B", running_loras=set())) + self.assertNotIn("lora_A", loader.lora_to_overlap_load_event) + self.assertIn("lora_B", loader.lora_to_overlap_load_event) + self.mock_lora_manager.fetch_new_loras.assert_called_once_with( + {"lora_B"}, set() + ) + + self.mock_lora_manager.fetch_new_loras.reset_mock() + self.assertTrue(loader.try_overlap_load_lora("lora_A", running_loras=set())) + self.assertIn("lora_B", loader.lora_to_overlap_load_event) + self.mock_lora_manager.fetch_new_loras.assert_not_called() + + def test_pending_lora_load_must_complete_even_if_memory_pool_has_slot(self): + loader = self._create_loader() + self.mock_lora_manager.memory_pool = MagicMock() + self.mock_lora_manager.memory_pool.uid_to_buffer_id = {"lora_A": 0} + + loader.lora_to_overlap_load_event["lora_A"] = self._create_mock_event(False) + + result = loader.try_overlap_load_lora("lora_A", running_loras=set()) + + self.assertFalse(result) + self.mock_lora_manager.fetch_new_loras.assert_not_called() + self.assertIn("lora_A", loader.lora_to_overlap_load_event) + + def test_full_lifecycle_single_lora_load(self): + loader = self._create_loader() + + # Initially not loaded + status = loader._check_overlap_load_status("lora_A") + self.assertEqual(status, LoRAOverlapLoadStatus.NOT_LOADED) + + # First call starts async load, returns False + result = loader.try_overlap_load_lora("lora_A", running_loras=set()) + self.assertFalse(result) + self.assertIn("lora_A", loader.lora_to_overlap_load_event) + self.mock_lora_manager.fetch_new_loras.assert_called_once_with( + {"lora_A"}, set() + ) + + # Simulate load still in progress - returns False, event persists + loader.lora_to_overlap_load_event["lora_A"].query.return_value = False + result = loader.try_overlap_load_lora("lora_A", running_loras=set()) + self.assertFalse(result) + self.assertEqual( + loader._check_overlap_load_status("lora_A"), LoRAOverlapLoadStatus.LOADING + ) + + # Simulate load complete - returns True, event removed + loader.lora_to_overlap_load_event["lora_A"].query.return_value = True + result = loader.try_overlap_load_lora("lora_A", running_loras=set()) + self.assertTrue(result) + self.assertNotIn("lora_A", loader.lora_to_overlap_load_event) + + def test_capacity_constraints_block_new_loads(self): + loader = self._create_loader() + + events = [self._create_mock_event() for _ in range(4)] + self.mock_device_module.Event.side_effect = events + + # Load 3 loras successfully + for i in range(3): + self.assertTrue( + loader._try_start_overlap_load(f"lora_{i}", running_loras=set()) + ) + self.assertEqual(len(loader.lora_to_overlap_load_event), 3) + + # Capacity full - new load blocked + self.mock_lora_manager.validate_lora_batch.return_value = False + self.mock_lora_manager.fetch_new_loras.reset_mock() + result = loader.try_overlap_load_lora("lora_3", running_loras=set()) + self.assertFalse(result) + self.mock_lora_manager.fetch_new_loras.assert_not_called() + self.assertNotIn("lora_3", loader.lora_to_overlap_load_event) + + # First lora completes, freeing capacity + loader.lora_to_overlap_load_event["lora_0"].query.return_value = True + + loader._drain_completed_overlap_loads() + self.assertEqual( + loader._check_overlap_load_status("lora_0"), LoRAOverlapLoadStatus.LOADED + ) + + # Now new load succeeds + self.mock_lora_manager.validate_lora_batch.return_value = True + self.assertTrue(loader._try_start_overlap_load("lora_3", running_loras=set())) + + def test_validation_includes_pending_and_running_loras(self): + loader = self._create_loader() + + events = [self._create_mock_event() for _ in range(5)] + self.mock_device_module.Event.side_effect = events + + # Start pending loads + loader._try_start_overlap_load("pending_1", running_loras=set()) + loader._try_start_overlap_load("pending_2", running_loras=set()) + + # Load new lora with running_loras + self.mock_lora_manager.validate_lora_batch.reset_mock() + running = {"running_1", "running_2"} + loader.try_overlap_load_lora("new_lora", running_loras=running) + + # Validation should include: pending + running + new + call_args = self.mock_lora_manager.validate_lora_batch.call_args[0][0] + expected = {"pending_1", "pending_2", "running_1", "running_2", "new_lora"} + self.assertEqual(call_args, expected) + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + unittest.main(warnings="ignore") diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3.py new file mode 100644 index 0000000000000000000000000000000000000000..08c13364cff841e3d06bdc1af6a0d92527e085fc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3.py @@ -0,0 +1,43 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import multiprocessing as mp +import unittest + +from sglang.test.ci.ci_register import register_amd_ci +from sglang.test.lora_utils import ( + LORA_MODELS_QWEN3, + run_lora_multiple_batch_on_model_cases, +) +from sglang.test.test_utils import CustomTestCase + +register_amd_ci( + est_time=30, + suite="stage-b-test-1-gpu-small-amd", + disabled="see https://github.com/sgl-project/sglang/issues/13107", +) + + +class TestLoRAQwen3(CustomTestCase): + def test_ci_lora_models(self): + run_lora_multiple_batch_on_model_cases(LORA_MODELS_QWEN3) + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + unittest.main(warnings="ignore") diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_30b_a3b_instruct_2507_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_30b_a3b_instruct_2507_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..2a68928bd54dbca7f323f67767c4b14ff9135516 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_30b_a3b_instruct_2507_logprob_diff.py @@ -0,0 +1,147 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Regression test for Qwen3-30B-A3B-Instruct-2507 LoRA logprob accuracy. + +Compares SGLang LoRA logprobs against reference training logprobs from a +pre-computed dataset. The LoRA adapter and reference data are downloaded from: +https://huggingface.co/datasets/yushengsu/lora-diff-Qwen3-30B-A3B-Instruct-2507 + +Usage: + python -m unittest test_lora_qwen3_30b_a3b_instruct_2507_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest + +import torch +from huggingface_hub import snapshot_download + +import sglang as sgl +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=100, stage="extra-b", runner_config="4-gpu-b200") + +BASE_MODEL = "Qwen/Qwen3-30B-A3B-Instruct-2507" +LORA_HF_REPO = "yushengsu/lora-diff-Qwen3-30B-A3B-Instruct-2507" +LORA_BACKEND = "triton" +MAX_LORA_RANK = 32 +TP_SIZE = 4 +MOE_RUNNER_BACKEND = "triton" +EXPERTS_SHARED_OUTER_LORAS = True +PREFILL_ATTENTION_BACKEND = "fa4" +DECODE_ATTENTION_BACKEND = "fa4" + +KL_THRESHOLD = 5e-3 + + +def kl_v2(a, b): + a = torch.tensor(a) if not torch.is_tensor(a) else a + b = torch.tensor(b) if not torch.is_tensor(b) else b + return (((a - b) ** 2) * 0.5).mean().item() + + +def get_prompt_logprobs(engine, input_ids, lora_path): + out = engine.generate( + input_ids=input_ids, + sampling_params={"max_new_tokens": 0, "temperature": 0.0}, + return_logprob=True, + logprob_start_len=0, + lora_path=lora_path, + ) + return [logprob for logprob, _, _ in out["meta_info"]["input_token_logprobs"]][1:] + + +class TestLoRAQwen3_30B_A3B_Instruct_2507_LogprobDiff(CustomTestCase): + + def test_lora_qwen3_30b_a3b_instruct_2507_logprob_accuracy(self): + adapter_path = snapshot_download( + LORA_HF_REPO, + repo_type="dataset", + ) + + engine = sgl.Engine( + model_path=BASE_MODEL, + tp_size=TP_SIZE, + enable_lora=True, + max_lora_rank=MAX_LORA_RANK, + lora_paths={"my_lora": adapter_path}, + lora_backend=LORA_BACKEND, + attention_backend="flashinfer", + flashinfer_allreduce_fusion_backend="trtllm", + moe_runner_backend=MOE_RUNNER_BACKEND, + experts_shared_outer_loras=EXPERTS_SHARED_OUTER_LORAS, + prefill_attention_backend=PREFILL_ATTENTION_BACKEND, + decode_attention_backend=DECODE_ATTENTION_BACKEND, + ) + + try: + cdata = torch.load( + os.path.join(adapter_path, "compare_sample_train_data.pt"), + weights_only=False, + ) + + base_logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path=None) + logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path="my_lora") + + base_t = torch.tensor(base_logprobs) + lora_t = torch.tensor(logprobs) + diff = (base_t - lora_t).abs() + print( + f"[VERIFY] base vs lora: mean_diff={diff.mean().item():.6f}, " + f"max_diff={diff.max().item():.6f}, " + f"identical={torch.equal(base_t, lora_t)}" + ) + + self.assertFalse( + torch.equal(base_t, lora_t), + "LoRA logprobs should differ from base model logprobs", + ) + + kl_sglang_trainer = kl_v2(cdata["training_logprobs"], logprobs) + kl_orig_trainer = kl_v2( + cdata["training_logprobs"], cdata["sampling_logprobs"] + ) + kl_sglang_orig = kl_v2(logprobs, cdata["sampling_logprobs"]) + + print(f"KL(orig_sampler, trainer) = {kl_orig_trainer:.6e}") + print(f"KL(sglang, trainer) = {kl_sglang_trainer:.6e}") + print(f"KL(sglang, orig_sampler) = {kl_sglang_orig:.6e}") + + self.assertLessEqual( + kl_sglang_trainer, + KL_THRESHOLD, + f"KL(sglang, trainer) = {kl_sglang_trainer:.6e} exceeds " + f"threshold {KL_THRESHOLD}", + ) + + finally: + engine.shutdown() + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_5_35b_a3b_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_5_35b_a3b_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..9504468b59e940958938e086b8b9593d728d7896 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_5_35b_a3b_logprob_diff.py @@ -0,0 +1,158 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Regression test for Qwen3.5-35B-A3B LoRA logprob accuracy. + +Compares SGLang LoRA logprobs against reference training logprobs from a +pre-computed dataset. The LoRA adapter and reference data are downloaded from: +https://huggingface.co/datasets/opherlie/lora-test-case-Qwen3.5-35B-A3B + +Usage: + python -m unittest test_lora_qwen3_5_35b_a3b_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest + +import torch +from huggingface_hub import snapshot_download + +import sglang as sgl +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci( + est_time=110, + stage="base-c", + runner_config="4-gpu-b200", +) + +BASE_MODEL = "Qwen/Qwen3.5-35B-A3B" +LORA_HF_REPO = "opherlie/lora-test-case-Qwen3.5-35B-A3B" +LORA_BACKEND = "triton" +MAX_LORA_RANK = 64 +TP_SIZE = 4 +MOE_RUNNER_BACKEND = "triton" +EXPERTS_SHARED_OUTER_LORAS = True +LORA_USE_VIRTUAL_EXPERTS = True +DISABLE_SHARED_EXPERTS_FUSION = True + +KL_THRESHOLD = 1e-3 + + +def kl_v2(a, b): + a = torch.tensor(a) if not torch.is_tensor(a) else a + b = torch.tensor(b) if not torch.is_tensor(b) else b + return (((a - b) ** 2) * 0.5).mean().item() + + +def get_prompt_logprobs(engine, input_ids, lora_path): + if isinstance(input_ids, torch.Tensor): + input_ids = [input_ids.tolist()] + elif not isinstance(input_ids[0], list): + input_ids = [input_ids] + out = engine.generate( + input_ids=input_ids, + sampling_params={"max_new_tokens": 0, "temperature": 0.0}, + return_logprob=True, + logprob_start_len=0, + lora_path=lora_path, + ) + if isinstance(out, list): + out = out[0] + return [logprob for logprob, _, _ in out["meta_info"]["input_token_logprobs"]][1:] + + +class TestLoRAQwen3_5_35B_A3B_LogprobDiff(CustomTestCase): + + def test_lora_qwen3_5_35b_a3b_logprob_accuracy(self): + adapter_path = snapshot_download( + LORA_HF_REPO, + repo_type="dataset", + ) + + engine = sgl.Engine( + model_path=BASE_MODEL, + tp_size=TP_SIZE, + enable_lora=True, + max_lora_rank=MAX_LORA_RANK, + lora_paths={"my_lora": adapter_path}, + lora_backend=LORA_BACKEND, + moe_runner_backend=MOE_RUNNER_BACKEND, + experts_shared_outer_loras=EXPERTS_SHARED_OUTER_LORAS, + lora_use_virtual_experts=LORA_USE_VIRTUAL_EXPERTS, + disable_shared_experts_fusion=DISABLE_SHARED_EXPERTS_FUSION, + # OOM's on logits with the defaults here, as this test-case is longer context and qwen3.5 has larger vocab + chunked_prefill_size=8192, + mem_fraction_static=0.8, + ) + + try: + cdata = torch.load( + os.path.join(adapter_path, "compare_sample_train_data.pt"), + weights_only=False, + ) + + base_logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path=None) + logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path="my_lora") + + base_t = torch.tensor(base_logprobs) + lora_t = torch.tensor(logprobs) + diff = (base_t - lora_t).abs() + print( + f"[VERIFY] base vs lora: mean_diff={diff.mean().item():.6f}, " + f"max_diff={diff.max().item():.6f}, " + f"identical={torch.equal(base_t, lora_t)}" + ) + + self.assertFalse( + torch.equal(base_t, lora_t), + "LoRA logprobs should differ from base model logprobs", + ) + + kl_sglang_trainer = kl_v2(cdata["training_logprobs"], logprobs) + kl_orig_trainer = kl_v2( + cdata["training_logprobs"], cdata["sampling_logprobs"] + ) + kl_sglang_orig = kl_v2(logprobs, cdata["sampling_logprobs"]) + + print(f"KL(orig_sampler, trainer) = {kl_orig_trainer:.6e}") + print(f"KL(sglang, trainer) = {kl_sglang_trainer:.6e}") + print(f"KL(sglang, orig_sampler) = {kl_sglang_orig:.6e}") + + self.assertLessEqual( + kl_sglang_trainer, + KL_THRESHOLD, + f"KL(sglang, trainer) = {kl_sglang_trainer:.6e} exceeds " + f"threshold {KL_THRESHOLD}", + ) + + finally: + engine.shutdown() + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_5_4b_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_5_4b_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..c4d4420c4498f3c1b96dd26d470f43756dacf9e5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_5_4b_logprob_diff.py @@ -0,0 +1,143 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Regression test for Qwen3.5-4B LoRA logprob accuracy. + +Compares SGLang LoRA logprobs against reference training logprobs from a +pre-computed dataset. The LoRA adapter and reference data are downloaded from: +https://huggingface.co/datasets/opherlie/lora-test-case-Qwen3.5-4B + +Usage: + python -m unittest test_lora_qwen3_5_4b_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest + +import torch +from huggingface_hub import snapshot_download + +import sglang as sgl +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=90, stage="extra-a", runner_config="1-gpu-large") + +BASE_MODEL = "Qwen/Qwen3.5-4B" +LORA_HF_REPO = "opherlie/lora-test-case-Qwen3.5-4B" +LORA_BACKEND = "triton" +MAX_LORA_RANK = 64 +TP_SIZE = 1 + +KL_THRESHOLD = 4e-3 + + +def kl_v2(a, b): + a = torch.tensor(a) if not torch.is_tensor(a) else a + b = torch.tensor(b) if not torch.is_tensor(b) else b + return (((a - b) ** 2) * 0.5).mean().item() + + +def get_prompt_logprobs(engine, input_ids, lora_path): + if isinstance(input_ids, torch.Tensor): + input_ids = [input_ids.tolist()] + elif not isinstance(input_ids[0], list): + input_ids = [input_ids] + out = engine.generate( + input_ids=input_ids, + sampling_params={"max_new_tokens": 0, "temperature": 0.0}, + return_logprob=True, + logprob_start_len=0, + lora_path=lora_path, + ) + if isinstance(out, list): + out = out[0] + return [logprob for logprob, _, _ in out["meta_info"]["input_token_logprobs"]][1:] + + +class TestLoRAQwen3_5_4BLogprobDiff(CustomTestCase): + + def test_lora_qwen3_5_4b_logprob_accuracy(self): + adapter_path = snapshot_download( + LORA_HF_REPO, + repo_type="dataset", + ) + + engine = sgl.Engine( + model_path=BASE_MODEL, + tp_size=TP_SIZE, + enable_lora=True, + max_lora_rank=MAX_LORA_RANK, + lora_paths={"my_lora": adapter_path}, + lora_backend=LORA_BACKEND, + ) + + try: + cdata = torch.load( + os.path.join(adapter_path, "compare_sample_train_data.pt"), + weights_only=False, + ) + + base_logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path=None) + logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path="my_lora") + + base_t = torch.tensor(base_logprobs) + lora_t = torch.tensor(logprobs) + diff = (base_t - lora_t).abs() + print( + f"[VERIFY] base vs lora: mean_diff={diff.mean().item():.6f}, " + f"max_diff={diff.max().item():.6f}, " + f"identical={torch.equal(base_t, lora_t)}" + ) + + self.assertFalse( + torch.equal(base_t, lora_t), + "LoRA logprobs should differ from base model logprobs", + ) + + kl_sglang_trainer = kl_v2(cdata["training_logprobs"], logprobs) + kl_orig_trainer = kl_v2( + cdata["training_logprobs"], cdata["sampling_logprobs"] + ) + kl_sglang_orig = kl_v2(logprobs, cdata["sampling_logprobs"]) + + print(f"KL(orig_sampler, trainer) = {kl_orig_trainer:.6e}") + print(f"KL(sglang, trainer) = {kl_sglang_trainer:.6e}") + print(f"KL(sglang, orig_sampler) = {kl_sglang_orig:.6e}") + + self.assertLessEqual( + kl_sglang_trainer, + KL_THRESHOLD, + f"KL(sglang, trainer) = {kl_sglang_trainer:.6e} exceeds " + f"threshold {KL_THRESHOLD}", + ) + + finally: + engine.shutdown() + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_8b_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_8b_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..5e3b5ecc0e2a4a7126940fe92162b721035adaaa --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_8b_logprob_diff.py @@ -0,0 +1,201 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Regression test for Qwen3-8B LoRA logprob accuracy. + +Compares SGLang LoRA logprobs against reference training logprobs from a +pre-computed dataset. The LoRA adapter and reference data are downloaded from: +https://huggingface.co/datasets/yushengsu/lora-diff-Qwen3-8B + +Usage: + python -m unittest test_lora_qwen3_8b_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest +from unittest.mock import patch + +import torch +import torch.nn as nn +from huggingface_hub import snapshot_download + +import sglang as sgl +from sglang.srt.lora.utils import auto_detect_lora_target_modules +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=40, stage="extra-a", runner_config="1-gpu-large") + +BASE_MODEL = "Qwen/Qwen3-8B" +LORA_HF_REPO = "yushengsu/lora-diff-Qwen3-8B" +LORA_BACKEND = "triton" +MAX_LORA_RANK = 32 +TP_SIZE = 1 +PREFILL_ATTENTION_BACKEND = "fa4" +DECODE_ATTENTION_BACKEND = "fa4" + +KL_THRESHOLD = 5e-3 + + +def kl_v2(a, b): + a = torch.tensor(a) if not torch.is_tensor(a) else a + b = torch.tensor(b) if not torch.is_tensor(b) else b + return (((a - b) ** 2) * 0.5).mean().item() + + +def get_prompt_logprobs(engine, input_ids, lora_path): + out = engine.generate( + input_ids=input_ids, + sampling_params={"max_new_tokens": 0, "temperature": 0.0}, + return_logprob=True, + logprob_start_len=0, + lora_path=lora_path, + ) + return [logprob for logprob, _, _ in out["meta_info"]["input_token_logprobs"]][1:] + + +class _MockLinearBase(nn.Module): + pass + + +class _MockFusedMoE(nn.Module): + pass + + +class _MockParallelLMHead(nn.Module): + pass + + +def _build_qwen3_mock(): + """Build a lightweight nn.Module tree that mirrors Qwen3-8B's named modules.""" + model = nn.Module() + inner = nn.Module() + layer = nn.Module() + + attn = nn.Module() + attn.qkv_proj = _MockLinearBase() + attn.o_proj = _MockLinearBase() + layer.self_attn = attn + + mlp = nn.Module() + mlp.gate_up_proj = _MockLinearBase() + mlp.down_proj = _MockLinearBase() + layer.mlp = mlp + + inner.layers = nn.ModuleList([layer]) + inner.embed_tokens = nn.Embedding(10, 8) # not a LinearBase — should be excluded + model.model = inner + model.lm_head = _MockParallelLMHead() + return model + + +class TestLoRAQwen3_8BLogprobDiff(CustomTestCase): + + def test_auto_detect_lora_target_modules(self): + """Verify auto_detect_lora_target_modules returns the expected module + set for a Qwen3-8B-like (dense) architecture. Catches silent renames + of internal param names that would break LoRA auto-detection.""" + model = _build_qwen3_mock() + + with ( + patch("sglang.srt.layers.linear.LinearBase", _MockLinearBase), + patch( + "sglang.srt.layers.moe.fused_moe_triton.layer.FusedMoE", _MockFusedMoE + ), + patch( + "sglang.srt.layers.vocab_parallel_embedding.ParallelLMHead", + _MockParallelLMHead, + ), + ): + detected = auto_detect_lora_target_modules(model) + + expected = {"qkv_proj", "o_proj", "gate_up_proj", "down_proj", "lm_head"} + self.assertEqual(detected, expected) + + def test_lora_qwen3_8b_logprob_accuracy(self): + adapter_path = snapshot_download( + LORA_HF_REPO, + repo_type="dataset", + ) + + engine = sgl.Engine( + model_path=BASE_MODEL, + tp_size=TP_SIZE, + enable_lora=True, + max_lora_rank=MAX_LORA_RANK, + lora_paths={"my_lora": adapter_path}, + lora_backend=LORA_BACKEND, + attention_backend="flashinfer", + prefill_attention_backend=PREFILL_ATTENTION_BACKEND, + decode_attention_backend=DECODE_ATTENTION_BACKEND, + ) + + try: + cdata = torch.load( + os.path.join(adapter_path, "compare_sample_train_data.pt"), + weights_only=False, + ) + + base_logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path=None) + logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path="my_lora") + + base_t = torch.tensor(base_logprobs) + lora_t = torch.tensor(logprobs) + diff = (base_t - lora_t).abs() + print( + f"[VERIFY] base vs lora: mean_diff={diff.mean().item():.6f}, " + f"max_diff={diff.max().item():.6f}, " + f"identical={torch.equal(base_t, lora_t)}" + ) + + self.assertFalse( + torch.equal(base_t, lora_t), + "LoRA logprobs should differ from base model logprobs", + ) + + kl_sglang_trainer = kl_v2(cdata["training_logprobs"], logprobs) + kl_orig_trainer = kl_v2( + cdata["training_logprobs"], cdata["sampling_logprobs"] + ) + kl_sglang_orig = kl_v2(logprobs, cdata["sampling_logprobs"]) + + print(f"KL(orig_sampler, trainer) = {kl_orig_trainer:.6e}") + print(f"KL(sglang, trainer) = {kl_sglang_trainer:.6e}") + print(f"KL(sglang, orig_sampler) = {kl_sglang_orig:.6e}") + + self.assertLessEqual( + kl_sglang_trainer, + KL_THRESHOLD, + f"KL(sglang, trainer) = {kl_sglang_trainer:.6e} exceeds " + f"threshold {KL_THRESHOLD}", + ) + + finally: + engine.shutdown() + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_vl_30b_a3b_instruct_logprob_diff.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_vl_30b_a3b_instruct_logprob_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..0618c26677b2f1ecb2b4cf981a80797a2ea769a2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_qwen3_vl_30b_a3b_instruct_logprob_diff.py @@ -0,0 +1,150 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Regression test for Qwen3-VL-30B-A3B-Instruct LoRA logprob accuracy. + +Compares SGLang LoRA logprobs against reference training logprobs from a +pre-computed dataset. The LoRA adapter and reference data are downloaded from: +https://huggingface.co/datasets/yushengsu/lora-diff-Qwen3-VL-30B-A3B-Instruct + +Usage: + python -m unittest test_lora_qwen3_vl_30b_a3b_instruct_logprob_diff +""" + +import multiprocessing as mp +import os +import unittest + +import torch +from huggingface_hub import snapshot_download + +import sglang as sgl +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci( + est_time=110, + stage="base-c", + runner_config="4-gpu-b200", +) + +BASE_MODEL = "Qwen/Qwen3-VL-30B-A3B-Instruct" +LORA_HF_REPO = "yushengsu/lora-diff-Qwen3-VL-30B-A3B-Instruct" +LORA_BACKEND = "triton" +MAX_LORA_RANK = 32 +TP_SIZE = 4 +MOE_RUNNER_BACKEND = "triton" +EXPERTS_SHARED_OUTER_LORAS = True +PREFILL_ATTENTION_BACKEND = "fa4" +DECODE_ATTENTION_BACKEND = "fa4" + +KL_THRESHOLD = 5e-3 + + +def kl_v2(a, b): + a = torch.tensor(a) if not torch.is_tensor(a) else a + b = torch.tensor(b) if not torch.is_tensor(b) else b + return (((a - b) ** 2) * 0.5).mean().item() + + +def get_prompt_logprobs(engine, input_ids, lora_path): + out = engine.generate( + input_ids=input_ids, + sampling_params={"max_new_tokens": 0, "temperature": 0.0}, + return_logprob=True, + logprob_start_len=0, + lora_path=lora_path, + ) + return [logprob for logprob, _, _ in out["meta_info"]["input_token_logprobs"]][1:] + + +class TestLoRAQwen3VL_30B_A3B_Instruct_LogprobDiff(CustomTestCase): + + def test_lora_qwen3_vl_30b_a3b_instruct_logprob_accuracy(self): + adapter_path = snapshot_download( + LORA_HF_REPO, + repo_type="dataset", + ) + + engine = sgl.Engine( + model_path=BASE_MODEL, + tp_size=TP_SIZE, + enable_lora=True, + max_lora_rank=MAX_LORA_RANK, + lora_paths={"my_lora": adapter_path}, + lora_backend=LORA_BACKEND, + attention_backend="flashinfer", + moe_runner_backend=MOE_RUNNER_BACKEND, + experts_shared_outer_loras=EXPERTS_SHARED_OUTER_LORAS, + prefill_attention_backend=PREFILL_ATTENTION_BACKEND, + decode_attention_backend=DECODE_ATTENTION_BACKEND, + ) + + try: + cdata = torch.load( + os.path.join(adapter_path, "compare_sample_train_data.pt"), + weights_only=False, + ) + + base_logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path=None) + logprobs = get_prompt_logprobs(engine, cdata["tokens"], lora_path="my_lora") + + base_t = torch.tensor(base_logprobs) + lora_t = torch.tensor(logprobs) + diff = (base_t - lora_t).abs() + print( + f"[VERIFY] base vs lora: mean_diff={diff.mean().item():.6f}, " + f"max_diff={diff.max().item():.6f}, " + f"identical={torch.equal(base_t, lora_t)}" + ) + + self.assertFalse( + torch.equal(base_t, lora_t), + "LoRA logprobs should differ from base model logprobs", + ) + + kl_sglang_trainer = kl_v2(cdata["training_logprobs"], logprobs) + kl_orig_trainer = kl_v2( + cdata["training_logprobs"], cdata["sampling_logprobs"] + ) + kl_sglang_orig = kl_v2(logprobs, cdata["sampling_logprobs"]) + + print(f"KL(orig_sampler, trainer) = {kl_orig_trainer:.6e}") + print(f"KL(sglang, trainer) = {kl_sglang_trainer:.6e}") + print(f"KL(sglang, orig_sampler) = {kl_sglang_orig:.6e}") + + self.assertLessEqual( + kl_sglang_trainer, + KL_THRESHOLD, + f"KL(sglang, trainer) = {kl_sglang_trainer:.6e} exceeds " + f"threshold {KL_THRESHOLD}", + ) + + finally: + engine.shutdown() + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + try: + unittest.main(warnings="ignore", verbosity=2) + finally: + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.synchronize() diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_radix_cache.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_radix_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..4320f580c17c908bae69d9dfcc93c318d124b195 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_radix_cache.py @@ -0,0 +1,82 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import multiprocessing as mp +import unittest + +import torch + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.lora_utils import CI_MULTI_LORA_MODELS, run_lora_test_one_by_one +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=200, suite="nightly-1-gpu", nightly=True) +register_amd_ci(est_time=200, suite="nightly-amd-1-gpu", nightly=True) + +PROMPTS = [ + "AI is a field of computer science focused on", + """ + ### Instruction: + Tell me about llamas and alpacas + ### Response: + Llamas are large, long-necked animals with a woolly coat. They have two toes on each foot instead of three like other camelids. + ### Question: + What do you know about llamas? + ### Answer: + """, +] + + +class TestLoRARadixCache(CustomTestCase): + + def test_lora_radix_cache(self): + # Here we need a model case with multiple adaptors for testing correctness of radix cache + model_case = CI_MULTI_LORA_MODELS[0] + + torch_dtype = torch.float16 + max_new_tokens = 32 + batch_prompts = ( + PROMPTS + if not model_case.skip_long_prompt + else [p for p in PROMPTS if len(p) < 1000] + ) + + # Test lora with radix cache + run_lora_test_one_by_one( + batch_prompts, + model_case, + torch_dtype, + max_new_tokens=max_new_tokens, + disable_radix_cache=False, + test_tag="lora-with-radix-cache", + ) + + # Test lora without radix cache + run_lora_test_one_by_one( + batch_prompts, + model_case, + torch_dtype, + max_new_tokens=max_new_tokens, + disable_radix_cache=True, + test_tag="lora-without-radix-cache", + ) + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + unittest.main(warnings="ignore") diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_tied_lm_head.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_tied_lm_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b4894db00959a73abf04a7109143e805e4bbf3ef --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_tied_lm_head.py @@ -0,0 +1,224 @@ +# Copyright 2023-2025 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +""" +Test LoRA on models with tied lm_head (tie_word_embeddings=True). + +When tie_word_embeddings=True, lm_head shares the same weight tensor as +embed_tokens. PyTorch's named_modules() deduplicates by object identity, +so lm_head won't appear as a separate module. This test validates that +SGLang correctly handles this case by untying lm_head before LoRA wrapping. + +The test: +1. Programmatically creates a LoRA adapter with lm_head in target_modules + using PEFT on a model with tie_word_embeddings=True (Qwen/Qwen2.5-0.5B). +2. Compares logprobs between HuggingFace+PEFT and SGLang to ensure numerical + consistency. This implicitly verifies no NaN values are produced and that + LoRA is actually being applied (since HF+PEFT is the trusted reference). +""" + +import multiprocessing as mp +import os +import shutil +import tempfile +import unittest + +import torch + +try: + from peft import LoraConfig, get_peft_model +except ImportError: + import subprocess + + subprocess.check_call(["pip", "install", "peft", "--no-deps"]) + from peft import LoraConfig, get_peft_model + +from transformers import AutoModelForCausalLM + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.runners import HFRunner, SRTRunner +from sglang.test.test_utils import DEFAULT_PORT_FOR_SRT_TEST_RUNNER, CustomTestCase + +register_cuda_ci(est_time=120, suite="nightly-1-gpu", nightly=True) + +# Use a small model with tie_word_embeddings=True +BASE_MODEL = "Qwen/Qwen2.5-0.5B" + +TEST_PROMPTS = [ + "AI is a field of computer science focused on", + "The capital of France is", +] + +MAX_NEW_TOKENS = 16 +LOGPROB_THRESHOLD = 2e-1 + + +def create_lora_adapter_with_lm_head(base_model_name: str, output_dir: str): + """ + Programmatically create a LoRA adapter that targets lm_head, + using a model with tie_word_embeddings=True. + + The adapter uses randomly initialized LoRA weights (no training). + This is sufficient to test that: + - SGLang can load the adapter without errors + - lm_head LoRA is applied (output differs from base model) + - Logprobs match between HF and SGLang + """ + model = AutoModelForCausalLM.from_pretrained( + base_model_name, + torch_dtype=torch.float16, + device_map="cpu", + ) + + # Verify the model actually has tied embeddings + assert ( + model.config.tie_word_embeddings + ), f"Expected tie_word_embeddings=True for {base_model_name}" + + # Only target lm_head to isolate the test to the tied-embedding scenario. + lora_config = LoraConfig( + r=8, + lora_alpha=16, + target_modules=["lm_head"], + lora_dropout=0, + bias="none", + task_type="CAUSAL_LM", + ) + + peft_model = get_peft_model(model, lora_config) + + # PEFT initializes lora_B to zeros by default, which makes the adapter + # produce identical output to the base model. Initialize lora_B with + # non-zero random weights so the adapter has a visible effect. + with torch.no_grad(): + for name, param in peft_model.named_parameters(): + if "lora_B" in name: + torch.nn.init.normal_(param, mean=0.0, std=0.02) + + peft_model.save_pretrained(output_dir) + + # Verify the saved adapter contains lm_head keys + from safetensors import safe_open + + safetensors_path = os.path.join(output_dir, "adapter_model.safetensors") + f = safe_open(safetensors_path, framework="pt") + lm_head_keys = [k for k in f.keys() if "lm_head" in k] + assert ( + len(lm_head_keys) > 0 + ), f"Expected lm_head LoRA weights in adapter, got keys: {sorted(f.keys())}" + + print(f"Created LoRA adapter at {output_dir}") + print(f" lm_head keys: {lm_head_keys}") + + # Clean up the model to free memory + del peft_model, model + torch.cuda.empty_cache() + + +class TestLoRATiedLMHead(CustomTestCase): + """ + Test that LoRA works correctly on models with tied lm_head. + """ + + _adapter_dir = None + + @classmethod + def setUpClass(cls): + """Create a temporary LoRA adapter with lm_head targeting.""" + super().setUpClass() + cls._adapter_dir = tempfile.mkdtemp(prefix="sglang_test_lora_tied_lm_head_") + create_lora_adapter_with_lm_head(BASE_MODEL, cls._adapter_dir) + + @classmethod + def tearDownClass(cls): + """Clean up the temporary adapter directory.""" + if cls._adapter_dir and os.path.exists(cls._adapter_dir): + shutil.rmtree(cls._adapter_dir) + super().tearDownClass() + + def test_tied_lm_head_lora_hf_sgl_logprob_match(self): + """ + Compare logprobs between HuggingFace+PEFT and SGLang+LoRA + for a tied lm_head adapter, ensuring numerical consistency. + """ + prompts = TEST_PROMPTS[:2] + + # Run SGLang with LoRA + with SRTRunner( + BASE_MODEL, + torch_dtype=torch.float16, + model_type="generation", + lora_paths=[self._adapter_dir], + max_loras_per_batch=1, + lora_backend="triton", + lora_target_modules=["lm_head"], + disable_cuda_graph=True, + disable_radix_cache=True, + mem_fraction_static=0.80, + port=DEFAULT_PORT_FOR_SRT_TEST_RUNNER, + ) as srt_runner: + srt_outputs = srt_runner.forward( + prompts, + max_new_tokens=MAX_NEW_TOKENS, + lora_paths=[self._adapter_dir] * len(prompts), + ) + + torch.cuda.empty_cache() + + # Run HuggingFace with LoRA (via PEFT) + with HFRunner( + BASE_MODEL, + torch_dtype=torch.float16, + model_type="generation", + ) as hf_runner: + hf_outputs = hf_runner.forward( + prompts, + max_new_tokens=MAX_NEW_TOKENS, + lora_paths=[self._adapter_dir] * len(prompts), + ) + + # Compare prefill logprobs + for i in range(len(prompts)): + srt_logprobs = torch.tensor(srt_outputs.top_input_logprobs[i]) + hf_logprobs = torch.tensor(hf_outputs.top_input_logprobs[i]) + max_diff = torch.max(torch.abs(srt_logprobs - hf_logprobs)).item() + print(f"Prompt {i} prefill logprob max_diff (SGLang vs HF): {max_diff:.6e}") + self.assertLess( + max_diff, + LOGPROB_THRESHOLD, + f"Prompt {i}: prefill logprob diff {max_diff:.6e} " + f"exceeds threshold {LOGPROB_THRESHOLD:.0e}", + ) + + # Compare decode logprobs + for i in range(len(prompts)): + srt_logprobs = torch.tensor(srt_outputs.top_output_logprobs[i]) + hf_logprobs = torch.tensor(hf_outputs.top_output_logprobs[i]) + max_diff = torch.max(torch.abs(srt_logprobs - hf_logprobs)).item() + print(f"Prompt {i} decode logprob max_diff (SGLang vs HF): {max_diff:.6e}") + self.assertLess( + max_diff, + LOGPROB_THRESHOLD, + f"Prompt {i}: decode logprob diff {max_diff:.6e} " + f"exceeds threshold {LOGPROB_THRESHOLD:.0e}", + ) + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + unittest.main(warnings="ignore") diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_tp.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_tp.py new file mode 100644 index 0000000000000000000000000000000000000000..39658741ee3240aad78de0b65d5640927573260d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_tp.py @@ -0,0 +1,100 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import multiprocessing as mp +import os +import unittest +from typing import List, Optional + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.lora_utils import ( + ALL_OTHER_LORA_MODELS, + CI_LORA_MODELS, + CI_MULTI_LORA_MODELS, + DEFAULT_PROMPTS, + TORCH_DTYPES, + LoRAModelCase, + run_lora_test_one_by_one, +) +from sglang.test.test_utils import CustomTestCase, is_in_ci + +register_cuda_ci( + est_time=230, + stage="base-c", + runner_config="8-gpu-h200", +) +register_amd_ci( + est_time=116, + suite="stage-b-test-2-gpu-large-amd", + disabled="see https://github.com/sgl-project/sglang/issues/13107", +) + + +class TestLoRATP(CustomTestCase): + + def _run_tp_on_model_cases( + self, + model_cases: List[LoRAModelCase], + enable_lora_overlap_loading: Optional[bool] = None, + ): + tp_list = [2] # Define TP sizes to iterate over + for model_case in model_cases: + # If skip_long_prompt is True, filter out prompts longer than 1000 characters + prompts = ( + DEFAULT_PROMPTS + if not model_case.skip_long_prompt + else [p for p in DEFAULT_PROMPTS if len(p) < 1000] + ) + for tp_size in tp_list: + model_case.tp_size = tp_size + for torch_dtype in TORCH_DTYPES: + run_lora_test_one_by_one( + prompts, + model_case, + torch_dtype, + max_new_tokens=32, + enable_lora_overlap_loading=enable_lora_overlap_loading, + test_tag=f"tp={tp_size}, enable_lora_overlap_loading={enable_lora_overlap_loading}", + attention_backend="fa3", + ) + + def test_ci_lora_models(self): + self._run_tp_on_model_cases(CI_LORA_MODELS) + + def test_lora_overlap_loading_ci_lora_models(self): + self._run_tp_on_model_cases( + CI_MULTI_LORA_MODELS, enable_lora_overlap_loading=True + ) + + def test_all_lora_models(self): + if is_in_ci(): + return + + # Retain ONLY_RUN check here + filtered_models = [] + for model_case in ALL_OTHER_LORA_MODELS: + if "ONLY_RUN" in os.environ and os.environ["ONLY_RUN"] != model_case.base: + continue + filtered_models.append(model_case) + + self._run_tp_on_model_cases(filtered_models) + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + unittest.main(warnings="ignore") diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_lora_update.py b/asian_ai/performance/SGLang/test/registered/lora/test_lora_update.py new file mode 100644 index 0000000000000000000000000000000000000000..b08d651ff1b6cb37957ff741f707f8c5441e5454 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_lora_update.py @@ -0,0 +1,1558 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import json +import multiprocessing as mp +import unittest +from dataclasses import dataclass +from enum import Enum +from typing import Any, Iterable, List, Optional, Union + +import requests +import torch + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.runners import SRTRunner +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + calculate_rouge_l, + is_in_ci, + popen_launch_server, +) + +register_cuda_ci( + est_time=487, + stage="base-b", + runner_config="1-gpu-large", +) +register_amd_ci( + est_time=730, + suite="stage-b-test-1-gpu-large-amd", +) + +PROMPTS = [ + "SGL is a", + "AI is a field of computer science focused on", + "Computer science is the study of", + "Write a short story.", + "What are the main components of a computer?", +] + +MEM_FRACTION_STATIC = 0.8 + + +class OperationType(Enum): + LOAD = "load" + UNLOAD = "unload" + FORWARD = "forward" + + +@dataclass +class Operation: + # Operation type, can be LOAD, UNLOAD, FORWARD + type: OperationType + # Data associated with the operation. Exact type varies depending on the operation + data: Optional[Any] + # If the operation is expected to fail, this is the error message to expect + expected_error: Optional[str] = None + # Because the logic for implicitly evicting LoRA adapters can be complicated, we explicitly + # pass in LoRA adapters that should be implicitly evicted here + expected_implicit_evictions: Optional[set[str]] = None + + +@dataclass +class TestCase: + description: str + base: str + max_loras_per_batch: int + all_adapters: List[str] + op_sequence: List[Operation] + initial_adapters: Optional[List[str]] = None + enable_lora: Optional[bool] = None + max_lora_rank: Optional[int] = None + lora_target_modules: Optional[List] = None + max_new_tokens: int = 32 + max_loaded_loras: Optional[int] = None + + +def create_batch_data(adapters: Union[str, list]) -> List[tuple[str, str]]: + if not isinstance(adapters, list): + adapters = [adapters] + return [(prompt, adapter) for prompt in PROMPTS for adapter in adapters] + + +BASIC_TESTS = [ + TestCase( + description="dynamic lora update with initial lora_paths", + base="meta-llama/Llama-3.1-8B-Instruct", + max_loras_per_batch=3, + all_adapters=[ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + ], + initial_adapters=[ + # Testing 3 supported lora-path formats. + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control=nvidia/llama-3.1-nemoguard-8b-topic-control", + { + "lora_name": "pbevan11/llama-3.1-8b-ocr-correction", + "lora_path": "pbevan11/llama-3.1-8b-ocr-correction", + "pinned": False, + }, + ], + op_sequence=[ + Operation( + type=OperationType.LOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + expected_error="already loaded", + ), + Operation( + type=OperationType.UNLOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + Operation( + type=OperationType.LOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + ] + ), + ), + Operation( + type=OperationType.UNLOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + Operation( + type=OperationType.UNLOAD, + data="pbevan11/llama-3.1-8b-ocr-correction", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("philschmid/code-llama-3-1-8b-text-to-sql-lora"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("nvidia/llama-3.1-nemoguard-8b-topic-control"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("pbevan11/llama-3.1-8b-ocr-correction"), + ), + Operation( + type=OperationType.LOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + expected_error="already loaded", + ), + Operation( + type=OperationType.LOAD, + data="pbevan11/llama-3.1-8b-ocr-correction", + expected_error="already loaded", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + ] + ), + ), + Operation( + type=OperationType.UNLOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("philschmid/code-llama-3-1-8b-text-to-sql-lora"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + ] + ), + ), + Operation( + type=OperationType.UNLOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + Operation( + type=OperationType.UNLOAD, + data="pbevan11/llama-3.1-8b-ocr-correction", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("nvidia/llama-3.1-nemoguard-8b-topic-control"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("pbevan11/llama-3.1-8b-ocr-correction"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + None, + ), + ), + ], + ), + TestCase( + description="dynamic lora update without initial lora_paths", + base="meta-llama/Llama-3.1-8B-Instruct", + enable_lora=True, + max_lora_rank=256, + lora_target_modules=["all"], + max_loras_per_batch=4, + all_adapters=[ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + ], + op_sequence=[ + Operation( + type=OperationType.LOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + Operation( + type=OperationType.LOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + Operation( + type=OperationType.LOAD, + data="pbevan11/llama-3.1-8b-ocr-correction", + ), + Operation( + type=OperationType.LOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + expected_error="already loaded", + ), + Operation( + type=OperationType.UNLOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + Operation( + type=OperationType.LOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + None, + ] + ), + ), + Operation( + type=OperationType.UNLOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("philschmid/code-llama-3-1-8b-text-to-sql-lora"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + None, + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + None, + ] + ), + ), + Operation( + type=OperationType.UNLOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + Operation( + type=OperationType.UNLOAD, + data="pbevan11/llama-3.1-8b-ocr-correction", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("nvidia/llama-3.1-nemoguard-8b-topic-control"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("pbevan11/llama-3.1-8b-ocr-correction"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data(None), + ), + Operation( + type=OperationType.LOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + expected_error="already loaded", + ), + Operation( + type=OperationType.LOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + expected_error="already loaded", + ), + Operation( + type=OperationType.LOAD, + data="pbevan11/llama-3.1-8b-ocr-correction", + expected_error="already loaded", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + None, + ] + ), + ), + ], + ), +] +TARGET_MODULE_TESTS = [ + TestCase( + description="Test explicitly specified lora-target-modules.", + base="meta-llama/Llama-3.1-8B-Instruct", + max_loras_per_batch=3, + lora_target_modules=["all"], + max_lora_rank=64, + all_adapters=[ + "nvidia/llama-3.1-nemoguard-8b-topic-control", # target_modules = q, k, v, o, gate, up, down + "algoprog/fact-generation-llama-3.1-8b-instruct-lora", # target_modules = q, k, v, o, gate + ], + initial_adapters=["algoprog/fact-generation-llama-3.1-8b-instruct-lora"], + op_sequence=[ + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + "algoprog/fact-generation-llama-3.1-8b-instruct-lora" + ), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("nvidia/llama-3.1-nemoguard-8b-topic-control"), + expected_error="never been loaded", + ), + Operation( + type=OperationType.LOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "algoprog/fact-generation-llama-3.1-8b-instruct-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + None, + ] + ), + ), + ], + ), + TestCase( + description="Test inferred lora-target-modules - start with larger adapter", + base="meta-llama/Llama-3.1-8B-Instruct", + max_loras_per_batch=3, + max_lora_rank=64, + all_adapters=[ + "nvidia/llama-3.1-nemoguard-8b-topic-control", # target_modules = q, k, v, o, gate, up, down + "algoprog/fact-generation-llama-3.1-8b-instruct-lora", # target_modules = q, k, v, o, gate + ], + initial_adapters=["nvidia/llama-3.1-nemoguard-8b-topic-control"], + op_sequence=[ + Operation( + type=OperationType.FORWARD, + data=create_batch_data("nvidia/llama-3.1-nemoguard-8b-topic-control"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + "algoprog/fact-generation-llama-3.1-8b-instruct-lora" + ), + expected_error="never been loaded", + ), + Operation( + type=OperationType.LOAD, + data="algoprog/fact-generation-llama-3.1-8b-instruct-lora", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "algoprog/fact-generation-llama-3.1-8b-instruct-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + None, + ] + ), + ), + ], + ), + TestCase( + description="Test inferred lora-target-modules - start with smaller adapter", + base="meta-llama/Llama-3.1-8B-Instruct", + max_loras_per_batch=3, + max_lora_rank=64, + all_adapters=[ + "nvidia/llama-3.1-nemoguard-8b-topic-control", # target_modules = q, k, v, o, gate, up, down + "algoprog/fact-generation-llama-3.1-8b-instruct-lora", # target_modules = q, k, v, o, gate + ], + initial_adapters=["algoprog/fact-generation-llama-3.1-8b-instruct-lora"], + op_sequence=[ + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + "algoprog/fact-generation-llama-3.1-8b-instruct-lora" + ), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("nvidia/llama-3.1-nemoguard-8b-topic-control"), + expected_error="never been loaded", + ), + Operation( + type=OperationType.LOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + expected_error="incompatible", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "algoprog/fact-generation-llama-3.1-8b-instruct-lora", + None, + ] + ), + ), + ], + ), +] +MAX_LORA_RANK_TESTS = [ + TestCase( + description="Test explicitly specified max-lora-rank.", + base="meta-llama/Llama-3.1-8B-Instruct", + max_loras_per_batch=3, + max_lora_rank=32, + all_adapters=[ + "nvidia/llama-3.1-nemoguard-8b-topic-control", # r = 4 + "pbevan11/llama-3.1-8b-ocr-correction", # r = 32 + "philschmid/code-llama-3-1-8b-text-to-sql-lora", # r = 256 + ], + initial_adapters=["nvidia/llama-3.1-nemoguard-8b-topic-control"], + op_sequence=[ + Operation( + type=OperationType.FORWARD, + data=create_batch_data("nvidia/llama-3.1-nemoguard-8b-topic-control"), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("philschmid/code-llama-3-1-8b-text-to-sql-lora"), + expected_error="never been loaded", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("pbevan11/llama-3.1-8b-ocr-correction"), + expected_error="never been loaded", + ), + Operation( + type=OperationType.LOAD, + data="pbevan11/llama-3.1-8b-ocr-correction", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "pbevan11/llama-3.1-8b-ocr-correction", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + None, + ] + ), + ), + Operation( + type=OperationType.LOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + expected_error="incompatible", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + expected_error="never been loaded", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "pbevan11/llama-3.1-8b-ocr-correction", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + None, + ] + ), + ), + ], + ), + TestCase( + description="test implicitly inferred max-lora-rank", + base="meta-llama/Llama-3.1-8B-Instruct", + max_loras_per_batch=3, + all_adapters=[ + "nvidia/llama-3.1-nemoguard-8b-topic-control", # r = 4 + "pbevan11/llama-3.1-8b-ocr-correction", # r = 32 + "philschmid/code-llama-3-1-8b-text-to-sql-lora", # r = 256 + ], + initial_adapters=["pbevan11/llama-3.1-8b-ocr-correction"], + op_sequence=[ + Operation( + type=OperationType.FORWARD, + data=create_batch_data("pbevan11/llama-3.1-8b-ocr-correction"), + ), + Operation( + type=OperationType.LOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + expected_error="incompatible", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data("philschmid/code-llama-3-1-8b-text-to-sql-lora"), + expected_error="never been loaded", + ), + Operation( + type=OperationType.LOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + "nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + None, + ] + ), + ), + ], + ), +] +MAX_LOADED_LORAS_TESTS = [ + TestCase( + description="Test max_loaded_loras limit as well as implicit eviction and reloading", + base="meta-llama/Llama-3.1-8B-Instruct", + max_loras_per_batch=2, + max_loaded_loras=2, + all_adapters=[ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + ], + initial_adapters=["philschmid/code-llama-3-1-8b-text-to-sql-lora"], + op_sequence=[ + Operation( + type=OperationType.LOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + Operation( + type=OperationType.LOAD, + data="pbevan11/llama-3.1-8b-ocr-correction", + expected_implicit_evictions={ + "philschmid/code-llama-3-1-8b-text-to-sql-lora" + }, + ), + # Implicitly load "philschmid/code-llama-3-1-8b-text-to-sql-lora" + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + ] + ), + expected_implicit_evictions={"pbevan11/llama-3.1-8b-ocr-correction"}, + ), + Operation( + type=OperationType.UNLOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "nvidia/llama-3.1-nemoguard-8b-topic-control", + ] + ), + ), + Operation( + type=OperationType.LOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + # Implicitly load "pbevan11/llama-3.1-8b-ocr-correction" and make sure that "nvidia/llama-3.1-nemoguard-8b-topic-control" + # isn't implicitly unloaded even though it is LRU because it is needed for this forward pass + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + ] + ), + expected_implicit_evictions={ + "philschmid/code-llama-3-1-8b-text-to-sql-lora" + }, + ), + Operation( + type=OperationType.UNLOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + Operation( + type=OperationType.LOAD, + data="algoprog/fact-generation-llama-3.1-8b-instruct-lora", + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + ] + ), + expected_implicit_evictions={ + "pbevan11/llama-3.1-8b-ocr-correction", + "algoprog/fact-generation-llama-3.1-8b-instruct-lora", + }, + ), + ], + ), + TestCase( + description="Test implicit eviction and reloading with pinned LoRA adapters", + base="meta-llama/Llama-3.1-8B-Instruct", + max_loras_per_batch=2, + max_loaded_loras=2, + all_adapters=[ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + ], + initial_adapters=[ + { + "lora_name": "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "lora_path": "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "pinned": True, + } + ], + op_sequence=[ + Operation( + type=OperationType.LOAD, + data="nvidia/llama-3.1-nemoguard-8b-topic-control", + ), + Operation( + type=OperationType.LOAD, + data="pbevan11/llama-3.1-8b-ocr-correction", + expected_implicit_evictions={ + "nvidia/llama-3.1-nemoguard-8b-topic-control" + }, + ), + # Implicitly load "nvidia/llama-3.1-nemoguard-8b-topic-control" + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + ] + ), + expected_implicit_evictions={"pbevan11/llama-3.1-8b-ocr-correction"}, + ), + Operation( + type=OperationType.LOAD, + data={ + "lora_name": "pbevan11/llama-3.1-8b-ocr-correction", + "lora_path": "pbevan11/llama-3.1-8b-ocr-correction", + "pinned": True, + }, + expected_error="starvation", + ), + Operation( + type=OperationType.UNLOAD, + data="philschmid/code-llama-3-1-8b-text-to-sql-lora", + ), + Operation( + type=OperationType.LOAD, + data={ + "lora_name": "pbevan11/llama-3.1-8b-ocr-correction", + "lora_path": "pbevan11/llama-3.1-8b-ocr-correction", + "pinned": True, + }, + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pbevan11/llama-3.1-8b-ocr-correction", + ] + ), + ), + ], + ), +] +EVICTION_TESTS = [ + TestCase( + description="dynamic lora update with evictions", + base="meta-llama/Llama-3.1-8B-Instruct", + max_loras_per_batch=2, + all_adapters=[ + "lora1=philschmid/code-llama-3-1-8b-text-to-sql-lora", + "lora2=nvidia/llama-3.1-nemoguard-8b-topic-control", + "lora3=pbevan11/llama-3.1-8b-ocr-correction", + ], + enable_lora=True, + max_lora_rank=256, + lora_target_modules=["all"], + op_sequence=[ + Operation( + type=OperationType.LOAD, + data={ + "lora_name": "lora1", + "lora_path": "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "pinned": True, + }, + ), + Operation( + type=OperationType.LOAD, + data={ + "lora_name": "lora2", + "lora_path": "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pinned": True, + }, + expected_error="starvation", + ), + Operation( + type=OperationType.LOAD, + data={ + "lora_name": "lora2", + "lora_path": "nvidia/llama-3.1-nemoguard-8b-topic-control", + "pinned": False, + }, + ), + Operation( + type=OperationType.LOAD, + data={ + "lora_name": "lora3", + "lora_path": "pbevan11/llama-3.1-8b-ocr-correction", + "pinned": False, + }, + ), + Operation( + type=OperationType.UNLOAD, + data="lora1", + ), + Operation( + type=OperationType.UNLOAD, + data="lora3", + ), + Operation( + type=OperationType.LOAD, + data={ + "lora_name": "lora3", + "lora_path": "pbevan11/llama-3.1-8b-ocr-correction", + "pinned": True, + }, + ), + Operation( + type=OperationType.LOAD, + data={ + "lora_name": "lora1", + "lora_path": "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "pinned": True, + }, + expected_error="starvation", + ), + Operation( + type=OperationType.LOAD, + data={ + "lora_name": "lora1", + "lora_path": "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "pinned": False, + }, + ), + # pinned: lora3 + # unpinned: lora1, lora2 + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "lora1", + "lora2", + ] + ), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "lora1", + "lora3", + ] + ), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "lora1", + "lora2", + ] + ), + ), + Operation( + type=OperationType.FORWARD, + data=create_batch_data( + [ + "lora1", + "lora2", + None, + ] + ), + ), + ], + ), +] + +ALL_TESTS = ( + BASIC_TESTS + + TARGET_MODULE_TESTS + + MAX_LORA_RANK_TESTS + + MAX_LOADED_LORAS_TESTS + + EVICTION_TESTS +) + + +class LoRAUpdateTestSessionMode(Enum): + ENGINE = "engine" + SERVER = "server" + + +class LoRAUpdateTestSessionBase: + """ + Base context manager for testing LoRA adapters. + """ + + def __init__( + self, + *, + testcase: Optional[TestCase], + model_path: str, + lora_paths: List[Union[str, dict]], + max_loras_per_batch: int, + max_loaded_loras: Optional[int] = None, + max_lora_rank: Optional[int], + enable_lora: Optional[bool] = None, + lora_target_modules: Optional[List[str]] = None, + lora_backend: str = "csgmv", + disable_cuda_graph: bool = False, + cuda_graph_max_bs_decode: int = 4, + ): + self.testcase = testcase + self.model_path = model_path + self.lora_paths = lora_paths + self.max_lora_rank = max_lora_rank + self.lora_target_modules = lora_target_modules + self.max_loras_per_batch = max_loras_per_batch + self.max_loaded_loras = max_loaded_loras + self.lora_backend = lora_backend + self.disable_cuda_graph = disable_cuda_graph + self.cuda_graph_max_bs_decode = cuda_graph_max_bs_decode + self.enable_lora = enable_lora + + self.expected_adapters = set() + if self.lora_paths: + for adapter in self.lora_paths: + if isinstance(adapter, dict): + lora_name = adapter["lora_name"] + elif "=" in adapter: + lora_name = adapter.split("=")[0] + else: + lora_name = adapter + self.expected_adapters.add(lora_name) + + self.handle = None # Will be set in __enter__ + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + # Don't suppress exceptions by default + return False + + def load_lora_adapter( + self, + lora_name: str, + lora_path: Optional[str] = None, + expected_error: Optional[str] = None, + expected_implicit_evictions: Optional[set[str]] = None, + ): + """ + Load a LoRA adapter by name and path. + """ + raise NotImplementedError("Subclasses must implement load_lora_adapter") + + def unload_lora_adapter(self, lora_name: str): + """ + Unload a LoRA adapter by name. + """ + raise NotImplementedError("Subclasses must implement unload_lora_adapter") + + def forward( + self, + prompts: List[str], + lora_paths: List[str], + max_new_tokens: int = 32, + expected_error: Optional[str] = None, + expected_implicit_evictions: Optional[set[str]] = None, + ): + """ + Perform a batch forward pass with the current set of loaded LoRA adapters. + """ + raise NotImplementedError("Subclasses must implement forward") + + +class LoRAUpdateEngineTestSession(LoRAUpdateTestSessionBase): + """ + Context manager for testing LoRA adapters with in-process engine. + """ + + def __enter__(self): + # in-process runner + self.handle = SRTRunner( + model_path=self.model_path, + model_type="generation", + lora_paths=self.lora_paths, + max_lora_rank=self.max_lora_rank, + lora_target_modules=self.lora_target_modules, + lora_backend=self.lora_backend, + torch_dtype=torch.float16, + mem_fraction_static=MEM_FRACTION_STATIC, + max_loras_per_batch=self.max_loras_per_batch, + max_loaded_loras=self.max_loaded_loras, + disable_cuda_graph=self.disable_cuda_graph, + cuda_graph_max_bs_decode=self.cuda_graph_max_bs_decode, + enable_lora=self.enable_lora, + disable_radix_cache=True, + ) + self.handle.__enter__() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.handle is not None: + # delegate cleanup to SRTRunner + return self.handle.__exit__(exc_type, exc_val, exc_tb) + # don't suppress exceptions + return False + + def load_lora_adapter( + self, + lora_name: str, + lora_path: Optional[str] = None, + expected_error: Optional[str] = None, + pinned: bool = False, + expected_implicit_evictions: Optional[set[str]] = None, + ): + """ + Load a LoRA adapter by name and path. + """ + if lora_path is None: + lora_path = lora_name + + response = self.handle.load_lora_adapter( + lora_name=lora_name, + lora_path=lora_path, + pinned=pinned, + ) + if expected_error: + self.testcase.assertFalse( + response.success, f"Expected failure for {lora_name}, but got success." + ) + self.testcase.assertIn( + expected_error, + response.error_message, + f"Expected error message to contain '{expected_error}', but got '{response.error_message}'", + ) + print(f"Received error as expected: {response.error_message}") + else: + self.expected_adapters.add(lora_name) + if expected_implicit_evictions is not None: + self.expected_adapters -= expected_implicit_evictions + + self.testcase.assertTrue( + response.success, + f"Failed to load LoRA adapter {lora_name}: {response.error_message}", + ) + loaded_adapters = set(response.loaded_adapters) + print(f"loaded_adapters: {loaded_adapters}") + self.testcase.assertEqual( + loaded_adapters, + self.expected_adapters, + f"Expected loaded adapters to be {self.expected_adapters}, but got {loaded_adapters}", + ) + + def unload_lora_adapter(self, lora_name: str): + """ + Unload a LoRA adapter by name. + """ + self.expected_adapters.remove(lora_name) + + response = self.handle.unload_lora_adapter( + lora_name=lora_name, + ) + self.testcase.assertTrue( + response.success, + f"Failed to unload LoRA adapter {lora_name}: {response.error_message}", + ) + loaded_adapters = set(response.loaded_adapters) + + print(f"loaded_adapters: {loaded_adapters}") + self.testcase.assertEqual( + loaded_adapters, + self.expected_adapters, + f"Expected loaded adapters to be {self.expected_adapters}, but got {loaded_adapters}", + ) + + def forward( + self, + prompts: List[str], + lora_paths: List[str], + max_new_tokens: int = 32, + expected_error: Optional[str] = None, + expected_implicit_evictions: Optional[set[str]] = None, + ): + """ + Perform a batch forward pass with the current set of loaded LoRA adapters. + """ + try: + response = self.handle.batch_forward( + prompts=prompts, + lora_paths=lora_paths, + max_new_tokens=max_new_tokens, + ) + except ValueError as e: + if expected_error: + error_message = str(e) + self.testcase.assertIn( + expected_error, + error_message, + f"Expected error message to contain '{expected_error}', but got '{error_message}'", + ) + print(f"Received error as expected: {error_message}") + return error_message + + raise e + + self.testcase.assertEqual( + len(response.output_strs), + len(prompts), + f"Expected {len(prompts)} outputs, but got {len(response.output_strs)}", + ) + output = response.output_strs + print(f"output_strs: {output}") + + self.expected_adapters.update( + [lora_path for lora_path in lora_paths if lora_path is not None] + ) + + if expected_implicit_evictions is not None: + self.expected_adapters -= expected_implicit_evictions + + return output + + +class LoRAUpdateServerTestSession(LoRAUpdateTestSessionBase): + """ + Context manager for testing LoRA adapters with standalone server. + """ + + def __enter__(self): + other_args = [ + "--cuda-graph-max-bs-decode", + str(self.cuda_graph_max_bs_decode), + "--max-loras-per-batch", + str(self.max_loras_per_batch), + "--lora-backend", + self.lora_backend, + "--random-seed", + "42", + "--max-running-request", + "1", + "--mem-fraction-static", + str(MEM_FRACTION_STATIC), + "--disable-radix-cache", + ] + if self.enable_lora: + other_args.append("--enable-lora") + if self.lora_paths: + other_args.append("--lora-paths") + for lora_path in self.lora_paths: + if isinstance(lora_path, dict): + lora_path = json.dumps(lora_path) + other_args.append(lora_path) + if self.disable_cuda_graph: + other_args.append("--disable-cuda-graph") + if self.max_lora_rank is not None: + other_args.extend(["--max-lora-rank", str(self.max_lora_rank)]) + if self.lora_target_modules is not None: + other_args.extend(["--lora-target-modules"] + self.lora_target_modules) + if self.max_loaded_loras is not None: + other_args.extend(["--max-loaded-loras", str(self.max_loaded_loras)]) + + # launch external server + self.handle = popen_launch_server( + self.model_path, + DEFAULT_URL_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.handle is not None: + kill_process_tree(self.handle.pid) + # don't suppress exceptions + return False + + def load_lora_adapter( + self, + lora_name: str, + lora_path: Optional[str] = None, + expected_error: Optional[str] = None, + pinned: bool = False, + expected_implicit_evictions: Optional[set[str]] = None, + ): + """ + Load a LoRA adapter by name and path. + """ + if lora_path is None: + lora_path = lora_name + + response = requests.post( + DEFAULT_URL_FOR_TEST + "/load_lora_adapter", + json={"lora_name": lora_name, "lora_path": lora_path, "pinned": pinned}, + ) + if expected_error: + self.testcase.assertEqual( + response.status_code, + 400, + f"Expected error for {lora_name}, but got success.", + ) + self.testcase.assertIn( + expected_error, + response.text, + f"Expected error message to contain '{expected_error}', but got '{response.text}'", + ) + print(f"Received error as expected: {response.text}") + else: + self.expected_adapters.add(lora_name) + if expected_implicit_evictions is not None: + self.expected_adapters -= expected_implicit_evictions + + self.testcase.assertTrue( + response.ok, f"Failed to load LoRA adapter {lora_name}: {response.text}" + ) + loaded_adapters = set(response.json()["loaded_adapters"]) + print(f"loaded_adapters: {loaded_adapters}") + self.testcase.assertEqual( + loaded_adapters, + self.expected_adapters, + f"Expected loaded adapters to be {self.expected_adapters}, but got {loaded_adapters}", + ) + + def unload_lora_adapter(self, lora_name: str): + """ + Unload a LoRA adapter by name. + """ + self.expected_adapters.remove(lora_name) + + response = requests.post( + DEFAULT_URL_FOR_TEST + "/unload_lora_adapter", + json={"lora_name": lora_name}, + ) + + self.testcase.assertTrue( + response.ok, f"Failed to unload LoRA adapter {lora_name}: {response.text}" + ) + loaded_adapters = set(response.json()["loaded_adapters"]) + + print(f"loaded_adapters: {loaded_adapters}") + self.testcase.assertEqual( + loaded_adapters, + self.expected_adapters, + f"Expected loaded adapters to be {self.expected_adapters}, but got {loaded_adapters}", + ) + + def forward( + self, + prompts: List[str], + lora_paths: List[str], + max_new_tokens: int = 32, + expected_error: Optional[str] = None, + expected_implicit_evictions: Optional[set[str]] = None, + ): + """ + Perform a batch forward pass with the current set of loaded LoRA adapters. + """ + response = requests.post( + DEFAULT_URL_FOR_TEST + "/generate", + json={ + "text": prompts, + "lora_path": lora_paths, + "sampling_params": { + "temperature": 0, + "top_k": 1, + "max_new_tokens": max_new_tokens, + }, + }, + ) + if expected_error: + self.testcase.assertEqual( + response.status_code, + 400, + f"Expected error for forward pass, but got success: {response.text}", + ) + self.testcase.assertIn( + expected_error, + response.text, + f"Expected error message to contain '{expected_error}', but got '{response.text}'", + ) + output = response.text + print(f"Received error as expected: {response.text}") + return output + else: + self.testcase.assertTrue( + response.ok, f"Failed to generate text: {response.text}" + ) + output = [r["text"] for r in response.json()] + self.testcase.assertEqual( + len(output), + len(prompts), + f"Expected {len(prompts)} outputs, but got {len(output)}", + ) + print(f"output_strs: {output}") + + self.expected_adapters.update( + [lora_path for lora_path in lora_paths if lora_path is not None] + ) + + if expected_implicit_evictions is not None: + self.expected_adapters -= expected_implicit_evictions + + return output + + +# Factory function to create the appropriate LoRA test session based on mode +def LoRAUpdateTestSession( + testcase: Optional[TestCase], + mode: LoRAUpdateTestSessionMode, + **kwargs: Any, +): + if mode == LoRAUpdateTestSessionMode.ENGINE: + return LoRAUpdateEngineTestSession(testcase=testcase, **kwargs) + elif mode == LoRAUpdateTestSessionMode.SERVER: + return LoRAUpdateServerTestSession(testcase=testcase, **kwargs) + else: + raise ValueError(f"Unrecognized mode: {mode!r}") + + +class TestLoRADynamicUpdate(CustomTestCase): + """ + This test case verifies that the SRT runner can dynamically load and unload LoRA adapters + during a sequence of operations, and that the outputs of forward passes with dynamically loaded + adapters match the outputs of forward passes with statically loaded adapters. + """ + + def _repeat_each(lst, n): + return [x for x in lst for _ in range(n)] + + def _run_operation_sequence( + self, + mode: LoRAUpdateTestSessionMode, + base: str, + initial_adapters: List[Union[str, dict]], + op_sequence: List[Operation], + max_loras_per_batch: int, + max_loaded_loras: Optional[int] = None, + enable_lora: Optional[bool] = None, + max_lora_rank: Optional[int] = None, + lora_target_modules: Optional[List[str]] = None, + max_new_tokens: int = 32, + ) -> List[tuple]: + """ + Runs a sequence of operations on the SRT runner, including loading and unloading LoRA adapters, + and performing forward passes with the current set of loaded adapters. + """ + + forward_outputs = [] + with LoRAUpdateTestSession( + testcase=self, + mode=mode, + model_path=base, + lora_paths=initial_adapters, + max_loras_per_batch=max_loras_per_batch, + max_loaded_loras=max_loaded_loras, + max_lora_rank=max_lora_rank, + lora_target_modules=lora_target_modules, + enable_lora=enable_lora, + ) as session: + for op in op_sequence: + op_type = op.type + data = op.data + expected_error = op.expected_error + expected_implicit_evictions = op.expected_implicit_evictions + print("-" * 100) + print( + f"Running operation: {op_type} --- data: {data} --- mode: {mode} ---" + ) + if op_type == OperationType.LOAD: + if isinstance(data, str): + adapter_info = { + "lora_name": data, + "lora_path": data, + "pinned": False, + } + else: + adapter_info = data + + result = session.load_lora_adapter( + expected_error=expected_error, + expected_implicit_evictions=expected_implicit_evictions, + **adapter_info, + ) + elif op_type == OperationType.UNLOAD: + result = session.unload_lora_adapter( + lora_name=data, + ) + elif op_type == OperationType.FORWARD: + prompts, adapters = zip(*data) + result = session.forward( + prompts=list(prompts), + lora_paths=list(adapters), + max_new_tokens=max_new_tokens, + expected_error=expected_error, + expected_implicit_evictions=expected_implicit_evictions, + ) + if not expected_error: + forward_outputs.append(result) + + return forward_outputs + + def _run_dynamic_adapter_updates( + self, mode: LoRAUpdateTestSessionMode, test_cases: Iterable[TestCase] + ): + for case_idx, test_case in enumerate(test_cases, start=1): + print("=" * 100) + print( + f"Starting test case {case_idx} in {mode.value} mode. Test description: {test_case.description}" + ) + print("=" * 100) + + print( + f"--- Running dynamic update pass with {len(test_case.op_sequence)} operations ---" + ) + # Test dynamic loading of adapters + dynamic_output = self._run_operation_sequence( + mode=mode, + initial_adapters=test_case.initial_adapters, + enable_lora=test_case.enable_lora, + base=test_case.base, + max_loras_per_batch=test_case.max_loras_per_batch, + max_loaded_loras=test_case.max_loaded_loras, + op_sequence=test_case.op_sequence, + max_new_tokens=test_case.max_new_tokens, + max_lora_rank=test_case.max_lora_rank, + lora_target_modules=test_case.lora_target_modules, + ) + + # static loading + forward_ops = [ + x + for x in test_case.op_sequence + if x.type == OperationType.FORWARD and x.expected_error is None + ] + + if not forward_ops: + print( + f"No forward operations found in test case {case_idx}. Skipping static pass." + ) + continue + + print("=" * 100) + print(f"\n--- Running static pass with {len(forward_ops)} operations ---") + static_output = self._run_operation_sequence( + mode=mode, + initial_adapters=test_case.all_adapters, + enable_lora=test_case.enable_lora, + base=test_case.base, + max_loras_per_batch=test_case.max_loras_per_batch, + op_sequence=forward_ops, + max_new_tokens=test_case.max_new_tokens, + ) + + ROUGE_L_TOL = 0.9 + + print(f"Dynamic output: {dynamic_output}") + print(f"Static output: {static_output}") + print("=" * 100) + self.assertEqual( + len(dynamic_output), + len(static_output), + f"Dynamic output length {len(dynamic_output)} does not match static output length {len(static_output)}", + ) + for i, (dynamic, static) in enumerate( + zip(dynamic_output, static_output), start=1 + ): + self.assertEqual( + len(dynamic), + len(static), + f"Output length mismatch at batch {i}:\n- Dynamic={len(dynamic)}\n- Static={len(static)}", + ) + for j, (d_out, s_out) in enumerate(zip(dynamic, static), start=1): + d_out_str = d_out.strip() + s_out_str = s_out.strip() + rouge_score = calculate_rouge_l([d_out_str], [s_out_str])[0] + + self.assertGreaterEqual( + rouge_score, + ROUGE_L_TOL, + f"ROUGE-L score {rouge_score} of outputs is below tolerance of {ROUGE_L_TOL} " + f"at batch {i}, prompt {j}:\n- Dynamic: '{d_out}'\n- Static: '{s_out}'", + ) + + # def test_dynamic_lora_update_engine(self): + # """ + # Test dynamic LoRA updates in engine mode. + # """ + # test_cases = BASIC_TESTS if is_in_ci() else ALL_TESTS + # self._run_dynamic_adapter_updates( + # mode=LoRAUpdateTestSessionMode.ENGINE, + # test_cases=test_cases, + # ) + + def test_dynamic_lora_update_server(self): + """ + Test dynamic LoRA updates in server mode. + """ + test_cases = BASIC_TESTS if is_in_ci() else ALL_TESTS + self._run_dynamic_adapter_updates( + mode=LoRAUpdateTestSessionMode.SERVER, test_cases=test_cases + ) + + def test_v1_models_endpoint_with_lora(self): + """ + Test that /v1/models endpoint returns base model and loaded LoRA adapters. + """ + adapters = [ + "philschmid/code-llama-3-1-8b-text-to-sql-lora", + "nvidia/llama-3.1-nemoguard-8b-topic-control", + ] + + with LoRAUpdateTestSession( + testcase=self, + mode=LoRAUpdateTestSessionMode.SERVER, + model_path="meta-llama/Llama-3.1-8B-Instruct", + lora_paths=[], + max_loras_per_batch=2, + max_lora_rank=256, + lora_target_modules=["all"], + enable_lora=True, + ) as session: + # Test with no adapters loaded + response = requests.get(DEFAULT_URL_FOR_TEST + "/v1/models") + self.assertTrue(response.ok, response.text) + models_data = response.json() + self.assertEqual(models_data["object"], "list") + self.assertEqual(len(models_data["data"]), 1) # Only base model + base_model = models_data["data"][0] + self.assertIn("meta-llama", base_model["id"].lower()) + self.assertIsNone(base_model.get("parent")) + + # Load first adapter + session.load_lora_adapter(lora_name="adapter1", lora_path=adapters[0]) + + # Test with one adapter loaded + response = requests.get(DEFAULT_URL_FOR_TEST + "/v1/models") + self.assertTrue(response.ok, response.text) + models_data = response.json() + self.assertEqual(len(models_data["data"]), 2) # Base model + 1 adapter + + # Verify adapter information + adapter_models = [m for m in models_data["data"] if m.get("parent")] + self.assertEqual(len(adapter_models), 1) + self.assertEqual(adapter_models[0]["id"], "adapter1") + self.assertEqual(adapter_models[0]["root"], adapters[0]) + self.assertIsNotNone(adapter_models[0]["parent"]) + + # Load second adapter + session.load_lora_adapter(lora_name="adapter2", lora_path=adapters[1]) + + # Test with two adapters loaded + response = requests.get(DEFAULT_URL_FOR_TEST + "/v1/models") + self.assertTrue(response.ok, response.text) + models_data = response.json() + self.assertEqual(len(models_data["data"]), 3) # Base model + 2 adapters + + # Verify both adapters are listed + adapter_models = [m for m in models_data["data"] if m.get("parent")] + self.assertEqual(len(adapter_models), 2) + adapter_names = {m["id"] for m in adapter_models} + self.assertEqual(adapter_names, {"adapter1", "adapter2"}) + + # Unload one adapter + session.unload_lora_adapter(lora_name="adapter1") + + # Test after unloading + response = requests.get(DEFAULT_URL_FOR_TEST + "/v1/models") + self.assertTrue(response.ok, response.text) + models_data = response.json() + self.assertEqual(len(models_data["data"]), 2) # Base model + 1 adapter + adapter_models = [m for m in models_data["data"] if m.get("parent")] + self.assertEqual(len(adapter_models), 1) + self.assertEqual(adapter_models[0]["id"], "adapter2") + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + unittest.main(warnings="ignore") diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_moe_lora_info.py b/asian_ai/performance/SGLang/test/registered/lora/test_moe_lora_info.py new file mode 100644 index 0000000000000000000000000000000000000000..bf6b4fa7cb533012336863899da76d5afdd42fd2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_moe_lora_info.py @@ -0,0 +1,87 @@ +import sys + +import pytest +import torch + +from sglang.srt.lora.backend.base_backend import _compute_moe_lora_info +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=5, stage="base-b", runner_config="1-gpu-small") + + +def _expected_adapter_enabled( + lora_ranks: torch.Tensor, + weight_indices: torch.Tensor, +) -> torch.Tensor: + expected = torch.zeros_like(lora_ranks) + expected.scatter_( + 0, + weight_indices.long(), + (lora_ranks[weight_indices.long()] > 0).to(torch.int32), + ) + return expected + + +@pytest.mark.parametrize("use_preallocated_buffers", [False, True]) +def test_compute_moe_lora_info_expands_segments(use_preallocated_buffers: bool): + device = "cuda" + seg_lens = torch.tensor([5, 1, 7, 3, 9, 2], dtype=torch.int32, device=device) + seg_indptr = torch.zeros((seg_lens.numel() + 1,), dtype=torch.int32, device=device) + seg_indptr[1:] = torch.cumsum(seg_lens, dim=0) + + weight_indices = torch.tensor([2, 0, 5, 2, 3, 7], dtype=torch.int32, device=device) + lora_ranks = torch.tensor( + [0, 12, 16, 32, 24, 8, 0, 4], dtype=torch.int32, device=device + ) + num_tokens = int(seg_indptr[-1].item()) + + if use_preallocated_buffers: + adapter_enabled = torch.full_like(lora_ranks, 123) + token_lora_mapping = torch.full( + (num_tokens + 11,), 456, dtype=torch.int32, device=device + ) + else: + adapter_enabled = None + token_lora_mapping = None + + actual_enabled, actual_mapping = _compute_moe_lora_info( + num_tokens, + seg_indptr, + lora_ranks, + weight_indices, + adapter_enabled, + token_lora_mapping, + max_len=int(seg_lens.max().item()), + ) + torch.cuda.synchronize() + + expected_mapping = torch.repeat_interleave(weight_indices, seg_lens) + expected_enabled = _expected_adapter_enabled(lora_ranks, weight_indices) + + torch.testing.assert_close(actual_mapping, expected_mapping) + torch.testing.assert_close(actual_enabled, expected_enabled) + + if use_preallocated_buffers: + assert actual_mapping.data_ptr() == token_lora_mapping.data_ptr() + + +def test_compute_moe_lora_info_rejects_undercovered_launch(): + device = "cuda" + seg_indptr = torch.tensor([0, 300], dtype=torch.int32, device=device) + weight_indices = torch.tensor([0], dtype=torch.int32, device=device) + lora_ranks = torch.tensor([16], dtype=torch.int32, device=device) + + with pytest.raises(AssertionError, match="under-covers tokens"): + _compute_moe_lora_info( + 300, + seg_indptr, + lora_ranks, + weight_indices, + None, + None, + max_len=1, + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_multi_lora_backend.py b/asian_ai/performance/SGLang/test/registered/lora/test_multi_lora_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..b650695de611c702ab521d1dfbc92609161e1fda --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_multi_lora_backend.py @@ -0,0 +1,59 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import multiprocessing as mp +import os +import unittest + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.lora_utils import ( + ALL_OTHER_MULTI_LORA_MODELS, + CI_MULTI_LORA_MODELS, + run_lora_batch_splitting_equivalence_test, + run_lora_multiple_batch_on_model_cases, +) +from sglang.test.test_utils import CustomTestCase, is_in_ci + +register_cuda_ci(est_time=99, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=100, suite="stage-b-test-1-gpu-small-amd") + + +class TestMultiLoRABackend(CustomTestCase): + def test_ci_lora_models_batch_splitting(self): + run_lora_batch_splitting_equivalence_test(CI_MULTI_LORA_MODELS) + + def test_ci_lora_models_multi_batch(self): + run_lora_multiple_batch_on_model_cases(CI_MULTI_LORA_MODELS) + + def test_all_lora_models(self): + if is_in_ci(): + return + + # Retain ONLY_RUN check here + filtered_models = [] + for model_case in ALL_OTHER_MULTI_LORA_MODELS: + if "ONLY_RUN" in os.environ and os.environ["ONLY_RUN"] != model_case.base: + continue + filtered_models.append(model_case) + + run_lora_multiple_batch_on_model_cases(filtered_models) + + +if __name__ == "__main__": + try: + mp.set_start_method("spawn") + except RuntimeError: + pass + + unittest.main(warnings="ignore") diff --git a/asian_ai/performance/SGLang/test/registered/lora/test_virtual_experts_kernels.py b/asian_ai/performance/SGLang/test/registered/lora/test_virtual_experts_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..f4eeccccd22e32923658f6a5c01719fdd1af4d78 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/lora/test_virtual_experts_kernels.py @@ -0,0 +1,280 @@ +"""Unit tests for the LoRA virtual-experts kernels under post-EP-dispatch +sentinel `topk_ids` (-1) and out-of-range expert IDs. + +Covers two regression bugs that surface only with `--lora-use-virtual-experts` ++ `ep_size > 1`: + +- `_fused_virtual_topk_ids` must preserve negative sentinel topk_ids. After + EP dispatch, non-local experts arrive as `-1`; the pre-fix kernel mapped + them onto a real virtual-expert slot belonging to another adapter and + triggered OOB loads in downstream LoRA kernels. + +- `_align_block_size_torch` / `_align_block_size_jit` (the `>= 1024`-expert + fallback paths) must route `-1` and `>= num_experts` IDs into a sentinel + bucket so they don't OOB-index `padded_offsets[sorted_expert_ids]` (negative + wrap, or past-end) and don't get assigned to a real expert in the + consumer-block table. + +Both kernels run on CUDA. The fallback is gated on `virtual_num_experts >= 1024` +in production, but we exercise it directly here at smaller sizes for cheaper +iteration; one test sticks to the >1024 regime to mirror the production trigger. + +Usage: + python -m pytest test/registered/lora/test_virtual_experts_kernels.py -v +""" + +import unittest + +import torch + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=15, stage="base-b", runner_config="1-gpu-small") + +from sglang.srt.lora.triton_ops.virtual_experts import ( + _align_block_size_jit, + _align_block_size_torch, + _fused_virtual_topk_ids, + fused_sanitize_expert_ids, +) + + +class TestFusedVirtualTopkIdsPreservesSentinels(CustomTestCase): + """Item B regression: post-EP-dispatch -1 sentinels must NOT be remapped.""" + + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA required") + cls.device = "cuda:0" + + def test_negative_sentinels_preserved(self): + # Mix of valid topk_ids in [0, num_experts), -1 sentinels (typical + # post-EP-dispatch), and a synthetic -2 to ensure the fix doesn't + # depend on the exact -1 value. + topk_ids = torch.tensor( + [ + [3, -1], + [-1, 5], + [0, 7], + [-1, -1], + [2, 9], + [11, -2], + [-1, 4], + [6, -1], + ], + dtype=torch.int32, + device=self.device, + ) + token_lora_mapping = torch.tensor( + [0, 1, 0, 2, -1, 1, 0, 1], dtype=torch.int32, device=self.device + ) + num_experts = 16 + max_loras = 4 + + virtual_ids, _, _ = _fused_virtual_topk_ids( + topk_ids, + token_lora_mapping, + num_experts, + shared_outer=False, + max_loras=max_loras, + ) + + # Every negative input must stay negative (and equal) in the output. + for m in range(topk_ids.shape[0]): + for k in range(topk_ids.shape[1]): + base = topk_ids[m, k].item() + if base < 0: + self.assertEqual( + virtual_ids[m, k].item(), + base, + f"negative sentinel at ({m},{k}) was remapped: " + f"{base} -> {virtual_ids[m, k].item()}", + ) + + def test_positive_topk_remapped_correctly(self): + """Sanity: valid (non-negative) IDs follow the + `base + safe_lora * num_experts` rule.""" + topk_ids = torch.tensor( + [[3, 1], [0, 7], [2, 9]], dtype=torch.int32, device=self.device + ) + token_lora_mapping = torch.tensor( + [0, 1, 2], dtype=torch.int32, device=self.device + ) + num_experts = 16 + max_loras = 4 + + virtual_ids, _, _ = _fused_virtual_topk_ids( + topk_ids, token_lora_mapping, num_experts, False, max_loras + ) + + for m in range(topk_ids.shape[0]): + lora = token_lora_mapping[m].item() + for k in range(topk_ids.shape[1]): + base = topk_ids[m, k].item() + expected = base + max(lora, 0) * num_experts + self.assertEqual(virtual_ids[m, k].item(), expected) + + def test_no_lora_token_does_not_shift_base(self): + """`token_lora_mapping[m] == -1` (no LoRA) keeps `safe_lora=0`, + so positive bases pass through unchanged and the row mask is False.""" + topk_ids = torch.tensor([[3, 5]], dtype=torch.int32, device=self.device) + token_lora_mapping = torch.tensor([-1], dtype=torch.int32, device=self.device) + num_experts = 16 + + virtual_ids, mask, _ = _fused_virtual_topk_ids( + topk_ids, token_lora_mapping, num_experts, False, max_loras=4 + ) + self.assertEqual(virtual_ids[0, 0].item(), 3) + self.assertEqual(virtual_ids[0, 1].item(), 5) + self.assertFalse(bool(mask[0].item())) + + +class _AlignBlockSizeSentinelBucketBase(CustomTestCase): + """Shared tests for both the torch.compile and JIT align_block_size paths. + + Subclasses override ``_align`` to select the concrete implementation. + """ + + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA required") + if cls is _AlignBlockSizeSentinelBucketBase: + raise unittest.SkipTest("Base class") + cls.device = "cuda:0" + + def _align(self, topk_ids, block_size, num_experts): + raise NotImplementedError + + @staticmethod + def _assigned_experts(expert_ids: torch.Tensor) -> list: + """Return the list of real expert ids assigned to blocks (filtering + out -1 sentinels for padding/exclusion).""" + return expert_ids[expert_ids != -1].cpu().tolist() + + def _assert_only_real_or_sentinel(self, expert_ids: torch.Tensor, num_experts: int): + for eid in expert_ids.cpu().tolist(): + self.assertTrue( + eid == -1 or 0 <= eid < num_experts, + f"expert_ids contains invalid value {eid}", + ) + + def test_all_valid_baseline(self): + """Sanity: with no invalid IDs, every present real expert appears + in the assignment, and no junk values leak through.""" + num_experts = 8 + block_size = 16 + topk_ids = torch.tensor( + [[0, 3], [4, 7], [1, 2], [5, 6]], + dtype=torch.int32, + device=self.device, + ) + + _, expert_ids, _ = self._align(topk_ids, block_size, num_experts) + + self._assert_only_real_or_sentinel(expert_ids, num_experts) + assigned = set(self._assigned_experts(expert_ids)) + self.assertEqual(assigned, set(range(num_experts))) + + def test_negative_ids_routed_to_sentinel(self): + """`-1` tokens must not appear as real expert assignments and must + not corrupt the assignment of real IDs.""" + num_experts = 8 + block_size = 16 + topk_ids = torch.tensor( + [[0, -1], [-1, 7], [1, -1], [-1, -1]], + dtype=torch.int32, + device=self.device, + ) + + _, expert_ids, _ = self._align(topk_ids, block_size, num_experts) + + self._assert_only_real_or_sentinel(expert_ids, num_experts) + assigned = self._assigned_experts(expert_ids) + for valid_eid in (0, 1, 7): + self.assertIn(valid_eid, assigned) + + def test_oor_ids_routed_to_sentinel(self): + """IDs `>= num_experts` (e.g. virtual-experts remap when combined + with non-local sentinels) must not break cumsum/searchsorted and + must not show up as real assignments.""" + num_experts = 8 + block_size = 16 + topk_ids = torch.tensor( + [[0, 100], [50, 7], [1, 200]], + dtype=torch.int32, + device=self.device, + ) + + _, expert_ids, _ = self._align(topk_ids, block_size, num_experts) + + self._assert_only_real_or_sentinel(expert_ids, num_experts) + assigned = self._assigned_experts(expert_ids) + for valid_eid in (0, 1, 7, 50): + if valid_eid >= num_experts: + self.assertNotIn(valid_eid, assigned) + else: + self.assertIn(valid_eid, assigned) + + def test_mixed_invalid_at_production_size(self): + """Mirror the production trigger: `num_experts >= 1024` (only path + where the large-expert fallback is invoked instead of the native + align kernel).""" + num_experts = 1500 + block_size = 16 + topk_ids = torch.tensor( + [ + [-1, 500], + [num_experts + 7, 1000], + [num_experts * 2, 100], + [-1, 0], + ], + dtype=torch.int32, + device=self.device, + ) + + _, expert_ids, _ = self._align(topk_ids, block_size, num_experts) + + self._assert_only_real_or_sentinel(expert_ids, num_experts) + assigned = self._assigned_experts(expert_ids) + for valid_eid in (0, 100, 500, 1000): + self.assertIn(valid_eid, assigned) + + def test_empty_topk_ids_does_not_crash(self): + """Edge: empty input. Should return empty/zero outputs without + OOB indexing on the sentinel bucket.""" + num_experts = 8 + block_size = 16 + topk_ids = torch.empty((0, 2), dtype=torch.int32, device=self.device) + + sorted_token_ids, expert_ids, num_post_padded = self._align( + topk_ids, block_size, num_experts + ) + + self.assertEqual(num_post_padded.item(), 0) + self.assertEqual(self._assigned_experts(expert_ids), []) + + +class TestAlignBlockSizeTorchSentinelBucket(_AlignBlockSizeSentinelBucketBase): + """Test the pure-PyTorch torch.compile fallback path (AMD/ROCm compatible).""" + + def _align(self, topk_ids, block_size, num_experts): + return _align_block_size_torch(topk_ids, block_size, num_experts) + + +class TestAlignBlockSizeJitSentinelBucket(_AlignBlockSizeSentinelBucketBase): + """Test the CUDA JIT kernel path (with fused_sanitize_expert_ids, as in + production).""" + + def _align(self, topk_ids, block_size, num_experts): + sorted_token_ids, expert_ids, num_tokens_post_padded = _align_block_size_jit( + topk_ids, block_size, num_experts + ) + expert_ids = fused_sanitize_expert_ids(expert_ids, num_experts) + return sorted_token_ids, expert_ids, num_tokens_post_padded + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/asian_ai/performance/SGLang/test/registered/mem_cache/test_int8_checkpoint_store.py b/asian_ai/performance/SGLang/test/registered/mem_cache/test_int8_checkpoint_store.py new file mode 100644 index 0000000000000000000000000000000000000000..b1637a7aae065f10882f172fe124d79a97a88276 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mem_cache/test_int8_checkpoint_store.py @@ -0,0 +1,185 @@ +"""Tests for Int8CheckpointStore (int8-compressed cached linear-attn states). + +CPU tests cover the codec error bound, store/load round-trip, and the active-pool +copy-on-write helpers. The CUDA test reproduces the validated decode-output error +(int8 checkpoint loaded once then decoded continues bf16) ~ 0.5%, far below the +bf16-baseline-relative threshold that GSM8K showed is quality-safe. + + python -m pytest test/registered/mem_cache/test_int8_checkpoint_store.py -v +""" + +import unittest + +import torch + +from sglang.srt.mem_cache.mamba_checkpoint_pool import ( + Int8CheckpointStore, + MambaCheckpointPool, +) +from sglang.test.ci.ci_register import register_cpu_ci + +# These are CPU codec / store / pool unit tests (the single CUDA decode-error +# case self-skips when no GPU is present), so they run on the cheapest CI tier. +# The int8 GPU decode path is covered end-to-end by +# test_int8_mamba_checkpoint_e2e (now in the extra stage). +register_cpu_ci(est_time=15, suite="base-a-test-cpu") + +H, V, K = 32, 128, 128 +L = 4 + + +def _rand_state(n, device="cpu"): + # KDA-like state magnitudes (see fp8_checkpoint_probe: |S| mean ~6e-2) + return torch.randn(L, n, H, V, K, device=device) * 6e-2 + + +class TestInt8CheckpointCodec(unittest.TestCase): + def test_quantize_dequantize_error_bound(self): + s = _rand_state(8) + q, scale = Int8CheckpointStore.quantize(s) + self.assertEqual(q.dtype, torch.int8) + self.assertEqual(scale.shape, (L, 8, H, 1, K)) # per (layer,slot,head,k-chan) + deq = Int8CheckpointStore.dequantize(q, scale, torch.float32) + rel = (deq - s).norm() / s.norm() + # uniform int8 per-channel on a ~uniform state: well under 1% + self.assertLess(rel.item(), 1e-2, f"int8 codec rel err too high: {rel}") + + def test_symmetric_and_zero(self): + s = torch.zeros(L, 1, H, V, K) + q, scale = Int8CheckpointStore.quantize(s) + self.assertTrue(torch.equal(q, torch.zeros_like(q))) + deq = Int8CheckpointStore.dequantize(q, scale, torch.float32) + self.assertTrue(torch.equal(deq, s)) + + def test_store_load_roundtrip(self): + store = Int8CheckpointStore( + num_layers=L, + num_slots=16, + num_heads=H, + head_v_dim=V, + head_k_dim=K, + device="cpu", + ) + s = _rand_state(4) + slots = torch.tensor([1, 3, 5, 7]) + store.store(slots, s) + out = store.load(slots, torch.float32) + # load == dequant of stored + q, scale = Int8CheckpointStore.quantize(s) + ref = Int8CheckpointStore.dequantize( + q, scale.to(store.scale.dtype), torch.float32 + ) + self.assertLess((out - ref).abs().max().item(), 1e-3) + + def test_cow_helpers(self): + store = Int8CheckpointStore( + num_layers=L, + num_slots=16, + num_heads=H, + head_v_dim=V, + head_k_dim=K, + device="cpu", + ) + active = torch.zeros(L, 10, H, V, K) # bf16/fp32 active pool + active[:, 2] = _rand_state(1).squeeze(1) + # store active slot 2 -> ckpt slot 4 + store.store_from_pool(active, torch.tensor([2]), torch.tensor([4])) + # load ckpt slot 4 -> active slot 6 (cache-hit COW) + store.copy_to_pool(active, torch.tensor([4]), torch.tensor([6])) + rel = (active[:, 6] - active[:, 2]).norm() / active[:, 2].norm() + self.assertLess(rel.item(), 1e-2) + + def test_memory_is_half_of_bf16(self): + store = Int8CheckpointStore( + num_layers=L, + num_slots=100, + num_heads=H, + head_v_dim=V, + head_k_dim=K, + device="cpu", + ) + bf16_per_slot = L * H * V * K * 2 + # int8 data (1B) + small per-(head,k) bf16 scale -> well under bf16; ~2x slots + self.assertLess(store.bytes_per_slot(), bf16_per_slot * 0.6) + + def test_estimate_matches_actual_mem(self): + # the pre-allocation estimate (used to fit-check HBM before building the + # pool) must equal the real allocated footprint, for any temporal dtype + for tdt in (torch.bfloat16, torch.float32): + kw = dict( + num_layers=L, + num_slots=64, + num_heads=H, + head_v_dim=V, + head_k_dim=K, + conv_shapes=[(4, K)], + conv_dtype=torch.bfloat16, + temporal_dtype=tdt, + ) + est = MambaCheckpointPool.estimate_mem_usage_bytes(**kw) + pool = MambaCheckpointPool(**kw, device="cpu") + self.assertEqual(est["qdata"] + est["scale"] + est["conv"], est["total"]) + self.assertEqual(est["total"], pool.mem_usage_bytes()) + + +@unittest.skipUnless(torch.cuda.is_available(), "needs CUDA + fla kernels") +class TestInt8CheckpointDecodeError(unittest.TestCase): + def test_decode_error_within_bound(self): + try: + from sglang.srt.layers.attention.fla.kda import fused_recurrent_kda + except (ImportError, ModuleNotFoundError) as e: + self.skipTest(f"fla kernels unavailable: {e}") + + dev = "cuda" + torch.manual_seed(0) + + def synth(T, s): + torch.manual_seed(s) + q = torch.randn(1, T, H, K, device=dev, dtype=torch.bfloat16) * 0.5 + k = torch.randn(1, T, H, K, device=dev, dtype=torch.bfloat16) * 0.5 + v = (torch.randn(1, T, H, V, device=dev) * 0.5).bfloat16() + beta = torch.rand(1, T, H, device=dev, dtype=torch.bfloat16) + g = -torch.rand(1, T, H, K, device=dev, dtype=torch.float32) * 0.1 - 0.005 + return q, k, v, g, beta + + def decode(state, inp): + st = state.clone() + o, _ = fused_recurrent_kda( + q=inp[0], + k=inp[1], + v=inp[2], + g=inp[3], + beta=inp[4], + scale=K**-0.5, + initial_state=st, + inplace_final_state=True, + use_qk_l2norm_in_kernel=True, + cu_seqlens=None, + ) + return o.float() + + S = torch.zeros(1, H, V, K, device=dev, dtype=torch.float32) + pre = synth(512, 0) + fused_recurrent_kda( + q=pre[0], + k=pre[1], + v=pre[2], + g=pre[3], + beta=pre[4], + scale=K**-0.5, + initial_state=S, + inplace_final_state=True, + use_qk_l2norm_in_kernel=True, + cu_seqlens=None, + ) + dec = synth(128, 1) + o_ref = decode(S, dec) + q, scale = Int8CheckpointStore.quantize(S) # [1,H,V,K] + S_int8 = Int8CheckpointStore.dequantize(q, scale, torch.float32) + o_int8 = decode(S_int8, dec) + rel = (o_int8 - o_ref).norm() / o_ref.norm() + self.assertLess(rel.item(), 1.5e-2, f"int8 decode err {rel} too high") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mla/test_flashmla.py b/asian_ai/performance/SGLang/test/registered/mla/test_flashmla.py new file mode 100644 index 0000000000000000000000000000000000000000..1cf91234acee335f4916e463e8bb3a9c5d55478b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mla/test_flashmla.py @@ -0,0 +1,93 @@ +""" +Usage: +python3 test/registered/mla/test_flashmla.py +""" + +import unittest +from types import SimpleNamespace + +import requests +import torch + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +# FlashMLA attention backend tests with MTP speculative decoding +register_cuda_ci(est_time=160, stage="base-b", runner_config="1-gpu-large") + + +class TestFlashMLAMTP(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "lmsys/sglang-ci-dsv3-test" + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = ["--trust-remote-code"] + if torch.cuda.is_available() and torch.version.cuda: + other_args.extend( + [ + "--cuda-graph-max-bs-decode", + "4", + "--disable-radix", + "--enable-torch-compile", + "--torch-compile-max-bs", + "1", + "--speculative-algorithm", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/sglang-ci-dsv3-test-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "3", + "--attention-backend", + "flashmla", + ] + ) + # Use longer timeout for DeepGEMM JIT compilation which can take 10-20 minutes + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 2, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + requests.get(self.base_url + "/flush_cache") + + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + server_info = requests.get(self.base_url + "/server_info").json() + avg_spec_accept_length = server_info["internal_states"][0][ + "avg_spec_accept_length" + ] + print(f"{avg_spec_accept_length=}") + self.assertGreater(avg_spec_accept_length, 2.4) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mla/test_mla_flashinfer.py b/asian_ai/performance/SGLang/test/registered/mla/test_mla_flashinfer.py new file mode 100644 index 0000000000000000000000000000000000000000..8b048458df0ab5fadae6a95b28f174d7565d38cc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mla/test_mla_flashinfer.py @@ -0,0 +1,84 @@ +import unittest +from types import SimpleNamespace + +import requests +import torch + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +# FlashInfer MLA backend tests with MTP speculative decoding +register_cuda_ci(est_time=130, stage="base-b", runner_config="1-gpu-large") + + +class TestFlashinferMLAMTP(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "lmsys/sglang-ci-dsv3-test" + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = ["--trust-remote-code"] + if torch.cuda.is_available() and torch.version.cuda: + other_args.extend( + [ + "--cuda-graph-max-bs-decode", + "4", + "--enable-torch-compile", + "--torch-compile-max-bs", + "1", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--attention-backend", + "flashinfer", + ] + ) + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + requests.get(self.base_url + "/flush_cache") + + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + server_info = requests.get(self.base_url + "/server_info").json() + avg_spec_accept_length = server_info["internal_states"][0][ + "avg_spec_accept_length" + ] + print(f"{avg_spec_accept_length=}") + self.assertGreater(avg_spec_accept_length, 2.5) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mla/test_mla_fp8.py b/asian_ai/performance/SGLang/test/registered/mla/test_mla_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6d7d8d728acab937d9cf67bc9b9bcb2146cdfc --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mla/test_mla_fp8.py @@ -0,0 +1,55 @@ +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import MGSMEnMixin +from sglang.test.test_utils import ( + DEFAULT_MLA_FP8_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_amd_ci, + popen_launch_server, +) + +# MLA FP8 KV cache test with MGSM evaluation +register_cuda_ci(est_time=104, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=800, suite="stage-b-test-1-gpu-small-amd") + + +class TestMLA(CustomTestCase, MGSMEnMixin): + mgsm_en_score_threshold = 0.8 + + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_FP8_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--trust-remote-code", + "--kv-cache-dtype", + "fp8_e5m2", + # Pin MoE expert dispatch and kernel reduction order so MGSM + # scores don't drift across runs. The eval already uses greedy + # decoding, but FP8 dequant + non-deterministic MoE top-k + # tie-breaks produce ~1–3 point swings without this flag and + # straddle the 0.8 threshold. With deterministic inference, + # the score becomes a fixed function of (model, weights, CUDA + # stack), so threshold-edge flakes stop being random noise. + ] + if not is_in_amd_ci(): + # On AMD, the default attention backend (aiter) is not in the deterministic-inference allowlist, so the server fails to start, disable it. + other_args.append("--enable-deterministic-inference") + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mla/test_mla_int8_deepseek_v3.py b/asian_ai/performance/SGLang/test/registered/mla/test_mla_int8_deepseek_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..c402653698192658cd7560fe4764b7fab5b54d5a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mla/test_mla_int8_deepseek_v3.py @@ -0,0 +1,146 @@ +import unittest +from types import SimpleNamespace + +import requests +import torch + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, +) + +# DeepSeek-V3 INT8 quantization tests (channel and block INT8) +register_cuda_ci(est_time=160, stage="base-b", runner_config="1-gpu-large") + + +class TestDeepseekV3MTPChannelInt8(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "lmsys/sglang-ci-dsv3-channel-int8-test" + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = ["--trust-remote-code"] + if torch.cuda.is_available() and torch.version.cuda: + other_args.extend( + [ + "--cuda-graph-max-bs-decode", + "16", + "--enable-torch-compile", + "--torch-compile-max-bs", + "2", + "--speculative-algorithm", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/sglang-ci-dsv3-channel-int8-test-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ] + ) + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + requests.get(self.base_url + "/flush_cache") + + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + server_info = requests.get(self.base_url + "/server_info") + avg_spec_accept_length = server_info.json()["internal_states"][0][ + "avg_spec_accept_length" + ] + print(f"{avg_spec_accept_length=}") + self.assertGreater(avg_spec_accept_length, 2.5) + + +@unittest.skipIf(is_in_ci(), "To reduce the CI execution time.") +class TestDeepseekV3MTPBlockInt8(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "lmsys/sglang-ci-dsv3-block-int8-test" + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = ["--trust-remote-code"] + if torch.cuda.is_available() and torch.version.cuda: + other_args.extend( + [ + "--cuda-graph-max-bs-decode", + "16", + "--enable-torch-compile", + "--torch-compile-max-bs", + "2", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ] + ) + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + requests.get(self.base_url + "/flush_cache") + + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + server_info = requests.get(self.base_url + "/server_info") + avg_spec_accept_length = server_info.json()["internal_states"][0][ + "avg_spec_accept_length" + ] + print(f"{avg_spec_accept_length=}") + self.assertGreater(avg_spec_accept_length, 2.5) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_pd.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_pd.py new file mode 100644 index 0000000000000000000000000000000000000000..1a208881041ddec73287b64470dea67a40aa39c4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_pd.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import time +import unittest +from concurrent.futures import ThreadPoolExecutor, as_completed +from typing import ClassVar, Dict, List + +import requests + +from sglang.srt.utils import is_hip +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kv_canary.violation_log_utils import assert_no_violation_in_log +from sglang.test.mock_model.utils import ( + MOCK_MODEL_PATH, + mock_model_server_args, + mock_model_server_env, +) +from sglang.test.server_fixtures.disaggregation_fixture import ( + PDDisaggregationServerBase, +) + +register_cuda_ci(est_time=600, stage="extra-a", runner_config="2-gpu-large") +register_amd_ci(est_time=165, stage="extra-a", runner_config="2-gpu-large-amd") + +# DO NOT pass --disable-cuda-graph in canary e2e tests. The canary kernel +# must run inside the cuda graph alongside the real attn kernel; disabling the +# full graph silently bypasses the only path that exercises that invariant +# end-to-end. +# +# --disable-piecewise-cuda-graph is REQUIRED by canary: install_canary +# (api.py) asserts it, and the SingleForwardManager design depends on it. +# mock_model_server_args() already passes it; do not remove it. +_NUM_PROMPTS = 32 +_INPUT_LEN = 6144 +_OUTPUT_LEN = 1024 + + +def _send_parallel_requests( + base_url: str, + *, + n: int, + max_new_tokens: int, + timeout: float = 60.0, + max_workers: int = 16, +) -> List[Dict[str, object]]: + """Fire N /generate requests concurrently; return raw response dicts.""" + + def _one(i: int) -> Dict[str, object]: + payload = { + "input_ids": _make_input_ids(seed=i, length=_INPUT_LEN), + "sampling_params": {"max_new_tokens": max_new_tokens, "temperature": 0.0}, + } + try: + resp = requests.post(base_url + "/generate", json=payload, timeout=timeout) + return {"index": i, "status_code": resp.status_code, "text": resp.text} + except requests.exceptions.RequestException as exc: + return {"index": i, "error": repr(exc)} + + results: List[Dict[str, object]] = [] + with ThreadPoolExecutor(max_workers=max_workers) as pool: + futures = [pool.submit(_one, i) for i in range(n)] + for fut in as_completed(futures): + results.append(fut.result()) + results.sort(key=lambda r: r["index"]) + return results + + +def _make_input_ids(*, seed: int, length: int) -> List[int]: + return [((seed + i) % 2048) + 1 for i in range(length)] + + +class _MockModelPDBase(PDDisaggregationServerBase): + """PD fixture for mock-model + canary e2e tests.""" + + capture_per_side_logs = True + model: ClassVar[str] = MOCK_MODEL_PATH + extra_prefill_args: ClassVar[List[str]] = mock_model_server_args( + "--skip-server-warmup" + ) + extra_decode_args: ClassVar[List[str]] = mock_model_server_args( + "--skip-server-warmup" + ) + extra_prefill_env: ClassVar[Dict[str, str]] = mock_model_server_env( + input_check_enabled=True + ) + extra_decode_env: ClassVar[Dict[str, str]] = mock_model_server_env( + input_check_enabled=True + ) + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + cls.launch_all() + + def assert_no_canary_violation(self) -> None: + time.sleep(2) + log_text = "".join( + buf.getvalue() + for buf in ( + self._prefill_stdout_buf, + self._prefill_stderr_buf, + self._decode_stdout_buf, + self._decode_stderr_buf, + ) + if buf is not None + ) + assert_no_violation_in_log(log_text) + + +class TestPdTransferCanaryClean(_MockModelPDBase, unittest.TestCase): + """PD standard scenario + baseline canary (input-check, no real-KV checksum); no violation expected.""" + + def test_pd_transfer_canary_clean(self) -> None: + # Step 1: send parallel requests through the LB to exercise PD transfer path. + results = _send_parallel_requests( + self.lb_url, + n=_NUM_PROMPTS, + max_new_tokens=_OUTPUT_LEN, + timeout=240.0, + max_workers=_NUM_PROMPTS, + ) + + # Step 2: every request must complete with status 200. + for result in results: + self.assertEqual(result.get("status_code"), 200, result) + + # Step 3: servers must stay alive. + self.assertIsNone(self.process_prefill.poll(), "Prefill server died") + self.assertIsNone(self.process_decode.poll(), "Decode server died") + self.assert_no_canary_violation() + + +@unittest.skipIf( + is_hip(), + "ROCm: PD full-real-data KV checksum intermittently trips a " + "verify_real_kv_hash canary violation on the decode-side transferred prefix " + "(see https://github.com/sgl-project/sglang/issues/28971). The baseline PD " + "canary test above stays enabled on AMD.", +) +class TestPdTransferChecksumFullRealData(_MockModelPDBase, unittest.TestCase): + """--kv-canary-real-data=all + sweep every step, no perturb, no violation.""" + + extra_prefill_args: ClassVar[List[str]] = mock_model_server_args( + "--skip-server-warmup", + "--kv-canary-real-data", + "all", + "--kv-canary-sweep-interval", + "1", + ) + extra_decode_args: ClassVar[List[str]] = mock_model_server_args( + "--skip-server-warmup", + "--kv-canary-real-data", + "all", + "--kv-canary-sweep-interval", + "1", + "--disaggregation-decode-enable-radix-cache", + ) + + def test_pd_transfer_checksum_full_real_data(self) -> None: + # Step 1: drive traffic through the PD path with full real-KV hashing. + results = _send_parallel_requests( + self.lb_url, + n=_NUM_PROMPTS, + max_new_tokens=_OUTPUT_LEN, + timeout=240.0, + max_workers=_NUM_PROMPTS, + ) + + # Step 2: all requests must succeed. + for result in results: + self.assertEqual(result.get("status_code"), 200, result) + + # Step 3: servers must stay healthy. + self.assertIsNone(self.process_prefill.poll(), "Prefill server died") + self.assertIsNone(self.process_decode.poll(), "Decode server died") + self.assert_no_canary_violation() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_pp.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_pp.py new file mode 100644 index 0000000000000000000000000000000000000000..e3369835f264a66752e690c3ac76fd3b4c9d564a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_pp.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import unittest + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.mock_model.utils import run_mock_model_bench_serving +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=600, stage="extra-a", runner_config="2-gpu-large") +register_amd_ci(est_time=67, stage="extra-a", runner_config="2-gpu-large-amd") + + +class TestE2EPipelineParallel(CustomTestCase): + def test_pp_no_canary_violation(self) -> None: + run_mock_model_bench_serving( + extra_server_args=["--pp-size", "2"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_spec_eagle.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_spec_eagle.py new file mode 100644 index 0000000000000000000000000000000000000000..2eed4ef1fecbf9e101008437fe59d81716950bda --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_spec_eagle.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +import unittest + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.mock_model.utils import MOCK_MODEL_PATH, run_mock_model_bench_serving +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=600, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=77, stage="extra-a", runner_config="1-gpu-small-amd") + + +class TestE2ESpeculativeEagle(CustomTestCase): + def test_spec_eagle_no_canary_violation(self) -> None: + run_mock_model_bench_serving( + extra_server_args=[ + "--speculative-algorithm", + "EAGLE", + "--speculative-draft-model-path", + MOCK_MODEL_PATH, + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", + "--mem-fraction-static", + "0.45", + ], + input_check_enabled=False, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_tp.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_tp.py new file mode 100644 index 0000000000000000000000000000000000000000..573397f69c36412e23cba4479fe8a37970df5b52 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_e2e_tp.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import unittest + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.mock_model.utils import run_mock_model_bench_serving +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=600, stage="extra-a", runner_config="2-gpu-large") +register_amd_ci(est_time=167, stage="extra-a", runner_config="2-gpu-large-amd") + + +class TestE2ETensorParallel(CustomTestCase): + def test_tp_no_canary_violation(self) -> None: + run_mock_model_bench_serving( + extra_server_args=["--tp", "2", "--mem-fraction-static", "0.88"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_self_e2e_perturb_next_token_swap.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_e2e_perturb_next_token_swap.py new file mode 100644 index 0000000000000000000000000000000000000000..41bede9d14f2ef46838b44f2385e00b7264454a8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_e2e_perturb_next_token_swap.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import unittest + +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.mock_model.perturb_e2e_base import MockModelPerturbE2EBase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=131, stage="extra-a", runner_config="1-gpu-small-amd") + + +class TestPerturbNextTokenSwap(MockModelPerturbE2EBase): + """Mock-model self-test: swap two reqs' sampled next tokens at the sampler exit. + + KV path is untouched, so kv_canary KV-side fail_reasons stay silent. The + token-oracle input check downstream MUST report fail_reason=write_token. + Validates the input-check link is genuinely active. + """ + + extra_env = { + "SGLANG_KV_CANARY_PERTURB_NEXT_TOKEN_SWAP_PROB": "0.1", + "SGLANG_KV_CANARY_PERTURB_WARMUP_STEPS": "0", + } + extra_server_args = ("--skip-server-warmup",) + + def test_swap_triggers_input_check_violation_but_kv_paths_silent(self) -> None: + """Verify next_token swap fires write_token violation while KV reasons stay silent.""" + self.send_parallel_requests(n=4, timeout=30.0) + self.assert_log_contains("kv_canary perturb next_token_swap: swapped") + self.assert_any_launch_tag_violation_reported(fail_reason="write_token") + self.assert_any_launch_tag_violation_absent(fail_reason="verify_real_kv_hash") + self.assert_any_launch_tag_violation_absent(fail_reason="verify_position") + self.assert_any_launch_tag_violation_absent(fail_reason="verify_chain_hash") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_canary_mock_wiring.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_canary_mock_wiring.py new file mode 100644 index 0000000000000000000000000000000000000000..61f96cd5c2e9924373c5362f63562e1acf02c700 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_canary_mock_wiring.py @@ -0,0 +1,239 @@ +from __future__ import annotations + +import dataclasses +import unittest + +import torch + +from sglang.srt.kv_canary.expected_inputs import ExpectedInputs +from sglang.srt.kv_canary.token_oracle.oracle import HashOracle +from sglang.srt.kv_canary.token_oracle.sampler import install_oracle_sampler +from sglang.srt.model_executor.forward_batch_info import ( + ForwardMode, + _stable_hash_str_to_i64, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.mock_model.utils import mock_model_server_args, mock_model_server_env +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=60, suite="extra-a-test-1-gpu-small-amd") + + +@dataclasses.dataclass +class _StubForwardBatch: + input_ids: torch.Tensor + positions: torch.Tensor + req_pool_indices: torch.Tensor + forward_mode: ForwardMode + extend_seq_lens: object + rids_int: torch.Tensor + bootstrap_room_ids_int: torch.Tensor | None = None + spec_info: object | None = None + seq_lens: torch.Tensor | None = None + + +def _scalar_expected_token( + oracle: HashOracle, *, generalized_req_id: int, position: int +) -> int: + out = oracle.expected_tokens( + generalized_req_ids=torch.tensor([generalized_req_id], dtype=torch.int64), + positions=torch.tensor([position], dtype=torch.int64), + ) + return int(out.tolist()[0]) + + +class TestFillExpectedInputs(CustomTestCase): + def test_sample_next_tokens_uses_next_position(self) -> None: + oracle = HashOracle(vocab_size=32000) + hook = install_oracle_sampler(oracle=oracle) + + rid_a = "req-a" + hashed_a = _stable_hash_str_to_i64(rid_a) + out = hook.sample_next_tokens( + generalized_req_ids=torch.tensor([hashed_a], dtype=torch.int64), + logits_positions=torch.tensor([5], dtype=torch.int64), + ) + + self.assertEqual( + out.tolist(), + [_scalar_expected_token(oracle, generalized_req_id=hashed_a, position=6)], + ) + + def test_fill_expected_inputs_decode_one_token_per_req(self) -> None: + """Verify decode mode fills one expected token per request.""" + oracle = HashOracle(vocab_size=32000) + hook = install_oracle_sampler(oracle=oracle) + + rid_a = "req-a" + rid_b = "req-b" + fb = _StubForwardBatch( + input_ids=torch.tensor([0, 0], dtype=torch.int64), + positions=torch.tensor([10, 20], dtype=torch.int64), + req_pool_indices=torch.tensor([5, 7], dtype=torch.int64), + forward_mode=ForwardMode.DECODE, + extend_seq_lens=None, + rids_int=torch.tensor( + [_stable_hash_str_to_i64(rid_a), _stable_hash_str_to_i64(rid_b)], + dtype=torch.int64, + ), + ) + expected_inputs = ExpectedInputs.allocate( + capacity=8, device=torch.device("cpu") + ) + + hook.fill_expected_inputs( + forward_batch=fb, + expected_inputs_out=expected_inputs, + ) + + self.assertEqual( + expected_inputs.tokens[:2].tolist(), + [ + _scalar_expected_token( + oracle, + generalized_req_id=_stable_hash_str_to_i64(rid_a), + position=10, + ), + _scalar_expected_token( + oracle, + generalized_req_id=_stable_hash_str_to_i64(rid_b), + position=20, + ), + ], + ) + self.assertEqual(expected_inputs.positions[:2].tolist(), [10, 20]) + + def test_fill_expected_inputs_prefers_bootstrap_room_ids(self) -> None: + """Verify PD oracle checks can key by bootstrap room without rewriting rids_int.""" + oracle = HashOracle(vocab_size=32000) + hook = install_oracle_sampler(oracle=oracle) + + rid_a = "prefill-local-rid" + rid_b = "regular-rid" + hashed_a = _stable_hash_str_to_i64(rid_a) + hashed_b = _stable_hash_str_to_i64(rid_b) + fb = _StubForwardBatch( + input_ids=torch.tensor([0, 0], dtype=torch.int64), + positions=torch.tensor([10, 20], dtype=torch.int64), + req_pool_indices=torch.tensor([5, 7], dtype=torch.int64), + forward_mode=ForwardMode.DECODE, + extend_seq_lens=None, + rids_int=torch.tensor([hashed_a, hashed_b], dtype=torch.int64), + bootstrap_room_ids_int=torch.tensor([1234, -1], dtype=torch.int64), + ) + expected_inputs = ExpectedInputs.allocate( + capacity=8, device=torch.device("cpu") + ) + + hook.fill_expected_inputs( + forward_batch=fb, + expected_inputs_out=expected_inputs, + ) + + self.assertEqual(fb.rids_int.tolist(), [hashed_a, hashed_b]) + self.assertEqual( + expected_inputs.tokens[:2].tolist(), + [ + _scalar_expected_token(oracle, generalized_req_id=1234, position=10), + _scalar_expected_token( + oracle, generalized_req_id=hashed_b, position=20 + ), + ], + ) + self.assertEqual(expected_inputs.positions[:2].tolist(), [10, 20]) + + def test_fill_expected_inputs_extend_uses_forward_input_ids(self) -> None: + """Verify extend mode checks prompt tokens already present in the forward batch.""" + oracle = HashOracle(vocab_size=32000) + hook = install_oracle_sampler(oracle=oracle) + + rid_a = "req-a" + rid_b = "req-b" + hashed_a = _stable_hash_str_to_i64(rid_a) + hashed_b = _stable_hash_str_to_i64(rid_b) + fb = _StubForwardBatch( + input_ids=torch.tensor([101, 102, 103, 201], dtype=torch.int64), + positions=torch.tensor([0, 1, 2, 0], dtype=torch.int64), + req_pool_indices=torch.tensor([5, 7], dtype=torch.int64), + forward_mode=ForwardMode.EXTEND, + extend_seq_lens=torch.tensor([3, 1], dtype=torch.int64), + rids_int=torch.tensor([hashed_a, hashed_b], dtype=torch.int64), + ) + expected_inputs = ExpectedInputs.allocate( + capacity=8, device=torch.device("cpu") + ) + + hook.fill_expected_inputs( + forward_batch=fb, + expected_inputs_out=expected_inputs, + ) + + self.assertEqual( + expected_inputs.tokens[:4].tolist(), + [101, 102, 103, 201], + ) + self.assertEqual(expected_inputs.positions[:4].tolist(), [0, 1, 2, 0]) + + def test_fill_expected_inputs_zero_tokens_is_noop( + self, + ) -> None: + """Verify filling zero expected tokens leaves the output buffer unchanged.""" + hook = install_oracle_sampler(oracle=HashOracle(vocab_size=100)) + + rid_a = "req-a" + rid_b = "req-b" + fb = _StubForwardBatch( + input_ids=torch.empty(0, dtype=torch.int64), + positions=torch.empty(0, dtype=torch.int64), + req_pool_indices=torch.tensor([5, 7], dtype=torch.int64), + forward_mode=ForwardMode.DECODE, + extend_seq_lens=None, + rids_int=torch.tensor( + [_stable_hash_str_to_i64(rid_a), _stable_hash_str_to_i64(rid_b)], + dtype=torch.int64, + ), + ) + expected_inputs = ExpectedInputs.allocate( + capacity=4, device=torch.device("cpu") + ) + initial_tokens = expected_inputs.tokens.clone() + + hook.fill_expected_inputs( + forward_batch=fb, + expected_inputs_out=expected_inputs, + ) + + self.assertEqual(expected_inputs.tokens.tolist(), initial_tokens.tolist()) + + +class TestMockModelServerLaunchHelpers(CustomTestCase): + def test_mock_model_server_args_adds_canary_defaults(self) -> None: + """Verify mock model launch args include KV canary defaults before user args.""" + args = mock_model_server_args("--tp", "2") + + self.assertIn("--load-format", args) + self.assertIn("dummy", args) + self.assertIn("--sampling-backend", args) + self.assertIn("token_oracle", args) + self.assertIn("--kv-canary", args) + self.assertIn("raise", args) + self.assertEqual(args[-2:], ["--tp", "2"]) + + def test_mock_model_server_env_enables_input_check_by_default(self) -> None: + """Verify mock model launch env enables canary input checking by default.""" + env = mock_model_server_env() + + self.assertEqual(env["SGLANG_KV_CANARY_ENABLE_WRITE_INPUT_ASSERT"], "1") + self.assertEqual(env["SGLANG_KV_CANARY_ENABLE_TOKEN_ORACLE"], "1") + + def test_mock_model_server_env_can_disable_input_check(self) -> None: + """Verify mock model launch env can disable canary input checking.""" + env = mock_model_server_env(input_check_enabled=False) + + self.assertEqual(env["SGLANG_KV_CANARY_ENABLE_WRITE_INPUT_ASSERT"], "0") + self.assertEqual(env["SGLANG_KV_CANARY_ENABLE_TOKEN_ORACLE"], "1") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_canary_perturb.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_canary_perturb.py new file mode 100644 index 0000000000000000000000000000000000000000..d49bfd253e0f04938ab08de7fe6da21b47ccf6e5 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_canary_perturb.py @@ -0,0 +1,47 @@ +import logging +import unittest +from unittest.mock import Mock + +from sglang.srt.kv_canary.perturb import real_kv_used +from sglang.srt.kv_canary.perturb.config import PerturbConfig, TargetGroupKind +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class TestCanaryPerturb(CustomTestCase): + def test_real_kv_used_logs_when_target_group_has_no_real_kv_sources(self) -> None: + """Verify real KV used perturbation logs when the target group has no sources.""" + config = PerturbConfig( + req_to_token_prob=0.0, + real_kv_used_prob=1.0, + real_kv_unused_cache_prob=0.0, + real_kv_post_forward_prob=0.0, + target_group_kind=TargetGroupKind.FULL, + warmup_steps=0, + ) + warmup_gate = Mock() + warmup_gate.is_in_warmup.return_value = False + + # Empty buffer_groups means pick_target_group returns None, so run() takes + # the early-return branch before any slot is picked. + with self.assertLogs(real_kv_used.logger.name, level=logging.INFO) as logs: + real_kv_used.run( + maybe_inaccurate_forward_batch=Mock(), + config=config, + req_to_token_pool=Mock(), + buffer_groups=(), + swa_window_size=0, + warmup_gate=warmup_gate, + ) + + self.assertIn( + "kv_canary perturb real_kv_used: skipped because no target group with " + "real_kv_sources_k matched target_group_kind=full", + "\n".join(logs.output), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_install.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_install.py new file mode 100644 index 0000000000000000000000000000000000000000..9328670d7e04c7831f11e4f03f6a3dbb74da0814 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_install.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import os +import unittest +from types import SimpleNamespace + +os.environ["SGLANG_KV_CANARY_ENABLE_TOKEN_ORACLE"] = "1" + +from sglang.srt.kv_canary.token_oracle.install import install_token_oracle_from_env +from sglang.srt.kv_canary.token_oracle.oracle import HashOracle +from sglang.srt.layers.sampler import _CUSTOM_SAMPLER_FACTORIES +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=60, suite="extra-a-test-1-gpu-small-amd") + + +def _make_server_args(*, sampling_backend: str) -> SimpleNamespace: + return SimpleNamespace(sampling_backend=sampling_backend) + + +class TestInstallTokenOracleFromEnv(CustomTestCase): + def test_install_token_oracle_from_env_disabled_returns_none(self) -> None: + """Verify server-arg-disabled token oracle installation (sampling_backend != 'token_oracle') returns no TokenOracleManager.""" + server_args = _make_server_args(sampling_backend="auto") + hook = install_token_oracle_from_env(server_args=server_args, vocab_size=1000) + self.assertIsNone(hook) + + def test_install_token_oracle_from_env_enabled_registers_oracle_backend( + self, + ) -> None: + """Verify token oracle installation via sampling_backend='token_oracle' registers the oracle backend.""" + server_args = _make_server_args(sampling_backend="token_oracle") + hook = install_token_oracle_from_env(server_args=server_args, vocab_size=512) + self.assertIsNotNone(hook) + self.assertIn("token_oracle", _CUSTOM_SAMPLER_FACTORIES) + + def test_install_token_oracle_from_env_enabled_returns_hook_with_hash_oracle( + self, + ) -> None: + """Verify token oracle installation via sampling_backend='token_oracle' returns a TokenOracleManager wrapping a HashOracle.""" + server_args = _make_server_args(sampling_backend="token_oracle") + hook = install_token_oracle_from_env(server_args=server_args, vocab_size=256) + self.assertIsNotNone(hook) + self.assertIsInstance(hook.oracle, HashOracle) + self.assertEqual(hook.oracle.vocab_size, 256) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_oracle.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..2d2716d1ab2ef36832d7a12a5445a310c2b688e0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_oracle.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import random +import unittest + +import torch + +from sglang.jit_kernel.kv_canary.consts import splitmix64 +from sglang.srt.kv_canary.token_oracle.oracle import ( + HashOracle, + _splitmix64_tensor, +) +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=60, suite="extra-a-test-1-gpu-small-amd") + + +_U64_MASK: int = (1 << 64) - 1 + + +def _signed_to_unsigned_i64(value: int) -> int: + return value & _U64_MASK + + +def _call(oracle: HashOracle, *, generalized_req_id: int, position: int) -> int: + out = oracle.expected_tokens( + generalized_req_ids=torch.tensor([generalized_req_id], dtype=torch.int64), + positions=torch.tensor([position], dtype=torch.int64), + ) + return int(out.tolist()[0]) + + +class TestHashOracle(CustomTestCase): + def test_hash_oracle_is_deterministic_for_same_inputs(self) -> None: + """Verify HashOracle returns the same token for identical inputs.""" + oracle = HashOracle(vocab_size=32000) + + first = _call(oracle, generalized_req_id=7, position=42) + second = _call(oracle, generalized_req_id=7, position=42) + + self.assertEqual(first, second) + + def test_hash_oracle_output_in_vocab_range(self) -> None: + """Verify HashOracle outputs stay within the configured vocabulary range.""" + vocab_size = 1024 + oracle = HashOracle(vocab_size=vocab_size) + + generalized_req_ids = torch.arange(0, 64, dtype=torch.int64).repeat_interleave( + 64 + ) + positions = torch.arange(0, 64, dtype=torch.int64).repeat(64) + tokens = oracle.expected_tokens( + generalized_req_ids=generalized_req_ids, positions=positions + ).tolist() + + for token in tokens: + self.assertTrue(0 <= token < vocab_size) + + +class TestSplitmix64Tensor(CustomTestCase): + def test_splitmix64_tensor_matches_scalar_ref_on_random_inputs(self) -> None: + """Verify tensor SplitMix64 matches the scalar reference on random inputs.""" + rng = random.Random(0) + num_cases = 1000 + unsigned_inputs: list[int] = [ + rng.randrange(0, 1 << 64) for _ in range(num_cases) + ] + + signed_inputs = [ + value if value < (1 << 63) else value - (1 << 64) + for value in unsigned_inputs + ] + actual = _splitmix64_tensor(torch.tensor(signed_inputs, dtype=torch.int64)) + + actual_unsigned = [_signed_to_unsigned_i64(v) for v in actual.tolist()] + expected_unsigned = [splitmix64(v) for v in unsigned_inputs] + + self.assertEqual(actual_unsigned, expected_unsigned) + + def test_splitmix64_tensor_known_vectors(self) -> None: + """Verify tensor SplitMix64 matches scalar reference values for known inputs.""" + inputs = [0, 1, -1, 1 << 32, (1 << 63) - 1, -(1 << 63)] + expected_unsigned = [splitmix64(_signed_to_unsigned_i64(v)) for v in inputs] + + actual = _splitmix64_tensor(torch.tensor(inputs, dtype=torch.int64)) + actual_unsigned = [_signed_to_unsigned_i64(v) for v in actual.tolist()] + + self.assertEqual(actual_unsigned, expected_unsigned) + + def test_splitmix64_tensor_preserves_shape_and_dtype(self) -> None: + """Verify tensor SplitMix64 preserves input shape and int64 dtype.""" + shape = (3, 4, 5) + rng = torch.Generator().manual_seed(42) + inputs = torch.randint( + low=-(1 << 62), + high=(1 << 62), + size=shape, + dtype=torch.int64, + generator=rng, + ) + + out = _splitmix64_tensor(inputs) + + self.assertEqual(out.shape, inputs.shape) + self.assertEqual(out.dtype, torch.int64) + + def test_splitmix64_tensor_is_deterministic(self) -> None: + """Verify tensor SplitMix64 returns stable values for repeated calls.""" + inputs = torch.tensor([0, 1, 2, 3, 1 << 40, -7], dtype=torch.int64) + + first = _splitmix64_tensor(inputs.clone()).tolist() + second = _splitmix64_tensor(inputs.clone()).tolist() + + self.assertEqual(first, second) + + def test_splitmix64_tensor_is_injective_on_distinct_inputs(self) -> None: + """Verify tensor SplitMix64 maps distinct sampled inputs to distinct outputs.""" + inputs = torch.arange(-1000, 1000, dtype=torch.int64) + + out = _splitmix64_tensor(inputs).tolist() + + self.assertEqual(len(set(out)), len(out)) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_oracle_torch_vs_ref.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_oracle_torch_vs_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..6ddd19438c742773414991ddcc878658c58185e1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_oracle_torch_vs_ref.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import random +import unittest + +import torch + +from sglang.jit_kernel.kv_canary.verify_ref import splitmix64 +from sglang.srt.kv_canary.token_oracle.oracle import HashOracle +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=30, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=30, suite="extra-a-test-1-gpu-small-amd") + + +class TestHashOracleTorchVsRef(CustomTestCase): + def test_hash_oracle_matches_scalar_splitmix64_ref(self) -> None: + """Verify single-item HashOracle calls match the scalar SplitMix64 reference.""" + rng = random.Random(0) + vocab_size = 32000 + num_cases = 1000 + + generalized_req_ids: list[int] = [] + positions: list[int] = [] + for _ in range(num_cases): + generalized_req_ids.append(rng.randrange(0, 1 << 60)) + positions.append(rng.randrange(0, 1 << 60)) + + ref_tokens: list[int] = [ + splitmix64(generalized_req_ids[i] ^ positions[i]) % vocab_size + for i in range(num_cases) + ] + + oracle = HashOracle(vocab_size=vocab_size) + torch_tokens: list[int] = [] + generalized_req_ids_tensor = torch.tensor( + generalized_req_ids, dtype=torch.int64 + ) + positions_tensor = torch.tensor(positions, dtype=torch.int64) + for i in range(num_cases): + out = oracle.expected_tokens( + generalized_req_ids=generalized_req_ids_tensor[i : i + 1], + positions=positions_tensor[i : i + 1], + ) + torch_tokens.append(int(out.tolist()[0])) + + for i in range(num_cases): + self.assertEqual( + torch_tokens[i], + ref_tokens[i], + f"mismatch at case {i}: generalized_req_id={generalized_req_ids[i]} " + f"position={positions[i]}: torch={torch_tokens[i]} ref={ref_tokens[i]}", + ) + + def test_hash_oracle_batched_matches_scalar_splitmix64_ref(self) -> None: + """Verify batched HashOracle calls match the scalar SplitMix64 reference.""" + rng = random.Random(1) + vocab_size = 32000 + num_cases = 1000 + + generalized_req_ids = [rng.randrange(0, 1 << 60) for _ in range(num_cases)] + positions = [rng.randrange(0, 1 << 60) for _ in range(num_cases)] + ref_tokens = [ + splitmix64(generalized_req_ids[i] ^ positions[i]) % vocab_size + for i in range(num_cases) + ] + + oracle = HashOracle(vocab_size=vocab_size) + out = oracle.expected_tokens( + generalized_req_ids=torch.tensor(generalized_req_ids, dtype=torch.int64), + positions=torch.tensor(positions, dtype=torch.int64), + ) + torch_tokens = out.tolist() + + for i in range(num_cases): + self.assertEqual( + torch_tokens[i], + ref_tokens[i], + f"batched mismatch at case {i}: generalized_req_id={generalized_req_ids[i]} " + f"position={positions[i]}: torch={torch_tokens[i]} ref={ref_tokens[i]}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_sampler_hookpoint.py b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_sampler_hookpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..07c1815057faa21e0ca7cd4c345b63f7958c44ae --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/mock_model/test_self_unit_sampler_hookpoint.py @@ -0,0 +1,50 @@ +"""install_oracle_sampler registration into sglang's sampler-backend registry. + +Instantiating the registered _OracleSampler factory requires a live distributed (TP) group +plus a populated global ServerArgs, so the forward-path behavior of _OracleSampler is covered +by the e2e harness rather than this unit file. Here we only assert the registration-side +contract: the backend name shows up in the registry / choice set, and second install replaces +the factory with one bound to the new oracle. +""" + +from __future__ import annotations + +import os +import unittest + +os.environ["SGLANG_KV_CANARY_ENABLE_TOKEN_ORACLE"] = "1" + +from sglang.srt.kv_canary.token_oracle.oracle import HashOracle +from sglang.srt.kv_canary.token_oracle.sampler import install_oracle_sampler +from sglang.srt.layers.sampler import _CUSTOM_SAMPLER_FACTORIES +from sglang.srt.server_args import SAMPLING_BACKEND_CHOICES +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=60, stage="extra-a", runner_config="1-gpu-small") +register_amd_ci(est_time=60, suite="extra-a-test-1-gpu-small-amd") + + +class TestInstallOracleSampler(CustomTestCase): + def test_install_oracle_sampler_twice_returns_distinct_hooks_with_replaced_oracle( + self, + ) -> None: + """Verify reinstalling the oracle sampler replaces the registered factory.""" + oracle_a = HashOracle(vocab_size=100) + oracle_b = HashOracle(vocab_size=100) + + hook_a = install_oracle_sampler(oracle=oracle_a) + self.assertIn("token_oracle", _CUSTOM_SAMPLER_FACTORIES) + self.assertIn("token_oracle", SAMPLING_BACKEND_CHOICES) + factory_a = _CUSTOM_SAMPLER_FACTORIES["token_oracle"] + self.assertIs(hook_a.oracle, oracle_a) + + hook_b = install_oracle_sampler(oracle=oracle_b) + factory_b = _CUSTOM_SAMPLER_FACTORIES["token_oracle"] + self.assertIs(hook_b.oracle, oracle_b) + self.assertIsNot(hook_a, hook_b) + self.assertIsNot(factory_a, factory_b) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/model_loading/test_external_models.py b/asian_ai/performance/SGLang/test/registered/model_loading/test_external_models.py new file mode 100644 index 0000000000000000000000000000000000000000..1f5bba5afa0243594cfb21b40ed5e5deee8e45e6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/model_loading/test_external_models.py @@ -0,0 +1,37 @@ +import unittest + +import sglang as sgl +from sglang.srt.environ import envs +from sglang.test.ci.ci_register import ( + register_amd_ci, + register_cpu_ci, + register_cuda_ci, +) +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=29, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=45, suite="stage-b-test-1-gpu-small-amd") +register_cpu_ci(est_time=203, suite="base-c-test-cpu") + + +class TestExternalModels(CustomTestCase): + def test_external_model(self): + envs.SGLANG_EXTERNAL_MODEL_PACKAGE.set("sglang.test.external_models") + envs.SGLANG_EXTERNAL_MM_PROCESSOR_PACKAGE.set("sglang.test.external_models") + prompt = "Today is a sunny day and I like" + model_path = "Qwen/Qwen2-VL-2B-Instruct" + + engine = sgl.Engine( + model_path=model_path, + cuda_graph_max_bs_decode=1, + max_total_tokens=64, + enable_multimodal=True, + ) + out = engine.generate(prompt)["text"] + engine.shutdown() + + self.assertGreater(len(out), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/model_loading/test_load_weights_from_remote_instance.py b/asian_ai/performance/SGLang/test/registered/model_loading/test_load_weights_from_remote_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..6c3bc1ddc3035e691df7613f4186024237e5b846 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/model_loading/test_load_weights_from_remote_instance.py @@ -0,0 +1,436 @@ +"""Test loading weights from remote instance. + +This test suite simulates loading weights from a remote instance. +Rank 0 represents the seed instance, while ranks 1 represents the +new instance that needs to loading weights from the seed instance. + +Seed instance must be started in `Server` mode, while the dst instance +can be either `Engine` mode or `Server` mode. + +Seed instance does not support concurrently serving multiple dst instances. +User has to guarantee that there is only one dst instance trying to load +weights from the seed instance at any time. + +""" + +import gc +import os +import random +import unittest + +import numpy as np +import requests +import torch +import torch.multiprocessing as mp + +import sglang as sgl +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import ( + DEFAULT_PORT_FOR_SRT_TEST_RUNNER, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, +) +from sglang.utils import terminate_process + +mp.set_start_method("spawn", force=True) + +register_cuda_ci(est_time=145, stage="extra-a", runner_config="2-gpu-large") +register_amd_ci(est_time=72, suite="stage-b-test-2-gpu-large-amd") + + +def verify_params_close(params1, params2, error_msg): + """Verify if two parameter arrays are close enough.""" + try: + assert np.allclose(np.array(params1), np.array(params2)), error_msg + except Exception as e: + print(f"Parameters not close for {error_msg}") + print("Params1:", np.array(params1)) + print("Params2:", np.array(params2)) + raise e + + +def init_process( + rank, + param_queue, + truncate_size, + tp_size, + model_name, + backends, + checking_parameters, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + event_seed_ready, + event_dst_ready_list, + remote_instance_loader_backend, +): + torch.cuda.set_device(rank) + + if rank == 0: + init_process_seed( + rank, + param_queue, + truncate_size, + model_name, + checking_parameters, + tp_size, + event_seed_ready, + event_dst_ready_list, + ) + elif rank in [1, 2]: + init_process_dst( + rank, + param_queue, + truncate_size, + model_name, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + checking_parameters, + backends[rank - 1], + tp_size, + event_seed_ready, + event_dst_ready_list, + remote_instance_loader_backend, + ) + + +def init_process_seed( + rank, + param_queue, + truncate_size, + model_name, + checking_parameters, + tp_size, + event_seed_ready, + event_dst_ready_list, +): + # These two environment variables are very important + # to avoid unexpected behaviors of CUDA and NCCL. + os.environ["NCCL_CUMEM_ENABLE"] = "0" + os.environ["NCCL_NVLS_ENABLE"] = "0" + + # Load model and get parameters + torch.cuda.set_device(rank) + torch.cuda.synchronize() + + url = DEFAULT_URL_FOR_TEST + process = popen_launch_server( + model_name, + url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=( + "--base-gpu-id", + str(rank), + "--tp-size", + str(tp_size), + "--remote-instance-weight-loader-start-seed-via-transfer-engine", + ), + ) + torch.cuda.synchronize() + + seed_params = [] + # Get the weights of seed instance for correctness check. + for parameter_name in checking_parameters: + seed_params.append( + requests.get( + f"{url}/get_weights_by_name", + json={ + "name": parameter_name, + "truncate_size": truncate_size, + }, + ).json() + ) + param_queue.put((f"seed_params", seed_params)) + + event_seed_ready.set() + for i in range(len(event_dst_ready_list)): + event_dst_ready_list[i].wait() + terminate_process(process) + + +def init_process_dst( + rank, + param_queue, + truncate_size, + model_name, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + checking_parameters, + backend, + tp_size, + event_seed_ready, + event_dst_ready_list, + remote_instance_loader_backend, +): + torch.cuda.set_device(rank * tp_size) + torch.cuda.synchronize() + base_gpu_id = rank * tp_size + + event_seed_ready.wait() + print(f"rank {rank}, seed ready") + for i in range(rank - 1): + print(f"rank {rank}, wait dst {i}") + event_dst_ready_list[i].wait() + + ports = [] + for i in range(tp_size): + ports.append(seed_instance_group_base_port + (rank - 1) * tp_size + i) + + if backend == "Engine": + print(f"[sgl] rank {rank} init engine") + engine = sgl.Engine( + model_path=model_name, + base_gpu_id=base_gpu_id, + tp_size=tp_size, + cuda_graph_max_bs_decode=2, + tokenizer_path=model_name, + remote_instance_weight_loader_seed_instance_ip=seed_instance_ip, + remote_instance_weight_loader_seed_instance_service_port=seed_instance_service_port, + remote_instance_weight_loader_send_weights_group_ports=ports, + load_format="remote_instance", + remote_instance_weight_loader_backend=remote_instance_loader_backend, + remote_instance_weight_loader_start_seed_via_transfer_engine=False, + ) + else: + host, _, port = DEFAULT_URL_FOR_TEST.rpartition(":") + url = ":".join([host, str(int(port) + 10000 + rank)]) + + print(f"[sgl] rank {rank} init server on url: {url}") + process = popen_launch_server( + model_name, + url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=( + "--base-gpu-id", + str(base_gpu_id), + "--tp-size", + str(tp_size), + "--cuda-graph-max-bs-decode", + 2, + "--tokenizer-path", + model_name, + "--remote-instance-weight-loader-seed-instance-ip", + seed_instance_ip, + "--remote-instance-weight-loader-seed-instance-service-port", + seed_instance_service_port, + "--remote-instance-weight-loader-send-weights-group-ports", + f"[{','.join(str(port) for port in ports)}]", + "--load-format", + "remote_instance", + "--remote-instance-weight-loader-backend", + remote_instance_loader_backend, + "--remote-instance-weight-loader-start-seed-via-transfer-engine", + "--engine-info-bootstrap-port", + str(6789 + rank), + ), + ) + torch.cuda.synchronize() + + event_dst_ready_list[rank - 1].set() + + # Get weights of destination instance loaded from remote instance. + dst_params = [] + for parameter_name in checking_parameters: + dst_params.append( + engine.get_weights_by_name(parameter_name, truncate_size) + if backend == "Engine" + else requests.get( + f"{url}/get_weights_by_name", + json={"name": parameter_name, "truncate_size": truncate_size}, + ).json() + ) + + param_queue.put((f"sgl_dp_{rank}_dst_params", dst_params)) + + # Shutdown the engine or terminate the server process. + if backend == "Engine": + engine.shutdown() + else: + terminate_process(process) + + +def test_load_weights_from_remote_instance( + tp_size, + dp_size, + model_name, + backends, + truncate_size, + checking_parameters, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + remote_instance_loader_backend, +): + print( + f"Testing model: {model_name} tp_size: {tp_size}, dp_size: {dp_size} backend: {backends} remote_instance_loader_backend: {remote_instance_loader_backend}" + ) + param_queue = mp.Queue() + results = {} + event_seed_ready = mp.Event() + event_dst_ready_list = [] + for i in range(dp_size): + event_dst_ready = mp.Event() + event_dst_ready_list.append(event_dst_ready) + + context = mp.spawn( + init_process, + args=( + param_queue, + truncate_size, + tp_size, + model_name, + backends, + checking_parameters, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + event_seed_ready, + event_dst_ready_list, + remote_instance_loader_backend, + ), + nprocs=1 + dp_size, + join=False, + ) + + while len(results) < (1 + dp_size): + try: + key, value = param_queue.get(timeout=5) + results[key] = value + except Exception: + if all(not p.is_alive() for p in context.processes): + break + + context.join() + + if len(results) != (1 + dp_size): + raise RuntimeError( + f"Expected {(1 + dp_size)} parameters but got {len(results)}" + ) + + params = { + "seed": results.get("seed_params"), + "sgl_dp_1_dest": results.get("sgl_dp_1_dst_params"), + } + + if dp_size == 2: + dp2_params = { + "sgl_dp_2_dest": results.get("sgl_dp_2_dst_params"), + } + assert all(v is not None for v in dp2_params.values()) + params.update(dp2_params) + + # Check the correctness of weights loaded from remote instance + # by verifying the weights of seed instance and destination instance. + for i in range(len(params["seed"])): + verify_params_close( + params["seed"][i], + params["sgl_dp_1_dest"][i], + f"sgl_dp_1_dst_params rank {i}", + ) + + if dp_size == 2: + verify_params_close( + params["seed"][i], + params["sgl_dp_2_dest"][i], + f"sgl_dp_2_dst_params rank {i}", + ) + + # Delete the context and close the parameter queue. + del context + param_queue.close() + param_queue.join_thread() + gc.collect() + torch.cuda.empty_cache() + + +class TestLoadWeightsFromRemoteInstance(CustomTestCase): + + def test_load_weights_from_remote_instance(self): + + assert torch.cuda.device_count() >= 2, "At least 2 GPUs are required" + # test_suits : tp, dp, model_name, backend, dst_instance_id + if is_in_ci(): + # FIXME: refactor this test to have less random behavior + mode = random.choice(["Engine", "Server"]) + remote_instance_loader_backend = random.choice(["nccl", "transfer_engine"]) + test_suits = [ + ( + 1, + 1, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + [mode], + remote_instance_loader_backend, + ), + ] + else: + test_suits = [ + (1, 1, DEFAULT_SMALL_MODEL_NAME_FOR_TEST, ["Engine"], "nccl"), + (1, 1, DEFAULT_SMALL_MODEL_NAME_FOR_TEST, ["Server"], "nccl"), + (2, 2, DEFAULT_SMALL_MODEL_NAME_FOR_TEST, ["Engine", "Server"], "nccl"), + ( + 1, + 1, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + ["Engine"], + "transfer_engine", + ), + ( + 1, + 1, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + ["Server"], + "transfer_engine", + ), + ( + 2, + 2, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + ["Engine", "Server"], + "transfer_engine", + ), + ] + + truncate_size = 10 + checking_parameters = [ + "model.embed_tokens.weight", + "model.layers.0.input_layernorm.weight", + "model.layers.1.self_attn.q_proj.weight", + "model.layers.2.self_attn.k_proj.weight", + "model.layers.3.self_attn.v_proj.weight", + "model.layers.4.self_attn.o_proj.weight", + "model.layers.5.mlp.gate_proj.weight", + "model.layers.6.mlp.up_proj.weight", + "model.layers.7.mlp.down_proj.weight", + "model.layers.8.post_attention_layernorm.weight", + "model.norm.weight", + ] + + for ( + tp_size, + dp_size, + model_name, + backends, + remote_instance_loader_backend, + ) in test_suits: + test_load_weights_from_remote_instance( + tp_size, + dp_size, + model_name, + backends, + truncate_size, + checking_parameters, + "127.0.0.1", + DEFAULT_PORT_FOR_SRT_TEST_RUNNER + 1000, + 60000, + remote_instance_loader_backend, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/model_loading/test_load_weights_from_remote_instance_npu.py b/asian_ai/performance/SGLang/test/registered/model_loading/test_load_weights_from_remote_instance_npu.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff9acda49e8dca6856a2360ca3eb88eb2782ebe --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/model_loading/test_load_weights_from_remote_instance_npu.py @@ -0,0 +1,443 @@ +"""Test loading weights from remote instance. + +This test suite simulates loading weights from a remote instance. +Rank 0 represents the seed instance, while ranks 1 represents the +new instance that needs to loading weights from the seed instance. + +Seed instance must be started in `Server` mode, while the dst instance +can be either `Engine` mode or `Server` mode. + +Seed instance does not support concurrently serving multiple dst instances. +User has to guarantee that there is only one dst instance trying to load +weights from the seed instance at any time. + +""" + +import gc +import os +import random +import unittest + +import numpy as np +import requests +import torch +import torch.multiprocessing as mp + +import sglang as sgl +from sglang.test.ci.ci_register import register_npu_ci +from sglang.test.test_utils import ( + DEFAULT_PORT_FOR_SRT_TEST_RUNNER, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, +) +from sglang.utils import terminate_process + +mp.set_start_method("spawn", force=True) + +register_npu_ci( + est_time=400, + suite="nightly-1-npu-a3", + nightly=True, + disabled="run failed", +) + + +def verify_params_close(params1, params2, error_msg): + """Verify if two parameter arrays are close enough.""" + try: + assert np.allclose(np.array(params1), np.array(params2)), error_msg + except Exception as e: + print(f"Parameters not close for {error_msg}") + print("Params1:", np.array(params1)) + print("Params2:", np.array(params2)) + raise e + + +def init_process( + rank, + param_queue, + truncate_size, + tp_size, + model_name, + backends, + checking_parameters, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + event_seed_ready, + event_dst_ready_list, + remote_instance_loader_backend, +): + torch.npu.set_device(rank) + + if rank == 0: + init_process_seed( + rank, + param_queue, + truncate_size, + model_name, + checking_parameters, + tp_size, + event_seed_ready, + event_dst_ready_list, + ) + elif rank in [1, 2]: + init_process_dst( + rank, + param_queue, + truncate_size, + model_name, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + checking_parameters, + backends[rank - 1], + tp_size, + event_seed_ready, + event_dst_ready_list, + remote_instance_loader_backend, + ) + + +def init_process_seed( + rank, + param_queue, + truncate_size, + model_name, + checking_parameters, + tp_size, + event_seed_ready, + event_dst_ready_list, +): + # These two environment variables are very important + # to avoid unexpected behaviors of npu and NCCL. + os.environ["NCCL_CUMEM_ENABLE"] = "0" + os.environ["NCCL_NVLS_ENABLE"] = "0" + + # Load model and get parameters + torch.npu.set_device(rank) + torch.npu.synchronize() + + url = DEFAULT_URL_FOR_TEST + process = popen_launch_server( + model_name, + url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=( + "--attention-backend", + "ascend", + "--device", + "npu", + "--base-gpu-id", + str(rank), + "--tp-size", + str(tp_size), + ), + ) + torch.npu.synchronize() + + seed_params = [] + # Get the weights of seed instance for correctness check. + for parameter_name in checking_parameters: + seed_params.append( + requests.get( + f"{url}/get_weights_by_name", + json={ + "name": parameter_name, + "truncate_size": truncate_size, + }, + ).json() + ) + param_queue.put((f"seed_params", seed_params)) + + event_seed_ready.set() + for i in range(len(event_dst_ready_list)): + event_dst_ready_list[i].wait() + terminate_process(process) + + +def init_process_dst( + rank, + param_queue, + truncate_size, + model_name, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + checking_parameters, + backend, + tp_size, + event_seed_ready, + event_dst_ready_list, + remote_instance_loader_backend, +): + torch.npu.set_device(rank * tp_size) + torch.npu.synchronize() + base_gpu_id = rank * tp_size + + event_seed_ready.wait() + print(f"rank {rank}, seed ready") + for i in range(rank - 1): + print(f"rank {rank}, wait dst {i}") + event_dst_ready_list[i].wait() + + ports = [] + for i in range(tp_size): + ports.append(seed_instance_group_base_port + (rank - 1) * tp_size + i) + + if backend == "Engine": + print(f"[sgl] rank {rank} init engine") + engine = sgl.Engine( + attention_backend="ascend", + device="npu", + model_path=model_name, + base_gpu_id=base_gpu_id, + tp_size=tp_size, + cuda_graph_max_bs_decode=2, + tokenizer_path=model_name, + remote_instance_weight_loader_seed_instance_ip=seed_instance_ip, + remote_instance_weight_loader_seed_instance_service_port=seed_instance_service_port, + remote_instance_weight_loader_send_weights_group_ports=ports, + load_format="remote_instance", + remote_instance_weight_loader_backend=remote_instance_loader_backend, + ) + else: + host, _, port = DEFAULT_URL_FOR_TEST.rpartition(":") + url = ":".join([host, str(int(port) + 10000 + rank)]) + + print(f"[sgl] rank {rank} init server on url: {url}") + process = popen_launch_server( + model_name, + url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=( + "--attention-backend", + "--device", + "npu", + "--base-gpu-id", + str(base_gpu_id), + "--tp-size", + str(tp_size), + "--cuda-graph-max-bs-decode", + 2, + "--tokenizer-path", + model_name, + "--remote-instance-weight-loader-seed-instance-ip", + seed_instance_ip, + "--remote-instance-weight-loader-seed-instance-service-port", + seed_instance_service_port, + "--remote-instance-weight-loader-send-weights-group-ports", + f"[{','.join(str(port) for port in ports)}]", + "--load-format", + "remote_instance", + "--remote-instance-weight-loader-backend", + remote_instance_loader_backend, + ), + ) + torch.npu.synchronize() + + event_dst_ready_list[rank - 1].set() + + # Get weights of destination instance loaded from remote instance. + dst_params = [] + for parameter_name in checking_parameters: + dst_params.append( + engine.get_weights_by_name(parameter_name, truncate_size) + if backend == "Engine" + else requests.get( + f"{url}/get_weights_by_name", + json={"name": parameter_name, "truncate_size": truncate_size}, + ).json() + ) + + param_queue.put((f"sgl_dp_{rank}_dst_params", dst_params)) + + # Shutdown the engine or terminate the server process. + if backend == "Engine": + engine.shutdown() + else: + terminate_process(process) + + +def test_load_weights_from_remote_instance( + tp_size, + dp_size, + model_name, + backends, + truncate_size, + checking_parameters, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + remote_instance_loader_backend, +): + print( + f"Testing model: {model_name} tp_size: {tp_size}, dp_size: {dp_size} backend: {backends} remote_instance_loader_backend: {remote_instance_loader_backend}" + ) + param_queue = mp.Queue() + results = {} + event_seed_ready = mp.Event() + event_dst_ready_list = [] + for i in range(dp_size): + event_dst_ready = mp.Event() + event_dst_ready_list.append(event_dst_ready) + + context = mp.spawn( + init_process, + args=( + param_queue, + truncate_size, + tp_size, + model_name, + backends, + checking_parameters, + seed_instance_ip, + seed_instance_service_port, + seed_instance_group_base_port, + event_seed_ready, + event_dst_ready_list, + remote_instance_loader_backend, + ), + nprocs=1 + dp_size, + join=False, + ) + + while len(results) < (1 + dp_size): + try: + key, value = param_queue.get(timeout=5) + results[key] = value + except Exception: + if all(not p.is_alive() for p in context.processes): + break + + context.join() + + if len(results) != (1 + dp_size): + raise RuntimeError( + f"Expected {(1 + dp_size)} parameters but got {len(results)}" + ) + + params = { + "seed": results.get("seed_params"), + "sgl_dp_1_dest": results.get("sgl_dp_1_dst_params"), + } + + if dp_size == 2: + dp2_params = { + "sgl_dp_2_dest": results.get("sgl_dp_2_dst_params"), + } + assert all(v is not None for v in dp2_params.values()) + params.update(dp2_params) + + # Check the correctness of weights loaded from remote instance + # by verifying the weights of seed instance and destination instance. + for i in range(len(params["seed"])): + verify_params_close( + params["seed"][i], + params["sgl_dp_1_dest"][i], + f"sgl_dp_1_dst_params rank {i}", + ) + + if dp_size == 2: + verify_params_close( + params["seed"][i], + params["sgl_dp_2_dest"][i], + f"sgl_dp_2_dst_params rank {i}", + ) + + # Delete the context and close the parameter queue. + del context + param_queue.close() + param_queue.join_thread() + gc.collect() + torch.npu.empty_cache() + + +class TestLoadWeightsFromRemoteInstance(CustomTestCase): + + def test_load_weights_from_remote_instance(self): + + assert torch.npu.device_count() >= 2, "At least 2 GPUs are required" + # test_suits : tp, dp, model_name, backend, dst_instance_id + if is_in_ci(): + mode = random.choice(["Engine", "Server"]) + remote_instance_loader_backend = random.choice(["nccl", "nccl"]) + test_suits = [ + ( + 1, + 1, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + [mode], + remote_instance_loader_backend, + ), + ] + else: + test_suits = [ + (1, 1, DEFAULT_SMALL_MODEL_NAME_FOR_TEST, ["Server"], "nccl"), + (1, 1, DEFAULT_SMALL_MODEL_NAME_FOR_TEST, ["Server"], "nccl"), + (2, 2, DEFAULT_SMALL_MODEL_NAME_FOR_TEST, ["Server", "Server"], "nccl"), + ( + 1, + 1, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + ["Server"], + "nccl", + ), + ( + 1, + 1, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + ["Server"], + "nccl", + ), + ( + 2, + 2, + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + ["Server", "Server"], + "nccl", + ), + ] + + truncate_size = 10 + checking_parameters = [ + "model.embed_tokens.weight", + "model.layers.0.input_layernorm.weight", + "model.layers.1.self_attn.q_proj.weight", + "model.layers.2.self_attn.k_proj.weight", + "model.layers.3.self_attn.v_proj.weight", + "model.layers.4.self_attn.o_proj.weight", + "model.layers.5.mlp.gate_proj.weight", + "model.layers.6.mlp.up_proj.weight", + "model.layers.7.mlp.down_proj.weight", + "model.layers.8.post_attention_layernorm.weight", + "model.norm.weight", + ] + + for ( + tp_size, + dp_size, + model_name, + backends, + remote_instance_loader_backend, + ) in test_suits: + test_load_weights_from_remote_instance( + tp_size, + dp_size, + model_name, + backends, + truncate_size, + checking_parameters, + "127.0.0.1", + DEFAULT_PORT_FOR_SRT_TEST_RUNNER + 1000, + 60010, + remote_instance_loader_backend, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/model_loading/test_prefetch_checkpoints_multi_gpu.py b/asian_ai/performance/SGLang/test/registered/model_loading/test_prefetch_checkpoints_multi_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..6526b4e59de30f7b49fa6f78eb5fbcb9c5b37ff1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/model_loading/test_prefetch_checkpoints_multi_gpu.py @@ -0,0 +1,49 @@ +import unittest + +import sglang as sgl +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=300, suite="nightly-4-gpu") + +PROMPTS = [ + "Hello, my name is", + "The president of the United States is", + "The capital of France is", + "The future of AI is", +] + + +class TestPrefetchCheckpointsMultiGPU(CustomTestCase): + """Verify that --weight-loader-prefetch-checkpoints works with DP attention.""" + + @classmethod + def setUpClass(cls): + cls.engine = sgl.Engine( + model_path="Qwen/Qwen1.5-MoE-A2.7B-Chat", + tp_size=4, + dp_size=4, + enable_dp_attention=True, + disable_radix_cache=True, + weight_loader_prefetch_checkpoints=True, + cuda_graph_max_bs_decode=1, + max_total_tokens=256, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "engine") and cls.engine: + cls.engine.shutdown() + + def test_generate_with_prefetch(self): + """Server launched with prefetch must produce valid output.""" + outputs = self.engine.generate(PROMPTS) + self.assertEqual(len(outputs), len(PROMPTS)) + for i, output in enumerate(outputs): + text = output["text"] + self.assertIsInstance(text, str) + self.assertGreater(len(text), 0, f"Prompt {i} produced empty output") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/model_loading/test_runai_model_loader.py b/asian_ai/performance/SGLang/test/registered/model_loading/test_runai_model_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..402df925e034de1d88e2fb4c0b8156884b612beb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/model_loading/test_runai_model_loader.py @@ -0,0 +1,50 @@ +import unittest + +import sglang as sgl +from sglang.srt.environ import temp_set_env +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=380, suite="nightly-1-gpu", nightly=True) + +TEST_GCS_MODEL = "gs://vertex-model-garden-public-us/codegemma/codegemma-2b/" + +PROMPTS = [ + "Hello, my name is", + "The president of the United States is", + "The capital of France is", + "The future of AI is", +] + + +class TestRunaiModelLoader(CustomTestCase): + @classmethod + def setUpClass(cls): + with temp_set_env( + GOOGLE_CLOUD_PROJECT="fake-project", + RUNAI_STREAMER_GCS_USE_ANONYMOUS_CREDENTIALS="true", + CLOUD_STORAGE_EMULATOR_ENDPOINT="https://storage.googleapis.com", + ): + cls.engine = sgl.Engine( + model_path=TEST_GCS_MODEL, + load_format="runai_streamer", + cuda_graph_max_bs_decode=1, + max_total_tokens=64, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "engine") and cls.engine: + cls.engine.shutdown() + + def test_generate_produces_output(self): + outputs = self.engine.generate(PROMPTS) + self.assertEqual(len(outputs), len(PROMPTS)) + for i, output in enumerate(outputs): + text = output["text"] + self.assertIsInstance(text, str) + self.assertGreater(len(text), 0, f"Prompt {i} produced empty output") + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/model_loading/test_utils_update_weights.py b/asian_ai/performance/SGLang/test/registered/model_loading/test_utils_update_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb256010dc995426e259dcd634d986c2b4ed104 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/model_loading/test_utils_update_weights.py @@ -0,0 +1,173 @@ +import asyncio +import os +import unittest + +import torch +import torch.distributed as dist +from torch.distributed.device_mesh import init_device_mesh +from transformers import AutoModelForCausalLM + +from sglang.srt.entrypoints.engine import Engine +from sglang.srt.weight_sync.utils import update_weights +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST + +register_cuda_ci(est_time=32, stage="base-b", runner_config="1-gpu-large") + + +class AsyncEngine(Engine): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + async def update_weights_from_tensor(self, update_weights_request): + return await self.tokenizer_manager.update_weights_from_tensor( + update_weights_request, None + ) + + +def is_distributed_available(): + """Check if distributed training environment is available""" + required_vars = ["RANK", "WORLD_SIZE", "MASTER_ADDR", "MASTER_PORT"] + return all(var in os.environ for var in required_vars) + + +def setup_single_process_distributed(): + """Setup distributed environment for single process testing""" + if not is_distributed_available(): + os.environ["RANK"] = "0" + os.environ["WORLD_SIZE"] = "1" + os.environ["MASTER_ADDR"] = "localhost" + os.environ["MASTER_PORT"] = "12356" + os.environ["LOCAL_RANK"] = "0" + + +class TestUtilsUpdateWeights(unittest.TestCase): + """Test class for utils.update_weights function""" + + @classmethod + def setUpClass(cls): + """Setup distributed environment and test fixtures for the entire test class""" + cls.setup_distributed() + cls.setup_test_engine() + cls.setup_test_model() + cls.setup_device_mesh() + + @classmethod + def tearDownClass(cls): + """Cleanup after all tests""" + if hasattr(cls, "engine") and cls.engine: + cls.engine.shutdown() + + # Cleanup distributed + if dist.is_initialized(): + dist.destroy_process_group() + + @classmethod + def setup_distributed(cls): + """Setup distributed environment for testing""" + setup_single_process_distributed() + + if not dist.is_initialized(): + try: + dist.init_process_group( + backend="nccl" if torch.cuda.is_available() else "gloo" + ) + except Exception as e: + raise unittest.SkipTest( + f"Could not initialize distributed backend: {e}" + ) + + cls.rank = dist.get_rank() + cls.world_size = dist.get_world_size() + + if torch.cuda.is_available(): + torch.cuda.set_device(cls.rank % torch.cuda.device_count()) + + # Set up environment variables + os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" + os.environ["NCCL_CUMEM_ENABLE"] = "0" + os.environ["CUDA_DEVICE_MAX_CONNECTIONS"] = "4" + os.environ["CUDA_MODULE_LOADING"] = "AUTO" + + @classmethod + def setup_test_engine(cls): + """Setup test engine""" + if cls.rank == 0: + cls.engine = AsyncEngine( + model_path=DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + dtype="bfloat16", + mem_fraction_static=0.3, + enable_memory_saver=True, + tp_size=cls.world_size, + disable_cuda_graph=False, + ) + else: + cls.engine = None + + @classmethod + def setup_test_model(cls): + """Load test model""" + try: + cls.model = AutoModelForCausalLM.from_pretrained( + DEFAULT_SMALL_MODEL_NAME_FOR_TEST, + device_map="cpu", + trust_remote_code=True, + low_cpu_mem_usage=True, + torch_dtype=( + torch.float16 if torch.cuda.is_available() else torch.float32 + ), + ) + except Exception as e: + raise unittest.SkipTest(f"Could not load test model: {e}") + + @classmethod + def setup_device_mesh(cls): + """Create device mesh for testing""" + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA not available for device mesh") + + cls.device_mesh_key = "tp" + cls.mesh = init_device_mesh( + "cuda", (cls.world_size,), mesh_dim_names=(cls.device_mesh_key,) + ) + + def create_test_params_batch(self, model, num_params=64): + """Create a batch of test parameters from the model""" + param_names = [] + test_tensors = [] + + # Get first few parameters from the model for testing + for i, (name, tensor) in enumerate(model.named_parameters()): + if i >= num_params: + break + param_names.append(name) + # Create test tensor with known values, matching original shape and dtype + test_tensor = torch.full_like(tensor, 1.5, dtype=tensor.dtype).cuda() + test_tensors.append(test_tensor) + + return list(zip(param_names, test_tensors)) + + def test_utils_update_weights(self): + """Test basic functionality of utils.update_weights""" + + async def async_test(): + # Create test parameters batch + params_batch = self.create_test_params_batch(self.model, num_params=2) + + # Test the utils.update_weights function + result = await update_weights( + engine=self.engine, + params_batch=params_batch, + device_mesh_key=self.device_mesh_key, + device_mesh=self.mesh, + load_format=None, + ) + + self.assertIn("Success", result) + + # Run the async test + asyncio.run(async_test()) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models/test_compressed_tensors_models.py b/asian_ai/performance/SGLang/test/registered/models/test_compressed_tensors_models.py new file mode 100644 index 0000000000000000000000000000000000000000..270af4b61bf567f9f82394109d854ff8f8fb9f7d --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models/test_compressed_tensors_models.py @@ -0,0 +1,56 @@ +# Model tests for compressed tensors (FP8) + +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import is_hip, kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=65, stage="extra-a", runner_config="1-gpu-large") +register_amd_ci(est_time=42, suite="stage-b-test-1-gpu-small-amd") + + +class TestCompressedTensorsLlama3FP8(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "RedHatAI/Meta-Llama-3.1-8B-FP8" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + if is_hip(): + # Lower threshold for AMD because FP8 dtype differs (fp8_fnuz) + self.assertGreaterEqual(metrics["score"], 0.40) + else: + self.assertGreaterEqual(metrics["score"], 0.45) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models/test_generation_models.py b/asian_ai/performance/SGLang/test/registered/models/test_generation_models.py new file mode 100644 index 0000000000000000000000000000000000000000..62394651a31850d2230e21c54875d86f46d15e80 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models/test_generation_models.py @@ -0,0 +1,223 @@ +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci + +# Generation model tests (CUDA only) +register_cuda_ci(est_time=150, stage="extra-a", runner_config="1-gpu-large") +register_amd_ci(est_time=106, suite="stage-b-test-1-gpu-small-amd") + +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +""" +Usage: + +To test a specific model locally: +1. Add it to ALL_MODELS, for example, `ModelCase("Qwen/Qwen2-1.5B")` +2. Run `ONLY_RUN=Qwen/Qwen2-1.5B python3 -m unittest test_generation_models.TestGenerationModels` +""" + +import dataclasses +import multiprocessing as mp +import os +import unittest +from contextlib import nullcontext +from typing import List, Optional + +import torch + +from sglang.srt.environ import envs +from sglang.srt.utils import is_hip +from sglang.test.runners import ( + DEFAULT_PROMPTS, + HFRunner, + SRTRunner, + check_close_model_outputs, +) +from sglang.test.test_utils import CustomTestCase, is_in_ci + + +@dataclasses.dataclass +class ModelCase: + model_path: str + tp_size: int = 1 + prefill_tolerance: float = 5e-2 + decode_tolerance: float = 6e-2 # Increased to fix numerical error in issue #8614. + rouge_l_tolerance: float = 1 + skip_long_prompt: bool = False + trust_remote_code: bool = False + attention_backend: Optional[str] = None + + +# Popular models that run on the CI +CI_MODELS = [ + ModelCase("meta-llama/Llama-3.1-8B-Instruct"), + ModelCase("google/gemma-2-2b", attention_backend="triton" if is_hip() else None), +] + +# the complete set of models to test sglang's generation model +ALL_MODELS = [ + *CI_MODELS, + ModelCase("Qwen/Qwen2-1.5B", decode_tolerance=7e-2), + ModelCase("Qwen/Qwen2.5-14B-Instruct"), + ModelCase("HuggingFaceTB/SmolLM-135M-Instruct", skip_long_prompt=True), + ModelCase("allenai/OLMo-1B-0724-hf", decode_tolerance=8e-2, skip_long_prompt=True), + ModelCase("shanearora/2025-sep-a-base-model"), + ModelCase( + "THUDM/glm-4-9b-chat", tp_size=2, trust_remote_code=True, skip_long_prompt=True + ), + ModelCase("openai-community/gpt2"), + ModelCase("microsoft/phi-1_5", trust_remote_code=True), + ModelCase("adept/persimmon-8b-chat"), + ModelCase("upstage/SOLAR-10.7B-Instruct-v1.0"), + ModelCase("inclusionAI/Ling-lite", trust_remote_code=True), + ModelCase("microsoft/Phi-3-small-8k-instruct", trust_remote_code=True), + ModelCase("allenai/OLMo-2-1124-7B-Instruct", skip_long_prompt=True), + ModelCase("ibm-granite/granite-3.0-2b-instruct", skip_long_prompt=True), + ModelCase( + "microsoft/Phi-3.5-MoE-instruct", + tp_size=2, + trust_remote_code=True, + skip_long_prompt=True, + ), + ModelCase("facebook/opt-125m", skip_long_prompt=True), + ModelCase( + "nvidia/Llama-3_3-Nemotron-Super-49B-v1_5", + tp_size=2, + trust_remote_code=True, + skip_long_prompt=True, + ), + ModelCase( + "nvidia/Llama-3_1-Nemotron-Ultra-253B-v1", + tp_size=8, + trust_remote_code=True, + skip_long_prompt=True, + ), + ModelCase( + "nvidia/NVIDIA-Nemotron-Nano-9B-v2", + trust_remote_code=True, + skip_long_prompt=True, + ), + ModelCase( + "swiss-ai/Apertus-8B", + trust_remote_code=True, + skip_long_prompt=True, + ), + ModelCase( + "LiquidAI/LFM2.5-1.2B-Instruct", + trust_remote_code=True, + ), + ModelCase( + "ibm-granite/granite-4.0-h-micro", + trust_remote_code=True, + ), +] + +MAMBA_MODEL_PATHS = [ + "LiquidAI/LFM2.5-1.2B-Instruct", +] + +TORCH_DTYPES = [torch.float16] + + +class TestGenerationModels(CustomTestCase): + + @classmethod + def setUpClass(cls): + mp.set_start_method("spawn", force=True) + + def assert_close_logits_and_output_strs( + self, + prompts: List[str], + model_case: ModelCase, + torch_dtype: torch.dtype, + ) -> None: + model_path = model_case.model_path + max_new_tokens = 32 + + # Set conv dtype for hybrid models to match inference dtype + dtype_str = {torch.float16: "float16", torch.bfloat16: "bfloat16"}.get( + torch_dtype, "bfloat16" + ) + + if model_case.model_path in MAMBA_MODEL_PATHS: + env_ctx = envs.SGLANG_MAMBA_CONV_DTYPE.override(dtype_str) + else: + env_ctx = nullcontext() + + with HFRunner( + model_path, + torch_dtype=torch_dtype, + model_type="generation", + trust_remote_code=model_case.trust_remote_code, + ) as hf_runner: + hf_outputs = hf_runner.forward(prompts, max_new_tokens=max_new_tokens) + + with ( + env_ctx, + SRTRunner( + model_path, + tp_size=model_case.tp_size, + torch_dtype=torch_dtype, + model_type="generation", + trust_remote_code=model_case.trust_remote_code, + attention_backend=model_case.attention_backend, + ) as srt_runner, + ): + srt_outputs = srt_runner.forward(prompts, max_new_tokens=max_new_tokens) + + check_close_model_outputs( + hf_outputs=hf_outputs, + srt_outputs=srt_outputs, + prefill_tolerance=model_case.prefill_tolerance, + decode_tolerance=model_case.decode_tolerance, + rouge_l_tolerance=model_case.rouge_l_tolerance, + debug_text=f"model_path={model_path} prompts={prompts}", + ) + + @unittest.skipIf(not is_in_ci(), "Local test should run all models") + def test_ci_models(self): + for model_case in CI_MODELS: + for torch_dtype in TORCH_DTYPES: + prompts = DEFAULT_PROMPTS + + # Skip long prompts for models that do not have a long context + if model_case.skip_long_prompt: + prompts = [p for p in DEFAULT_PROMPTS if len(p) < 1000] + + # Assert the logits and output strs are close + self.assert_close_logits_and_output_strs( + prompts, model_case, torch_dtype + ) + + @unittest.skipIf(is_in_ci(), "CI only runs selected models for simplicity") + def test_all_models(self): + for model_case in ALL_MODELS: + for torch_dtype in TORCH_DTYPES: + if ( + "ONLY_RUN" in os.environ + and os.environ["ONLY_RUN"] != model_case.model_path + ): + continue + + # Skip long prompts for models that do not have a long context + prompts = DEFAULT_PROMPTS + if model_case.skip_long_prompt: + prompts = [p for p in DEFAULT_PROMPTS if len(p) < 1000] + + # Assert the logits and output strs are close + self.assert_close_logits_and_output_strs( + prompts, model_case, torch_dtype + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models/test_transformers_backend_eval.py b/asian_ai/performance/SGLang/test/registered/models/test_transformers_backend_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..c6d10a6fa7c856e2e8eb88e6b22317fc5dac9355 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models/test_transformers_backend_eval.py @@ -0,0 +1,49 @@ +"""A small end-to-end eval coverage for the transformers modeling backend.""" + +import unittest +from types import SimpleNamespace + +from sglang.test.ci.ci_register import ( + register_amd_ci, + register_cpu_ci, + register_cuda_ci, +) +from sglang.test.few_shot_gsm8k import run_eval +from sglang.test.server_fixtures.default_fixture import DefaultServerBase + +register_cuda_ci(est_time=48, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=48, suite="stage-b-test-1-gpu-small-amd") +register_cpu_ci(est_time=320, suite="base-c-test-cpu") + + +class TestTransformersBackendEval(DefaultServerBase): + model = "HuggingFaceTB/SmolLM3-3B" + gsm8k_num_questions = 30 + gsm8k_accuracy_thres = 0.5 + gsm8k_parallel = 30 + other_args = [ + "--model-impl", + "transformers", + "--enable-torch-compile", + "--torch-compile-max-bs", + "4", + "--disable-cuda-graph", + ] + + def test_gsm8k(self): + args = SimpleNamespace( + num_shots=5, + data_path=None, + num_questions=self.gsm8k_num_questions, + max_new_tokens=512, + parallel=self.gsm8k_parallel, + host="127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreaterEqual(metrics["accuracy"], self.gsm8k_accuracy_thres) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models/test_transformers_models.py b/asian_ai/performance/SGLang/test/registered/models/test_transformers_models.py new file mode 100644 index 0000000000000000000000000000000000000000..93fbff908a2fc897aabac44c6986cf57ac40aae8 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models/test_transformers_models.py @@ -0,0 +1,161 @@ +# Transformers fallback model tests + +import dataclasses +import multiprocessing as mp +import unittest +from types import SimpleNamespace +from typing import List + +import torch + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.runners import DEFAULT_PROMPTS, SRTRunner, check_close_model_outputs +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, +) + +register_cuda_ci(est_time=177, stage="base-b", runner_config="1-gpu-small") +register_amd_ci(est_time=320, suite="stage-b-test-1-gpu-small-amd") + + +class TestTransformersFallbackEndpoint(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=["--model-impl", "transformers"], + ) + cls.mmlu_lower_bound = 0.63 + cls.gsm8k_lower_bound = 0.65 + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + metrics = run_eval(args) + self.assertGreaterEqual(metrics["score"], self.mmlu_lower_bound) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], self.gsm8k_lower_bound) + + +@dataclasses.dataclass +class ModelCase: + model_path: str + tp_size: int = 1 + prefill_tolerance: float = 5e-2 + decode_tolerance: float = 5e-2 + rouge_l_tolerance: float = 1 + skip_long_prompt: bool = False + trust_remote_code: bool = False + torch_dtype: torch.dtype = torch.float16 + + +# Popular models that run on the CI +CI_MODELS = [ + ModelCase(DEFAULT_MODEL_NAME_FOR_TEST), +] + +ALL_OTHER_MODELS = [ + ModelCase(DEFAULT_MODEL_NAME_FOR_TEST, tp_size=2), +] + + +class TestTransformersFallbackEngine(CustomTestCase): + @classmethod + def setUpClass(cls): + mp.set_start_method("spawn", force=True) + + def assert_close_logits_and_output_strs( + self, + prompts: List[str], + model_case: ModelCase, + ) -> None: + model_path = model_case.model_path + max_new_tokens = 32 + # force to use transformers impl + with SRTRunner( + model_path, + tp_size=model_case.tp_size, + torch_dtype=model_case.torch_dtype, + model_type="generation", + model_impl="transformers", + trust_remote_code=model_case.trust_remote_code, + ) as srt_runner: + srt_outputs = srt_runner.forward(prompts, max_new_tokens=max_new_tokens) + + with SRTRunner( + model_path, + tp_size=model_case.tp_size, + torch_dtype=model_case.torch_dtype, + model_type="generation", + trust_remote_code=model_case.trust_remote_code, + ) as srt_runner: + srt_transformers_outputs = srt_runner.forward( + prompts, max_new_tokens=max_new_tokens + ) + + check_close_model_outputs( + hf_outputs=srt_transformers_outputs, + srt_outputs=srt_outputs, + prefill_tolerance=model_case.prefill_tolerance, + decode_tolerance=model_case.decode_tolerance, + rouge_l_tolerance=model_case.rouge_l_tolerance, + debug_text=f"model_path={model_path} prompts={prompts}", + ) + + def test_ci_models(self): + for model_case in CI_MODELS: + # Skip long prompts for models that do not have a long context + prompts = DEFAULT_PROMPTS + if model_case.skip_long_prompt: + prompts = [p for p in DEFAULT_PROMPTS if len(p) < 1000] + # Assert the logits and output strs are close + self.assert_close_logits_and_output_strs(prompts, model_case) + + def test_others(self): + if is_in_ci(): + return + + # Skip long prompts for models that do not have a long context + prompts = DEFAULT_PROMPTS + for model_case in ALL_OTHER_MODELS: + if model_case.skip_long_prompt: + prompts = [p for p in DEFAULT_PROMPTS if len(p) < 1000] + + # Assert the logits and output strs are close + self.assert_close_logits_and_output_strs(prompts, model_case) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models/test_vit_pos_embed_interpolate.py b/asian_ai/performance/SGLang/test/registered/models/test_vit_pos_embed_interpolate.py new file mode 100644 index 0000000000000000000000000000000000000000..c35409d24746752c5ba9300f3f2a6013cc4854a7 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models/test_vit_pos_embed_interpolate.py @@ -0,0 +1,123 @@ +"""Bit-exact unit test for the vectorized ViT position-embedding interpolation. + +The vectorized path (``fast_pos_embed_interpolate_vectorized``) removes the +per-image Python loop / CPU<->GPU sync of the legacy implementations. It is meant +to be a pure speedup, so it must be numerically *identical* (bit-exact, rtol=0 +atol=0) to the loop version it replaces -- for single images, many images, video +(t>1), and mixed-size batches, in both bf16 and fp32. + +The interpolation is a sequence of embedding lookups + arithmetic, so it runs and +is bit-exact on CPU; the test exercises CUDA too when available. It calls the real +model methods on a lightweight stub holding a real ``nn.Embedding`` (no model +weights / distributed init needed). + + python -m pytest test/registered/models/test_vit_pos_embed_interpolate.py -v +""" + +import unittest +from types import SimpleNamespace + +import torch +import torch.nn as nn + +from sglang.test.ci.ci_register import ( + register_amd_ci, + register_cpu_ci, + register_cuda_ci, +) +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=20, suite="base-a-test-cpu") +register_cuda_ci(est_time=20, stage="base-a", runner_config="1-gpu-small") +register_amd_ci(est_time=20, stage="stage-a", runner_config="1-gpu-small-amd") + +NUM_POS = 2304 # Qwen3-VL num_position_embeddings -> 48x48 grid +HIDDEN = 64 # small hidden dim keeps the unit test fast +MERGE = 2 + +# t, h, w grids (h, w are multiples of MERGE). Covers single / large-upsample / +# multi-mixed / video / video+image / many-duplicate. +GRID_CASES = { + "single": [[1, 16, 16]], + "single_large": [[1, 64, 98]], # h, w may exceed grid side (upsample) + "multi_mixed": [[1, 16, 24], [1, 32, 12], [1, 8, 40]], + "video": [[4, 16, 20]], + "video_plus_image": [[3, 12, 16], [1, 20, 28], [2, 8, 8]], + "many": [[1, 24, 24]] * 8, +} + + +def _devices(): + devs = [torch.device("cpu")] + if torch.cuda.is_available(): + devs.append(torch.device("cuda")) + return devs + + +class TestViTPosEmbedInterpolate(CustomTestCase): + def _check(self, stub, legacy_fn, vectorized_fn, grid, label): + ref = legacy_fn(stub, grid) + out = vectorized_fn(stub, grid) + self.assertEqual(ref.shape, out.shape, f"{label}: shape mismatch") + self.assertTrue( + torch.equal(ref, out), + f"{label}: not bit-exact, max|diff|=" + f"{(ref.float() - out.float()).abs().max().item():.3e}", + ) + + def test_qwen3_vl_vectorized_matches_loop(self): + try: + from sglang.srt.models.qwen3_vl import Qwen3VLMoeVisionModel as M + except Exception as e: # heavy optional deps (flashinfer, ...) unavailable + self.skipTest(f"cannot import Qwen3VLMoeVisionModel: {e}") + + for device in _devices(): + for dtype in (torch.bfloat16, torch.float32): + stub = SimpleNamespace( + num_grid_per_side=int(NUM_POS**0.5), + spatial_merge_size=MERGE, + num_position_embeddings=NUM_POS, + pos_embed=nn.Embedding(NUM_POS, HIDDEN).to( + device=device, dtype=dtype + ), + dtype=dtype, + device=device, + ) + for name, grid in GRID_CASES.items(): + self._check( + stub, + M.fast_pos_embed_interpolate_from_list, + M.fast_pos_embed_interpolate_vectorized, + grid, + f"qwen3_vl/{name}/{dtype}/{device.type}", + ) + + def test_moss_vl_vectorized_matches_loop(self): + try: + from sglang.srt.models.moss_vl import MossVLVisionModel as M + except Exception as e: + self.skipTest(f"cannot import MossVLVisionModel: {e}") + + for device in _devices(): + for dtype in (torch.bfloat16, torch.float32): + stub = SimpleNamespace( + spatial_merge_size=MERGE, + num_position_embeddings=NUM_POS, + pos_embed=nn.Embedding(NUM_POS, HIDDEN).to( + device=device, dtype=dtype + ), + ) + for name, grid in GRID_CASES.items(): + # the legacy moss method consumes a [num_images, 3] tensor + grid_t = torch.tensor(grid, device=device) + self._check( + stub, + M.fast_pos_embed_interpolate, + M.fast_pos_embed_interpolate_vectorized, + grid_t, + f"moss_vl/{name}/{dtype}/{device.type}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models/test_vlm_models.py b/asian_ai/performance/SGLang/test/registered/models/test_vlm_models.py new file mode 100644 index 0000000000000000000000000000000000000000..2dedd00b333f268f5a5202e551ed6e57c128c6f6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models/test_vlm_models.py @@ -0,0 +1,58 @@ +import random +import tempfile +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import is_hip +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.kits.mmmu_vlm_kit import ( + MMMUMultiModelTestBase, +) +from sglang.test.test_utils import is_in_amd_ci, is_in_ci + +# VLM (Vision Language Model) tests + + +register_cuda_ci(est_time=317, stage="extra-a", runner_config="1-gpu-large") +register_amd_ci(est_time=850, suite="stage-b-test-1-gpu-small-amd-nondeterministic") + +_is_hip = is_hip() +# VLM models for testing +if _is_hip: + MODELS = [ + # SimpleNamespace(model="openbmb/MiniCPM-V-2_6", mmmu_accuracy=0.4), # temporarily disabled: NaN in next_token_logits + SimpleNamespace(model="Qwen/Qwen2.5-VL-3B-Instruct", mmmu_accuracy=0.4), + ] +else: + MODELS = [ + SimpleNamespace(model="google/gemma-3-4b-it", mmmu_accuracy=0.38), + SimpleNamespace(model="Qwen/Qwen2.5-VL-3B-Instruct", mmmu_accuracy=0.4), + # SimpleNamespace(model="openbmb/MiniCPM-V-2_6", mmmu_accuracy=0.4), # temporarily disabled: NaN in next_token_logits + ] + + +class TestVLMModels(MMMUMultiModelTestBase): + def test_vlm_mmmu_benchmark(self): + """Test VLM models against MMMU benchmark.""" + models_to_test = MODELS + + if is_in_ci(): + models_to_test = [random.choice(MODELS)] + + for model in models_to_test: + # Use a unique temporary directory for each model to avoid cached results + with tempfile.TemporaryDirectory( + prefix=f"test_vlm_mmmu_{model.model.replace('/', '_')}_" + ) as temp_dir: + # On AMD CI, the aiter greedy_sample kernel returns an out-of-range + # token id (== vocab_size) for degenerate (all-NaN / all -inf) logit + # rows, producing empty completions that crash the MMMU eval. Disable + # it there so greedy sampling falls back to torch.argmax. + custom_env = None + if is_in_amd_ci(): + custom_env = {"SGLANG_DISABLE_AITER_GREEDY_SAMPLE": "1"} + self._run_vlm_mmmu_test(model, temp_dir, custom_env=custom_env) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models/test_zaya.py b/asian_ai/performance/SGLang/test/registered/models/test_zaya.py new file mode 100644 index 0000000000000000000000000000000000000000..e8eaa5688a234491dbb8314a4000cc986d609bb2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models/test_zaya.py @@ -0,0 +1,127 @@ +"""End-to-end server test for Zyphra ZAYA1 (hybrid CCA attention + MoE). + +This test boots a real ``Zyphra/ZAYA1-base`` SGLang server via +``popen_launch_server``, sends a handful of completions through the HTTP API, +and finishes with a small MMLU sanity slice. + +The test is gated behind ``RUN_ZAYA_E2E=1`` so the registered suite does not +have to download the full ZAYA1-base checkpoint (≈17 GB) on every run; the CI +job that owns this test sets the variable explicitly. +""" + +import os +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import is_hip, kill_process_tree +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +# ZAYA1-base is a heavyweight launch (≈120 transformer layers with MoE), so +# the estimated time is set generously to keep the CI scheduler from preempting +# the job before the server finishes warming up. +register_cuda_ci(est_time=420, stage="extra-a", runner_config="1-gpu-large") +register_amd_ci(est_time=420, suite="stage-b-test-1-gpu-large-amd") + + +_MODEL_PATH = os.environ.get("ZAYA_MODEL_PATH", "Zyphra/ZAYA1-base") + + +def _zaya_enabled() -> bool: + return os.environ.get("RUN_ZAYA_E2E", "0") == "1" + + +@unittest.skipUnless( + _zaya_enabled(), + "Set RUN_ZAYA_E2E=1 to enable the ZAYA1 end-to-end server test " + "(requires downloading the model weights).", +) +class TestZayaServer(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = _MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + + other_args = [ + "--mem-fraction-static", + "0.5", + "--max-running-requests", + "8", + ] + if is_hip(): + other_args += ["--attention-backend", "triton"] + + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + if getattr(cls, "process", None) is not None: + kill_process_tree(cls.process.pid) + + def test_generation_basic(self): + """Send three prompts through the ``/generate`` endpoint and require + non-empty completions for each.""" + import requests + + prompts = [ + "The capital of France is", + "1 + 2 + 3 + 4 + 5 =", + "Write a haiku about silicon:", + ] + for prompt in prompts: + resp = requests.post( + f"{self.base_url}/generate", + json={ + "text": prompt, + "sampling_params": { + "temperature": 0.0, + "max_new_tokens": 16, + }, + }, + timeout=60, + ) + self.assertEqual(resp.status_code, 200, resp.text) + data = resp.json() + self.assertIn("text", data, data) + self.assertGreater(len(data["text"].strip()), 0, data) + + def test_mmlu_sanity(self): + """32-example MMLU sanity slice. + + ZAYA1-base is a pretrained (non instruction-tuned) checkpoint that + emits long ``…`` reasoning blocks before settling on a + final letter, so ``max_tokens`` must be large enough for the evaluator + to see the chosen answer. The threshold sits just above chance: it is + a regression sanity check rather than a production-quality gate. An + instruction-tuned ZAYA1 checkpoint scores meaningfully higher and + should raise this bound when wired in. + """ + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=32, + num_threads=8, + max_tokens=1024, + ) + metrics = run_eval(args) + self.assertGreaterEqual( + metrics["score"], + 0.30, + f"MMLU sanity below threshold: {metrics}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v3_fp4.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v3_fp4.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c1ee2d93e97921fd30894643f63ec77e0cf5e0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v3_fp4.py @@ -0,0 +1,41 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase + +# Per-commit: SymmetricMemory variant only. +# - TestDeepseekV3FP4 (TRTLLM) archived to test/manual/quant/test_deepseek_v3_fp4_4gpu_trtllm.py +# - TestDeepseekV3FP4CutlassMoE moved to test_deepseek_v3_fp4_4gpu_extra.py +register_cuda_ci(est_time=960, stage="base-c", runner_config="4-gpu-b200") + +FULL_DEEPSEEK_V3_FP4_MODEL_PATH = "nvidia/DeepSeek-V3-0324-FP4" + + +class TestDeepseekV3FP4SymmetricMemory(GSM8KMixin, DefaultServerBase): + model = FULL_DEEPSEEK_V3_FP4_MODEL_PATH + timeout = 1200 + other_args = [ + "--tp", + "4", + "--attention-backend", + "trtllm_mla", + "--moe-runner-backend", + "flashinfer_trtllm", + "--quantization", + "modelopt_fp4", + "--kv-cache-dtype", + "fp8_e4m3", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', + "--enable-symm-mem", + ] + + gsm8k_accuracy_thres = 0.93 + gsm8k_num_questions = 1319 + gsm8k_num_threads = 1319 + gsm8k_num_shots = 8 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v3_mtp.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v3_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..4062d6a55ac5af7261c2da782f12ed5cec7539e0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v3_mtp.py @@ -0,0 +1,67 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.send_one import BenchArgs, send_one_prompt +from sglang.test.server_fixtures.default_fixture import DefaultServerBase +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + is_in_amd_ci, + is_in_ci, + write_github_step_summary, +) + +register_cuda_ci(est_time=300, stage="base-c", runner_config="8-gpu-h200") + +FULL_DEEPSEEK_V3_MODEL_PATH = "deepseek-ai/DeepSeek-V3-0324" + +_OTHER_ARGS = [ + "--tp", + "8", + "--trust-remote-code", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', +] +if not is_in_amd_ci(): + _OTHER_ARGS += ["--mem-frac", "0.85"] + + +class TestDeepseekV3MTP(GSM8KMixin, DefaultServerBase): + model = FULL_DEEPSEEK_V3_MODEL_PATH + other_args = _OTHER_ARGS + timeout = DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 5 + + gsm8k_accuracy_thres = 0.935 + gsm8k_accept_length_thres = 2.8 + + # `test_z_bs_1_speed` runs after `test_gsm8k` (alphabetical) so it + # measures steady-state speed on a warmed server. + def test_z_bs_1_speed(self): + args = BenchArgs(port=int(self.base_url.split(":")[-1]), max_new_tokens=2048) + acc_length, speed = send_one_prompt(args) + + print(f"{acc_length=:.2f} {speed=:.2f}") + + if is_in_ci(): + write_github_step_summary( + f"### test_bs_1_speed (deepseek-v3 mtp)\n" + f"{acc_length=:.2f}\n" + f"{speed=:.2f} token/s\n" + ) + self.assertGreater(acc_length, 2.8) + if is_in_amd_ci(): + self.assertGreater(speed, 15) + else: + self.assertGreater(speed, 130) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp4_b200.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp4_b200.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf76dbd64f80bb7af89dfd31328d66df11ee9f0 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp4_b200.py @@ -0,0 +1,218 @@ +"""B200 per-commit CI: DeepSeek-V4-Flash FP4 (LowLatency recipe). + +Launches TP=4 with flashinfer_mxfp4 MoE runner + EAGLE speculative decoding. +Runs 12 ServerSanity probes (correctness, streaming, concurrency, determinism) +plus a GSM8K accuracy gate. + +Registry: base-c-test-deepep-4-gpu-b200 (per-commit, 4x B200) +""" + +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, + try_cached_model, +) + +register_cuda_ci(est_time=465, stage="base-c", runner_config="deepep-4-gpu-b200") + +MODEL = "deepseek-ai/DeepSeek-V4-Flash" +SERVER_LAUNCH_TIMEOUT = 3600 +DEEPEP_CONFIG = '{"normal_dispatch":{"num_sms":96},"normal_combine":{"num_sms":96}}' + +_DEEPEP_ENV = { + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "1024", +} + + +class TestDSV4FlashFP4B200( + SpecDecodingMixin, + BasicDecodeCorrectnessMixin, + GSM8KMixin, + CustomTestCase, +): + """LowLatency recipe: TP=4, FP4 (mxfp4), EAGLE spec decoding.""" + + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 2.8 + bs_1_speed_thres = 220 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--moe-runner-backend", + "flashinfer_mxfp4", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--chunked-prefill-size", + "4096", + "--disable-flashinfer-autotune", + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +class TestDSV4FlashFP4B200Balanced( + SpecDecodingMixin, + BasicDecodeCorrectnessMixin, + GSM8KMixin, + CustomTestCase, +): + """Balanced recipe: TP=4, DP=4, DeepEP, EAGLE (1-step spec).""" + + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 1.8 + bs_1_speed_thres = 100 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "deepep", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", + "--deepep-config", + DEEPEP_CONFIG, + ], + env=_DEEPEP_ENV, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +class TestDSV4FlashFP4NonMTPB200( + BasicDecodeCorrectnessMixin, GSM8KMixin, CustomTestCase +): + """Non-MTP recipe: TP=4, DP=4, DeepEP, no speculative decoding.""" + + gsm8k_accuracy_thres = 0.93 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "deepep", + "--deepep-config", + DEEPEP_CONFIG, + ], + env=_DEEPEP_ENV, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +class TestDSV4FlashFP4BreakableCudaGraphB200( + BasicDecodeCorrectnessMixin, GSM8KMixin, CustomTestCase +): + """BCG recipe: TP=4, DP=4, DeepEP, DP attention, mixed chunk.""" + + gsm8k_accuracy_thres = 0.93 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--enable-mixed-chunk", + "--cuda-graph-backend-prefill", + "breakable", + "--moe-a2a-backend", + "deepep", + "--deepep-config", + DEEPEP_CONFIG, + "--chunked-prefill-size", + "4096", + "--piecewise-cuda-graph-max-tokens", + "1024", + "--mem-fraction-static", + "0.80", + "--cuda-graph-max-bs-decode", + "16", + "--max-running-requests", + "128", + "--watchdog-timeout", + "900", + ], + env=_DEEPEP_ENV, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp4_h200.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp4_h200.py new file mode 100644 index 0000000000000000000000000000000000000000..2e36180928754a68f3dc384283969fb771c2d28e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp4_h200.py @@ -0,0 +1,174 @@ +"""H200 per-commit CI: DeepSeek-V4-Flash FP4 Marlin (LowLatency recipe). + +Launches TP=4 with Marlin FP4 MoE runner + EAGLE speculative decoding. +Runs 12 ServerSanity probes (correctness, streaming, concurrency, determinism) +plus a GSM8K accuracy gate. + +Registry: base-c-test-deepep-8-gpu-h200 (per-commit, 8x H200 — only 4 used by TP=4) +""" + +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, + try_cached_model, +) + +register_cuda_ci(est_time=370, stage="base-c", runner_config="deepep-8-gpu-h200") + + +def _flashinfer_has_sm90_cutlass_mxfp4() -> bool: + try: + from flashinfer.fused_moe import ( # noqa: F401 + interleave_moe_weights_for_sm90_mixed_gemm, + ) + + return True + except ImportError: + return False + + +MODEL = "deepseek-ai/DeepSeek-V4-Flash" +MODEL_FP8 = "sgl-project/DeepSeek-V4-Flash-FP8" +SERVER_LAUNCH_TIMEOUT = 3600 +DEEPEP_CONFIG = '{"normal_dispatch":{"num_sms":96},"normal_combine":{"num_sms":96}}' + + +class TestDSV4FlashFP4H200( + SpecDecodingMixin, + BasicDecodeCorrectnessMixin, + GSM8KMixin, + CustomTestCase, +): + """LowLatency recipe: TP=4, Marlin FP4, EAGLE spec decoding.""" + + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 2.8 + bs_1_speed_thres = 240 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--moe-runner-backend", + "marlin", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--watchdog-timeout", + "900", + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +@unittest.skipUnless( + _flashinfer_has_sm90_cutlass_mxfp4(), + "FlashInfer build lacks SM90 mixed-input MXFP4 helpers (PR #3084, >= 0.6.11)", +) +class TestDSV4FlashFP4H200FlashInferCutlass( + SpecDecodingMixin, + BasicDecodeCorrectnessMixin, + GSM8KMixin, + CustomTestCase, +): + """FlashInfer SM90 mixed-input cutlass MXFP4 backend (this PR): TP=4 + EAGLE. + + Mirrors :class:`TestDSV4FlashFP4H200` but swaps `--moe-runner-backend marlin` + for `flashinfer_mxfp4`, exercising the SM90 cutlass path from FlashInfer PR + #3084 end-to-end on a real DSv4-Flash checkpoint. + """ + + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 2.8 + bs_1_speed_thres = 230 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--moe-runner-backend", + "flashinfer_mxfp4", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +class TestDSV4FlashFP4NonMTPH200( + BasicDecodeCorrectnessMixin, GSM8KMixin, CustomTestCase +): + """LowLatency recipe without MTP: TP=4, Marlin FP4, no speculative decoding.""" + + gsm8k_accuracy_thres = 0.93 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--moe-runner-backend", + "marlin", + "--watchdog-timeout", + "900", + ], + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp4_megamoe_b200.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp4_megamoe_b200.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0e4ba28dfc69cc011fe2d5383dbe45f110ddd9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp4_megamoe_b200.py @@ -0,0 +1,137 @@ +"""B200 per-commit CI: DeepSeek-V4-Flash FP4 (LowLatency recipe). + +Launches TP=4 with flashinfer_mxfp4 MoE runner + EAGLE speculative decoding. +Runs 12 ServerSanity probes (correctness, streaming, concurrency, determinism) +plus a GSM8K accuracy gate. + +Registry: extra-b-test-deepep-4-gpu-b200 (label-gated, 4x B200) +""" + +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, + try_cached_model, +) + +register_cuda_ci(est_time=900, stage="extra-b", runner_config="deepep-4-gpu-b200") + +MODEL = "deepseek-ai/DeepSeek-V4-Flash" +SERVER_LAUNCH_TIMEOUT = 3600 + + +_W4A8_MEGAMOE_ENV = { + "SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK": "4096", +} + + +_W4A4_MEGAMOE_ENV = { + "SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK": "4096", + "SGLANG_OPT_DEEPGEMM_MEGA_MOE_USE_FP4_ACTS": "1", + "SGLANG_OPT_DEEPGEMM_MEGA_MOE_USE_MXF4_KIND": "1", +} + + +class TestDSV4FlashFP4B200W4A8MegaMoE( + SpecDecodingMixin, + BasicDecodeCorrectnessMixin, + GSM8KMixin, + CustomTestCase, +): + """Balanced recipe: TP=4, DP=4, MegaMoE.""" + + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 1.8 + bs_1_speed_thres = 100 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "megamoe", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", + ], + env=_W4A8_MEGAMOE_ENV, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +class TestDSV4FlashFP4B200W4A4MegaMoE( + SpecDecodingMixin, + BasicDecodeCorrectnessMixin, + GSM8KMixin, + CustomTestCase, +): + """Balanced recipe: TP=4, DP=4, MegaMoE.""" + + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 2.8 + bs_1_speed_thres = 100 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "megamoe", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + ], + env=_W4A4_MEGAMOE_ENV, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp8_h200.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp8_h200.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8abd3a4b51536e3c9624e95c45b9166f9c75b4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_deepseek_v4_flash_fp8_h200.py @@ -0,0 +1,91 @@ +"""H200 per-commit CI: DeepSeek-V4-Flash FP8 (LowLatency recipe). + +Launches TP=4 with DeepEP a2a backend + EAGLE speculative decoding, +with FP4 experts disabled via SGLANG_DSV4_FP4_EXPERTS=0. +Runs 12 ServerSanity probes (correctness, streaming, concurrency, determinism) +plus a GSM8K accuracy gate. + +Registry: extra-b-test-deepep-8-gpu-h200 (label-gated, 8x H200 — only 4 used by TP=4) +""" + +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, + try_cached_model, +) + +register_cuda_ci(est_time=280, stage="extra-b", runner_config="deepep-8-gpu-h200") + +MODEL_FP8 = "sgl-project/DeepSeek-V4-Flash-FP8" +SERVER_LAUNCH_TIMEOUT = 3600 +DEEPEP_CONFIG = '{"normal_dispatch":{"num_sms":96},"normal_combine":{"num_sms":96}}' + + +class TestDSV4FlashFP8H200( + SpecDecodingMixin, + BasicDecodeCorrectnessMixin, + GSM8KMixin, + CustomTestCase, +): + """LowLatency recipe: TP=4, Marlin FP4, EAGLE spec decoding.""" + + gsm8k_accuracy_thres = 0.93 + accept_length_thres = 1.8 + bs_1_speed_thres = 140 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL_FP8) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--moe-a2a-backend", + "deepep", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "1", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "2", + "--cuda-graph-max-bs-decode", + "128", + "--max-running-requests", + "128", + "--deepep-config", + DEEPEP_CONFIG, + "--watchdog-timeout", + "900", + ], + env={ + "SGLANG_DSV4_FP4_EXPERTS": "0", + "SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK": "256", + }, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "process") and cls.process: + kill_process_tree(cls.process.pid) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_dsa_glm52_dp_mtp.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_dsa_glm52_dp_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d9079b17bd717bca0d00745f2c8b8585f05a65 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_dsa_glm52_dp_mtp.py @@ -0,0 +1,28 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.server_fixtures.dsa_mtp_fixture import ( + DsaMtpEvalConfigDefaults, + DsaMtpServerBase, +) + +register_cuda_ci( + est_time=400, + stage="base-c", + runner_config="8-gpu-h200", +) + + +class TestGLM52DPMTP( + DsaMtpServerBase, DsaMtpEvalConfigDefaults, GSM8KMixin, SpecDecodingMixin +): + model = "zai-org/GLM-5.2-FP8" + mem_fraction_static = 0.88 + enable_dp_attention = True + bs_1_speed_thres = 70 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_dsa_glm52_hisparse.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_dsa_glm52_hisparse.py new file mode 100644 index 0000000000000000000000000000000000000000..328c89d8f0e16b5ffd31ff7d80bf4181d7c0090a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_dsa_glm52_hisparse.py @@ -0,0 +1,69 @@ +import subprocess +import time +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase + +register_cuda_ci(est_time=720, stage="extra-b", runner_config="8-gpu-h200") + +GLM52_FP8_MODEL_PATH = "zai-org/GLM-5.2-FP8" + + +class TestGLM52HiSparse(DefaultServerBase, GSM8KMixin): + """GLM-5.2 FP8 with HiSparse (host-to-device sparse KV offload) on DSA decode. + + HiSparse targets the high-concurrency regime and is not used together with + EAGLE MTP, so this variant runs without speculative decoding (unlike the + DSA-MTP variants in test_dsa_glm52_{dp,tp}_mtp.py). + """ + + model = GLM52_FP8_MODEL_PATH + other_args = [ + "--trust-remote-code", + "--tp", + "8", + "--dp", + "8", + "--enable-dp-attention", + "--page-size", + "64", + "--max-running-requests", + "200", + "--mem-fraction-static", + "0.85", + "--disable-radix-cache", + "--kv-cache-dtype", + "bfloat16", + "--dsa-decode-backend", + "flashmla_sparse", + "--enable-hisparse", + "--hisparse-config", + '{"top_k": 2048, "device_buffer_size": 4096, "host_to_device_ratio": 5}', + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ] + + # Match the original standalone hisparse eval config. + gsm8k_accuracy_thres = 0.94 + gsm8k_num_questions = 500 + gsm8k_num_threads = 100 + gsm8k_num_shots = 24 + + @classmethod + def tearDownClass(cls): + # HiSparse's large pinned host buffer stalls an external SIGKILL teardown + # (kernel unpin). Drive the server's own graceful shutdown so each rank + # unregisters in userspace; hard-kill as a fallback. + cls.process.terminate() + try: + cls.process.wait(timeout=90) + except subprocess.TimeoutExpired: + kill_process_tree(cls.process.pid, wait_timeout=60) + time.sleep(2) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_dsa_glm52_tp_mtp.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_dsa_glm52_tp_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..f330bbd3a971b0e5af51193526f2cfcc4c792609 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_dsa_glm52_tp_mtp.py @@ -0,0 +1,27 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.server_fixtures.dsa_mtp_fixture import ( + DsaMtpEvalConfigDefaults, + DsaMtpServerBase, +) + +register_cuda_ci( + est_time=400, + stage="base-c", + runner_config="8-gpu-h200", +) + + +class TestGLM52TPMTP( + DsaMtpServerBase, DsaMtpEvalConfigDefaults, GSM8KMixin, SpecDecodingMixin +): + model = "zai-org/GLM-5.2-FP8" + mem_fraction_static = 0.8 + bs_1_speed_thres = 150 + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_dummy_grok_models.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_dummy_grok_models.py new file mode 100644 index 0000000000000000000000000000000000000000..321467c78a1165d44d9b3baad2ee9b3b7675a948 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_dummy_grok_models.py @@ -0,0 +1,42 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase, is_in_ci, run_bench_one_batch + +register_cuda_ci( + est_time=120, + stage="base-b", + runner_config="2-gpu-large", + disabled="Temporarily disabled", +) + + +class TestDummyGrok1(CustomTestCase): + + def test_dummy_grok_1(self): + _, output_throughput, _ = run_bench_one_batch( + None, + [ + "--model", + "/dummy-grok", + "--tokenizer-path", + "Xenova/grok-1-tokenizer", + "--batch-size", + "2", + "--tp", + "2", + "--quantization", + "fp8", + "--load-format", + "dummy", + "--json-model-override-args", + '{"num_hidden_layers": 2}', + ], + ) + + if is_in_ci(): + self.assertGreater(output_throughput, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_gemma4_fp8_per_expert_loading.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_gemma4_fp8_per_expert_loading.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2482efde53e31c09ad185b60c0e6aef7f41ad4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_gemma4_fp8_per_expert_loading.py @@ -0,0 +1,109 @@ +"""End-to-end test for compressed-tensors per-expert FP8 MoE checkpoint +loading on Gemma4 (e.g. RedHatAI/gemma-4-26B-A4B-it-FP8-Dynamic). + +Regression coverage for the load_weights path that recognises +`experts..{gate,up,down}_proj.{weight,weight_scale}` keys and folds +them into SGLang's fused FusedMoE parameters. Without that path, all +routed-expert weights are silently skipped at load time and the model +emits only `` tokens at inference (GSM8K collapses to 0.0). +""" + +import unittest +from types import SimpleNamespace + +import requests + +from sglang.srt.utils import get_device_sm, kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +# Compressed-tensors per-expert FP8 MoE checkpoint that exercises the +# loader path (gated repo + ~27 GB download + 4 GPUs at TP=4). +register_cuda_ci(est_time=120, stage="base-c", runner_config="4-gpu-h100") + + +@unittest.skipIf(get_device_sm() < 90, "Test requires CUDA SM 90 or higher") +class TestGemma4FP8PerExpertLoading(CustomTestCase): + """Three-stage check that catches the silent-skip failure mode: + 1. server health + 2. completion is not the all-`` garbage state + 3. GSM8K accuracy matches the BF16 baseline + """ + + model = "RedHatAI/gemma-4-26B-A4B-it-FP8-Dynamic" + base_url = DEFAULT_URL_FOR_TEST + + @classmethod + def setUpClass(cls): + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp", + "4", + "--trust-remote-code", + "--random-seed", + "42", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_health(self): + r = requests.get(self.base_url + "/health") + self.assertEqual(r.status_code, 200) + + def test_basic_generation_not_garbage(self): + """Pre-fix the server starts but every routed expert is zero-init, + which leads chat completions to deterministic `` spam.""" + r = requests.post( + self.base_url + "/v1/chat/completions", + json={ + "model": self.model, + "messages": [{"role": "user", "content": "What is 7 + 5?"}], + "temperature": 0, + "max_tokens": 32, + }, + ) + self.assertEqual(r.status_code, 200) + text = r.json()["choices"][0]["message"]["content"] + self.assertNotIn( + "", text, f"Output looks like the pre-fix garbage state: {text!r}" + ) + self.assertGreater(len(text.strip()), 0, "Empty completion") + self.assertIn("12", text, f"Expected the answer to mention '12': {text!r}") + + def test_gsm8k_accuracy(self): + """Pre-fix this scores exactly 0.00 (zero routed-expert weights); + post-fix it matches the BF16 baseline (~0.95 on 20 samples).""" + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + num_examples=20, + num_threads=16, + ) + metrics = run_eval(args) + score = float(metrics["score"]) + print(f"Gemma4 FP8 per-expert GSM8K-20 score: {score:.3f}") + # Threshold rules out the failure mode (0.00) while leaving ample + # margin under the BF16 baseline (~0.95). + self.assertGreaterEqual( + score, + 0.80, + f"Per-expert FP8 ckpt accuracy collapsed: {score} " + "(pre-fix value is 0.00; BF16 baseline is ~0.95).", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_gpt_oss_4gpu_bf16.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_gpt_oss_4gpu_bf16.py new file mode 100644 index 0000000000000000000000000000000000000000..9faa3be63d3b8f7bd8fb26b6ab40f8933687ef1a --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_gpt_oss_4gpu_bf16.py @@ -0,0 +1,23 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.gpt_oss_common import BaseTestGptOss + +register_cuda_ci(est_time=220, stage="base-c", runner_config="4-gpu-h100") +register_cuda_ci(est_time=220, stage="base-c", runner_config="4-gpu-b200") + + +class TestGptOss4GpuBf16(BaseTestGptOss): + def test_bf16_120b(self): + self.run_test( + model_variant="120b", + quantization="bf16", + expected_score_of_reasoning_effort={ + "low": 0.58, + }, + other_args=["--tp", "4", "--cuda-graph-max-bs-decode", "200"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_gpt_oss_4gpu_mxfp4.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_gpt_oss_4gpu_mxfp4.py new file mode 100644 index 0000000000000000000000000000000000000000..91bcf7c7be143ce5fdab27c50828d62cec657c2b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_gpt_oss_4gpu_mxfp4.py @@ -0,0 +1,28 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.gpt_oss_common import BaseTestGptOss + +register_cuda_ci(est_time=220, stage="base-c", runner_config="4-gpu-h100") +register_cuda_ci(est_time=220, stage="base-c", runner_config="4-gpu-b200") + + +class TestGptOss4GpuMxfp4(BaseTestGptOss): + def test_mxfp4_120b(self): + self.run_test( + model_variant="120b", + quantization="mxfp4", + expected_score_of_reasoning_effort={ + "low": 0.58, + }, + other_args=[ + "--tp", + "4", + "--cuda-graph-max-bs-decode", + "200", + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_gpt_oss_sm120.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_gpt_oss_sm120.py new file mode 100644 index 0000000000000000000000000000000000000000..0adcc616ad753670a476cf0d9267f76071db7264 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_gpt_oss_sm120.py @@ -0,0 +1,34 @@ +import unittest + +import torch + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.gpt_oss_common import BaseTestGptOss + +register_cuda_ci(est_time=345, stage="extra-a", runner_config="1-gpu-small") + + +@unittest.skipIf(not torch.cuda.is_available(), "CUDA is not available") +class TestGptOssSm120(BaseTestGptOss): + @classmethod + def setUpClass(cls): + compute_capability = torch.cuda.get_device_capability() + if compute_capability != (12, 0): + raise unittest.SkipTest( + f"GPT-OSS SM120 test requires SM 12.0, but found {compute_capability[0]}.{compute_capability[1]}" + ) + + def test_mxfp4_20b(self): + self.run_test( + model_variant="20b", + quantization="mxfp4", + expected_score_of_reasoning_effort={ + "low": 0.34, + "medium": 0.34, + "high": 0.27, + }, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_kimi_linear_models.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_kimi_linear_models.py new file mode 100644 index 0000000000000000000000000000000000000000..ec184a1580c6bef400e6519606d2a3bdb740eb88 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_kimi_linear_models.py @@ -0,0 +1,49 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=178, stage="base-b", runner_config="2-gpu-large") + + +class TestKimiLinear(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "moonshotai/Kimi-Linear-48B-A3B-Instruct" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=["--tp-size", "2", "--trust-remote"], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.88) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_mimo_v2.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_mimo_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe01735247fe9fa7a8f7a58b6879c6aab3143e6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_mimo_v2.py @@ -0,0 +1,60 @@ +import unittest + +from sglang.srt.environ import envs +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.server_fixtures.mmmu_fixture import MMMUServerBase + +register_cuda_ci(est_time=400, stage="base-c", runner_config="8-gpu-h200") + +MIMO_V2_MODEL = "XiaomiMiMo/MiMo-V2.5" +MIMO_V2_OTHER_ARGS = [ + "--tp", + "8", + "--dp", + "2", + "--enable-dp-attention", + "--mm-enable-dp-encoder", + "--attention-backend", + "fa3", + "--mm-attention-backend", + "fa3", + "--reasoning-parser", + "mimo", + "--enable-hierarchical-cache", + "--hicache-ratio", + "1.5", + "--hicache-mem-layout", + "page_first_direct", + "--hicache-io-backend", + "direct", +] +MIMO_V2_MTP_OTHER_ARGS = MIMO_V2_OTHER_ARGS + [ + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--enable-multi-layer-eagle", +] + + +class TestMiMoV2(GSM8KMixin, MMMUServerBase): + gsm8k_accuracy_thres = 0.75 + gsm8k_accept_length_thres = 2.5 + model = MIMO_V2_MODEL + mem_fraction_static = 0.65 + server_api_key = None + other_args = MIMO_V2_MTP_OTHER_ARGS + + @classmethod + def setUpClass(cls): + with envs.SGLANG_ENABLE_UNIFIED_RADIX_TREE.override(True): + super().setUpClass() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_mimo_v2_flash.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_mimo_v2_flash.py new file mode 100644 index 0000000000000000000000000000000000000000..04907f1969a18e4a9e65ab1c780b19f9b44491c3 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_mimo_v2_flash.py @@ -0,0 +1,65 @@ +import unittest + +from sglang.srt.environ import envs +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase + +register_cuda_ci(est_time=350, stage="base-c", runner_config="8-gpu-h200") + + +class TestMiMoV2Flash(GSM8KMixin, SpecDecodingMixin, DefaultServerBase): + gsm8k_accuracy_thres = 0.75 + gsm8k_num_questions = 1319 + gsm8k_num_threads = 1319 + model = "XiaomiMiMo/MiMo-V2-Flash" + + other_args = [ + "--tp", + "4", + "--dp", + "2", + "--enable-dp-attention", + "--trust-remote-code", + "--attention-backend", + "fa3", + "--max-running-requests", + "128", + "--cuda-graph-max-bs-decode", + "64", + "--page-size", + "64", + "--mem-fraction-static", + "0.75", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--enable-multi-layer-eagle", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', + "--enable-hierarchical-cache", + "--hicache-ratio", + "1.5", + "--hicache-mem-layout", + "page_first_direct", + "--hicache-io-backend", + "direct", + ] + + bs_1_speed_thres = 170 + accept_length_thres = 3.2 + + @classmethod + def setUpClass(cls): + with envs.SGLANG_ENABLE_UNIFIED_RADIX_TREE.override(True): + super().setUpClass() + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_minimax_m25_basic.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_minimax_m25_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..8f6c3da5c8bb7050e86161d17834cfeac13ffef6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_minimax_m25_basic.py @@ -0,0 +1,85 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.few_shot_gsm8k import run_eval as run_eval_few_shot_gsm8k +from sglang.test.send_one import BenchArgs, send_one_prompt +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + is_in_ci, + popen_launch_server, + write_github_step_summary, +) + +register_cuda_ci(est_time=250, stage="base-c", runner_config="8-gpu-h200") + +MINIMAX_M25_MODEL_PATH = "MiniMaxAI/MiniMax-M2.5" + + +class TestMiniMaxM25Basic(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = MINIMAX_M25_MODEL_PATH + cls.base_url = DEFAULT_URL_FOR_TEST + other_args = [ + "--trust-remote-code", + "--tp", + "8", + "--ep-size", + "8", + "--mem-fraction-static", + "0.85", + "--reasoning-parser", + "minimax-append-think", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + "--weight-loader-prefetch-checkpoints", + ] + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=other_args, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_a_gsm8k(self): + args = SimpleNamespace( + num_shots=20, + data_path=None, + num_questions=1400, + parallel=1400, + max_new_tokens=512, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval_few_shot_gsm8k(args) + print(f"{metrics=}") + + if is_in_ci(): + write_github_step_summary( + f"### test_gsm8k (minimax-m25)\n" f'{metrics["accuracy"]=:.3f}\n' + ) + self.assertGreater(metrics["accuracy"], 0.900) + + def test_bs_1_speed(self): + args = BenchArgs(port=int(self.base_url.split(":")[-1]), max_new_tokens=2048) + acc_length, speed = send_one_prompt(args) + + print(f"{speed=:.2f}") + + if is_in_ci(): + write_github_step_summary( + f"### test_bs_1_speed (minimax-m25)\n" f"{speed=:.2f} token/s\n" + ) + self.assertGreater(speed, 90) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_ministral3_models.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_ministral3_models.py new file mode 100644 index 0000000000000000000000000000000000000000..d86fec59eb319370385e8ccf55df0b1d1536c372 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_ministral3_models.py @@ -0,0 +1,34 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.mmmu_vlm_kit import MMMUMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase +from sglang.test.server_fixtures.mmmu_fixture import MMMUServerBase + +register_cuda_ci( + est_time=200, + stage="base-b", + runner_config="1-gpu-small", + disabled="Temporarily disabled", +) + +MODEL = "mistralai/Ministral-3-3B-Instruct-2512" + + +class TestMinistral3TextOnly(GSM8KMixin, DefaultServerBase): + gsm8k_accuracy_thres = 0.6 + model = MODEL + other_args = ["--trust-remote-code"] + + +class TestMinistral3MMMU(MMMUMixin, MMMUServerBase): + accuracy = 0.3 + model = MODEL + other_args = ["--trust-remote-code"] + mmmu_args = ["--limit=0.1"] + """`--limit=0.1`: 10 percent of each task - this is fine for testing since the nominal result isn't interesting - this run is just to prevent relative regressions.""" + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_ministral4_models.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_ministral4_models.py new file mode 100644 index 0000000000000000000000000000000000000000..988d2eb63f94f071a8271fc18b28093d1a2c58a2 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_ministral4_models.py @@ -0,0 +1,29 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.mmmu_vlm_kit import MMMUMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase +from sglang.test.server_fixtures.mmmu_fixture import MMMUServerBase + +register_cuda_ci(est_time=200, stage="extra-a", runner_config="2-gpu-large") + +MODEL = "mistralai/Mistral-Small-4-119B-2603" + + +class TestMistralSmall4TextOnly(GSM8KMixin, DefaultServerBase): + gsm8k_accuracy_thres = 0.9 + model = MODEL + other_args = ["--tp-size", "2", "--trust-remote-code"] + + +class TestMistralSmall4MMMU(MMMUMixin, MMMUServerBase): + accuracy = 0.45 + model = MODEL + other_args = ["--tp-size", "2", "--trust-remote-code"] + mmmu_args = ["--limit=0.1"] + """`--limit=0.1`: 10 percent of each task - this is fine for testing since the nominal result isn't interesting - this run is just to prevent relative regressions.""" + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_nvidia_nemotron_3_nano.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_nvidia_nemotron_3_nano.py new file mode 100644 index 0000000000000000000000000000000000000000..f99beab78892cc2d68a0abdcf2629cb7080a3cca --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_nvidia_nemotron_3_nano.py @@ -0,0 +1,34 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.lm_eval_kit import LMEvalMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase + +register_cuda_ci( + est_time=190, + stage="base-b", + runner_config="2-gpu-large", +) + +NEMOTRON_3_NANO_THINKING_ARGS = [ + "--trust-remote-code", + "--tool-call-parser", + "qwen3_coder", + "--reasoning-parser", + "deepseek-r1", +] + + +class TestNvidiaNemotron3Nano30BFP8(LMEvalMixin, DefaultServerBase): + """Test Nemotron-3-Nano-30B FP8 model with lm-eval GSM8K evaluation.""" + + model = "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8" + model_config_name = "lm_eval_configs/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8.yaml" + other_args = [ + "--tp-size", + "2", + ] + NEMOTRON_3_NANO_THINKING_ARGS + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_nvidia_nemotron_3_super_bf16.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_nvidia_nemotron_3_super_bf16.py new file mode 100644 index 0000000000000000000000000000000000000000..536b0f5df419bfb7ed342e1f82177a2e1a4c13df --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_nvidia_nemotron_3_super_bf16.py @@ -0,0 +1,69 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=200, stage="extra-b", runner_config="8-gpu-h200") + +NEMOTRON_3_SUPER_BF16_MODEL = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16" + +NEMOTRON_3_SUPER_BF16_ARGS = [ + "--tp-size", + "8", + "--trust-remote-code", + "--reasoning-parser", + "nemotron_3", + "--tool-call-parser", + "qwen3_coder", + "--disable-radix-cache", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 50}', +] + + +class TestNvidiaNemotron3SuperBF16(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = NEMOTRON_3_SUPER_BF16_MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=NEMOTRON_3_SUPER_BF16_ARGS, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + model=self.model, + eval_name="gsm8k", + num_shots=5, + num_examples=200, + max_tokens=16000, + num_threads=200, + repeat=1, + temperature=1.0, + top_p=0.95, + base_url=self.base_url, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreaterEqual(metrics["score"], 0.96) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_nvidia_nemotron_3_super_bf16_mtp.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_nvidia_nemotron_3_super_bf16_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..7e519273abf85d6d7439ac5c26641eea7fba6678 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_nvidia_nemotron_3_super_bf16_mtp.py @@ -0,0 +1,84 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=200, stage="extra-b", runner_config="8-gpu-h200") + +NEMOTRON_3_SUPER_BF16_MODEL = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16" + +NEMOTRON_3_SUPER_BF16_ARGS = [ + "--tp-size", + "8", + "--trust-remote-code", + "--reasoning-parser", + "nemotron_3", + "--tool-call-parser", + "qwen3_coder", + "--disable-radix-cache", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 50}', +] + +MTP_ARGS = [ + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--max-running-requests", + "200", + "--mem-fraction-static", + "0.75", +] + + +class TestNvidiaNemotron3SuperBF16MTP(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = NEMOTRON_3_SUPER_BF16_MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=NEMOTRON_3_SUPER_BF16_ARGS + MTP_ARGS, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + model=self.model, + eval_name="gsm8k", + num_shots=5, + num_examples=200, + max_tokens=16000, + num_threads=200, + repeat=1, + temperature=1.0, + top_p=0.95, + base_url=self.base_url, + host="http://127.0.0.1", + port=int(self.base_url.split(":")[-1]), + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreaterEqual(metrics["score"], 0.96) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen35_fp4_flashinfer.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen35_fp4_flashinfer.py new file mode 100644 index 0000000000000000000000000000000000000000..8fac43ae4b5a49841846f202c0d1e2bd79758b0b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen35_fp4_flashinfer.py @@ -0,0 +1,83 @@ +import unittest + +import torch + +from sglang.test.accuracy_test_runner import AccuracyTestParams +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_combined_tests import run_combined_tests +from sglang.test.test_utils import ( + CustomTestCase, + ModelLaunchSettings, +) + +register_cuda_ci(est_time=720, stage="base-c", runner_config="4-gpu-b200") + +QWEN35_FP4_MODEL = "nvidia/Qwen3.5-397B-A17B-NVFP4" +ACC_THRESHOLDS = {QWEN35_FP4_MODEL: {"gsm8k": 0.95}} + +_cuda_major = int(torch.version.cuda.split(".")[0]) if torch.version.cuda else 0 + +_is_sm100_cuda13 = ( + torch.cuda.is_available() + and torch.cuda.get_device_capability()[0] >= 10 + and _cuda_major >= 13 +) + + +@unittest.skipUnless(_is_sm100_cuda13, "requires SM100+ GPU and CUDA 13+") +class TestQwen35FP4FlashInfer(CustomTestCase): + def test_gsm8k(self): + base_args = [ + "--tp-size", + "4", + "--chunked-prefill-size", + "2048", + "--mamba-scheduler-strategy", + "extra_buffer", + "--mamba-track-interval", + "128", + "--mamba-ssm-dtype", + "bfloat16", + "--max-running-requests", + "128", + "--reasoning-parser", + "qwen3", + "--attention-backend", + "trtllm_mha", + "--quantization", + "modelopt_fp4", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', + "--linear-attn-decode-backend", + "flashinfer", + "--linear-attn-prefill-backend", + "flashinfer", + ] + + variants = [ + ModelLaunchSettings( + QWEN35_FP4_MODEL, + extra_args=base_args, + variant="FlashInfer", + ), + ] + + run_combined_tests( + models=variants, + test_name="Qwen3.5-397B-A17B-NVFP4", + accuracy_params=AccuracyTestParams( + dataset="gsm8k", + baseline_accuracy=ACC_THRESHOLDS[QWEN35_FP4_MODEL]["gsm8k"], + num_examples=200, + num_threads=128, + max_tokens=16000, + thinking_mode="qwen3", + temperature=0.6, + top_p=0.95, + top_k=20, + ), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen35_fp4_mtp.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen35_fp4_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc512229ccf6153f0e584979e35ff4467f4cbc9 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen35_fp4_mtp.py @@ -0,0 +1,138 @@ +import unittest +from types import SimpleNamespace + +import requests + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.reasoning_kit import ReasoningTokenUsageMixin +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=740, stage="base-c", runner_config="4-gpu-b200") + +QWEN35_FP4_MODEL = "nvidia/Qwen3.5-397B-A17B-NVFP4" +ACC_THRESHOLDS = {QWEN35_FP4_MODEL: {"gsm8k": 0.95}} + +MTP_BASE_ARGS = [ + "--tp-size", + "4", + "--chunked-prefill-size", + "2048", + "--mamba-scheduler-strategy", + "extra_buffer", + "--mamba-track-interval", + "128", + "--mamba-ssm-dtype", + "bfloat16", + "--max-running-requests", + "128", + "--reasoning-parser", + "qwen3", + "--attention-backend", + "trtllm_mha", + "--quantization", + "modelopt_fp4", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--mem-fraction-static", + "0.8", + "--model-loader-extra-config", + '{"enable_multithread_load": true,"num_threads": 64}', +] + + +def _run_mtp_gsm8k(test_case): + args = SimpleNamespace( + model=test_case.model, + eval_name="gsm8k", + num_shots=5, + num_examples=200, + max_tokens=16000, + num_threads=128, + repeat=1, + temperature=0.6, + top_p=0.95, + top_k=20, + base_url=test_case.base_url, + host="http://127.0.0.1", + port=int(test_case.base_url.split(":")[-1]), + ) + metrics = run_eval(args) + print(f"{metrics=}") + test_case.assertGreaterEqual( + metrics["score"], ACC_THRESHOLDS[test_case.model]["gsm8k"] + ) + + server_info = requests.get(test_case.base_url + "/server_info") + avg_spec_accept_length = server_info.json()["internal_states"][0][ + "avg_spec_accept_length" + ] + print(f"{avg_spec_accept_length=}") + test_case.assertGreater(avg_spec_accept_length, 3.3) + + +class TestQwen35FP4MTP(ReasoningTokenUsageMixin, CustomTestCase): + reasoning_parser_name = "qwen3" + + @classmethod + def setUpClass(cls): + cls.model = QWEN35_FP4_MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.init_reasoning_token_verifier() + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=MTP_BASE_ARGS, + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + _run_mtp_gsm8k(self) + + +class TestQwen35FP4MTPFlashInfer(ReasoningTokenUsageMixin, CustomTestCase): + reasoning_parser_name = "qwen3" + + @classmethod + def setUpClass(cls): + cls.model = QWEN35_FP4_MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.init_reasoning_token_verifier() + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=MTP_BASE_ARGS + + [ + "--linear-attn-decode-backend", + "flashinfer", + "--enforce-disable-flashinfer-allreduce-fusion", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + _run_mtp_gsm8k(self) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen3_next_models.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen3_next_models.py new file mode 100644 index 0000000000000000000000000000000000000000..35922625cbb5d778b7a489b0576eb95b45b0b31b --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen3_next_models.py @@ -0,0 +1,104 @@ +import os +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.kl_divergence_kit import KLDivergenceMixin +from sglang.test.kits.prefix_cache_branching_kit import PrefixCacheBranchingMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase + +register_cuda_ci(est_time=250, stage="base-c", runner_config="4-gpu-h100") + +QWEN3_NEXT_MODEL = "Qwen/Qwen3-Next-80B-A3B-Instruct" + +_COMMON_ARGS = [ + "--trust-remote-code", + "--tp-size", + "4", + "--chunked-prefill-size", + "2048", + "--mamba-scheduler-strategy", + "extra_buffer_lazy", + "--attention-backend", + "triton", +] + + +def _make_args(*, page_size=1, track_interval=2): + return [ + *_COMMON_ARGS, + "--mamba-track-interval", + str(track_interval), + "--page-size", + str(page_size), + ] + + +class TestQwen3NextLazyExtraBuffer( + GSM8KMixin, KLDivergenceMixin, PrefixCacheBranchingMixin, DefaultServerBase +): + model = QWEN3_NEXT_MODEL + cache_chunk_size = 64 + gsm8k_accuracy_thres = 0.93 + kl_div_thres = 0.002 + other_args = _make_args(page_size=1, track_interval=2) + + +class TestQwen3NextLazyExtraBufferLargePage( + GSM8KMixin, KLDivergenceMixin, PrefixCacheBranchingMixin, DefaultServerBase +): + model = QWEN3_NEXT_MODEL + cache_chunk_size = 64 + gsm8k_accuracy_thres = 0.93 + kl_div_thres = 0.002 + other_args = _make_args(page_size=2, track_interval=2) + + +@unittest.skip("Manual-only: forces all lazy preallocs to fail") +class TestQwen3NextLazyExtraBufferAllocFail( + GSM8KMixin, KLDivergenceMixin, PrefixCacheBranchingMixin, DefaultServerBase +): + model = QWEN3_NEXT_MODEL + cache_chunk_size = 64 + gsm8k_accuracy_thres = 0.93 + kl_div_thres = 0.002 + other_args = _make_args(page_size=1, track_interval=2) + + @classmethod + def setUpClass(cls): + os.environ["SGLANG_TEST_MAMBA_LAZY_ALLOC_FAIL"] = "1" + os.environ["SGLANG_TEST_SKIP_CACHE_HIT_ASSERT"] = "1" + super().setUpClass() + + @classmethod + def tearDownClass(cls): + super().tearDownClass() + os.environ.pop("SGLANG_TEST_MAMBA_LAZY_ALLOC_FAIL", None) + os.environ.pop("SGLANG_TEST_SKIP_CACHE_HIT_ASSERT", None) + + +@unittest.skip("Manual-only: forces all lazy preallocs to fail") +class TestQwen3NextLazyExtraBufferLargePageAllocFail( + GSM8KMixin, KLDivergenceMixin, PrefixCacheBranchingMixin, DefaultServerBase +): + model = QWEN3_NEXT_MODEL + cache_chunk_size = 64 + gsm8k_accuracy_thres = 0.93 + kl_div_thres = 0.002 + other_args = _make_args(page_size=2, track_interval=2) + + @classmethod + def setUpClass(cls): + os.environ["SGLANG_TEST_MAMBA_LAZY_ALLOC_FAIL"] = "1" + os.environ["SGLANG_TEST_SKIP_CACHE_HIT_ASSERT"] = "1" + super().setUpClass() + + @classmethod + def tearDownClass(cls): + super().tearDownClass() + os.environ.pop("SGLANG_TEST_MAMBA_LAZY_ALLOC_FAIL", None) + os.environ.pop("SGLANG_TEST_SKIP_CACHE_HIT_ASSERT", None) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen3_next_models_fp4.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen3_next_models_fp4.py new file mode 100644 index 0000000000000000000000000000000000000000..40339a56052331a98d4ab0a25098d9ea41fc7ab1 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen3_next_models_fp4.py @@ -0,0 +1,34 @@ +import unittest + +from sglang.srt.utils import get_device_sm +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase + +register_cuda_ci(est_time=500, suite="nightly-4-gpu-b200", nightly=True) + +QWEN3_NEXT_MODEL_FP4 = "nvidia/Qwen3-Next-80B-A3B-Instruct-NVFP4" + + +@unittest.skipIf( + get_device_sm() < 100, "Test requires CUDA SM 100 or higher (Blackwell)" +) +class TestQwen3NextFp4(GSM8KMixin, DefaultServerBase): + model = QWEN3_NEXT_MODEL_FP4 + gsm8k_accuracy_thres = 0.93 + other_args = [ + "--tp-size", + "4", + "--chunked-prefill-size", + "2048", + "--quantization", + "modelopt_fp4", + "--mamba-scheduler-strategy", + "extra_buffer", + "--mamba-track-interval", + "128", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen3_next_models_mtp.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen3_next_models_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..4bc70e8f932666e4e01ab3ab2c5a58ab016c84a4 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_qwen3_next_models_mtp.py @@ -0,0 +1,75 @@ +import unittest + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.kl_divergence_kit import KLDivergenceMixin +from sglang.test.kits.prefix_cache_branching_kit import PrefixCacheBranchingMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase + +register_cuda_ci(est_time=290, stage="base-c", runner_config="4-gpu-h100") + +QWEN3_NEXT_MODEL = "Qwen/Qwen3-Next-80B-A3B-Instruct" + + +class TestQwen3NextMTPTopk( + GSM8KMixin, KLDivergenceMixin, PrefixCacheBranchingMixin, DefaultServerBase +): + # topk > 1 (tree) MTP on a hybrid-GDN model, on spec v2: the tree-aware mamba + # state update lives in the spec v2 verify path, so mamba + topk > 1 no longer + # falls back to spec v1. + model = QWEN3_NEXT_MODEL + cache_chunk_size = 64 + gsm8k_accuracy_thres = 0.93 + kl_div_thres = 0.008 + other_args = [ + "--trust-remote-code", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + "5", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "8", + "--mem-fraction-static", + "0.8", + "--tp", + "4", + "--chunked-prefill-size", + "2048", + "--mamba-scheduler-strategy", + "extra_buffer", + "--mamba-track-interval", + "128", + ] + + +class TestQwen3NextMTPV2(GSM8KMixin, KLDivergenceMixin, DefaultServerBase): + model = QWEN3_NEXT_MODEL + gsm8k_accuracy_thres = 0.93 + kl_div_thres = 0.0035 + other_args = [ + "--trust-remote-code", + "--speculative-algorithm", + "NEXTN", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--mem-fraction-static", + "0.8", + "--tp", + "4", + "--chunked-prefill-size", + "2048", + "--mamba-scheduler-strategy", + "extra_buffer", + "--mamba-track-interval", + "128", + ] + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/models_e2e/test_step3p5_flash_chain_mtp.py b/asian_ai/performance/SGLang/test/registered/models_e2e/test_step3p5_flash_chain_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..338bc7c0d2d7085ea1d3639e3005937ae470b482 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/models_e2e/test_step3p5_flash_chain_mtp.py @@ -0,0 +1,190 @@ +import unittest + +import numpy as np +import requests + +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.server_fixtures.default_fixture import DefaultServerBase +from sglang.test.test_utils import DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH + +register_cuda_ci(est_time=480, stage="extra-b", runner_config="8-gpu-h200") + +STEP3P5_FLASH_MODEL_PATH = "stepfun-ai/Step-3.5-Flash" + + +class TestStep3p5FlashChainMTP(GSM8KMixin, DefaultServerBase): + """Chain-style multi-layer EAGLE speculative decoding on Step-3.5-Flash. + + Step3p5ForCausalLM auto-enables multi-layer EAGLE and spec v2 when + --speculative-algorithm=EAGLE is set. The chain MTP propagation + (each MTP layer feeds its hidden states to the next) is activated + automatically for the Step3p5MTP draft architecture. + """ + + model = STEP3P5_FLASH_MODEL_PATH + timeout = DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 3 + other_args = [ + "--tp", + "8", + "--trust-remote-code", + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "3", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "4", + "--attention-backend", + "fa3", + "--enable-multi-layer-eagle", + "--mem-fraction-static", + "0.75", + "--chunked-prefill-size", + "4096", + "--model-loader-extra-config", + '{"enable_multithread_load": true, "num_threads": 64}', + ] + + gsm8k_accuracy_thres = 0.83 + gsm8k_accept_length_thres = 2.6 + + def test_logprob_spec_v2_match(self): + """Verify spec v2 decode logprobs match prefill scoring logprobs. + + Generate tokens with chain MTP spec v2, then score the same sequence + via prefill-only (no speculation). The two sets of logprobs should be + close, validating that spec v2 + multi-layer EAGLE computes logprobs + correctly. + """ + requests.get(self.base_url + "/flush_cache") + + top_k = 5 + probe_token_ids = [1, 2, 10, 100, 1000] + prompts = [ + "The capital of France is", + "Explain quantum computing in simple terms:", + ] + + for round_idx, prompt in enumerate(prompts): + with self.subTest(round=round_idx, prompt=prompt): + gen_res = requests.post( + self.base_url + "/generate", + json={ + "text": prompt, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 32, + "ignore_eos": True, + }, + "return_logprob": True, + "top_logprobs_num": top_k, + "token_ids_logprob": probe_token_ids, + "logprob_start_len": 0, + }, + ).json() + + decode_logprobs = gen_res["meta_info"]["output_token_logprobs"] + decode_top_logprobs = gen_res["meta_info"]["output_top_logprobs"] + decode_tid_logprobs = gen_res["meta_info"]["output_token_ids_logprobs"] + input_token_ids = [ + t[1] for t in gen_res["meta_info"]["input_token_logprobs"] + ] + output_token_ids = [t[1] for t in decode_logprobs] + num_prompt_tokens = gen_res["meta_info"]["prompt_tokens"] + + score_res = requests.post( + self.base_url + "/generate", + json={ + "input_ids": input_token_ids + output_token_ids, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 0, + }, + "return_logprob": True, + "top_logprobs_num": top_k, + "token_ids_logprob": probe_token_ids, + "logprob_start_len": 0, + }, + ).json() + + score_logprobs = score_res["meta_info"]["input_token_logprobs"][ + num_prompt_tokens: + ] + score_top_logprobs = score_res["meta_info"]["input_top_logprobs"][ + num_prompt_tokens: + ] + score_tid_logprobs = score_res["meta_info"]["input_token_ids_logprobs"][ + num_prompt_tokens: + ] + + self.assertEqual(len(decode_logprobs), len(score_logprobs)) + + decode_vals = np.array([t[0] for t in decode_logprobs]) + score_vals = np.array([t[0] for t in score_logprobs]) + max_diff = np.max(np.abs(decode_vals - score_vals)) + print( + f"[round {round_idx}] prompt={prompt!r} " + f"logprob max_diff={max_diff:.6f}" + ) + print(f"[round {round_idx}] decode_vals[-5:]={decode_vals[-5:]}") + print(f"[round {round_idx}] score_vals[-5:]={score_vals[-5:]}") + self.assertLess(max_diff, 0.255) + + # Top-k / probe tokens are not sampled, so they drift more than + # the chosen-token logprob under TP=8 + multi-layer EAGLE noise. + # Collect the diff distribution to see whether outliers are + # isolated tail tokens or systemic drift before asserting. + top_diffs = [] + for pos in range(len(decode_logprobs)): + dec_top = {t[1]: t[0] for t in decode_top_logprobs[pos]} + scr_top = {t[1]: t[0] for t in score_top_logprobs[pos]} + common_ids = set(dec_top.keys()) & set(scr_top.keys()) + self.assertGreater(len(common_ids), 0) + for tid in common_ids: + top_diffs.append(abs(dec_top[tid] - scr_top[tid])) + top_diffs_arr = np.array(top_diffs) + print( + f"[round {round_idx}] top-k diffs: " + f"n={len(top_diffs_arr)} " + f"max={top_diffs_arr.max():.4f} " + f"p99={np.percentile(top_diffs_arr, 99):.4f} " + f"p95={np.percentile(top_diffs_arr, 95):.4f} " + f"p50={np.percentile(top_diffs_arr, 50):.4f} " + f"mean={top_diffs_arr.mean():.4f}" + ) + + self.assertEqual(len(decode_tid_logprobs), len(score_tid_logprobs)) + tid_diffs = [] + for pos in range(len(decode_tid_logprobs)): + dec_tid = {t[1]: t[0] for t in decode_tid_logprobs[pos]} + scr_tid = {t[1]: t[0] for t in score_tid_logprobs[pos]} + self.assertEqual(set(dec_tid.keys()), set(scr_tid.keys())) + for tid in dec_tid: + tid_diffs.append(abs(dec_tid[tid] - scr_tid[tid])) + tid_diffs_arr = np.array(tid_diffs) + print( + f"[round {round_idx}] token_ids_logprob diffs: " + f"n={len(tid_diffs_arr)} " + f"max={tid_diffs_arr.max():.4f} " + f"p99={np.percentile(tid_diffs_arr, 99):.4f} " + f"p95={np.percentile(tid_diffs_arr, 95):.4f} " + f"p50={np.percentile(tid_diffs_arr, 50):.4f} " + f"mean={tid_diffs_arr.mean():.4f}" + ) + + # Bulk of the distribution must stay tight. Tail (max / p99) is + # dominated by very low-probability tokens whose logprobs are + # extremely sensitive to BF16 + TP=8 logsumexp noise — a real + # bug in chain MTP hidden state propagation would shift the + # median, not just the tail. + self.assertLess(np.percentile(top_diffs_arr, 50), 0.1) + self.assertLess(top_diffs_arr.mean(), 0.2) + self.assertLess(np.percentile(top_diffs_arr, 95), 0.4) + self.assertLess(np.percentile(tid_diffs_arr, 50), 0.2) + self.assertLess(tid_diffs_arr.mean(), 0.4) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_cutedsl_moe.py b/asian_ai/performance/SGLang/test/registered/moe/test_cutedsl_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..a4979d836bef60b4b988318adadfc9cc42460bd6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_cutedsl_moe.py @@ -0,0 +1,1325 @@ +# SPDX-License-Identifier: Apache-2.0 +import unittest + +import torch +from flashinfer import fp4_quantize, scaled_fp4_grouped_quantize +from torch.nn import functional as F + +from sglang.srt.layers.activation import SiluAndMul +from sglang.srt.layers.moe.flashinfer_cutedsl_moe import flashinfer_cutedsl_moe_masked +from sglang.test.ci.ci_register import register_cuda_ci + +try: + from flashinfer import CuteDslMoEWrapper + from flashinfer.cute_dsl.utils import convert_sf_to_mma_layout +except ImportError: + CuteDslMoEWrapper = None + convert_sf_to_mma_layout = None + +register_cuda_ci(est_time=24, stage="extra-b", runner_config="4-gpu-b200") + +SKIP_TEST = torch.cuda.get_device_capability() < (10, 0) +SKIP_REASON = "Nvfp4 Requires compute capability of 10 or above." + +kE2M1ToFloat = torch.tensor( + [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], dtype=torch.float32 +) + +FLOAT8_E4M3_MAX = 448.0 +FLOAT4_E2M1_MAX = 6.0 + + +def convert_swizzled_to_linear(a_sf_swizzled: torch.Tensor, m, k, block_size): + m_tiles = (m + 128 - 1) // 128 + f = block_size * 4 + k_tiles = (k + f - 1) // f + tmp = torch.reshape(a_sf_swizzled, (1, m_tiles, k_tiles, 32, 4, 4)) + tmp = torch.permute(tmp, (0, 1, 4, 3, 2, 5)) + out = tmp.reshape(m_tiles * 128, k_tiles * f // block_size) + return out[0:m, 0:k] + + +def dequantize_nvfp4_to_dtype( + tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16 +): + """Dequantize the fp4 tensor back to high precision.""" + # Two fp4 values are packed into one uint8. + assert tensor_fp4.dtype == torch.uint8 + m, packed_k = tensor_fp4.shape + k = packed_k * 2 + tensor_f32 = break_fp4_bytes(tensor_fp4, dtype) + tensor_f32 = tensor_f32.reshape(m, k // block_size, block_size) + tensor_sf = tensor_sf.view(torch.float8_e4m3fn) + tensor_sf = convert_swizzled_to_linear(tensor_sf, m, k, block_size) + tensor_sf_dtype = tensor_sf.to(torch.float32) / global_scale + + # scale the tensor + out = (tensor_f32 * tensor_sf_dtype.unsqueeze(-1)).reshape(m, k) + return out.to(dtype=dtype) + + +def break_fp4_bytes(a, dtype): + assert a.dtype == torch.uint8 + m, n = a.shape + + # Vectorized nibble processing + a_flat = a.flatten() + high = (a_flat & 0xF0) >> 4 # Upper nibbles + low = a_flat & 0x0F # Lower nibbles + + # Combine nibbles for batch processing + combined = torch.stack((low, high), dim=1).flatten() + + # Vectorized sign and magnitude extraction + signs = (combined & 0x08).to(torch.bool) # Sign bits + abs_vals = (combined & 0x07).to(torch.long) # Magnitude indices + + # Device-aware lookup and sign application + kE2M1 = kE2M1ToFloat.to(device=a.device) + values = kE2M1[abs_vals] * torch.where(signs, -1.0, 1.0) + + # Reshape to final form + return values.reshape(m, n * 2).to(dtype=dtype) + + +def _interleave_w13_halves( + x: torch.Tensor, group_size: int = 64, dim: int = -1 +) -> torch.Tensor: + """Interleave the two logical W13 halves for the CuteDSL wrapper layout.""" + sizes = x.size() + dim = dim % x.dim() + assert sizes[dim] % (group_size * 2) == 0 + prev_sizes = sizes[:dim] + post_sizes = sizes[dim + 1 :] + x = x.view(*prev_sizes, 2, sizes[dim] // (group_size * 2), group_size, *post_sizes) + x = x.transpose(dim, dim + 1).contiguous().view(*sizes) + return x + + +def _create_cutedsl_wrapper_tensors( + num_tokens: int, + hidden_size: int, + intermediate_size: int, + num_experts: int, + top_k: int, + device: str = "cuda", + seed: int = 42, +): + """Create quantized tensors for CuteDslMoEWrapper.run() (MMA layout, same as production). + + Returns quantized inputs for the wrapper **and** the original bf16 weights + needed to compute a numerical reference. Scale values (w1_alpha, w2_alpha, + fc2_input_scale) are derived from weight magnitudes so that scale-contract + bugs are caught. + """ + assert CuteDslMoEWrapper is not None and convert_sf_to_mma_layout is not None + torch.manual_seed(seed) + sf_vec_size = 16 + + x_bf16 = ( + torch.randn(num_tokens, hidden_size, dtype=torch.bfloat16, device=device) / 10 + ) + a1_gs = torch.tensor([1.0], device=device, dtype=torch.float32) + x_quantized, x_sf = fp4_quantize( + x_bf16, + global_scale=a1_gs, + sf_vec_size=sf_vec_size, + is_sf_swizzled_layout=False, + ) + x_sf = x_sf.unsqueeze(-1) + + router_logits = torch.randn(num_tokens, num_experts, device=device) + routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float) + routing_weights, selected_experts = torch.topk(routing_weights, top_k, dim=-1) + routing_weights = routing_weights / routing_weights.sum(dim=-1, keepdim=True) + routing_weights = routing_weights.float() + selected_experts = selected_experts.to(torch.int32) + + # --- GEMM1 weights --- + w1_bf16 = ( + torch.randn( + num_experts, + 2 * intermediate_size, + hidden_size, + dtype=torch.bfloat16, + device=device, + ) + / 10 + ) + w1_bf16_interleaved = _interleave_w13_halves(w1_bf16, group_size=64, dim=1) + w1_amax = w1_bf16.abs().amax(dim=(1, 2)).to(torch.float32) + w1_gs = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w1_amax.mean() + w1_gs = w1_gs.unsqueeze(0) + w1_flat = w1_bf16_interleaved.view(num_experts * 2 * intermediate_size, hidden_size) + w1_q_flat, w1_sf_flat = fp4_quantize( + w1_flat, + global_scale=w1_gs, + sf_vec_size=sf_vec_size, + is_sf_swizzled_layout=True, + ) + w1_q = w1_q_flat.view(num_experts, 2 * intermediate_size, hidden_size // 2) + w1_weight_sf = convert_sf_to_mma_layout( + w1_sf_flat, + m=2 * intermediate_size, + k=hidden_size, + num_groups=num_experts, + sf_vec_size=sf_vec_size, + ) + w1_alpha = 1.0 / (a1_gs * w1_gs).expand(num_experts) + + # --- GEMM2 weights --- + w2_bf16 = ( + torch.randn( + num_experts, + hidden_size, + intermediate_size, + dtype=torch.bfloat16, + device=device, + ) + / 10 + ) + w2_amax = w2_bf16.abs().amax(dim=(1, 2)).to(torch.float32) + w2_gs = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w2_amax.mean() + w2_gs = w2_gs.unsqueeze(0) + w2_flat = w2_bf16.view(num_experts * hidden_size, intermediate_size) + w2_q_flat, w2_sf_flat = fp4_quantize( + w2_flat, + global_scale=w2_gs, + sf_vec_size=sf_vec_size, + is_sf_swizzled_layout=True, + ) + w2_q = w2_q_flat.view(num_experts, hidden_size, intermediate_size // 2) + w2_weight_sf = convert_sf_to_mma_layout( + w2_sf_flat, + m=hidden_size, + k=intermediate_size, + num_groups=num_experts, + sf_vec_size=sf_vec_size, + ) + fc2_input_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w2_amax.mean() + fc2_input_scale = fc2_input_scale.unsqueeze(0) + w2_alpha = 1.0 / (fc2_input_scale * w2_gs).expand(num_experts) + + return { + "x": x_quantized, + "x_sf": x_sf, + "x_bf16": x_bf16, + "token_selected_experts": selected_experts, + "token_final_scales": routing_weights, + "w1_weight": w1_q, + "w1_weight_sf": w1_weight_sf, + "w1_weight_bf16": w1_bf16, + "w1_alpha": w1_alpha, + "fc2_input_scale": fc2_input_scale, + "w2_weight": w2_q, + "w2_weight_sf": w2_weight_sf, + "w2_weight_bf16": w2_bf16, + "w2_alpha": w2_alpha, + # Global scales needed by _quantize_local_expert_weights + "a1_gs": a1_gs, + "w1_gs": w1_gs, + "w2_gs": w2_gs, + } + + +def _quantize_local_expert_weights( + w1_bf16_local: torch.Tensor, + w2_bf16_local: torch.Tensor, + a1_gs: torch.Tensor, + w1_gs: torch.Tensor, + w2_gs: torch.Tensor, + fc2_input_scale: torch.Tensor, +): + """Independently quantize and MMA-convert a local expert weight shard. + + Mirrors the per-rank weight preprocessing that happens during model loading + in production (each rank holds [num_local_experts, ...] bf16 weights, + quantizes them, and calls convert_sf_to_mma_layout with + num_groups=num_local_experts). + """ + sf_vec_size = 16 + num_local_experts = w1_bf16_local.shape[0] + intermediate_size_2x = w1_bf16_local.shape[1] + hidden_size = w1_bf16_local.shape[2] + intermediate_size = w2_bf16_local.shape[2] + + # GEMM1: interleave -> quantize -> MMA layout + w1_interleaved = _interleave_w13_halves(w1_bf16_local, group_size=64, dim=1) + w1_flat = w1_interleaved.view(num_local_experts * intermediate_size_2x, hidden_size) + w1_q_flat, w1_sf_flat = fp4_quantize( + w1_flat, + global_scale=w1_gs, + sf_vec_size=sf_vec_size, + is_sf_swizzled_layout=True, + ) + w1_q = w1_q_flat.view(num_local_experts, intermediate_size_2x, hidden_size // 2) + w1_sf = convert_sf_to_mma_layout( + w1_sf_flat, + m=intermediate_size_2x, + k=hidden_size, + num_groups=num_local_experts, + sf_vec_size=sf_vec_size, + ) + w1_alpha = 1.0 / (a1_gs * w1_gs).expand(num_local_experts) + + # GEMM2: quantize -> MMA layout + w2_flat = w2_bf16_local.view(num_local_experts * hidden_size, intermediate_size) + w2_q_flat, w2_sf_flat = fp4_quantize( + w2_flat, + global_scale=w2_gs, + sf_vec_size=sf_vec_size, + is_sf_swizzled_layout=True, + ) + w2_q = w2_q_flat.view(num_local_experts, hidden_size, intermediate_size // 2) + w2_sf = convert_sf_to_mma_layout( + w2_sf_flat, + m=hidden_size, + k=intermediate_size, + num_groups=num_local_experts, + sf_vec_size=sf_vec_size, + ) + w2_alpha = 1.0 / (fc2_input_scale * w2_gs).expand(num_local_experts) + + return { + "w1_weight": w1_q, + "w1_weight_sf": w1_sf, + "w1_alpha": w1_alpha, + "w2_weight": w2_q, + "w2_weight_sf": w2_sf, + "w2_alpha": w2_alpha, + } + + +def _run_wrapper(wrapper, tensors, **overrides): + """Call wrapper.run() with the standard 11-arg dict from _create_cutedsl_wrapper_tensors.""" + kwargs = dict( + x=tensors["x"], + x_sf=tensors["x_sf"], + token_selected_experts=tensors["token_selected_experts"], + token_final_scales=tensors["token_final_scales"], + w1_weight=tensors["w1_weight"], + w1_weight_sf=tensors["w1_weight_sf"], + w1_alpha=tensors["w1_alpha"], + fc2_input_scale=tensors["fc2_input_scale"], + w2_weight=tensors["w2_weight"], + w2_weight_sf=tensors["w2_weight_sf"], + w2_alpha=tensors["w2_alpha"], + ) + kwargs.update(overrides) + return wrapper.run(**kwargs) + + +def _quant_dequant_fp4_reference( + tensor: torch.Tensor, + global_scale: torch.Tensor, + sf_vec_size: int = 16, +) -> torch.Tensor: + """Simulate FP4 quant-dequant roundtrip for reference computation.""" + from flashinfer.fp4_quantization import e2m1_and_ufp8sf_scale_to_float + + tensor_bf16 = tensor.to(torch.bfloat16) + fp4_packed, sf = fp4_quantize( + tensor_bf16, + global_scale=global_scale, + sf_vec_size=sf_vec_size, + is_sf_swizzled_layout=False, + ) + sf_uint8 = sf.view(torch.uint8).reshape(-1) + dequantized = e2m1_and_ufp8sf_scale_to_float( + fp4_packed.cpu(), + sf_uint8.cpu(), + (1.0 / global_scale).cpu(), + sf_vec_size=sf_vec_size, + ufp8_type=1, + is_sf_swizzled_layout=False, + ).to(tensor.device) + return dequantized.float() + + +def _compute_reference_moe_fp4( + hidden_states: torch.Tensor, + gemm1_weights: torch.Tensor, + gemm2_weights: torch.Tensor, + token_selected_experts: torch.Tensor, + token_final_scales: torch.Tensor, + num_experts: int, + top_k: int, + hidden_size: int, + intermediate_size: int, + fc2_input_scale: torch.Tensor, +) -> torch.Tensor: + """Pure-PyTorch MoE reference using bf16 weights (pre-interleave layout). + + gemm1_weights is [num_experts, 2*intermediate_size, hidden_size] with the + *original* (un-interleaved) layout: first half = linear, second half = gate. + """ + device = hidden_states.device + num_tokens = hidden_states.shape[0] + hidden_states = hidden_states.float() + gemm1_weights = gemm1_weights.float() + gemm2_weights = gemm2_weights.float() + + output = torch.zeros(num_tokens, hidden_size, dtype=torch.float32, device=device) + + for token_idx in range(num_tokens): + token_input = hidden_states[token_idx : token_idx + 1] + for k in range(top_k): + expert_idx = token_selected_experts[token_idx, k].item() + scale = token_final_scales[token_idx, k].item() + if expert_idx < 0 or expert_idx >= num_experts: + continue + + w1 = gemm1_weights[expert_idx] + gemm1_out = token_input @ w1.T + + linear = gemm1_out[:, :intermediate_size] + gate = gemm1_out[:, intermediate_size:] + swiglu_out = F.silu(gate) * linear + + if fc2_input_scale is not None: + swiglu_out = _quant_dequant_fp4_reference( + swiglu_out, fc2_input_scale, sf_vec_size=16 + ) + + w2 = gemm2_weights[expert_idx] + gemm2_out = swiglu_out @ w2.T + output[token_idx] += scale * gemm2_out.squeeze(0) + + return output + + +def compute_routing(router_logits: torch.Tensor, top_k: int): + routing_weights = torch.softmax(router_logits, dim=1, dtype=torch.float) + routing_weights, selected_experts = torch.topk(routing_weights, top_k, dim=-1) + routing_weights /= routing_weights.sum(dim=-1, keepdim=True) + routing_weights = routing_weights.float() + return routing_weights, selected_experts + + +def prepare_inputs( + hidden_states: torch.Tensor, + router_logits: torch.Tensor, + num_experts: int, + topk: int, +): + routing_weights, topk_idx = compute_routing(router_logits, topk) + + masked_m = [] + for i in range(num_experts): + mask = topk_idx.view(-1) == i + masked_m.append(mask.sum()) + + masked_m = torch.tensor(masked_m, dtype=torch.int32) + hidden_states_3d = torch.empty( + (num_experts, max(masked_m), hidden_states.shape[1]), dtype=hidden_states.dtype + ) + for i in range(num_experts): + hidden_states_3d[i, : masked_m[i], :] = hidden_states[topk_idx.view(-1) == i] + + return hidden_states_3d, masked_m, topk_idx, routing_weights + + +# Reference implementation of torch_moe +def torch_moe(a, w1, w2, score, topk, expert_map): + B, D = a.shape + a = a.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D) + out = torch.zeros(B * topk, w2.shape[1], dtype=a.dtype, device=a.device) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + topk_weight = topk_weight.view(-1) + topk_ids = topk_ids.view(-1) + if expert_map is not None: + topk_ids = expert_map[topk_ids] + for i in range(w1.shape[0]): + mask = topk_ids == i + if mask.sum(): + out[mask] = SiluAndMul()(a[mask] @ w1[i].transpose(0, 1)) @ w2[i].transpose( + 0, 1 + ) + return ( + out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype) + ).sum(dim=1) + + +def torch_moe_nvfp4(a, w1, w2, topk, topk_weight, topk_ids): + B, D = a.shape + a = a.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D) + out = torch.zeros(B * topk, w2.shape[1], dtype=a.dtype, device=a.device) + + topk_weight = topk_weight.view(-1) + topk_ids = topk_ids.view(-1) + + for i in range(w1.shape[0]): + mask = topk_ids == i + if mask.sum(): + m = w1[i].shape[0] + assert m % 2 == 0 + # The first and second W13 halves feed the two SwiGLU branches. + w3_expert, w1_expert = w1[i][m // 2 :, :], w1[i][: m // 2, :] + inter = F.silu(a[mask] @ w1_expert.t()) * (a[mask] @ w3_expert.t()) + inter_gs = torch.tensor(1.0).cuda() + inter_q, inter_blockscale = fp4_quantize(inter, inter_gs) + inter = dequantize_nvfp4_to_dtype( + inter_q, + inter_blockscale, + inter_gs, + dtype=inter.dtype, + device=inter.device, + block_size=16, + ).cuda() + out[mask] = inter @ w2[i].transpose(0, 1) + return ( + out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype) + ).sum(dim=1) + + +class TestCuteDslV2(unittest.TestCase): + """Correctness tests for the CuteDSL v2 (standard) path. + + The v2 path uses CuteDslMoEWrapper with: + - W13 in [Up, Gate] order (load_up_proj_weight_first = True) + - W13 interleaved in 64-row chunks (interleave_w13_halves) + - MMA-layout blockscales (convert_sf_to_mma_layout) + + This is the path used with --moe-runner-backend flashinfer_cutedsl and + --moe-a2a-backend none or flashinfer (i.e. NOT deepep). + """ + + @unittest.skipIf(SKIP_TEST, SKIP_REASON) + @unittest.skipIf( + CuteDslMoEWrapper is None or convert_sf_to_mma_layout is None, + "CuteDslMoEWrapper / convert_sf_to_mma_layout not available", + ) + def test_v2_wrapper_correctness(self): + """CuteDslMoEWrapper.run() with MMA-layout tensors vs PyTorch reference.""" + test_cases = [ + # (num_tokens, hidden_size, intermediate_size, num_experts, top_k) + # Minimum dimensions match FlashInfer's test_wrapper_accuracy: + # num_experts >= 256, hidden_size >= 256, intermediate_size >= 512, + # num_tokens >= 128. The CuteDSL GEMM kernels have tile-size + # constraints that make smaller dimensions unreliable. + (128, 256, 512, 256, 2), + (128, 256, 512, 256, 8), + (256, 256, 512, 256, 4), + ] + + for ( + num_tokens, + hidden_size, + intermediate_size, + num_experts, + top_k, + ) in test_cases: + with self.subTest( + num_tokens=num_tokens, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + top_k=top_k, + ): + tensors = _create_cutedsl_wrapper_tensors( + num_tokens=num_tokens, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + num_experts=num_experts, + top_k=top_k, + ) + + wrapper = CuteDslMoEWrapper( + num_experts=num_experts, + top_k=top_k, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + use_cuda_graph=False, + ) + + with torch.no_grad(): + out = _run_wrapper(wrapper, tensors) + + self.assertEqual(out.shape, (num_tokens, hidden_size)) + self.assertEqual(out.dtype, torch.bfloat16) + self.assertFalse( + torch.isnan(out).any().item() or torch.isinf(out).any().item(), + "Output contains NaN or Inf", + ) + + ref_output = _compute_reference_moe_fp4( + hidden_states=tensors["x_bf16"].float().cuda(), + gemm1_weights=tensors["w1_weight_bf16"].float().cuda(), + gemm2_weights=tensors["w2_weight_bf16"].float().cuda(), + token_selected_experts=tensors["token_selected_experts"], + token_final_scales=tensors["token_final_scales"], + num_experts=num_experts, + top_k=top_k, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + fc2_input_scale=tensors["fc2_input_scale"], + ) + + out_f32 = out.float() + ref_f32 = ref_output.float() + output_scale = max(ref_f32.std().item(), 0.01) + atol = max(0.1, 3.0 * output_scale) + rtol = 0.85 + abs_diff = torch.abs(out_f32 - ref_f32) + rel_diff = abs_diff / (torch.abs(ref_f32) + 1e-8) + within_tol = (abs_diff < atol) | (rel_diff < rtol) + pct_within = within_tol.float().mean().item() + self.assertGreaterEqual( + pct_within, + 0.925, + f"Only {pct_within * 100:.2f}% of elements within tolerance " + f"(atol={atol:.4f})", + ) + + @unittest.skipIf(SKIP_TEST, SKIP_REASON) + @unittest.skipIf( + CuteDslMoEWrapper is None or convert_sf_to_mma_layout is None, + "CuteDslMoEWrapper / convert_sf_to_mma_layout not available", + ) + def test_v2_cuda_graph_parity(self): + """Verify non-graph and cuda_graph v2 wrappers produce identical results. + + Also checks both match the pure-PyTorch reference, and that a second + cuda_graph pass reuses buffers deterministically (subsumes the former + cuda_graph check). + """ + test_cases = [ + # (num_tokens, hidden_size, intermediate_size, num_experts, top_k) + (128, 256, 512, 256, 2), + (256, 256, 512, 256, 4), + ] + + for ( + num_tokens, + hidden_size, + intermediate_size, + num_experts, + top_k, + ) in test_cases: + with self.subTest( + num_tokens=num_tokens, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + top_k=top_k, + ): + tensors = _create_cutedsl_wrapper_tensors( + num_tokens=num_tokens, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + num_experts=num_experts, + top_k=top_k, + ) + + wrapper_args = dict( + num_experts=num_experts, + top_k=top_k, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + ) + wrapper_no_graph = CuteDslMoEWrapper( + **wrapper_args, use_cuda_graph=False + ) + wrapper_graph = CuteDslMoEWrapper( + **wrapper_args, + use_cuda_graph=True, + max_num_tokens=num_tokens, + ) + + with torch.no_grad(): + out_no_graph = _run_wrapper(wrapper_no_graph, tensors) + out_graph = _run_wrapper(wrapper_graph, tensors) + out_graph2 = _run_wrapper(wrapper_graph, tensors) + + torch.testing.assert_close( + out_no_graph, + out_graph, + atol=1e-2, + rtol=1e-2, + msg="non-graph vs cuda_graph wrapper outputs diverge", + ) + torch.testing.assert_close( + out_graph, + out_graph2, + atol=1e-5, + rtol=1e-5, + msg="second cuda_graph pass should reuse buffers identically", + ) + + ref_output = _compute_reference_moe_fp4( + hidden_states=tensors["x_bf16"].float().cuda(), + gemm1_weights=tensors["w1_weight_bf16"].float().cuda(), + gemm2_weights=tensors["w2_weight_bf16"].float().cuda(), + token_selected_experts=tensors["token_selected_experts"], + token_final_scales=tensors["token_final_scales"], + num_experts=num_experts, + top_k=top_k, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + fc2_input_scale=tensors["fc2_input_scale"], + ) + + out_f32 = out_graph.float() + ref_f32 = ref_output.float() + output_scale = max(ref_f32.std().item(), 0.01) + atol = max(0.1, 3.0 * output_scale) + rtol = 0.85 + abs_diff = torch.abs(out_f32 - ref_f32) + rel_diff = abs_diff / (torch.abs(ref_f32) + 1e-8) + within_tol = (abs_diff < atol) | (rel_diff < rtol) + pct_within = within_tol.float().mean().item() + self.assertGreaterEqual( + pct_within, + 0.925, + f"graph vs reference: only {pct_within * 100:.2f}% within tol", + ) + + @unittest.skipIf(SKIP_TEST, SKIP_REASON) + @unittest.skipIf( + CuteDslMoEWrapper is None or convert_sf_to_mma_layout is None, + "CuteDslMoEWrapper / convert_sf_to_mma_layout not available", + ) + def test_v2_ep_sharded_allreduce(self): + """Verify EP-sharded v2 execution: partial outputs from EP ranks sum to full result. + + Simulates the EP=TP all-reduce pattern used by the CuteDSL moe_runner when + ep_size > 1 and moe_a2a_backend=none. Each "rank" runs a v2 wrapper with + num_local_experts < num_experts and a corresponding local_expert_offset, + receiving only the local slice of weights/scales/alphas -- matching the + real runtime contract where each rank holds only its own expert partition. + The partial outputs are summed (simulating tensor_model_parallel_all_reduce) + and compared against a single wrapper processing all experts. + """ + test_cases = [ + # (num_tokens, hidden_size, intermediate_size, num_experts, top_k, ep_size) + # Dimensions match FlashInfer's minimum wrapper requirements. + (128, 256, 512, 256, 2, 2), + (128, 256, 512, 256, 2, 4), + (128, 256, 512, 256, 8, 8), + ] + + for ( + num_tokens, + hidden_size, + intermediate_size, + num_experts, + top_k, + ep_size, + ) in test_cases: + with self.subTest( + num_tokens=num_tokens, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + top_k=top_k, + ep_size=ep_size, + ): + assert num_experts % ep_size == 0 + num_local_experts = num_experts // ep_size + + tensors = _create_cutedsl_wrapper_tensors( + num_tokens=num_tokens, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + num_experts=num_experts, + top_k=top_k, + ) + + # Full-expert baseline (EP=1): all experts on one "rank" + wrapper_full = CuteDslMoEWrapper( + num_experts=num_experts, + top_k=top_k, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + use_cuda_graph=False, + ) + with torch.no_grad(): + out_full = _run_wrapper(wrapper_full, tensors) + + # EP-sharded: each rank independently quantizes its local + # bf16 weight shard and calls convert_sf_to_mma_layout with + # num_groups=num_local_experts — matching the real per-rank + # weight preprocessing in the CuteDSL moe_runner path. + accumulated = torch.zeros_like(out_full) + for rank in range(ep_size): + lo = rank * num_local_experts + hi = lo + num_local_experts + + local_tensors = _quantize_local_expert_weights( + w1_bf16_local=tensors["w1_weight_bf16"][lo:hi], + w2_bf16_local=tensors["w2_weight_bf16"][lo:hi], + a1_gs=tensors["a1_gs"], + w1_gs=tensors["w1_gs"], + w2_gs=tensors["w2_gs"], + fc2_input_scale=tensors["fc2_input_scale"], + ) + + wrapper_shard = CuteDslMoEWrapper( + num_experts=num_experts, + top_k=top_k, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + use_cuda_graph=False, + num_local_experts=num_local_experts, + local_expert_offset=lo, + ) + with torch.no_grad(): + partial = _run_wrapper(wrapper_shard, tensors, **local_tensors) + accumulated += partial + + torch.testing.assert_close( + out_full, + accumulated, + atol=1e-2, + rtol=1e-2, + msg=( + f"EP-sharded all-reduce mismatch " + f"(ep_size={ep_size}, tokens={num_tokens})" + ), + ) + + +class TestCuteDslV1(unittest.TestCase): + """Correctness tests for the CuteDSL v1 (deepep) path. + + The v1 path (flashinfer_cutedsl_moe_masked, dispatched via the + @register_fused_func("deepep", "flashinfer_cutedsl") MoeRunner entry) + is used when --moe-runner-backend flashinfer_cutedsl and --moe-a2a-backend + deepep are combined. It expects: + - W13 in default [Gate, Up] order (load_up_proj_weight_first = False) + - W13 NOT interleaved (no interleave_w13_halves) + - Swizzled blockscales (w13_blockscale_swizzled, not MMA layout) + + A regression that accidentally applies v2 transforms (interleave, + [Up,Gate] flip, MMA blockscales) to v1 weights would cause these tests + to fail with numerical mismatch against the PyTorch reference. + + The companion v2 (standard) path correctness is covered by TestCuteDslV2. + """ + + @unittest.skipIf(SKIP_TEST, SKIP_REASON) + def test_v1_masked_kernel_bf16_input(self): + """V1 masked kernel with BF16 activations (kernel quantizes internally). + + Weights are in v1 layout: [Gate, Up] order, non-interleaved, swizzled + blockscales. This mirrors the production path when DeepEP dispatch + does NOT pre-quantize activations (MOE_NVFP4_DISPATCH is off). + """ + test_cases = [ + # (bs, hidden_dim, inter_dim, topk) + (2, 128, 256, 1), + (2, 128, 256, 2), + (2, 128, 256, 4), + (16, 128, 512, 1), + (16, 128, 512, 2), + (16, 128, 512, 4), + ] + + for bs, hidden_dim, inter_dim, topk in test_cases: + with self.subTest( + bs=bs, hidden_dim=hidden_dim, inter_dim=inter_dim, topk=topk + ): + with torch.inference_mode(): + torch.manual_seed(42) + device = "cuda" + num_experts = 8 + hidden_states = ( + torch.randn(bs, hidden_dim, dtype=torch.bfloat16, device=device) + / 5.0 + ) + w1 = ( + torch.randn( + num_experts, + 2 * inter_dim, + hidden_dim, + dtype=torch.bfloat16, + device=device, + ) + / 10.0 + ) + w2 = ( + torch.randn( + num_experts, + hidden_dim, + inter_dim, + dtype=torch.bfloat16, + device=device, + ) + / 10.0 + ) + router_logits = torch.randn(bs, num_experts, dtype=torch.float32) + + hidden_states_expanded = ( + hidden_states.view(bs, -1, hidden_dim) + .repeat(1, topk, 1) + .reshape(-1, hidden_dim) + ) + hidden_states_3d, masked_m, topk_idx, routing_weights = ( + prepare_inputs( + hidden_states_expanded, router_logits, num_experts, topk + ) + ) + + w1_amax = w1.abs().amax(dim=(1, 2)).to(torch.float32).to(w1.device) + w2_amax = w2.abs().amax(dim=(1, 2)).to(torch.float32).to(w2.device) + input_global_scale = torch.ones( + (num_experts,), dtype=torch.float32, device=hidden_states.device + ) + + w1_global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w1_amax + w2_global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w2_amax + a2_global_scale = torch.ones( + (num_experts,), dtype=torch.float32, device=hidden_states.device + ) + + w1_fp4, w1_blockscale = scaled_fp4_grouped_quantize( + w1, + torch.ones(num_experts, dtype=torch.int32, device=w1.device) + * 2 + * inter_dim, + w1_global_scale, + ) + w2_fp4, w2_blockscale = scaled_fp4_grouped_quantize( + w2, + torch.ones(num_experts, dtype=torch.int32, device=w2.device) + * hidden_dim, + w2_global_scale, + ) + + w1_alpha = 1.0 / (input_global_scale * w1_global_scale) + w2_alpha = 1.0 / (a2_global_scale * w2_global_scale) + + out = flashinfer_cutedsl_moe_masked( + (hidden_states_3d.to(hidden_states.device), None), + input_global_scale, + w1_fp4.permute(2, 0, 1), + w1_blockscale, + w1_alpha, + w2_fp4.permute(2, 0, 1), + a2_global_scale, + w2_blockscale, + w2_alpha, + masked_m.to(hidden_states.device), + ) + + a_global_scale = input_global_scale[:1] + a_fp4, a_scale_interleaved = fp4_quantize( + hidden_states, a_global_scale + ) + a_in_dtype = dequantize_nvfp4_to_dtype( + a_fp4, + a_scale_interleaved, + a_global_scale, + dtype=hidden_states.dtype, + device=hidden_states.device, + block_size=16, + ) + w1_d = torch.empty( + (num_experts, 2 * inter_dim, hidden_dim), + device=w1.device, + dtype=w1.dtype, + ) + w2_d = torch.empty( + (num_experts, hidden_dim, inter_dim), + device=w2.device, + dtype=w2.dtype, + ) + + for idx in range(0, num_experts): + w1_fp4_sliced, w1_blockscale_sliced = fp4_quantize( + w1[idx], w1_global_scale[idx] + ) + w2_fp4_sliced, w2_blockscale_sliced = fp4_quantize( + w2[idx], w2_global_scale[idx] + ) + w1_d[idx] = dequantize_nvfp4_to_dtype( + w1_fp4_sliced, + w1_blockscale_sliced, + w1_global_scale[idx], + dtype=w1.dtype, + device=w1.device, + block_size=16, + ) + w2_d[idx] = dequantize_nvfp4_to_dtype( + w2_fp4_sliced, + w2_blockscale_sliced, + w2_global_scale[idx], + dtype=w2.dtype, + device=w2.device, + block_size=16, + ) + + ref_output = torch_moe_nvfp4( + a_in_dtype, + w1_d, + w2_d, + topk, + routing_weights.to(a_in_dtype.device), + topk_idx.to(a_in_dtype.device), + ) + out_weighted = torch.zeros_like( + ref_output, device=out.device, dtype=out.dtype + ) + + positions = torch.nonzero(masked_m[topk_idx], as_tuple=False) + rows, cols = positions[:, 0], positions[:, 1] + experts = topk_idx[rows, cols] + for i in range(num_experts): + mask = experts == i + if mask.any(): + idx = torch.nonzero(mask, as_tuple=False).squeeze(-1) + r, c = rows[idx], cols[idx] + out_weighted[r] += out[i, : len(r), :] * routing_weights[ + r, c + ].to(out.device).unsqueeze(-1) + torch.testing.assert_close( + out_weighted.cpu(), ref_output.cpu(), atol=5e-2, rtol=5e-2 + ) + + @unittest.skipIf(SKIP_TEST, SKIP_REASON) + def test_v1_masked_kernel_rejects_v2_w13_layout(self): + """Applying the v2 W13 transform must break the v1 masked path.""" + with torch.inference_mode(): + torch.manual_seed(42) + device = "cuda" + num_experts, bs, hidden_dim, inter_dim, topk = 8, 16, 128, 512, 2 + + hidden_states = ( + torch.randn(bs, hidden_dim, dtype=torch.bfloat16, device=device) / 5.0 + ) + w1 = ( + torch.randn( + num_experts, + 2 * inter_dim, + hidden_dim, + dtype=torch.bfloat16, + device=device, + ) + / 10.0 + ) + w2 = ( + torch.randn( + num_experts, + hidden_dim, + inter_dim, + dtype=torch.bfloat16, + device=device, + ) + / 10.0 + ) + router_logits = torch.randn(bs, num_experts, dtype=torch.float32) + + hidden_expanded = ( + hidden_states.view(bs, -1, hidden_dim) + .repeat(1, topk, 1) + .reshape(-1, hidden_dim) + ) + hidden_3d, masked_m, topk_idx, routing_weights = prepare_inputs( + hidden_expanded, router_logits, num_experts, topk + ) + + input_global_scale = torch.ones( + (num_experts,), dtype=torch.float32, device=device + ) + w1_amax = w1.abs().amax(dim=(1, 2)).to(torch.float32) + w2_amax = w2.abs().amax(dim=(1, 2)).to(torch.float32) + w1_global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w1_amax + w2_global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w2_amax + a2_global_scale = torch.ones( + (num_experts,), dtype=torch.float32, device=device + ) + + expert_sizes_w1 = ( + torch.ones(num_experts, dtype=torch.int32, device=device) + * 2 + * inter_dim + ) + expert_sizes_w2 = ( + torch.ones(num_experts, dtype=torch.int32, device=device) * hidden_dim + ) + w1_fp4, w1_blockscale = scaled_fp4_grouped_quantize( + w1, expert_sizes_w1, w1_global_scale + ) + w2_fp4, w2_blockscale = scaled_fp4_grouped_quantize( + w2, expert_sizes_w2, w2_global_scale + ) + + # The v2 standard path flips W13 to [Up, Gate] order and interleaves + # 64-row chunks for CuteDslMoEWrapper. The v1 masked kernel must not + # receive that transformed layout. + w1_v2 = torch.cat((w1[:, inter_dim:, :], w1[:, :inter_dim, :]), dim=1) + w1_v2 = _interleave_w13_halves(w1_v2, group_size=64, dim=1).contiguous() + w1_fp4_v2, w1_blockscale_v2 = scaled_fp4_grouped_quantize( + w1_v2, expert_sizes_w1, w1_global_scale + ) + + w1_alpha = 1.0 / (input_global_scale * w1_global_scale) + w2_alpha = 1.0 / (a2_global_scale * w2_global_scale) + + out_v1 = flashinfer_cutedsl_moe_masked( + (hidden_3d.to(device), None), + input_global_scale, + w1_fp4.permute(2, 0, 1), + w1_blockscale, + w1_alpha, + w2_fp4.permute(2, 0, 1), + a2_global_scale, + w2_blockscale, + w2_alpha, + masked_m.to(device), + ) + out_v2_layout = flashinfer_cutedsl_moe_masked( + (hidden_3d.to(device), None), + input_global_scale, + w1_fp4_v2.permute(2, 0, 1), + w1_blockscale_v2, + w1_alpha, + w2_fp4.permute(2, 0, 1), + a2_global_scale, + w2_blockscale, + w2_alpha, + masked_m.to(device), + ) + + a_global_scale = input_global_scale[:1] + a_fp4, a_scale_interleaved = fp4_quantize(hidden_states, a_global_scale) + a_in_dtype = dequantize_nvfp4_to_dtype( + a_fp4, + a_scale_interleaved, + a_global_scale, + dtype=hidden_states.dtype, + device=device, + block_size=16, + ) + w1_d = torch.empty( + (num_experts, 2 * inter_dim, hidden_dim), + device=device, + dtype=w1.dtype, + ) + w2_d = torch.empty( + (num_experts, hidden_dim, inter_dim), device=device, dtype=w2.dtype + ) + + for idx in range(num_experts): + w1_fp4_sliced, w1_blockscale_sliced = fp4_quantize( + w1[idx], w1_global_scale[idx] + ) + w2_fp4_sliced, w2_blockscale_sliced = fp4_quantize( + w2[idx], w2_global_scale[idx] + ) + w1_d[idx] = dequantize_nvfp4_to_dtype( + w1_fp4_sliced, + w1_blockscale_sliced, + w1_global_scale[idx], + dtype=w1.dtype, + device=device, + block_size=16, + ) + w2_d[idx] = dequantize_nvfp4_to_dtype( + w2_fp4_sliced, + w2_blockscale_sliced, + w2_global_scale[idx], + dtype=w2.dtype, + device=device, + block_size=16, + ) + + ref_output = torch_moe_nvfp4( + a_in_dtype, + w1_d, + w2_d, + topk, + routing_weights.to(device), + topk_idx.to(device), + ) + + positions = torch.nonzero(masked_m[topk_idx], as_tuple=False) + rows, cols = positions[:, 0], positions[:, 1] + experts = topk_idx[rows, cols] + + def combine_weighted_output(out: torch.Tensor) -> torch.Tensor: + out_weighted = torch.zeros_like( + ref_output, device=device, dtype=out.dtype + ) + for i in range(num_experts): + mask = experts == i + if mask.any(): + idx = torch.nonzero(mask, as_tuple=False).squeeze(-1) + r, c = rows[idx], cols[idx] + out_weighted[r] += out[i, : len(r), :] * routing_weights[ + r, c + ].to(device).unsqueeze(-1) + return out_weighted + + out_v1_weighted = combine_weighted_output(out_v1) + out_v2_layout_weighted = combine_weighted_output(out_v2_layout) + + torch.testing.assert_close( + out_v1_weighted.cpu(), ref_output.cpu(), atol=5e-2, rtol=5e-2 + ) + with self.assertRaises(AssertionError): + torch.testing.assert_close( + out_v2_layout_weighted.cpu(), + ref_output.cpu(), + atol=5e-2, + rtol=5e-2, + ) + + @unittest.skipIf(SKIP_TEST, SKIP_REASON) + def test_v1_masked_kernel_fp4_input(self): + """V1 masked kernel with pre-quantized FP4 activations. + + In production with MOE_NVFP4_DISPATCH, the DeepEP dispatcher quantizes + activations during dispatch. The v1 kernel receives + hidden_states=(fp4_data, blockscale) instead of (bf16_data, None) and + skips its internal scaled_fp4_grouped_quantize call. + """ + with torch.inference_mode(): + torch.manual_seed(42) + device = "cuda" + num_experts, bs, hidden_dim, inter_dim, topk = 8, 16, 128, 512, 2 + + hidden_states = ( + torch.randn(bs, hidden_dim, dtype=torch.bfloat16, device=device) / 5.0 + ) + w1 = ( + torch.randn( + num_experts, + 2 * inter_dim, + hidden_dim, + dtype=torch.bfloat16, + device=device, + ) + / 10.0 + ) + w2 = ( + torch.randn( + num_experts, + hidden_dim, + inter_dim, + dtype=torch.bfloat16, + device=device, + ) + / 10.0 + ) + router_logits = torch.randn(bs, num_experts, dtype=torch.float32) + + hidden_expanded = ( + hidden_states.view(bs, -1, hidden_dim) + .repeat(1, topk, 1) + .reshape(-1, hidden_dim) + ) + hidden_3d, masked_m, topk_idx, routing_weights = prepare_inputs( + hidden_expanded, router_logits, num_experts, topk + ) + + input_gs = torch.ones(num_experts, dtype=torch.float32, device=device) + w1_amax = w1.abs().amax(dim=(1, 2)).to(torch.float32) + w2_amax = w2.abs().amax(dim=(1, 2)).to(torch.float32) + w1_gs = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w1_amax + w2_gs = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / w2_amax + a2_gs = torch.ones(num_experts, dtype=torch.float32, device=device) + + expert_sizes_w1 = ( + torch.ones(num_experts, dtype=torch.int32, device=device) + * 2 + * inter_dim + ) + expert_sizes_w2 = ( + torch.ones(num_experts, dtype=torch.int32, device=device) * hidden_dim + ) + w1_fp4, w1_bs = scaled_fp4_grouped_quantize(w1, expert_sizes_w1, w1_gs) + w2_fp4, w2_bs = scaled_fp4_grouped_quantize(w2, expert_sizes_w2, w2_gs) + w1_alpha = 1.0 / (input_gs * w1_gs) + w2_alpha = 1.0 / (a2_gs * w2_gs) + + # Pre-quantize activations -- simulates what DeepEP dispatch does + # when MOE_NVFP4_DISPATCH is enabled. The kernel expects + # (m, k//2, num_experts) layout from scaled_fp4_grouped_quantize. + a_q, a_q_sf = scaled_fp4_grouped_quantize( + hidden_3d.to(device), + masked_m.to(device), + input_gs, + ) + + out = flashinfer_cutedsl_moe_masked( + (a_q, a_q_sf), + input_gs, + w1_fp4.permute(2, 0, 1), + w1_bs, + w1_alpha, + w2_fp4.permute(2, 0, 1), + a2_gs, + w2_bs, + w2_alpha, + masked_m.to(device), + ) + + # PyTorch reference (same as the bf16 input test) + a_gs = input_gs[:1] + a_fp4, a_scale = fp4_quantize(hidden_states, a_gs) + a_deq = dequantize_nvfp4_to_dtype( + a_fp4, + a_scale, + a_gs, + dtype=torch.bfloat16, + device=device, + block_size=16, + ) + w1_d = torch.empty( + (num_experts, 2 * inter_dim, hidden_dim), + device=device, + dtype=w1.dtype, + ) + w2_d = torch.empty( + (num_experts, hidden_dim, inter_dim), device=device, dtype=w2.dtype + ) + for idx in range(num_experts): + w1_fp4_sliced, w1_blockscale_sliced = fp4_quantize(w1[idx], w1_gs[idx]) + w2_fp4_sliced, w2_blockscale_sliced = fp4_quantize(w2[idx], w2_gs[idx]) + w1_d[idx] = dequantize_nvfp4_to_dtype( + w1_fp4_sliced, + w1_blockscale_sliced, + w1_gs[idx], + dtype=w1.dtype, + device=device, + block_size=16, + ) + w2_d[idx] = dequantize_nvfp4_to_dtype( + w2_fp4_sliced, + w2_blockscale_sliced, + w2_gs[idx], + dtype=w2.dtype, + device=device, + block_size=16, + ) + ref = torch_moe_nvfp4( + a_deq, + w1_d, + w2_d, + topk, + routing_weights.to(device), + topk_idx.to(device), + ) + + out_weighted = torch.zeros_like(ref, device=device) + positions = torch.nonzero(masked_m[topk_idx], as_tuple=False) + rows, cols = positions[:, 0], positions[:, 1] + experts = topk_idx[rows, cols] + for i in range(num_experts): + mask = experts == i + if mask.any(): + idx = torch.nonzero(mask, as_tuple=False).squeeze(-1) + r, c = rows[idx], cols[idx] + out_weighted[r] += out[i, : len(r), :] * routing_weights[r, c].to( + device + ).unsqueeze(-1) + + torch.testing.assert_close( + out_weighted.cpu(), + ref.cpu(), + atol=5e-2, + rtol=5e-2, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_flashinfer_a2a_cutedsl_v2.py b/asian_ai/performance/SGLang/test/registered/moe/test_flashinfer_a2a_cutedsl_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..50a1c04c83e5b9f2e667e9eb2e6d0d6fa97a0e62 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_flashinfer_a2a_cutedsl_v2.py @@ -0,0 +1,89 @@ +"""Test CuteDSL FP4 MoE + FlashInfer alltoall on B200 with DP attention. + +Config: Qwen3.5-397B-A17B-NVFP4, B200x4, EP=4 DP=4, cutedsl + flashinfer a2a. +""" + +import unittest +from types import SimpleNamespace + +import torch + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=600, stage="extra-b", runner_config="4-gpu-b200") + +MODEL = "nvidia/Qwen3.5-397B-A17B-NVFP4" + +SKIP_TEST = torch.cuda.get_device_capability() < (10, 0) +SKIP_REASON = "Requires Blackwell (B200, sm_100a) or above." + + +@unittest.skipIf(SKIP_TEST, SKIP_REASON) +class TestCuteDslFlashinferA2A(CustomTestCase): + """CuteDSL FP4 MoE + FlashInfer one-sided alltoall + DP4 EP4 on B200.""" + + @classmethod + def setUpClass(cls): + cls.model = MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 3, + other_args=[ + "--trust-remote-code", + "--quantization", + "modelopt_fp4", + "--tp", + "4", + "--ep-size", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--enable-dp-lm-head", + "--moe-runner-backend", + "flashinfer_cutedsl", + "--moe-a2a-backend", + "flashinfer", + "--max-prefill-tokens", + "4096", + "--disable-radix-cache", + "--disable-flashinfer-autotune", + "--watchdog-timeout", + "900", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + eval_name="gsm8k", + num_examples=1319, + max_tokens=10240, + repeat=1, + num_threads=1319, + num_shots=8, + temperature=0.6, + top_p=0.95, + top_k=20, + ) + metrics = run_eval(args) + print(metrics) + self.assertGreater(metrics["score"], 0.90) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_flashinfer_a2a_cutlass.py b/asian_ai/performance/SGLang/test/registered/moe/test_flashinfer_a2a_cutlass.py new file mode 100644 index 0000000000000000000000000000000000000000..432e53d1daf608fabfac7bae91cb7aca2b305400 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_flashinfer_a2a_cutlass.py @@ -0,0 +1,93 @@ +"""Test FlashInfer Cutlass BF16 MoE + FlashInfer alltoall on B200 with DP attention. + +Config: Qwen3-30B-A3B, B200x4, EP=4 DP=4, flashinfer cutlass + flashinfer a2a. +""" + +import os +import unittest +from types import SimpleNamespace + +import torch + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci( + est_time=600, + stage="extra-b", + runner_config="4-gpu-b200", + disabled="Waived until sgl-kernel fix is released", +) + +MODEL = os.environ.get("QWEN3_30B_A3B_MODEL_PATH", "Qwen/Qwen3-30B-A3B") + +SKIP_TEST = torch.cuda.get_device_capability() < (10, 0) +SKIP_REASON = "Requires Blackwell (B200, sm_100a) or above." + + +@unittest.skipIf(SKIP_TEST, SKIP_REASON) +class TestFlashinferCutlassFlashinferA2A(CustomTestCase): + """FlashInfer Cutlass BF16 MoE + FlashInfer one-sided alltoall + DP4 EP4 on B200.""" + + @classmethod + def setUpClass(cls): + cls.model = MODEL + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH * 3, + other_args=[ + "--trust-remote-code", + "--tp", + "4", + "--ep-size", + "4", + "--dp", + "4", + "--enable-dp-attention", + "--enable-dp-lm-head", + "--moe-runner-backend", + "flashinfer_cutlass", + "--moe-a2a-backend", + "flashinfer", + "--max-prefill-tokens", + "4096", + "--disable-radix-cache", + "--disable-flashinfer-autotune", + "--watchdog-timeout", + "900", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + eval_name="gsm8k", + num_examples=1319, + max_tokens=10240, + repeat=1, + num_threads=1319, + num_shots=8, + temperature=0.6, + top_p=0.95, + top_k=20, + ) + metrics = run_eval(args) + print(metrics) + self.assertGreater(metrics["score"], 0.90) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_fused_append_remap_per_rank_shared_slots.py b/asian_ai/performance/SGLang/test/registered/moe/test_fused_append_remap_per_rank_shared_slots.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd6737779feceb67508af598722d13a0e6d54eb --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_fused_append_remap_per_rank_shared_slots.py @@ -0,0 +1,187 @@ +"""Unit tests for fused append + per-rank shared-slot remap. + +Covers ``fused_append_remap_shared_experts_deepep``, which collapses +``fused_append_shared_experts()`` followed by +``remap_topk_for_per_rank_shared_slots()`` into a +single Triton launch on the per-rank shared-slot path. The kernel is GPU-only +(Triton), so these tests are skipped when no accelerator is present. +""" + +import unittest + +import torch + +from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe_triton_kernels import ( + fused_append_remap_shared_experts_deepep, + fused_append_shared_experts, +) +from sglang.srt.layers.moe.topk import ( + TopKConfig, + _use_aiter, + remap_topk_for_per_rank_shared_slots, +) +from sglang.srt.runtime_context import get_parallel +from sglang.srt.utils import get_device +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=20, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=20, suite="stage-b-test-1-gpu-small-amd") + + +def _reference_append_remap( + topk_ids, topk_weights, s, scale_factor, shared_id_base, num_local_routed +): + """Pure-torch golden reference mirroring the kernel's documented contract. + + Routed IDs: e -> e + e // num_local_routed + Shared IDs: shared_id_base + arange(s) + Routed wgt: passthrough + Shared wgt: scale_factor + """ + m, k = topk_ids.shape + out_ids = torch.empty((m, k + s), dtype=topk_ids.dtype, device=topk_ids.device) + out_w = torch.empty( + (m, k + s), dtype=topk_weights.dtype, device=topk_weights.device + ) + out_ids[:, :k] = topk_ids + topk_ids // num_local_routed + out_w[:, :k] = topk_weights + shared = shared_id_base + torch.arange(s, device=topk_ids.device) + out_ids[:, k:] = shared.to(topk_ids.dtype) + out_w[:, k:] = scale_factor + return out_ids, out_w + + +@unittest.skipUnless( + torch.cuda.is_available(), "fused append+remap kernel requires a GPU" +) +class TestFusedAppendRemapPerRankSharedSlots(CustomTestCase): + # (m, k, num_physical_routed, ep_size, ep_rank, num_fused_shared_experts). + # k and num_fused_shared_experts are kept powers of two (tl.arange constraint). + CASES = [ + (1, 8, 256, 8, 0, 1), + (4, 8, 256, 8, 7, 1), + (17, 8, 264, 8, 3, 1), + (128, 16, 128, 4, 2, 2), + ] + + def _make_inputs(self, m, k, num_physical_routed, ids_dtype=torch.int64): + device = get_device() + g = torch.Generator(device="cpu").manual_seed(m * 1000 + k * 7 + 1) + topk_ids = torch.randint( + 0, num_physical_routed, (m, k), generator=g, dtype=ids_dtype + ).to(device) + topk_weights = torch.rand((m, k), generator=g, dtype=torch.float32).to(device) + return topk_ids, topk_weights + + @staticmethod + def _shared_id_base(num_physical_routed, ep_size, ep_rank, s): + num_local_routed = num_physical_routed // ep_size + num_local_experts = num_local_routed + s + return ep_rank * num_local_experts + num_local_routed, num_local_routed + + def test_matches_golden_reference(self): + """Kernel output equals the documented routed-remap + shared-append math.""" + for m, k, npr, ep_size, ep_rank, s in self.CASES: + with self.subTest(m=m, k=k, npr=npr, ep_rank=ep_rank, s=s): + shared_id_base, num_local_routed = self._shared_id_base( + npr, ep_size, ep_rank, s + ) + scale_factor = 1.0 + topk_ids, topk_weights = self._make_inputs(m, k, npr) + + got_ids, got_w = fused_append_remap_shared_experts_deepep( + topk_ids, + topk_weights, + s, + scale_factor, + shared_id_base, + num_local_routed, + ) + exp_ids, exp_w = _reference_append_remap( + topk_ids, + topk_weights, + s, + scale_factor, + shared_id_base, + num_local_routed, + ) + + self.assertEqual(tuple(got_ids.shape), (m, k + s)) + self.assertTrue(torch.equal(got_ids, exp_ids)) + self.assertTrue(torch.allclose(got_w, exp_w)) + + def test_equivalence_with_eager_append_then_remap(self): + """Fused kernel == append shared experts + per-rank shared-slot remap. + + The eager remap overwrites the shared weight: 1.0 on the aiter/HIP path + (routed_scaling_factor is pre-folded into the routed topk weights), else + 1/routed_scaling_factor. The fused kernel is invoked with that same value + so the two paths stay bit-identical (ids match regardless of scaling). + """ + rsf = 2.5 + scale_factor = 1.0 if _use_aiter else 1.0 / rsf + for m, k, npr, ep_size, ep_rank, s in self.CASES: + with self.subTest(m=m, k=k, npr=npr, ep_rank=ep_rank, s=s): + shared_id_base, num_local_routed = self._shared_id_base( + npr, ep_size, ep_rank, s + ) + topk_ids, topk_weights = self._make_inputs(m, k, npr) + + fused_ids, fused_w = fused_append_remap_shared_experts_deepep( + topk_ids.clone(), + topk_weights.clone(), + s, + scale_factor, + shared_id_base, + num_local_routed, + ) + + with get_parallel().override(moe_ep_size=ep_size, moe_ep_rank=ep_rank): + eager_ids, eager_w = fused_append_shared_experts( + topk_ids.clone(), + topk_weights.clone(), + s, + scale_factor, + npr, # shared-expert base id (overwritten by the remap) + ) + eager_ids, eager_w = remap_topk_for_per_rank_shared_slots( + eager_ids, + eager_w, + s, + npr, + TopKConfig( + top_k=k, + num_fused_shared_experts=s, + routed_scaling_factor=rsf, + ), + ) + + self.assertTrue(torch.equal(fused_ids, eager_ids)) + self.assertTrue(torch.allclose(fused_w, eager_w)) + + def test_shared_weight_is_one_on_aiter_path(self): + """On the aiter path the always-on shared expert must contribute 1.0x.""" + m, k, npr, ep_size, ep_rank, s = 8, 8, 256, 8, 1, 1 + shared_id_base, num_local_routed = self._shared_id_base( + npr, ep_size, ep_rank, s + ) + topk_ids, topk_weights = self._make_inputs(m, k, npr) + + _, got_w = fused_append_remap_shared_experts_deepep( + topk_ids, topk_weights, s, 1.0, shared_id_base, num_local_routed + ) + self.assertTrue(torch.all(got_w[:, -s:] == 1.0)) + + def test_no_shared_experts_is_noop(self): + """s == 0 returns the inputs untouched (no kernel launch).""" + topk_ids, topk_weights = self._make_inputs(4, 8, 256) + got_ids, got_w = fused_append_remap_shared_experts_deepep( + topk_ids, topk_weights, 0, 1.0, 0, 32 + ) + self.assertTrue(torch.equal(got_ids, topk_ids)) + self.assertTrue(torch.equal(got_w, topk_weights)) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_fused_moe.py b/asian_ai/performance/SGLang/test/registered/moe/test_fused_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..44cafb89e4a81f4da6089f7bb41c010d124c858e --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_fused_moe.py @@ -0,0 +1,244 @@ +import unittest + +import torch +from tqdm import tqdm + +from sglang.srt.layers.activation import SiluAndMul +from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe import fused_moe +from sglang.srt.layers.moe.topk import TopKConfig, select_experts +from sglang.srt.layers.quantization.fp8_kernel import is_fp8_fnuz +from sglang.srt.layers.quantization.fp8_utils import normalize_e4m3fn_to_e4m3fnuz +from sglang.srt.server_args import ServerArgs, set_global_server_args_for_scheduler +from sglang.srt.utils import get_device, get_device_capability, is_hip +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.test_utils import CustomTestCase, empty_gpu_cache + +register_cuda_ci(est_time=87, stage="base-b", runner_config="1-gpu-large") +register_amd_ci(est_time=30, suite="stage-b-test-1-gpu-small-amd") + +_is_hip = is_hip() +_is_fp8_fnuz = is_fp8_fnuz() + + +class TestFusedMOE(CustomTestCase): + NUM_EXPERTS = [8, 64] + TOP_KS = [2, 6] + + @staticmethod + def create_random_gpu_tensor(shape, dtype, mean=0, std=0.01): + """Create a random Torch(device) tensor + + Args: + shape: Tensor shape + dtype: Data type + mean: Mean value + std: Standard deviation + + Returns: + torch.Tensor: Randomly initialized Torch(device) tensor + """ + return torch.empty(shape, dtype=dtype, device=get_device()).normal_(mean, std) + + def get_tolerance(self, dtype): + """Get tolerance values for different data types + + Args: + dtype: Data type + + Returns: + tuple: (relative tolerance, absolute tolerance) + """ + if dtype == torch.float32: + return 1e-3, 1e-5 + elif dtype in [torch.float16, torch.bfloat16]: + return 1e-1, 1e-2 + else: + return 1e-2, 1e-2 # Default values for other types + + def torch_naive_moe( + self, + a, + w1, + w2, + score, + topk, + w1_scale=None, + w2_scale=None, + a1_scale=None, + a2_scale=None, + ): + set_global_server_args_for_scheduler(ServerArgs(model_path="dummy")) + + B, D = a.shape + a = a.view(B, -1, D).repeat(1, topk, 1).reshape(-1, D) + out = torch.zeros(B * topk, w2.shape[1], dtype=a.dtype, device=a.device) + score = torch.softmax(score, dim=-1, dtype=torch.float32) + topk_weight, topk_ids = torch.topk(score, topk) + topk_weight = topk_weight.view(-1) + topk_ids = topk_ids.view(-1) + + if w1.dtype in [torch.float8_e4m3fn, torch.float8_e4m3fnuz]: + w1_compute = w1.to(a.dtype) + w2_compute = w2.to(a.dtype) + + if w1_scale is not None: + w1_compute = (w1_compute * w1_scale.view(-1, 1, 1)).to(a.dtype) + if w2_scale is not None: + w2_compute = (w2_compute * w2_scale.view(-1, 1, 1)).to(a.dtype) + if a1_scale is not None: + a = (a * a1_scale).to(a.dtype) + if a2_scale is not None: + a = (a * a2_scale).to(a.dtype) + else: + w1_compute = w1 + w2_compute = w2 + + for i in range(w1_compute.shape[0]): + mask = topk_ids == i + if mask.sum(): + out[mask] = SiluAndMul()( + a[mask] @ w1_compute[i].transpose(0, 1) + ) @ w2_compute[i].transpose(0, 1) + + return ( + out.view(B, -1, w2.shape[1]) * topk_weight.view(B, -1, 1).to(out.dtype) + ).sum(dim=1) + + def _test_case(self, m, n, k, e, topk, dtype, use_fp8_w8a8=False): + rtol, atol = self.get_tolerance(dtype) + + if use_fp8_w8a8: + # AssertionError: fp8e4nv data type is not supported on CUDA arch < 89 + capability = get_device_capability() + if not _is_hip and not (capability[0] >= 9 or capability == (8, 9)): + return + + a = self.create_random_gpu_tensor((m, k), dtype) + w1 = self.create_random_gpu_tensor((e, 2 * n, k), dtype) + w2 = self.create_random_gpu_tensor((e, k, n), dtype) + w1 = w1.to(torch.float8_e4m3fn) + w2 = w2.to(torch.float8_e4m3fn) + score = self.create_random_gpu_tensor((m, e), dtype) + w1_scale = self.create_random_gpu_tensor(e, torch.float32) + w2_scale = self.create_random_gpu_tensor(e, torch.float32) + a1_scale = self.create_random_gpu_tensor(1, torch.float32) + a2_scale = self.create_random_gpu_tensor(1, torch.float32) + + # Handle HIP case: normalize float8 weights so fused kernel doesn't break + # on ROCm. + if _is_fp8_fnuz: + # Normalize to e4m3fnuz on HIP + w1, w1_scale, _ = normalize_e4m3fn_to_e4m3fnuz( + weight=w1, + weight_scale=w1_scale, + input_scale=a1_scale, + ) + w2, w2_scale, _ = normalize_e4m3fn_to_e4m3fnuz( + weight=w2, + weight_scale=w2_scale, + input_scale=a2_scale, + ) + + topk_output = select_experts( + hidden_states=a, + router_logits=score, + topk_config=TopKConfig(top_k=topk, renormalize=False), + ) + + torch_output = self.torch_naive_moe( + a, + w1, + w2, + score, + topk, + w1_scale, + w2_scale, + a1_scale, + a2_scale, + ) + + sglang_output = fused_moe( + a, + w1, + w2, + topk_output, + use_fp8_w8a8=True, + w1_scale=w1_scale, + w2_scale=w2_scale, + a1_scale=a1_scale, + a2_scale=a2_scale, + ) + torch.testing.assert_close( + sglang_output, torch_output, rtol=rtol, atol=atol + ) + else: + a = self.create_random_gpu_tensor((m, k), dtype) + w1 = self.create_random_gpu_tensor((e, 2 * n, k), dtype) + w2 = self.create_random_gpu_tensor((e, k, n), dtype) + score = self.create_random_gpu_tensor((m, e), dtype) + + topk_output = select_experts( + hidden_states=a, + router_logits=score, + topk_config=TopKConfig(top_k=topk, renormalize=False), + ) + + triton_output = fused_moe(a, w1, w2, topk_output) + torch_output = self.torch_naive_moe(a, w1, w2, score, topk) + torch.testing.assert_close( + triton_output, torch_output, rtol=rtol, atol=atol + ) + + def test_various_configurations(self): + m_values = [1, 33, 64, 222] + n_values = [128, 1024] + k_values = [128, 511, 1024] + dtypes = [torch.float16, torch.bfloat16] + fp8_modes = [False, True] + + set_global_server_args_for_scheduler(ServerArgs(model_path="dummy")) + + # Calculate total number of tests + total_tests = ( + len(m_values) + * len(n_values) + * len(k_values) + * len(self.NUM_EXPERTS) + * len(self.TOP_KS) + * len(dtypes) + * len(fp8_modes) + ) + + # Create progress bar + with tqdm(total=total_tests, desc="Running MoE tests") as pbar: + for m in m_values: + for n in n_values: + for k in k_values: + for e in self.NUM_EXPERTS: + for topk in self.TOP_KS: + for dtype in dtypes: + for use_fp8_w8a8 in fp8_modes: + with self.subTest( + m=m, + n=n, + k=k, + e=e, + topk=topk, + dtype=dtype, + fp8=use_fp8_w8a8, + ): + self._test_case( + m, + n, + k, + e, + topk, + dtype, + use_fp8_w8a8=use_fp8_w8a8, + ) + empty_gpu_cache() + pbar.update(1) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_glm4_moe_models.py b/asian_ai/performance/SGLang/test/registered/moe/test_glm4_moe_models.py new file mode 100644 index 0000000000000000000000000000000000000000..318a2175797347d56e2508310ce9bae492013c2c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_glm4_moe_models.py @@ -0,0 +1,52 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=171, stage="base-b", runner_config="2-gpu-large") + + +class TestGLM4MoE(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = "zai-org/GLM-4.5-Air-FP8" + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--tp-size", + "2", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=100, + num_threads=128, + ) + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.8) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_hash_topk.py b/asian_ai/performance/SGLang/test/registered/moe/test_hash_topk.py new file mode 100644 index 0000000000000000000000000000000000000000..ea0c98c7902cb1f3cfc524850ea28aff36b46c7f --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_hash_topk.py @@ -0,0 +1,145 @@ +import sys +from types import SimpleNamespace + +import pytest +import torch + +from sglang.srt.eplb.expert_location_dispatch import ExpertLocationDispatchInfo +from sglang.srt.layers.moe import hash_topk as hash_topk_module +from sglang.srt.layers.moe.hash_topk import HashTopK +from sglang.srt.layers.moe.topk import ( + StandardTopKOutput, +) +from sglang.srt.models.deepseek_v2 import DeepseekV2MoE +from sglang.srt.runtime_context import get_parallel +from sglang.srt.server_args import ServerArgs, set_global_server_args_for_scheduler +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-b-test-cpu") + + +@pytest.fixture(autouse=True) +def _set_dummy_server_args(): + set_global_server_args_for_scheduler(ServerArgs(model_path="dummy")) + + +def test_hash_topk_remaps_per_rank_fused_shared_slots(monkeypatch): + monkeypatch.setattr( + hash_topk_module, "has_per_rank_fused_shared_slots", lambda *_args: True + ) + recorded = {} + + class FakeRecorder: + def on_select_experts(self, *, topk_ids): + recorded["topk_ids"] = topk_ids.clone() + + monkeypatch.setattr( + hash_topk_module, + "get_global_expert_distribution_recorder", + lambda: FakeRecorder(), + ) + + topk = HashTopK( + topk=3, + num_experts=256, + num_fused_shared_experts=1, + vocab_size=2, + scoring_func="sqrtsoftplus", + routed_scaling_factor=2.5, + ) + with torch.no_grad(): + topk.tid2eid.copy_(torch.tensor([[0, 65], [63, 127]], dtype=torch.int32)) + + info = ExpertLocationDispatchInfo( + ep_dispatch_algorithm="static", + partial_logical_to_rank_dispatch_physical_map=torch.arange( + 256, dtype=torch.int32 + ), + partial_logical_to_all_physical_map=torch.arange(256, dtype=torch.int32).view( + 256, 1 + ), + partial_logical_to_all_physical_map_num_valid=torch.ones( + 256, dtype=torch.int32 + ), + num_physical_experts=256, + ) + + with ( + get_parallel().override(moe_ep_size=4, moe_ep_rank=2), + hash_topk_module.envs.SGLANG_OPT_USE_FUSED_HASH_TOPK.override(False), + ): + output = topk( + hidden_states=torch.empty(2, 4), + router_logits=torch.ones(2, 256), + input_ids=torch.tensor([0, 1], dtype=torch.int64), + expert_location_dispatch_info=info, + ) + + # Physical layout for EP=4 has 64 routed slots per rank plus one local + # shared slot: [0..63, shared, 64..127, shared, ...]. + assert output.topk_ids.tolist() == [[0, 66, 194], [63, 128, 194]] + assert torch.allclose(output.topk_weights[:, -1], torch.full((2,), 0.4)) + assert recorded["topk_ids"].tolist() == [[0, 65], [63, 127]] + + +def test_hash_topk_empty_output_keeps_per_rank_shared_slot(monkeypatch): + monkeypatch.setattr( + hash_topk_module, "has_per_rank_fused_shared_slots", lambda *_args: True + ) + + topk = HashTopK( + topk=7, + num_experts=256, + num_fused_shared_experts=1, + vocab_size=2, + scoring_func="softmax", + ) + + output = topk.empty_topk_output(torch.device("cpu")) + + assert output.topk_ids.shape == (0, 7) + assert output.topk_weights.shape == (0, 7) + assert output.router_logits.shape == (0, 6) + + +def test_deepep_empty_forward_does_not_append_shared_slot_twice(): + captured = {} + + class FakeTopK: + def empty_topk_output(self, device, *, layer_id=None): + return StandardTopKOutput( + topk_weights=torch.empty((0, 9), dtype=torch.float32, device=device), + topk_ids=torch.empty((0, 9), dtype=torch.int32, device=device), + router_logits=torch.empty((0, 8), dtype=torch.float32, device=device), + ) + + class FakeExperts: + should_fuse_routed_scaling_factor_in_topk = True + + def __call__(self, hidden_states, topk_output): + captured["topk_ids_shape"] = tuple(topk_output.topk_ids.shape) + captured["topk_weights_shape"] = tuple(topk_output.topk_weights.shape) + return hidden_states + + moe = SimpleNamespace( + _fuse_shared_experts_inside_sbo=False, + is_nextn=False, + num_fused_shared_experts=1, + layer_id=0, + topk=FakeTopK(), + experts=FakeExperts(), + alt_stream=None, + routed_scaling_factor=1.0, + ) + + hidden_states = torch.empty((0, 4), dtype=torch.float32) + forward_batch = SimpleNamespace(num_token_non_padded=None) + + DeepseekV2MoE.forward_deepep(moe, hidden_states, forward_batch) + + assert captured["topk_ids_shape"] == (0, 9) + assert captured["topk_weights_shape"] == (0, 9) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_hybrid_dp_ep_tp_mtp.py b/asian_ai/performance/SGLang/test/registered/moe/test_hybrid_dp_ep_tp_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..156f42cad15d74aafda3bfa088bd531f0b5a871c --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_hybrid_dp_ep_tp_mtp.py @@ -0,0 +1,2733 @@ +# Comprehensive test for hybrid parallelism (DP/TP attention, DP/TP Dense FFN, TP/EP Sparse FFN, DP/VP LM head) plus speculative decoding. + +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST, + DEFAULT_MLA_MODEL_NAME_FOR_TEST, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +# 60 test classes testing hybrid parallelism configurations +# Each test launches server + runs MMLU eval (~90s per test) +register_cuda_ci(est_time=5400, suite="weekly-8-gpu-h200", nightly=True) + + +class Test00(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test01(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test02(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test03(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--moe-dense-tp-size", + "1", + "--enable-flashinfer-allreduce-fusion", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test04(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test05(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test06(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--enable-dp-lm-head", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test07(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--enable-dp-lm-head", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test08(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test09(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test10(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test11(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test12(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test13(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--moe-dense-tp-size", + "1", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test14(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test15(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test16(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test17(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test18(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test19(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "128", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test20(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test21(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test22(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test23(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--moe-dense-tp-size", + "1", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test24(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test25(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test26(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--enable-dp-lm-head", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test27(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--enable-dp-lm-head", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test28(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test29(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MLA_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--ep", + "8", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test30(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test31(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test32(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test33(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--moe-dense-tp-size", + "1", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test34(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test35(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test36(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--enable-dp-lm-head", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test37(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--enable-dp-lm-head", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test38(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test39(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test40(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test41(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test42(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test43(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--moe-dense-tp-size", + "1", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test44(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test45(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test46(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test47(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test48(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test49(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--moe-a2a-backend", + "deepep", + "--cuda-graph-max-bs-decode", + "32", + "--max-running-requests", + "32", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test50(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test51(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test52(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test53(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--moe-dense-tp-size", + "1", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test54(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test55(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test56(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--enable-dp-lm-head", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test57(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--enable-dp-lm-head", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test58(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "4", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +class Test59(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_DEEPEP_MODEL_NAME_FOR_TEST + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "8", + "--enable-dp-attention", + "--dp", + "8", + "--moe-dense-tp-size", + "1", + "--enable-dp-lm-head", + "--ep", + "8", + "--speculative-algo", + "EAGLE", + "--speculative-draft-model-path", + "lmsys/DeepSeek-V3-0324-NextN", + "--speculative-num-steps", + "2", + "--speculative-eagle-topk", + "4", + "--speculative-num-draft-tokens", + "4", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_mmlu(self): + args = SimpleNamespace( + base_url=self.base_url, + model=self.model, + eval_name="mmlu", + num_examples=64, + num_threads=32, + ) + + metrics = run_eval(args) + print(f"{metrics=}") + self.assertGreater(metrics["score"], 0.48) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_moe_ep.py b/asian_ai/performance/SGLang/test/registered/moe/test_moe_ep.py new file mode 100644 index 0000000000000000000000000000000000000000..14ca592dfcf4b6592313d15ed4f3492a9a272297 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_moe_ep.py @@ -0,0 +1,58 @@ +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST_MLA, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +# Per-commit: TP=2 EP=2 baseline. +# DeepGEMM/FP8 variant moved to test_moe_ep_nightly.py. +register_cuda_ci(est_time=279, stage="base-b", runner_config="2-gpu-large") + + +class TestEp(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "2", + "--ep-size", + "2", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +if __name__ == "__main__": + unittest.main() diff --git a/asian_ai/performance/SGLang/test/registered/moe/test_moe_ep_extra.py b/asian_ai/performance/SGLang/test/registered/moe/test_moe_ep_extra.py new file mode 100644 index 0000000000000000000000000000000000000000..c98281fcae2d968a56c91543852f93695942e9f6 --- /dev/null +++ b/asian_ai/performance/SGLang/test/registered/moe/test_moe_ep_extra.py @@ -0,0 +1,66 @@ +"""Extra: TP=2 EP=2 with FP8 + DeepGEMM MoE backend. + +Sibling per-commit file (test_moe_ep.py) keeps the baseline TP=2 EP=2 +variant. +""" + +import unittest +from types import SimpleNamespace + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.run_eval import run_eval +from sglang.test.test_utils import ( + DEFAULT_MODEL_NAME_FOR_TEST_MLA, + DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + DEFAULT_URL_FOR_TEST, + CustomTestCase, + popen_launch_server, +) + +register_cuda_ci(est_time=279, stage="extra-a", runner_config="2-gpu-large") + + +class TestEpDeepGEMM(CustomTestCase): + @classmethod + def setUpClass(cls): + cls.model = DEFAULT_MODEL_NAME_FOR_TEST_MLA + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, + other_args=[ + "--trust-remote-code", + "--tp", + "2", + "--ep-size", + "2", + "--quantization", + "fp8", + "--moe-runner-backend", + "deep_gemm", + ], + ) + + @classmethod + def tearDownClass(cls): + kill_process_tree(cls.process.pid) + + def test_gsm8k(self): + args = SimpleNamespace( + base_url=self.base_url, + eval_name="gsm8k", + api="completion", + max_tokens=512, + num_examples=200, + num_threads=128, + ) + metrics = run_eval(args) + print(metrics) + + self.assertGreater(metrics["score"], 0.60) + + +if __name__ == "__main__": + unittest.main()