Skip to content

fix: validation loss accumulation rescaling - #1758

Merged
tianyu-l merged 3 commits into
pytorch:mainfrom
jdinalt:fix/validation_loss
Sep 26, 2025
Merged

tianyu-l merged 3 commits into
pytorch:mainfrom
jdinalt:fix/validation_loss

Conversation

@jdinalt

@jdinalt jdinalt commented Sep 25, 2025

Copy link
Copy Markdown
Contributor

[Problem]
When gradient accumulation is enabled, the validation loss is incorrect. This is a consequence of the loss_fn being shared between train and validation mode. The loss function is wrapped with rescale_accumulated_loss(), which rescales the loss by the number of gradient accumulation steps.

This works for train, as the loss from N accumulation steps is summed at the end of the accumulation, before being logged. In the case of validation, the loop assumes that each step is a normal step, and the reported loss is scaled by 1/N.

There are two separate pathways by which this occurs. In the normal case, the wrapped loss function is used "as-is." In the case of PP, the loss function is not directly used, but is still applied indirectly through the pipeline scheduler.

In both cases, the result is that the reported validation loss is divided by the number of accumulation steps.

[Solution]
The number of gradient accumulation steps is not communicated to the validation-factory, thus it does not have access to this parameter, which is computed in the Trainer's constructor.

One possible solution would be to pass this value, as an argument, to the validator, which could then rescale the loss by this factor, before logging it. This was the suggested solution to the problem.

My solution is a little different. The function
"rescale_accumulated_loss()" now returns a loss function with a "no_rescale()" context manager, which we apply before calling the validator. This transparently disables rescaling while within this context.

This approach avoids the need to communicate this detail to the Validator and avoids having to modify the signature of the Validator factory -- which means modifying quite a few other files.

Note that in the case of PP, we double-wrap the loss function. The context manager only applies to the outer layer, thus has no impact on the PP scaling, which is what we want.

[Testing]
First, run the trainer with both a normal, single GPU, run and a 2-stage pipeline. In both cases, set the number of accumulation steps to be sufficiently hight that the problem is obvious. This covers both pathways to the wrapped loss function.

Repeat the tests with the fix. The magnitude of the validation loss should roughly correlate with the train loss.

[Problem]
When gradient accumulation is enabled, the validation loss is incorrect.
This is a consequence of the loss_fn being shared between train and
validation mode. The loss function is wrapped with
rescale_accumulated_loss(), which rescales the loss by the number of
gradient accumulation steps.

This works for train, as the loss from N accumulation steps is summed at
the end of the accumulation, before being logged. In the case of
validation, the loop assumes that each step is a normal step, and the
reported loss is scaled by 1/N.

There are two separate pathways by which this occurs. In the normal
case, the wrapped loss function is used "as-is." In the case of PP, the
loss function is not directly used, but is still applied indirectly
through the pipeline scheduler.

In both cases, the result is that the reported validation loss is
divided by the number of accumulation steps.

[Solution]
The number of gradient accumulation steps is not communicated to the
validation-factory, thus it does not have access to this parameter,
which is computed in the Trainer's constructor.

One possible solution would be to pass this value, as an argument, to
the validator, which could then rescale the loss by this factor, before
logging it. This was the suggested solution to the problem.

My solution is a little different. The function
"rescale_accumulated_loss()" now returns a loss function with a
"no_rescale()" context manager, which we apply before calling the
validator. This transparently disables rescaling while within this
context.

This approach avoids the need to communicate this detail to the
Validator and avoids having to modify the signature of the Validator
factory -- which means modifying quite a few other files.

Note that in the case of PP, we double-wrap the loss function. The
context manager only applies to the outer layer, thus has no impact on
the PP scaling, which is what we want.

[Testing]
First, run the trainer with both a normal, single GPU, run and a 2-stage
pipeline. In both cases, set the number of accumulation steps to be
sufficiently hight that the problem is obvious. This covers both
pathways to the wrapped loss function.

Repeat the tests with the fix. The magnitude of the validation loss
should roughly correlate with the train loss.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 25, 2025
jdinalt added a commit to jdinalt/forgather that referenced this pull request Sep 25, 2025
These are the configuration I used for testing the validation loss
issue. Specifically, "control.yaml" and "pp.yaml"

Committing for potential replication of findings.

See: pytorch/torchtitan#1758

@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.

oh this sounds correct, but also sounds a bit overkill

@jdinalt

jdinalt commented Sep 25, 2025

Copy link
Copy Markdown
Contributor Author

This shows the train and validation loss before and after the change. There is one run with PP and one with a single GPU. Both use 10 gradient accumulation steps.
Screenshot 2025-09-25 1 02 41 AM

The test configurations can be found here:
https://github.com/jdinalt/forgather/tree/main/examples/torchtitan/test_parallelisms

@jdinalt

jdinalt commented Sep 25, 2025

Copy link
Copy Markdown
Contributor Author

It seems likely that there may be more than one call to the Validator class in the codebase. First, let me know if this approach works for you. If it does, I'll be sure to track the others down and add the context manager.

As part of fixing validation loss scaling, when using gradient
accumulation, I have added a new context manger to the wrapped loss
function for disabling scaling.

This added the context manager to the remaining instances of validation,
the one instance in forge.

@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.

I think this approach is fine. Here correctness is more important than simplicity.

Please update https://github.com/pytorch/torchtitan/blob/main/torchtitan/train.py#L359 to also use self.loss_fn.

As we can now correctly handle the case of using the train loss function
with validation, we now use the same function for both.

[Testing]
Ran the "control.yaml" configuration, which uses the passed in loss
function. The results track exactly with the previouos run.
@jdinalt

jdinalt commented Sep 26, 2025 •

Copy link
Copy Markdown
Contributor Author

I have verified that this works. It was OK before, but it's cleaner to use only one instance of the loss function. This makes it more difficult to create a divergence between PP and non-PP and not notice.

Partial logs, with 1 GPU, debug model, and 10 accumulation steps

INFO:root:Trainer is initialized with local batch size 32, global batch size 320, gradient accumulation steps 10, sequence length 512, total steps 500 (warmup 2)
INFO:forgather.ml.training_script:**** Training Script Started *****
INFO:forgather.ml.training_script:config_name: G10
INFO:forgather.ml.training_script:config_description: 10 Gradient Accumulation Steps
INFO:forgather.ml.training_script:output_dir: /home/dinalt/ai_assets/forgather/examples/torchtitan/llama3/output_models/debug_model
INFO:forgather.ml.training_script:logging_dir: /home/dinalt/ai_assets/forgather/examples/torchtitan/llama3/output_models/debug_model/runs/g10_2025-09-26T01-58-36
INFO:root:Training starts at step 1
Assigning 1024 shards (or data sources) of the dataset to each node.
INFO:datasets.iterable_dataset:Assigning 1024 shards (or data sources) of the dataset to each node.
INFO:root:step:  1  loss:  8.1037  grad_norm:  0.2645  memory:  1.38GiB(5.86%)  tps: 13,185  tflops: 0.57  mfu: 0.18%
Assigning 8 shards (or data sources) of the dataset to each node.
INFO:datasets.iterable_dataset:Assigning 8 shards (or data sources) of the dataset to each node.
INFO:root:validate step:  1  loss:  8.0586  memory:  1.39GiB(5.89%)  tps: 179,074
INFO:root:Synchronizing and adjusting timeout for all ProcessGroups to 0:01:40
INFO:root:step: 10  loss:  6.7333  grad_norm:  0.5516  memory:  1.40GiB(5.91%)  tps: 384,264  tflops: 16.63  mfu: 5.33%

@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.

LGTM

@tianyu-l
tianyu-l merged commit 24e9105 into pytorch:main Sep 26, 2025
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
[Problem]
When gradient accumulation is enabled, the validation loss is incorrect.
This is a consequence of the loss_fn being shared between train and
validation mode. The loss function is wrapped with
rescale_accumulated_loss(), which rescales the loss by the number of
gradient accumulation steps.

This works for train, as the loss from N accumulation steps is summed at
the end of the accumulation, before being logged. In the case of
validation, the loop assumes that each step is a normal step, and the
reported loss is scaled by 1/N.

There are two separate pathways by which this occurs. In the normal
case, the wrapped loss function is used "as-is." In the case of PP, the
loss function is not directly used, but is still applied indirectly
through the pipeline scheduler.

In both cases, the result is that the reported validation loss is
divided by the number of accumulation steps.

[Solution]
The number of gradient accumulation steps is not communicated to the
validation-factory, thus it does not have access to this parameter,
which is computed in the Trainer's constructor.

One possible solution would be to pass this value, as an argument, to
the validator, which could then rescale the loss by this factor, before
logging it. This was the suggested solution to the problem.

My solution is a little different. The function
"rescale_accumulated_loss()" now returns a loss function with a
"no_rescale()" context manager, which we apply before calling the
validator. This transparently disables rescaling while within this
context.

This approach avoids the need to communicate this detail to the
Validator and avoids having to modify the signature of the Validator
factory -- which means modifying quite a few other files.

Note that in the case of PP, we double-wrap the loss function. The
context manager only applies to the outer layer, thus has no impact on
the PP scaling, which is what we want.

[Testing]
First, run the trainer with both a normal, single GPU, run and a 2-stage
pipeline. In both cases, set the number of accumulation steps to be
sufficiently hight that the problem is obvious. This covers both
pathways to the wrapped loss function.

Repeat the tests with the fix. The magnitude of the validation loss
should roughly correlate with the train loss.
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
[Problem]
When gradient accumulation is enabled, the validation loss is incorrect.
This is a consequence of the loss_fn being shared between train and
validation mode. The loss function is wrapped with
rescale_accumulated_loss(), which rescales the loss by the number of
gradient accumulation steps.

This works for train, as the loss from N accumulation steps is summed at
the end of the accumulation, before being logged. In the case of
validation, the loop assumes that each step is a normal step, and the
reported loss is scaled by 1/N.

There are two separate pathways by which this occurs. In the normal
case, the wrapped loss function is used "as-is." In the case of PP, the
loss function is not directly used, but is still applied indirectly
through the pipeline scheduler.

In both cases, the result is that the reported validation loss is
divided by the number of accumulation steps.

[Solution]
The number of gradient accumulation steps is not communicated to the
validation-factory, thus it does not have access to this parameter,
which is computed in the Trainer's constructor.

One possible solution would be to pass this value, as an argument, to
the validator, which could then rescale the loss by this factor, before
logging it. This was the suggested solution to the problem.

My solution is a little different. The function
"rescale_accumulated_loss()" now returns a loss function with a
"no_rescale()" context manager, which we apply before calling the
validator. This transparently disables rescaling while within this
context.

This approach avoids the need to communicate this detail to the
Validator and avoids having to modify the signature of the Validator
factory -- which means modifying quite a few other files.

Note that in the case of PP, we double-wrap the loss function. The
context manager only applies to the outer layer, thus has no impact on
the PP scaling, which is what we want.

[Testing]
First, run the trainer with both a normal, single GPU, run and a 2-stage
pipeline. In both cases, set the number of accumulation steps to be
sufficiently hight that the problem is obvious. This covers both
pathways to the wrapped loss function.

Repeat the tests with the fix. The magnitude of the validation loss
should roughly correlate with the train loss.
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.

Validation loss is incorrectly scaled when combined with gradient accumulation

2 participants