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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix Studio MLX VLM resized image layout (#6019)
Long Yixing8e2a983f5822
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex b6ec057231c..0a3b1f20193 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -1074,7 +1074,74 @@ def _mlx_vlm_max_resized_size(width: int, height: int, target: int) -> tuple[intreturn new_w, new_h-def _resize_mlx_vlm_image(image, resize):+_MLX_VLM_RESIZED_IMAGE_LAYOUT_CACHE = {}+++def _mlx_vlm_resized_image_layout(processor = None) -> str | None:+ """Return the numpy image layout expected after Studio-side VLM resizing."""+ image_processor = getattr(processor, "image_processor", None)+ if image_processor is None:+ return None+ cls = image_processor.__class__+ key = (getattr(cls, "__module__", ""), getattr(cls, "__qualname__", cls.__name__))+ if key in _MLX_VLM_RESIZED_IMAGE_LAYOUT_CACHE:+ return _MLX_VLM_RESIZED_IMAGE_LAYOUT_CACHE[key]+ copied_image_processor = _copy_mlx_vlm_image_processor(image_processor)+ layout = (+ _probe_mlx_vlm_numpy_image_layout(copied_image_processor)+ if copied_image_processor is not None+ else None+ )+ _MLX_VLM_RESIZED_IMAGE_LAYOUT_CACHE[key] = layout+ return layout+++def _copy_mlx_vlm_image_processor(image_processor):+ import copy+ try:+ return copy.deepcopy(image_processor)+ except Exception:+ try:+ return copy.copy(image_processor)+ except Exception:+ return None+++def _probe_mlx_vlm_numpy_image_layout(image_processor) -> str | None:+ try:+ import numpy as np+ except ImportError:+ return None++ def _accepts(candidate) -> bool:+ try:+ image_processor(images = [candidate])+ return True+ except TypeError:+ try:+ image_processor([candidate])+ return True+ except Exception:+ return False+ except Exception:+ return False++ # Use an asymmetric image so CHW-vs-HWC mistakes are visible to processors+ # that skip conversion for 3D numpy arrays.+ hwc = np.zeros((64, 96, 3), dtype = np.uint8)+ chw = np.ascontiguousarray(hwc.transpose(2, 0, 1))+ if _accepts(hwc):+ return None+ if _accepts(chw):+ return "chw"+ return None+++def _resize_mlx_vlm_image(+ image,+ resize,+ image_layout = None,+):if resize is None:return imagetry:@@ -1092,16 +1159,27 @@ def _resize_mlx_vlm_image(image, resize):# On resize, hand mlx-vlm a writable RGB ndarray so its PIL-path# square-resize is skipped and HF processors don't warn on non-writable# views. resize=None above keeps the original PIL.- return np.array(image, copy = True)+ array = np.array(image, copy = True)+ if image_layout == "chw":+ return np.ascontiguousarray(array.transpose(2, 0, 1))+ return array-def _resize_mlx_vlm_images(value, resize):+def _resize_mlx_vlm_images(+ value,+ resize,+ image_layout = None,+):if isinstance(value, list):- return [_resize_mlx_vlm_image(image, resize) for image in value]- return _resize_mlx_vlm_image(value, resize)+ return [_resize_mlx_vlm_image(image, resize, image_layout = image_layout) for image in value]+ return _resize_mlx_vlm_image(value, resize, image_layout = image_layout)-def _adapt_for_mlx_vlm(items, resize = None):+def _adapt_for_mlx_vlm(+ items,+ resize = None,+ image_layout = None,+):"""Adapt GPU-path VLM dataset output for mlx-vlm.The GPU path embeds PIL images in message content as@@ -1121,7 +1199,13 @@ def _adapt_for_mlx_vlm(items, resize = None):if isinstance(part, dict) and part.get("type") == "image":img = part.get("image")if img is not None:- images.append(_resize_mlx_vlm_image(img, resize))+ images.append(+ _resize_mlx_vlm_image(+ img,+ resize,+ image_layout = image_layout,+ )+ )new_content.append({"type": "image"})else:new_content.append(part)@@ -1132,9 +1216,17 @@ def _adapt_for_mlx_vlm(items, resize = None):if images:out["image"] = images[0] if len(images) == 1 else imageselif "image" in item:- out["image"] = _resize_mlx_vlm_images(item["image"], resize)+ out["image"] = _resize_mlx_vlm_images(+ item["image"],+ resize,+ image_layout = image_layout,+ )elif "images" in item:- out["images"] = _resize_mlx_vlm_images(item["images"], resize)+ out["images"] = _resize_mlx_vlm_images(+ item["images"],+ resize,+ image_layout = image_layout,+ )adapted.append(out)return adapted@@ -1322,7 +1414,6 @@ def _run_mlx_training(event_queue, stop_queue, config):"status",status_message = f"MLX vision image resize: {vision_image_size} (max dimension)",)-# ── 2. Apply LoRA / full FT ──# gradient_checkpointing stays a string ("mlx"/"unsloth"/"none"/etc.);# get_peft_model and MLXTrainer both accept and handle strings.@@ -1447,9 +1538,15 @@ def _run_mlx_training(event_queue, stop_queue, config):progress_callback = _fmt_progress,)if vlm_info.get("success"):+ vision_image_layout = (+ _mlx_vlm_resized_image_layout(tokenizer)+ if vision_image_size is not None+ else None+ )dataset = _adapt_for_mlx_vlm(vlm_info["dataset"],resize = vision_image_size,+ image_layout = vision_image_layout,)else:errors = vlm_info.get("errors", [])@@ -1463,9 +1560,15 @@ def _run_mlx_training(event_queue, stop_queue, config):dataset_name = hf_dataset or "local",)if ev_info.get("success"):+ vision_image_layout = (+ _mlx_vlm_resized_image_layout(tokenizer)+ if vision_image_size is not None+ else None+ )eval_dataset = _adapt_for_mlx_vlm(ev_info["dataset"],resize = vision_image_size,+ image_layout = vision_image_layout,)elif format_type:diff --git a/studio/backend/tests/test_mlx_training_worker_config.py b/studio/backend/tests/test_mlx_training_worker_config.pyindex 811971ec368..44020314678 100644--- a/studio/backend/tests/test_mlx_training_worker_config.py+++ b/studio/backend/tests/test_mlx_training_worker_config.py@@ -63,6 +63,10 @@ _worker = _load_worker_module()_normalize_mlx_studio_optimizer = _worker._normalize_mlx_studio_optimizer_normalize_mlx_studio_scheduler = _worker._normalize_mlx_studio_scheduler_mlx_vlm_max_resized_size = _worker._mlx_vlm_max_resized_size+_mlx_vlm_resized_image_layout = _worker._mlx_vlm_resized_image_layout+_copy_mlx_vlm_image_processor = _worker._copy_mlx_vlm_image_processor+_resize_mlx_vlm_image = _worker._resize_mlx_vlm_image+_adapt_for_mlx_vlm = _worker._adapt_for_mlx_vlmdef test_mlx_studio_optimizer_aliases_are_explicit():@@ -90,3 +94,123 @@ def test_mlx_vlm_resize_uses_max_dimension_like_torch_trainer():# Half-pixel cases must match the Torch collator (not banker's round).assert _mlx_vlm_max_resized_size(333, 1000, 500) == (167, 500)assert _mlx_vlm_max_resized_size(1000, 333, 500) == (500, 167)+++def test_mlx_vlm_resize_keeps_default_numpy_layout_hwc():+ Image = pytest.importorskip("PIL.Image")+ image = Image.new("RGB", (320, 200), color = (10, 20, 30))++ resized = _resize_mlx_vlm_image(image, 128)++ assert resized.shape == (80, 128, 3)+ assert resized.flags.c_contiguous+++def test_mlx_vlm_resize_uses_requested_chw_numpy_layout():+ Image = pytest.importorskip("PIL.Image")+ image = Image.new("RGB", (320, 200), color = (10, 20, 30))++ resized = _resize_mlx_vlm_image(image, 128, image_layout = "chw")++ assert resized.shape == (3, 80, 128)+ assert resized.flags.c_contiguous+++def test_mlx_vlm_resized_image_layout_probes_processor_contract():+ class ChwOnlyImageProcessor:+ def __call__(self, images = None):+ image = images[0]+ if image.shape[0] == 3:+ return {"pixel_values": image}+ raise ValueError("expected CHW")++ class HwcImageProcessor:+ def __call__(self, images = None):+ image = images[0]+ if image.shape[-1] == 3:+ return {"pixel_values": image}+ raise ValueError("expected HWC")++ assert (+ _mlx_vlm_resized_image_layout(+ types.SimpleNamespace(image_processor = ChwOnlyImageProcessor())+ )+ == "chw"+ )+ assert (+ _mlx_vlm_resized_image_layout(types.SimpleNamespace(image_processor = HwcImageProcessor()))+ is None+ )+++def test_mlx_vlm_layout_probe_copies_image_processor():+ class StatefulImageProcessor:+ def __init__(self):+ self.calls = 0++ def __call__(self, images = None):+ self.calls += 1+ image = images[0]+ if image.shape[0] == 3:+ return {"pixel_values": image}+ raise ValueError("expected CHW")++ image_processor = StatefulImageProcessor()++ layout = _mlx_vlm_resized_image_layout(types.SimpleNamespace(image_processor = image_processor))++ assert layout == "chw"+ assert image_processor.calls == 0+++def test_mlx_vlm_image_processor_copy_refuses_uncopyable_processors():+ class UncopyableImageProcessor:+ def __copy__(self):+ raise RuntimeError("no copy")++ def __deepcopy__(self, _memo):+ raise RuntimeError("no deepcopy")++ image_processor = UncopyableImageProcessor()++ assert _copy_mlx_vlm_image_processor(image_processor) is None+++def test_mlx_vlm_layout_probe_skips_uncopyable_processors():+ class UncopyableImageProcessor:+ def __copy__(self):+ raise RuntimeError("no copy")++ def __deepcopy__(self, _memo):+ raise RuntimeError("no deepcopy")++ def __call__(self, images = None):+ raise AssertionError("live processor should not be probed")++ assert (+ _mlx_vlm_resized_image_layout(+ types.SimpleNamespace(image_processor = UncopyableImageProcessor())+ )+ is None+ )+++def test_mlx_vlm_adapter_applies_chw_layout_to_message_images():+ Image = pytest.importorskip("PIL.Image")+ image = Image.new("RGB", (320, 200), color = (10, 20, 30))+ item = {+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "image", "image": image},+ {"type": "text", "text": "Describe it."},+ ],+ }+ ]+ }++ adapted = _adapt_for_mlx_vlm([item], resize = 128, image_layout = "chw")++ assert adapted[0]["image"].shape == (3, 80, 128)+ assert adapted[0]["messages"][0]["content"][0] == {"type": "image"}