Skip to content

Studio: keep every turn when training a chat dataset with Alpaca format - #11053

Merged
danielhanchen merged 3 commits into
unslothai:mainfrom
NilayYadav:fix-alpaca-multi-turn
Sep 16, 2026
Merged

danielhanchen merged 3 commits into
unslothai:mainfrom
NilayYadav:fix-alpaca-multi-turn

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

If you picked Alpaca as the Target Format for a chat dataset, training only used the first question and answer of each conversation. The system prompt and every later turn were dropped with no warning, and training still finished normally.

Each assistant reply now becomes its own Alpaca row. The user message goes in instruction, and the system prompt plus earlier turns go in input. This is the same layout Studio already uses when you export chats as Alpaca. Auto and the other formats are unchanged.

With 8 conversations that each have a system prompt and 3 turns, main trained on 8 rows with only the first turn. With this change it trains on 24 rows with every turn and the system prompt, and Auto gives the same result as main. Added unit tests that fail on main.


Before and after in Studio

Two isolated Studio installs, one built from this PR's merge base 89862daec and one from head e430d2edc, each serving its own checkout. Same local file on both sides (8 conversations, a system prompt and 3 turns each, dataset_sha256 identical on both halves), same model unsloth/Qwen2.5-0.5B-Instruct, LoRA, 1 epoch, batch 1, Target Format Alpaca. The Train tab's History card is the surface a user actually reads:

PR 11053 before and after, Train history card

merge base 89862daec this PR e430d2edc
History card Loss: 0.9216 Steps: 8/8 Loss: 0.1279 Steps: 24/24
rows trained 8, first turn only, system prompt dropped 24, every reply, system prompt in input

The row count is the only input that moved: both sides read a byte-identical dataset file.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T11:11:39.101498Z e430d2e Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 7f8339c9a5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@NilayYadav

NilayYadav commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Review + UI evidence

Pinned head: 7f8339c9a5bf009b717b828650a3f43b07d1a2f8 (merge base 128659085b).

Review fix (Codex P2, genuine). When Studio trains a vision-capable model on a text dataset (for example Gemma 3), the tokenizer is a processor, so chat standardization turns every message into a list of text parts. Structured ChatML datasets arrive the same way. The first commit joined the system prompt as a string and raised TypeError: sequence item 0: expected str instance, list found, so the conversion failed. Reproduced with the real unsloth/gemma-3-4b-it processor, 8 conversations × 3 turns:

Input main fd0dfc0 7f8339c
ShareGPT, text tokenizer 8 rows, system prompt dropped 24 rows 24 rows
ShareGPT, Gemma 3 processor 8 rows of [{'type': 'text', ...}] text conversion failed 24 rows, plain text
ChatML with content parts 8 rows of [{'type': 'text', ...}] text conversion failed 24 rows, plain text

7f8339c converts content parts to text before building the rows. It adds two regression tests: both fail on fd0dfc0 and pass on 7f8339c, 10/10 in the file. The no-torch import test passes, and the pinned ruff 0.6.9 reports no changes.

GitHub Actions A/B (same workflow, fresh upstream main 201790e; the only difference is format_conversion.py):

  • PR head (passing run): text tokenizer rows=24 system_prompt_kept=True last_turn_trained=True. Processor tokenizer: same result. PASS: 24 Alpaca rows, system prompt and every turn kept, 10 passed.
  • format_conversion.py reverted to main (expected-failing run): text tokenizer rows=8 system_prompt_kept=False last_turn_trained=False. Processor tokenizer: same result. FAIL: expected 24 Alpaca rows with the system prompt and every turn for 8 conversations x 3 turns, 9 failed, 1 passed.

Studio UI, before/after. Real Studio on an NVIDIA L4 (Chromium 1440×900). Each side trained unsloth/Qwen2.5-0.5B-Instruct with LoRA, 1 epoch, batch 1, on the same local file: 8 conversations, each with a system prompt and 3 turns. Target format was Alpaca.

  • main 128659085b: run completed, total_steps 8, final_step 8, 8 rows tokenized. The History card shows Steps: 8/8.
  • PR 7f8339c9a5: run completed, total_steps 24, final_step 24, 24 rows tokenized. The History card shows Steps: 24/24.

Neither side changes the frontend, so both use the same build. Each side served its own backend checkout.

PR 11053 Train history before/after

Conclusion: on main, Alpaca target format dropped the system prompt and every turn after the first. This PR trains on all 24 replies, and it now also handles processor tokenizers and structured content. Codex approved 7f8339c with no open items.

Fork CI (full official workflows, fresh upstream main 201790e + this PR): 14/15 workflows passed. The only red is Backend CI → tests/test_formatter_fixed_point.py, which flags tests/studio/test_wsl_shortcut_script_is_valid_powershell.py (not touched here). It fails identically on main 201790e without this PR (PR run, main run), so it predates this change.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this hits format_conversion.py where the Alpaca conversion keeps only the first user and assistant message and always leaves input empty, so the system prompt and later turns never reach training. Will get this reviewed.

@danielhanchen danielhanchen self-assigned this Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Reviewed e430d2edc (merge base 89862daec, format_conversion.py unchanged on main since). Malicious scan clean. Searched 5331 PRs across unsloth and unsloth-zoo for overlap: none, so this is the only fix in flight for it.

Verdict: issue REAL | PR as submitted: CORRECT | merge: YES. Two follow-ups below, neither blocking.

The bug, reproduced on main

I wrote a probe independent of your tests and ran it against both trees so a bug in the tests could not hide a bug in the code. 8 conversations, system prompt plus 3 turns each:

Fixture main this PR
ShareGPT conversations 8 rows, first turn only, input empty 24 rows, system prompt and every turn
Standard messages 8 rows, same loss 24 rows
Content as [{"type":"text",...}] 1 row whose instruction is the literal [{'type': 'text', 'text': 'Q1-1'}] 3 rows of plain text
None / [] conversation in the column TypeError: 'NoneType' object is not iterable, conversion dies handled, no orphan rows
9 combinations of num_proc 1/2/4 x batch_size 1/2/1000, mixed 0/1/2/7-row conversations crashes on all 9 22 rows, byte-identical on all 9

Two of those are fixes you did not claim in the description. Main does not just drop turns on a structured-content dataset, it trains on the stringified dict; and a chat column containing a null conversation crashes the conversion outright on main.

I also checked the layout against studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx:835-863. The Python is a faithful port of the TypeScript export: same \n\n system accumulation, same context.join("\n"), same inputParts.join("\n\n"), same skip-when-no-pending-user. Good call keeping those consistent.

Tests and lint

  • tests/test_chatml_to_alpaca.py: 10 passed on head. With only format_conversion.py reverted to main, 9 failed / 1 passed. Your "fails on main" claim verified locally, not just from the CI links.
  • tests/test_chatml_to_alpaca.py plus test_training_streaming.py, test_alpaca_blank_cells.py, test_dataset_map_num_proc.py, test_third_party_progress_bars.py: 110 passed, 1 skipped.
  • Broader dataset/format/chat/token selection: 2161 passed, 70 failed. All 70 are in test_rag_upload_formats.py, test_chat_generation_supervisor.py, test_chat_generation_run_lease.py, test_hub_write_ambient_token.py and test_chat_generation_run_account_sweep.py, and the identical 70 fail on untouched main. Pre-existing, none of them yours.
  • tests/python/test_studio_import_no_torch.py: 29 passed. ruff 0.6.9: clean.

Real training run, B200, unsloth/Qwen2.5-0.5B-Instruct LoRA, 1 epoch, batch 1, max_seq_length 2048

Loss columns are not comparable across arms, by design: the arms train on genuinely different data. What matters is that the extra rows reach the trainer and nothing diverges.

Arm Rows Steps Peak mem Tokens/s Losses (1st,2nd,3rd..last2) Grad norms
main, 8 convos x 3 turns 8 8 1.17 GB 59.8 3.098, 3.017, 1.741 .. 0.471, 0.367 15.73, 15.41, 16.507 .. 3.35, 3.263
PR, 8 convos x 3 turns 24 24 1.17 GB 271.4 2.694, 2.679, 1.874 .. 0.112, 0.114 13.082, 13.299, 7.552 .. 1.806, 1.635
main, 4 convos x 40 turns 4 4 1.21 GB 159.6 1.132, 1.13, 0.674, 0.674, 0.556 4.963, 5.044, 5.011, 5.011, 11.5
PR, 4 convos x 40 turns 160 160 2.11 GB 8807.9 0.124, 0.124, 0.12 .. 0.017, 0.003 0.497, 0.5, 0.481 .. 0.159, 0.02

3x the rows on the short dataset, both arms complete, no NaN. remove_columns is doing real work here, not cosmetics: a batched map that changes row count fails on a length mismatch without it, and nothing on this path reads the dropped columns (dataset_utils.py:615 sets chat_column = None, and _format_alpaca at chat_templates.py:276-291 reads only the three).

Two follow-ups, neither blocking

1. Eval rows leak into training inputs. split_dataset_for_evaluation (core/training/eval_dataset.py:29) calls train_test_split with shuffle on the already-expanded dataset, so turns of one conversation scatter across both splits, and a later turn carries the earlier answers verbatim in input. With 20 conversations x 3 turns (60 rows, 44 train / 16 eval) I measured 8 of the 16 eval answers appearing word for word inside a training row's input. This is new: on main input was always empty, so it could not happen. It does not corrupt training, but it makes the eval loss Studio reports optimistic. Splitting before expansion, or grouping by conversation, would fix it. Fine as a separate PR.

2. A zero-row streaming conversion raises an error with no reason in it. Zero-row conversions are newly possible (a conversation with only tool roles, or assistant-only). For a streaming dataset the next(iter(result)) probe then raises StopIteration, which except Exception catches and reports as:

ValueError: Streaming ChatML-to-Alpaca conversion failed on the first row:

Empty after the colon, because StopIteration carries no message. Main returned 4 garbage rows instead. Catching StopIteration separately and saying that no conversation produced a usable user/assistant pair would be clearer. One line. The non-streaming twin silently yields a 0-row dataset for the same input.

Smaller notes, no action needed

  • Images are dropped silently: _content_text skips non-text parts and remove_columns now also removes the image column. The path is reachable (a text model plus an image-bearing chat dataset, since dataset_utils.py:806 branches on the model not the data). Still a clear improvement, since main put the stringified [{'type': 'image', ...}] into instruction. The "Multimodal dataset detected" warning is discarded by the hardcoded "warnings": [] at dataset_utils.py:611-621, which predates this PR.
  • input grows with the full prefix, so long conversations get long. Measured on the 40-turn arm above: max row 5780 tokens, and 104 of 160 rows silently right-truncated at 2048. Inherent to this layout and matching the export, so I would not change it. Worth knowing that with "Train on completions" on, such a dataset can now hit the >30% dropped-samples error at trainer.py:4368; that setting is off by default and its message already points at max_seq_length.
  • n_rows = len(dataset) at dataset_utils.py:1018 is read before conversion and reused in the progress text at line 1050, and the dataset preview reports raw rows, so the count shown will not match the steps the user gets. Cosmetic.
  • bound_dataset_rows caps conversations before formatting (trainer.py:3061), so a max_steps run now tokenizes more rows than the cap intends. Not a correctness issue.
  • remove_columns=dataset.column_names or ... would pass a dict to map for a DatasetDict. Every training path names a split first so I could not reach it; sibling code guards for it explicitly (dataset_bounds.py:349, dataset_none_detect.py:484-501). Main fails on the same input too, just with a different message.
  • The column_names or list(next(iter(dataset), {})) fallback pulls a row eagerly for an untyped IterableDataset. Instrumented generator: starts 2 -> 3, rows read 3 -> 4.

What I did not prove

Windows and macOS (pure Python with no platform-specific paths, so I judged the org CI sufficient); real remote streaming datasets, only local IterableDataset; and any dataset large enough for the quadratic input growth to matter at scale, since my largest was 200 turns.

@danielhanchen

Copy link
Copy Markdown
Member

Simulation: #11053 | issue: REAL | PR as submitted: DEFECTIVE, 0 fixed by me (1 silent-drop + 3 export divergences reported, none blocking) | merge: YES

Head e430d2edc, merge base 89862daec. This is the "what else changed" pass, separate from the earlier review. It found four things that pass did not.

issue what the user hits today what they get after the PR reproduced on main fixed on branch verdict
Alpaca target format drops the system prompt and every turn after the first 8 conversations of system + 3 turns train as 8 rows, input empty, turns 2 and 3 never seen; training completes with no warning 24 rows, system prompt in input, every reply trained rows=8 system_prompt_kept=False, and a real LoRA run reports total_steps 8 rows=24 system_prompt_kept=True, same run reports total_steps 24 REAL

The inverse question: is the path identical for everyone else

438 cells, every role value (7 aliases, system, unknown, empty string, wrong case, explicit None, absent key, unhashable) crossed with every content shape (plain, empty, None, absent, number, NaN, one/two text parts, image part, mixed parts, empty text part, list of bare strings, empty list, part without a type), each in three positions.

classification cells
identical alpaca triple 400
same row count, different triple 34
fewer rows than main 3
more rows than main (the fix) 1
new crash 0

Provably identical, not merely probably: the 400 are byte-equal on the (instruction, input, output) triple. The 34 are all either the intended system-prompt and multi-turn change, or main emitting garbage that the branch cleans up (main produced ('', '', None) for a leading orphan assistant; the branch produces ('Q', '', 'A')). The 3 fewer-row cells are conversations whose only user turn had empty or absent content: main emitted a row with a null instruction, the branch drops it. That is a defensible improvement, not a loss.

No bare except is added. The one newly reachable broad handler is the pre-existing except Exception around the streaming first-row probe, which zero-row conversions now reach (reported in the earlier pass).

The PR cites the TypeScript export as its rationale; I ran it

studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx:835-863 copied verbatim into node and driven with the same 8 fixtures as the Python converter.

fixture TS export main PR head
canonical system + 3 turns 3 rows 1 row 3 rows, identical strings match
leading orphan assistant 1 1 1 match
system message midway 2 1 2 match
trailing user, single pair 1, 1 1, 1 1, 1 match
consecutive assistants [('Q','','hello')] [('Q','','hello')] [('Q','','hello\n\nA')] diverges
consecutive users [('Q','','A')] [('hello','','A')] [('hello\n\nQ','','A')] diverges
empty user between two replies 2 rows, second with an empty instruction 1 row [('REAL-QUESTION','','REAL-ANSWER\n\nORPHANED-ANSWER')] diverges

The happy path matches the export exactly, which is the claim that mattered. The divergence is the new consecutive-same-role merge, which the export does not do: it takes the last user message and skips an assistant with no pending user. The third row is the sharp one. An empty user turn is dropped before pairing, so the two assistant replies become adjacent and merge, and the training target REAL-ANSWER\n\nORPHANED-ANSWER is a string that appears nowhere in the source data. Main omitted the second reply; the branch fabricates a combined one.

test_unpaired_empty_and_unknown_turns_are_skipped pins this merge ("A\n\nA again"), so it is deliberate, but the test conflates two genuinely consecutive assistant messages with two replies separated by a dropped empty turn.

Silent total loss on OpenAI-shaped content parts

_content_text accepts only part["type"] == "text". The same codebase already has _monitor_content_text at studio/backend/routes/inference.py:5959, which accepts text, input_text and output_text. Measured:

part type rows out
text 1
input_text 0
output_text 0
image_url 0

A dataset in OpenAI Responses shape converts to nothing at all, silently. Reusing the existing helper's type list is a one-line change. This is the one finding I would call a defect in the new code's own terms rather than an edge case.

Negative controls: can the PR's tests fail

Nine mutations of the PR's own source, each run against tests/test_chatml_to_alpaca.py. All nine killed, so no guard is untested.

mutation result killed by
_content_text ignores list parts KILLED 2 tests
no consecutive-role merge KILLED test_unpaired_empty_and_unknown_turns_are_skipped
drop remove_columns KILLED 9 tests
system prompt left out of input KILLED 8 tests
emit only the first reply KILLED 8 tests
context joined with a blank line KILLED 8 tests
remove the or [] null-conversation guard KILLED 1 test
remove the empty-content skip KILLED 1 test
rename the User: / Assistant: prefixes KILLED 8 tests

No vacuous pass found: nothing ran as root, no test was skipped for an absent dependency, and every assertion compares a value rather than presence.

Dependency corners

datasets is pinned >=3.4.1,!=4.0.*,!=4.1.0,<4.4.0. One subprocess per cell, isolated venv per version, Dataset.map and IterableDataset.map signatures probed from the installed package rather than assumed.

datasets base rows (mat / stream / np2) head rows remove_columns in both map signatures verdict
3.4.1 floor 2 / 1 / 8 6 / 3 / 24 yes pass
3.6.0 installed 2 / 1 / 8 6 / 3 / 24 yes pass
4.3.0 ceiling 2 / 1 / 8 6 / 3 / 24 yes pass
5.0.1 outside the pin 2 / 1 / 8 6 / 3 / 24 yes pass

8 cells, 8 resolved, 0 drift. num_proc=2 output was row-identical to num_proc=1 in every cell.

Harness fault to declare: my first matrix run reported ModuleNotFoundError: No module named 'utils' on the non-streaming cells. That was my stub missing the lazily imported utils.hardware, not the PR. Fixed and re-run before any of the numbers above were read.

Cross-platform, both arms

staging_ci.py cross-platform, counts read from run logs.

runner base arm head arm verdict
ubuntu-latest 9 failed, 8 passed 17 passed, 22 skipped PASS
ubuntu-24.04-arm 9 failed, 8 passed 17 passed, 22 skipped PASS
macos-15 (Apple Silicon) 9 failed, 8 passed 17 passed, 22 skipped PASS
windows-latest 9 failed, 8 passed 17 passed, 22 skipped PASS
windows-11-arm install failed install failed, identically NOT RESOLVABLE

Not VOID: the base arm shows the defect on all four resolvable platforms and the head arm is green on all four. windows-11-arm fails at pip install on both arms because sqlite-vec==0.1.9 publishes no win-arm64 wheel; that is the runner, not the PR, and it answers nothing either way.

This matters more than it looks: num_proc=2 uses fork on Linux and spawn on macOS and Windows, and _convert now closes over a dict. test_parallel_conversion_keeps_every_reply_in_order ran and passed on macOS and Windows, so the closure pickles. The 22 skips are all in test_studio_import_no_torch.py (venv-building tests); all 10 conversion tests ran on every platform. The generated workflow has escape hatches that downgrade dependency-absence failures to green, and they did not fire here, which the red base arm proves.

Cost

5 repeats per cell, same seed and data order. The first iteration of each cell includes Arrow fingerprint warmup and is the stated noise band (a 4.3 to 4.6 s outlier on both arms).

shape base median head median rows base to head
1000 conversations x 3 turns 11.4 ms (spread 4274 ms, first-iteration warmup) 12.3 ms (spread 4541 ms, same warmup) 1000 to 3000
100 conversations x 20 turns 6.5 ms (spread 0.5 ms) 10.4 ms (spread 4.2 ms) 100 to 2000

1.6x the wall time for 20x the rows. Conversion cost is not a concern. The cost that is real is downstream: on a 4 x 40-turn dataset the branch produced 160 rows with a longest row of 5780 tokens and 104 of 160 silently right-truncated at max_seq_length 2048, against 4 untruncated rows on main.

Blast radius

  • _content_text is the only new module-level symbol. Grep across unsloth, unsloth_zoo, studio/backend and studio/frontend: no collision. _monitor_content_text in routes/inference.py is a distinct name in a distinct module, and is the duplicate-logic finding above rather than a conflict.
  • roles, turns, system, context are function-local.
  • utils/datasets/__init__.py is untouched, so the exported surface is unchanged.
  • Full studio backend dataset/format/chat/token selection: 2161 passed, 70 failed on head; the identical 70 fail on untouched main, in test_rag_upload_formats.py, test_chat_generation_supervisor.py, test_chat_generation_run_lease.py, test_hub_write_ambient_token.py and test_chat_generation_run_account_sweep.py. Pre-existing, named, not touched.

Adversarial pass: a different question

The first pass asked what the change does to the data. This one asked what it does to a user who had already converted the dataset before updating, since datasets caches map results by fingerprint and a stale hit would silently keep the 8-row conversion.

No finding. Same source dataset and cache directory, run base then head then base again: fingerprints 6ca657a254ec171a (8 rows), ea4c2f21f9df0da0 (24 rows), 6ca657a254ec171a (8 rows). The closure change alters the fingerprint, so the cache invalidates correctly and the result is deterministic in both directions. What would have changed my mind: a shared fingerprint across arms, which would have meant an updating user silently keeping the old conversion.

What I could not prove

  • No real Studio UI walk in this pass; the before and after screenshots in the PR are the author's, not reproduced by me.
  • windows-11-arm is unanswered on both arms (sqlite-vec has no win-arm64 wheel), so the ARM64 Windows path is untested, not passing.
  • No remote streaming dataset; all IterableDataset work was local, so network-backed restartability of the next(iter(dataset), {}) fallback is unverified.
  • Largest conversation tested was 200 turns; the quadratic input growth is characterised, not stress-tested at dataset scale.
  • Checkpoint resume across the change (a run started on main at total_steps 8 resumed after updating, when the dataset now yields 24) was not exercised.
  • The unhashable-role and bare-string-list content shapes are unreachable through a real Dataset, since Arrow rejects them first on both arms; they are classified not resolvable rather than passing.

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: e430d2edce

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 16, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 16, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
@danielhanchen
danielhanchen merged commit dc0a7db into unslothai:main Sep 16, 2026
43 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…at (unslothai#11053)

* Studio: keep every turn when converting chat datasets to Alpaca

* Studio: read structured message content when converting chats to Alpaca

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants