Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 11 additions & 12 deletions csrc/stream_ep.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1366,9 +1365,8 @@ std::tuple<torch::Tensor, torch::Tensor, EventHandle> 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1914,10 +1912,11 @@ std::tuple<torch::Tensor, torch::Tensor, EventHandle> 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);
Expand Down
53 changes: 29 additions & 24 deletions pixi.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions pixi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "*"

Expand Down
41 changes: 35 additions & 6 deletions stream_ep/stream_moe/recv_pool_compress.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
20 changes: 13 additions & 7 deletions stream_ep/stream_moe/stream_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
from stream_ep.stream_moe.recv_pool_compress import (
compress_pool_to_recv,
reexpand_recv_to_pool,
zero_padding_rows,
)


Expand Down Expand Up @@ -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 ────────────────
Expand Down Expand Up @@ -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(
Expand All @@ -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)
Expand All @@ -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):
Expand Down
4 changes: 4 additions & 0 deletions stream_ep_tests/kernels/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading