Repository navigation
Add ChatDataset and ChatDataLoader for SFT training - #2556
Conversation
Adds an SFT dataloader and config under torchtitan/experiments/sft/ that reuses the existing Trainer without modification. Key features: - Incremental prefix re-tokenization for correct label masking at BPE boundaries (matches torchtune's approach) - Greedy sequence packing with EOS-based document boundaries for flex/varlen attention backends - Config validation for attention backend compatibility and validation hang prevention - Epoch shuffling with deterministic seeds for checkpoint reproducibility - GSM8K dataset config with Qwen3 reasoning trace support Includes 13 unit tests and a 2-GPU integration test.
…idation When packing multiple documents into one sequence, RoPE positions were not reset per document, causing later documents to receive wrong positional embeddings (positions continued from the previous document instead of restarting at 0). This fixes pytorch#2559. Changes: - Yield per-document position tensors from packed sequences that reset to 0 at each document boundary, flowing through extra_inputs to Decoder.forward(positions=...) - Validate attn_mask_type='block_causal' when pack_sequences=True to prevent cross-document attention leakage - Simplify _tokenize_sample to single-turn with explicit validation - Extract _flush_pack_buffer helper and use slice assignment for masking
2610ced to
d3e2e81
Compare
67bc98f to
7b26c19
Compare
tianyu-l
left a comment
There was a problem hiding this comment.
TRL loss comparison (scripts/compare_trl_loss.py): Compared against TRL's SFTTrainer with completion_only_loss=True on Qwen3-0.6B, 20 steps, matching hyperparameters.
...
Loss trajectories are in the same range.
They look very different to me. Could you double check?
|
|
||
| dataset = load_dataset(config.dataset_path, **config.load_dataset_kwargs) | ||
|
|
||
| chat_ds = ChatDataset( |
There was a problem hiding this comment.
Is cls the only actual difference that necessitates ChatDataLoader? Maybe we can do if/else factory here in TextDataLoader based on the dataset type. (If we can't "tell" from the dataset, we can add a field in https://github.com/pytorch/torchtitan/blob/main/torchtitan/hf_datasets/__init__.py#L15)
There was a problem hiding this comment.
You're correct that the dataloaders are just wrappers around the datasets which they construct. However, any change to unify the dataloaders (which I agree should be done) will require BC breaking changes to at least the params.
Seeing as I'd like to propose some larger changes to how Titan does dataloading, I'd rather get this SFT work in with these clean boundaries.
| if self.pack_sequences: | ||
| yield from self._iter_greedy_packed() | ||
| else: | ||
| yield from self._iter_unpacked() |
There was a problem hiding this comment.
how valuable is this in reality? Would user ever want to use it over packing?
There was a problem hiding this comment.
I use this exclusively for testing. Since I don't imagine we will check in the script that directly compares loss curves against TRL, we can remove after proving parity.
|
|
||
| pad_len = self.seq_len - len(input_ids) | ||
| if pad_len > 0: | ||
| input_ids = input_ids + [self._eos_id] * pad_len |
There was a problem hiding this comment.
Padding by eos_id instead of pad_id sounds unintuitive to me. In current torchtitan, I wonder if the flex attention masking can handle this correctly: e.g. there should be 0 computation in attention, instead of eos_id attending to itself.
There was a problem hiding this comment.
This is the most common approach for packing (axolotl, trl). In practice, there is very little padding so this extra computation is negligible.
But you're right, we could explore adding a padding mask to the existing document_mask via flex_attention's mask_mod. Let me add that as a TODO.
| load_dataset_kwargs={"name": "main", "split": "train"}, | ||
| sample_processor=process_sample, |
There was a problem hiding this comment.
I wonder if it makes sense to have a fixed registration table at https://github.com/pytorch/torchtitan/blob/main/torchtitan/hf_datasets/text_datasets.py#L35
It certainly makes writing test easier inside torchtitan (instead of ad hoc in config_registry like here), but makes it harder for people outside. Either way works for me, but let's make pretrain / sft datasets consistent.
There was a problem hiding this comment.
As we evolve more into posttraining, I'd like Titan to adopt more of this "recipe"-style config. Each one of these is so model/data/algo specific that it quickly becomes cumbersome to specify all as a fixed registration table and even more cumbersome to ensure that each piece is used with the correct combo of model/data/algo.
264be8c to
e4d6c5b
Compare
Adds ChatDataset (single-turn chat/instruction-tuning dataset) and ChatDataLoader to text_datasets.py alongside the existing completion dataset. ChatDataset tokenizes [user, assistant] message pairs, masks prompt tokens with IGNORE_INDEX, and supports greedy sequence packing with per-document positions for block_causal attention. Includes SFT config functions for llama3 (sft_debugmodel) and qwen3 (sft_qwen3_8b_math), plus 14 unit tests covering label masking, packing, checkpointing, overflow drop, and message validation. Verified: Qwen3-8B SFT on GSM8K starts at loss 2.01, converges to 0.72 in 20 steps on 2xH100.
e4d6c5b to
cb44b35
Compare
tianyu-l
left a comment
There was a problem hiding this comment.
The gap is explained by TRL appending a duplicate EOS token to every sample. TRL's add_eos checks completion.endswith(eos_token), but chat templates produce <|im_end|>\n (with a trailing newline), so the check fails and TRL appends a redundant <|im_end|>
oh is it a bug? If so, shall we file an issue for them?
| skip_rocm_test=True, | ||
| "SFT ChatDataset integration test", | ||
| "sft", | ||
| ngpu=1, |
There was a problem hiding this comment.
at least 2 / 4 so we get signal from distributed
| return path, config.loader, config.sample_processor | ||
|
|
||
|
|
||
| class HuggingFaceTextDataset(IterableDataset, Stateful): |
There was a problem hiding this comment.
For consistency, maybe we should rename this to
| class TextDataset(IterableDataset, Stateful): |
and also similar for dataloader. Doesn't have to be in this PR tho.
There was a problem hiding this comment.
Agree, will do in a follow-up.
ChatDataset now always packs sequences. Packing is strictly better for throughput and is the standard approach for SFT. Removes pack_sequences parameter, _iter_unpacked method, and associated tests. Updates sft_debugmodel to use varlen attention with block_causal masking, matching the qwen3 SFT config.
8f4c1d5 to
ef107de
Compare
# Conflicts: # tests/integration_tests/features.py
Rename _token_buffer/_position_buffer in HuggingFaceTextDataset and _pack_buffer_* in ChatDataset to a consistent naming convention: _inputs_buffer, _labels_buffer, _positions_buffer.
Captures deterministic loss values (seed=42) for sft_debugmodel on 2xGPU with flex attention. Use with loss_compare.py --assert-equal --import-result to verify SFT data pipeline correctness. Also switches sft_debugmodel from varlen to flex attention for compatibility with torch 2.10 (varlen_attn API mismatch).
5597b87 to
87f9748
Compare
|
|
||
| model_spec = model_registry("8B") | ||
| # pyrefly: ignore [missing-attribute] | ||
| model_spec.model.layer.attention.attn_backend = "varlen" |
There was a problem hiding this comment.
This override can be removed if #2649 landed. cc @zhxchen17 please update these part if this PR (#2556) lands first.
Reverts the epoch-based shuffle on dataset re-loop to match upstream behavior. The shuffle changed pre-training numerics causing the golden loss file comparison to fail in CI.
Use model_registry's attn_backend_override parameter instead of manually patching attn_backend and attn_mask_type on the model spec.
…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.
…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.
…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.
…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.
## 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 - [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 (#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]>
## 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]>
Summary
Adds
ChatDatasetandChatDataLoadertotorchtitan/hf_datasets/text_datasets.pyfor supervised fine-tuning on instruction/conversation datasets.ChatDataset: single-turn [user, assistant] tokenization with prompt masking (IGNORE_INDEX), greedy sequence packing with per-document RoPE positions, checkpointing via Stateful. Supports both map-style and iterable/streaming datasets.ChatDataLoader: thinParallelAwareDataloadersubclass (same pattern asHuggingFaceTextDataLoader)sft_debugmodel) and qwen3 (sft_qwen3_8b_math)torchtitan/experiments/sft/(promoted to core)HuggingFaceTextDatasetto shuffle map-style datasets on re-loop (previously iterated in the same order every epoch)Training results
WandB run: https://wandb.ai/jcummings/torchtitan/runs/wnk5kdbe
Correctness verification
Tokenization comparison (script, output): Verified against HuggingFace
AutoTokenizeron GSM8K with Qwen3-8B tokenizer. All 3 phases pass (chat template rendering, full tokenization, prompt/label split).Single-sample loss comparison (script, output): Forward pass on the same sample with the same Qwen3-0.6B model. Delta: 0.020.
TRL loss comparison (Qwen3-0.6B, 20 steps, no packing, sequential data)
(script, output)
TorchTitan losses are consistently lower. The gap is explained by TRL appending a duplicate EOS token to every sample. TRL's
add_eoscheckscompletion.endswith(eos_token), but chat templates produce<|im_end|>\n(with a trailing newline), so the check fails and TRL appends a redundant<|im_end|>:When we intentionally replicate TRL's behavior (add duplicate EOS + use HF internal shift), the losses match to within 0.0002:
Test plan
test_chat_dataset.py(label masking, token shifting, packing, per-document positions, overflow drop, message validation, checkpointing round-trip, infinite looping)test_dataloader.pyandtest_dataset_checkpointing.pystill pass (existing completion path unchanged)AutoTokenizerexactly (Qwen3-0.6B and 8B)pre-commit run --all-filespasses (flake8, ufmt, pydoclint, codespell)Also included: script to migrate old checkpoints