refactor(sft): unify the loss path with the RL trainer (#3044)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s

* refactor(sft): unify the loss path with the RL trainer

Remove loss_impl (torch / liger / liger_fused / quack_fused) and route SFT
through the same chunked LM head the RL trainer uses:

- fused_lm_head_token_chunk_size (int, default 1024) selects FusedOutputLinear;
  per-token cross-entropy is the negative target logprob computed in token
  chunks — full [N, V] logits are never materialized. "disabled" falls back to
  the vanilla logits + CrossEntropyLoss path.
- The same [model] block now behaves identically across SFT and RL, and SFT
  drops the ~17 GB logits tax that loss_impl="torch" carried at long context.
- Delete the liger/quack fused-CE heads, the fused_cross_entropy plumbing in
  setup_model/inject_prime_lm_head, the SFT validator that force-disabled
  chunking, and the liger-kernel dependency.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: relock without liger-kernel

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: restore _online_logsumexp_and_weighted_update

The fused-CE class removal also swallowed this helper (defined between the
deleted classes) which the chunked logprob head uses at runtime.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style: ruff

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mika Senghaas
2026-07-16 21:50:49 -07:00
committed by GitHub
co-authored by Claude Fable 5
parent d7bcd1b1f5
commit e0d60e4d85
6 changed files with 15 additions and 150 deletions
@@ -221,9 +221,6 @@ class SFTConfig(BaseConfig):
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
"""Cross-entropy loss implementation. ``liger_fused`` fuses the lm_head projection with the CE loss to avoid materializing full logits. ``quack_fused`` uses quack-kernels for chunked linear + CE with CuTe DSL CUDA kernels."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@@ -361,11 +358,6 @@ class SFTConfig(BaseConfig):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def validate_and_disable_chunked_loss(self):
self.model.fused_lm_head_token_chunk_size = "disabled"
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
-1
View File
@@ -10,7 +10,6 @@ dependencies = [
"beartype>=0.21.0",
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
"liger-kernel>=0.5.10",
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"numpy>=2.2.6",
+1 -2
View File
@@ -1151,7 +1151,6 @@ def setup_model(
config: ModelConfig,
parallel_dims: ParallelDims,
loading_from_checkpoint_later: bool = False,
fused_cross_entropy: bool | str = False,
) -> nn.Module:
if config.attn == "flash_attention_3" and not is_flash_attn_3_available():
raise ValueError(
@@ -1185,7 +1184,7 @@ def setup_model(
if isinstance(config.fused_lm_head_token_chunk_size, int):
lm_head_chunk_size = config.fused_lm_head_token_chunk_size
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size, fused_cross_entropy=fused_cross_entropy)
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size)
apply_quantization(model, config)
+5 -103
View File
@@ -10,8 +10,6 @@ from torch import Tensor
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_final_logit_softcapping
FUSED_CE_IGNORE_INDEX = -100
class PrimeLmOutput(TypedDict, total=False):
"""Output from LM head - a TypedDict so pytree can find tensors for FSDP2 hooks."""
@@ -75,78 +73,6 @@ class VanillaOutputLinear(torch.nn.Linear):
return PrimeLmOutput(logits=super().forward(hidden_states))
class FusedCrossEntropyOutputLinear(torch.nn.Linear):
"""Fused lm_head + cross-entropy loss using Liger kernel.
Avoids materializing the full [N, V] logits tensor by fusing the linear
projection with the cross-entropy loss computation.
"""
IGNORE_INDEX = FUSED_CE_IGNORE_INDEX
def __init__(self, in_features: int, out_features: int, softcap: float | None = None):
super().__init__(in_features, out_features, bias=False)
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
self.fused_ce = LigerFusedLinearCrossEntropyLoss(
ignore_index=self.IGNORE_INDEX, reduction="mean", softcap=softcap
)
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
) -> PrimeLmOutput:
if labels is None:
return PrimeLmOutput(logits=super().forward(hidden_states))
b, s, h = hidden_states.shape
hidden_flat = hidden_states.reshape(b * s, h).contiguous()
labels_flat = labels.reshape(b * s).contiguous()
loss = self.fused_ce(self.weight, hidden_flat, labels_flat)
return PrimeLmOutput(loss=loss)
class QuackFusedCrossEntropyOutputLinear(torch.nn.Linear):
"""Fused lm_head + cross-entropy loss using quack-kernels.
Chunks the linear projection and cross-entropy computation to avoid
materializing the full [N, V] logits tensor, using quack's optimized
CuTe DSL kernels for CE and GEMM.
"""
IGNORE_INDEX = FUSED_CE_IGNORE_INDEX
def __init__(self, in_features: int, out_features: int, chunk_size: int = 4096):
super().__init__(in_features, out_features, bias=False)
self.chunk_size = chunk_size
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
) -> PrimeLmOutput:
if labels is None:
return PrimeLmOutput(logits=super().forward(hidden_states))
from quack.linear_cross_entropy import chunked_linear_cross_entropy
b, s, h = hidden_states.shape
hidden_flat = hidden_states.reshape(b * s, h).contiguous()
labels_flat = labels.reshape(b * s).contiguous()
loss = chunked_linear_cross_entropy(
hidden_flat,
self.weight,
labels_flat,
chunk_size=self.chunk_size,
ignore_index=self.IGNORE_INDEX,
reduction="mean",
)
return PrimeLmOutput(loss=loss)
def _online_logsumexp_and_weighted_update(
m: torch.Tensor, s: torch.Tensor, t: torch.Tensor, chunk_logits: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
@@ -275,7 +201,6 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
def inject_prime_lm_head(
model: nn.Module,
chunk_size: int | None = None,
fused_cross_entropy: bool | str = False,
) -> None:
"""
Inject a PrimeRL LM head into a model.
@@ -286,11 +211,7 @@ def inject_prime_lm_head(
Args:
model: The model to wrap.
chunk_size: When set to an int, uses FusedOutputLinear with sequence-token chunked
logprob/entropy computation (for RL).
fused_cross_entropy: Controls fused lm_head + CE loss. Accepts:
- False: no fusion
- True or "liger": Liger kernel fusion
- "quack": quack-kernels fusion (chunked linear + CE with CuTe DSL kernels)
logprob/entropy computation.
"""
# Guards so we have nicer error messages when a non-standard model is used
assert hasattr(model, "model"), f"model doesnt have backbone in model.model:\n{model}"
@@ -306,33 +227,14 @@ def inject_prime_lm_head(
# Check for Gemma-style softcapping - dispatch to specialized implementation.
final_logit_softcapping = get_final_logit_softcapping(model.config)
if final_logit_softcapping:
if fused_cross_entropy == "quack":
raise ValueError(
"quack_fused does not support Gemma logit softcapping. "
"Use loss_impl='liger_fused' or loss_impl='torch' instead."
)
if not fused_cross_entropy:
from prime_rl.trainer.models.layers.lm_head_gemma import inject_gemma_lm_head
from prime_rl.trainer.models.layers.lm_head_gemma import inject_gemma_lm_head
inject_gemma_lm_head(model, chunk_size, final_logit_softcapping)
return
inject_gemma_lm_head(model, chunk_size, final_logit_softcapping)
return
# Replace the lm_head with the appropriate wrapper
old_lm_head = model.lm_head
if fused_cross_entropy == "quack":
logger.info("Injecting fused cross-entropy LM head (quack-kernels)")
model.lm_head = QuackFusedCrossEntropyOutputLinear(
in_features=old_lm_head.in_features,
out_features=old_lm_head.out_features,
)
elif fused_cross_entropy:
logger.info("Injecting fused cross-entropy LM head (Liger kernel)")
model.lm_head = FusedCrossEntropyOutputLinear(
in_features=old_lm_head.in_features,
out_features=old_lm_head.out_features,
softcap=final_logit_softcapping,
)
elif isinstance(chunk_size, int):
if isinstance(chunk_size, int):
logger.info(f"Injecting chunked LM head with chunk size {chunk_size}")
model.lm_head = FusedOutputLinear(
in_features=old_lm_head.in_features, out_features=old_lm_head.out_features, chunk_size=chunk_size
+9 -21
View File
@@ -51,8 +51,6 @@ from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit, to_col_format
import torch.distributed as dist
from liger_kernel.transformers.cross_entropy import LigerCrossEntropyLoss
from prime_rl.trainer.models.layers.lm_head import FUSED_CE_IGNORE_INDEX
from torchtitan.distributed.utils import clip_grad_norm_
@@ -138,8 +136,7 @@ def train(config: SFTConfig):
# Initialize the model and tokenizer
logger.info(f"Initializing model ({config.model})")
loading_from_ckpt_later = config.ckpt and checkpoint_step is not None
fused_cross_entropy: bool | str = {"liger_fused": "liger", "quack_fused": "quack"}.get(config.loss_impl, False)
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later, fused_cross_entropy=fused_cross_entropy)
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
if parallel_dims.cp_enabled:
from prime_rl.utils.cp import assert_cp_style_supports_model
@@ -225,17 +222,6 @@ def train(config: SFTConfig):
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
cp_size = parallel_dims.cp
ce_loss = None
match config.loss_impl:
case "liger":
ce_loss = LigerCrossEntropyLoss(reduction="none")
case "torch":
ce_loss = CrossEntropyLoss(reduction="none")
case "liger_fused" | "quack_fused":
pass # loss is computed inside the fused lm_head
case _:
raise ValueError(f"Invalid loss implementation: {config.loss_impl}")
def compute_loss(micro_batch: dict) -> tuple[torch.Tensor, torch.Tensor]:
"""Forward pass returning (loss_sum, token_count) over unmasked tokens."""
input_ids = micro_batch["input_ids"].to("cuda")
@@ -256,16 +242,18 @@ def train(config: SFTConfig):
token_count = loss_mask.sum(dtype=torch.int64)
with maybe_activation_offloading(config.model.ac_offloading):
if config.loss_impl in ("liger_fused", "quack_fused"):
masked_target_ids = target_ids.clone()
masked_target_ids[~loss_mask] = FUSED_CE_IGNORE_INDEX
out = forward(model, input_ids, position_ids, labels=masked_target_ids)
loss_sum = out["loss"] * token_count
if isinstance(config.model.fused_lm_head_token_chunk_size, int):
# Same path as the RL trainer: the chunked LM head computes per-token
# logprobs without materializing the [N, V] logits, and per-token
# cross-entropy is the negative target logprob.
temperature = torch.ones_like(target_ids, dtype=torch.float32)
out = forward(model, input_ids, position_ids, labels=target_ids, temperature=temperature)
loss_sum = -out["logprobs"][loss_mask].sum()
else:
out = forward(model, input_ids, position_ids)
logits = out["logits"]
B, L, V = logits.shape
token_loss = ce_loss(logits.view(-1, V), target_ids.view(-1)).view(B, L)
token_loss = CrossEntropyLoss(reduction="none")(logits.view(-1, V), target_ids.view(-1)).view(B, L)
loss_sum = token_loss[loss_mask].sum()
del logits
Generated
-15
View File
@@ -3076,19 +3076,6 @@ requires-dist = [
{ name = "verifiers", specifier = ">=0.2.0" },
]
[[package]]
name = "liger-kernel"
version = "0.8.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "torch" },
{ name = "triton" },
]
sdist = { url = "https://files.pythonhosted.org/packages/41/d6/85f032b40fc30c969e817f9f3527f987b508171b46d9958befd0868855fd/liger_kernel-0.8.0.tar.gz", hash = "sha256:f98b94faf018814a0757e7b72bb8ebaaf12a78782cd09b157732acca2791e72c", size = 3989670, upload-time = "2026-04-30T23:02:15.183Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/7c/6b/eb29b56f128a819e2cded552e293212c57daa949481206b82490b207deac/liger_kernel-0.8.0-py3-none-any.whl", hash = "sha256:e1f03eeb4ba6a6a413d585dacf92c4c15d164bab5844fa4ead2fede6bcac469c", size = 403120, upload-time = "2026-04-30T23:02:13.443Z" },
]
[[package]]
name = "linkify-it-py"
version = "2.1.0"
@@ -4928,7 +4915,6 @@ dependencies = [
{ name = "dion" },
{ name = "flash-linear-attention" },
{ name = "jaxtyping" },
{ name = "liger-kernel" },
{ name = "loguru" },
{ name = "mooncake-transfer-engine" },
{ name = "msgspec" },
@@ -5039,7 +5025,6 @@ requires-dist = [
{ name = "flash-linear-attention", git = "https://github.com/fla-org/flash-linear-attention" },
{ name = "jaxtyping", specifier = ">=0.3.2" },
{ name = "kernels", marker = "extra == 'gpt-oss'" },
{ name = "liger-kernel", specifier = ">=0.5.10" },
{ name = "loguru", specifier = ">=0.7.3" },
{ name = "modelexpress", marker = "extra == 'modelexpress'", specifier = "==0.3.0" },
{ name = "mooncake-transfer-engine", specifier = ">=0.3.10.post2" },