Skip to content

Add ChatDataset and ChatDataLoader for SFT training - #2556

Merged
joecummings merged 12 commits into
pytorch:mainfrom
joecummings:sft-experiment
Mar 30, 2026
Merged

joecummings merged 12 commits into
pytorch:mainfrom
joecummings:sft-experiment

Conversation

@joecummings

@joecummings joecummings commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds ChatDataset and ChatDataLoader to torchtitan/hf_datasets/text_datasets.py for 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: thin ParallelAwareDataloader subclass (same pattern as HuggingFaceTextDataLoader)
  • SFT config functions for llama3 (sft_debugmodel) and qwen3 (sft_qwen3_8b_math)
  • Removes torchtitan/experiments/sft/ (promoted to core)
  • Fixes HuggingFaceTextDataset to shuffle map-style datasets on re-loop (previously iterated in the same order every epoch)

Training results

Step Loss Grad Norm MFU
1 1.906 24.89 0.59%
10 0.846 3.37 21.89%
50 0.853 2.42 21.86%
100 0.753 1.95 21.85%
180 0.664 1.96 21.85%

WandB run: https://wandb.ai/jcummings/torchtitan/runs/wnk5kdbe

Correctness verification

Tokenization comparison (script, output): Verified against HuggingFace AutoTokenizer on 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)

Step TorchTitan TRL
1 1.279 1.656
2 0.912 0.996
3 0.680 0.744
4 0.812 0.814
5 0.843 0.799
10 0.963 0.993
14 0.415 0.415
20 0.417 0.527

TorchTitan losses are consistently lower. 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|>:

When we intentionally replicate TRL's behavior (add duplicate EOS + use HF internal shift), the losses match to within 0.0002:

Test plan

  • 14 unit tests in test_chat_dataset.py (label masking, token shifting, packing, per-document positions, overflow drop, message validation, checkpointing round-trip, infinite looping)
  • test_dataloader.py and test_dataset_checkpointing.py still pass (existing completion path unchanged)
  • Full 180-step Qwen3-8B SFT run on GSM8K converges (loss 1.91 -> 0.66)
  • Tokenization matches HuggingFace AutoTokenizer exactly (Qwen3-0.6B and 8B)
  • Single-sample forward loss matches HF to within 0.02
  • TRL loss gap fully explained by duplicate EOS (matches to 0.0002 when replicated)
  • pre-commit run --all-files passes (flake8, ufmt, pydoclint, codespell)

Also included: script to migrate old checkpoints

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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 11, 2026
Comment thread torchtitan/experiments/sft/dataset.py Resolved
Comment thread torchtitan/experiments/sft/configs.py Resolved
…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
@joecummings
joecummings force-pushed the sft-experiment branch 2 times, most recently from 2610ced to d3e2e81 Compare March 25, 2026 02:39
@joecummings joecummings changed the title [do not review] Add SFT experiment Add ChatDataset and ChatDataLoader for SFT training Mar 25, 2026
@joecummings
joecummings force-pushed the sft-experiment branch 2 times, most recently from 67bc98f to 7b26c19 Compare March 25, 2026 03:06

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

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?

Comment thread torchtitan/hf_datasets/text_datasets.py Resolved

dataset = load_dataset(config.dataset_path, **config.load_dataset_kwargs)

chat_ds = ChatDataset(

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.

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)

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.

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.

Comment thread torchtitan/hf_datasets/text_datasets.py Resolved
Comment thread torchtitan/hf_datasets/text_datasets.py Resolved
Comment thread torchtitan/hf_datasets/text_datasets.py Outdated
if self.pack_sequences:
yield from self._iter_greedy_packed()
else:
yield from self._iter_unpacked()

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.

how valuable is this in reality? Would user ever want to use it over packing?

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

Comment thread torchtitan/hf_datasets/text_datasets.py Outdated

pad_len = self.seq_len - len(input_ids)
if pad_len > 0:
input_ids = input_ids + [self._eos_id] * pad_len

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.

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.

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

Comment thread torchtitan/hf_datasets/text_datasets.py Resolved
Comment on lines +268 to +269
load_dataset_kwargs={"name": "main", "split": "train"},
sample_processor=process_sample,

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

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.

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.

@joecummings
joecummings force-pushed the sft-experiment branch 5 times, most recently from 264be8c to e4d6c5b Compare March 25, 2026 23:51
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.

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

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?

Comment thread tests/integration_tests/features.py Outdated
skip_rocm_test=True,
"SFT ChatDataset integration test",
"sft",
ngpu=1,

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.

at least 2 / 4 so we get signal from distributed

return path, config.loader, config.sample_processor


class HuggingFaceTextDataset(IterableDataset, Stateful):

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.

For consistency, maybe we should rename this to

Suggested change
class TextDataset(IterableDataset, Stateful):

and also similar for dataloader. Doesn't have to be in this PR tho.

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.

Agree, will do in a follow-up.

Comment thread torchtitan/hf_datasets/text_datasets.py Resolved
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.
# 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).
@joecummings
joecummings marked this pull request as ready for review March 26, 2026 03:14

model_spec = model_registry("8B")
# pyrefly: ignore [missing-attribute]
model_spec.model.layer.attention.attn_backend = "varlen"

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.

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.
@joecummings
joecummings merged commit 04893dc into pytorch:main Mar 30, 2026
17 of 28 checks passed
@joecummings
joecummings deleted the sft-experiment branch March 30, 2026 16:56
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
HosseinKaviani-H pushed a commit to HosseinKaviani-H/torchtitan_local that referenced this pull request Jul 1, 2026
…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.
HosseinKaviani-H pushed a commit to HosseinKaviani-H/torchtitan_local that referenced this pull request Jul 7, 2026
…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.
HosseinKaviani-H pushed a commit to HosseinKaviani-H/torchtitan_local that referenced this pull request Jul 8, 2026
…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.
HosseinKaviani-H pushed a commit to HosseinKaviani-H/torchtitan_local that referenced this pull request Jul 9, 2026
…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.
HosseinKaviani-H added a commit that referenced this pull request Jul 9, 2026
## 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]>
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]>
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