Repository navigation
added z loss - #5736
added z loss#5736
Conversation
|
|
|
@claude review |
|
Claude finished @tianyu-l's task in 3m 43s —— View job Request changes: enabling z-loss also adds it to the reported validation loss, and there's no run showing training with z-loss on. See the review. |
There was a problem hiding this comment.
Verdict: Request changes -- turning on z-loss silently adds the regularizer to the reported validation loss, and nothing shows the enabled path training correctly.
What this PR does. It adds an optional z_loss_weight to CrossEntropyLoss. When set, the loss becomes (CE + w * sum lse^2) / tokens. Under TP, _LossParallelCrossEntropy reuses its existing all-reduced max and sumexp to return the per-token logsumexp, so no extra collective is needed. The pretraining trainer now reduces and logs the loss metrics, which it used to drop. With the weight unset, the default path is unchanged (bitwise-equal runs are reported).
Example.
CrossEntropyLoss.Config(global_vocab_size=V, z_loss_weight=1e-4)
# N = global valid tokens
# before: loss = sum_t CE_t / N metrics = {}
# after: loss = (sum_t CE_t + 1e-4 * sum_t lse_t^2) / N
# metrics = {"ce/mean": sum CE / N, "z/mean": sum lse^2 / N}
# train_step sums */mean over microbatches and the dp/cp loss mesh, then logs them
# validation: loss_sum = sum CE + 1e-4 * sum lse^2 <- z term includedMust fix
torchtitan/components/validator.py:264(not in diff) -- the validator usesengine.loss_fn(trainer.py:273), so itsloss_sumnow includesw * sum lse^2. The PP eval path does too, through_scalar_loss_fn. Validation loss stops being CE, and runs with and without z-loss can't be compared. Either have validation report only the CE term (on both the PP and non-PP paths), or ban/document this explicitly. Don't leave it implicit.- No numerics evidence for
z_loss_weightset. The tables only cover the disabled path. This is a computation change, so add a short convergence run with z-loss on, e.g. llama3 debug or 8B on C4 with FSDP and FSDP+TP. It should showce/meanclose to the baseline loss,z/meangoing down, andglobal_avg_loss == ce/mean + w * z/mean. loss.py:349-- the config docstring says "(ignored)".
Should consider
loss.py:92-107-- drop the unusedreduction="none", raiseValueErrorforglobal_vocab_size=Noneunder TP, and add a docstring.loss.py:384-400-- call the two functions directly instead of going through a dual-typed_loss_fn, compute the metrics once, and use clearer key names.trainer.py:413-428-- use the suffix rules already inChunkedLossWrapper._combine_chunk_metricsinstead of a narrower copy, and add a TODO(#4202).
Questions
- @tianyu-l, in #2523 you suggested logging z-loss first (no-grad) rather than making it a regularizer. Are you fine with a configurable regularizer that defaults to off? No in-repo recipe sets
z_loss_weight.
Details
- Parallelisms.
lseisI@TPandVon dp/cp, soz = lse.square().sum()isPon dp/cp likece, and summing over the loss mesh (dp x cp, which excludes TP) is correct. Under PP, only last-stage ranks hold metrics. Their loss-mesh collectives stay within that stage, and the metrics rank is the last stage (rank 0 for V schedules), so the keys reach the logger. - TP backward.
backwardnow returns 6 grads. The existing 5-argapplycallers (cross_entropy_loss,compute_logprobs) still work because PyTorch trims trailingNonegrads.grad_lseis materialized as zeros if unused, so theassertholds. - MTP.
MTPCrossEntropyLossbuilds its innerCrossEntropyLosswithoutz_loss_weight, so DeepSeek-V3 MTP recipes can't enable z-loss. That's fine until someone needs it. - Logging cost. Each metric key adds one
dist_sum(an all-reduce plus a D2H sync) on log steps. That is small with two keys. Stacking the keys into one all-reduce per op would avoid it growing with more keys.
Not verified: GPU runs. The TP gradient parity was checked by reading the code, not by running it. A maintainer still needs to review, since this touches trainer.py.
|
@francesco-bertolotti
|
Z-loss is simply a regularization term used to prevent logit explosion: where
I think it could be implemented using The main reason is that Z-loss is computed from the log-sum-exp of the logits, which is already required by cross-entropy. Ideally, we should reuse the log-sum-exp computed by CE and derive the Z-loss from that value, rather than computing it twice.
Generally speaking, yes! I think this is very important for understanding whether training is progressing cleanly or running into issues. I would probably decouple metric collection from the logging step. Lightweight metrics, such as loss and gradient norm, could be collected every step, while other metrics could be collected less frequently (e.g. every 10 or 100 steps). For Z-loss specifically, I don't think this approach would be directly suitable. The reason is that It might be possible to make it work with Since torchtitan/torchtitan/components/loss.py Line 28 in 4e8b4b8 |
|
@francesco-bertolotti thanks for explaining, makes total sense. Could you address claude's review comments? |
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
|
@claude review again |
|
Claude finished @tianyu-l's task in 48s —— View job Request changes: the only new commit fixes the docstring. Validation loss still includes the z-loss term, and there's no run with z-loss enabled. See the review. |
There was a problem hiding this comment.
Verdict: Request changes -- the only new commit (e0cd07a) fixes the docstring. With z-loss on, validation loss still includes the z term, and there is still no run that trains with z-loss enabled.
What changed since the last review. One commit, e0cd07a, which applies the suggested z_loss_weight docstring. Nothing else in loss.py, trainer.py or the tests changed.
Example (unchanged at HEAD).
CrossEntropyLoss.Config(global_vocab_size=V, z_loss_weight=1e-4)
# train: loss = (sum CE + 1e-4 * sum lse^2) / N, logs ce/mean, z/mean
# validation: validator.py:264 calls the same engine.loss_fn
# -> loss_sum = sum CE + 1e-4 * sum lse^2 (not CE)Resolved
loss.py:349docstring now says what the weight does.- Open question on regularizer vs. logging only: @tianyu-l accepted z-loss as a configurable regularizer after the author's explanation (it reuses the CE logsumexp, so
aux_loss.pywould compute it twice).
Must fix (still open)
torchtitan/components/validator.py:264(not in diff) -- the validator and the PP eval path (_scalar_loss_fn) still useengine.loss_fn, so validation loss becomesCE + w * zonce z-loss is enabled. You can't compare validation loss between runs with and without z-loss. Report only the CE term in validation, for example by building the validator's loss withz_loss_weight=None, or by having validation use thecepart. Cover both the PP and non-PP paths.- Still no numerics evidence with
z_loss_weightset. Both tables in the description cover only the disabled path. Add a short run with z-loss on (llama3 debug or 8B on C4, FSDP and FSDP+TP). It should showce/meantracking the baseline loss,z/meandecreasing, andglobal_avg_loss == ce/mean + w * z/mean. - @tianyu-l asked the author to address the earlier review comments. Besides the two items above, these are still open (see the earlier inline comments):
loss.py:92-107-- drop the unusedreduction="none", raiseValueErrorforglobal_vocab_size=Noneunder TP (ideally inConfig.__post_init__), and add a docstring.loss.py:368-400-- call the two functions directly instead of going through the dual-typed_loss_fn, compute the metrics once after normalization, and use clearer key names (ce_loss/mean,z_loss/mean).trainer.py:413-428-- reuse the suffix rules inChunkedLossWrapper._combine_chunk_metricsinstead of this narrower copy (a/minor/fracmetric would raise here), and add aTODO(#4202).
Not verified: GPU runs. A maintainer still needs to review, since this touches trainer.py.
|
Sorry, I am still working on the PR. I just merged claude code suggestion (#5736 (comment)) so that I could pull it locally. |
|
@claude review |
|
Claude finished @tianyu-l's task in 4m 34s —— View job Approve, with fixes before merging: one CPU test now fails and the PR description needs updating. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The earlier must-fix items are addressed: the code is refactored as suggested, validation logs ce_loss/mean, and a run with z-loss on is posted. What's left: one CPU test that this PR breaks, and a PR description that no longer matches the code.
What this PR does. It adds an optional z_loss_weight to CrossEntropyLoss. When set, the loss is (CE + w * sum lse^2) / N, and the loss also returns ce_loss/mean and z_loss/mean. Under TP, _LossParallelCrossEntropy(return_lse=True) builds the lse from its existing all-reduces, so there is no extra collective. A new shared combine_loss_metrics replaces ChunkedLossWrapper._combine_chunk_metrics. The trainer and the validator use it to reduce loss metrics over microbatches and the loss mesh, then log them. Both used to drop these metrics.
Example.
CrossEntropyLoss.Config(global_vocab_size=V, z_loss_weight=1e-4)
# train: loss = (sum CE + 1e-4 * sum lse^2) / N
# logs ce_loss/mean, z_loss/mean (summed over microbatches + dp/cp)
# eval: validation_metrics/loss = CE + 1e-4 * z (z term included)
# validation_metrics/ce_loss/mean, .../z_loss/mean (raw sums / N)
# Author's run at step 1000: 2.695 = 2.6924 + 1e-4 * 26.52 (train)
# 2.5578 = 2.5553 + 1e-4 * 25.20 (val)
# z_loss_weight=None: no metrics, no new collectives, bitwise-equal loss (per PR)Resolved since the last review
- Validation loss with z-loss on:
ce_loss/meanandz_loss/meanare now logged for validation, on both the PP path (vialoss_kwarg_mbs) and the non-PP path, so runs can be compared. See the inline note about documenting this. - Numerics with z-loss on: the screenshot shows
z_loss/meandecreasing, andglobal_avg_loss == ce_loss/mean + w * z_loss/mean. cross_entropy_and_logsumexp: no morereduction="none", it raisesValueErrorwithoutglobal_vocab_sizeunder TP, and it has a docstring.CrossEntropyLoss.__call__calls the two functions directly, normalizes the metrics once, and uses clearer key names.- Metric reduction rules now live in one place (
combine_loss_metrics), andTODO(#4202)is added.
Must fix
torchtitan/components/validator.py:276--test_accelerator_graph_validation_config.py:99-101still expects_validate_bodyto return a tensor (see inline).- PR description -- update it to match the code:
- The "Trainer.train_step" bullet should describe
combine_loss_metrics. - Mention the validator changes and the
ChunkedLossWrapperrefactor (mechanical). - Move the z-loss-on run into the description, with its model, parallelism and
w. Ideally use FSDP+TP, since the new custom backward (probs * grad_lse) only runs under TP. Overlay az_loss_weight=Nonebaseline so readers can see thatce_loss/meantracks the baseline loss.
- The "Trainer.train_step" bullet should describe
Should consider
torchtitan/components/loss.py:688-- the suffix parse is looser than the docstring says, and the op-name round trip is roundabout (see inline).torchtitan/components/loss.py:354-- document that the reported train and validation losses include the z term (see inline).
Details
- Parallelisms.
lseisI@TPandVon dp/cp, sozisPon dp/cp likece. The loss-mesh all-reduce (dp x cp, which excludes TP) is correct. Under PP, only last-stage ranks hold metrics. Each stage's loss mesh stays within that stage, and every rank in it has the same keys, so the sorted per-key collectives can't hang. - Validator + accelerator graphs. The metric dicts are part of the captured output pytree. Cloning before accumulating (
validator.py:372-377) is needed because replay overwrites the static outputs, and the code does it.prepare_for_capturepassesloss_kwargs={}, so metadata inference doesn't touch the dicts. - Cost. With z-loss off, no keys means no collectives or syncs. With it on, each log step adds one all-reduce and one
.item()per key (two keys). - graph_trainer PP.
graph_pp/pipeline.py:325scalar_loss_fnforwardsloss_metrics=into the loss without filling it, so graph_trainer PP runs log no loss metrics. That already happens in training today, and it's an experiment, so this is fine for now. - Other consumers. No other core loss returns non-empty metrics (MTP returns
{}), so the new trainer logging adds keys only when z-loss is on.FluxValidatorcallslog_validationwithoutextra_metrics, which still works.
Not verified: GPU runs and the CPU test suite. I couldn't run tests here, and CI is waiting for workflow approval. A maintainer still needs to review, since this touches trainer.py and validator.py.
tianyu-l
left a comment
There was a problem hiding this comment.
please address remaining comments
|
Ready for another review |
|
@claude review again |
|
Claude finished @tianyu-l's task in 1m 41s —— View job Approve -- please address the items below before merging: everything from the last review is fixed. The one remaining item is reverting the unrelated |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. All the must-fix and should-consider items from the last review are done. One new commit makes an unrelated change, and it should be reverted.
What changed since the last review. Three commits: 225220a (review round two), f5d5bf3 (pre-commit), and 90c822b (LossFunction now types (loss, metrics)). The PR description was also rewritten.
Example (at HEAD).
CrossEntropyLoss.Config(global_vocab_size=V, z_loss_weight=1e-4)
# train: loss = (sum CE + 1e-4 * sum lse^2) / N; logs ce_loss/mean, z_loss/mean
# eval: validation_metrics/loss includes the z term;
# validation_metrics/ce_loss/mean is what to compare to runs without z-loss
loss_metric_reduce_op("x/bar_mean") # "sum"
loss_metric_reduce_op("x_max") # ValueError (before this push it returned max)Resolved
test_accelerator_graph_validation_config.py:99now unpacks(loss, _)from_validate_body.- PR description: it now describes
combine_loss_metrics, the validator changes and the mechanicalChunkedLossWrappermove. The z-loss-on run (FSDP 2 x TP 2,w = 1e-4, compared against aNonebaseline) is in the description. loss_metric_reduce_opmatches exactly the documented suffixes and returnsLiteral["sum", "max", "min"]. The op names live in small local and dist lookup tables.CrossEntropyLoss.Config.z_loss_weightsays that the reported train and validation losses include the z term.
Must fix
torchtitan/components/data/multimodal/utils/video.py:105-- unrelated drop of apyrefly: ignore, which CI likely needs (see inline).
Details
LossFunctionretype. All in-repo callers already unpack a tuple or index into it:pipeline_parallel.py:462,flux/validator.py:357, and the validator. Onlygraph_pp/pipeline.py:327still has anisinstance(loss, tuple)branch, which is now always true. That is experiment code, so leaving it is fine.- Validator mesh check.
dp_cp_enabledbecameget_optional_mesh("loss") is not None. The loss mesh isdp_replicate * dp_shard * cpand isNoneexactly when that product is 1, so the two checks are equivalent.
Not verified: GPU runs. A maintainer still needs to review, since this touches trainer.py and validator.py.
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
…itan into f14-z-loss-2
|
|
@francesco-bertolotti I apologize that there seems merging conflict. Would you please rebase again? |
…1-engine Conflicts: - components/loss.py: CrossEntropyLoss takes main's z-loss; the loss and its ce_loss/mean and z_loss/mean metrics stay token sums (no count divide). ChunkedLossWrapper uses main's combine_loss_metrics; the duplicate _combine_chunk_metrics is gone. - trainer.py: main's loss-metric logging, with sum-type metrics (/mean, /frac) divided by the step's loss-token count, like the loss. Aux-loss metrics keep num_loss_tokens. The core trainer test now also checks that division. Main's new validator test builds microbatches with this PR's loss_token_count field.

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).What changed
z-loss
CrossEntropyLoss.Config.z_loss_weight: float | None. When set, the loss addsw * sum lse^2before token normalization and returnsce_loss/meanandz_loss/mean(unweighted). WhenNone, 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 addssoftmax * grad_lse(still collective-free).return_lse=Falseis unchanged.Loss-metric logging
combine_loss_metrics(metrics_list, *, mesh=None)+loss_metric_reduce_op(key)inloss.py: one rule set by key suffix (/mean,/frac,_mean,_frac→ sum;/max→ max;/min→ min), applied locally and, withmesh, across ranks.ChunkedLossWrappernow 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 (oneloss_metricsdict per microbatch viapp_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 asvalidation_metrics/<key>.User-facing changes
CrossEntropyLoss.Config(z_loss_weight=...)ce_loss/mean,z_loss/mean,validation_metrics/...)loss_metrics/global_avg_lossandvalidation_metrics/lossincludew * z; comparece_loss/meanagainst runs without z-lossNumerics
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):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, localc4_testdata. TP exercises the newprobs * grad_lsebackward.global_avg_loss == ce_loss/mean + w * z_loss/meanat every step (max abs diff 2e-6).ce_loss/meantracks 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/meanfalls from ~1500 (warmup spike) to 234 (lse ≈ 36 → 15).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
test_cross_entropy_and_logsumexp_matches_cross_entropy_loss(no TP; CE and lse vs. fp64).test_cross_entropy_and_logsumexp_parity(4 TP ranks, uneven vocab,IGNORE_INDEX, strict spmd typechecking). TP CE is bitwise equal tocross_entropy_loss; lse and the gradient ofCE + sum(lse^2)match fp64. Catches regressions in the custom lse backward.test_validation_logs_loss_metrics:/meanmetrics are normalized by the valid-token total and/maxis not._validate_bodyreturn value and validator mocks:test_validator.py,test_accelerator_graph_validation_config.py, GPUtest_accelerator_graph_train_eval.py(11/11 pass on 4x A100, including the PP schedules).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.