Skip to content

Enable SFT for HF Transformer backed trainer - #3243

Merged
HosseinKaviani-H merged 12 commits into
pytorch:mainfrom
HosseinKaviani-H:sft
Jul 9, 2026
Merged

HosseinKaviani-H merged 12 commits into
pytorch:mainfrom
HosseinKaviani-H:sft

Conversation

@HosseinKaviani-H

@HosseinKaviani-H HosseinKaviani-H commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Enables supervised fine-tuning (SFT) for any HuggingFace model in the
transformers_modeling_backend experiment, building on the native SFT infrastructure from #2556.

  • Uses FlexAttention with BlockMask for packed sequences. Builds the BlockMask in
    post_dataloading_process (before parallelism sharding) using TorchTitan's existing
    get_causal_mask_mod + get_document_mask_mod — same mask infrastructure as native TorchTitan SFT.
  • HFFlexAttention subclasses TorchTitan's FlexAttention kernel module, handling HF's tensor
    layout via transposes. Registered as a submodule on each HF attention layer so
    apply_cp_to_forward works naturally — no globals needed.
  • Registers flex_torchtitan as a custom attention implementation that bypasses HF's internal
    mask creation (which builds at the wrong point for TP+SP) and routes through a compile-friendly
    flex_attention call.
  • SFTTrainer subclass overrides post_dataloading_process to build the BlockMask at full
    sequence length before any parallelism touches the data.
  • HFTransformerStateDictAdapter enables loading pretrained HF weights (trivial model. prefix
    mapping, handles weight tying).
  • HFBackendTokenizer passes bos_token/eos_token to chat templates and fixes an edge case
    where BOS and EOS share the same token string.
  • TitanDenseModelConfig defaults changed to None so HF config values aren't overridden when using
    full-size models.
  • No dynamo cache_size_limit workaround needed: relies on the upstream nested-AsyncCollectiveTensor
    fix (pytorch#186442), so the flex path stays under the default recompile limit across all parallelisms.
  • All changes within torchtitan/experiments/transformers_modeling_backend/ — no core modifications.

Files changed

File Description
trainer.py (new) SFTTrainer builds BlockMask before parallelism sharding, handles CP load balancer
state_dict_adapter.py (new) model. prefix strip/add for HF weight loading, handles weight tying
tokenizer.py (new) Passes special tokens to chat templates, fixes shared BOS/EOS edge case
model.py HFFlexAttention subclass + _flex_torchtitan_attention_forward; forward() accepts positions/attention_masks; guard
intermediate_size/head_dim recalculation; disable attention_dropout for FlexAttention
configs.py build() override to use SFTTrainer
parallelize.py Collects HFFlexAttention modules and calls apply_cp_to_forward for CP
init.py sft_debugmodel/sft_full flavors with attn_implementation="flex_torchtitan"; wire state_dict_adapter; None defaults for
TitanDenseModelConfig
config_registry.py SFT config functions (random init + pretrained weight loading) using ChatDataLoader and HFBackendTokenizer
tests/integration_tests.py 2-GPU SFT integration test

Parallelism support

Parallelism Status
FSDP Works
FSDP + TP Works
FSDP + TP + PP Works
FSDP + AC (selective/full) Works
FSDP + compile Works
FSDP + TP + compile Works
FSDP + CP Works
CP + compile Works
TP + CP Works
FSDP + TP + CP Works
FSDP + TP + CP + compile Works

Test plan

  • Pretraining regression: transformers_modeling_backend_debugmodel identical loss before/after
  • SFT debugmodel (Qwen3 arch): loss 11.0 → 3.3, 2 GPUs
  • SFT debugmodel (Mistral arch): loss 10.9 → 8.3 — architecture-agnostic
  • SFT with pretrained Qwen3-0.6B: loss 13.4 → 6.1
  • SFT with pretrained Qwen2.5-0.5B-Instruct: loss 5.3 → 1.7
  • SFT with pretrained Llama-3.2-1B-Instruct: loss 7.6 → 0.0001
  • SFT with pretrained Seed-Coder-8B-Instruct: loss 6.8 → 2.1
  • SFT with pretrained Granite-3.1-2B-Instruct: loss 50.2 → 12.2
  • FSDP + TP (4 GPU): works
  • FSDP + TP + PP (8 GPU): works
  • FSDP + compile (2 GPU): works
  • FSDP + TP + compile (4 GPU): works
  • FSDP + CP (2 GPU): works
  • CP + compile (2 GPU): works
  • TP + CP (4 GPU): works
  • FSDP + TP + CP (8 GPU): works
  • FSDP + TP + CP + compile (8 GPU, full 28-layer qwen3_0.6b): works — 0 cache-limit hits at default recompile limit
  • Reproducibility: compare loss curves against native SFT on same model/data
  • SFT loss/KL parity vs native (Add ChatDataset and ChatDataLoader for SFT training #2556), qwen3_0.6b, same weights + packed batch: max |loss diff| 3.4e-06, max KL 5.0e-09

Numeric verification results:

Native TorchTitan vs HuggingFace — logit parity (qwen3_0.6b, same weights + input, fp32, 161 positions)

metric value
top1 match 100.0000%
top5 overlap 100.0000%
KL(HF ‖ native) 1.60e-06
KL(native ‖ HF) 6.78e-07
max |logit diff| 9.06e-05
mean |logit diff| 5.14e-06
cosine similarity 1.000000

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 6, 2026
@pytorch-bot

pytorch-bot Bot commented May 6, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@HosseinKaviani-H HosseinKaviani-H changed the title Add SFT support to transformers_modeling_backend experiment. Uses 4D block-causal attention masks via HF native attention_mask interface. SFTTrainer subclass, HFTransformerStateDictAdapter for pretrained weight loading. All changes within experiments folder. Enable SFT for HF Transformer backed trainer May 6, 2026
@HosseinKaviani-H
HosseinKaviani-H force-pushed the sft branch 2 times, most recently from a30b214 to d4b91d8 Compare May 18, 2026 18:03
AttentionInterface._global_mapping[
attn_implementation
] = sdpa_attention_forward
if attn_implementation == "flex_torchtitan":

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.

maybe align the naming with core titan?

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.

So HF couples two things to the attn_implementation name: which attention function to call and whether to build a mask. We need FlexAttention but can't use HF's mask creation - need to build it before the parallelism sharding. The custom name lets us split these and register our function, opt out of HF's mask building. My understanding is that this is the same approach pretraining already uses with "sdpa_torchtitan".

attn_implementation
] = sdpa_attention_forward
if attn_implementation == "flex_torchtitan":
# HF model code has more dynamo guards than native TorchTitan,

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.

could you explain more on why HF model code has more dynamo guards? and why setting size to 64?

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.

This was one of my ambiguities as well. HF's attention forward has a bunch of if checks (KV cache, output_attentions, use_cache, dict dispatch) that native TorchTitan doesn't have. Each one becomes a dynamo guard. When TP's async collectives produce different tensor types during the first few steps, the combination of these extra guards causes more recompilations than the default limit of 8 allows. It stabilizes after 3-5 steps. So 64 just gives enough room to get there. What are your thoughts?

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.

@xmfan would appreciate your opinion.

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.

TP's async collectives produce different tensor types

What do we mean by tensor "types"? Limit to 64 is quite high, but I think it's fine since it stabilizes after 5 steps.

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.

@xmfan By "types" I mean the Python type() - AsyncCollectiveTensor vs regular Tensor. First few steps FSDP's allgather returns AsyncCollectiveTensor, later steps it's a resolved Tensor. Dynamo guards on type() so each variation triggers a recompile. Combined with HF's extra if checks, this goes past 8. Stabilizes after ~10-15 recompiles. I can decrease it to 32 if that makes more sense here?

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 is a new compile guards issue, so the weights are sometimes AsyncCollectiveTensor, iirc the compiler will always await them before running the compiled region and guards were always created on the tensor class.

It sounds like it doesn't block you, so the increased recompile count sounds good. But if you have time, please file an issue on pytorch repo.

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.

@xmfan Sg, I have created a repro and submitted an issue here: pytorch/pytorch#187073

@HosseinKaviani-H
HosseinKaviani-H force-pushed the sft branch 2 times, most recently from 3f00f39 to 00c31de Compare May 26, 2026 17:12

config_fields = {f.name for f in fields(self)}
overlap = config_fields & kwargs.keys()
if overlap:

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.

what is this overlap logic for?

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.

It's copied from the base Configurable.Config.build(). It prevents accidentally passing a config field as a build() kwarg (torchtitan/config/configurable.py))

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 class should inherit base config? can we call the super class method instead of redoing in subclass?

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 don't think we can call super().build() directly. This uses self._owner which resolves to Trainer and we need SFTTrainer. One cleaner option could be to just override _owner on the config class instead of reimplementing build():

@dataclass(kw_only=True, slots=True)
class TransformersBackendConfig(Trainer.Config):
    hf_model: str = ""

TransformersBackendConfig._owner = SFTTrainer

Then super().build() would naturally return SFTTrainer. No duplication. Thoughts?

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.

Got it, why don't we inherit from SFTTrainer.Config?

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.

@acisseJZhong Done. Gave SFTTrainer its own nested Config(Trainer.Config) so _owner auto-wires to SFTTrainer, and configs.py is now just TransformersBackendConfig = SFTTrainer.Config. Dropped the duplicated build()/overlap check. Verified _owner=SFTTrainer and the overlap check still fires.

attn_implementation
] = sdpa_attention_forward
if attn_implementation == "flex_torchtitan":
# HF model code has more dynamo guards than native TorchTitan,

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.

@xmfan would appreciate your opinion.

def apply_chat_template(self, messages, **kwargs):
kwargs.setdefault("bos_token", self.bos_token or "")
kwargs.setdefault("eos_token", self.eos_token or "")
kwargs.setdefault("add_generation_prompt", True)

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 can't we pass these kwargs in when calling this function? In general, why do we need to create this subclass?

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 core calls apply_chat_template with only messages and no kwargs. Some HF models chat templates reference bos_token/eos_token in their Jinja template (like Seed-Coder) and the base tokenizer doesn't pass them. The subclass automatically injects these so all HF chat templates work without changing the call site.

There's also an EOS edge case. Granite uses the same string for both bos_token and eos_token. The base tokenizer has an if/elif that sets BOS but skips EOS when they match. ChatDataset requires eos_id for padding packed sequences so it crashes. The subclass detects and fixes this.

@HosseinKaviani-H

Copy link
Copy Markdown
Contributor Author

@fegin would appreciate your comments on this PR.

@HosseinKaviani-H
HosseinKaviani-H force-pushed the sft branch 2 times, most recently from a936a49 to b627fbd Compare July 8, 2026 18:09

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

Attention part looks good to me.

# local_batch_size * seq_len * vocab logits tensor. batch=8,
# seq=2048 is ~9GB in fp32 and OOMs the 22GB CI GPUs.
local_batch_size=1,
seq_len=1024,

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.

@acisseJZhong Just want to make sure you are aligned before I merged this. Changed this to pass the CI test and prevent OOM.

Hossein Kavianihamedani added 2 commits July 9, 2026 10:03
Enables supervised fine-tuning for any HF dense model using FlexAttention
with BlockMask for packed sequence masking. All parallelism modes supported:
FSDP, TP, PP, compile, AC, CP.

- HFFlexAttention: subclasses FlexAttention kernel module, handles HF's
  tensor layout via transposes. Registered as submodule on each HF attention
  layer so apply_cp_to_forward works naturally.
- SFTTrainer: builds BlockMask in post_dataloading_process before
  parallelism sharding, using same mask functions as native TorchTitan.
- HFTransformerStateDictAdapter: model. prefix mapping with weight tying.
- HFBackendTokenizer: passes special tokens to chat templates, fixes
  shared BOS/EOS edge case.
- Tested with Qwen3, Qwen2.5, Llama 3.2, Seed-Coder 8B, Granite 2B.
Hossein Kavianihamedani added 10 commits July 9, 2026 10:03
- config_registry: OptimizersContainer.Config -> default_adamw; ActivationCheckpointConfig(mode=...) -> SelectiveAC.Config()
- trainer: post_dataloading_process returns 3-tuple (extra_inputs folded into extra_kwargs)
- parallelize: group tied tok_embeddings/norm/lm_head into one FSDP unit (FSDP2 requires tied params in the same group)
Follow core torchtitan convention (PR pytorch#3443): name Q/K/V/out tensors with
shape suffixes (q_BLNH native layout, q_BNLH flex-kernel layout) and add a
legend comment. Pure rename + ASCII-ize the layout-transition comments; no
behavior change.
_flex_torchtitan_attention_forward is only registered as the flex_torchtitan
attention impl, and every self_attn gets a _flex_kernel attached when that impl
is selected, so the kernel is always present. Drop the speculative no-CP
fallback and access module._flex_kernel directly.
…tion

_flex_torchtitan_attention_forward returned the attention output with an
extra transpose to (B, N, L, H), but HF's attention interface expects
(B, L, N, H) -- the same layout sdpa_attention_forward returns. The
seq/heads swap scrambled the logits, so SFT via flex_torchtitan produced
worse-than-random loss (17.5 vs 3.75 for native qwen3) despite correct
weights and mask. Return out_BLNH directly (no transpose).

Verified: flex forward now matches HuggingFace (top1 100%, cos 1.0); SFT
training converges and tracks native qwen3 (pytorch#2556) SFT to ~1e-6 loss /
~1e-8 KL over 100 steps.
…eimplementing build()

Give SFTTrainer its own nested Config(Trainer.Config) so Configurable's
__init_subclass__ auto-wires _owner=SFTTrainer. configs.py collapses to
TransformersBackendConfig = SFTTrainer.Config, dropping the duplicated
build() override and manual _owner -- the config-field/build()-kwarg
overlap check is inherited from the base Configurable.Config.build().

Addresses review feedback on the duplicated build() logic.
Only override the SDPA default ('headtail') with 'ptrr' for block_causal
CP -- 'headtail' can't shard a FlexAttention BlockMask. An explicit None
(disable balancing) or 'ptrr' is now respected, and a warning is emitted
when the default is overridden.

Addresses review feedback about clobbering user-specified load balancer.
sft_debugmodel keeps the full Qwen3 vocab (~152k), so cross-entropy
materializes a local_batch_size * seq_len * vocab logits tensor. At
batch=8/seq=2048 that's ~9.3GB in fp32 and OOMs the 22GB A10G CI
runners. Drop to batch=1/seq=1024 (~0.6GB) -- still exercises the
packed flex block_causal SFT path, just within the CI memory budget.
…ound

The bump to 64 was added (b501a04, May) on a torch nightly predating
pytorch#186442 (nested AsyncCollectiveTensor fix). On that stack the activation
checkpoint-wrapper forward re-specialized repeatedly on varying ACTs during
TP/CP/FSDP warmup, exceeding the default cache_size_limit of 8. With #186442 in
the current nightly, ACT is normalized and that frame recompiles once.

Verified with the default limit (8) across FSDP, TP, PP, CP, and compile combos
(incl. FSDP+TP+CP+compile on the full 28-layer qwen3_0.6b): all pass, peak of 2
recompiles / generation 1, zero cache-limit hits.
@HosseinKaviani-H
HosseinKaviani-H merged commit 31948fb into pytorch:main Jul 9, 2026
12 of 14 checks passed
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Jul 15, 2026
## Summary


  Enables supervised fine-tuning (SFT) for any HuggingFace model in the
transformers_modeling_backend experiment, building on the native SFT
infrastructure from pytorch#2556.

- Uses FlexAttention with BlockMask for packed sequences. Builds the
BlockMask in
`post_dataloading_process` (before parallelism sharding) using
TorchTitan's existing
`get_causal_mask_mod` + `get_document_mask_mod` — same mask
infrastructure as native TorchTitan SFT.
- `HFFlexAttention` subclasses TorchTitan's `FlexAttention` kernel
module, handling HF's tensor
layout via transposes. Registered as a submodule on each HF attention
layer so
    `apply_cp_to_forward` works naturally — no globals needed.
- Registers `flex_torchtitan` as a custom attention implementation that
bypasses HF's internal
mask creation (which builds at the wrong point for TP+SP) and routes
through a compile-friendly
    `flex_attention` call.
- `SFTTrainer` subclass overrides `post_dataloading_process` to build
the BlockMask at full
    sequence length before any parallelism touches the data.
- `HFTransformerStateDictAdapter` enables loading pretrained HF weights
(trivial `model.` prefix
    mapping, handles weight tying).
- `HFBackendTokenizer` passes `bos_token`/`eos_token` to chat templates
and fixes an edge case
    where BOS and EOS share the same token string.
- TitanDenseModelConfig defaults changed to None so HF config values
aren't overridden when using
    full-size models.
- No dynamo `cache_size_limit` workaround needed: relies on the upstream
nested-`AsyncCollectiveTensor`
fix (pytorch#186442), so the flex path stays under the default recompile
limit across all parallelisms.
- All changes within
`torchtitan/experiments/transformers_modeling_backend/` — no core
modifications.

  ## Files changed

  | File | Description |
  |---|---|
| trainer.py (new) | `SFTTrainer` builds BlockMask before parallelism
sharding, handles CP load balancer |
| state_dict_adapter.py (new) | `model.` prefix strip/add for HF weight
loading, handles weight tying |
| tokenizer.py (new) | Passes special tokens to chat templates, fixes
shared BOS/EOS edge case |
| model.py | `HFFlexAttention` subclass +
`_flex_torchtitan_attention_forward`; `forward()` accepts
positions/attention_masks; guard
`intermediate_size`/`head_dim` recalculation; disable
`attention_dropout` for FlexAttention |
  | configs.py | `build()` override to use `SFTTrainer` |
| parallelize.py | Collects `HFFlexAttention` modules and calls
`apply_cp_to_forward` for CP |
| __init__.py | `sft_debugmodel`/`sft_full` flavors with
`attn_implementation="flex_torchtitan"`; wire `state_dict_adapter`; None
defaults for
  TitanDenseModelConfig |
| config_registry.py | SFT config functions (random init + pretrained
weight loading) using `ChatDataLoader` and `HFBackendTokenizer` |
  | tests/integration_tests.py | 2-GPU SFT integration test |

  ## Parallelism support

  | Parallelism | Status |
  |---|---|
  | FSDP | Works |
  | FSDP + TP | Works |
  | FSDP + TP + PP | Works |
  | FSDP + AC (selective/full) | Works |
  | FSDP + compile | Works |
  | FSDP + TP + compile | Works |
  | FSDP + CP | Works |
  | CP + compile | Works |
  | TP + CP | Works |
  | FSDP + TP + CP | Works |
  | FSDP + TP + CP + compile | Works |

  ## Test plan

- [x] Pretraining regression: `transformers_modeling_backend_debugmodel`
identical loss before/after
  - [x] SFT debugmodel (Qwen3 arch): loss 11.0 → 3.3, 2 GPUs
- [x] SFT debugmodel (Mistral arch): loss 10.9 → 8.3 —
architecture-agnostic
  - [x] SFT with pretrained Qwen3-0.6B: loss 13.4 → 6.1
  - [x] SFT with pretrained Qwen2.5-0.5B-Instruct: loss 5.3 → 1.7
  - [x] SFT with pretrained Llama-3.2-1B-Instruct: loss 7.6 → 0.0001
  - [x] SFT with pretrained Seed-Coder-8B-Instruct: loss 6.8 → 2.1
  - [x] SFT with pretrained Granite-3.1-2B-Instruct: loss 50.2 → 12.2
  - [x] FSDP + TP (4 GPU): works
  - [x] FSDP + TP + PP (8 GPU): works
  - [x] FSDP + compile (2 GPU): works
  - [x] FSDP + TP + compile (4 GPU): works
  - [x] FSDP + CP (2 GPU): works
  - [x] CP + compile (2 GPU): works
  - [x] TP + CP (4 GPU): works
  - [x] FSDP + TP + CP (8 GPU): works
- [x] FSDP + TP + CP + compile (8 GPU, full 28-layer qwen3_0.6b): works
— 0 cache-limit hits at default recompile limit
- [x] Reproducibility: compare loss curves against native SFT on same
model/data
- [x] SFT loss/KL parity vs native (pytorch#2556), qwen3_0.6b, same weights +
packed batch: max |loss diff| 3.4e-06, max KL 5.0e-09

  Numeric verification results:

### Native TorchTitan vs HuggingFace — logit parity (qwen3_0.6b, same
weights + input, fp32, 161 positions)

  | metric | value |
  |---|---|
  | top1 match | 100.0000% |
  | top5 overlap | 100.0000% |
  | KL(HF ‖ native) | 1.60e-06 |
  | KL(native ‖ HF) | 6.78e-07 |
  | max \|logit diff\| | 9.06e-05 |
  | mean \|logit diff\| | 5.14e-06 |
  | cosine similarity | 1.000000 |

---------

Co-authored-by: Hossein Kavianihamedani <[email protected]>
mreso added a commit to mreso/torchtitan that referenced this pull request Jul 15, 2026
Absorbs 13 upstream commits (RoPE YaRN unification, dataloader resume fix,
qwen3.5 TP vision caches, fsspec checkpoint paths, etc.) and reconciles the HF
transformers backend with upstream's SFT PR (pytorch#3243), keeping our spmd-ready
design while preserving main's SFT.

- Kept our design for the conflicts: the Module-protocol path (convert_hf_to_
  module + declarative hf_sharding), HFFlexKernel + _wrap_flex_kernel_cp for
  flex/CP, EP + native-MoE + MLA kernels. Discarded main's DTensor-era
  HFFlexAttention/apply_cp_to_forward/apply_non_moe_tp where it conflicted.
- Fixed a silent auto-merge break in parallelize.py (main's orphaned
  apply_cp_to_forward(flex_modules) block, which looked for main's _flex_kernel).
- Preserved main's SFT on top of our stack: tokenizer.py, SFT flavors + ChatDataset
  presets, and a unified HFTransformerTrainer (our delegating design, which keeps
  the base Trainer's ntokens_seen and spmd_backend annotation).

Config convergence (Design A): dropped the redundant use_flex_attn bool; the
attention impl is now driven by attn_implementation ("flex_torchtitan" vs
"sdpa_torchtitan", matching main) and the mask by attn_mask_type ("causal" vs
"block_causal"), wired through get_attention_masks. block_causal requires the
flex impl (fail-loud ValueError). SFT block_causal uses main's
get_document_mask_mod (verified bit-identical to the prior efficient fast path).

HFTransformerTrainer raises a ValueError on the SDPA-only "headtail" CP load
balancer under flex, which cannot shard a flex BlockMask.

Verified: flex+CP (loss 11.87->9.31), EP/MoE (12.53->7.31), SFT end-to-end
(11.09->6.99), R4 raise, flex unit tests (3 passed), lint clean.
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