Repository navigation
[BC][loss] Redesign loss abstractions - #4582
Conversation
dc68200 to
83b855d
Compare
36d28ba to
e81c4de
Compare
e81c4de to
8084d01
Compare
## Summary - keep TP policy logits vocab-sharded when computing token logprobs and entropy - reuse vocab-parallel cross-entropy forward/backward for per-token gradients - compute exact entropy from shard-local sufficient statistics and small TP reductions - set decoder vocabulary size explicitly when constructing non-batch-invariant DAPO/GRPO recipe configs, including chunked losses - keep batch-invariant mode on the existing full-gather operation sequence, with an explicit runtime guard and warning for misconfigured recipes ## Why The RL trainer previously gathered every vocabulary shard on every TP rank before computing sampled-token logprobs and entropy. The new path uses shard-local values plus per-token reductions for the global maximum, softmax denominator, target contribution, and entropy-weighted sum. Entropy remains a no-grad metric. ## Correctness and compatibility Distributed parity tests compare logprobs, entropy, and non-uniformly weighted gradients against the full-vocabulary reference. They cover TP=2/4, DP=2 x TP=2, even/uneven vocabulary, FP32/BF16, ignored labels, partially masked logits, and strict SPMD type checking. Batch-invariant training leaves `global_vocab_size` unset to retain the original trainer operation sequence. In the generator, `VLLMModelWrapper.compute_logits()` already gathers the LM-head vocabulary shards into the full logits tensor expected by vLLM, so the patched vLLM logprob call correctly receives full logits and does not select the trainer vocab-sharded path. A CPU regression test pins its `compute_logprobs(logits, labels)` call and multi-column token-id behavior. The generic RL loss default also remains unset, preserving the fallback for configurations that do not opt in. A runtime `is_in_batch_invariant_mode()` check forces that same gather path if a recipe accidentally supplies `global_vocab_size`; the selector is documented explicitly in `compute_logprobs`. `GRPOLoss.Config` now inherits the shared DAPO config instead of duplicating this field. Recipe configuration regression tests assert that ordinary recipes use the model vocabulary size and batch-invariant recipes leave it unset. They are wired into the RL CI workflow, which installs vLLM and the example dependencies. ## Performance evidence A local forward+backward CPU/Gloo component benchmark with the Qwen3 vocabulary size (151,936) measured 2.66x at TP2 and 3.97x at TP4 after warmup. These are component-level CPU measurements, not GPU or end-to-end RL throughput claims. ## Validation - 22 runnable loss tests previously passed, including the distributed parity matrix - batch-invariance CPU regressions on the current head: 2 passed; the new case verifies that a misconfigured vocab-parallel size warns and still gathers - config regression tests: 10 skipped locally because macOS lacks vLLM; scheduled in the RL CI job - modified-file AST, format, lint, docstring, and spelling checks: passed - targeted Pyrefly on changed files reports missing local vLLM and the existing `torch.stack` union diagnostic, with no new diagnostic from the guard; full-project checking is unavailable because this environment lacks nightly PyTorch, Monarch, TorchStore, Renderers, and the configured PyTorch search path The local stable PyTorch environment cannot collect the mainline loss tests because it lacks the nightly `DataParallelMeshDims` API. Ten config tests skip locally for missing optional vLLM/renderers dependencies. The new-head Lint, CPU Unit Test, and GPU Unit Tests workflows are awaiting maintainer approval (`action_required`); only three Meta checks have passed on this head. Prior-head CI results are not being claimed for this revision. This change is orthogonal to the loss abstraction work in #4582. Closes #4683
tianyu-l
left a comment
There was a problem hiding this comment.
nice direction! Left some comments
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class Config(BaseLoss.Config): | ||
| class Config(LossConfig): |
There was a problem hiding this comment.
they didn't share configs, DAPO loss has
ratio_clip_low
ratio_clip_high
while GRPO has clip_eps
|
|
||
|
|
||
| class DAPOLoss(BaseLoss): | ||
| class DAPOLoss(Configurable): |
| LossInputT = TypeVar("LossInputT", contravariant=True) | ||
|
|
||
|
|
||
| class Loss(Protocol[LossInputT]): |
There was a problem hiding this comment.
why don't we inherit https://github.com/pytorch/torchtitan/blob/main/torchtitan/config/function.py#L16 and make LossConfig -> Loss.Config?
There was a problem hiding this comment.
changed to class Loss(ABC, Function[LossResult], Generic[LossInputT])
Actually we shouldn't inherit from Function as it does not have self.fn, I inherit from Configurable instead.
|
|
||
|
|
||
| class MTPLoss(CrossEntropyLoss): | ||
| class MTPLoss( |
There was a problem hiding this comment.
If hardcoding cross-entropy, should be called MTPCrossEntropyLoss; o/w make it generic by owning a tensor loss config?
| ) | ||
|
|
||
|
|
||
| class GradAccumulator: |
There was a problem hiding this comment.
Is this only location change?
There was a problem hiding this comment.
yeah, I reorganized this file in the order of
- Core abstractions: shared input/output types, Loss class
- Standard losses: cross_entropy_loss, _LossParallelCrossEntropy, CrossEntropyLoss, MSELoss
- policy training utilities: _VocabParallelEntropy, compute_logprobs
- chunked loss helpers: _DecoderOutputGradientBackProp, GradAccumulator
- ChunkedLossWrapper
| """Set the lm_head module. Must be called before the first __call__.""" | ||
| self.lm_head = lm_head | ||
|
|
||
| @override |
| ): | ||
| logger.info("Compiling the loss function with torch.compile") | ||
| self.fn = torch.compile(self.fn, backend=compile_config.backend) | ||
| self.fn = _maybe_compile_loss_fn(cross_entropy_loss, compile_config) |
There was a problem hiding this comment.
why moving this out to be a function?
There was a problem hiding this comment.
gone after rebasing.
| loss = loss / global_valid_tokens | ||
| return loss, {} | ||
| loss = self.fn(pred, labels, global_vocab_size=self.global_vocab_size) | ||
| return _normalize_loss(loss, global_valid_tokens), {} |
There was a problem hiding this comment.
inlined this function as it's only used twice.
8084d01 to
e445c0f
Compare
|
|
||
| def __init__(self, config: Config): | ||
| super().__init__(config) | ||
| self.cross_entropy = CrossEntropyLoss( |
There was a problem hiding this comment.
| self.cross_entropy = CrossEntropyLoss( | |
| self.cross_entropy_loss = CrossEntropyLoss( |
| LossInputT = TypeVar("LossInputT", contravariant=True) | ||
|
|
||
|
|
||
| class Loss(ABC, Configurable, Generic[LossInputT]): |
There was a problem hiding this comment.
it seems a mistake for Function to have a field fn. E.g. https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/activation.py#L20 doesn't use it. Could you help remove the field and inherit it here?
Motivation
The previous loss hierarchy mixed the trainer-facing interface with concrete
single-output behavior:
BaseLoss,CrossEntropyLoss, andMSELossdescribed tensor-only inputs,while MTP and chunked loss also operate on aligned prediction/label tuples.
MTPLossinherited fromCrossEntropyLosseven though it combines severalcross-entropy objectives.
ChunkedLossWrapperinherited objective behavior even though it changes howanother loss is executed.
As a result, inheritance did not accurately describe input contracts,
composition, or execution wrapping.
Design
Loss: a configurable, typed callable abstractionLossis a generic abstractConfigurablewhose type parameter describes theshared structure of
predandlabels:The abstraction inherits directly from
Configurable; it does not inherit fromthe concrete
Functionwrapper because losses do not store and forward to aconfigured
fn.CrossEntropyLoss,MSELoss,DAPOLoss, andGRPOLossuse the tensor inputcontract. Policy losses retain their specialized keyword-only inputs.
MTPCrossEntropyLoss: composition instead of inheritanceMTPCrossEntropyLossimplements the tuple input contract and owns aCrossEntropyLoss. It applies cross entropy independently to the main and MTPdepth outputs, normalizes each objective by its corresponding token count, and
combines the weighted terms.
The explicit name reflects that this implementation hard-codes cross entropy.
ChunkedLossWrapper: execution wrappingChunkedLossWrapperaccepts either a tensor pair or aligned prediction/labeltuples:
It preserves that structure while chunking inputs, running
lm_head, invokingthe configured inner loss, accumulating gradients, and reconnecting decoder
backward. It does not define the wrapped objective.
The resulting relationships are composition:
Detailed changes
BaseLosswithLoss[T]and nestedLoss.Config.Loss[torch.Tensor]directly.argument name with the shared
predcontract.MTPLosstoMTPCrossEntropyLossand use composition rather thaninheriting from
CrossEntropyLoss.ChunkedLossWrapperexplicitly support tensor and tuple inputs whilepreserving runtime structure validation.
Validation
The numerical comparisons below used baseline commit
310e2a66e, the same seedcheckpoint,
--debug.seed=42,--debug.deterministic, disabled CUDA graphs,and full-precision TensorBoard values for 10 training steps.
Additional validation:
84 passed, 7 subtests passed.
deepseek_v3_mtp_tp+cp: 10/10 steps passed on 4 GPUs.completed forward and backward successfully.
subtests passed. One unrelated local LoRA/FlexAttention CPU compile case could
not load a TorchInductor artifact because of a local shared-library symbol
mismatch.