Skip to content

Fix loss computation by handling valid token imbalance in train loop - #2206

Merged
wwwjn merged 15 commits into
mainfrom
loss-calc
Jan 26, 2026
Merged

wwwjn merged 15 commits into
mainfrom
loss-calc

Conversation

@wwwjn

@wwwjn wwwjn commented Jan 7, 2026 •

Copy link
Copy Markdown
Contributor

Solve #1842

The previous implementation used per-rank/per-microbatch normalization, which caused incorrect gradient weighting when different ranks or microbatches had different numbers of valid tokens. This PR implements global token-based loss normalization to ensure each valid token contributes equally to the final loss, regardless of which rank or microbatches it appears in.

What changed

  1. cross_entropy_loss always use "sum" reduction instead of "mean" reduction.
  2. Pre-fetch all the microbatches when PP , sum all the valid tokens (global_valid_tokens) across DP ranks before gradient accumulation start.
  3. Use the global_valid_tokens to rescale loss in train loop , so each token has equal contribution to loss value.
  4. When PP is applied: use sum cross entropy loss, rescale and handle imbalance between pp-microbatchs in train loop
  5. Change validation.py: for validation, only need to handle imbalance tokens between ranks

NOTE: This change will change the loss value for integration tests, as we are back-propagating with loss = local_rank_loss_sum / global_valid_tokens (in contrast with previously, we were back-propagating using loss = local_rank_loss_sum / local_total_tokens).

The convergence speed / gradient will be the same because we disabled the AVG of gradient in FSDP.

Cons:

  • This change would incur one all_reduce() to get # global valid tokens

Testing

  1. DP + gradient accumulation: loss is identical comparing main vs this branch
  2. PP: NGPU=2, PP=2 compare main vs this branch, loss is identical.
  3. TP / loss parallel: comparing loss_parallel=true vs. loss_parallel=false, the loss are identical.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jan 7, 2026
@wwwjn
wwwjn force-pushed the loss-calc branch 2 times, most recently from fd67128 to 71d6cfe Compare January 7, 2026 06:10
@wwwjn wwwjn changed the title [WIP] handle valid token imbalance in train loop [WIP] handle valid token imbalance and fix loss computation in train loop Jan 7, 2026
@wwwjn
wwwjn requested a review from felipemello1 January 7, 2026 21:18
@wwwjn wwwjn changed the title [WIP] handle valid token imbalance and fix loss computation in train loop Handle valid token imbalance and fix loss computation in train loop Jan 7, 2026
@wwwjn wwwjn changed the title Handle valid token imbalance and fix loss computation in train loop Fix loss computation by handle valid token imbalance and in train loop Jan 7, 2026
@wwwjn wwwjn changed the title Fix loss computation by handle valid token imbalance and in train loop Fix loss computation by handling valid token imbalance in train loop Jan 7, 2026
@wwwjn wwwjn changed the title Fix loss computation by handling valid token imbalance in train loop [WIP] Fix loss computation by handling valid token imbalance in train loop Jan 8, 2026

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

Thanks for the PR!! Left a few comments

Comment thread torchtitan/train.py Resolved
Comment thread torchtitan/train.py
local_valid_tokens += (labels != IGNORE_INDEX).sum()
microbatches.append((input_dict, labels))

# All-reduce to get global token count across DP ranks

@felipemello1 felipemello1 Jan 8, 2026 •

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.

Noob question: Should we also do cp_mesh, or only dp_mesh?

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.

The number of valid tokens only comes from dataloader, cp mesh will not affect data loading behavior

@fegin fegin Jan 12, 2026 •

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.

This is a bit misleading though. After CP is applied, the input and label are sharded along sequence dimension. You can ignore cp_mesh and use batch mesh only because you are doing the computation before CP is applied. This causes the inconsistency between the logic here and the logic to compute the loss, where we need to consider CP dimension.

We should consider to put the logic into post_dataloading_process and move post_dataloading_process out from the forward_backward_step.

Comment thread torchtitan/train.py Resolved
@wwwjn wwwjn changed the title [WIP] Fix loss computation by handling valid token imbalance in train loop Fix loss computation by handling valid token imbalance in train loop Jan 8, 2026
Comment thread torchtitan/train.py Resolved
Comment thread torchtitan/train.py Resolved
Comment thread torchtitan/train.py Outdated
# All-reduce to get global token count across DP ranks
if parallel_dims.dp_enabled:
dp_mesh = parallel_dims.get_optional_mesh("batch")
ft_pg = self.ft_manager.loss_sync_pg

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 don't know the details here, what is loss_sync_pg? For non-ft, we should sync along DDP, FSDP, and CP for loss, but only DDP, FSDP for valid tokens.

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.

I follow the practice when we log the loss in train.py:

if parallel_dims.dp_cp_enabled:
loss = loss.detach()
ft_pg = self.ft_manager.loss_sync_pg
loss_mesh = parallel_dims.get_optional_mesh("loss")
global_avg_loss, global_max_loss, global_ntokens_seen = (
dist_utils.dist_mean(loss, loss_mesh, ft_pg),
dist_utils.dist_max(loss, loss_mesh, ft_pg),
dist_utils.dist_sum(
torch.tensor(
self.ntokens_seen, dtype=torch.int64, device=self.device
),
loss_mesh,
ft_pg,
),
)
.

For non-ft, we should sync along DDP, FSDP, and CP for loss, but only DDP, FSDP for valid tokens.

This is right, thank you

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.

My question is not resolved -- why do we sync across CP for num_valid_token computation?

@wwwjn wwwjn Jan 20, 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.

My question is not resolved -- why do we sync across CP for num_valid_token computation?

We didn't sync cross CP for num_valid_token computation, here batch dimension is only "dp_replicate" and "dp_shard", not "CP".

We have discussion with @fegin about this, CP is applied in forward_backward_step (here), which is after the num_valid_token calculation. But when we log the loss after forward_backward_step returned, cp are already applied.

You can ignore cp_mesh and use batch mesh only because you are doing the computation before CP is applied. This causes the inconsistency between the logic here and the logic to compute the loss, where we need to consider CP dimension.

We should consider to put the logic into post_dataloading_process and move post_dataloading_process out from the forward_backward_step.

This part is more tricky because now we put input / labels on CPU and calculate the number of valid tokens before post_dataloading_process. Calculating attention mask needs the inputs to be on GPU. I think about this because of Flux: FLUX do the same post_dataloading_process to apply image encoder on the label image, which will change the shape of the label. So for FLUX model, we should only calculate the number of valid tokens after the post_dataloading_process, which has already make all the labels on GPU.

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.

to clarify: my question is on the usage of ft_pg = self.ft_manager.loss_sync_pg. Do you know what it does? In the long term, could you help move ft-related logic to experiments?

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.

Oh I see where the "loss" comes from, thanks for clarification! I don't exactly know what this pg is doing, but I think we could remove here, and long-term move ft related to experiments

Comment thread torchtitan/train.py Resolved
Comment thread torchtitan/train.py Resolved
Comment thread torchtitan/train.py Resolved
Comment thread torchtitan/train.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/validate.py Outdated
loss /= num_steps
# All-reduce token count across DP ranks to get global token count
if parallel_dims.dp_enabled:
loss_mesh = parallel_dims.get_optional_mesh("dp_replicate", "dp_shard")

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 CP is not included here? parallel_dims.get_optional_mesh("loss") is ("dp_replicate", "dp_shard", "cp"). We need to do dist_sum across all these dimensions to get global valid tokens? I may misunderstand something here.

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.

My bad, for validation, I moved the global_valid_token calculation before the CP is applied, and right after dataloader

Comment thread torchtitan/distributed/parallel_dims.py Resolved
Comment thread torchtitan/train.py Resolved
Comment thread torchtitan/train.py
local_valid_tokens += (labels != IGNORE_INDEX).sum()
microbatches.append((input_dict, labels))

# All-reduce to get global token count across DP ranks

@fegin fegin Jan 12, 2026 •

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.

This is a bit misleading though. After CP is applied, the input and label are sharded along sequence dimension. You can ignore cp_mesh and use batch mesh only because you are doing the computation before CP is applied. This causes the inconsistency between the logic here and the logic to compute the loss, where we need to consider CP dimension.

We should consider to put the logic into post_dataloading_process and move post_dataloading_process out from the forward_backward_step.

Comment thread torchtitan/train.py
@@ -529,10 +528,9 @@ def forward_backward_step(
# accumulate losses across pipeline microbatches
# TODO: PP+FSDP unexpectedly puts the loss back to the CPU

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.

@H-Huang
Is this expected, or fixed? IIUC putting loss on CPU would incur d2h sync which could've been avoided?

@wwwjn can we create an issue to track?

Comment thread torchtitan/train.py Outdated
# All-reduce to get global token count across DP ranks
if parallel_dims.dp_enabled:
dp_mesh = parallel_dims.get_optional_mesh("batch")
ft_pg = self.ft_manager.loss_sync_pg

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.

My question is not resolved -- why do we sync across CP for num_valid_token computation?

Comment thread torchtitan/components/validate.py Resolved
Comment thread torchtitan/components/validate.py Resolved
Comment thread torchtitan/components/validate.py Resolved
Comment thread torchtitan/train.py Resolved

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

please address the last comment

Comment thread torchtitan/models/flux/train.py Resolved
@wwwjn

wwwjn commented Jan 23, 2026

Copy link
Copy Markdown
Contributor Author

CI failing "DeepSeek V3 Flex+PP+FSDP+EP+SACOP" not related to this change

@tianyu-l

tianyu-l commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor

may need to rebase for the varlen error to disappear

wwwjn and others added 14 commits January 25, 2026 15:40
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* #2145
* __->__ #2144

**Summary**

1. Refactored CP Dispatching:
- New apply_cp() function uses PyTorch's _ContextParallel
parallelization plan to dispatch attention call.
  - Enables CP dispatcher for SDPA attention type inside apply_cp()
2. New CP Data Sharding Approach:
- Added a cp_shard() helper function that wraps PyTorch's
_context_parallel_shard API
  - Uses _HeadTailLoadBalancer for SDPA attention load balancing
  - FlexAttention CP support deferred to a future PR
- CP sharding now happens explicitly in post_dataloading_process() where
inputs, labels, and positions are sharded
  - The new positions argument allows us to not shard the freqs_cis.

Note that this PR require pytorch/pytorch#170200

**Test**
```
-> % python3 scripts/loss_compare.py . chienchin/loss_compare --baseline-options="--parallelism.context_parallel_degree=8" --test-options="--parallelism.context_parallel_degree=8" --steps=100 --assert-equal

pick 5903566a Improve the loss_compare.sh logic

[LOSS_COMPARE]
[LOSS_COMPARE] Asserting losses are equal...
[LOSS_COMPARE] Baseline log: /tmp/baseline_training.log
[LOSS_COMPARE] Test log: /tmp/test_training.log
[LOSS_COMPARE] Extracted 100 steps from baseline log
[LOSS_COMPARE] Extracted 100 steps from test log
test_losses_equal
(__main__.assert_losses_equal.<locals>.LossEqualityTest.test_losses_equal)
... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
[LOSS_COMPARE] All losses are equal. Assertion passed!
[LOSS_COMPARE] ==========================================
[LOSS_COMPARE] LOSS COMPARISON ANALYSIS
[LOSS_COMPARE] ==========================================

[LOSS_COMPARE] Step-by-step loss comparison:
[LOSS_COMPARE] Step    Baseline Loss    Test Loss   Difference
[LOSS_COMPARE] ----    -------------    ---------   ----------
[LOSS_COMPARE] 1       8.1309           8.1309           0.000000
[LOSS_COMPARE] 2       7.8268           7.8268           0.000000
[LOSS_COMPARE] 3       7.2284           7.2284           0.000000
[LOSS_COMPARE] 4       6.4669           6.4669           0.000000
[LOSS_COMPARE] 5       5.4017           5.4017           0.000000
[LOSS_COMPARE] 6       4.7656           4.7656           0.000000
[LOSS_COMPARE] 7       4.3587           4.3587           0.000000
[LOSS_COMPARE] 8       4.0938           4.0938           0.000000
[LOSS_COMPARE] 9       4.4019           4.4019           0.000000
[LOSS_COMPARE] 10      3.7451           3.7451           0.000000
....
[LOSS_COMPARE] 90      2.802            2.802            0.000000
[LOSS_COMPARE] 91      2.7207           2.7207           0.000000
[LOSS_COMPARE] 92      2.7454           2.7454           0.000000
[LOSS_COMPARE] 93      2.6992           2.6992           0.000000
[LOSS_COMPARE] 94      2.743            2.743            0.000000
[LOSS_COMPARE] 95      2.7534           2.7534           0.000000
[LOSS_COMPARE] 96      2.8403           2.8403           0.000000
[LOSS_COMPARE] 97      2.783            2.783            0.000000
[LOSS_COMPARE] 98      3.0892           3.0892           0.000000
[LOSS_COMPARE] 99      2.7905           2.7905           0.000000
[LOSS_COMPARE] 100     2.733            2.733            0.000000
[LOSS_COMPARE]
[LOSS_COMPARE] Summary statistics:
[LOSS_COMPARE] Average baseline loss:  3.1414940000000002
[LOSS_COMPARE] Average test loss: 3.1414940000000002
[LOSS_COMPARE] Average difference:     0.000000
[LOSS_COMPARE]
[LOSS_COMPARE] Loss comparison complete. No results saved (no output
folder specified).
```

**TODO**
- This PR will invalidate torch.compile + CP due to
pytorch/pytorch#170110. We will have to wait
for Dynamo to fix the issue or refactor nn.Module core logic to avoid
check hook_id.
@wwwjn
wwwjn merged commit 0cb7435 into main Jan 26, 2026
hann-wang added a commit to hann-wang/torchtitan that referenced this pull request Feb 24, 2026
* support launching custom trainer;
* init trainer components through .build() (pytorch#2386);
* move data to GPU by micro-batch;
* remove rescale_accumulated_loss (pytorch#2206).
tianyu-l pushed a commit that referenced this pull request Feb 25, 2026
* support launching custom trainer;
* init trainer components through .build() (#2386);
* move data to GPU by micro-batch;
* remove rescale_accumulated_loss (#2206).
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
…ytorch#2206)

Solve pytorch#1842

The previous implementation used per-rank/per-microbatch normalization,
which caused incorrect gradient weighting when different ranks or
microbatches had different numbers of valid tokens. This PR implements
global token-based loss normalization to ensure each valid token
contributes equally to the final loss, regardless of which rank or
microbatches it appears in.

## What changed
1. cross_entropy_loss always use "sum" reduction instead of "mean"
reduction.
2. Pre-fetch all the microbatches when PP , sum all the valid tokens
(global_valid_tokens) across DP ranks before gradient accumulation
start.
3. Use the global_valid_tokens to rescale loss in train loop , so each
token has *equal* contribution to loss value.
4. When PP is applied: use sum cross entropy loss, rescale and handle
imbalance between pp-microbatchs in train loop
5. Change `validation.py`: for validation, only need to handle imbalance
tokens between ranks

NOTE: This change will change the loss value for integration tests, as
we are back-propagating with loss = local_rank_loss_sum /
global_valid_tokens (in contrast with previously, we were
back-propagating using loss = local_rank_loss_sum / local_total_tokens).

The convergence speed / gradient will be the same because we disabled
the AVG of gradient in FSDP.

Cons:
- This change would incur one all_reduce() to get # global valid tokens

## Testing
1. DP + gradient accumulation: loss is identical comparing `main` vs
this branch
2. PP: NGPU=2, PP=2 compare `main` vs this branch, loss is identical. 
3. TP / loss parallel: comparing loss_parallel=true vs.
loss_parallel=false, the loss are identical.

---------

Co-authored-by: Chien-Chin Huang <[email protected]>
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
* support launching custom trainer;
* init trainer components through .build() (pytorch#2386);
* move data to GPU by micro-batch;
* remove rescale_accumulated_loss (pytorch#2206).
hann-wang added a commit to AMD-AGI/torchtitan-amd that referenced this pull request Apr 15, 2026
* support launching custom trainer;
* init trainer components through .build() (pytorch#2386);
* move data to GPU by micro-batch;
* remove rescale_accumulated_loss (pytorch#2206).
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
…ytorch#2206)

Solve pytorch#1842

The previous implementation used per-rank/per-microbatch normalization,
which caused incorrect gradient weighting when different ranks or
microbatches had different numbers of valid tokens. This PR implements
global token-based loss normalization to ensure each valid token
contributes equally to the final loss, regardless of which rank or
microbatches it appears in.

## What changed
1. cross_entropy_loss always use "sum" reduction instead of "mean"
reduction.
2. Pre-fetch all the microbatches when PP , sum all the valid tokens
(global_valid_tokens) across DP ranks before gradient accumulation
start.
3. Use the global_valid_tokens to rescale loss in train loop , so each
token has *equal* contribution to loss value.
4. When PP is applied: use sum cross entropy loss, rescale and handle
imbalance between pp-microbatchs in train loop
5. Change `validation.py`: for validation, only need to handle imbalance
tokens between ranks

NOTE: This change will change the loss value for integration tests, as
we are back-propagating with loss = local_rank_loss_sum /
global_valid_tokens (in contrast with previously, we were
back-propagating using loss = local_rank_loss_sum / local_total_tokens).

The convergence speed / gradient will be the same because we disabled
the AVG of gradient in FSDP.

Cons:
- This change would incur one all_reduce() to get # global valid tokens

## Testing
1. DP + gradient accumulation: loss is identical comparing `main` vs
this branch
2. PP: NGPU=2, PP=2 compare `main` vs this branch, loss is identical. 
3. TP / loss parallel: comparing loss_parallel=true vs.
loss_parallel=false, the loss are identical.

---------

Co-authored-by: Chien-Chin Huang <[email protected]>
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
* support launching custom trainer;
* init trainer components through .build() (pytorch#2386);
* move data to GPU by micro-batch;
* remove rescale_accumulated_loss (pytorch#2206).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu 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.

4 participants