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 formatting_func race in UnslothVisionDataCollator without a lock (#7698)
FrMakeThisWorkF259ec3b22def
diff --git a/tests/test_video_path_validation.py b/tests/test_video_path_validation.pyindex cb101ead6c3..ab5d088adfa 100644--- a/tests/test_video_path_validation.py+++ b/tests/test_video_path_validation.py@@ -7,7 +7,9 @@ the full unsloth import chain (triton/CUDA kernels).import astimport osimport tempfile+import threadingimport warnings+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathimport pytest@@ -487,6 +489,10 @@ def real_collator_classes():)except Exception as exc: # noqa: BLE001 - skip on any import failurepytest.skip(f"full unsloth import unavailable: {exc!r}")+ # On Apple Silicon MLX, unsloth.trainer is a shim and this name is a+ # placeholder whose __call__ raises, not the zoo subclass under test.+ if not issubclass(UnslothVisionDataCollator, ZooBase):+ pytest.skip("MLX placeholder collator, not the torch subclass")return UnslothVisionDataCollator, ZooBase@@ -566,3 +572,62 @@ def test_real_collator_restores_formatting_func_when_super_raises(with pytest.raises(RuntimeError):collator([{"anything": 1}])assert collator.formatting_func is fmt+++def test_vision_collator_thread_safety(real_collator_classes, monkeypatch):+ """Concurrent callers must never see formatting_func blanked on the shared+ instance. Patches the zoo base, so the real trainer.py __call__ runs."""+ _, zoo_base = real_collator_classes++ num_threads, num_examples = 32, 3+ formatted, formatted_lock = [], threading.Lock()+ base_saw, base_saw_lock = [], threading.Lock()++ def formatter(example):+ with formatted_lock:+ formatted.append(example["tag"])+ return example++ leader_parked, release_leader = threading.Event(), threading.Event()+ first_entry, entered = threading.Lock(), []++ def fake_base(self, examples):+ with base_saw_lock:+ base_saw.append(self.formatting_func)+ park = False+ with first_entry:+ if not entered:+ entered.append(True)+ park = True+ if park:+ # Hold the window open: unsynchronised code lets every follower+ # read the temporary None and skip formatting entirely.+ leader_parked.set()+ release_leader.wait(10)+ return examples++ monkeypatch.setattr(zoo_base, "__call__", fake_base)+ collator = _make_real_collator(real_collator_classes, formatting_func = formatter)++ # Fresh examples per thread, so an in-place formatter races on collator+ # state rather than on shared user data.+ def work(thread_id):+ return collator([{"tag": (thread_id, i)} for i in range(num_examples)])++ try:+ with ThreadPoolExecutor(max_workers = num_threads) as executor:+ leader = executor.submit(work, 0)+ assert leader_parked.wait(10), "leader never reached the base collator"+ followers = [executor.submit(work, i) for i in range(1, num_threads)]+ release_leader.set()+ leader.result(timeout = 30)+ for future in followers:+ future.result(timeout = 30)+ finally:+ release_leader.set()++ expected = num_threads * num_examples+ assert len(formatted) == expected+ assert len(set(formatted)) == expected # each example formatted exactly once+ assert base_saw == [None] * num_threads+ assert collator.formatting_func is formatterdiff --git a/unsloth/trainer.py b/unsloth/trainer.pyindex 7b715e98144..764bfce7c2b 100644--- a/unsloth/trainer.py+++ b/unsloth/trainer.py@@ -12,6 +12,7 @@# See the License for the specific language governing permissions and# limitations under the License.+import copyimport loggingimport osimport psutil@@ -86,12 +87,12 @@ class UnslothVisionDataCollator(_UnslothVisionDataCollatorBase):if formatting_func is None:return super().__call__(examples)- # why: base __call__ would reapply formatting_func; applied above.- self.formatting_func = None- try:- return super().__call__(examples)- finally:- self.formatting_func = formatting_func+ # why: base __call__ would reapply formatting_func; applied above. A+ # per-call shallow view shares every other attribute by reference, so a+ # concurrent caller can never observe formatting_func blanked on self.+ view = copy.copy(self)+ view.formatting_func = None+ return super(UnslothVisionDataCollator, view).__call__(examples)_AUTO_PADDING_FREE_ENV_DISABLED = os.environ.get(