Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix image inputs in Clef training and prediction (#13471)

Lee Jacksona00ef5f56e42
diff --git a/tests/test_decision_images.py b/tests/test_decision_images.py
new file mode 100644
index 00000000000..aea4e8df945
--- /dev/null
+++ b/tests/test_decision_images.py
@@ -0,0 +1,189 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+from types import SimpleNamespace
+
+import pytest
+import torch
+from PIL import Image
+
+import unsloth
+from transformers import AutoConfig, AutoModelForImageTextToText, AutoProcessor
+from unsloth.models import decision
+from unsloth.models.clef import JointSchemaHead, collate_records, encode_record
+
+
[email protected](scope = "module")
+def processor():
+ return AutoProcessor.from_pretrained("Qwen/Qwen3.5-0.8B")
+
+
+def row():
+ return {
+ "state": "Frames are ordered oldest to newest.",
+ "images": [Image.new("RGB", (56, 56), color) for color in ("red", "green", "blue")],
+ "questions": {
+ "motion": {
+ "type": "choice",
+ "criteria": {"left": "moves left", "right": "moves right"},
+ },
+ "visible": {"type": "noul", "instructions": "Is an object visible?"},
+ },
+ "gold": {"motion": "right", "visible": True},
+ }
+
+
+def build(rows, processor):
+ model = SimpleNamespace(is_clef = True, decision_config = {"max_len": 2048})
+ return decision.FastDecisionModel.build_dataset(rows, processor, model)
+
+
+def test_image_records_batch_and_permute_without_losing_order(processor, row):
+ variants = [
+ {**row, "images": []},
+ {**row, "images": row["images"][:1]},
+ row,
+ {**row, "images": row["images"][::-1]},
+ ]
+ items, report = build(variants, processor)
+ assert report["skipped"] == 0
+ encoded = [
+ encode_record(processor.tokenizer, r, max_length = 2048, processor = processor)
+ for r in variants
+ ]
+ for item, record in zip(items, encoded):
+ assert item["input_ids"] == list(record.input_ids)
+ assert "pixel_values" not in (item["record"].media or {})
+ expected = collate_records(encoded, processor.tokenizer.pad_token_id, torch.device("cpu"))
+ collator = decision.ClefDataCollator(processor.tokenizer.pad_token_id, tokenizer = processor)
+ batch = collator(items)
+ for key in ("input_ids", "attention_mask"):
+ torch.testing.assert_close(batch[key], expected[key])
+ for key, value in expected["media"].items():
+ torch.testing.assert_close(batch[key], value)
+ assert not torch.equal(
+ collator(items[2:3])["pixel_values"], collator(items[3:4])["pixel_values"]
+ )
+ shuffled = decision.ClefDataCollator(
+ processor.tokenizer.pad_token_id,
+ tokenizer = processor,
+ max_len = 2048,
+ permute_fields = True,
+ seed = 1,
+ )(items[2:3])
+ assert [q.question_id for q in shuffled["records"][0].questions] == ["visible", "motion"]
+ by_name = dict(zip(row["questions"], items[2]["targets"]))
+ for target, question in zip(shuffled["target"], shuffled["records"][0].questions):
+ assert target[: len(question.option_ids)].tolist() == by_name[question.question_id]
+ torch.testing.assert_close(shuffled["pixel_values"], collator(items[2:3])["pixel_values"])
+
+
+def test_image_columns_read_like_mlx(processor, row):
+ import io
+
+ image = row["images"][0]
+ buffer = io.BytesIO()
+ image.save(buffer, format = "PNG")
+ forms = [[image], image, [{"bytes": buffer.getvalue(), "path": None}]]
+ items, report = build([{**row, "images": form} for form in forms], processor)
+ assert report["skipped"] == 0
+ collator = decision.ClefDataCollator(processor.tokenizer.pad_token_id, tokenizer = processor)
+ first = collator(items[:1])
+ for item in items[1:]:
+ assert item["input_ids"] == items[0]["input_ids"]
+ torch.testing.assert_close(collator([item])["pixel_values"], first["pixel_values"])
+
+
+def test_image_rows_require_a_processor(processor, row):
+ items, report = build([row], processor.tokenizer)
+ assert items == []
+ assert report["skipped"] == len(row["questions"])
+ assert "require a processor" in report["reason"]
+
+
+def model():
+ config = AutoConfig.from_pretrained("Qwen/Qwen3.5-0.8B")
+ text = config.text_config
+ text.hidden_size, text.intermediate_size, text.num_hidden_layers = 64, 128, 2
+ text.num_attention_heads, text.num_key_value_heads, text.head_dim = 4, 2, 16
+ text.layer_types = ["full_attention"] * 2
+ text.rope_parameters = {
+ **text.rope_parameters,
+ "partial_rotary_factor": 1.0,
+ "mrope_section": [2, 3, 3],
+ }
+ vision = config.vision_config
+ vision.depth, vision.hidden_size, vision.intermediate_size = 1, 32, 64
+ vision.num_heads, vision.out_hidden_size = 4, 64
+ torch.manual_seed(13461)
+ backbone = AutoModelForImageTextToText.from_config(config, attn_implementation = "eager")
+ head = JointSchemaHead(
+ hidden_size = 64,
+ width = 32,
+ routing_layers = 1,
+ layers = 1,
+ heads = 4,
+ feedforward = 64,
+ )
+ model = decision.ClefDecisionModel(backbone, head).eval()
+ model.decision_config = {"max_len": 2048, "temperature": [1.0] * 3}
+ return model
+
+
+def test_images_reach_forward_gradients_prediction_and_evaluation(processor, row, model):
+ items, _ = build([row], processor)
+ batch = decision.ClefDataCollator(processor.tokenizer.pad_token_id, tokenizer = processor)(items)
+ calls = []
+ hook = model.encoder.model.visual.register_forward_hook(lambda *args: calls.append(1))
+ try:
+ batch["pixel_values"] = batch["pixel_values"].detach().requires_grad_(True)
+ logits, _ = model(**batch)
+ loss = decision._decision_loss(logits, batch["target"], batch["marker_mask"])
+ loss.backward()
+ assert calls and torch.isfinite(loss)
+ assert batch["pixel_values"].grad.abs().sum() > 0
+ assert any(
+ p.grad is not None and p.grad.abs().sum() > 0
+ for p in model.encoder.model.visual.parameters()
+ )
+ changed, _ = model(**{**batch, "pixel_values": torch.zeros_like(batch["pixel_values"])})
+ assert not torch.allclose(logits, changed, atol = 1e-5)
+ calls.clear()
+ answers = decision.FastDecisionModel.predict(
+ model,
+ processor,
+ row["state"],
+ row["questions"],
+ images = row["images"],
+ )
+ assert calls and set(answers) == set(row["questions"])
+ calls.clear()
+ evaluated, _ = decision._clef_logits(
+ model, items, processor.tokenizer.pad_token_id, processor = processor
+ )
+ assert calls and len(evaluated) == len(row["questions"])
+ for expected, actual in zip(logits.detach(), evaluated):
+ torch.testing.assert_close(expected, actual)
+ finally:
+ hook.remove()
+
+
+def test_text_only_prediction_keeps_language_path(processor, row, model):
+ calls = []
+ hook = model.encoder.model.visual.register_forward_hook(lambda *args: calls.append(1))
+ try:
+ answers = decision.FastDecisionModel.predict(
+ model, processor, row["state"], row["questions"]
+ )
+ tokenizer_only = decision.FastDecisionModel.predict(
+ model,
+ processor.tokenizer,
+ row["state"],
+ row["questions"],
+ )
+ assert answers == tokenizer_only
+ assert not calls
+ finally:
+ hook.remove()
diff --git a/tests/test_decision_model.py b/tests/test_decision_model.py
index 76da6f2f21f..55623f16ca2 100644
--- a/tests/test_decision_model.py
+++ b/tests/test_decision_model.py
@@ -1020,6 +1020,7 @@ def test_clef_metrics_score_in_the_runs_batch_size(monkeypatch):
items,
pad_token_id,
batch_size = 4,
+ processor = None,
):
seen.append(batch_size)
raise StopIteration
@@ -1463,7 +1464,12 @@ def test_a_clef_prompt_that_fits_exactly_is_not_truncated(monkeypatch):
# Serving (Studio's Decision API) and predict share this rule.
from unsloth.models import clef
- def encode(tokenizer, record, max_length):
+ def encode(
+ tokenizer,
+ record,
+ max_length,
+ processor = None,
+ ):
# The state needs `natural` tokens; anything over max_length is cut to fit.
return types.SimpleNamespace(input_ids = [0] * min(record["state"], max_length))
diff --git a/unsloth/models/_decision_common.py b/unsloth/models/_decision_common.py
index a952fed5b85..043bb4b3be5 100644
--- a/unsloth/models/_decision_common.py
+++ b/unsloth/models/_decision_common.py
@@ -28,6 +28,7 @@ __all__ = [
"_checkpoint_folder",
"_lm_subfolder",
"_parsed",
+ "_row_images",
"_internal",
"_option_keys",
"_label",
@@ -232,6 +233,34 @@ def _parsed(value):
return value
+def _row_images(row: dict) -> list:
+ # A row's "images": PIL images, data URLs, or the {"bytes": ..., "path": ...} an undecoded image column holds.
+ images = _parsed(row.get("images"))
+ if images is None:
+ return []
+ found = []
+ for image in images if isinstance(images, (list, tuple)) else [images]:
+ if isinstance(image, dict) and set(image) <= {"bytes", "path"}:
+ import io
+
+ from PIL import Image
+
+ data = image.get("bytes")
+ # A nullable image column holds an empty struct where a row has no image.
+ try:
+ image = (
+ Image.open(io.BytesIO(data) if data is not None else image["path"])
+ if data is not None or image.get("path")
+ else None
+ )
+ except Image.DecompressionBombError as exc:
+ # Not an OSError: without this one oversized image aborts the whole dataset.
+ raise ValueError(str(exc)) from None
+ if image is not None:
+ found.append(image)
+ return found
+
+
def _internal(question) -> dict:
if not isinstance(question, dict) or question.get("type") not in QUESTION_TYPES:
raise DecisionDataError("is not a valid question")
diff --git a/unsloth/models/decision.py b/unsloth/models/decision.py
index 178fd838d31..04f30bbc484 100644
--- a/unsloth/models/decision.py
+++ b/unsloth/models/decision.py
@@ -8,6 +8,7 @@ __all__ = [
import contextlib
import copy
+import dataclasses
import json
import math
import os
@@ -34,6 +35,7 @@ from ._decision_common import * # noqa: F401,F403
HEAD_LEARNING_RATE = 1e-4
# DecisionTrainer defaults for Clef; every key is also a DecisionTrainer argument.
CLEF_RECIPE = {}
+_PIXEL_KEYS = ("pixel_values", "pixel_values_videos")
_DECISION_CONFIG = "unsloth_decision_config.json"
# Copied byte for byte from the checkpoint a Clef fine-tune started from: Cloudflare's loader and
# license, and the tokenizer / processor files, which transformers would otherwise rewrite (a
@@ -234,6 +236,7 @@ class ClefDataCollator:
seed = 3407,
):
self.pad_token_id = pad_token_id
+ self.processor = tokenizer if hasattr(tokenizer, "tokenizer") else None
self.tokenizer, self.max_len = getattr(tokenizer, "tokenizer", tokenizer), max_len
self.permute_fields = permute_fields and tokenizer is not None
self.random = random.Random(seed)
@@ -248,8 +251,9 @@ class ClefDataCollator:
try:
record = encode_record(
self.tokenizer,
- {"state": item["source"]["state"], "questions": questions},
+ {**item["source"], "questions": questions},
max_length = self.max_len,
+ processor = self.processor,
)
except ValueError:
return item
@@ -261,18 +265,30 @@ class ClefDataCollator:
"targets": [item["targets"][i] for i in order],
}
+ def _with_pixels(self, item) -> dict:
+ from .._vendor.clef.joint_schema_model import _encode_media
+
+ record = item["record"]
+ if not record.media or any(key in record.media for key in _PIXEL_KEYS):
+ return item
+ _, media = _encode_media(self.processor, item["source"])
+ pixels = {key: media[key] for key in _PIXEL_KEYS if key in media}
+ return {**item, "record": dataclasses.replace(record, media = {**record.media, **pixels})}
+
def __call__(self, items: list) -> dict:
- from .clef import QUESTION_TYPES as CLEF_TYPES
+ from .clef import QUESTION_TYPES as CLEF_TYPES, collate_records
if self.permute_fields:
items = [self._permuted(item) if "source" in item else item for item in items]
- rows, length = len(items), max(len(item["input_ids"]) for item in items)
+ items = [self._with_pixels(item) for item in items]
+ inputs = collate_records(
+ [item["record"] for item in items], self.pad_token_id, torch.device("cpu")
+ )
targets = [target for item in items for target in item["targets"]]
options = max(len(target) for target in targets)
batch = {
- "input_ids": torch.full((rows, length), self.pad_token_id, dtype = torch.long),
- "attention_mask": torch.zeros((rows, length), dtype = torch.long),
- "records": [item["record"] for item in items],
+ **{key: value for key, value in inputs.items() if key != "media"},
+ **inputs["media"],
"marker_mask": torch.zeros((len(targets), options), dtype = torch.bool),
"target": torch.zeros((len(targets), options), dtype = torch.float32),
"ordinal": torch.tensor(
@@ -280,9 +296,6 @@ class ClefDataCollator:
dtype = torch.bool,
),
}
- for i, item in enumerate(items):
- batch["input_ids"][i, : len(item["input_ids"])] = torch.tensor(item["input_ids"])
- batch["attention_mask"][i, : len(item["input_ids"])] = 1
for i, target in enumerate(targets):
batch["marker_mask"][i, : len(target)] = True
batch["target"][i, : len(target)] = torch.tensor(target)
@@ -313,16 +326,25 @@ class ClefDecisionModel(torch.nn.Module):
head = None,
**kwargs,
):
+ from .._vendor.clef.joint_schema_model import MEDIA_BATCH_KEYS, MEDIA_TOKEN_KEYS
+
head = self.head if head is None else head
backbone = self._backbone()
# GPT-2 style models keep their decoder under base_model_prefix (.transformer), not .model.
text_model = getattr(backbone, "model", None) or backbone.base_model
- text_model = getattr(text_model, "language_model", text_model)
+ media = {
+ k: kwargs[k]
+ for k in (*MEDIA_BATCH_KEYS, *MEDIA_TOKEN_KEYS)
+ if kwargs.get(k) is not None
+ }
+ if not media:
+ text_model = getattr(text_model, "language_model", text_model)
hidden = text_model(
input_ids = input_ids,
attention_mask = attention_mask,
use_cache = False,
return_dict = True,
+ **media,
).last_hidden_state
logits = head(
hidden,
@@ -345,6 +367,7 @@ class ClefDecisionModel(torch.nn.Module):
def _clef_items(rows, tokenizer, max_len, validate, report, skip) -> list:
from .clef import QUESTION_TYPES as CLEF_TYPES, encode_record, question_options
+ processor = tokenizer if hasattr(tokenizer, "tokenizer") else None
tokenizer = getattr(tokenizer, "tokenizer", tokenizer)
items = []
for index, row in enumerate(rows):
@@ -374,14 +397,20 @@ def _clef_items(rows, tokenizer, max_len, validate, report, skip) -> list:
kept[str(name)], targets, labels = clef_question, targets + [target], labels + [label]
if not kept:
continue
+ source = {"state": state, "questions": kept}
try:
- record = encode_record(
- tokenizer, {"state": state, "questions": kept}, max_length = max_len
- )
- except (TypeError, ValueError) as exc:
+ images = _row_images(row)
+ if images:
+ source.update(images = images, media_kwargs = row.get("media_kwargs"))
+ record = encode_record(tokenizer, source, max_length = max_len, processor = processor)
+ except (TypeError, ValueError, OSError) as exc:
for name in kept:
skip(index, f"does not fit: {exc}", name)
continue
+ if record.media:
+ # ClefDataCollator makes the pixels again per batch: kept here they cost 24 MiB per 1024x1024 image.
+ media = {k: v for k, v in record.media.items() if k not in _PIXEL_KEYS}
+ record = dataclasses.replace(record, media = media)
items.append(
{
"input_ids": list(record.input_ids),
@@ -390,7 +419,7 @@ def _clef_items(rows, tokenizer, max_len, validate, report, skip) -> list:
"targets": targets,
"labels": labels,
"row": index,
- "source": {"state": state, "questions": kept},
+ "source": source,
}
)
return items
@@ -402,13 +431,16 @@ def _clef_logits(
items: list,
pad_token_id: int,
batch_size: int = 4,
+ processor = None,
) -> tuple:
# Per question logits plus one Laya-shaped item per question for the shared metrics.
from .clef import QUESTION_TYPES as CLEF_TYPES
device = next(model.parameters()).device
amp_dtype = _clef_amp_dtype(model, device)
- collate = ClefDataCollator(pad_token_id)
+ if not hasattr(processor, "tokenizer"):
+ processor = getattr(model, "_saved_temp_tokenizer", None)
+ collate = ClefDataCollator(pad_token_id, tokenizer = processor)
# Clef numbers question types noul, choice, score; Laya's metrics use choice, score, noul.
laya_type = {CLEF_TYPES[kind]: QUESTION_TYPES.index(kind) for kind in QUESTION_TYPES}
was_training = model.training
@@ -445,7 +477,7 @@ def _decision_logits(
pad_token_id = getattr(tokenizer, "tokenizer", tokenizer).pad_token_id
if getattr(model, "is_clef", False):
# A run that lowered its batch to fit a 9B / 27B backbone scores in that batch too.
- return _clef_logits(model, items, pad_token_id, batch_size or 4)
+ return _clef_logits(model, items, pad_token_id, batch_size or 4, tokenizer)
return _logits(model, items, pad_token_id), items
@@ -457,23 +489,33 @@ def _clef_decide(
questions: dict,
max_length = None,
predicted = False,
+ images = None,
) -> dict:
# One Decision API request over every question in one prefill, at served temperatures.
- from .clef import encode_record, systemone_answer
+ from .clef import collate_records, encode_record, systemone_answer
+ processor = tokenizer if hasattr(tokenizer, "tokenizer") else None
tokenizer = getattr(tokenizer, "tokenizer", tokenizer)
max_length = int(max_length or model.decision_config.get("max_len", CLEF_MAX_LEN))
encoded = encode_record(
- tokenizer, {"state": state, "questions": questions}, max_length = max_length
+ tokenizer,
+ {"state": state, "questions": questions, "images": images},
+ max_length = max_length,
+ processor = processor,
)
device = next(model.parameters()).device
amp_dtype = _clef_amp_dtype(model, device)
- ids = torch.tensor([encoded.input_ids], device = device)
+ batch = collate_records([encoded], tokenizer.pad_token_id, device)
was_training = model.training
model.eval()
try:
with torch.autocast(device.type, dtype = amp_dtype, enabled = amp_dtype is not None):
- logits, _ = model(input_ids = ids, attention_mask = torch.ones_like(ids), records = [encoded])
+ logits, _ = model(
+ input_ids = batch["input_ids"],
+ attention_mask = batch["attention_mask"],
+ records = batch["records"],
+ **batch["media"],
+ )
finally:
model.train(was_training)
rows = [
@@ -499,18 +541,35 @@ def _clef_decide(
return {
"answers": answers,
"input_tokens": len(encoded.input_ids),
- "truncated": _clef_truncated(tokenizer, state, questions, encoded, max_length),
+ "truncated": _clef_truncated(
+ tokenizer, state, questions, encoded, max_length, images = images, processor = processor
+ ),
}
-def _clef_truncated(tokenizer, state, questions, encoded, max_length) -> bool:
+def _clef_truncated(
+ tokenizer,
+ state,
+ questions,
+ encoded,
+ max_length,
+ images = None,
+ processor = None,
+) -> bool:
# One spare token tells a cut state from one that fits exactly.
if len(encoded.input_ids) < max_length:
return False
from .clef import encode_record
- record = {"state": state, "questions": questions}
- return len(encode_record(tokenizer, record, max_length = max_length + 1).input_ids) > max_length
+ record = {"state": state, "questions": questions, "images": images}
+ return (
+ len(
+ encode_record(
+ tokenizer, record, max_length = max_length + 1, processor = processor
+ ).input_ids
+ )
+ > max_length
+ )
def _laya_decide(
@@ -1701,11 +1760,19 @@ class FastDecisionModel:
)
@staticmethod
- def predict(model, tokenizer, state, questions: dict) -> dict:
+ def predict(
+ model,
+ tokenizer,
+ state,
+ questions: dict,
+ *,
+ images = None,
+ ) -> dict:
"""Answers one Decision API request: {name: answer} at the calibrated temperatures.
Each answer is the Decision API's (choice / confidence, score / legend, or noul) plus
"answer" (the option, True / False for noul, the level number for score) and
- "probabilities" over every option. Works for Laya, Clef and converted language models."""
+ "probabilities" over every option. Works for Laya, Clef and converted language models.
+ A Clef also reads ordered `images` when tokenizer is the processor from from_pretrained."""
if not isinstance(questions, dict) or not questions:
raise DecisionDataError("questions must be a non-empty dict of name to question")
state = _parsed(state)
@@ -1716,9 +1783,17 @@ class FastDecisionModel:
int(model.decision_config.get("max_len", CLEF_MAX_LEN)), CLEF_SERVE_MAX_LEN
)
return _clef_decide(
- model, tokenizer, state, questions, max_length = max_length, predicted = True
+ model,
+ tokenizer,
+ state,
+ questions,
+ max_length = max_length,
+ predicted = True,
+ images = _row_images({"images": images}),
)["answers"]
tokenizer = getattr(tokenizer, "tokenizer", tokenizer)
+ if images:
+ raise DecisionDataError("images require a Clef multimodal model and processor")
return _laya_decide(model, tokenizer, state, questions, predicted = True)["answers"]
@staticmethod
diff --git a/unsloth/models/decision_mlx.py b/unsloth/models/decision_mlx.py
index ecb950c9680..69cd854ae21 100644
--- a/unsloth/models/decision_mlx.py
+++ b/unsloth/models/decision_mlx.py
@@ -49,6 +49,7 @@ from unsloth._decision_common import (
_option_keys,
_parsed,
_predicted,
+ _row_images,
_served_lengths,
_served_temperatures,
_target,
@@ -57,34 +58,6 @@ from unsloth._decision_common import (
)
-def _row_images(row: dict) -> list:
- # A row's "images": PIL images, data URLs, or the {"bytes": ..., "path": ...} an undecoded image column holds.
- images = _parsed(row.get("images"))
- if images is None:
- return []
- found = []
- for image in images if isinstance(images, (list, tuple)) else [images]:
- if isinstance(image, dict) and set(image) <= {"bytes", "path"}:
- import io
-
- from PIL import Image
-
- data = image.get("bytes")
- # A nullable image column holds an empty struct where a row has no image.
- try:
- image = (
- Image.open(io.BytesIO(data) if data is not None else image["path"])
- if data is not None or image.get("path")
- else None
- )
- except Image.DecompressionBombError as exc:
- # Not an OSError: without this one oversized image aborts the whole dataset.
- raise ValueError(str(exc)) from None
- if image is not None:
- found.append(image)
- return found
-
-
def _decision_clef_items(rows, options: Callable, encode: Callable, validate, report, skip) -> list:
# One item per row. `options(question)` names a question's options in the head's order and
# `encode(state, questions, images)` returns the backend's tokenized fields, raising when they do not fit.