Repository navigation
Enable SFT for HF Transformer backed trainer - #3243
Conversation
|
|
a30b214 to
d4b91d8
Compare
| AttentionInterface._global_mapping[ | ||
| attn_implementation | ||
| ] = sdpa_attention_forward | ||
| if attn_implementation == "flex_torchtitan": |
There was a problem hiding this comment.
maybe align the naming with core titan?
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
could you explain more on why HF model code has more dynamo guards? and why setting size to 64?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@xmfan Sg, I have created a repro and submitted an issue here: pytorch/pytorch#187073
3f00f39 to
00c31de
Compare
|
|
||
| config_fields = {f.name for f in fields(self)} | ||
| overlap = config_fields & kwargs.keys() | ||
| if overlap: |
There was a problem hiding this comment.
what is this overlap logic for?
There was a problem hiding this comment.
It's copied from the base Configurable.Config.build(). It prevents accidentally passing a config field as a build() kwarg (torchtitan/config/configurable.py))
There was a problem hiding this comment.
I think this class should inherit base config? can we call the super class method instead of redoing in subclass?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Got it, why don't we inherit from SFTTrainer.Config?
There was a problem hiding this comment.
@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, |
| 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) |
There was a problem hiding this comment.
why can't we pass these kwargs in when calling this function? In general, why do we need to create this subclass?
There was a problem hiding this comment.
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.
c7afca1 to
f812341
Compare
|
@fegin would appreciate your comments on this PR. |
a936a49 to
b627fbd
Compare
fegin
left a comment
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
@acisseJZhong Just want to make sure you are aligned before I merged this. Changed this to pass the CI test and prevent OOM.
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.
- 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.
## 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]>
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.
Summary
Enables supervised fine-tuning (SFT) for any HuggingFace model in the
transformers_modeling_backend experiment, building on the native SFT infrastructure from #2556.
post_dataloading_process(before parallelism sharding) using TorchTitan's existingget_causal_mask_mod+get_document_mask_mod— same mask infrastructure as native TorchTitan SFT.HFFlexAttentionsubclasses TorchTitan'sFlexAttentionkernel module, handling HF's tensorlayout via transposes. Registered as a submodule on each HF attention layer so
apply_cp_to_forwardworks naturally — no globals needed.flex_torchtitanas a custom attention implementation that bypasses HF's internalmask creation (which builds at the wrong point for TP+SP) and routes through a compile-friendly
flex_attentioncall.SFTTrainersubclass overridespost_dataloading_processto build the BlockMask at fullsequence length before any parallelism touches the data.
HFTransformerStateDictAdapterenables loading pretrained HF weights (trivialmodel.prefixmapping, handles weight tying).
HFBackendTokenizerpassesbos_token/eos_tokento chat templates and fixes an edge casewhere BOS and EOS share the same token string.
full-size models.
cache_size_limitworkaround needed: relies on the upstream nested-AsyncCollectiveTensorfix (pytorch#186442), so the flex path stays under the default recompile limit across all parallelisms.
torchtitan/experiments/transformers_modeling_backend/— no core modifications.Files changed
SFTTrainerbuilds BlockMask before parallelism sharding, handles CP load balancermodel.prefix strip/add for HF weight loading, handles weight tyingHFFlexAttentionsubclass +_flex_torchtitan_attention_forward;forward()accepts positions/attention_masks; guardintermediate_size/head_dimrecalculation; disableattention_dropoutfor FlexAttentionbuild()override to useSFTTrainerHFFlexAttentionmodules and callsapply_cp_to_forwardfor CPsft_debugmodel/sft_fullflavors withattn_implementation="flex_torchtitan"; wirestate_dict_adapter; None defaults forChatDataLoaderandHFBackendTokenizerParallelism support
Test plan
transformers_modeling_backend_debugmodelidentical loss before/afterNumeric verification results:
Native TorchTitan vs HuggingFace — logit parity (qwen3_0.6b, same weights + input, fp32, 161 positions)