Skip to content
Merged
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
284 changes: 255 additions & 29 deletions benchmarks/bench_cake_moe_grouped_det_gemm.py

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions benchmarks/bench_cake_moe_grouped_gemm.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
early stop off so that every arm recomputes its forward), both gradients included.
Opt-in autograd rows over the same distributions: ``step_es``, that step with
checkpoint early stop on (the torch default: an arm whose inputs are saved
before its GEMM launches, ``cake`` and ``torch._grouped_mm``, skips the
recomputed forward); ``block`` / ``block_es``, one checkpointed MoE expert
before its GEMM launches, ``cake_det``, ``cake`` and ``torch._grouped_mm``,
skips the recomputed forward); ``block`` / ``block_es``, one checkpointed MoE expert
block with early stop off / on -- gate_up, ``silu(a) * b`` on its two halves,
down, with the gradients of ``x``, ``w1`` and ``w2`` -- in which only the
recompute of the down GEMM can be skipped. The rate of these rows counts the
Expand Down Expand Up @@ -263,9 +263,9 @@ def _step(autograd_fn, t, early_stop=False):
Early stop off (the ``step`` rows): every arm recomputes its forward GEMM,
``2 x forward + backward``. On (the torch default, the ``step_es`` rows): the
recompute stops once the region saved its last tensor, so an arm whose inputs are
saved before its GEMM launches (``torch._grouped_mm``, ``cake_grouped_mm``) does one
GEMM less, and one that launches inside ``Function.forward`` (``cake_det``,
``cake_inforward``) still recomputes it."""
saved before its GEMM launches (``torch._grouped_mm``, ``cake_grouped_det_mm``,
``cake_grouped_mm``) does one GEMM less, and one that launches inside
``Function.forward`` (``cake_inforward``) still recomputes it."""
return _checkpointed(autograd_fn, t, ("x", "w"), early_stop)


Expand Down
4 changes: 2 additions & 2 deletions flashinfer/experimental/cake/grouped_mm.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@
The mode of :func:`cake_grouped_mm` is fixed at its forward call: the backward
runs the package the forward chose (a non-reentrant activation-checkpoint
replay that recomputes the forward gives the same bits; with early stop on,
the non-deterministic package's replay may skip its forward GEMM, as a
built-in op's does). Called directly, the package
the replay of either package may skip its forward GEMM, as a built-in op's
does). Called directly, the package
``flashinfer.experimental.cake.cake_moe_grouped_gemm`` accepts only
``deterministic=False`` and, under torch's deterministic mode, its weight
gradient raises PyTorch's non-determinism alert (a ``RuntimeError``, or a
Expand Down
9 changes: 9 additions & 0 deletions flashinfer/experimental/cake_moe_grouped_det_gemm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,15 @@ programs always reduce in a fixed order, so `deterministic=False` currently
runs the same deterministic programs; `grouped_det_gemm_wgrad(..., out_dtype=torch.float32)`
gives an fp32 weight gradient. `CakeGroupedDetMm` calls the three programs as
plain functions; no torch custom op is registered.
The wrapper launches the forward GEMM after `CakeGroupedDetMm.apply` returns,
that is after autograd saved `x`, `w` and `offs`, as for a built-in op. Under
`torch.utils.checkpoint(..., use_reentrant=False)` with early stop on (the
default), the recomputation therefore stops before this GEMM when these are
the last saves of the innermost checkpointed region; a later save in that
region (of its output or of any other tensor) makes it run, with the same
bits. A direct `CakeGroupedDetMm.apply(x, w, offs, True)` launches inside
`forward` and is always recomputed, as is the wrapper under `torch.jit.trace`
and `torch.compile`.

## Host plan

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
# projection ``Y = X @ W[e].T`` with the activation gradient ``dX = G @ W[e]``
# and the weight gradient ``dW[e] = G[e].T @ X[e]`` in ``backward``.
# ``CakeGroupedDetMm`` calls the three generated programs as plain functions; no
# torch custom op is registered.
# torch custom op is registered. ``cake_grouped_det_mm`` launches the forward
# after ``CakeGroupedDetMm.apply`` returns, so autograd saves ``x``, ``w`` and
# ``offs`` before the GEMM runs, as it does for a built-in op: a non-reentrant
# checkpoint with early stop on (the torch default) then skips the recomputed
# GEMM when these are the last saves of the innermost checkpointed region.

from __future__ import annotations

Expand Down Expand Up @@ -64,23 +68,48 @@ def _bf16_rows(t: torch.Tensor) -> torch.Tensor:
return t


# Passed by ``cake_grouped_det_mm`` as the fifth argument of
# ``CakeGroupedDetMm.apply``: ``forward`` then allocates ``Y`` without launching,
# and the wrapper fills it after ``apply`` returns (after autograd saved the
# inputs).
_DEFER_FWD = object()


def _fill_fwd(
x: torch.Tensor, w: torch.Tensor, offs: torch.Tensor, y: torch.Tensor
) -> None:
"""The forward GEMM into ``y`` as ``forward`` runs it: grad mode off, so no node and no saved tensor."""
with torch.no_grad():
_fwd_op(x, w, offs, y.detach())


class CakeGroupedDetMm(torch.autograd.Function):
"""``Y = grouped X @ W[e].T`` with ``dX`` and ``dW`` from the Cake programs.

``x`` ``[sum_m, K]`` bf16, ``w`` ``[E, N, K]`` bf16, ``offs`` int32 device
end offsets ``[E]`` (or ``m_indptr`` ``[E + 1]``). ``backward`` returns
``dX`` ``[sum_m, K]`` bf16 and ``dW`` ``[E, N, K]`` in the dtype of ``w``;
both reductions are bitwise deterministic and empty groups give exact
zeros.
zeros. Through :func:`cake_grouped_det_mm` the forward GEMM runs after
autograd saved ``x``, ``w`` and ``offs``, so a checkpoint's early stop can
skip it; a direct ``CakeGroupedDetMm.apply(x, w, offs, deterministic)``
launches inside ``forward`` and a checkpoint always recomputes it, as does
the wrapper under ``torch.jit.trace`` and ``torch.compile``.
"""

@staticmethod
def forward(
ctx, x: torch.Tensor, w: torch.Tensor, offs: torch.Tensor, deterministic: bool
ctx,
x: torch.Tensor,
w: torch.Tensor,
offs: torch.Tensor,
deterministic: bool,
_launch=None,
):
num_groups = int(w.shape[0])
y = torch.empty(x.shape[0], w.shape[1], dtype=torch.bfloat16, device=x.device)
_fwd_op(x, w, offs, y)
if _launch is not _DEFER_FWD:
_fwd_op(x, w, offs, y)
ctx.save_for_backward(x, w, offs)
ctx.num_groups = num_groups
return y
Expand All @@ -103,7 +132,7 @@ def backward(ctx, grad_y: torch.Tensor):
ctx.num_groups, w.shape[1], w.shape[2], dtype=w.dtype, device=w.device
)
_wgrad_op(g, x, offs, dw, ctx.num_groups)
return dx, dw, None, None
return (dx, dw) + (None,) * (len(ctx.needs_input_grad) - 2)


def cake_grouped_det_mm(
Expand Down Expand Up @@ -134,10 +163,21 @@ def cake_grouped_det_mm(
``[sum_m, N]`` bfloat16. ``backward`` produces ``x.grad`` ``[sum_m, K]``
bfloat16 and ``w.grad`` ``[E, N, K]`` in ``w``'s dtype (bfloat16); use
:func:`grouped_det_gemm_wgrad` directly for an fp32 weight gradient.
The forward GEMM runs after autograd saved ``x``, ``w`` and ``offs``:
under a non-reentrant checkpoint with early stop on, the recomputation
skips it when these are the last saves of the innermost checkpointed
region, as for a built-in op.
"""
if x.dtype != torch.bfloat16 or w.dtype != torch.bfloat16:
raise ValueError(f"x and w must be bfloat16 (got {x.dtype} and {w.dtype})")
return CakeGroupedDetMm.apply(x, w, offs, bool(deterministic))
if torch.jit.is_tracing() or torch.compiler.is_compiling():
# A trace records ``apply`` only, and Dynamo cannot lift the deferred
# launch out of a checkpointed region: keep the launch inside ``forward``.
return CakeGroupedDetMm.apply(x, w, offs, bool(deterministic))
# ``apply`` saves x, w and offs; a checkpoint recomputation may stop inside it.
y = CakeGroupedDetMm.apply(x, w, offs, bool(deterministic), _DEFER_FWD)
_fill_fwd(x, w, offs, y)
return y


# The names of the package before the deterministic-family rename (when it was
Expand Down
4 changes: 4 additions & 0 deletions flashinfer/grouped_mm/cake.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ def cake_grouped_det_mm(
``[sum_m, N]`` bfloat16. ``backward`` produces ``x.grad`` ``[sum_m, K]``
bfloat16 and ``w.grad`` ``[E, N, K]`` in ``w``'s dtype (bfloat16); use
:func:`grouped_det_gemm_wgrad` directly for an fp32 weight gradient.
The forward GEMM runs after autograd saved ``x``, ``w`` and ``offs``:
under a non-reentrant checkpoint with early stop on, the recomputation
skips it when these are the last saves of the innermost checkpointed
region, as for a built-in op.
"""
from ..experimental.cake_moe_grouped_det_gemm.cake_autograd import (
cake_grouped_det_mm as _impl,
Expand Down
Loading
Loading