Repository navigation
Add an opt-in chunked causal-LM loss that keeps no full-vocabulary FP32 tensor - #8653
Conversation
Hugging Face's ForCausalLMLoss upcasts the whole [tokens, vocab] logits to FP32 and calls cross_entropy, which saves an FP32 log-softmax for backward; backward then allocates two more FP32 [tokens, vocab] tensors. At 8,192 tokens with Qwen3's 151,936-token vocabulary each is about 5 GB, and an allocator trace of AutoEP training on 16 H100s shows all three live at the step's peak, together about 15 of the 19 GB allocated during the step. ChunkedCausalLMLoss computes the same FP32 cross entropy one block of rows at a time: forward saves only the given logits and one FP32 log-sum-exp per token, and backward recomputes each block's softmax and writes the gradient straight into the logits' dtype, which is the dtype the stock path casts its FP32 gradient to. Shifting, ignore_index and num_items_in_batch follow ForCausalLMLoss. install_chunked_causal_lm_loss is opt-in and only replaces the stock ForCausalLMLoss. Tests compare against the stock loss directly, and through the forward and backward of a small Hugging Face causal LM. Signed-off-by: yh0903 <helloyu0903@gmail.com>
Signed-off-by: yh0903 <helloyu0903@gmail.com>
The PyTorch blocks make about six full FP32 passes over each block, so at S8192 and Qwen3's vocabulary forward plus backward took 35.2 ms on H100 against 20.8 ms for the stock loss. The Triton backend reads the logits once in forward (online log-sum-exp) and once in backward, writing the gradient once in the logits' dtype. backend="auto" uses it for CUDA logits when Triton is available; the PyTorch backend stays as the reference and the CPU path, and naming a backend that cannot run raises. Signed-off-by: yh0903 <helloyu0903@gmail.com>
The Triton kernels index the target by row with unit stride, so a strided target read the wrong labels, and they load the target's logit without a bounds check, so an out-of-range target silently read another row where cross_entropy fails. Targets are now made contiguous, and an out-of-range target fails through a device-side assert, which adds no host synchronization to the step. Signed-off-by: yh0903 <helloyu0903@gmail.com>
…second derivative Both backwards compute the gradient outside autograd: the Triton kernel's output carries no graph, and the PyTorch backend uses a log-sum-exp saved as a constant. With create_graph=True, a gradient penalty built on the Triton gradient was therefore treated as a constant and silently dropped, and the PyTorch backend failed only through an in-place-modification error. Both backwards now raise under create_graph=True. Ordinary backward, including under reentrant and non-reentrant activation checkpointing, runs with grad mode off and is unaffected. Signed-off-by: yh0903 <helloyu0903@gmail.com>
Its signatures use PEP 604 unions, which Python 3.8 and 3.9 evaluate at definition time and reject, while setup.py still lists both versions. Postponed evaluation of annotations keeps the module importable there. Signed-off-by: yh0903 <helloyu0903@gmail.com>
modal-torch-latest selects tests only under tests/unit/v1, and aws-torch-latest runs tests/unit/v1, so in tests/unit/runtime the Triton and CUDA cases would never run in CI; only the CPU subset would, through cpu-torch-latest. Signed-off-by: yh0903 <helloyu0903@gmail.com>
The section was inserted as a new heading just above AutoEP's Constraints list, so those constraints read as part of the loss section. It now follows them, and states that backward with create_graph=True raises. Signed-off-by: yh0903 <helloyu0903@gmail.com>
f1bac14 to
6316236
Compare
0z5a
left a comment
There was a problem hiding this comment.
I reproduced two correctness issues on the current PR head using the public ChunkedCausalLMLoss wrapper and the stock Hugging Face loss as reference. Valid-input checks passed: 27 selected PR tests and a two-step BF16 CUDA Llama run. The inline comments cover the failing input cases.
| safe_target = torch.where(valid, target, torch.zeros_like(target)) | ||
| log_sum_exp = torch.empty(n_rows, dtype=torch.float32, device=logits.device) | ||
| target_logits = torch.empty(n_rows, dtype=torch.float32, device=logits.device) | ||
| for start in range(0, n_rows, block_rows): |
There was a problem hiding this comment.
block_rows reaches this loop without validation. With block_rows=-1, the forward and backward loops skip every row, leaving torch.empty loss and gradient buffers uninitialized; through ChunkedCausalLMLoss, I observed loss 0.000000 versus 2.596814 from the stock HF loss on the same input. block_rows=0 is also accepted by the constructor, then fails here in range. Please reject non-positive row counts and add regression cases for 0 and -1.
| if reduction not in ("none", "sum", "mean"): | ||
| raise ValueError(f"Unsupported reduction: {reduction!r}") | ||
| # The Triton kernels index both tensors by row with unit stride. | ||
| target = target.to(device=logits.device, dtype=torch.long).contiguous() |
There was a problem hiding this comment.
This cast silently changes the advertised ForCausalLMLoss behavior. With floating shift_labels containing 1.5, the stock HF loss rejects the input, while ChunkedCausalLMLoss truncates it and returns a finite loss (2.369995 in my reproduction). Boolean targets are also accepted here but rejected by PyTorch cross entropy. Please validate class-index dtypes before this conversion and cover floating-label rejection in a regression test.
tohtana
left a comment
There was a problem hiding this comment.
Hi @yh0903,
Thank you for submitting a great PR! I confirmed a significant performance improvement and memory reduction on my side.
Hi @0z5a, I appreciate your help with reviewing this! I think your comments are valid.
I didn't find any other issue. @yh0903 Let's merge this once the concerns from @0z5a are addressed.
…speedai#8671) ## Summary AutoEP's native collective path (`comm_backend="comm"`, NCCL all-to-all) puts each rank's received rows into expert-major order before the grouped GEMM, and back afterwards, with `permute_by_local_expert` and `unpermute_by_local_expert`. The `autoep_size=1` path uses the same two functions. Both moved every routed row more often than needed: - **`permute_by_local_expert`:** - appended a zero row to the received rows with `torch.vstack`, a full copy, before indexing the padded expert-major buffer; - its backward was an accumulating `index_put`, i.e. a sort plus atomic adds. - **`unpermute_by_local_expert`:** zero-filled an `[N + 1, H]` buffer, then scattered into it with an elementwise `index_put`. On CUDA with Triton, both directions are now gathers: | Direction | Forward | Backward | |---|---|---| | permute | a Triton row gather that writes zero rows where `generate_permute_indices` marked padding (`-1`) | `index_select` through the inverse permutation | | unpermute | `index_select` through the inverse permutation | the same padded row gather | **Scope.** - This is a local, on-rank change to the expert reorder. - The all-to-alls send and receive the same rows in the same order, so communication volume is unchanged, and no communication/computation overlap is added. - `generate_permute_indices` is unchanged, and the DeepEP backend does not call these functions. - There is no switch: the gathers replace the previous code for 2-D CUDA tensors when Triton is available, because their results are equal to it (see Numerics). Other tensors keep the previous code. ## Permutation contract `generate_permute_indices` sends each received row to exactly one slot of the padded expert-major buffer and marks every other slot `-1`. The gathers rely on that one-to-one mapping: - **Permute forward:** writes each output row once: the row mapped to its slot, or zeros at a padding slot. - **Inverse permutation:** a scatter of slot positions into scratch of `N + N_padded` entries. Each padding slot goes to its own entry past `N`, so no entry is written twice, and every row's entry is written. - **Unpermute forward:** reads each row's slot through the inverse; padding rows are never read. - **Backward:** each direction's backward is the other gather. A row's gradient is that of the one slot it occupied, not a sum, and padding slots get zero gradient. Both backwards are autograd functions themselves, so double backward goes through the same pair. - **Top-k:** each received row is one (token, expert) assignment. Summing a token's top-k expert outputs, in the combine, and accumulating its top-k gradients, in the backward of the routed gather `x[token_indices // top_k]`, stay in the surrounding code, unchanged. These helpers are therefore not a general gather/scatter. `permute_rows`, `unpermute_rows` and `inverse_permutation` require the valid entries to be a complete one-to-one permutation of the rows, and do not check it; the docstrings say so. Both callers meet the requirement, because the counts sum to the number of rows: - with expert parallelism, each all-to-all receives exactly the row sums of the exchanged counts; - with `autoep_size=1`, the `T × top_k` routed rows are sorted by expert, and the counts are per expert. The previous code tolerated counts that sum to fewer rows (the rows left out came back as zeros); the gathers do not. The row gather reads its index by linear offset, so it now makes the index contiguous first, as it already did the source rows. ## Numerics The gathers only move data. Outputs, gradients and double-backward gradients equal the previous implementation's under `torch.equal`, which does not distinguish `+0.0` from `-0.0`. We also compared bit patterns on H100, in bf16, fp16 and fp32, with inputs and upstream gradients of which a quarter were `-0.0`: - Both outputs and the unpermute gradient are bitwise identical to the previous implementation's. - The permute gradient differs only where the upstream gradient is `-0.0`. The previous backward accumulated it into a zero-filled buffer, giving `+0.0`, whereas the gather passes `-0.0` through. ## Validation **Unit tests** (below): the earlier H100 validation passed these 27 tests and the existing `tests/unit/v1/moe/test_autoep_unit.py` (217 tests). The review follow-up additionally validates all 27 reorder cases with plain, forked and xdist-forked execution. **Local token movement**, one rank's work for one MoE layer, on one H100: - Shape: T tokens, top-8 of 128 experts, EP16 (8 local experts), hidden 2048. - The all-to-alls are replaced by the identity and the experts by a scalar multiply, so only the local work is timed. - Each iteration runs a no-grad forward, a grad forward and a backward, as under reentrant activation checkpointing. - The whole local chain is timed; only the reorder differs between the two columns. | T | Before | After | Saving × 48 layers | |---|---|---|---| | 8192 | 7.04 ms | 5.12 ms | −92 ms | | 16384 | 13.53 ms | 9.58 ms | −190 ms | At T=8192, per grad forward, the permute goes from 0.44 to 0.27 ms and the unpermute from 0.71 to 0.21 ms. **End to end**, Qwen3-30B-A3B training with AutoEP: - 16× H100, expert parallel 16, 48 layers, micro-batch 1, BF16, ZeRO stage 1, reentrant activation checkpointing, and a fixed routing, so both arms route identically. - `comm_backend="comm"` with `combine_impl="fused_weighted_sum"` and `async_split_plan=true`. - Both arms also carry other opt-in kernels under review: fused RMSNorm (deepspeedai#8645, deepspeedai#8664), fused RoPE (deepspeedai#8663), chunked loss (deepspeedai#8653) and BF16 gradient release (deepspeedai#8654). The arms differ only in this PR. - Both arms ran on the same 16 GPUs in mirrored order, two runs each. | Sequence | Before | After | Change | |---|---|---|---| | 8192 | 2649.4 ms | 2554.3 ms | −95.2 ms (−3.6%) | | 16384 | 5434.6 ms | 5244.5 ms | −190.2 ms (−3.5%) | - Each arm's two runs agree within 5 ms. - The end-to-end saving matches the local estimate scaled to 48 layers (−92 and −190 ms). - Peak memory and the step-0 loss are identical in both arms. These numbers come from one model, two sequence lengths, one GPU type and one parallel layout. The saving scales with the rows each rank reorders, so its share of the step depends on the configuration. Small shapes are not guaranteed to improve in every direction: a review microbenchmark on RTX PRO 4500 found slower forwards at 8,192 rows × hidden 1,025, while both backwards improved. This PR does not add a shape-dependent dispatch heuristic. The local and end-to-end numbers were measured with this PR's first commit. The later commits add `index.contiguous()`, a no-op for the contiguous indices both callers pass, and change docstrings and tests. The forked-runner review follow-up changes only test execution, not the runtime implementation. ## Tests `tests/unit/v1/moe/test_autoep_permute_rows.py`, 27 tests: 26 need CUDA and Triton, and 1 runs on the host. All compare against the previous zero-row-and-index implementation with `torch.equal`: - forward and backward of both reorders: - bf16 and fp32; - hidden 2048, 100 and 1; - source-major `[ep, E_local]` counts with and without empty experts, and aggregated `[E_local]` counts; - fp16 and bf16 rows read through a column-strided view, with column-major upstream gradients, in both directions, including the output strides; - double backward of both reorders; - a round trip with zero padding; - zero tokens; - the row gather with both padding encodings, through a contiguous and a strided index; - host tensors keeping the previous code. Results: - 1× NVIDIA H100 80GB HBM3, Python 3.12, torch 2.10 (CUDA 13.0), Triton 3.6.0: 27 passed, and 217 together with `tests/unit/v1/moe/test_autoep_unit.py`. - The same 27 tests against this PR's first commit, the code the timings used: 26 passed. The strided-index case failed, because that commit read the index as if contiguous. - CPU, torch 2.14: 1 passed, 26 skipped. - Forked-runner review regression on H100, torch 2.10 (CUDA 13.0), Triton 3.6.0: plain pytest, `pytest --forked` and `pytest -n 4 --forked` each pass all 27 cases, with no skips and no bad-fork errors. In the same environment, the previous tests fail under `--forked` (26 failed, 1 host case passed), reproducing the reported issue. - CPU review regression, torch 2.14: `--forked` and `-n 4 --forked` each give 1 passed, 26 skipped. - `pre-commit run --files` on the changed files: passed. ## CI - `cpu-torch-latest` runs the host test and skips the rest. - The test file is under `tests/unit/v1`, in the scope of both AWS and Modal GPU CI; Modal executes the selected GPU tests when the PR enters the merge queue. - `aws-torch-latest` uses `pytest -n 4 --forked`. The GPU cases now use `DistributedTest` with `world_size=1`, launching clean workers even when CUDA was touched while importing DeepSpeed during collection. These local operator tests do not need a process group (`init_distributed=False`). CUDA availability is checked by the runner during test execution, not by this file's collection-time skip condition. The host case remains an ordinary test, and all 27 cases and their numerical assertions are unchanged. ## Not covered - ROCm: PyTorch reports ROCm devices as `cuda`, so the gathers would be used there, as the existing Triton index generation is. Neither was tested on ROCm here. - Inputs that break the permutation contract. It is not checked; both callers meet it by construction. - `torch.compile` of the MoE layer itself. AutoEP's regional compilation keeps that layer eager, and the path already launched Triton kernels there. - Models, sequence lengths, hardware and parallel layouts other than the ones above. --------- Signed-off-by: yh0903 <helloyu0903@gmail.com> Co-authored-by: pengdurice <pengduhit@gmail.com>
…eepspeedai#8663) ## Summary Adds an opt-in fused Triton kernel for Hugging Face's split-half rotary position embedding, `apply_rotary_pos_emb`, as used by Llama-, Mistral-, Qwen- and DeepSeek-V3-style models: ```python from deepspeed.ops.triton_ops.fused_rotary_pos_emb import replace_rotary_pos_emb patched = replace_rotary_pos_emb(model) # number of modeling modules patched; 1 for Qwen3-30B-A3B ``` The eager function, `q * cos + rotate_half(q) * sin`, runs several elementwise kernels, each reading and writing the whole query or key tensor, and its backward does the same again. The fused kernel reads and writes each tensor once per pass and applies each position's `cos`/`sin` to all of that position's heads. Nothing changes unless `replace_rotary_pos_emb` is called. ## Semantics and safety - **Process-wide patch.** Attention layers look `apply_rotary_pos_emb` up in their modeling module, so the installer replaces it there. The replacement applies to every model of that architecture in the process, not only to `model`. Calling it again is a no-op, and `restore_rotary_pos_emb()` undoes it. - **Which modules.** A modeling module is patched only if all of these hold: - one of the model's submodules is defined in it; - it is listed in `SUPPORTED_ROTARY_MODULES` (Llama, Mistral, Mixtral, Qwen2, Qwen2-MoE, Qwen3, Qwen3-MoE, DeepSeek-V3); - its `apply_rotary_pos_emb` and `rotate_half` still have the split-half expression's code: the same bytecode, names, constants and defaults, whatever their docstrings. Constants are compared because bytecode refers to them by index: a `rotate_half` that splits at a quarter, or along another axis, otherwise has the same bytecode. Several architectures define functions of the same name that rotate part of the head dimension or add casts (for example Phi-3 and OLMo-2). A module whose functions differ is left alone with a warning. This includes transformers releases whose `apply_rotary_pos_emb` still takes `position_ids`, such as 4.51. - **Fallback.** For any input the kernel does not cover, the patched function runs the original eager function and warns once. Uncovered inputs are: - dtypes other than bf16/fp16, or mixed dtypes; - tensors not on one CUDA device; - an odd head dimension, one over 512, or one without unit stride; - shapes whose batch, sequence or head dimension do not match `cos`/`sin`; - `unsqueeze_dim` other than 1 or 2; - `cos`/`sin` that require grad. Without Triton, or on ROCm, it always runs eager. - **Direct call.** `fused_apply_rotary_pos_emb` applies the kernel directly and raises on unsupported inputs instead. - **Launch device.** Forward and backward select the inputs' CUDA device for the Triton launch, use that device's current stream, and restore the caller's current device. Inputs need not be on the device that was current when the function was called. - **Autograd.** Gradients are first order, for `q` and `k`; `cos` and `sin` are constants. Double backward raises. ## Numerics and layout Every product and sum is rounded to the input dtype where the eager expression rounds it. The kernel is compiled with `enable_fp_fusion=False`, because an FMA contraction would skip a product's rounding. Outputs and the gradients for `q` and `k` equal eager's element for element under `torch.equal`, which does not distinguish `+0.0` from `-0.0`. Layout: - For dense inputs, such as attention's transposed projection, outputs keep the input strides, as eager's do. - Other non-contiguous inputs can give outputs laid out differently from eager's, with equal values. - The gradients for `q` and `k` take the outputs' layout, whereas eager's follow the incoming gradient. Weight gradients computed from them further back can therefore differ in the last bits (see the attention block below). ## Validation Three levels, reported separately. **1. Operator.** Earlier validation passed the original 32 cases on one H100. The review follow-up adds two cross-device cases (BF16/FP16); current regression results are listed below. **2. Full attention block, one H100.** Qwen3-30B-A3B attention layer (32 query heads, 4 KV heads, head dim 128). The unit is forward, recompute and backward under reentrant activation checkpointing; each arm ran twice in mirrored order. | Sequence | Eager RoPE | Fused RoPE | Saved per layer | RoPE segment | |---|---|---|---|---| | 8192 | 9.27 ms | 7.80 ms | 1.46 ms | 1.57 → 0.19 ms | | 16384 | 26.62 ms | 23.66 ms | 2.96 ms | 3.13 → 0.39 ms | - The block output and the block's input gradient equal eager's. - The `q_proj` and input-norm weight gradients differ from eager's by a relative 4e-5. A `torch.compile`d RoPE moves them too (8e-6 and 1e-5). This comes from the layout of the gradient the weight GEMMs receive, not from RoPE's arithmetic. - The fused kernel is about 0.2–0.4 ms per layer faster than a `torch.compile`d RoPE configured to reproduce eager rounding. **3. End to end, together with the narrow-row RMSNorm change.** AutoEP training of Qwen3-30B-A3B: - 16× H100, expert parallel 16, 48 layers, one sequence per GPU, BF16, activation checkpointing. - Both arms use other opt-in AutoEP changes, including the fused row weighting (deepspeedai#8644), fused RMSNorm (deepspeedai#8645) and chunked loss (deepspeedai#8653). - "After" adds this PR and a narrow-row path for the fused RMSNorm (a follow-up to deepspeedai#8645), and nothing else. - Both arms ran on the same 16 GPUs, two runs each. | Sequence | Before | After | Change | |---|---|---|---| | 8192 | 1713.8 ms | 1654.2 ms | −3.5% | | 16384 | 3631.7 ms | 3510.5 ms | −3.3% | - At 8192 the result separates: both "after" runs are below both "before" runs. At 16384 the run ranges overlap, so that result is indicative. - These numbers cover both changes and cannot be split between them. In the attention-block measurement scaled to 48 layers, RoPE accounts for 70 of the 84 ms the two save at 8192, and 142 of 179 ms at 16384. End to end, about 70% of that combined estimate shows up. - Peak allocated memory is unchanged. - The step-0 loss differs by 8e-4. That comes from the narrow-row RMSNorm's reduction order, since RoPE's forward equals eager's. Final-step losses differ by at most 0.0023, within the 0.0016–0.0068 spread between runs of the same arm. This is a short-run check, not a convergence result. The attention-block and end-to-end numbers were measured with this PR's kernel and autograd function. Earlier follow-ups hardened the installer check, tests and documentation. The multi-GPU review follow-up adds an input-device guard to the shared forward/backward launcher; kernel arithmetic and launch configuration are unchanged. The existing performance measurements were not rerun for this correctness fix. ## Tests `tests/unit/v1/ops/triton_ops/test_fused_rotary_pos_emb.py`, 34 tests. They need CUDA and Triton and are skipped otherwise; the two cross-device cases additionally require two visible CUDA devices. Comparisons with eager use `torch.equal`. Coverage: - forward and backward in bf16/fp16 across shapes, for attention's transposed projection and for contiguous inputs, including output and gradient strides; - `unsqueeze_dim=2`, a table broadcast over the batch, non-contiguous incoming gradients, an unused output leaving no gradient, an empty sequence, and double backward raising; - every rejected input on the direct call, and the eager fallback of the installed function; - an installed two-layer Qwen3 (eager attention, small shapes) whose logits and every parameter gradient equal eager's; - installer idempotence and restore, and an unlisted model; - refusal of a changed expression, and of two `rotate_half` variants that differ from the split-half one only in constants; - acceptance of functions that differ only in their docstrings. - BF16/FP16 inputs and a non-default stream on one device while another device is current: compare outputs and both input gradients against eager, and check caller device and stream restoration. The rejected-input cases are parametrized by name and built inside the test, so collection creates no tensors on any device. Results: - 1× NVIDIA H100 80GB HBM3, Python 3.12, torch 2.10 (CUDA 13.0), Triton 3.6.0, transformers 5.12.0: 32 passed. - The same tests against the previous installer check, which compared bytecode, names and defaults but not constants: 30 passed. The two constant-variant tests failed because that check patched the module. - CPU review regression: 34 skipped under `pytest -n 4 --forked`. - Multi-GPU review regression on two NVIDIA H100 80GB HBM3 GPUs, torch 2.10 (CUDA 13.0), Triton 3.6.0, transformers 5.12.0: the full suite passes all 34 cases under `pytest --forked`, with no skips. The two BF16/FP16 cross-device cases also pass plain pytest and `pytest -n 4 --forked`. - With the same new tests and the previous runtime, both cross-device cases fail with the reported `Pointer argument ... cannot be accessed from Triton` error. This confirms the device guard fixes the reported issue. - Code check without a GPU, on transformers 5.12 and 5.17 under Python 3.13 and 3.14: all eight listed modules still match. The functions of Phi-3, OLMo-2, GPT-NeoX, Qwen3-Next, GLM-4-MoE, ERNIE-4.5-MoE and Cohere, none of them listed, are refused. - `pre-commit run --files` on the changed files: passed. ## CI - `cpu-torch-latest` collects the file and skips it. - `python ci/tests_fetcher.py --base upstream/master --explain` selects exactly this file. `modal-torch-latest` runs it on the GPU, without `--forked`, when the PR enters the merge queue. - `aws-torch-latest` runs `tests/unit/v1` with `pytest --forked`. The cases now use `DistributedTest(world_size=1, init_distributed=False)` to run in clean workers despite CUDA state created during collection. This file no longer probes CUDA availability in its collection-time skip condition; process-wide installer patches are restored in the worker that installed them. Documentation: a new "Fused rotary position embedding (experimental)" section in `docs/code-docs/source/autoep.rst`, before the AutoEP constraints. ## Not covered - Architectures outside `SUPPORTED_ROTARY_MODULES`. For example, Gemma's functions also match the split-half expression but are not listed or tested. - Transformers releases whose `apply_rotary_pos_emb` takes `position_ids`, which are left unpatched. - Partial, interleaved or other RoPE variants, fp32, ROCm, and `torch.compile`/`torch.func` transforms. - Matching eager's layout for non-dense inputs; the values are equal. - Splitting the end-to-end gain between this PR and the narrow-row RMSNorm change, and long-run convergence. --------- Signed-off-by: yh0903 <helloyu0903@gmail.com> Co-authored-by: Masahiro Tanaka <81312776+tohtana@users.noreply.github.com>
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Supported-version compatibility, input validation, and fork-safe test collection issues remain.
Review effort: Balanced
Findings: 1
Open (5)
What changed in this PR
Adds an opt-in, memory-efficient causal-LM cross-entropy implementation compatible with Hugging Face models.
Changes:
- Adds chunked PyTorch and Triton loss backends.
- Adds correctness, integration, and memory tests.
- Documents installation and behavior.
| File | Description |
|---|---|
deepspeed/runtime/chunked_cross_entropy.py |
Implements loss backends and model installer. |
tests/unit/v1/runtime/test_chunked_cross_entropy.py |
Tests semantics, gradients, and memory usage. |
docs/code-docs/source/autoep.rst |
Documents the opt-in loss. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| # silently read another row. Asserting on the device fails the way cross_entropy does, without the host | ||
| # synchronization a Python-side check would add to every step. | ||
| out_of_range = (target != ignore_index) & ((target < 0) | (target >= logits.shape[-1])) | ||
| torch._assert_async(~out_of_range.any(), f"Target is out of range for vocabulary size {logits.shape[-1]}") |
| if reduction not in ("none", "sum", "mean"): | ||
| raise ValueError(f"Unsupported reduction: {reduction!r}") | ||
| # The Triton kernels index both tensors by row with unit stride. | ||
| target = target.to(device=logits.device, dtype=torch.long).contiguous() |
| if block_rows is None: | ||
| block_rows = _block_rows(logits.shape[-1]) | ||
| loss = _ChunkedCrossEntropy.apply(logits, target, ignore_index, block_rows) |
| model.loss_function = loss_function | ||
| if model.loss_function is not loss_function: | ||
| raise ValueError("Unable to install the chunked causal-LM loss: the model's loss_function is not writable") |
|
|
||
| loss_utils = pytest.importorskip("transformers.loss.loss_utils") | ||
|
|
||
| _TRITON_ON_CUDA = torch.cuda.is_available() and triton_backend_available() #ignore-cuda |
Signed-off-by: yh0903 <helloyu0903@gmail.com>
Signed-off-by: yh0903 <helloyu0903@gmail.com>
Reject non-positive or fractional row blocks and non-long class indices before execution, without changing valid-input math or supplied shift-label precedence. Use the supported Torch 2.0 assertion signature and report rejecting loss-function properties explicitly. Defer the shared Triton driver import to the test worker and use import-safe device discovery. Cover direct calls, wrappers and installed Hugging Face models, plus documented legacy API and actual fork/allocation contracts. Kernels, both backwards and existing numerical thresholds are unchanged. Signed-off-by: yh0903 <helloyu0903@gmail.com>
|
Thanks @0z5a and @tohtana for the review. Fixed in the later commits, after syncing the branch with recent master. Both input issues are addressed: constructor, installer and direct calls now reject non-positive row blocks before execution, and class-index targets must be I also addressed the follow-up comments: the existing version helper selects Torch 2.0’s one-argument async assertion API, and read-only/rejecting loss properties produce an actionable installer error. Collection uses NVML-based GPU discovery and defers the loss runtime, including the shared Triton driver probe to the worker. |
tohtana
left a comment
There was a problem hiding this comment.
Looks good to me, thank you!



Summary
Adds an opt-in replacement for Hugging Face's
ForCausalLMLossthat computes the same FP32 cross entropy without materializing any FP32[tokens, vocab]tensor.ForCausalLMLossupcasts the whole logits tensor to FP32 and callscross_entropy, which saves an FP32 log-softmax for backward; backward then allocates two more FP32[tokens, vocab]tensors. At 8,192 tokens with Qwen3's 151,936-token vocabulary each is 4.98 GB, and all three are alive when backward starts.install_chunked_causal_lm_loss(model)sets the model'sloss_functiontoChunkedCausalLMLoss:backend="auto"picks Triton when it can run, and naming a backend that cannot run raises instead of substituting.ForCausalLMLossand refuses any otherloss_function. Nothing changes unless it is installed.Semantics
As in
ForCausalLMLoss:ignore_index, unlessshift_labelsis given;torch.long; floating-point, boolean and other non-long targets are rejected rather than silently converted. Whenshift_labelsis supplied, only those actual targets are checked; unusedlabelsretain the stock loss's behavior;ignore_indexget zero loss and zero gradient;num_items_in_batchthe loss is the mean over non-ignored tokens (NaN if every token is ignored); with it, the sum divided bynum_items_in_batch;Beyond that:
block_rowsmust be a positive integer orNonefor automatic sizing. Constructor, installer and direct calls reject invalid values before a backend runs, including when the selected backend would not use row blocking;cross_entropydoes, without adding a host synchronization;required_torch_versionhelper to call Torch 2.0's one-argument API and supply the message only on Torch 2.1+;loss_functionproduces an actionable installer error, including property setters raisingAttributeErrororTypeError;create_graph=Trueraises, because the gradient is computed outside autograd and a second derivative would otherwise be silently missing.Results (NVIDIA H100 80GB HBM3)
Operator speed. Loss forward plus backward alone at 8192 × 151936 BF16 logits, median of 40 alternating iterations:
ForCausalLMLossMemory, end to end. AutoEP training of Qwen3-30B-A3B (48 layers, sequence length 8192, EP16 on 16 GPUs, BF16, ZeRO stage 1, reentrant activation checkpointing), four mirrored repeats per arm that differ only in the loss. Both arms also use the opt-in fused row weighting (#8644) and fused RMSNorm (#8645).
In the stock arm, the three FP32
[tokens, vocab]tensors account for 14.9 GB of the memory live at the peak.Step time, end to end. In the same runs, the median step is 1763.6 ms stock and 1752.8 ms chunked (−0.6%, 95% interval [−6.0%, +2.9%]). The ~18 ms the operator saves is about 1% of the step, below what this comparison resolves, so no end-to-end speedup is claimed.
Training loss. Step 0 is identical. Over 24 steps the largest cross-arm difference is 0.0098, within the 0.0078–0.0124 spread between repeats of the same arm. This is a short-run check, not a convergence result.
These operator and end-to-end numbers were measured at the "Compute the chunked causal-LM loss with Triton on CUDA" commit. For the contiguous, in-range targets used there, the later commits add a no-op
.contiguous(), a device-side range check of the targets, and a grad-mode check in backward.The input-validation follow-up adds only API guards and compatibility handling. Triton kernels and both autograd implementations are byte-identical to the previously validated head. Existing memory/performance evidence is reused; no large-vocabulary allocation test or full E2E was rerun for this follow-up, and the historical timings are not new measurements of the added guards.
Tests
tests/unit/v1/runtime/test_chunked_cross_entropy.py: the original 28 cases plus input/installer/compatibility regressions (50 cases total):ForCausalLMLossfor BF16, FP16 and FP32 on both backends, across Triton tile boundaries;num_items_in_batch, a givenshift_labels, ignored rows (zero gradient) and all-ignored (NaN), matching the stock loss;create_graph=Trueraising on both backends, and a named backend that cannot run raising;shift_labelsoverriding unused floating/absent labels; non-writable loss properties leaving the stock function unchanged; Torch 2.0's one-argument assertion contract; and fresh collection followed by a real fork and CUDA allocation.Results:
pytest --forkedeach passed 49 cases, 0 skipped. Only the previously validated large-vocabulary allocator case was deselected. Both runs retain the original loss/gradient tolerances.create_graphguard: 27 passed, and the Tritoncreate_graphcase failed because the second derivative was silently dropped.pre-commit run --fileson the changed files: passed.CI
cpu-torch-latestruns the CPU cases (30 after this follow-up). Collection uses NVML-baseddevice_countand importability checks only. The loss runtime is imported by a worker-local fixture, because the shared Triton helper probes its driver on import; this prevents parent-process CUDA initialization before--forkedworkers without changing the shared helper.tests/unit/v1, wheremodal-torch-latestselects tests andaws-torch-latestruns them.python ci/tests_fetcher.py --base upstream/master --explainselects exactly this file;modal-torch-latestruns its selection on the GPU when the PR enters the merge queue.Documentation: a new section at the end of
docs/code-docs/source/autoep.rst.Not covered
ForCausalLMLoss.