Compare commits

...
Author SHA1 Message Date
c1ac451e39 fix(trainer): declare contiguous outputs in the fp8 and ring attention fakes (#3567)
Three custom-op fake kernels declared output strides copied from their
inputs, while the real kernels return freshly allocated contiguous
buffers. `torch.compile` trusts the fake, bakes its strides into an
`assert_size_stride` guard, and the guard fires at runtime. This showed
up first in the fp8 MoE backward with activation checkpointing off,
where `ac=full` had been hiding the expert backward inside a recompute
region:

```
assert_size_stride(buf2, (32, 1408, 4096), (5767168, 1, 1408), 'torch.ops.prime_rl.grouped_fp8_gemm_backward.default')
AssertionError: expected size 1408==1408, stride 4096==1 at dim=1; expected size 4096==4096, stride 1==1408 at dim=2
```

All three fakes now declare metadata that is a pure function of their
inputs' shapes and dtypes, independent of the inputs' strides, of the
`needs_grad_*` flags, and of an unstated bf16 contract.

- `grouped_fp8_gemm_backward`, active: MoE passes a transposed weight;
real `(524288, 1024, 1)` vs fake `(524288, 1, 512)`.
- `ring_attn::attention`, active: rope leaves `q` non-contiguous, so
real `(1024, 128, 1)` vs fake `(128, 32768, 1)`, on every CP ring step.
- `fp8_blockwise_mm_backward` and the grouped GEMM's `grad_x`, latent:
masked only because production inputs are contiguous.
- The fp8 kernels' unobservable placeholder allocations are contiguous
too, which is what drops the flag-conditional stride.
- `ring_attn.py` needed no real-kernel change, since `torch.cat` is
already unconditionally contiguous.
- `_compute_grad_weight` downcasts to `weight.dtype`, not a hardcoded
bf16; a no-op today, as call sites pre-cast.
- Verified already correct, left alone: both fp8 forward fakes,
`attention_backward`, and the forward's `softmax_lse`.
- `compile=on, ac=off, fp8 MoE` now completes a full forward and
backward on the GLM-4.5-MoE path.

Noticed while auditing, not addressed: `gpt_oss` has its own ring
implementation that bypasses this op.

## Verification

An `opcheck` test for the four fp8 ops was added in `02f3f684b` and
removed again in `49ce67cff`: it needs an SM90+ GPU and `deep_gemm`, so
it would only ever skip on CI's `vm` runner. To re-run it on a Hopper or
Blackwell node:

```
git show 02f3f684b:tests/unit/train/models/test_fp8_fake_kernels.py > tests/unit/train/models/test_fp8_fake_kernels.py
DG_JIT_CACHE_DIR=<warm deepgemm cache> uv run pytest tests/unit/train/models/test_fp8_fake_kernels.py -v
```

`torch.library.opcheck` with `test_utils=["test_schema",
"test_faketensor"]` compares the real op's output shape, stride, and
dtype against the fake's. On 8x H200 that is 26 passed post-fix; against
the pre-fix sources it fails exactly the 9 cases where a grad is
requested and its corresponding input is non-contiguous and passes the
other 17, so it discriminates rather than failing everywhere. The
ring-attention fake was verified the same way under a two-rank
`torchrun` harness, not committed since a distributed GPU test would
also only skip on CI. `uv run pytest tests/unit/train/models` is green
on the same node: 177 passed, 5 skipped.

Verified end to end with a harness built from production code only
(`Glm4MoeForCausalLM`, `configure_moe_runtime` with
`DeepGemmFP8MoEComputeConfig`, `apply_compile`, `setup_fsdp`):
`compile=on, ac=off` completes forward and backward at `ep` 1, 2, and 4,
up to real GLM-4.5-Air dimensions on 8 H200s. Restoring the pre-fix fake
reproduces the original `assert_size_stride` traceback at the same
shapes, so the check is not inert.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 12:59:53 -04:00
3 changed files with 12 additions and 12 deletions
@@ -17,7 +17,7 @@ from prime_rl.trainer.models.kernels.fp8_utils import (
def _compute_grad_weight(
x: torch.Tensor,
grad_output: torch.Tensor,
weight_shape: torch.Size,
weight: torch.Tensor,
padded_total_m: int,
block_to_group: torch.Tensor,
ks_tensor: torch.Tensor,
@@ -78,7 +78,7 @@ def _compute_grad_weight(
)
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_nt_contiguous
grad_weight = torch.zeros(weight_shape, device=x.device, dtype=torch.float32)
grad_weight = torch.zeros(weight.shape, device=x.device, dtype=torch.float32)
grouped_weight_grad(
x_fp8,
dy_fp8,
@@ -87,7 +87,7 @@ def _compute_grad_weight(
ks_tensor,
grad_weight,
)
return grad_weight.to(torch.bfloat16)
return grad_weight.to(weight.dtype)
@torch.library.custom_op("prime_rl::grouped_fp8_gemm", mutates_args=())
@@ -165,14 +165,14 @@ def _grouped_fp8_gemm_backward(
block_starts_tensor,
) = build_grouped_layout(offs, total_m=x.size(0))
grad_output = grad_output.contiguous()
grad_x = torch.empty_like(x)
grad_weight = torch.empty_like(weight)
grad_x = x.new_empty(x.shape)
grad_weight = weight.new_empty(weight.shape)
if needs_grad_weight:
grad_weight = _compute_grad_weight(
x,
grad_output,
weight.shape,
weight,
padded_total_m,
block_to_group,
ks_tensor,
@@ -230,7 +230,7 @@ def _grouped_fp8_gemm_backward_fake(
needs_grad_x: bool,
needs_grad_weight: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(x), torch.empty_like(weight)
return x.new_empty(x.shape), weight.new_empty(weight.shape)
def _grouped_fp8_gemm_setup_context(ctx, inputs, output) -> None:
@@ -48,8 +48,8 @@ def _fp8_blockwise_mm_backward(
x_2d = x.reshape(-1, x.shape[-1]).contiguous()
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
use_ue8m0 = ue8m0_for_device(grad_output.device)
grad_x = torch.empty_like(x)
grad_weight = torch.empty_like(weight)
grad_x = x.new_empty(x.shape)
grad_weight = weight.new_empty(weight.shape)
if needs_grad_x:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, use_ue8m0, block_size)
@@ -68,7 +68,7 @@ def _fp8_blockwise_mm_backward(
x_2d = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d, use_ue8m0, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d, use_ue8m0, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
grad_weight_fp32 = torch.zeros(weight.shape, device=weight.device, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
x_t_fp8,
@@ -90,7 +90,7 @@ def _fp8_blockwise_mm_backward_fake(
needs_grad_x: bool,
needs_grad_weight: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(x), torch.empty_like(weight)
return x.new_empty(x.shape), weight.new_empty(weight.shape)
def _fp8_blockwise_mm_setup_context(ctx, inputs, output) -> None:
@@ -272,7 +272,7 @@ def _ring_attention_forward_fake(
window_size_right: int,
attention_backend: str,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(q), q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
return q.new_empty(q.shape), q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
@torch.library.custom_op("prime_rl_ring::attention_backward", mutates_args=())