Skip to content

Configurable Z Loss - #2576

Closed
francesco-bertolotti wants to merge 4 commits into
pytorch:mainfrom
francesco-bertolotti:f14-z-loss
Closed

francesco-bertolotti wants to merge 4 commits into
pytorch:mainfrom
francesco-bertolotti:f14-z-loss

Conversation

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator

Overview

Following #2523, this PR introduces an initial implementation of z-loss and includes some refactoring to make the loss configuration more flexible.

Z-Loss

I added z-loss support to the cross-entropy loss. The implementation is inspired by the one used in OLMo:
https://github.com/allenai/OLMo-core/blob/main/src/olmo_core/nn/cross_entropy_loss.py.

If z_loss_weight is set to a value different from 0, the z-loss is computed and added to the cross-entropy loss, scaled by z_loss_weight.

Refactoring

I also refactored the loss configuration so it can be defined via the CLI or through TOML configuration files. This is just a proposal and can be adapted if it does not align with the Torchtitan design.

The current setup allows configuring multiple loss types (currently MSE and CrossEntropy). Each loss is defined as a configurable object with the following fields:

  • enable: whether the loss is active (exactly one loss must be enabled)
  • compile: if true, the loss module is compiled with torch.compile

Additional options are available for specific losses:

  • CrossEntropyLoss

    • z_loss_weight (default: 0.0)
    • ignore_index (default: -100)

Both CrossEntropy and MSE return a LossOutput object containing:

  • main: the loss used for gradient computation (the one .backward() should be called on)
  • aux: a dictionary containing auxiliary values intended only for logging

For example, the CrossEntropy loss populates LossOutput.aux with both the unscaled z-loss and the raw cross-entropy loss.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 14, 2026
# resolver does not handle ``Callable[..., X]`` (Ellipsis as param spec).
# The detailed TypeAliases above are still available for use in function
# signatures elsewhere in the codebase.
build_loss_fn: Callable

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.

Changing loss configuration from "build function" to config-based sounds good. However,

  • why do we move it from ModelSpec to Trainer?
  • by default only CrossEntropyLoss is used, which changes the default for FLUX model

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I was under the impression that this was no longer necessary, since the loss can now be configured directly from the config file. So I simplified it. However, it may make more sense to keep it, I'm happy to revert this change if needed.

)


class Loss(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.

We should have one BaseLoss class which crossentropy and mse inherit, rather than one monolithic Loss class responsible for everything.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Right now, cross-entropy and MSE losses are implemented as separate classes (though they could definitely share a common BaseLoss parent). The current Loss object simply routes to the appropriate implementation based on the configuration.

For example, the CLI for configuring the loss looks like this:

torchtitan/train.py \
  --config qwen3_debugmodel \
  --module qwen3 \
  --loss.cross-entropy.enable \
  --loss.cross-entropy.compile \
  --loss.cross-entropy.ignore-index -100 \
  --loss.cross-entropy.z-loss-weight 1e-5

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.

the current thinking around CLI is that

  • python config is strictly closer to the actual object than CLI, thus more "minimal" to support
  • the design should focus on this minimal nature, not biased (too much) by CLI concern
  • users can always build CLI oriented config on top of existing config

ignore_index=IGNORE_INDEX,
)
main: torch.Tensor
aux: dict[str, torch.Tensor] = field(default_factory=dict)

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 aux is only for logging. I think it'd be cleaner to wait until #2607 lands.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yep aux is meant only for logging. No problem in waiting for #2607

tianyu-l pushed a commit that referenced this pull request Nov 5, 2026
## Summary

Z loss has become a fairly popular regularization loss used together
with Cross Entropy. I already did a PR about this but it stalled for
there were major mods coming to the way loss was handled. I do not know
if the situation stabilized from
#2576 but here I am
re-proposing the same feature.

## Why
Adds an optional z-loss regularizer used by PaLM/OLMo/Trinity) to
`CrossEntropyLoss`. To make it observable, the trainer and validator now
log the metrics a loss returns (both dropped them before).

```python
CrossEntropyLoss.Config(global_vocab_size=V, z_loss_weight=1e-4)  # None = off (default)
# loss = (sum_t CE_t + w * sum_t lse_t^2) / N
# logs:  ce_loss/mean, z_loss/mean                         (train)
#        validation_metrics/ce_loss/mean, .../z_loss/mean  (validation)
```

## What changed
**z-loss**
- `CrossEntropyLoss.Config.z_loss_weight: float | None`. When set, the
loss adds `w * sum lse^2` before token normalization and returns
`ce_loss/mean` and `z_loss/mean` (unweighted). When `None`, the path is
unchanged.
- `cross_entropy_and_logsumexp` (new, `@local_compile("loss")`): returns
`(CE, lse[T])` from one logsumexp. Under TP it uses
`_LossParallelCrossEntropy(..., return_lse=True)`.
- `_LossParallelCrossEntropy(return_lse=False)`: optional second output.
lse = `local_max + log(sum_exp)` from the existing all-reduces (no extra
collective); backward adds `softmax * grad_lse` (still collective-free).
`return_lse=False` is unchanged.

**Loss-metric logging**
- `combine_loss_metrics(metrics_list, *, mesh=None)` +
`loss_metric_reduce_op(key)` in `loss.py`: one rule set by key suffix
(`/mean`, `/frac`, `_mean`, `_frac` → sum; `/max` → max; `/min` → min),
applied locally and, with `mesh`, across ranks.
- `ChunkedLossWrapper` now uses it instead of `_combine_chunk_metrics`
(mechanical move).
- `Trainer.train_step`: combines loss metrics over microbatches and the
loss mesh and logs them. `TODO(#4202)`.
- `Validator`: collects loss metrics on the non-PP path and on the PP
path (one `loss_metrics` dict per microbatch via
`pp_schedule.eval(loss_kwarg_mbs=...)`, filled by `_scalar_loss_fn`);
combines across steps and ranks; divides sum-type keys by the global
valid-token count; logs them as `validation_metrics/<key>`.
- LossFunction now types a Loss ((loss, metrics)); the raw mse_loss
kernel annotation is fixed accordingly (typing only)

## User-facing changes
| Before | After |
| --- | --- |
| no z-loss | `CrossEntropyLoss.Config(z_loss_weight=...)` |
| loss metrics dropped by trainer and validator | logged
(`ce_loss/mean`, `z_loss/mean`, `validation_metrics/...`) |
| — | with z-loss on, `loss_metrics/global_avg_loss` and
`validation_metrics/loss` include `w * z`; compare `ce_loss/mean`
against runs without z-loss |


## Numerics
**z-loss off:** bitwise-equal loss and grad_norm vs. base `b832ae41` (20
steps, seed 42, deterministic, `scripts/loss_compare.py --assert-equal
--metrics loss,grad_norm`):

| Config | GPUs | Loss | grad_norm |
| --- | --- | --- | --- |
| llama3 debug, FSDP 4 | 4x A100-SXM-64GB | bitwise equal | bitwise
equal |
| llama3 debug, FSDP 2 + TP 2 | 4x A100-SXM-64GB | bitwise equal |
bitwise equal |
| llama3 debug, PP 2 + FSDP 2 (1F1B, 8 microbatches) | 4x A100-SXM-64GB
| bitwise equal | bitwise equal |

**z-loss on vs. off** (`w = 1e-4`): llama3 (4 layers, dim 8192, seq
2048), FSDP 2 × TP 2, 4x A100-SXM-64GB, 400 steps, seed 42,
deterministic, local `c4_test` data. TP exercises the new `probs *
grad_lse` backward.
- `global_avg_loss == ce_loss/mean + w * z_loss/mean` at every step (max
abs diff 2e-6).
- `ce_loss/mean` tracks the baseline loss: mean over steps 301–400 is
2.8065 vs. 2.8091; validation CE at step 400 is 2.7249 vs. 2.7268.
- `z_loss/mean` falls from ~1500 (warmup spike) to 234 (lse ≈ 36 → 15).

<img width="2250" height="660" alt="zloss_fsdp2_tp2"
src="https://github.com/user-attachments/assets/e0f91785-5892-4736-bb80-dd1660b541ef"
/>

The implementation matches OLMo-core's `cross_entropy_loss(...,
compute_z_loss=True)`: identical loss, z term equal to the last fp32
digit, gradients within 6e-17.

## Testing
- New: `test_cross_entropy_and_logsumexp_matches_cross_entropy_loss` (no
TP; CE and lse vs. fp64).
- New: `test_cross_entropy_and_logsumexp_parity` (4 TP ranks, uneven
vocab, `IGNORE_INDEX`, strict spmd typechecking). TP CE is bitwise equal
to `cross_entropy_loss`; lse and the gradient of `CE + sum(lse^2)` match
fp64. Catches regressions in the custom lse backward.
- New: `test_validation_logs_loss_metrics`: `/mean` metrics are
normalized by the valid-token total and `/max` is not.
- Updated for the new `_validate_body` return value and validator mocks:
`test_validator.py`, `test_accelerator_graph_validation_config.py`, GPU
`test_accelerator_graph_train_eval.py` (11/11 pass on 4x A100, including
the PP schedules).
- Also run: `test_loss.py`, `test_trainer.py`, `test_invalid_loss.py`,
`test_pipeline_parallel.py`, `test_compile_config.py`,
`graph_trainer/tests/test_chunked_loss.py`.

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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