Skip to content

[BC][loss] Redesign loss abstractions - #4582

Merged
acisseJZhong merged 5 commits into
mainfrom
chunkedlosswrapper
Oct 28, 2026
Merged

acisseJZhong merged 5 commits into
mainfrom
chunkedlosswrapper

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

The previous loss hierarchy mixed the trainer-facing interface with concrete
single-output behavior:

  • BaseLoss, CrossEntropyLoss, and MSELoss described tensor-only inputs,
    while MTP and chunked loss also operate on aligned prediction/label tuples.
  • MTPLoss inherited from CrossEntropyLoss even though it combines several
    cross-entropy objectives.
  • ChunkedLossWrapper inherited objective behavior even though it changes how
    another loss is executed.

As a result, inheritance did not accurately describe input contracts,
composition, or execution wrapping.

Design

Loss: a configurable, typed callable abstraction

Loss is a generic abstract Configurable whose type parameter describes the
shared structure of pred and labels:

LossInputT = TypeVar("LossInputT", contravariant=True)

class Loss(ABC, Configurable, Generic[LossInputT]):
    @dataclass(kw_only=True, slots=True)
    class Config(Configurable.Config):
        pass

    @abstractmethod
    def __call__(
        self,
        pred: LossInputT,
        labels: LossInputT,
        global_loss_token_counts: torch.Tensor | None = None,
        **loss_inputs: Any,
    ) -> LossResult:
        ...

The abstraction inherits directly from Configurable; it does not inherit from
the concrete Function wrapper because losses do not store and forward to a
configured fn.

CrossEntropyLoss, MSELoss, DAPOLoss, and GRPOLoss use the tensor input
contract. Policy losses retain their specialized keyword-only inputs.

MTPCrossEntropyLoss: composition instead of inheritance

MTPCrossEntropyLoss implements the tuple input contract and owns a
CrossEntropyLoss. It applies cross entropy independently to the main and MTP
depth 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 wrapping

ChunkedLossWrapper accepts either a tensor pair or aligned prediction/label
tuples:

LossInput = torch.Tensor | tuple[torch.Tensor, ...]

It preserves that structure while chunking inputs, running lm_head, invoking
the configured inner loss, accumulating gradients, and reconnecting decoder
backward. It does not define the wrapped objective.

The resulting relationships are composition:

chunked cross entropy: ChunkedLossWrapper -> CrossEntropyLoss
chunked MTP:           ChunkedLossWrapper -> MTPCrossEntropyLoss -> CrossEntropyLoss

Detailed changes

  • Replace BaseLoss with Loss[T] and nested Loss.Config.
  • Make cross entropy and MSE implement Loss[torch.Tensor] directly.
  • Make DAPO and GRPO inherit the tensor loss abstraction; align DAPO's first
    argument name with the shared pred contract.
  • Rename MTPLoss to MTPCrossEntropyLoss and use composition rather than
    inheriting from CrossEntropyLoss.
  • Make ChunkedLossWrapper explicitly support tensor and tuple inputs while
    preserving runtime structure validation.
  • Update trainer, model, recipe, documentation, and test call sites.

Validation

The numerical comparisons below used baseline commit 310e2a66e, the same seed
checkpoint, --debug.seed=42, --debug.deterministic, disabled CUDA graphs,
and full-precision TensorBoard values for 10 training steps.

Configuration GPUs Maximum loss difference Maximum grad-norm difference
MTP + chunked loss 1 0 0
MTP + chunked loss, TP=2, CP=2, SP 4 0 0

Additional validation:

  • Loss, CLI-config, graph-trainer, config-manager, and CP-validation tests:
    84 passed, 7 subtests passed.
  • Real-process-group deepseek_v3_mtp_tp+cp: 10/10 steps passed on 4 GPUs.
  • Compiled MTP + chunked loss CPU smoke test using the eager compile backend
    completed forward and backward successfully.
  • Latest focused loss tests after the abstraction follow-ups: 41 passed and 14
    subtests passed. One unrelated local LoRA/FlexAttention CPU compile case could
    not load a TorchInductor artifact because of a local shared-library symbol
    mismatch.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 10, 2026
@acisseJZhong
acisseJZhong force-pushed the chunkedlosswrapper branch 2 times, most recently from dc68200 to 83b855d Compare September 10, 2026 21:17
@acisseJZhong
acisseJZhong force-pushed the chunkedlosswrapper branch 5 times, most recently from 36d28ba to e81c4de Compare September 15, 2026 00:50
@acisseJZhong acisseJZhong changed the title [do not review] redesign loss abstractions [loss] Redesign loss abstractions Sep 15, 2026
@acisseJZhong
acisseJZhong marked this pull request as ready for review September 15, 2026 00:52
tianyu-l pushed a commit that referenced this pull request Sep 16, 2026
## 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 tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice direction! Left some comments


@dataclass(kw_only=True, slots=True)
class Config(BaseLoss.Config):
class Config(LossConfig):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inherit DAPOLoss.Config

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not inheriting Loss?

Comment thread torchtitan/components/loss.py Outdated
LossInputT = TypeVar("LossInputT", contravariant=True)


class Loss(Protocol[LossInputT]):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@acisseJZhong acisseJZhong Oct 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/models/deepseek_v3/mtp.py Outdated


class MTPLoss(CrossEntropyLoss):
class MTPLoss(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If hardcoding cross-entropy, should be called MTPCrossEntropyLoss; o/w make it generic by owning a tensor loss config?

Comment thread torchtitan/components/loss.py Outdated
)


class GradAccumulator:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this only location change?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, I reorganized this file in the order of

  1. Core abstractions: shared input/output types, Loss class
  2. Standard losses: cross_entropy_loss, _LossParallelCrossEntropy, CrossEntropyLoss, MSELoss
  3. policy training utilities: _VocabParallelEntropy, compute_logprobs
  4. chunked loss helpers: _DecoderOutputGradientBackProp, GradAccumulator
  5. ChunkedLossWrapper

Comment thread torchtitan/components/loss.py Outdated
"""Set the lm_head module. Must be called before the first __call__."""
self.lm_head = lm_head

@override

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this wrapper?

Comment thread torchtitan/components/loss.py Outdated
):
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why moving this out to be a function?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gone after rebasing.

Comment thread torchtitan/components/loss.py Outdated
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), {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

similar

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inlined this function as it's only used twice.

@acisseJZhong
acisseJZhong marked this pull request as draft October 27, 2026 07:03
@acisseJZhong acisseJZhong changed the title [loss] Redesign loss abstractions [BC][loss] Redesign loss abstractions Oct 27, 2026
@acisseJZhong
acisseJZhong marked this pull request as ready for review October 27, 2026 23:16
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 27, 2026
@acisseJZhong
acisseJZhong requested a review from pzhan9 as a code owner October 27, 2026 23:16
Comment thread torchtitan/models/deepseek_v3/mtp.py Outdated

def __init__(self, config: Config):
super().__init__(config)
self.cross_entropy = CrossEntropyLoss(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self.cross_entropy = CrossEntropyLoss(
self.cross_entropy_loss = CrossEntropyLoss(

Comment thread torchtitan/components/loss.py Outdated
LossInputT = TypeVar("LossInputT", contravariant=True)


class Loss(ABC, Configurable, Generic[LossInputT]):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@acisseJZhong
acisseJZhong merged commit 740d5f7 into main Oct 28, 2026
35 of 36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants