Skip to content

[CP] Fix positions handling with CP + block_causal + flexattention - #2780

Merged
fegin merged 6 commits into
mainfrom
gh/fegin/105/head
Apr 2, 2026
Merged

fegin merged 6 commits into
mainfrom
gh/fegin/105/head

Conversation

@fegin

@fegin fegin commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Issue:

When CP is enabled with block_causal + FlexAttention, the dataloader provides per-document positions in extra_inputs AND prepare_context_parallel_input() creates its own sequential positions in
extra_kwargs. Both dicts are unpacked in the model call, causing "got multiple values for keyword argument 'positions'". Additionally, the sequential positions overwrote the dataloader's per-document positions, which are needed for correct RoPE with packed sequences.

Fix:

Consolidate all positions resolution in post_dataloading_process and make prepare_context_parallel_input a pure sharding function.

  • post_dataloading_process now always pops positions from extra_inputs
    and places them in extra_kwargs when needed: dataloader per-document positions for block_causal, sequential arange positions for CP with causal attention, or nothing (model defaults to sequential RoPE slice).
  • prepare_context_parallel_input no longer creates positions — it just shards whatever the caller provides in extra_kwargs["positions"].
  • Positions always go into extra_kwargs (forwarded to all PP stages) rather than extra_inputs (first stage only), which is correct since every stage needs them for RoPE.

Verification:

  • CP2+TP2+FlexAttention
  • FlexAttention-only
  • SDPA+CP2+TP2
  • SDPA-only

fegin added 2 commits April 1, 2026 10:56
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 1, 2026
**Issue:**

When CP is enabled with block_causal + FlexAttention, the dataloader provides per-document positions in `extra_inputs` AND `prepare_context_parallel_input()` creates its own sequential positions in
extra_kwargs. Both dicts are unpacked in the model call, causing "got multiple values for keyword argument 'positions'". Additionally, the sequential positions overwrote the dataloader's per-document positions, which are needed for correct RoPE with packed sequences.

**Fix:**

Consolidate all positions resolution in `post_dataloading_process` and make `prepare_context_parallel_input` a pure sharding function.

- `post_dataloading_process` now always pops `positions` from `extra_inputs`
and places them in `extra_kwargs` when needed: dataloader per-document `positions` for block_causal, sequential arange `positions` for CP with causal attention, or nothing (model defaults to sequential RoPE slice).
- `prepare_context_parallel_input` no longer creates `positions` — it just shards whatever the caller provides in `extra_kwargs["positions"]`.
- `Positions` always go into `extra_kwargs` (forwarded to all PP stages) rather than extra_inputs (first stage only), which is correct since every stage needs them for RoPE.

**Verification:**
 - CP2+TP2+FlexAttention
 - FlexAttention-only
 - SDPA+CP2+TP2
 - SDPA-only


ghstack-source-id: 236331b
Pull-Request: #2780
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 1, 2026
@tianyu-l
tianyu-l requested a review from joecummings April 1, 2026 21:05
fegin added 2 commits April 1, 2026 22:09
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 2, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* #2785
* #2780
* __->__ #2633

## Motivation

Parameter initialization should be configurable without modifying module
code. Previously, each module defined its own `init_weights` method with
hardcoded init logic (e.g., `nn.init.trunc_normal_` with a fixed std).
This couples initialization strategy to module definitions, making it
impossible to change init behavior without editing model code.

## Design
- **Expand the config to be per-module config**
- `param_init` is a `dict[str, Callable]` on `Module.Config`, mapping
local parameter names to init functions. It is set on every sub-config
in the model config registry.
- `init_states` auto-recurses the module tree (children first, then
self), calling `_init_self_parameters` and `_init_self_buffers` on each
module. Buffer initialization remains module-specific (e.g., RoPE cache,
MoE counters) via `_init_self_buffers` overrides.
- `DeferredCallable.Config` wraps init functions that vary by layer
depth (e.g., depth-scaled std). `resolve_deferred` walks the config tree
and resolves these markers during per-layer config expansion.
- `expand_layer_configs` (per model) deep-copies the layer template N
times, resolves deferred markers, and handles model-specific layer
interleaving (MoE vs dense, iRoPE, sliding attention).

## Summary of changes

- Remove all `init_weights` methods from modules (Linear, Embedding,
RMSNorm, FeedForward, GQAttention, MoE, GroupedExperts,
TokenChoiceTopKRouter, RoPE, Decoder).
- Add `param_init` field to `Module.Config`; `Config.build()` propagates
it to the instance as `_param_init`.
- Add `init_states` with auto-recursion, `_init_self_parameters`
(dict-lookup init), and `_init_self_buffers` (module-specific buffer
init).
- Add `DeferredCallable` (in `torchtitan/config/`) for depth-varying
init.
- Add `param_init.py` (in `torchtitan/models/common/`) with
`resolve_deferred`, `skip_param_init`, and `depth_scaled_std` utilities.
- Remove `init_mean`/`init_std` fields from `Linear.Config` and
`Embedding.Config` — init is now expressed entirely through `param_init`
dicts.
- Add `layers` list and `expand_layer_configs()` pattern to all model
registries, replacing per-layer config construction in
`Decoder.__init__`.
- Add `w1`/`w2w3` fields to `FeedForward.Config` and `wqkv`/`wo` fields
to `GQAttention.Config` (replacing `linear_bias: bool`), so each linear
sub-module gets its own `param_init`.

## Verification

Bitwise identical loss against `origin/main` with `--debug.seed=42
--debug.deterministic`:

| Model  | Steps | Result            |
|--------|-------|-------------------|
| Llama3 | 10    | Bitwise identical |
fegin added 2 commits April 1, 2026 23:49
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 2, 2026
**Issue:**

When CP is enabled with block_causal + FlexAttention, the dataloader provides per-document positions in `extra_inputs` AND `prepare_context_parallel_input()` creates its own sequential positions in
extra_kwargs. Both dicts are unpacked in the model call, causing "got multiple values for keyword argument 'positions'". Additionally, the sequential positions overwrote the dataloader's per-document positions, which are needed for correct RoPE with packed sequences.

**Fix:**

Consolidate all positions resolution in `post_dataloading_process` and make `prepare_context_parallel_input` a pure sharding function.

- `post_dataloading_process` now always pops `positions` from `extra_inputs`
and places them in `extra_kwargs` when needed: dataloader per-document `positions` for block_causal, sequential arange `positions` for CP with causal attention, or nothing (model defaults to sequential RoPE slice).
- `prepare_context_parallel_input` no longer creates `positions` — it just shards whatever the caller provides in `extra_kwargs["positions"]`.
- `Positions` always go into `extra_kwargs` (forwarded to all PP stages) rather than extra_inputs (first stage only), which is correct since every stage needs them for RoPE.

**Verification:**
 - CP2+TP2+FlexAttention
 - FlexAttention-only
 - SDPA+CP2+TP2
 - SDPA-only

ghstack-source-id: 74d3309
Pull-Request: #2780
@fegin
fegin changed the base branch from gh/fegin/105/base to main April 2, 2026 07:44
@fegin
fegin merged commit 18300a1 into main Apr 2, 2026
14 of 23 checks passed
@tianyu-l
tianyu-l deleted the gh/fegin/105/head branch April 2, 2026 07:52
@weifengpy

Copy link
Copy Markdown
Contributor

this seems to be causing CI error https://github.com/pytorch/torchtitan/actions/runs/23934353369/job/69807768323?pr=2741 . Happen to debug this for my PR: #2741

Root Cause (first observed failure):
[0]:
  time      : 2026-04-03_05:05:24
  host      : 7129cea87650
  rank      : 0 (local_rank: 0)
  exitcode  : 1 (pid: 201) 
  error_file: /tmp/torchelastic__77dx68b/none__qq2xtio/attempt_0/0/error.json
  traceback : Traceback (most recent call last):
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 367, in wrapper
      return f(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^
    File "/pytorch/torchtitan/torchtitan/trainer.py", line 850, in train
      self.train_step(data_iterator)
    File "/pytorch/torchtitan/torchtitan/trainer.py", line 760, in train_step
      loss = self.forward_backward_step(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/pytorch/torchtitan/torchtitan/trainer.py", line 708, in forward_backward_step
      pred = model_parts[0](inputs, **extra_inputs, **extra_kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1778, in _wrapped_call_impl
      return self._call_impl(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1884, in _call_impl
      return inner()
             ^^^^^^^
    File "/opt/conda/envs/py_3.12/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1832, in inner
      result = forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  TypeError: Llama3Siglip2Transformer.forward() got an unexpected keyword argument 'positions'
  
============================================================
INFO:root:None
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "/pytorch/torchtitan/torchtitan/experiments/vlm/tests/integration_tests.py", line 65, in <module>
    main()
  File "/pytorch/torchtitan/torchtitan/experiments/vlm/tests/integration_tests.py", line 61, in main
    run_tests(args, test_list)
  File "/pytorch/torchtitan/tests/integration_tests/run_tests.py", line 108, in run_tests
    run_single_test(test_flavor, args.output_dir, module, config)
  File "/pytorch/torchtitan/tests/integration_tests/run_tests.py", line 73, in run_single_test
    raise Exception(
Exception: Integration test failed, flavor : VLM FSDP, command : TORCH_TRACE="/home/ec2-user/actions-runner/_work/_temp/artifacts-to-be-uploaded/vlm_fsdp/compile_trace" NGPU=4 LOG_RANK=0,1,2,3 ./run_train.sh --dump_folder /home/ec2-user/actions-runner/_work/_temp/artifacts-to-be-uploaded/vlm_fsdp --module vlm --config vlm_debugmodel --parallelism.data_parallel_shard_degree 4 --dataloader.max_patches_per_image 1024 --dataloader.max_images_per_batch 64

TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
…orch#2633)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* pytorch#2785
* pytorch#2780
* __->__ pytorch#2633

## Motivation

Parameter initialization should be configurable without modifying module
code. Previously, each module defined its own `init_weights` method with
hardcoded init logic (e.g., `nn.init.trunc_normal_` with a fixed std).
This couples initialization strategy to module definitions, making it
impossible to change init behavior without editing model code.

## Design
- **Expand the config to be per-module config**
- `param_init` is a `dict[str, Callable]` on `Module.Config`, mapping
local parameter names to init functions. It is set on every sub-config
in the model config registry.
- `init_states` auto-recurses the module tree (children first, then
self), calling `_init_self_parameters` and `_init_self_buffers` on each
module. Buffer initialization remains module-specific (e.g., RoPE cache,
MoE counters) via `_init_self_buffers` overrides.
- `DeferredCallable.Config` wraps init functions that vary by layer
depth (e.g., depth-scaled std). `resolve_deferred` walks the config tree
and resolves these markers during per-layer config expansion.
- `expand_layer_configs` (per model) deep-copies the layer template N
times, resolves deferred markers, and handles model-specific layer
interleaving (MoE vs dense, iRoPE, sliding attention).

## Summary of changes

- Remove all `init_weights` methods from modules (Linear, Embedding,
RMSNorm, FeedForward, GQAttention, MoE, GroupedExperts,
TokenChoiceTopKRouter, RoPE, Decoder).
- Add `param_init` field to `Module.Config`; `Config.build()` propagates
it to the instance as `_param_init`.
- Add `init_states` with auto-recursion, `_init_self_parameters`
(dict-lookup init), and `_init_self_buffers` (module-specific buffer
init).
- Add `DeferredCallable` (in `torchtitan/config/`) for depth-varying
init.
- Add `param_init.py` (in `torchtitan/models/common/`) with
`resolve_deferred`, `skip_param_init`, and `depth_scaled_std` utilities.
- Remove `init_mean`/`init_std` fields from `Linear.Config` and
`Embedding.Config` — init is now expressed entirely through `param_init`
dicts.
- Add `layers` list and `expand_layer_configs()` pattern to all model
registries, replacing per-layer config construction in
`Decoder.__init__`.
- Add `w1`/`w2w3` fields to `FeedForward.Config` and `wqkv`/`wo` fields
to `GQAttention.Config` (replacing `linear_bias: bool`), so each linear
sub-module gets its own `param_init`.

## Verification

Bitwise identical loss against `origin/main` with `--debug.seed=42
--debug.deterministic`:

| Model  | Steps | Result            |
|--------|-------|-------------------|
| Llama3 | 10    | Bitwise identical |
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
…ytorch#2780)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* __->__ pytorch#2780

**Issue:**

When CP is enabled with block_causal + FlexAttention, the dataloader
provides per-document positions in `extra_inputs` AND
`prepare_context_parallel_input()` creates its own sequential positions
in
extra_kwargs. Both dicts are unpacked in the model call, causing "got
multiple values for keyword argument 'positions'". Additionally, the
sequential positions overwrote the dataloader's per-document positions,
which are needed for correct RoPE with packed sequences.

**Fix:**

Consolidate all positions resolution in `post_dataloading_process` and
make `prepare_context_parallel_input` a pure sharding function.

- `post_dataloading_process` now always pops `positions` from
`extra_inputs`
and places them in `extra_kwargs` when needed: dataloader per-document
`positions` for block_causal, sequential arange `positions` for CP with
causal attention, or nothing (model defaults to sequential RoPE slice).
- `prepare_context_parallel_input` no longer creates `positions` — it
just shards whatever the caller provides in `extra_kwargs["positions"]`.
- `Positions` always go into `extra_kwargs` (forwarded to all PP stages)
rather than extra_inputs (first stage only), which is correct since
every stage needs them for RoPE.

**Verification:**
 - CP2+TP2+FlexAttention
 - FlexAttention-only
 - SDPA+CP2+TP2
 - SDPA-only
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
…orch#2633)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* pytorch#2785
* pytorch#2780
* __->__ pytorch#2633

## Motivation

Parameter initialization should be configurable without modifying module
code. Previously, each module defined its own `init_weights` method with
hardcoded init logic (e.g., `nn.init.trunc_normal_` with a fixed std).
This couples initialization strategy to module definitions, making it
impossible to change init behavior without editing model code.

## Design
- **Expand the config to be per-module config**
- `param_init` is a `dict[str, Callable]` on `Module.Config`, mapping
local parameter names to init functions. It is set on every sub-config
in the model config registry.
- `init_states` auto-recurses the module tree (children first, then
self), calling `_init_self_parameters` and `_init_self_buffers` on each
module. Buffer initialization remains module-specific (e.g., RoPE cache,
MoE counters) via `_init_self_buffers` overrides.
- `DeferredCallable.Config` wraps init functions that vary by layer
depth (e.g., depth-scaled std). `resolve_deferred` walks the config tree
and resolves these markers during per-layer config expansion.
- `expand_layer_configs` (per model) deep-copies the layer template N
times, resolves deferred markers, and handles model-specific layer
interleaving (MoE vs dense, iRoPE, sliding attention).

## Summary of changes

- Remove all `init_weights` methods from modules (Linear, Embedding,
RMSNorm, FeedForward, GQAttention, MoE, GroupedExperts,
TokenChoiceTopKRouter, RoPE, Decoder).
- Add `param_init` field to `Module.Config`; `Config.build()` propagates
it to the instance as `_param_init`.
- Add `init_states` with auto-recursion, `_init_self_parameters`
(dict-lookup init), and `_init_self_buffers` (module-specific buffer
init).
- Add `DeferredCallable` (in `torchtitan/config/`) for depth-varying
init.
- Add `param_init.py` (in `torchtitan/models/common/`) with
`resolve_deferred`, `skip_param_init`, and `depth_scaled_std` utilities.
- Remove `init_mean`/`init_std` fields from `Linear.Config` and
`Embedding.Config` — init is now expressed entirely through `param_init`
dicts.
- Add `layers` list and `expand_layer_configs()` pattern to all model
registries, replacing per-layer config construction in
`Decoder.__init__`.
- Add `w1`/`w2w3` fields to `FeedForward.Config` and `wqkv`/`wo` fields
to `GQAttention.Config` (replacing `linear_bias: bool`), so each linear
sub-module gets its own `param_init`.

## Verification

Bitwise identical loss against `origin/main` with `--debug.seed=42
--debug.deterministic`:

| Model  | Steps | Result            |
|--------|-------|-------------------|
| Llama3 | 10    | Bitwise identical |
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
…ytorch#2780)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* __->__ pytorch#2780

**Issue:**

When CP is enabled with block_causal + FlexAttention, the dataloader
provides per-document positions in `extra_inputs` AND
`prepare_context_parallel_input()` creates its own sequential positions
in
extra_kwargs. Both dicts are unpacked in the model call, causing "got
multiple values for keyword argument 'positions'". Additionally, the
sequential positions overwrote the dataloader's per-document positions,
which are needed for correct RoPE with packed sequences.

**Fix:**

Consolidate all positions resolution in `post_dataloading_process` and
make `prepare_context_parallel_input` a pure sharding function.

- `post_dataloading_process` now always pops `positions` from
`extra_inputs`
and places them in `extra_kwargs` when needed: dataloader per-document
`positions` for block_causal, sequential arange `positions` for CP with
causal attention, or nothing (model defaults to sequential RoPE slice).
- `prepare_context_parallel_input` no longer creates `positions` — it
just shards whatever the caller provides in `extra_kwargs["positions"]`.
- `Positions` always go into `extra_kwargs` (forwarded to all PP stages)
rather than extra_inputs (first stage only), which is correct since
every stage needs them for RoPE.

**Verification:**
 - CP2+TP2+FlexAttention
 - FlexAttention-only
 - SDPA+CP2+TP2
 - SDPA-only
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.

3 participants