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
2 changes: 1 addition & 1 deletion agent-docs/models/bailing.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ The KDA layers run fla's Triton kernels, whose autotuners re-benchmark on shape-

Measured configs persist in the Triton disk cache, which `configure_training_run` anchors on `HF_HOME` (`TRITON_CACHE_DIR`), so the warm-up is paid once per volume and the slow-step pattern appears only against a fresh cache. Fresh caches can pick differently, which changes bf16 rounding ([Docker](../infrastructure/docker.md#baked-in-environment-variables)).

On Blackwell the KDA path shares the delta-rule state kernel, which fla autotunes only over its `num_warps=2` configs there, so the restriction also covers the Ling 3.0 remote code's direct `fla` import ([Qwen3.5 linear attention](qwen3_5.md#linear-attention-qwen3_5moegateddeltanet)). On Hopper, Ring's Lightning Attention-2 backward hands fla's gated chunk backward a per-token gate and keeps its state in fp32, which fla's TileLang kernel refuses, so it runs on the same torch backend there ([Qwen3.5 linear attention](qwen3_5.md#linear-attention-qwen3_5moegateddeltanet)). The load warning that names that backend reads GatedDeltaNet layers off the config, which Ring's lacks, so Ring trains through it without the warning.
On Blackwell the KDA path shares the delta-rule state kernel, which fla autotunes only over its `num_warps=2` configs there, so the restriction also covers the Ling 3.0 remote code's direct `fla` import ([Qwen3.5 linear attention](qwen3_5.md#linear-attention-qwen3_5moegateddeltanet)). On Hopper, Ring's Lightning Attention-2 backward hands fla's gated chunk backward a per-token gate and keeps its state in fp32, which fla's TileLang kernel refuses, so it runs on the same torch backend there ([Qwen3.5 linear attention](qwen3_5.md#linear-attention-qwen3_5moegateddeltanet)). Rank 0 warns once at load that this backward runs in torch. Ring's config declares no layer types, so the load finds those layers by their decay `slope`: Ling 3.0 declares the same layer groups, and its KDA backward never calls that kernel.

## Router balancing

Expand Down
2 changes: 1 addition & 1 deletion agent-docs/models/qwen3_5.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ transformers 5.24 passes the gated delta rule the model's `linear_num_key_heads`

On Blackwell fla autotunes the delta rule's state kernel (`chunk_gated_delta_rule_fwd_kernel_h_blockdim64`, shared by the gated delta rule and KDA) only over its `num_warps=2` configs. That holds whether the kernel is reached through this funnel or through a remote-code module's own `fla` import. Under the image's Triton 3.6 its `num_warps=4` configs give run-to-run different, at some positions wrong, outputs and gradients on packed (`cu_seqlens`) rows, and on B300 also on larger unpacked batches. `tests/gpu/kernels/test_fla_blackwell_autotune.py` pins the restriction, with a `num_warps=4` control that must still miss.

On Hopper, fla refuses its Triton kernel for the gated chunk backward (`chunk_bwd_kernel_dqkwg`) under Triton 3.4.0 to 3.7.0, the image's 3.6 included: Triton's SM90 codegen corrupts that kernel's `dk` and decay gradient, and Triton 3.7.1 fixes it ([fla #640](https://github.com/fla-org/flash-linear-attention/issues/640)). The forward is not affected. fla first tries its TileLang kernel, which takes the call only with the `tilelang` package and a usable `nvcc` present, the state in the query's dtype and value heads a multiple of key heads (the images do not install `tilelang`), and otherwise raises `Triton >= 3.4.0 and < 3.7.1 on Hopper GPUs produces incorrect results for gated chunk_bwd_dqkwg` at the first backward. `apply_fla_launch_options` therefore registers a torch implementation of that one kernel as an fla backend (`halo/kernels/gated_delta_backward.py`). fla tries it after TileLang, and it takes a call only where fla's own check would refuse it, read off the flags that check reads (fla sets them once at import, from device 0), so every other device keeps fla's Triton kernel. It keeps the kernel's casts and accumulates in fp32, one slice of 64 chunks at a time, and is slower than the kernel. Forced on a B300, where fla's kernel is correct, a Qwen3.5-4B LoRA step on packed rows of 4,095 tokens took 0.435 s against 0.323 s, 1.34 times as long, at the same peak memory, and 30 steps tracked the kernel's run within the spread of two kernel runs (one run each). Rank 0 says so once per run when a model with GatedDeltaNet layers loads on such a device. `FLA_DISABLE_BACKEND_DISPATCH=1` bypasses every fla backend, this one included, so fla raises again, and the load warning then says the backward will raise. `tests/cpu/kernels/test_gated_delta_backward.py` checks it against autograd of the chunk forward and of the token-by-token rule, and `tests/gpu/kernels/test_gated_delta_torch_backward.py` against fla's kernel and the fp32 recurrence at Qwen3.5-9B's head shapes.
On Hopper, fla refuses its Triton kernel for the gated chunk backward (`chunk_bwd_kernel_dqkwg`) under Triton 3.4.0 to 3.7.0, the image's 3.6 included: Triton's SM90 codegen corrupts that kernel's `dk` and decay gradient, and Triton 3.7.1 fixes it ([fla #640](https://github.com/fla-org/flash-linear-attention/issues/640)). The forward is not affected. fla first tries its TileLang kernel, which takes the call only with the `tilelang` package and a usable `nvcc` present, the state in the query's dtype and value heads a multiple of key heads (the images do not install `tilelang`), and otherwise raises `Triton >= 3.4.0 and < 3.7.1 on Hopper GPUs produces incorrect results for gated chunk_bwd_dqkwg` at the first backward. `apply_fla_launch_options` therefore registers a torch implementation of that one kernel as an fla backend (`halo/kernels/gated_delta_backward.py`). fla tries it after TileLang, and it takes a call only where fla's own check would refuse it, read off the flags that check reads (fla sets them once at import, from device 0), so every other device keeps fla's Triton kernel. It keeps the kernel's casts and accumulates in fp32, one slice of 64 chunks at a time, and is slower than the kernel. Forced on a B300, where fla's kernel is correct, a Qwen3.5-4B LoRA step on packed rows of 4,095 tokens took 0.435 s against 0.323 s, 1.34 times as long, at the same peak memory, and 30 steps tracked the kernel's run within the spread of two kernel runs (one run each). Rank 0 says so once per run when a model with GatedDeltaNet layers, or Ring's Lightning Attention-2 layers ([Bailing](bailing.md#remote-code-compatibility)), loads on such a device. `FLA_DISABLE_BACKEND_DISPATCH=1` bypasses every fla backend, this one included, so fla raises again, and the load warning then says the backward will raise. `tests/cpu/kernels/test_gated_delta_backward.py` checks it against autograd of the chunk forward and of the token-by-token rule, and `tests/gpu/kernels/test_gated_delta_torch_backward.py` against fla's kernel and the fp32 recurrence at Qwen3.5-9B's head shapes.

fla 0.6 forms the gradient of the decay `g` as the difference of two separately rounded dot products, so the gradient carries their rounding where the two nearly cancel. They cancel under strong decay, which a random-init tiny model has throughout (`g` down to -21). There the fp32 `A_log` and `dt_bias` gradients sit 1 to 4 times their own norm from an fp64 recurrence and move by percents for a 1e-7 change of the input. The rounding comes from Triton's default fp32 dot precision (TF32, 10 mantissa bits): with `TRITON_F32_DEFAULT=ieee` the same `A_log` gradient is 5.0e-4 from fp64 on fla 0.6.0 and 3.6e-4 on 0.4.2 (upstream report: [fla #1802](https://github.com/fla-org/flash-linear-attention/issues/1802)).

Expand Down
7 changes: 6 additions & 1 deletion halo/model_loading/buffer_repair.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,14 @@ def _power_of_2_slopes(n):
)


def is_lightning_attention(module: nn.Module) -> bool:
"""Ring's Lightning-Attention-2 mixer, the module holding the per-head decay ``slope``."""
return hasattr(module, "slope") and hasattr(module, "layer_idx") and hasattr(module, "num_heads")


def _fix_alibi_slope(module: nn.Module, name: str) -> int | None:
"""Bailing MoE Lightning-Attention-2 decay slopes, derived from ctor args nothing stores."""
if not (hasattr(module, "slope") and hasattr(module, "layer_idx") and hasattr(module, "num_heads")):
if not is_lightning_attention(module):
return None
num_hidden_layers = getattr(getattr(module, "config", None), "num_hidden_layers", None)
if num_hidden_layers is None:
Expand Down
20 changes: 15 additions & 5 deletions halo/model_loading/finalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from halo.kernels.fla_launch import apply_fla_launch_options, warm_fla_l2norm
from halo.kernels.gated_delta_backward import uses_torch_gated_backward
from halo.log import warn_once
from halo.model_loading.buffer_repair import apply_buffer_repairs
from halo.model_loading.buffer_repair import apply_buffer_repairs, is_lightning_attention
from halo.model_loading.external_tables import attach_external_tables
from halo.model_loading.lazy_safetensors.conversion import dequantizes_loop_experts
from halo.models.attention.layout import has_gated_delta_net_layers
Expand Down Expand Up @@ -64,11 +64,21 @@ def _warn_on_idle_mtp_tail(model: nn.Module) -> None:
)


def _has_gated_chunk_backward_layers(model: nn.Module) -> bool:
"""Whether ``model`` holds layers whose backward runs fla's gated ``chunk_bwd_dqkwg``: GatedDeltaNet layers, read
off the config, and Ring's Lightning-Attention-2 layers, found by module because Ling 3.0 declares the same layer
groups and its KDA backward never calls that kernel."""
return has_gated_delta_net_layers(getattr(model, "config", None)) or any(
map(is_lightning_attention, model.modules())
)


def _warn_on_torch_gated_backward(model: nn.Module) -> None:
"""fla refuses its Triton gated chunk backward on SM90 under Triton 3.4.0 to 3.7.0, which miscompile it there, so
a gated-delta-rule model trains that kernel in torch: slower, and worth naming once per run. With fla's dispatch
disabled at its import the torch kernel cannot run, and the warning says the backward will raise."""
if not has_gated_delta_net_layers(getattr(model, "config", None)) or not uses_torch_gated_backward():
a model whose linear-attention layers call it trains that kernel in torch: slower, and worth naming once per run.
With fla's dispatch disabled at its import the torch kernel cannot run, and the warning says the backward will
raise."""
if not uses_torch_gated_backward() or not _has_gated_chunk_backward_layers(model):
return
if is_global_main_process():
outcome = (
Expand All @@ -82,7 +92,7 @@ def _warn_on_torch_gated_backward(model: nn.Module) -> None:
logger,
_warned_torch_gated_backward,
"torch_gated_backward",
f"Triton {triton.__version__} miscompiles fla's gated delta-rule chunk backward (chunk_bwd_kernel_dqkwg) "
f"Triton {triton.__version__} miscompiles fla's gated chunk backward (chunk_bwd_kernel_dqkwg) "
f"on SM90 (fla #640), so fla refuses it: {outcome} An image with Triton >= 3.7.1 restores the fused kernel.",
)

Expand Down
38 changes: 38 additions & 0 deletions tests/cpu/kernels/test_gated_delta_backward.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@
uses_torch_gated_backward,
)
from halo.model_loading import finalization
from halo.models.attention.layout import declares_linear_layer_groups
from tests.common.tiny_models import (
TINY_BAILING_LING3_MLA_FAMILY,
TINY_BAILING_RING_FAMILY,
TINY_MOE_FAMILIES,
tiny_family_model,
)

# fla's own flags for its #640 check, as on an H100 under the images' Triton 3.6.
HOPPER_TRITON_3_6 = {"IS_NVIDIA_HOPPER": True, "TRITON_ABOVE_3_4_0": True, "TRITON_ABOVE_3_7_1": False}
Expand Down Expand Up @@ -269,6 +276,37 @@ def test_load_says_the_backward_will_raise_when_flas_dispatch_is_disabled(monkey
assert "runs that kernel in torch" not in warned


@pytest.mark.parametrize(
("family", "overrides", "groups", "main", "hopper", "warns"),
[
(TINY_BAILING_RING_FAMILY, {}, True, True, True, True),
(TINY_BAILING_RING_FAMILY, {}, True, False, True, False),
(TINY_BAILING_RING_FAMILY, {}, True, True, False, False),
(TINY_BAILING_LING3_MLA_FAMILY, {"layer_group_size": 2}, True, True, True, False),
(TINY_MOE_FAMILIES["bailing_moe"], {}, False, True, True, False),
],
ids=["ring_main_rank", "ring_other_rank", "ring_not_hopper", "ling3_kda_layers", "ling2_softmax_attention"],
)
def test_load_names_the_torch_backward_for_rings_lightning_attention(
monkeypatch, caplog, family, overrides, groups, main, hopper, warns
):
"""Ring's config declares no layer types. Ling 3.0's KDA layers (``layer_group_size: 2``) sit in the same layer
groups, and their backward never calls the kernel."""
model = tiny_family_model(family, overrides=overrides)
assert declares_linear_layer_groups(model.config) is groups
monkeypatch.setattr(finalization, "is_global_main_process", lambda: main)
monkeypatch.setattr(finalization, "_warned_torch_gated_backward", set())
monkeypatch.setattr(fla_backends, "_DISPATCH_DISABLED", False)
_set_fla_flags(monkeypatch, **{**HOPPER_TRITON_3_6, "IS_NVIDIA_HOPPER": hopper})
with caplog.at_level(logging.WARNING, logger=finalization.__name__):
finalization._warn_on_torch_gated_backward(model)
finalization._warn_on_torch_gated_backward(model)
warned = [record.getMessage() for record in caplog.records if record.name == finalization.__name__]
assert len(warned) == (1 if warns else 0)
if warns:
assert "fla #640" in warned[0] and "runs that kernel in torch" in warned[0]


def _rounded_call(seed: int) -> dict:
"""fp32 queries and outputs beside bf16 values and fp32 states, so the kernel's two bf16 roundings show in ``dq``."""
gen = torch.Generator().manual_seed(seed)
Expand Down