Skip to content

Vision notebooks: convert each batch in the collator instead of building a list of decoded images - #427

Open
HamedMP wants to merge 3 commits into
unslothai:mainfrom
HamedMP:vision-notebooks-lazy-formatting
Open

HamedMP wants to merge 3 commits into
unslothai:mainfrom
HamedMP:vision-notebooks-lazy-formatting

Conversation

@HamedMP

@HamedMP HamedMP commented Nov 13, 2026 •

Copy link
Copy Markdown

Fixes #426

Problem

The vision notebooks build converted_dataset = [convert_to_conversation(sample) for sample in dataset] before training. Reading sample["image"] decodes the image, so the list keeps a decoded PIL image for every row in RAM for the whole run. On unsloth/LaTeX_OCR (68,686 rows, about 336 MB of Arrow) that is about 2.5 GB of decoded pixels and about 4.7 GB of RSS (measured on 400 rows and scaled up).

Fix

UnslothVisionDataCollator already accepts formatting_func (unsloth_zoo 2024.12.3 and later) and applies it per batch. In each affected notebook:

  • the trainer gets train_dataset = dataset and UnslothVisionDataCollator(model, tokenizer, formatting_func = convert_to_conversation);
  • the list-building cell becomes converted_example = convert_to_conversation(dataset[0]), and the demo cell shows converted_example. The cell count stays the same, so update_all_notebooks.py keeps restoring the saved outputs, and the displayed output is unchanged;
  • the markdown before it explains why the dataset isn't converted up front.

Files:

  • original_template/: Gemma3_(4B)-Vision, Gemma3N_(4B)-Vision, Gemma4_(12B)Vision, Llama3.2(11B)-Vision, Ministral_3_VL_(3B)Vision, Qwen2_VL(7B)-Vision, Qwen2.5_VL_(7B)-Vision, Qwen3_VL_(8B)-Vision. These were regenerated into nb/, nb/Kaggle-* and python_scripts/ with python update_all_notebooks.py.
  • Hand-maintained nb/ notebooks (in DONT_UPDATE_EXCEPTIONS), edited directly: Gemma4_(26B_A4B)/(31B)/(E2B)/(E4B)-Vision, LFM2.5_VL_(1.6B)-Vision, Qwen3_5_(0_8B)/(2B)/(4B)_Vision.
  • The 16 nb/AMD-* copies, edited the same way, with their python_scripts/ mirrors regenerated by convert_notebook_to_script. I didn't commit a full --amd run, because it also rewrites about 40 AMD notebooks this change doesn't touch, adds 12 new ones, and appends an extra ! to the training markdown of the edited ones.
  • The generator run also touched README.md, scripts/model_created_at.csv and the Openenv_wordle_grpo / Kaggle-Qwen3.8 GRPO notebooks the same way it does on a clean main (the HF popularity lookup failed from my machine). Those are not in the commit.

The 88 changed files contain only these hunks. DeepSeek-OCR, PaddleOCR, ERNIE-VL and Muse Glimmer use their own collators and are not changed.

Testing

  • Batch equivalence on CPU with unsloth_zoo main (2026.11.4). For 48 unsloth/LaTeX_OCR rows in batches of 2, the collator on the old list and the collator on the dataset with formatting_func produced byte-identical tensors in 24 of 24 batches. I checked this with the processors of Qwen2.5-VL, Qwen3-VL-8B, gemma-3-4b-it, Llama-3.2-11B-Vision-Instruct and gemma-4-E2B-it. The model was a stand-in carrying only the checkpoint config, which is all the collator reads.

  • test_notebook_json_validity.py, test_python_scripts_regen_parity.py, test_fsdp2_scripts_mirror.py, test_live_names_bound_only_in_dead_code.py, test_saving_cell_names_a_bound_object.py, test_notebook_api_drift.py, test_notebook_amd_install_parity.py, test_amd_source_is_nb_for_hand_maintained.py, test_notebook_pin_consistency.py: 4830 passed, 27 skipped, the same as on main.

  • Every changed python_scripts/*.py parses.

  • GPU run: nb/Qwen3_VL_(8B)-Vision.ipynb from this branch on a free Colab T4, run as-is. The trainer reported Num examples = 68,686, and all 30 steps completed in 5.6 minutes. Training loss went from 1.25 at step 1 to between 0.04 and 0.13 over steps 23 to 30. Peak reserved GPU memory was 8.08 GB. System RAM leveled off at 5.5 of 12.7 GB for the whole run, including the model load. I did not run the unchanged notebook on Colab for a side-by-side RAM figure; the 4.7 GB estimate above comes from the CPU measurement.

One path difference: the trainer now sees a first row with an image key, so Unsloth's back-ported _is_vision_dataset is True where the messages-only list gave False. Dataset preparation is skipped either way, because the notebooks set skip_prepare_dataset = True, and the Colab run above goes through this path.

Takeover check (2026-11-23)

I measured old (list) vs new (formatting_func) on a Colab L4 with unsloth/Qwen3-VL-2B-Instruct-unsloth-bnb-4bit on the full unsloth/LaTeX_OCR train split (68,686 rows), 30 steps, the notebook's SFTConfig, seed 3407. Each arm ran in its own process, 4 runs per arm across two VMs (unsloth 2026.11.9, transformers 5.17.0, TRL 1.15.0). The first run on each VM is a cold start, so it is left out of the timing.

old: list of converted rows new: formatting_func
Building the train set 23.4 to 23.9 s 0.03 s
Host RSS after building it 5.77 GiB (+3.94 over the loaded model) 1.83 GiB (+0.00)
Host RSS after 30 steps 6.68 GiB 2.74 GiB
Peak RSS (VmHWM) 6.68 GiB 3.93 GiB (reached during model load)
Median step time, 3 warm runs 1.749 / 1.750 / 1.765 s 1.733 / 1.766 / 1.801 s
Num examples 68,686 68,686
  • Step time is the same within noise. The difference in medians is 0.016 s, and the spread across new runs is 0.07 s.
  • Loss parity: steps 1 and 2 match exactly across all runs on the same VM. Over 30 steps the largest old vs new loss gap is 0.012. Runs of the same arm differ by up to 0.006 (old) and 0.009 (new), so the gap is GPU nondeterminism.
  • Batches are byte-identical. On CPU with the Qwen3-VL processor, 120 of 120 batches of 2 (a seeded random draw of rows, like the trainer's sampler) gave identical input_ids, attention_mask, labels, pixel_values and image_grid_thw from the old list and from the dataset with formatting_func.

The changed notebooks also run end to end on a free Colab T4 with their own install cell (transformers 4.57.6, trl==0.22.2), with max_steps capped at 10: Gemma3_(4B)-Vision, Qwen2.5_VL_(7B)-Vision and Qwen3_5_(2B)Vision pass every cell; Llama3.2(11B)-Vision trains, runs inference, saves and reloads the LoRA (its last cell is all if False: and prints nothing). All of them have remove_unused_columns = False and skip_prepare_dataset = True, so the image / text columns reach the collator on both TRL corners. No cell in the changed files still refers to converted_dataset.

On the AMD copies: I ran update_all_notebooks.py --amd on this branch and on main. For the 16 AMD notebooks you edited, the generator output matches your hand edits exactly. The only line --amd still changes there is the reinforcement learning! to learning!! flip, and it does the same on main. That flip comes from the generator: the DPOTrainer rewrite keeps the template's own !, and the !! collapse runs before it. I will fix that in a separate PR, since it touches about 160 unrelated files.

I pushed two commits on top of yours:

  • merged main in, which now has the Intel XPU notebooks;
  • regenerated with --intel, so nb/Intel-Llama3.2_(11B)-Vision.ipynb and its python_scripts/ mirror get the same change. Without this it would be the only Llama 3.2 Vision copy still building the list.

…ing a list of decoded images

The vision notebooks ran `converted_dataset = [convert_to_conversation(sample) for sample in dataset]`
before training. Reading `sample["image"]` decodes the image, so the list holds every decoded
PIL image for the whole run. On unsloth/LaTeX_OCR (68,686 rows, about 336 MB of Arrow) that is
about 2.5 GB of decoded pixels and roughly 4.7 GB of RSS, extrapolated from 400 rows.

UnslothVisionDataCollator already takes `formatting_func` (unsloth_zoo 2024.12.3 and later) and
applies it per batch, so pass the dataset itself and `formatting_func = convert_to_conversation`.
Batches are unchanged. The demo cell now converts one example instead of indexing the list.

Edited the 8 templates in original_template/ and the 8 hand-maintained nb/ notebooks, then
regenerated with update_all_notebooks.py. The AMD- copies were edited the same way and their
python_scripts/ mirrors regenerated with convert_notebook_to_script, because a full --amd run
also rewrites unrelated AMD notebooks on main.
@HamedMP

HamedMP commented Nov 13, 2026

Copy link
Copy Markdown
Author

Side-by-side on a free Colab T4, Qwen3_VL_(8B)-Vision.ipynb run as-is from main and from this branch (30 steps, LaTeX_OCR, 68,686 examples):

main this PR
System RAM (Colab resources panel) 9.2 / 12.7 GB 5.5 / 12.7 GB
Peak reserved GPU memory 8.08 GB 8.08 GB
Train runtime 322.7 s 336.2 s
Loss at steps 1 / 10 / 20 / 30 1.2519 / 0.5044 / 0.1129 / 0.1273 1.2519 / 0.3894 / 0.0966 / 0.1308

The loss curves agree to about 1e-4 for the first 7 steps. They drift apart around steps 9–13, which I'd attribute to GPU nondeterminism since the batches are identical on CPU, and agree within about 0.02 over the last 10 steps. The extra ~13 s comes from converting each batch in the collator instead of once up front.

@danielhanchen danielhanchen self-assigned this Nov 23, 2026
…matting_func

The Intel XPU notebooks landed on main after this branch was cut. Rebased onto
main and ran update_all_notebooks.py --intel, which carries the same collator
change into nb/Intel-Llama3.2_(11B)-Vision.ipynb and its python_scripts mirror.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T08:47:34.932299Z 85f49a1 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 85f49a1c3f

ℹ️ 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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Vision notebooks keep every decoded image in RAM; use UnslothVisionDataCollator(formatting_func=...)

2 participants