Skip to content

ChunkedCELoss - #2937

Merged
wwwjn merged 36 commits into
mainfrom
chunked-loss
Apr 27, 2026
Merged

wwwjn merged 36 commits into
mainfrom
chunked-loss

Conversation

@wwwjn

@wwwjn wwwjn commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

ChunkedCELoss implementation in eager.

Implementation

When FSDP enabled:
- separate [norm, lm_head] FSDP group: separate backward (lm_head, decoder) will double fire reduce-scatters on the same FSDP module Need pytorch/pytorch#180428 to be landed

  • set_reshard_after_forward = false
  • set_reshard_after_backward = false
  • Reduce-scatter (SUM reduce) fires per-chunk for lm_head weights’ gradients
  • h_chunk.grad is populated via plain autograd, collected by GradAccumulator

When TP is enabled:

  • If SP is applied, all-gather on TP mesh to be Replicate(). Local tensor shape[B, L/N, D]
  • Then Detach
  • Apply chunk: chunk on sequence dimension. Local shape: [B, L/N, D].
  • Calculate CE loss on each chunk sequentially. Loss parallel is applied when calculating each chunk.

Memory Profiling

Qwen3-0.6B model FSDP=4

w/o ChunkedLoss:
Screenshot 2026-04-14 at 3 47 00 PM

With ChunkedCELoss:
Screenshot 2026-04-14 at 3 45 44 PM

Compatibility Test

(llama3 debug model)

TP + no SP

TP + SP

CP
Screenshot 2026-04-14 at 2 38 59 PM

PP

Compile
Screenshot 2026-04-14 at 4 14 19 PM

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 10, 2026
@wwwjn wwwjn changed the title ChunkedCELoss [Don't review] ChunkedCELoss Apr 10, 2026
Comment thread tests/integration_tests/features.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread tests/integration_tests/features.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread tests/integration_tests/features.py Resolved
Comment thread torchtitan/models/flux/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/components/loss.py Resolved
Comment thread torchtitan/trainer.py
**extra_kwargs,
target=targets,
losses=losses,
loss_kwargs=loss_kwargs,

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.

Here's the callsite of loss_kwargs cc @tugsbayasgalan

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

sgtm

Comment thread torchtitan/trainer.py Resolved
pytorchmergebot pushed a commit to pytorch/pytorch that referenced this pull request Apr 24, 2026
…0428)

torchtitan wraps `fully_shard([norm, lm_head])`. Two execution patterns:
- **Full forward** (no chunked loss): `norm` and `lm_head` run together
- **Chunked loss**: the model forward runs `norm`-only. Then `lm_head(chunk)` is called standalone per chunk with per-chunk backward

Depending on `_modules_to_run_forward` to drive unshard/reshard is wrong
for the chunked-loss pattern

## Changes

1. **Unshard gated on `is_unsharded`, not `_modules_to_run_forward`.**
   The pre-hook unshards whenever the group isn't already unsharded,
   independent of `_modules_to_run_forward`

2. **Root post-forward cleanup for incomplete groups.**
   `_force_complete_incomplete_states` runs at the root's
   `post_forward`

3. **Clear `iter_forward_root` in post-backward unconditionally.**
   When `model.lm_head(chunk)` claims `iter_forward_root` via its
   pre_forward, the group's `_post_forward` never fires to clear it
   (partial group)

## Why this design

Any call pattern that runs some submodule of the wrapped tree
leaves correctly reduced sharded grads after `.backward()` — across:

- Normal `model(x).backward()`.
- Unused-param cases (some modules don't run).
- Chunked-loss (standalone per-chunk calls).
- Grad accumulation (`set_requires_gradient_sync(False)`).
- Multiple forward passes before one backward.

chunked-loss fires N+1 reduce-scatters (one per chunk + one for
`h.backward`) instead of 1.

Users who know their pattern can reclaim the
single-RS behavior explicitly via `set_requires_gradient_sync(False)`: see torchtitan pytorch/torchtitan#2937

Pull Request resolved: #180428
Approved by: https://github.com/tianyu-l
@wwwjn wwwjn self-assigned this Apr 24, 2026
@wwwjn
wwwjn marked this pull request as ready for review April 24, 2026 15:59
@joecummings joecummings changed the title [Don't review] ChunkedCELoss ChunkedCELoss Apr 24, 2026
@wwwjn
wwwjn merged commit 786e26f into main Apr 27, 2026
26 of 33 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in TorchTitan Development Apr 27, 2026
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 28, 2026
The 21st upstream sync (b6c0469) brought in three breaking changes that
broke the ezpz models at import / config-build time:

- pytorch#2937 (ChunkedCELoss) removed `build_cross_entropy_loss` and replaced
  `ModelSpec.build_loss_fn` with the new `JobConfig.loss` field. Drop
  the `from torchtitan.components.loss import build_cross_entropy_loss`
  imports and the `build_loss_fn=...` kwargs. Update the ezpz trainer
  to call `config.loss.build(compile_config=config.compile)` instead.
- `Decoder.Config` renamed `output: Linear.Config` to `lm_head: Linear.Config`.
  Rename `output=Linear.Config(...)` -> `lm_head=Linear.Config(...)` in all
  agpt and moe configs.

This is the minimum mechanical fix; the sharding-API refactor (parallelize_module
-> Module.parallelize) is replayed in the next commit.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 28, 2026
50-step moe smoke test using the smallest non-debug flavor (500M) on
2 nodes, AdamW, no checkpoint, fineweb-edu HF stream. Mirrors
smoke_2b_50steps for moe to verify the post-pytorch#2963/pytorch#2937 replay end-to-end:
imports, model build, sharding-config population on MLA attention + dense
FFN, Module.parallelize, apply_moe_ep_tp, per-block compile, FSDP wrap,
optimizer step, loss decreasing.

scripts/submit_moe_smoke.sh mirrors competition/submit_run.sh but for
the moe module path.
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…orch#180428)

torchtitan wraps `fully_shard([norm, lm_head])`. Two execution patterns:
- **Full forward** (no chunked loss): `norm` and `lm_head` run together
- **Chunked loss**: the model forward runs `norm`-only. Then `lm_head(chunk)` is called standalone per chunk with per-chunk backward

Depending on `_modules_to_run_forward` to drive unshard/reshard is wrong
for the chunked-loss pattern

## Changes

1. **Unshard gated on `is_unsharded`, not `_modules_to_run_forward`.**
   The pre-hook unshards whenever the group isn't already unsharded,
   independent of `_modules_to_run_forward`

2. **Root post-forward cleanup for incomplete groups.**
   `_force_complete_incomplete_states` runs at the root's
   `post_forward`

3. **Clear `iter_forward_root` in post-backward unconditionally.**
   When `model.lm_head(chunk)` claims `iter_forward_root` via its
   pre_forward, the group's `_post_forward` never fires to clear it
   (partial group)

## Why this design

Any call pattern that runs some submodule of the wrapped tree
leaves correctly reduced sharded grads after `.backward()` — across:

- Normal `model(x).backward()`.
- Unused-param cases (some modules don't run).
- Chunked-loss (standalone per-chunk calls).
- Grad accumulation (`set_requires_gradient_sync(False)`).
- Multiple forward passes before one backward.

chunked-loss fires N+1 reduce-scatters (one per chunk + one for
`h.backward`) instead of 1.

Users who know their pattern can reclaim the
single-RS behavior explicitly via `set_requires_gradient_sync(False)`: see torchtitan pytorch/torchtitan#2937

Pull Request resolved: pytorch#180428
Approved by: https://github.com/tianyu-l
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…orch#180428)

torchtitan wraps `fully_shard([norm, lm_head])`. Two execution patterns:
- **Full forward** (no chunked loss): `norm` and `lm_head` run together
- **Chunked loss**: the model forward runs `norm`-only. Then `lm_head(chunk)` is called standalone per chunk with per-chunk backward

Depending on `_modules_to_run_forward` to drive unshard/reshard is wrong
for the chunked-loss pattern

## Changes

1. **Unshard gated on `is_unsharded`, not `_modules_to_run_forward`.**
   The pre-hook unshards whenever the group isn't already unsharded,
   independent of `_modules_to_run_forward`

2. **Root post-forward cleanup for incomplete groups.**
   `_force_complete_incomplete_states` runs at the root's
   `post_forward`

3. **Clear `iter_forward_root` in post-backward unconditionally.**
   When `model.lm_head(chunk)` claims `iter_forward_root` via its
   pre_forward, the group's `_post_forward` never fires to clear it
   (partial group)

## Why this design

Any call pattern that runs some submodule of the wrapped tree
leaves correctly reduced sharded grads after `.backward()` — across:

- Normal `model(x).backward()`.
- Unused-param cases (some modules don't run).
- Chunked-loss (standalone per-chunk calls).
- Grad accumulation (`set_requires_gradient_sync(False)`).
- Multiple forward passes before one backward.

chunked-loss fires N+1 reduce-scatters (one per chunk + one for
`h.backward`) instead of 1.

Users who know their pattern can reclaim the
single-RS behavior explicitly via `set_requires_gradient_sync(False)`: see torchtitan pytorch/torchtitan#2937

Pull Request resolved: pytorch#180428
Approved by: https://github.com/tianyu-l
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…orch#180428)

torchtitan wraps `fully_shard([norm, lm_head])`. Two execution patterns:
- **Full forward** (no chunked loss): `norm` and `lm_head` run together
- **Chunked loss**: the model forward runs `norm`-only. Then `lm_head(chunk)` is called standalone per chunk with per-chunk backward

Depending on `_modules_to_run_forward` to drive unshard/reshard is wrong
for the chunked-loss pattern

## Changes

1. **Unshard gated on `is_unsharded`, not `_modules_to_run_forward`.**
   The pre-hook unshards whenever the group isn't already unsharded,
   independent of `_modules_to_run_forward`

2. **Root post-forward cleanup for incomplete groups.**
   `_force_complete_incomplete_states` runs at the root's
   `post_forward`

3. **Clear `iter_forward_root` in post-backward unconditionally.**
   When `model.lm_head(chunk)` claims `iter_forward_root` via its
   pre_forward, the group's `_post_forward` never fires to clear it
   (partial group)

## Why this design

Any call pattern that runs some submodule of the wrapped tree
leaves correctly reduced sharded grads after `.backward()` — across:

- Normal `model(x).backward()`.
- Unused-param cases (some modules don't run).
- Chunked-loss (standalone per-chunk calls).
- Grad accumulation (`set_requires_gradient_sync(False)`).
- Multiple forward passes before one backward.

chunked-loss fires N+1 reduce-scatters (one per chunk + one for
`h.backward`) instead of 1.

Users who know their pattern can reclaim the
single-RS behavior explicitly via `set_requires_gradient_sync(False)`: see torchtitan pytorch/torchtitan#2937

Pull Request resolved: pytorch#180428
Approved by: https://github.com/tianyu-l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100.8 Trigger H100.8 CI ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot. high priority

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants