Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions .github/workflows/npu_unit_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ jobs:
- name: Run ops tests
run: |
uv run --frozen pytest -v -s -x tests/ops/test_comp.py
uv run --frozen pytest -v -s -x tests/ops/test_chunk_loss.py tests/ops/test_chunk_loss_saved_tensor_hooks.py tests/ops/test_chunk_loss_saved_hooks.py
uv run --frozen pytest -v -s -x tests/ops/test_moe_hw_gate.py
uv run --frozen pytest -v -s -x tests/ops/test_npu_kernels.py
- name: Run utils tests
Expand Down
18 changes: 18 additions & 0 deletions docs/design/kernel_selection.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ and DeepSeek V4's `hc_mult=4` layout.
model:
ops_implementation:
cross_entropy_loss_implementation: liger_kernel # default; set to "chunk_loss" / "npu" / "eager" on NPU
cross_entropy_loss_release_cache: false # opt in on memory-constrained chunk-loss profiles
```

**Field:** `OpsImplementationConfig.cross_entropy_loss_implementation`
Expand All @@ -203,6 +204,23 @@ The `npu` chunk-loss binds only to `ForCausalLM` and
`labels[..., 1:]` shift (incompatible with token-level classification
labels).

`cross_entropy_loss_release_cache=true` adds a stream synchronization and
allocator-cache release after the chunked kernel returns. On the plain CE path
this runs after the outer saved-tensor hook has packed the precomputed
input/lm-head gradients; on the `return_log_probs` and top-k distillation
paths it runs in the dispatch shim after those chunked helpers return. It can
lower the peak memory carried into model backward on constrained accelerators,
but it may reduce throughput through synchronization and allocator churn. The
default is `false`; this setting has no effect on the `eager` or
`liger_kernel` implementations.

Note on activation offload: the chunked CE path installs a nested identity
`saved_tensors_hooks` around the short-lived per-chunk graph so vocab-sized
FP32 logits stay on device (offloading them would be pure transfer cost).
That deliberately excludes the largest transient from CPU activation offload;
`cross_entropy_loss_release_cache` is the opt-in mitigation for reclaiming
that working set before model backward.

Selecting `liger_kernel` requires that the model's forward pass provide
`hidden_states=` and `weights=self.lm_head.weight` through
`self.loss_function(...)` — the Liger fused linear+CE kernel does the
Expand Down
1 change: 1 addition & 0 deletions docs/usage/arguments.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ NPU validation runs at two times:
| attn_implementation | `Optional[Literal[...]]` | `"flash_attention_2"` | Attention implementation. Supported public values include `eager`, `sdpa`, `flash_attention_2/3/4`, `flash_attention_2_hub`, `flash_attention_3_hub`, `flex_attention`, `magi_attention`, and `native-sparse`. Under the VeOmni modeling backend, Flash, Flex, and Magi values resolve to SP-aware registry names. The opt-in Hub backends require `MODELING_BACKEND=veomni`, `kernels==0.16.0`, and a compatible version-1 artifact from `kernels-community/flash-attn2` or `kernels-community/flash-attn3`. Both short and normalized Hub names are rejected on Ascend NPU before HF preloading; dependency/download errors do not fall back to local kernels. Local FA2/FA3 remain the defaults. FlexAttention requires a model-provided native `BlockMask`; Ulysses currently requires it to be head-broadcast. MagiAttention requires the optional `--extra magi` install (`uv sync --extra gpu --extra magi`), a model-provided `MagiAttentionMask`, physical batch size 1, `cp_size == 1`, and zero attention dropout; it does not support KV-cache offsets. It uses the CUTLASS overlay on SM90 and CUTE DSL/JIT on SM100+. |
| moe_implementation | `str` | `"fused_triton"` | MoE experts forward implementation. `fused_triton` uses Triton group-gemm (GPU, SM70+); `fused_quack` uses Quack CUTLASS/CuTe (GPU, SM90+); `fused_npu` uses the NPU group-gemm kernel; `eager` is the reference loop. A value still equal to the GPU default auto-resolves to `fused_npu` on NPU; explicit incompatible non-default overrides raise. |
| cross_entropy_loss_implementation | `str` | `"liger_kernel"` | Cross-entropy loss. `liger_kernel` (default, GPU only) fuses `lm_head` linear + CE; requires VeOmni-patched modeling files that pass `hidden_states=`/`weights=` to `self.loss_function(...)` — unpatched HF models that pass logits will RuntimeError. `chunk_loss` is the hardware-agnostic chunked F.linear+CE (CUDA + NPU). `npu` is a back-compat alias for `chunk_loss`. `eager` is `F.cross_entropy`. |
| cross_entropy_loss_release_cache | `bool` | `false` | Synchronize and release transient chunk-loss allocator cache after the chunked kernel returns. This can lower peak memory before model backward on constrained profiles, at the cost of per-microbatch synchronization and allocator churn. Applies to all `chunk_loss`/`npu` paths (plain CE, `return_log_probs`, top-k distillation); no-op for `eager`/`liger_kernel`. |
| rms_norm_implementation | `str` | `"liger_kernel"` | RMSNorm. Known values: `liger_kernel` (default, GPU only), `npu`, `triton` (DeepSeek-V3 only; GPU only), `eager`. |
| swiglu_mlp_implementation | `str` | `"liger_kernel"` | SwiGLU MLP. Known values: `liger_kernel` (default, GPU only), `eager`. There is no NPU backend, so a value still equal to the default auto-resolves to `eager` on NPU. |
| rotary_pos_emb_implementation | `str` | `"liger_kernel"` | Rotary pos emb. Known values: `liger_kernel` (default, GPU only), `npu`, `triton` (per-model: DeepSeek-V3, DeepSeek-V4, Wan; GPU only), `eager`. DeepSeek-V4 and Wan reject the `liger_kernel` default because their rotary layout is partial / non-standard, and DeepSeek-V4 also rejects `npu`; both raise at model registration, so their configs must pin `triton` or `eager`. |
Expand Down
47 changes: 47 additions & 0 deletions tests/ops/test_chunk_loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,50 @@ def test_chunk_loss_honors_explicit_shift_labels(monkeypatch):
)

torch.testing.assert_close(actual, expected)


def test_dispatch_forwards_chunk_size(monkeypatch):
import veomni.ops.kernels.cross_entropy as dispatch

seen = []

def record(*args, **kwargs):
seen.append(kwargs["chunk_size"])
return torch.tensor(0.0), None

monkeypatch.setattr(dispatch, "chunk_loss_function", record)
for size in (1024, 512, 256):
dispatch._chunk_loss_dispatch(hidden_states=None, weights=None, labels=None, chunk_size=size)
assert seen == [1024, 512, 256]


def test_dispatch_loss_and_gradients_match_dense(monkeypatch):
import veomni.ops.kernels.cross_entropy as dispatch

# Non-SP shifts once; SP receives labels already shifted by the collator.
for sp_enabled in (False, True):
monkeypatch.setattr(
chunk_loss_module, "get_parallel_state", lambda sp=sp_enabled: SimpleNamespace(sp_enabled=sp)
)
monkeypatch.setattr(chunk_loss_module, "reduce_sequence_parallel_loss", lambda loss, count: loss)
torch.manual_seed(73)
h = torch.randn(2, 13, 7)
w = torch.randn(19, 7)
labels = torch.randint(0, 19, (2, 13))
labels[:, 2:6] = -100 # includes a fully ignored chunk
refs = None
for size in (32, 4, 3, 1):
x, weight = h.clone().requires_grad_(), w.clone().requires_grad_()
loss, _, _ = dispatch._chunk_loss_dispatch(
hidden_states=x, weights=weight, labels=labels, vocab_size=19, chunk_size=size
)
loss.backward()
if refs is None:
xr, wr = h.clone().requires_grad_(), w.clone().requires_grad_()
logits = torch.nn.functional.linear(xr if sp_enabled else xr[:, :-1], wr)
target = labels if sp_enabled else labels[:, 1:]
dense = torch.nn.functional.cross_entropy(logits.reshape(-1, 19), target.reshape(-1))
dense.backward()
refs = dense.detach(), xr.grad, wr.grad
for result, ref in zip((loss, x.grad, weight.grad), refs):
torch.testing.assert_close(result, ref, atol=2e-6, rtol=2e-5)
120 changes: 120 additions & 0 deletions tests/ops/test_chunk_loss_saved_hooks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""CPU parity gates for chunk loss under saved tensor hooks and checkpointing."""

from contextlib import nullcontext
from types import SimpleNamespace

import pytest
import torch
from torch.utils.checkpoint import checkpoint

import veomni.ops.kernels.cross_entropy.chunk_loss as chunk_module
from veomni.distributed.offloading import build_activation_offloading_context
from veomni.distributed.sequence_parallel.loss import ReduceLoss


def _legacy_forward(ctx, hidden, weight, bias, loss_forward, kwargs_chunks, chunk_size):
loss = torch.tensor(0.0, device=hidden.device)
dh, dw = torch.empty_like(hidden), torch.zeros_like(weight)
for x, target, kwargs in zip(hidden.split(chunk_size, 1), dh.split(chunk_size, 1), kwargs_chunks):
(dx, delta), (value, _) = torch.func.grad_and_value(loss_forward, (0, 1), has_aux=True)(
x, weight, bias, **kwargs
)
loss.add_(value)
target.copy_(dx)
dw.add_(delta)
ctx.save_for_backward(dh, dw)
return loss


class LegacyChunkLoss(torch.autograd.Function):
forward = staticmethod(_legacy_forward)
backward = staticmethod(chunk_module.ChunkLoss.backward)


def _run(monkeypatch, implementation, dtype, sp, hooks, gc, frozen_head=False, all_ignored=False):
monkeypatch.setattr(chunk_module, "ChunkLoss", implementation)
monkeypatch.setattr(chunk_module, "get_parallel_state", lambda: SimpleNamespace(sp_enabled=sp))
# Exercise the real reducer including its zero-token guard, with a one-rank
# collective seam. Multi-rank communication is outside this CPU unit gate.
monkeypatch.setattr(torch.distributed, "all_reduce", lambda *a, **k: None)
monkeypatch.setattr(torch.distributed, "get_world_size", lambda *a, **k: 1)
monkeypatch.setattr(
chunk_module, "reduce_sequence_parallel_loss", lambda loss, count: ReduceLoss.apply(loss, count, object())
)
torch.manual_seed(127)
h = torch.randn(2, 11, 7, dtype=dtype, requires_grad=True)
w = torch.randn(19, 7, dtype=dtype, requires_grad=not frozen_head)
Comment thread
YLlllllllllll marked this conversation as resolved.
Resolved
labels = torch.randint(0, 19, (2, 11))
labels[:, 1:7] = -100 # whole ignored chunks and a short final chunk
if all_ignored:
labels.fill_(-100)
packed = []
unpacked = []

def pack(t):
packed.append(t.shape)
return t.detach().clone()

def unpack(t):
unpacked.append(t.shape)
return t

def forward(x, head):
# Upstream graph ensures local autograd does not accidentally consume
# the decoder graph or its accumulated gradients.
return chunk_module.chunk_loss_function(x.sin(), head, labels, chunk_size=3, vocab_size=19)[0]

fwd_context = torch.autograd.graph.saved_tensors_hooks(pack, unpack) if hooks else nullcontext()
bwd_context = nullcontext()
if hooks == "production":
fwd_context, bwd_context = build_activation_offloading_context(
enable_activation=True, enable_gradient_checkpointing=gc
)
with fwd_context:
loss = checkpoint(forward, h, w, use_reentrant=False) if gc else forward(h, w)
with bwd_context:
(loss * 0.37).backward() # non-unit upstream gradient (e.g. accumulation)
if hooks and hooks != "production":
assert packed and unpacked
return loss.detach(), h.grad, w.grad


def test_original_transform_rejects_saved_tensor_hooks():
x = torch.ones(2)
with torch.autograd.graph.saved_tensors_hooks(lambda t: t, lambda t: t):
with pytest.raises(RuntimeError, match="don't yet support saved tensor hooks"):
torch.func.grad_and_value(lambda t: t.square().sum())(x)


@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
@pytest.mark.parametrize("sp", [False, True])
@pytest.mark.parametrize(
"hooks,gc", [(False, False), (True, False), (False, True), (True, True), ("production", True)]
)
def test_loss_and_gradients_match_legacy(monkeypatch, dtype, sp, hooks, gc):
fixed = chunk_module.ChunkLoss
expected = _run(monkeypatch, LegacyChunkLoss, dtype, sp, False, False)
actual = _run(monkeypatch, fixed, dtype, sp, hooks, gc)
for got, ref in zip(actual, expected):
torch.testing.assert_close(got, ref, rtol=0, atol=0)


@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
def test_frozen_head_and_upstream_graph(monkeypatch, dtype):
fixed = chunk_module.ChunkLoss
expected = _run(monkeypatch, LegacyChunkLoss, dtype, False, False, False, frozen_head=True)
actual = _run(monkeypatch, fixed, dtype, False, True, True, frozen_head=True)
assert actual[2] is None
for got, ref in zip(actual[:2], expected[:2]):
torch.testing.assert_close(got, ref, rtol=0, atol=0)


@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
def test_zero_valid_sp_slice(monkeypatch, dtype):
fixed = chunk_module.ChunkLoss
expected = _run(monkeypatch, LegacyChunkLoss, dtype, True, False, False, all_ignored=True)
actual = _run(monkeypatch, fixed, dtype, True, True, True, all_ignored=True)
for got, ref in zip(actual, expected):
torch.testing.assert_close(got, ref, rtol=0, atol=0)
assert torch.isfinite(got).all()
assert torch.count_nonzero(got) == 0
Loading
Loading