diff --git a/AGENTS.md b/AGENTS.md index 6fc8e54aa..eb65b6271 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,8 +55,9 @@ waste, or fork the kernel forcing it. "Just for now" syncs stay forever. reuses the forward's saved `StreamingHandle`, so it runs no metadata kernel and no host poll. - Padding rows are never initialized; every consumer is padding-aware instead - (predicated atomics on `pool_recv_token >= 0`, `seqused_k` for the dW GEMMs, - the padding mask in `kernel_y_bwd`). A new consumer must gate the same way. + (predicated atomics on `pool_recv_token >= 0`, the padding mask in + `kernel_y_bwd`, and `zero_padding_rows` on the dW GEMM operands, which + contract over padding). A new consumer must gate the same way. Use conditional assignment, never multiplication by a 0/1 mask: the GEMM through garbage rows can produce inf/NaN, and `0 * inf = NaN`. @@ -151,12 +152,12 @@ find out why instead of dropping the shape. - StreamEP diverges freely from upstream DeepEP; when a cleaner streaming pipeline conflicts with staying close to upstream, the pipeline wins. -- The Quack fork is upstream `main` plus the one `seqused_k` commit and must - stay that way. Anything streaming-specific (subclasses, EpiOps, schedulers) - lives in `stream_ep/stream_moe/`, and the fork is dropped once `seqused_k` - lands upstream. +- Quack is used unmodified from upstream releases. Anything streaming-specific + (subclasses, EpiOps, schedulers) lives in `stream_ep/stream_moe/`. StreamEP + builds on Quack internals, so evoscale must run the same Quack version. - The pixi environments pin the versions evoscale runs. Bumping torch, CUDA, - NVSHMEM or cutlass-dsl here goes together with the matching evoscale bump. + NVSHMEM, cutlass-dsl or Quack here goes together with the matching evoscale + bump. ## Commits and PRs diff --git a/README.md b/README.md index aab1bdf78..8f911ccfe 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ Only `stream_ep/` and the extension ship in the wheel. `pixi.toml` defines three environments: - `default` — the wheel build env, pinned to the versions evoscale runs (python 3.12, torch 2.11.0+cu130, nvcc 13.3, gcc 14.3, `nvidia-nvshmem-cu13==3.4.5`). No GPU needed. -- `test` — `default` plus the runtime deps of the MoE kernels (evoscale's Quack fork, cutlass-dsl, CUDA 13.3 runtime), with StreamEP itself installed editable. +- `test` — `default` plus the runtime deps of the MoE kernels (Quack, cutlass-dsl, CUDA 13.3 runtime), with StreamEP itself installed editable. - `lint` — pre-commit only. ```bash diff --git a/csrc/stream_ep.cpp b/csrc/stream_ep.cpp index 17a7556e8..8ed2ad11c 100644 --- a/csrc/stream_ep.cpp +++ b/csrc/stream_ep.cpp @@ -1189,9 +1189,8 @@ StreamingDispatchOutputs Buffer::intranode_dispatch(const torch::Tensor& x, // post-poll bundle — too big to coalesce into the same caching-allocator // size class as the small bundle. Allocate uninitialized: every // downstream consumer either predicates on `pool_recv_token >= 0` (fwd - // kernel A's tile-streaming, fwd combine's gather) or uses quack's - // `lens_k` to bound the K-tile via TMA's OOB-zero-fill (bwd dW1's - // grouped GEMM). Padding rows are never read. + // kernel A's tile-streaming, fwd combine's gather) or, for bwd dW1's + // grouped GEMM, runs after `zero_padding_rows` zeroes the padding rows. // Allocated on the DEFAULT (caller) stream, NOT this dispatch's communicate // stream — pool is saved across fwd→bwd and freed at bwd return, after the // caller-side layer-end back-edges, so it shares the default pool and reuses @@ -1366,9 +1365,8 @@ std::tuple Buffer::intranode_dispatch // (real) slots; padding rows are NOT touched by the receiver. Allocate // uninitialized: kernel_y_bwd reads dL_do_pool through its mPaddingMask // predicate (zeros (dgate, dup, postact, g) at padding rows BEFORE any - // store), and dW2's grouped GEMM reads dL_do_pool through quack's - // `lens_k` which bounds the K-tile via TMA's OOB-zero-fill. Padding - // rows are never functionally read. + // store), and dW2's grouped GEMM runs after `zero_padding_rows` zeroes + // the padding rows. // Allocated on the DEFAULT (caller) stream, NOT communicate — dL_do_pool is // a bwd local freed at bwd return, after the caller-side layer-end // back-edges, so it shares the default pool without a record_consumer_stream @@ -1712,8 +1710,8 @@ StreamingDispatchOutputs Buffer::internode_dispatch(const torch::Tensor& x, // post-poll bundle — too big to coalesce into the same caching-allocator // size class. Allocate uninitialized: every downstream consumer either // predicates on `pool_recv_token >= 0` (kernel A's tile-streaming, - // combine's gather) or uses quack's `lens_k` for OOB-zero-fill (bwd dW - // grouped GEMM). Padding rows are never read. + // combine's gather) or, for the bwd dW grouped GEMM, runs after + // `zero_padding_rows` zeroes the padding rows. // Allocated on the DEFAULT (caller) stream, NOT communicate — saved across // fwd→bwd, freed at bwd return after the caller-side layer-end back-edges, so // it shares the default pool without a record_consumer_stream deferral. See @@ -1914,10 +1912,11 @@ std::tuple Buffer::internode_dispatch // kernel that writes them; alloc->first-use of a recycled default-pool block // is covered by the layer-start communicate.wait_stream(caller) gate. // (Whether the zero-init is strictly needed — the intranode dL_do_pool runs - // uninitialized, relying on kernel_y_bwd/dW2 masking padding rows, and the - // internode receiver has the same K-fanout-over-recv_token_to_slots write - // coverage — is a deferred optimization; kept zeroed here to preserve exact - // behavior, no regression vs the prior torch::zeros.) + // uninitialized, relying on kernel_y_bwd's padding mask and the bwd + // `zero_padding_rows` before dW2, and the internode receiver has the same + // K-fanout-over-recv_token_to_slots write coverage — is a deferred + // optimization; kept zeroed here to preserve exact behavior, no regression + // vs the prior torch::zeros.) auto dL_do_pool = empty_on_default_pool({TK_padded, hidden}, dL_dy.options(), default_stream_registered_, default_stream_handle_); CUDA_CHECK(cudaMemsetAsync(dL_do_pool.data_ptr(), 0x00, dL_do_pool.numel() * dL_dy.element_size(), stream)); auto i32_opts = at::TensorOptions().dtype(torch::kInt32).device(torch::kCUDA); diff --git a/pixi.lock b/pixi.lock index ff6d4ba12..b39deaad7 100644 --- a/pixi.lock +++ b/pixi.lock @@ -1,6 +1,11 @@ version: 7 platforms: - name: linux-64 + virtual-packages: + - __unix=0=0 + - __linux=4.18 + - __glibc=2.28 + - __archspec=0=x86_64 environments: default: channels: @@ -256,8 +261,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/sysroot_linux-64-2.28-h4ee821c_9.conda - conda: https://conda.anaconda.org/conda-forge/noarch/tzdata-2026e-h5d301ff_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/wheel-0.48.0-pyhd8ed1ab_0.conda - - pypi: . - - pypi: git+https://github.com/evolutionaryscale/quack.git?rev=1843cb2b9c698cdaddc27cb92026740d88d24624#1843cb2b9c698cdaddc27cb92026740d88d24624 + - pypi: ./ - pypi: https://download-r2.pytorch.org/whl/cu130/torch-2.11.0%2Bcu130-cp312-cp312-manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/08/97/896495b02ec87fd19372f3e5245be12e301651f610b6ec7408bc7e562426/nvidia_cutlass_dsl_libs_base-4.7.0-cp312-cp312-manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/16/92/d1e32e3e0d894fe00b15ce28ad4944ab692713f2e7f0a99787405e43533a/protobuf-6.33.6-cp39-abi3-manylinux2014_x86_64.whl @@ -283,6 +287,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/62/ac/39793266a20575889f95869ce7bd96374f30b31c53698a268ecf21bd11be/apache_tvm_ffi-0.1.15.post0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/73/d8/f5e56c38b286308d115a171e3c5c44f24e9d03980c3cfd22588df40261fa/quack_kernels-0.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/76/ce/75a7df4b90256f6924f8355e25bb52351750b2ce654cc926dd6a3aa1e354/nvidia_cutlass_dsl_libs_core-4.7.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/84/ec/a86c24290c1882ef7b40c15e177a06d9b1fbe8e960bcce6d053170862a83/nvidia_cufile-1.18.1.6-py3-none-manylinux_2_27_x86_64.whl @@ -1732,32 +1737,11 @@ packages: run_exports: {} size: 34528 timestamp: 1786613220176 -- pypi: . +- pypi: ./ name: stream-ep requires_dist: - torch==2.11.0 - nvidia-nvshmem-cu13==3.4.5 -- pypi: git+https://github.com/evolutionaryscale/quack.git?rev=1843cb2b9c698cdaddc27cb92026740d88d24624#1843cb2b9c698cdaddc27cb92026740d88d24624 - name: quack-kernels - version: 0.6.4 - requires_dist: - - nvidia-cutlass-dsl==4.7.0 - - torch ; extra == 'cu13' - - torch ; extra != 'cu13' - - apache-tvm-ffi>=0.1.6,<0.2 - - torch-c-dlpack-ext - - einops - - nvidia-cutlass-dsl[cu13]==4.7.0 ; extra == 'cu13' - - nvidia-matmul-heuristics ; extra == 'heuristics' - - jax ; extra == 'jax' - - jax-tvm-ffi ; extra == 'jax' - - pandas ; extra == 'bench' - - tyro ; extra == 'bench' - - pre-commit ; extra == 'dev' - - pytest ; extra == 'dev' - - pytest-xdist ; extra == 'dev' - - ruff ; extra == 'dev' - requires_python: '>=3.10' - pypi: https://download-r2.pytorch.org/whl/cu130/torch-2.11.0%2Bcu130-cp312-cp312-manylinux_2_28_x86_64.whl name: torch version: 2.11.0+cu130 @@ -2230,6 +2214,27 @@ packages: requires_dist: - colorama>=0.4.6 ; extra == 'windows-terminal' requires_python: '>=3.9' +- pypi: https://files.pythonhosted.org/packages/73/d8/f5e56c38b286308d115a171e3c5c44f24e9d03980c3cfd22588df40261fa/quack_kernels-0.6.5-py3-none-any.whl + name: quack-kernels + version: 0.6.5 + sha256: df1ddd31366c82eb9692fe087c671209189dcbde53c909c81a865d4ee66b158d + requires_dist: + - nvidia-cutlass-dsl>=4.7 + - torch + - apache-tvm-ffi>=0.1.6,<0.2 + - torch-c-dlpack-ext + - einops + - nvidia-cutlass-dsl[cu13]>=4.7 ; extra == 'cu13' + - nvidia-matmul-heuristics ; extra == 'heuristics' + - jax ; extra == 'jax' + - jax-tvm-ffi ; extra == 'jax' + - pandas ; extra == 'bench' + - tyro ; extra == 'bench' + - pre-commit ; extra == 'dev' + - pytest ; extra == 'dev' + - pytest-xdist ; extra == 'dev' + - ruff ; extra == 'dev' + requires_python: '>=3.10' - pypi: https://files.pythonhosted.org/packages/76/ce/75a7df4b90256f6924f8355e25bb52351750b2ce654cc926dd6a3aa1e354/nvidia_cutlass_dsl_libs_core-4.7.0-py3-none-any.whl name: nvidia-cutlass-dsl-libs-core version: 4.7.0 diff --git a/pixi.toml b/pixi.toml index 1a49c3784..82a8d7109 100644 --- a/pixi.toml +++ b/pixi.toml @@ -48,13 +48,13 @@ cmd = "python scripts/check_wheel.py" description = "Check dist/ holds one release-ready wheel matching pyproject's version" # Dev / GPU-test env: the build env plus the runtime-only deps of the -# streaming-MoE kernels, at the same pins as evoscale (the quack fork rev and -# cutlass-dsl come from evoscale's pixi.toml). stream-ep itself is an editable +# streaming-MoE kernels, at the same pins as evoscale (quack and cutlass-dsl +# come from evoscale's pixi.toml). stream-ep itself is an editable # install built by the env, so `build-ext` followed by a test task runs the # working tree. [feature.test.pypi-dependencies] stream-ep = { path = ".", editable = true } -quack-kernels = { git = "https://github.com/evolutionaryscale/quack.git", rev = "1843cb2b9c698cdaddc27cb92026740d88d24624", extras = ["cu13", "heuristics"] } +quack-kernels = { version = "==0.6.5", extras = ["cu13", "heuristics"] } nvidia-cutlass-dsl = { version = "==4.7.0", extras = ["cu13"] } pytest = "*" diff --git a/stream_ep/stream_moe/recv_pool_compress.py b/stream_ep/stream_moe/recv_pool_compress.py index 03a055ca5..0e174f8d5 100644 --- a/stream_ep/stream_moe/recv_pool_compress.py +++ b/stream_ep/stream_moe/recv_pool_compress.py @@ -1,12 +1,16 @@ -"""Triton kernels for activation_checkpoint_level=2 pool <-> x_recv row -compaction / re-expansion. +"""Triton kernels over pool rows. -One ``@triton.jit`` kernel, two ``GATHER`` specializations: +Activation_checkpoint_level=2 pool <-> x_recv compaction / re-expansion, one +``@triton.jit`` kernel with two ``GATHER`` specializations, both driven by +``pool_recv_token`` (slot -> recv-token id, -1 = padding), so compact needs no +per-token scan: * expand (GATHER=True): pool[slot] = x_recv[pool_recv_token[slot]] (0 if -1 pad) * compact (GATHER=False): x_recv[pool_recv_token[slot]] = pool[slot] (skip -1 pad) -Both are driven by ``pool_recv_token`` (slot -> recv-token id, -1 = padding), so -compact needs no per-token scan. +``zero_padding_rows`` zeroes the padding rows of a pool-shaped tensor in place, +for consumers that contract over them (the varlen-K dW GEMMs). Padding is the +tail of each expert's slot range, fewer than ``tile_m`` rows, so it launches one +program per (expert, H-block) rather than one per slot. Compile-once for ALL lengths: the row count ``L`` (= TK_padded) is the grid dimension, NOT a kernel argument, so it never enters triton's compile key — one @@ -50,6 +54,17 @@ def _index_copy_rows( tl.store(out_ptr + tokc * H + h, v, mask=hmask & valid) +@triton.jit +def _zero_padding_rows(t_ptr, block_offset_ptr, freq_ptr, H, TILE_M: tl.constexpr, BLOCK_H: tl.constexpr): + e = tl.program_id(0) + start = tl.load(block_offset_ptr + e) * TILE_M + tl.load(freq_ptr + e) # first padding row + end = tl.load(block_offset_ptr + e + 1) * TILE_M + rows = start + tl.arange(0, TILE_M) + h = tl.program_id(1) * BLOCK_H + tl.arange(0, BLOCK_H) + mask = (rows < end)[:, None] & (h < H)[None, :] + tl.store(t_ptr + rows[:, None] * H + h[None, :], tl.zeros([TILE_M, BLOCK_H], dtype=t_ptr.dtype.element_ty), mask=mask) + + def _check(pool: torch.Tensor, x_recv: torch.Tensor, pool_recv_token: torch.Tensor): assert pool.is_contiguous() and x_recv.is_contiguous() and pool_recv_token.is_contiguous() TK_padded, H = pool.shape @@ -72,7 +87,21 @@ def compress_pool_to_recv(pool: torch.Tensor, pool_recv_token: torch.Tensor, out def reexpand_recv_to_pool(x_recv: torch.Tensor, pool_recv_token: torch.Tensor, out: torch.Tensor, BLOCK_H: int = 512) -> None: """x_recv[T_recv, H] -> out[TK_padded, H], in place. Gather-by-slot; padding - slots (-1) are zeroed (masked / cu_seqlens-excluded by every consumer).""" + slots (-1) are zeroed.""" TK_padded, H = _check(out, x_recv, pool_recv_token) grid = (TK_padded, triton.cdiv(H, BLOCK_H)) _index_copy_rows[grid](out, x_recv, pool_recv_token, H, GATHER=True, BLOCK_H=BLOCK_H) + + +def zero_padding_rows( + pool: torch.Tensor, expert_pool_block_offset: torch.Tensor, expert_frequency: torch.Tensor, tile_m: int, BLOCK_H: int = 128 +) -> None: + """pool[TK_padded, H] in place: each expert's padding rows (past its + ``expert_frequency[e]`` real rows, up to its next tile boundary) set to zero, + real rows untouched.""" + num_experts = expert_frequency.numel() + assert pool.is_contiguous() and expert_pool_block_offset.shape == (num_experts + 1,) + assert pool.numel() < _INT32_MAX, f"int32 offset overflow: pool numel {pool.numel()} >= 2**31; widen offsets to int64 in-kernel" + H = pool.shape[1] + grid = (num_experts, triton.cdiv(H, BLOCK_H)) + _zero_padding_rows[grid](pool, expert_pool_block_offset, expert_frequency, H, TILE_M=tile_m, BLOCK_H=BLOCK_H) diff --git a/stream_ep/stream_moe/stream_moe.py b/stream_ep/stream_moe/stream_moe.py index 7ddc16c2c..55a01ec23 100644 --- a/stream_ep/stream_moe/stream_moe.py +++ b/stream_ep/stream_moe/stream_moe.py @@ -103,6 +103,7 @@ from stream_ep.stream_moe.recv_pool_compress import ( compress_pool_to_recv, reexpand_recv_to_pool, + zero_padding_rows, ) @@ -906,7 +907,6 @@ def backward(ctx, dL_dy): # type: ignore[override] # specific experts. with torch.cuda.stream(streams.compute): cu_seqlens_k = (handle.expert_pool_block_offset.to(torch.int32) * tile_m).contiguous() - seqused_k_dW = handle.expert_frequency.to(torch.int32) bwd_k_local_remaining.copy_(handle.k_local_total, non_blocking=True) # ── Stage 1 — dispatch_grads on streams.communicate ──────────────── @@ -1092,12 +1092,20 @@ def backward(ctx, dL_dy): # type: ignore[override] # Empty-rank guard: skip the dW1/dW2 grouped GEMMs and zero the # destinations. With ``total_tiles == 0`` the per-expert K-lens are # all zero — the GEMMs would have zero work, but quack's grouped-GEMM - # path isn't guaranteed to handle all-zero ``cu_seqlens_k`` / ``seqused_k`` - # gracefully. dW1_local / dW2_local were allocated as - # ``torch.empty_like`` so they hold uninitialized garbage; the genuine - # gradient is zero, so explicit ``.zero_()`` is correct. + # path isn't guaranteed to handle all-zero ``cu_seqlens_k`` gracefully. + # dW1_local / dW2_local were allocated as ``torch.empty_like`` so they + # hold uninitialized garbage; the genuine gradient is zero, so explicit + # ``.zero_()`` is correct. if total_tiles > 0: with torch.cuda.stream(streams.compute): + # The dW GEMMs contract over each expert's padded slot range. + # kernel_y_bwd zeroed the padding rows of postact_a_for_dW2 and + # dL_dswiglu_in; zero those of the other operands too, which + # hold garbage, so padding contributes 0 * 0 instead of 0 * NaN. + # dispatch_grads never writes padding slots, so this cannot race + # its tail on communicate. + for operand in (dL_do_pool, pool): + zero_padding_rows(operand, handle.expert_pool_block_offset, handle.expert_frequency, tile_m) # dW2[e] = postact_a_for_dW2[slot_range_e].T @ dL_do_pool[slot_range_e] postact_a_for_dW2_flat = postact_a_for_dW2.view(TK_padded, I) gemm( @@ -1113,7 +1121,6 @@ def backward(ctx, dL_dy): # type: ignore[override] pingpong=pingpong_dW2, max_swizzle_size=swizzle_dW2, cu_seqlens_k=cu_seqlens_k, - seqused_k=seqused_k_dW, ) # dW1[e] = (dL_dswiglu_in[slot_range_e]).T @ pool[slot_range_e] dL_dswiglu_in_flat = dL_dswiglu_in.view(TK_padded, two_I) @@ -1130,7 +1137,6 @@ def backward(ctx, dL_dy): # type: ignore[override] pingpong=pingpong_dW1, max_swizzle_size=swizzle_dW1, cu_seqlens_k=cu_seqlens_k, - seqused_k=seqused_k_dW, ) else: with torch.cuda.stream(streams.compute): diff --git a/stream_ep_tests/kernels/_common.py b/stream_ep_tests/kernels/_common.py index 06d317cdf..54d2973ec 100644 --- a/stream_ep_tests/kernels/_common.py +++ b/stream_ep_tests/kernels/_common.py @@ -45,6 +45,10 @@ def block_offset(self) -> torch.Tensor: """``expert_pool_block_offset``: [E_local + 1] prefix sum of tiles per expert.""" return torch.cat([self.tiles.new_zeros(1), self.tiles.cumsum(0)]).to(torch.int32) + def frequency(self) -> torch.Tensor: + """``expert_frequency``: [E_local] real rows per expert.""" + return torch.tensor(self.rows, device="cuda", dtype=torch.int32) + def slot_expert(self) -> torch.Tensor: """[num_slots] expert owning each pool slot.""" return torch.repeat_interleave(torch.arange(self.num_experts, device="cuda"), self.tiles * TILE_M) diff --git a/stream_ep_tests/kernels/test_dw_gemm.py b/stream_ep_tests/kernels/test_dw_gemm.py new file mode 100644 index 000000000..fabb3d388 --- /dev/null +++ b/stream_ep_tests/kernels/test_dw_gemm.py @@ -0,0 +1,95 @@ +"""The backward's dW1 / dW2 grouped GEMMs over the padded pool, against a torch reference. + +Each dW GEMM contracts over an expert's whole padded slot range +(``cu_seqlens_k`` = ``expert_pool_block_offset * tile_m``). One operand's +padding rows are zero (``kernel_y_bwd`` writes them); the other's hold whatever +the uninitialized pool held, here NaN or inf. ``zero_padding_rows`` on that +operand must make padding contribute nothing, so every expert's gradient equals +the sum over its real slots only, and an empty expert's is zero. +""" + +import pytest +import torch +from quack.gemm import gemm + +from stream_ep.stream_moe.recv_pool_compress import zero_padding_rows +from stream_ep.stream_moe.stream_moe import default_tile_config +from stream_ep_tests.kernels._common import KERNEL_SHAPES, LAYOUTS, TILE_M, PoolLayout, randn +from stream_ep_tests.utils import assert_rows_close + +RTOL = 4e-3 + + +def dw_kwargs(which: str, H: int, I: int) -> dict: + """The tile config stream_moe_func launches dW1 / dW2 with at this shape.""" + cfg = default_tile_config(I, H) + tile_m = getattr(cfg, f"tile_m_{which}") + tile_n = getattr(cfg, f"tile_n_{which}") + return { + "tile_M": tile_m if tile_m is not None else cfg.tile_m, + "tile_N": tile_n if tile_n is not None else cfg.tile_n_a, + "cluster_M": getattr(cfg, f"cluster_m_{which}"), + "cluster_N": getattr(cfg, f"cluster_n_{which}"), + "pingpong": getattr(cfg, f"pingpong_{which}"), + "max_swizzle_size": getattr(cfg, f"swizzle_{which}"), + } + + +def padded_operands(layout: PoolLayout, garbage_cols: int, masked_cols: int, garbage: float): + """(garbage_side, masked_side): random real rows; padding is ``garbage`` / zero.""" + real = layout.real() + garbage_side = randn(layout.num_slots, garbage_cols, seed=1) + garbage_side[~real] = garbage + masked_side = randn(layout.num_slots, masked_cols, seed=2) + masked_side[~real] = 0 + return garbage_side, masked_side + + +def grouped_dw(layout: PoolLayout, a: torch.Tensor, b: torch.Tensor, **kwargs) -> torch.Tensor: + """dW[e] = a[slots_e].T @ b[slots_e] over each expert's padded slot range.""" + out = torch.full((layout.num_experts, a.shape[1], b.shape[1]), float("nan"), dtype=a.dtype, device="cuda") + cu_seqlens_k = (layout.block_offset() * TILE_M).contiguous() + gemm(a.t(), b.t(), out, None, None, cu_seqlens_k=cu_seqlens_k, **kwargs) + torch.cuda.synchronize() + return out + + +def reference_dw(layout: PoolLayout, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + real, expert = layout.real(), layout.slot_expert() + out = torch.zeros(layout.num_experts, a.shape[1], b.shape[1], device="cuda") + for e in range(layout.num_experts): + idx = (real & (expert == e)).nonzero().flatten() + out[e] = a[idx].float().t() @ b[idx].float() + return out + + +def operands(which: str, layout: PoolLayout, H: int, I: int, garbage: float): + """(a, b, garbage_side) as the backward passes them: dW1 = dL_dswiglu_in.T @ pool, + dW2 = dL_do_pool.T @ postact_a_for_dW2.""" + if which == "dW1": + pool, dL_dswiglu_in = padded_operands(layout, H, 2 * I, garbage) + return dL_dswiglu_in, pool, pool + dL_do_pool, postact = padded_operands(layout, H, I, garbage) + return dL_do_pool, postact, dL_do_pool + + +@pytest.mark.parametrize("garbage", [float("nan"), float("inf")], ids=["nan", "inf"]) +@pytest.mark.parametrize("which", ["dW1", "dW2"]) +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("shape", KERNEL_SHAPES) +def test_dw_gemm(shape, layout, which, garbage): + (H, I), layout = KERNEL_SHAPES[shape], LAYOUTS[layout] + a, b, garbage_side = operands(which, layout, H, I, garbage) + zero_padding_rows(garbage_side, layout.block_offset(), layout.frequency(), TILE_M) + dw = grouped_dw(layout, a, b, **dw_kwargs(which, H, I)) + assert_rows_close(dw, reference_dw(layout, a, b), RTOL, which) + + +@pytest.mark.parametrize("which", ["dW1", "dW2"]) +def test_dw_gemm_reads_padding(which): + """Without ``zero_padding_rows`` the NaN padding reaches the gradient, so the + test above exercises the zeroing rather than a GEMM that skips padding.""" + (H, I), layout = next(iter(KERNEL_SHAPES.values())), LAYOUTS["small"] + a, b, _ = operands(which, layout, H, I, float("nan")) + dw = grouped_dw(layout, a, b, **dw_kwargs(which, H, I)) + assert not torch.isfinite(dw).all(), "padding NaN did not reach dW" diff --git a/stream_ep_tests/kernels/test_recv_pool_compress.py b/stream_ep_tests/kernels/test_recv_pool_compress.py index 0c713fe4c..acb621e40 100644 --- a/stream_ep_tests/kernels/test_recv_pool_compress.py +++ b/stream_ep_tests/kernels/test_recv_pool_compress.py @@ -4,13 +4,16 @@ pool, where a token's row repeats in every slot it routes to, and re-expands it in backward. The round trip must reproduce every real slot bit for bit, never read padding into ``x_recv``, and leave padding slots of the re-expanded -pool exactly zero whatever ``x_recv`` holds. +pool exactly zero whatever ``x_recv`` holds. ``zero_padding_rows`` must zero +an expert-major pool's NaN / inf padding rows in place and leave real rows bit +for bit. """ import pytest import torch -from stream_ep.stream_moe.recv_pool_compress import compress_pool_to_recv, reexpand_recv_to_pool +from stream_ep.stream_moe.recv_pool_compress import compress_pool_to_recv, reexpand_recv_to_pool, zero_padding_rows +from stream_ep_tests.kernels._common import LAYOUTS, TILE_M from stream_ep_tests.utils import DTYPE @@ -54,3 +57,17 @@ def test_padding_zero_with_inf_in_x_recv(): expanded = torch.full_like(pool, float("nan")) reexpand_recv_to_pool(x_recv, recv, expanded) assert not expanded[recv < 0].any(), "re-expanded padding slots not zero" + + +@pytest.mark.parametrize("garbage", [float("nan"), float("inf")], ids=["nan", "inf"]) +@pytest.mark.parametrize("H", [512, 513, 3072]) +@pytest.mark.parametrize("layout", LAYOUTS) +def test_zero_padding_rows(layout, H, garbage): + layout = LAYOUTS[layout] + real = layout.real() + pool = torch.randn(layout.num_slots, H, device="cuda").to(DTYPE) + pool[~real] = garbage + expected = pool[real].clone() + zero_padding_rows(pool, layout.block_offset(), layout.frequency(), TILE_M) + assert torch.equal(pool[real], expected), "real rows changed" + assert not pool[~real].any(), "padding rows not zero"