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
Trim comments in unsloth, unsloth_cli and tests (#12968)
Daniel Han63ae318e5415
diff --git a/unsloth/__init__.py b/unsloth/__init__.pyindex 8c8e15f8573..5d749ca9099 100644--- a/unsloth/__init__.py+++ b/unsloth/__init__.py@@ -13,9 +13,7 @@ import os, importlib.util, platform, sysos.environ["UNSLOTH_IS_PRESENT"] = "1"-# Opt into ROCm AOTriton kernels PyTorch still gates as experimental; it keeps its own hardware-# checks and reads this lazily at the SDPA probe, so no torch import here. `setdefault` preserves-# an explicit override, including "0".+# Opt into ROCm AOTriton kernels torch still gates as experimental; setdefault keeps an explicit "0".os.environ.setdefault("TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL", "1")# Before anything can create a process group: c10d and NCCL read these at init.@@ -42,13 +40,10 @@ try:except Exception:pass-# Transformers 4.x imports TensorFlow / Flax merely because they are installed (processing_utils-# -> image_transforms); it reads these variables once at its own import, so they have to land-# first. An explicit opt-in still wins, and 5.x ignores all of this.+# Transformers 4.x imports TF/Flax if installed and reads these vars once at import, so set them first; explicit opt-ins still win.if "transformers" not in sys.modules:_TRUE = {"1", "ON", "YES", "TRUE"}- # Overwrite, not `setdefault`: unset means AUTO ("enable if installed"), but an already-imported- # backend is in use, so opting it out breaks a `from_tf` load.+ # Overwrite, not setdefault (unset means AUTO); skip backends already imported, since opting one out breaks from_tf loads.for _var, _modules, _opt_ins in (("USE_TF", ("tensorflow",), ("USE_TF", "FORCE_TF_AVAILABLE")),("USE_FLAX", ("flax", "jax"), ("USE_FLAX",)),@@ -60,9 +55,7 @@ if "transformers" not in sys.modules:os.environ[_var] = "0"del _TRUE, _var, _modules, _opt_inselse:- # Transformers derives _tf_available / _flax_available from find_spec alone, and being in- # sys.modules does not mean its body ran, so clear the cached flags AND write the variables:- # inert once read, decisive in that window, unconditional since waiting deadlocks.+ # Transformers derives flags from find_spec: clear cached flags AND set the vars unconditionally, since waiting for the body deadlocks._TRUE = {"1", "ON", "YES", "TRUE"}_import_utils = sys.modules.get("transformers.utils.import_utils")for _var, _flag, _const, _modules, _opt_ins, _cached in (@@ -87,14 +80,12 @@ else:continueif any(os.environ.get(_v, "").upper() in _TRUE for _v in _opt_ins):continue- # An opt-in can be consumed and then restored, so read the snapshot Transformers used. Env USE_FLAX- # lands in the constant USE_JAX.+ # An opt-in can be consumed then restored, so read the snapshot Transformers used; env USE_FLAX lands in the constant USE_JAX.if any(str(getattr(_import_utils, _v, "")).upper() in _TRUE for _v in _cached):continueos.environ[_var] = "0"try:- # import_utils copies the env into USE_TF / USE_JAX (lines 102-104) and derives the flags at- # 264 / 355, so mid-body only the constant works.+ # Mid-body, import_utils already copied the env into USE_TF / USE_JAX; only the constant works.if hasattr(_import_utils, _const):setattr(_import_utils, _const, "0")# Absent on 5.x, and a module proxy can refuse the write.@@ -104,13 +95,11 @@ else:passdel _TRUE, _import_utils, _var, _flag, _const, _modules, _opt_ins, _cached-# Relax Metal's context-store timeout before MLX modules can initialize Metal; an explicit user-# value stays authoritative.+# Relax Metal's context-store timeout before MLX initializes Metal; an explicit user value wins.if platform.system() == "Darwin" and platform.machine() == "arm64":os.environ.setdefault("AGX_RELAX_CDM_CTXSTORE_TIMEOUT", "1")-# Legacy Windows consoles (cp1252) cannot encode Unsloth's emoji/box-drawing glyphs and crash with-# UnicodeEncodeError; errors="replace" guarantees no crash on an unencodable glyph.+# Legacy cp1252 consoles cannot encode Unsloth's glyphs; errors="replace" avoids UnicodeEncodeError.# ── Windows console UTF-8 safety ─────────────────────────────────────────────if platform.system() == "Windows":import sys as _sys@@ -150,8 +139,7 @@ def _bytes_to_gb(value):def _is_mlx_available():- # Transitional import barrier: keep non-Apple-Silicon imports from touching unsloth_zoo until- # unsloth_zoo.mlx is import-safe on GPU hosts.+ # Transitional: keep non-Apple-Silicon imports off unsloth_zoo until unsloth_zoo.mlx is GPU-host safe.if (os.environ.get("UNSLOTH_FORCE_GPU_PATH", "0") == "1"or platform.system() != "Darwin"@@ -170,20 +158,15 @@ def _is_mlx_available():_IS_MLX = _is_mlx_available()if _IS_MLX:- # Same reason again, and first because it is what turns the bare AttributeError into a- # diagnosis: this branch imports transformers below, so an Apple Silicon host carrying the- # old-torch/new-transformers pair hits #8933 here exactly as a CUDA host does, and- # _gpu_init.py, the only other installation site, is never reached on this path. The- # triton shim check is deliberately NOT mirrored: it is a CUDA/ROCm/XPU driver shim and- # there is no triton on this platform to inspect.+ # Run this first: it turns the bare AttributeError into a diagnosis, and _gpu_init.py never runs on this path.+ # The triton shim check is deliberately not mirrored: it is a CUDA/ROCm/XPU driver shim and Apple Silicon has no triton.try:from .import_fixes import patch_torch_missing_attribute_error as _patch_torch_attr_patch_torch_attr()del _patch_torch_attrexcept Exception:pass- # _gpu_init does this on the GPU path and the MLX path never reaches it, so torchao 0.18 + torch <- # 2.10 dies on `ScalingType`.+ # _gpu_init does this on the GPU path only; torchao 0.18 + torch < 2.10 dies on ScalingType.try:from .import_fixes import fix_torchao_torch_symbol_skew as _fix_torchao_fix_torchao()@@ -217,17 +200,14 @@ if _IS_MLX:except Exception:passtry:- # Same reason: this branch imports transformers itself further down, so a --no-deps floor miss would- # surface here with the same wrong remedy.+ # This branch imports transformers itself, so a --no-deps floor miss surfaces here with the same wrong remedy.from .import_fixes import check_transformers_dependency_versions as _check_tf_deps_check_tf_deps()del _check_tf_depsexcept Exception:passtry:- # Same reason: remote code reaches transformers' get_class_in_module on this platform- # too, and the wrap is what restores the image helpers transformers 5 stopped- # re-exporting. Costs nothing until a checkpoint's own modeling file is loaded.+ # Restores image helpers transformers 5 stopped re-exporting for remote code; lazy.from .import_fixes import (fix_transformers5_image_processing_reexports as _fix_image_reexports,)@@ -236,8 +216,7 @@ if _IS_MLX:except Exception:passtry:- # Same reason: 4.x remote configs are built here too, and their validators read plain RoPE- # as rope_scaling None. is_torch_fx_available is left to unsloth_zoo.mlx.loader.+ # 4.x remote configs are built here too, and read plain RoPE as rope_scaling None.from .import_fixes import (fix_transformers_remote_rope_scaling_none as _fix_remote_rope_scaling,)@@ -272,8 +251,7 @@ if _IS_MLX:"Unsloth: MLX support requires `unsloth-zoo` with MLX modules. ""Reinstall with `pip install unsloth-zoo` or rerun install.sh.") from _e- # An older unsloth-zoo satisfies `import unsloth_zoo` but lacks the mlx.trainer / mlx.loader- # submodules; surface an install hint instead of a raw ImportError.+ # An older unsloth-zoo lacks mlx.trainer / mlx.loader; surface an install hint instead.try:from unsloth_zoo.mlx.trainer import (MLXTrainer,@@ -296,8 +274,7 @@ if _IS_MLX:import types as _typesimport warnings as _warnings- # unsloth_zoo is a different distribution, pinned >=, so borrowing its number reported neither the- # installed core nor the latest zoo. `_version` imports nothing, so this stays torch-free.+ # Own version, not unsloth_zoo's; `_version` imports nothing, so this stays torch-free.from ._version import __version__DEVICE_TYPE = "mlx"@@ -352,8 +329,7 @@ if _IS_MLX:target = kwargs.get("device", device)if _is_mlx_cuda_device_target(target):return self- # device given by keyword: do not also pass the positional None, or the original raises "multiple- # values for 'device'".+ # Device given by keyword: also passing positional None raises "multiple values for 'device'".if "device" in kwargs:return original_to(self, *args, **kwargs)return original_to(self, device, *args, **kwargs)@@ -364,8 +340,7 @@ if _IS_MLX:_patch_mlx_batch_encoding_to_cuda()- # Load raw_text helpers without executing dataprep/__init__.py, which imports synthetic.py -> torch- # and would defeat the torch-free MLX path.+ # Load raw_text without dataprep/__init__.py, which imports torch via synthetic.py.from pathlib import Path as _Path_raw_text_path = _Path(__file__).resolve().parent / "dataprep" / "raw_text.py"@@ -490,11 +465,8 @@ if _IS_MLX:if clear_cache is None and hasattr(mx, "metal"):clear_cache = getattr(mx.metal, "clear_cache", None)if callable(clear_cache):- # MLX pins buffers a live command buffer reads, but not a dropped output array.- # Generation runs on its own streams, which a no-argument mx.synchronize()- # would not wait on. Best effort: this helper is torch.cuda.empty_cache() on- # MLX, called from finally arms on any thread, and synchronizing a stream- # bound on another thread raises (mlx 0.31.2 made encoders thread local).+ # Generation runs on its own streams, which a bare mx.synchronize() does not wait on. Best effort:+ # synchronizing a stream bound on another thread raises (mlx 0.31.2 thread-local encoders)._synchronize = getattr(mx, "synchronize", None)if callable(_synchronize):_drained = []@@ -1568,8 +1540,7 @@ if _IS_MLX:def train_on_responses_only(*args, **kwargs):"""Mask non-response tokens through the shared zoo dataset helper."""- # Prefer the chat_templates export, which bounds the zoo's dataset.map() worker count (#2693); it is- # None on a torch-free host, so fall back and let the zoo raise its own ImportError.+ # Prefer the chat_templates export, which bounds the zoo's map() workers; it is None without torch.from .chat_templates import train_on_responses_only as _train_on_responses_onlyif _train_on_responses_only is None:@@ -1593,8 +1564,7 @@ if _IS_MLX:safe_exports.append(name)return safe_exports- # Stub the trl trainers with no MLX implementation yet, so an unmigrated GRPO/DPO/ORPO notebook- # fails with a clear message instead of crashing deep inside the real torch/CUDA trainer.+ # Stub trl trainers with no MLX implementation so they fail clearly instead of deep in torch code._MLX_UNSUPPORTED_TRL_TRAINERS = ("GRPOTrainer","DPOTrainer",@@ -1648,13 +1618,9 @@ if _IS_MLX:_trl.SFTTrainer = UnslothTrainer_trl.SFTConfig = _MLXSFTConfig- # Only retarget trainers the installed trl actually exposes; idempotent, so re-importing unsloth is a no-op.- # Names come from trl's __all__ and already materialized attrs, never a getattr probe: resolving- # one triggers trl's lazy trainer import and pulls torch, breaking `import unsloth` on MLX.+ # Names come from trl's __all__, never a getattr probe: that triggers trl's lazy import and pulls torch._trl_exports = set(getattr(_trl, "__all__", ()) or ())- # Stub every non-SFT trainer trl exposes, not just a fixed list, so newer trainers (RLOOTrainer, ...)- # also fail with a clear MLX message instead of importing the real torch trainer. Names come from- # __all__ so we never resolve them (that would trigger trl's lazy import and pull torch).+ # Stub every non-SFT trl trainer so newer ones fail clearly too; take names from __all__ and never resolve them, since that pulls torch._unsupported = set(_MLX_UNSUPPORTED_TRL_TRAINERS) | {_n for _n in _trl_exports if _n.endswith("Trainer") and _n != "SFTTrainer"}@@ -1773,9 +1739,7 @@ else:pass-# A `pip install --target` / PYTHONPATH layout makes dill pickle whole modules by value, and every-# training path here builds a datasets.Dataset, which fingerprints through dill. See-# import_fixes.fix_dill_module_by_value_pickling.+# A pip --target / PYTHONPATH layout makes dill pickle modules by value, breaking dataset fingerprints.try:from .import_fixes import fix_dill_module_by_value_pickling as _fix_dill_fix_dill()diff --git a/unsloth/_compressed_quantize.py b/unsloth/_compressed_quantize.pyindex cdb2a698548..0141a9b34e2 100644--- a/unsloth/_compressed_quantize.py+++ b/unsloth/_compressed_quantize.py@@ -62,8 +62,7 @@ def compressed_ignore_patterns(config):class name) match."""ignore = ["lm_head"]- # Skip the same modules RedHatAI/NVIDIA skip for the Qwen3.5 / Qwen3-Next family: their shapes are- # not divisible by the grouped-scheme group_size and would error. No-ops elsewhere.+ # Skip what RedHatAI/NVIDIA skip for Qwen3.5 / Qwen3-Next: shapes not divisible by group_size.ignore += ["re:.*\\.linear_attn\\..*", "re:.*\\.visual\\..*", "re:.*mtp.*"]if _is_moe(config):# Keep MoE routing layers unquantized: the router gate and (Qwen) shared-expert gate.@@ -92,8 +91,7 @@ def _build_calibration_dataset(tokenizer, kind, value, num_samples, max_seq_lengexcept (ValueError, KeyError):from datasets import get_dataset_split_namestry:- # Resolve the first split name so only num_samples rows are fetched, instead of materializing the- # whole dataset just to take a small slice.+ # Resolve the split name so only num_samples rows are fetched.split = get_dataset_split_names(value)[0]ds = load_dataset(value, split = f"{split}[:{num_samples}]")except Exception:@@ -132,16 +130,14 @@ def _build_calibration_dataset(tokenizer, kind, value, num_samples, max_seq_lengcols = set(ds.column_names)if "input_ids" in cols:- # Drop non-model-input columns (e.g. a leftover 'messages' list) so llm-compressor's collator does- # not try to batch them.+ # Drop non-input columns so llm-compressor's collator does not try to batch them.keep = {"input_ids", "attention_mask", "labels", "position_ids"}extra = [c for c in ds.column_names if c not in keep]if extra:ds = ds.remove_columns(extra)return dsif "messages" in cols:- # Base / non-chat tokenizers have no chat template, and apply_chat_template would raise, so- # concatenate message contents instead.+ # Base tokenizers have no chat template, so concatenate message contents instead.has_chat_template = bool(getattr(_tok, "chat_template", None))def _content_to_text(content):@@ -229,8 +225,7 @@ def main():from llmcompressor import oneshotfrom llmcompressor.modifiers.quantization import QuantizationModifier- # Import the VLM auto-class only when needed: some transformers versions lack it, and the text path- # must not fail over a newer class.+ # Some transformers versions lack the VLM auto-class; the text path must not fail over it.if args.is_vlm:from transformers import AutoProcessortry:@@ -251,8 +246,7 @@ def main():model.eval()# A tokenizer may be absent if the caller saved it separately; only calibration needs one.try:- # The tokenizer/processor has its own trust flag: consent for one component must not let the other's- # custom code run.+ # The tokenizer/processor has its own trust flag: consent for one component must not let the other's custom code run.tokenizer = auto_proc.from_pretrained(args.model, trust_remote_code = args.trust_remote_code_tokenizer)@@ -264,8 +258,7 @@ def main():)tokenizer = None- # MoE models: keep the router/gate unquantized and calibrate every expert even if the sample set- # does not route tokens to all of them.+ # MoE models keep the router/gate unquantized and calibrate every expert, even ones the samples never route to.config = getattr(model, "config", None)is_moe = _is_moe(config)ignore = compressed_ignore_patterns(config)@@ -282,9 +275,8 @@ def main():args.num_calibration_samples,args.max_seq_length,)- # The sequential pipeline onloads layer-by-layer, so a model that does not fit at once still- # calibrates; tracing works only because this runs in a clean process without Unsloth's attention- # patches. Fall back to the memory-hungry "basic" pipeline only if tracing fails.+ # Sequential pipeline onloads layer by layer; tracing works only in this clean process without+ # Unsloth's attention patches. Fall back to the memory-hungry basic pipeline if tracing fails.try:oneshot(model = model,@@ -301,8 +293,7 @@ def main():"retrying with the 'basic' pipeline (needs the full model to fit in memory).",flush = True,)- # Free the partially-processed model before loading a fresh copy so the fallback never holds two- # on GPU: llm-compressor keeps the model in a global session after a failed run.+ # llm-compressor keeps the model in a global session after a failure, so free it before reloading.import gc as _gcimport torch as _torchdiff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.pyindex 5292e5967fe..e31c3f88625 100644--- a/unsloth/_gpu_init.py+++ b/unsloth/_gpu_init.py@@ -75,19 +75,12 @@ try:except Exception:pass-# Before anything imports huggingface_hub (disable_broken_vllm, check_fbgemm_gpu_version and-# fix_huggingface_hub all reach it): the Hub freezes HF_HUB_DISABLE_XET at import time. Stdlib-# only, so it does not disturb the torch ordering the next comment describes.+# Before anything imports huggingface_hub, which freezes HF_HUB_DISABLE_XET at import time.fix_broken_hf_xet_wheel()-# Configure libdrm ids table path early so ROCm can resolve AMD GPU names. Stdlib only,-# and it must stay ahead of the first `import torch` in this file: it sets-# AMDGPU_ASIC_ID_TABLE_PATH, and a torch that has already brought up libdrm would not see-# the discovered table.+# Must precede the first `import torch`: it sets AMDGPU_ASIC_ID_TABLE_PATH, read when libdrm loads.configure_amdgpu_asic_id_table_path()-# Ahead of every fix below and of `import unsloth_zoo`, because those are what-# import transformers, and a transformers newer than this torch raises its bare-# AttributeError at the first one of them to reach it (#8933). It imports torch, which is-# why the ROCm table above comes first.+# Must precede the fixes below and `import unsloth_zoo`: they import transformers, which raises bare AttributeError if newer than torch.+# It imports torch, which is why the ROCm table above comes first.patch_torch_missing_attribute_error()# Must precede `import unsloth_zoo` below, which imports bnb on ROCm.fix_bitsandbytes_rocm_arch_detection()@@ -104,8 +97,7 @@ disable_broken_causal_conv1d()disable_broken_vllm()fix_message_factory_issue()fix_torch_check_is_size()-# The above fixes THIS process only; vLLM's model-architecture inspector is a subprocess that-# imports torchao itself and hits the same ImportError.+# The fixes above cover only this process; vLLM's architecture inspector is a subprocess that imports torchao and hits the same ImportError.propagate_torchao_fix_to_subprocesses()# Warn, do not raise: this only adds the correct remedy just before transformers prints its misleading one.check_transformers_dependency_versions()@@ -115,11 +107,8 @@ check_triton_py_ssize_t_clean()fix_triton_module_cache_python_key()check_fbgemm_gpu_version()torchvision_compatibility_check()-# Ahead of `import unsloth_zoo` below, deliberately not down with the other import fixes: unsloth_zoo's-# temporary_patches reach transformers.processing_utils, which imports transformers.audio_utils, which-# imports torchaudio, so a torchaudio that raises at extension init takes the whole unsloth import down at-# that `import unsloth_zoo` line, long before the late block would have neutralised it. Measured:-# Kaggle-Muse_Glimmer_(30B)-GRPO died at cell 4 with the guard present but not yet run.+# Before `import unsloth_zoo`: its patches import torchaudio via transformers, and a broken+# torchaudio would fail the whole import before the later fixes run.disable_torchaudio_if_cuda_mismatched()fix_diffusers_warnings()fix_huggingface_hub()@@ -142,8 +131,7 @@ del fix_diffusers_warningsdel fix_huggingface_hubdel fix_broken_hf_xet_wheel-# Unsloth patches these libraries at import time; if they are imported first the unoptimized-# versions run, risking OOM or slower training.+# If imported before Unsloth, the unpatched versions run, risking OOM or slower training.if already_imported:# stacklevel=2 points the warning at the user's import linewarnings.warn(@@ -166,10 +154,8 @@ del maybe_set_windows_rocm_bnb_version# Fixes https://github.com/unslothai/unsloth/issues/1266os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"-# `docker --gpus '"device=N"'` sets NVIDIA_VISIBLE_DEVICES but not-# CUDA_VISIBLE_DEVICES, so Inductor's compile-worker pool cannot enumerate the-# cgroup-pinned GPU ("Could not find an active GPU backend"). Pinned ids only, not-# "all"/"none"/"void"/"". Opt out with UNSLOTH_FORCE_SINGLE_COMPILE_WORKER=0.+# docker --gpus sets NVIDIA_VISIBLE_DEVICES but not CUDA_VISIBLE_DEVICES, so Inductor compile workers miss the pinned GPU.+# Only for pinned ids, not all/none/void/empty. Opt out with UNSLOTH_FORCE_SINGLE_COMPILE_WORKER=0._nvd = os.environ.get("NVIDIA_VISIBLE_DEVICES", "").strip().lower()_cgroup_pinned = _nvd not in ("", "all", "none", "void")if (@@ -295,13 +281,8 @@ if os.environ.get("UNSLOTH_FORCE_SINGLE_COMPILE_WORKER", "0") == "1":"determine_compile_threads",lambda: 1,)- # `import unsloth_zoo` above already ran temporary_patches, so its- # module-level options dicts are snapshots of the original count and- # replacing the function only reaches dicts built from here on. Those- # snapshots go to torch.compile as `options`, which Inductor applies as a- # config patch outranking both the env var and the value set above. Rewrite- # them IN PLACE: each dict is shared by identity with every zoo module- # re-exporting it and with the functools.partial in `torch_compile`.+ # Zoo's options dicts were snapshotted at import and outrank the env var in Inductor; rewrite them+ # in place, since they are shared by identity across modules and the torch_compile partial.for module in list(sys.modules.values()):name = getattr(module, "__name__", "")if name != "unsloth_zoo" and not name.startswith("unsloth_zoo."):@@ -415,9 +396,7 @@ from .import_fixes import (fix_transformers5_legacy_config_types()# Must run first: guards PretrainedConfig before vLLM defines its config classes.fix_transformers5_bare_annotation_configs()-# Probe-gated: no-ops unless this transformers really hands SDPA a query row that attends to-# nothing. Ordered here, before anything imports a model, so a plain transformers.generate in the-# same process is covered too (#9708).+# Probe-gated: no-op unless SDPA gets a query row that attends to nothing; runs before model imports so plain generate is covered.fix_transformers_fully_masked_rows()fix_transformers_flash_attention_mrope_packed_sequence()fix_transformers_chunked_mask_block_sequence_ids()@@ -441,9 +420,7 @@ fix_transformers_bnb_prequantized_save()# A run that loads no pre-quantized multimodal checkpoint never fails either way.check_transformers_prequantized_vlm_quant_state()del check_transformers_prequantized_vlm_quant_state-# Probe-gated: no-ops unless replacing config.rope_scaling on this transformers really loses the-# RoPE base frequency. Ordered here, before any config is built, so the object-style delegation-# retry in models/llama.py sees a config that kept its base (#2405).+# Probe-gated: no-op unless assigning config.rope_scaling drops the RoPE base; must run before configs exist so llama.py retry keeps it.fix_transformers_rope_scaling_drops_theta()fix_transformers_fp8_modulelist_experts()fix_transformers_fp8_unscaled_checkpoint_linears()@@ -454,9 +431,7 @@ fix_transformers_longcat_lsa_config()# Remote code written for 4.x reads plain RoPE as rope_scaling None and imports is_torch_fx_available.fix_transformers_remote_rope_scaling_none()fix_transformers_is_torch_fx_available()-# Probe-gated and lazy: only wraps get_class_in_module, so the siglip image-# modules are imported and patched when a checkpoint's own modeling file runs,-# not on every `import unsloth`.+# Probe-gated and lazy: only wraps get_class_in_module.fix_transformers5_image_processing_reexports()fix_transformers5_remote_code_model_api()fix_xformers_performance_issue()@@ -465,8 +440,7 @@ fix_xformers_performance_issue()fix_flash_attn_4_namespace_shadow()fix_vllm_aimv2_issue()fix_vllm_lora_tokenizer_module()-# torchao 0.18.0 moved nf4tensor; torchtune (via xcodec2) still imports the old path. Lazy alias, so-# it costs nothing unless asked for.+# torchao 0.18.0 moved nf4tensor; torchtune (via xcodec2) imports the old path. Lazy alias.fix_torchao_nf4tensor_move()fix_compressed_tensors_activation_quant_gradient()fix_torchao_safe_int_mm_repr_probe()@@ -513,8 +487,7 @@ patch_peft_shared_active_adapter()# After peft is importable, so the already-bound is_torchao_available in peft.tuners.lora.torchao is# replaced too, not just import_utils'.fix_peft_stale_torchao_import_error()-# Same reason, one layer on: peft.tuners.lora.model imported dispatch_torchao by value, so both-# copies have to be replaced, and both modules exist by now.+# peft.tuners.lora.model imported dispatch_torchao by value, so both copies must be replaced.fix_peft_torchao_missing_tensor_subclass()patch_accelerate_recursively_apply()@@ -575,9 +548,7 @@ del patch_accelerate_recursively_apply# Torch 2.4 has including_emulationif DEVICE_TYPE == "cuda" and not torch.cuda.is_available():- # UNSLOTH_ALLOW_CPU=1 keeps DEVICE_TYPE at "cuda" on a host with a CUDA-built torch and no usable- # device, so ask whether a device is present before asking what it can do: get_device_capability()- # would raise out of _lazy_init(). is_bf16_supported() is stubbed to match.+ # UNSLOTH_ALLOW_CPU=1 keeps DEVICE_TYPE "cuda" with no device; get_device_capability() would raise.SUPPORTS_BFLOAT16 = Falsetorch.cuda.is_bf16_supported = lambda *args, **kwargs: Falseelif DEVICE_TYPE == "cuda":@@ -646,13 +617,7 @@ if DEVICE_TYPE == "hip" and any(arch_lacks_buffer_ops(arch) for arch in hip_visiapply_gfx101x_triton_workaround()# For Gradio HF Spaces?-# if "SPACE_AUTHOR_NAME" not in os.environ and "SPACE_REPO_NAME" not in os.environ:-# `triton` is optional here, like bitsandbytes below. The PyPI `triton` project publishes no-# Windows wheel (Windows is served by the separate `triton-windows` package), so a CPU only-# Windows install has no `triton` at all, and an unconditional import here killed-# `import unsloth` with a bare ModuleNotFoundError from a line whose only job is to resolve-# `libcuda_dirs` on CUDA hosts. Everything below treats `triton is None` as "no Triton-# kernels", which is already the state of a CPU only install.+# triton is optional (no PyPI Windows wheel); code below treats triton None as no Triton kernels, and CPU-only installs must import.try:import tritonexcept Exception as _triton_import_exception:@@ -695,8 +660,7 @@ if DEVICE_TYPE == "cuda":try:import bitsandbytes as bnb- # Bind the submodule by name: a half-imported bitsandbytes leaves the parent without a `functional`- # attribute, which would otherwise be misreported below as a CUDA linking failure.+ # Bind the submodule by name: a half-imported bitsandbytes lacks functional, which would otherwise be misreported as a CUDA linking failure.import bitsandbytes.functional as bnb_functionalexcept:print(@@ -709,9 +673,7 @@ if DEVICE_TYPE == "cuda":libcuda_dirs()except:if not torch.cuda.is_available():- # UNSLOTH_ALLOW_CPU=1 on a driverless host: a missing libcuda is the expected state, not broken- # linkage, and repairing it would ldconfig the host's linker cache as root for a device that is- # not there.+ # Driverless UNSLOTH_ALLOW_CPU host: missing libcuda is expected; do not ldconfig as root.passelif hasattr(os, "geteuid") and os.geteuid() == 0:warnings.warn("Unsloth: Running `ldconfig /usr/lib64-nvidia` to link CUDA.")@@ -744,9 +706,7 @@ if DEVICE_TYPE == "cuda":importlib.reload(bnb)if triton is not None:importlib.reload(triton)- # Same degradation as the cuda branch above: no bnb means no 4bit, not a failed `import unsloth`.- # No triton either means there is nothing to re-resolve here, and the missing Triton was- # already reported above, so do not re-report it as a CUDA linking failure.+ # No bnb means no 4bit, not a failed import; missing Triton was already reported above.try:libcuda_dirs = lambda: Noneif triton is None:diff --git a/unsloth/dataprep/raw_text.py b/unsloth/dataprep/raw_text.pyindex 98193256b64..fb51243d81b 100644--- a/unsloth/dataprep/raw_text.py+++ b/unsloth/dataprep/raw_text.py@@ -92,8 +92,7 @@ class RawTextDataLoader:)all_chunks.extend(chunks)if not all_chunks:- # All files empty/whitespace: raise like load_from_file instead of create_causal_dataset([])- # returning a 0-row text-column dataset.+ # Raise like load_from_file instead of returning a 0-row dataset.raise ValueError("All files are empty or contain only whitespace")return self.create_causal_dataset(all_chunks)@@ -150,8 +149,7 @@ class RawTextDataLoader:f"stride ({stride}) must be smaller than chunk_size ({chunk_size}) to progress the chunking loop")- # Skip empty/whitespace text before tokenizing: BPE/SentencePiece emit real tokens for- # spaces/newlines, so a len(tokens)==0 check misses it and would yield a degenerate lone-EOS sample.+ # BPE/SentencePiece emit tokens for whitespace, so check text, not len(tokens), to avoid lone-EOS rows.if not text or not text.strip():return []@@ -195,8 +193,7 @@ class RawTextDataLoader:breakstart_idx += chunk_size - stride- # Stride 0 + exact multiple leaves a lone-EOS chunk: end a full window at the EOS instead, so the- # EOS keeps its context (a [token, EOS] row spikes loss) and no content token loses its label.+ # Stride 0 with an exact multiple leaves a lone-EOS chunk; end a full window at EOS so EOS keeps context and no token loses its label.if reserve_eos and len(bounds) > 1 and bounds[-1][0] == len(tokens):bounds[-1][0] = num_tokens - chunk_size@@ -227,15 +224,13 @@ class RawTextDataLoader:def _read_file_by_format(self, file_path, file_format):"""Read file content based on detected format."""- # utf-8-sig: Windows tooling (PowerShell Out-File, Excel "CSV UTF-8") prepends a BOM that plain- # utf-8 keeps as a leading character. Without a BOM it decodes exactly like utf-8.+ # utf-8-sig strips the BOM Windows tools prepend; otherwise identical to utf-8.with open(file_path, "r", encoding = "utf-8-sig") as f:if file_format == "plain_text" or file_format == "markdown":return f.read()elif file_format == "json_lines":if Path(file_path).suffix.lower() == ".json":- # A .json file is a single JSON document (commonly a list of records), so parsing it per line drops- # the whole file.+ # A .json file is one JSON document, not JSON lines, so per-line parsing would drop the whole file.try:parsed = json.load(f)records = parsed if isinstance(parsed, list) else [parsed]@@ -244,8 +239,7 @@ class RawTextDataLoader:f.seek(0)records = self._iter_json_lines(f)else:- # A .jsonl file is one JSON value per line: stay streaming so a large file is never held in memory- # at once.+ # Stream .jsonl so large files are never held in memory.records = self._iter_json_lines(f)lines = []for data in records:@@ -285,8 +279,7 @@ class RawTextDataLoader:def _extract_text_from_json(self, data):"""Extract text from JSON object using common field names."""- # Skip non-object lines (str/list/number): `field in data` would be a substring/membership test, not- # a key lookup, and `data[field]` raises.+ # Skip non-dict lines: `field in data` would be a substring test, and `data[field]` raises.if not isinstance(data, dict):return ""for field in self._TEXT_FIELDS:@@ -321,9 +314,7 @@ def _iter_column(dataset, column):class _TextCharTable(dict):"""str.translate table for clean_text, filled in the first time each character is seen."""- # Drop only the invisible: control, private-use and surrogate code points, noncharacters, and the- # format characters below. Every other format character (ZWJ, ZWNJ, ayah signs, emoji tags) is text,- # and Cn just means newer than this interpreter's Unicode database.+ # Drop only invisible characters; other format chars (ZWJ, emoji tags) are text, and Cn may be newer Unicode._DROP_CATEGORIES = frozenset(("Cc", "Co", "Cs"))_JUNK_CHARS = frozenset(chr(codepoint)@@ -388,8 +379,7 @@ class TextPreprocessor:"""Extract specific sections (e.g., code blocks, quotes)"""sections = []for pattern in patterns:- # Compile pattern on first use and cache? Well, patterns are user-provided, so just use re.findall- # with compiled flags+ # Patterns are user-provided, so just use re.findall with compiled flags rather than a compile cache.matches = re.findall(pattern, text, re.MULTILINE | re.DOTALL)sections.extend(matches)return sections@@ -425,8 +415,7 @@ class TextPreprocessor:"warnings": [],}- # `column_names` is HF Dataset-only; None means a mapping-like (DataFrame, dict, custom- # __getitem__), which this method has always accepted.+ # None means a mapping-like (DataFrame, dict), which this method accepts.column_names = getattr(dataset, "column_names", None)if column_names is None or "text" in column_names:texts = _iter_column(dataset, "text")@@ -473,8 +462,7 @@ class TextPreprocessor:if text_lengths:stats["avg_length"] = sum(text_lengths) / len(text_lengths)- # No sample had content, so min_length is still its float("inf") seed; report 0 like max_length and- # avg_length beside it.+ # min_length keeps its float("inf") seed when no sample had content; report 0 like max_length and avg_length.if stats["min_length"] == float("inf"):stats["min_length"] = 0@@ -487,8 +475,7 @@ class TextPreprocessor:if stats["encoding_issues"] > 0:stats["warnings"].append(f"Found {stats['encoding_issues']} encoding issues")- # Guard on text_lengths, not on min_length: with nothing measured it is now 0, and zero measured- # samples is not "some samples are very short".+ # Guard on text_lengths, not min_length: with nothing measured min_length is 0, which must not warn as very short.if text_lengths and stats["min_length"] < 10:stats["warnings"].append("Some samples are very short (< 10 characters)")diff --git a/unsloth/dataprep/synthetic.py b/unsloth/dataprep/synthetic.pyindex 137b472ceb7..11c71b0297c 100644--- a/unsloth/dataprep/synthetic.py+++ b/unsloth/dataprep/synthetic.py@@ -23,9 +23,7 @@ from ..device_type import clean_gpu_cachedef _hf_transfer_importable() -> bool:- # huggingface_hub < 1.0 raises on every download when the flag is on and the package is- # missing (it is optional, and absent on Windows on ARM). find_spec never imports it, and- # raises ValueError for a sys.modules stub whose __spec__ is None.+ # find_spec, never import: huggingface_hub <1.0 raises on each download if the flag is on and hf_transfer is missing; stubs raise ValueError.try:return _importlib_util.find_spec("hf_transfer") is not Noneexcept (ImportError, ValueError):@@ -344,8 +342,7 @@ class SyntheticDataKit:stderr = subprocess.PIPE,start_new_session = True,)- # both "Starting vLLM API server on" (<= 0.18) and "Starting vLLM server on"- # (0.19), with the optional server index some versions insert+ # Matches both "Starting vLLM API server on" (<= 0.18) and "Starting vLLM server on" (0.19).ready_re = re.compile(r"Starting vLLM(?:\s+API)?\s+server(?:\s+\d+)?\s+on\b")self.vllm_process = vllm_processself.stdout_capture = PipeCapture(@@ -406,17 +403,14 @@ class SyntheticDataKit:"""deadline = _deadline(timeout)while True:- # Cap each lap at the time left: a flat poll_interval overshoots any shorter timeout, and- # readiness inside that overshoot would return success from an expired deadline. No deadline means- # full laps, which still notice a dead child where the bare Event.wait(None) this replaced hung.+ # Cap each wait at the time left so readiness after the deadline is not reported as success.remaining = _remaining(deadline)if remaining is not None and remaining <= 0:self._fail_vllm_server(f"was not ready within {timeout} seconds")wait = poll_interval if remaining is None else min(poll_interval, remaining)if self.stdout_capture.wait_for_ready(timeout = wait):return- # checked BEFORE the exit/closed arms, so a server that is ready on- # stderr is never reported as never having started+ # Checked before the exit/closed arms, so a ready server is never reported as not started.if self.stderr_capture.wait_for_ready(timeout = 0):returnreturncode = self.vllm_process.poll()@@ -424,8 +418,7 @@ class SyntheticDataKit:self._fail_vllm_server(f"exited with code {returncode} before it was ready")if self.stdout_capture.has_closed():self._fail_vllm_server("closed its stdout before it was ready")- # Expiry is checked at the top, so a dead or closed child keeps its own message rather than being- # reported as a timeout.+ # Expiry is checked at the top, so a dead or closed child keeps its own message rather than being reported as a timeout.def _fail_vllm_server(self, what_happened):"""Terminate the server and raise, quoting what it managed to say.@@ -542,8 +535,7 @@ class SyntheticDataKit:if max_tokens <= 5:raise RuntimeError("Generation length is way too long!")if max_tokens <= self.overlap:- # A non-positive stride (max_tokens - overlap) makes the n_chunks computation below divide by zero- # or go negative.+ # Stride max_tokens - overlap must be positive, or the n_chunks computation below divides by zero or goes negative.raise RuntimeError(f"The chunk size (max_seq_length - 2 * max_generation_tokens - 128 = "f"{max_tokens}) must be larger than the overlap ({self.overlap}). "@@ -554,16 +546,12 @@ class SyntheticDataKit:# Get left and right boundarieslength = len(input_ids)if length <= max_tokens:- # The whole document fits one chunk window: the multi-chunk path below would drop it (the- # linspace/stack pairing emits one fewer range than boundary points) or, for a document shorter- # than the overlap, slice the wrong tokens via negative start indices.+ # Fits one window: the multi-chunk path would drop it or slice wrong tokens when shorter than overlap.boundaries = [[0, length]] if length > 0 else []else:- # Minimal count: overlapping chunks cover `length` in ceil((length - overlap) / stride) chunks, not- # ceil(length / stride), which over-splits just past a stride multiple.+ # Overlapping chunks need ceil((length - overlap) / stride), not ceil(length / stride).n_chunks = int(np.ceil((length - self.overlap) / (max_tokens - self.overlap)))- # n_chunks + 1 points: the [:-1]/[1:] pairing yields n_chunks ranges; n_chunks points gave one- # fewer, oversized chunk (over max_tokens).+ # Needs n_chunks + 1 boundary points: with n_chunks the [:-1]/[1:] pairing drops a range and leaves one oversized chunk over max_tokens.boundaries = np.ceil(np.linspace(0, length - self.overlap, n_chunks + 1)).astype(int)boundaries = np.stack((boundaries[:-1], (boundaries + self.overlap)[1:])).Tboundaries = np.minimum(boundaries, length).tolist()diff --git a/unsloth/device_type.py b/unsloth/device_type.pyindex cffe6298ef3..df4f047ffa8 100644--- a/unsloth/device_type.py+++ b/unsloth/device_type.py@@ -99,12 +99,10 @@ def _zoo_cpu_backend(name):@functools.cachedef get_device_type():- # MLX first: torch is never imported on the MLX runtime, so claiming "cuda" here would NameError in- # get_device_count. Matches unsloth/__init__.py and unsloth_zoo.device_type.+ # MLX first: torch is never imported there. Matches unsloth/__init__.py and unsloth_zoo.device_type.if _IS_MLX:return "mlx"- # Test-only CPU fallback: report "cuda" so every DEVICE_TYPE == "cuda" branch behaves identically.- # Read once per process (function is cached).+ # Test-only CPU fallback: report "cuda" so all cuda branches behave identically.if os.environ.get("UNSLOTH_ALLOW_CPU", "0") == "1":return "cuda"if _zoo_cpu_backend("cpu_backend_forced"):@@ -167,18 +165,13 @@ def get_device_count():DEVICE_COUNT: int = get_device_count()-# 4-bit quantization requires a block size of 64: Instinct (MI) has a warp size of 64 against 32-# elsewhere. Since bitsandbytes 0.49.0 pre-quantized 64-blockwise models work on Radeon (Navi)-# but not Instinct (bitsandbytes-foundation/bitsandbytes#1748); since 0.49.2 blocksize=64 4-bit-# is supported on CDNA (MI Instinct / gfx9xx) too (#1856).+# 4-bit needs blocksize 64; Instinct warp size is 64. bnb 0.49.2+ supports blocksize 64 on CDNA too.ALLOW_PREQUANTIZED_MODELS: bool = True# HSA_STATUS_ERROR_EXCEPTION checks - sometimes AMD fails for BnBALLOW_BITSANDBYTES: bool = True-# Unusable bitsandbytes on any backend, not just hip: clear the flags the loader reads before it-# picks a 4bit checkpoint. A guarded import, not find_spec, since importable is not usable: from-# 0.46 a dead native library still resolves every ctypes handle to a closure that raises only when-# called, so 4bit would die mid-run rather than fall back here.+# Unusable bnb on any backend, not just hip: clear the flags the loader reads before it picks 4bit.+# Guarded import, not find_spec: a dead bnb 0.46+ native library only raises when called.try:import bitsandbytes as _bnb_probeexcept Exception:@@ -625,9 +618,7 @@ def get_device_stats() -> tuple[str, str, float]:name = gpu_stats.name + ". " if gpu_stats.name else "Intel XPU Device. "snippet = f"Intel Toolkit: {torch.version.xpu}."elif DEVICE_TYPE == "npu":- # Named for the vendor, like the arms either side of it: torch.npu and torch_npu are- # Ascend's, so an unnamed one is an Ascend NPU the driver declined to name, not some- # generic NPU. #10686 added the tests that say so and the code that did not.+ # torch.npu / torch_npu are Ascend's, so an unnamed device is an Ascend NPU.name = gpu_stats.name + ". " if gpu_stats.name else "Ascend NPU Device. "# Report the toolkit like the cuda/xpu arms, not the name already in `name`.try:diff --git a/unsloth/disk_utils.py b/unsloth/disk_utils.pyindex 4bbea3a770a..3442b6e4f60 100644--- a/unsloth/disk_utils.py+++ b/unsloth/disk_utils.py@@ -58,9 +58,7 @@ except ImportError:_TRUE = ("1", "true", "yes", "on")def is_kaggle_environment():- # Kept in step with unsloth_zoo.disk_utils: only a real kernel sets KAGGLE_KERNEL_RUN_TYPE and- # only the Kaggle image has /kaggle/working, whereas KAGGLE_USERNAME / KAGGLE_KEY /- # KAGGLE_CONFIG_DIR are what people export for the Kaggle CLI on their own machines.+ # Kept in step with unsloth_zoo.disk_utils: KAGGLE_USERNAME etc. are also set by CLI users locally.override = os.environ.get("UNSLOTH_IS_KAGGLE", None)if override is not None:return str(override).strip().lower() in _TRUE@@ -95,9 +93,7 @@ except ImportError:return Nonedef logical_numel(param, name = ""):- # Packed storage cannot be unpacked without the zoo's knowledge of the packing schemes, so report- # what numel() says, exactly as the code did before it asked. Barely reachable: model_16bit_bytes- # is 0 here and every caller returns before sizing anything.+ # Packed storage cannot be unpacked without the zoo, so report numel(); barely reachable.try:return int(param.numel())except Exception:@@ -110,8 +106,7 @@ except ImportError:return 0def estimate_gguf_export_bytes(*args, **kwargs):- # 0 means "unmeasurable", and every caller treats that as "do not block", so an old unsloth_zoo- # behaves exactly as it did.+ # 0 means unmeasurable, which callers treat as do not block.return 0def kaggle_tmp_redirect(save_directory, *args, **kwargs):diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex 9e23c474282..9a54306ff6d 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -151,25 +151,19 @@ if not UNSLOTH_ENABLE_LOGGING:# Applied to stderr for FBGEMM (pytorch/FBGEMM utils.py#L43-L52) and CUTLASS SM90-vs-SM100 MMA / arch / TMA errors.sys.stderr = HidePrintMessage(sys.stderr)- # https://github.com/pytorch/FBGEMM/blob/d99cd96490ec4aabac2ee95b1e76ea4dcfcfa628/fbgemm_gpu/experimental/ge- # mm/triton_gemm/utils.py#L43-L52+ # https://github.com/pytorch/FBGEMM/blob/d99cd96490ec4aabac2ee95b1e76ea4dcfcfa628/fbgemm_gpu/experimental/gemm/triton_gemm/utils.py#L43-L52sys.stderr.add_filter("TMA benchmarks will be running")- # CUTLASS/FBGEMM MMA instruction error on SM90 vs SM100 (Blackwell) GPUs- # https://github.com/NVIDIA/cutlass/blob/main/include/cutlass/gemm/kernel/sm90_gemm_tma_warpspecialized.hpp+ # CUTLASS/FBGEMM MMA instruction error on SM90 vs SM100 (Blackwell) GPUs: https://github.com/NVIDIA/cutlass/blob/main/include/cutlass/gemm/kernel/sm90_gemm_tma_warpspecialized.hppsys.stderr.add_filter("Arch conditional MMA instruction used without targeting")# CUTLASS arch conditional errors for various architecturessys.stderr.add_filter("CUTE_INVALID_CONTROL_PATH")# CUTLASS TMA-related errors when not targeting correct architecturesys.stderr.add_filter("Trying to use tma without CUTE_ARCH_TMA")- # torchao logs a cosmetic "Skipping import of cpp extensions" WARNING on torch < 2.11. The- # bnb-4bit / Unsloth paths do not use its cpp kernels, so drop that one record rather than- # raising the whole torchao logger to ERROR.+ # Drop only torchao's cosmetic cpp-extension warning rather than raising its logger level.logging.getLogger("torchao").addFilter(HideLoggingMessage("Skipping import of cpp extensions due to incompatible torch version"))- # torch >= 2.11: torchao dlopens each prebuilt _C*.so and logs a failure on an ABI tag- # mismatch (a cp310 .so under cp312) or a missing arch kernel, then falls back to non-cpp- # paths Unsloth does not use.+ # torch >= 2.11: torchao logs failed _C*.so loads (ABI tag/arch) then falls back; harmless.logging.getLogger("torchao").addFilter(HideLoggingMessage("Failed to load "))# SyntaxWarning: invalid escape sequence '\.'warnings.filterwarnings("ignore", message = "invalid escape sequence", category = SyntaxWarning)@@ -346,8 +340,7 @@ def fix_torch_check_is_size():return-# Fix "AttributeError: 'MessageFactory' object has no attribute 'GetPrototype'" first, mainly-# because tensorflow causes issues.+# Fix MessageFactory.GetPrototype AttributeError (caused by tensorflow) first.def fix_message_factory_issue():try:import google.protobuf.message_factory@@ -424,14 +417,8 @@ def fix_xformers_performance_issue():logger.info(f"Unsloth: Failed patching Xformers with error = {str(e)}")-# flash-attn 4 ships flash_attn/cute/ with no __init__.py, so flash_attn is a namespace package-# without flash_attn.flash_attn_interface. xformers gates on find_spec then imports that submodule-# unguarded, so `import xformers.ops` raises, _utils.py swallows it into xformers = None,-# HAS_XFORMERS goes False and every fast-path model drops to SDPA: measured on a B200 at seq_len-# 8192, 547 ms/step and 2.69 GB peak against 2154 ms/step and 19.02 GB on SDPA. The repair imports-# xformers ONCE with flash_attn hidden from find_spec, so it takes the next branch of its own elif-# chain and the working module is cached in sys.modules. Nothing is written to any third-party-# package.+# flash-attn 4 makes flash_attn a namespace package without flash_attn_interface, which breaks+# `import xformers.ops`; import xformers once with flash_attn hidden from find_spec._FLASH_ATTN_INTERFACE_NAME = "flash_attn_interface"_FLASH_ATTN_INTERFACE_MODULE = "flash_attn." + _FLASH_ATTN_INTERFACE_NAME_FA4_NAMESPACE_WARNED = [False]@@ -525,12 +512,10 @@ def fix_flash_attn_4_namespace_shadow():if _flash_attn_layout() != "flash_attn_4_only":returnif importlib.util.find_spec("xformers") is None:- # Nothing to protect: no xformers means SDPA anyway, and is_flash_attn_2_available() is False- # here, since the distribution is flash-attn-4 and the flash_attn metadata lookup misses.+ # No xformers means SDPA anyway; FA4's dist name means is_flash_attn_2_available() is False.returnif "xformers.ops.fmha.flash" in sys.modules:- # Already imported successfully. A FAILED import leaves nothing in sys.modules, so this does- # not mask the case we are here to fix.+ # A failed import leaves nothing in sys.modules, so this does not mask the bug.returnreal_find_spec = importlib.util.find_spec@@ -540,9 +525,7 @@ def fix_flash_attn_4_namespace_shadow():return Nonereturn real_find_spec(name, package)- # Process-global swap, scoped to this one import and restored in `finally`. Another thread- # calling find_spec("flash_attn*") in the ~1.0s window is told it is absent, which is honest- # for the FA2 namespace xformers asks about.+ # Process-global swap restored in finally; concurrent find_spec(flash_attn*) sees it absent.importlib.util.find_spec = _find_spec_without_flash_attntry:import xformers.ops # noqa: F401@@ -909,8 +892,7 @@ def _coerce_legacy_config_kwargs(cls, kwargs):def _legacy_config_init_is_generated(init):- # dataclass writes __init__ via exec ("<string>"); a hand-written one normalises its own- # arguments before forwarding, so only the generated init it reaches coerces them.+ # Only the dataclass-generated __init__ (exec'd as <string>) coerces arguments.depth = 0while hasattr(init, "__wrapped__") and depth < 32:init, depth = init.__wrapped__, depth + 1@@ -960,8 +942,7 @@ def fix_transformers5_legacy_config_types():if previous in _legacy_config_wrappers:return- # Patch lazily on first instantiation, once every class decorator has run:- # @strict(accept_kwargs=True) swaps in an __init__ that never calls the one it replaced.+ # Patch lazily, after every class decorator has run: @strict(accept_kwargs=True) swaps in an __init__ that never calls the original.def __new__(cls, *args, **kwargs):if cls not in _legacy_config_ready:for klass in cls.__mro__:@@ -986,10 +967,7 @@ def fix_transformers5_legacy_config_types():logger.info("Unsloth: Patched transformers config classes to accept legacy 4.x value types.")-# Where the image helpers that `modeling_*.py` files reach for actually live.-# Ordered so the image modules win: `resize` exists in image_transforms and is-# the one a preprocessor means, and `transformers.utils` is last because it is-# broad enough to shadow a name by accident.+# Image modules first so their `resize` wins; transformers.utils last, it can shadow names._IMAGE_PROCESSING_SYMBOL_HOMES = ("transformers.image_transforms","transformers.image_utils",@@ -998,8 +976,7 @@ _IMAGE_PROCESSING_SYMBOL_HOMES = ("transformers.utils",)-# Vision backbones whose image-processing module third-party remote code imports-# as a namespace (`import ... as siglip2_ips`) and then reads helpers off.+# Image-processing modules that third-party remote code imports as a namespace (`import ... as siglip2_ips`), then reads helpers off._IMAGE_PROCESSING_MODULES = ("transformers.models.siglip2.image_processing_siglip2","transformers.models.siglip.image_processing_siglip",@@ -1007,13 +984,10 @@ _IMAGE_PROCESSING_MODULES = (_IMAGE_REEXPORT_FLAG = "_unsloth_legacy_image_reexports"-# Names this fix bound onto a module, so the patch can be fully undone: the-# forwarder caches each hit with setattr, and removing only __getattr__ would-# leave those bindings behind.+# Tracks names the forwarder cached via setattr so undo can remove them too._IMAGE_REEXPORT_BOUND = "_unsloth_legacy_image_bound"-# One name per module that transformers 5 stopped re-exporting, used to decide-# whether this environment is affected at all.+# One probe name per module that transformers 5 stopped re-exporting, used to decide if this environment is affected._IMAGE_REEXPORT_PROBE = "filter_out_non_signature_kwargs"# Set on the wrapper AND on the module. The wrapper's copy is the one the guard reads.@@ -1068,9 +1042,7 @@ def _install_legacy_image_reexports(module_name):return Falseif _image_reexports_are_installed(module):return False- # A surviving forwarder answers for every missing name, so the probe below would report- # the re-exports as present and bail with the numpy half still unpatched. Reinstall just- # that half: reload wiped only the names the module body assigns.+ # A surviving forwarder fools the probe below; reinstall the numpy half that reload wiped.if getattr(getattr(module, "__getattr__", None), _IMAGE_REEXPORT_FLAG, False):try:_install_legacy_numpy_image_helpers(module)@@ -1084,8 +1056,7 @@ def _install_legacy_image_reexports(module_name):bound = set()def __getattr__(name):- # Dunders are looked up on the type for real modules; anything private- # is not a re-export, so leave both alone.+ # Private names are never re-exports, and dunders go through the type for real modules, so __getattr__ skips both.if not name.startswith("_"):for home in _IMAGE_PROCESSING_SYMBOL_HOMES:try:@@ -1109,8 +1080,7 @@ def _install_legacy_image_reexports(module_name):module.__getattr__ = __getattr__setattr(module, _IMAGE_REEXPORT_FLAG, True)setattr(module, _IMAGE_REEXPORT_BOUND, bound)- # Names that still resolve never reach __getattr__, so the ones whose- # contract changed from numpy to torch are handled separately.+ # Names that still resolve never reach __getattr__, so the ones whose contract changed from numpy to torch are handled separately.try:_install_legacy_numpy_image_helpers(module)except Exception as e:@@ -1118,13 +1088,8 @@ def _install_legacy_image_reexports(module_name):return True-# Helpers transformers 5 KEPT on these modules but re-specified from numpy-# (channel-last) to torch (channel-first). A module __getattr__ never fires for-# a name that still resolves, so these need replacing rather than forwarding.-# Phi-4-reasoning-vision-15B's modeling_phi4_visionr.py reaches both off the-# siglip2 namespace at lines 347-348, having built numpy arrays at line 302, so-# without this the class loads and then preprocessing fails:-# "cannot reshape array of size 150528 into shape (224,14,16,0,16)".+# Helpers transformers 5 kept but switched from numpy channel-last to torch channel-first;+# __getattr__ never fires for them, so they must be replaced (e.g. Phi-4-reasoning-vision)._IMAGE_REEXPORT_LEGACY_BOUND = "_unsloth_legacy_image_numpy_bound"@@ -1158,10 +1123,7 @@ def _legacy_pad_along_first_dim(return array, mask-# The keyword the first argument goes by, per era. transformers renamed-# pad_along_first_dim's first parameter from `array` to `tensor` when it moved-# to torch, so a 4.x caller using the keyword form names something the current-# implementation does not accept at all.+# transformers renamed pad_along_first_dim's first param from `array` to `tensor`._LEGACY_NUMPY_IMAGE_HELPERS = {"convert_image_to_patches": (_legacy_convert_image_to_patches, ("image",)),"pad_along_first_dim": (_legacy_pad_along_first_dim, ("array", "tensor")),@@ -1192,8 +1154,7 @@ def _install_legacy_numpy_image_helpers(module):):@functools.wraps(current)def dispatch(*args, **kwargs):- # The first argument may arrive positionally or under either- # era's keyword, so check all of them before deciding.+ # The first argument may arrive positionally or under either era's keyword, so check every spelling before deciding.first = args[0] if args else Noneif first is None:for key in first_names:@@ -1201,8 +1162,7 @@ def _install_legacy_numpy_image_helpers(module):first = kwargs[key]breakif isinstance(first, np.ndarray):- # Normalise onto the 4.x keyword the legacy function names,- # so a caller using the current era's spelling still works.+ # Rewrite the current-era keyword to the 4.x name the legacy function takes, so either spelling works.if not args:for key in first_names[1:]:if key in kwargs:@@ -1235,12 +1195,8 @@ def _remove_legacy_numpy_image_helpers(module):pass-# The same numpy/torch split one level up: BACKEND METHODS on the class.-# transformers 5 put a torchvision backend in every image processor's MRO, so a-# remote-code subclass handing channel-last numpy to `self.normalize` raises.-# `rescale` is the quieter half and the reason this cannot gate on exceptions:-# it accepts numpy and returns float64 where 4.x returned float32, so patching-# only the raising method leaves pixel_values float64 with nothing raised.+# transformers 5 backend methods reject or mis-handle numpy; `rescale` silently returns float64,+# so patching cannot be gated on exceptions._IMAGE_METHOD_PATCH_FLAG = "_unsloth_numpy_image_method"# Names installed on a class, so the patch can be fully undone.@@ -1249,10 +1205,7 @@ _IMAGE_METHOD_BOUND = "_unsloth_numpy_image_methods"# Where transformers puts every module it builds out of a checkpoint's own code._REMOTE_IMAGE_MODULE_PREFIX = "transformers_modules."-# Every transformers image processor descends from one of these. Matched by NAME-# on the already-loaded MRO rather than by isinstance, so classifying the configs-# and models that also come through `get_class_in_module` costs a string compare-# and imports nothing.+# Matched by name on the loaded MRO so classifying configs and models imports nothing._IMAGE_PROCESSOR_BASE_NAMES = frozenset(("ImageProcessingMixin",@@ -1306,12 +1259,8 @@ def _legacy_normalize()-# name -> (4.x implementation, kwargs valid on a probe image). Only methods that-# were THIN PASSTHROUGHS to the identically named `image_transforms` function in-# 4.x, so the legacy half is transformers' own code. `resize`, `center_crop` and-# `pad` are absent because their 4.x methods converted a dict `size` first, so-# forwarding them is not signature compatible; `convert_to_rgb` was never a 4.x-# method and is already bit-identical on numpy.+# Only 4.x thin passthroughs to image_transforms; resize/center_crop/pad converted a dict+# `size` first so are not signature compatible._LEGACY_NUMPY_IMAGE_METHODS = {"rescale": (_legacy_rescale, {"scale": 1.0 / 255.0}),"normalize": (_legacy_normalize, {"mean": [0.5, 0.5, 0.5], "std": [0.5, 0.5, 0.5]}),@@ -1412,8 +1361,7 @@ def _install_legacy_numpy_image_methods(cls):owner, current = _resolved_image_method(cls, name)if current is None:continue- # Read off the LIVE descriptor, per `_sdpa_mask_is_patched`: a class- # flag outlives what it describes. Also makes a subclass a no-op.+ # Read the live descriptor: a class flag outlives what it describes.if getattr(current, _IMAGE_METHOD_PATCH_FLAG, False):continueowner_module = getattr(owner, "__module__", "") or ""@@ -1425,17 +1373,14 @@ def _install_legacy_numpy_image_methods(cls):def make(current = current, legacy = legacy):@functools.wraps(current)def dispatch(self, image, *args, **kwargs):- # `image` is the parameter name in BOTH eras, so the keyword form- # remote code uses (`self.normalize(image=..., mean=...)`) binds- # here exactly as the positional one does.+ # `image` is the parameter name in both eras, so keyword calls like self.normalize(image=...) bind here too.if isinstance(image, np.ndarray):return legacy(self, image, *args, **kwargs)return current(self, image, *args, **kwargs)# Keep the original reachable, so the patch can be tested and undone.dispatch.__wrapped__ = current- # AFTER functools.wraps, which copies the wrapped function's __dict__- # and would otherwise be able to drop the mark. Do not reorder.+ # After functools.wraps, which copies __dict__ and could drop the mark. Do not reorder.setattr(dispatch, _IMAGE_METHOD_PATCH_FLAG, True)return dispatch@@ -1589,9 +1534,7 @@ class _RemoteImageProcessorLoader:return create(spec)def exec_module(self, module):- # BEFORE delegating: `exec_module` runs the module body, and a- # checkpoint reads the dropped re-exports while its CLASS BODY executes,- # so patching afterwards is already too late.+ # Before delegating: checkpoint class bodies read the dropped re-exports during exec_module.try:_install_legacy_image_reexports_now()except Exception:@@ -1619,11 +1562,7 @@ class _RemoteImageProcessorFinder(importlib.abc.MetaPathFinder):def __init__(self):setattr(self, _REMOTE_IMAGE_FINDER_SENTINEL, True)- # find_spec below walks sys.meta_path again, so it has to know it is- # already inside itself. Thread-local, not a plain attribute: two- # threads importing remote modules at once (a threaded DataLoader is- # the realistic case) would otherwise read each other's flag, and the- # loser is handed back an UNPATCHED module with nothing raised.+ # Thread-local reentrancy flag: a shared one lets concurrent imports return an unpatched module.self._finding = threading.local()def find_spec(@@ -1698,9 +1637,7 @@ def fix_transformers5_image_processing_reexports():logger.info(f"Unsloth: Skipping image processing re-export fix ({e})")return- # Before anything else, because the path it covers is an import in a CHILD- # process, where nothing has run yet: pickle rebuilds a processor by- # importing the remote module directly, never through get_class_in_module.+ # First: pickle in a child process imports the remote module directly, not via get_class_in_module.try:_install_remote_image_processor_finder()except Exception as e:@@ -1714,11 +1651,7 @@ def fix_transformers5_image_processing_reexports():except Exception as e:logger.info(f"Unsloth: Skipping image re-export fix for {module_name} ({e})")- # Asked of the live FUNCTION, not of the module flag: `importlib.reload` re-runs the- # module body in the existing namespace, so `get_class_in_module` goes back to upstream- # while any attribute we added survives. Gating on the flag would then refuse to re-wrap- # a module that is once again unpatched, which is the opposite of what an idempotence- # guard is for. Same reasoning as `_sdpa_mask_is_patched` below.+ # Check the live function, not a module flag: importlib.reload restores upstream but keeps attrs.original = getattr(dynamic_module_utils, "get_class_in_module", None)if original is None:return@@ -1727,18 +1660,13 @@ def fix_transformers5_image_processing_reexports():@functools.wraps(original)def get_class_in_module(*args, **kwargs):- # Runs immediately before a checkpoint's own modeling file is executed,- # which is the only place the missing re-exports are read.+ # Runs right before a checkpoint's modeling file executes, the only place the missing re-exports are read.try:_install_legacy_image_reexports_now()except Exception as e:logger.info(f"Unsloth: image re-export fix skipped ({e})")loaded = original(*args, **kwargs)- # Now the checkpoint's own modules exist, which is the only place the- # numpy backend methods can be corrected without touching transformers'- # own. The module sweep rather than `loaded` alone, because an image- # processor is usually defined beside the model and read off the module,- # so it never comes through here itself.+ # Sweep modules, not just `loaded`: image processors are usually read off the module.try:_install_legacy_numpy_image_methods_now(loaded)except Exception as e:@@ -2051,12 +1979,9 @@ def _sdpa_mask_leaves_rows_fully_masked():sdpa_mask = getattr(masking_utils, "sdpa_mask", None)if sdpa_mask is None:return False- # Unwrap first: a second call must probe the ORIGINAL, or the installed patch reports the bug- # as fixed and a reload silently drops it.+ # Unwrap first, or the installed patch reports the bug fixed and a reload drops it.sdpa_mask = getattr(sdpa_mask, "__wrapped__", sdpa_mask)- # The query axis is named differently per version: 5.x takes q_length, while 4.57.6 binds- # sdpa_mask to sdpa_mask_recent_torch, which takes cache_position. Ask the signature, since a- # probe that raises TypeError answers "no bug" for an unrelated reason.+ # Query arg is q_length on 5.x, cache_position on 4.57.6; ask the signature, since a TypeError would falsely answer no bug.kwargs = {"batch_size": 2,"kv_length": 2,@@ -2079,8 +2004,7 @@ def _sdpa_mask_leaves_rows_fully_masked():mask = sdpa_mask(**kwargs)if mask is None or mask.is_floating_point():return False- # Inside the guard too: reading a mask's truth value is what fails on a meta or unmaterialised- # tensor, and a probe that raises would take `import unsloth` down with it.+ # Inside the guard: reading a meta tensor's truth value raises and would break import.return bool((~mask.any(dim = -1)).any())except Exception:# Signature moved under us. Patching blind would be worse than not.@@ -2138,16 +2062,13 @@ def fix_transformers_fully_masked_rows():def sdpa_mask(*args, **kwargs):return _unmask_rows_attending_to_nothing(original(*args, **kwargs))- # functools.wraps sets __wrapped__, but set it explicitly: the probe and the tests both read- # it, and a wraps-less edit must not make the patch un-probeable and un-undoable.+ # Set explicitly: the probe and tests read __wrapped__.sdpa_mask.__wrapped__ = original- # The mark travels ON the wrapper, so the guard above reads the live binding and a reload that- # drops it is re-patched rather than skipped.+ # Mark on the wrapper so a reload that drops it is re-patched.setattr(sdpa_mask, _SDPA_MASK_PATCH_FLAG, True)try:- # BOTH bindings, which are not the same object: eager_mask calls the module global by name at- # call time, while the interface captured the original in _global_mapping at class-body time.+ # Both bindings: eager_mask reads the module global; the interface captured the original.masking_utils.sdpa_mask = sdpa_maskinterface = getattr(masking_utils, "ALL_MASK_ATTENTION_FUNCTIONS", None)if interface is not None:@@ -2459,19 +2380,11 @@ def fix_transformers_flex_mask_graph_breaks():_COMPOSITE_PREFIX_RENAMING_FLAG = "_unsloth_patched_composite_prefix_renaming"-# unsloth_zoo marks its own copy of this repair with this. Spelled as a literal rather than-# imported, so a zoo too old to define it cannot turn a skipped repair into an ImportError.+# Literal, not imported, so an older unsloth_zoo cannot cause an ImportError._ZOO_COMPOSITE_PREFIX_RENAMING_FLAG = "_unsloth_zoo_patched_composite_prefix_renaming"-# zoo's `temporary_patches/common.py:WRAPPER_INNER_ATTR`: the explicit link a wrapper on that-# same function publishes to whatever it wrapped. Following it matters because zoo's MoE-# wrapper (`temporary_patches/moe_utils_bnb4bit.py`) deliberately does NOT publish-# `__wrapped__` -- zoo's re-scope unwraps `__wrapped__` to pick what to wrap, so a MoE wrapper-# carrying one would be replaced rather than sat on top of, dropping its per-expert converters.-# zoo registers the re-scope BEFORE the MoE patch, so the MoE wrapper is on top in the normal-# case, and a `__wrapped__`-only walk stops there and reports no repair for one that is-# running underneath. Spelled as a literal, like the flag above, so a zoo too old to define it-# cannot turn a skipped repair into an ImportError.+# zoo's WRAPPER_INNER_ATTR: its MoE wrapper links the inner function here, not via __wrapped__,+# so walking only __wrapped__ would miss a repair underneath it._ZOO_WRAPPER_INNER_ATTR = "_unsloth_wrapper_inner"@@ -2544,9 +2457,7 @@ def _zoo_composite_prefix_renaming_installed():return False-# How many of a submodule's own parameter names to try a renaming against. A prefix renaming-# either matches every name under the submodule or none of them, so one would do; eight costs-# nothing and covers a mapping that only rewrites some leaf names.+# A renaming matches all names under a submodule or none; eight samples cover partial maps._COMPOSITE_RENAMING_SAMPLE = 8@@ -2636,9 +2547,7 @@ def _rescoped_renaming(conversion, prefix, sample_keys, model_keys):try:rescoped = type(conversion)(**patterns)except Exception:- # A subclass whose __init__ takes something else entirely -- upstream's `PrefixChange`- # takes prefixes, not patterns. It is still a WeightRenaming, and a renaming is all- # this produces, so fall back to the base class rather than giving up.+ # Subclasses like PrefixChange take other init args; fall back to base WeightRenaming.try:rescoped = WeightRenaming(**patterns)except Exception:@@ -2669,8 +2578,7 @@ def _leaked_submodule_prefix_renamings(model):from transformers.modeling_utils import PreTrainedModeldef extract(module, prefix):- # 5.6 to 5.9 take the submodule's dotted path as a second argument, everything else- # takes the module alone. Asked of the function rather than of a version.+ # 5.6 to 5.9 take the submodule's dotted path as a second argument.try:return extract_weight_conversions_for_model(module, prefix)except TypeError:@@ -2772,12 +2680,7 @@ def fix_transformers_composite_prefix_renaming():"""if _transformers_rescopes_submodule_prefix_renamings():return- # unsloth_zoo carries the same repair, in temporary_patches/conversion_mapping_rescope.py,- # because it owns the bitsandbytes Linear4bit patch that reports this failure and is- # importable without unsloth. When it installed first there is nothing left to do: a second- # wrapper is measurably inert -- the first pass leaves no leaked signature for the second to- # match -- but it is still a wrapper nobody needs, and one of the two has to yield. This one- # does, so the newer implementation wins on a stack where the two versions disagree.+ # unsloth_zoo carries the same repair; if it installed first, yield to it.if _zoo_composite_prefix_renaming_installed():returntry:@@ -2789,12 +2692,10 @@ def fix_transformers_composite_prefix_renaming():original = getattr(conversion_mapping, "get_model_conversion_mapping", None)if original is None:return- # Through the chain, not the top object: another library may have wrapped us since, and a- # second copy walks every submodule again per load.+ # Walk the chain: another library may have wrapped us since.if _own_composite_prefix_renaming_installed(original):return- # Wrap whatever is live, never `original.__wrapped__`: functools.wraps publishes that- # link, so unwrapping discards a third-party wrapper instead of one of ours.+ # Wrap whatever is live, never original.__wrapped__, or a third-party wrapper is discarded.@functools.wraps(original)def get_model_conversion_mapping(*args, **kwargs):@@ -2809,17 +2710,13 @@ def fix_transformers_composite_prefix_renaming():logger.info(f"Unsloth: Could not re-scope the conversion mapping ({e})")return conversions- # functools.wraps sets __wrapped__, but set it explicitly: the probe and the tests both- # read it, and a wraps-less edit must not make the patch un-probeable and un-undoable.+ # Set explicitly: the probe and tests read __wrapped__.get_model_conversion_mapping.__wrapped__ = originalsetattr(get_model_conversion_mapping, _COMPOSITE_PREFIX_RENAMING_FLAG, True)try:conversion_mapping.get_model_conversion_mapping = get_model_conversion_mapping- # `from ... import get_model_conversion_mapping` binds the object, not the attribute,- # so every holder needs rebinding: transformers.modeling_utils, transformers.- # integrations.peft, peft itself, and vllm's Transformers backend, which builds its- # WeightsMapper from it (vllm/model_executor/models/transformers/base.py).+ # `from ... import` binds the object, so rebind every holder (transformers, peft, vllm).owning_packages = ("transformers", "peft", "unsloth_zoo", "unsloth", "vllm")upstream_module = getattr(conversion_mapping, "__name__", "transformers.conversion_mapping")for module_name, module in list(sys.modules.items()):@@ -2831,13 +2728,8 @@ def fix_transformers_composite_prefix_renaming():namespace = getattr(module, "__dict__", None)if not isinstance(namespace, dict):continue- # `__dict__`, never `getattr`: transformers' lazy modules answer any name through- # `__getattr__` and print several hundred deprecation notices.- # Rebound only if it IS an alias of what we wrapped: `original` itself, upstream's- # own function (a module that imported the name before zoo wrapped it holds that,- # transformers.integrations.peft does), or zoo's marked wrapper. An identity test- # alone misses the first case; any-callable-by-name clobbers a package-local- # helper. Rebinding zoo's wrapper keeps its fix, since ours wraps it.+ # __dict__, not getattr: lazy modules print deprecation noise. Rebind only true aliases of+ # the wrapped function so package-local helpers are not clobbered.try:bound = namespace.get("get_model_conversion_mapping", None)if not callable(bound) or bound is get_model_conversion_mapping:@@ -3079,8 +2971,7 @@ def _carry_rope_theta_across_assignment(config, carried):parameters = getattr(config, "rope_parameters", None)per_layer = _rope_parameters_are_per_layer(config, parameters)if per_layer:- # Per-layer bases go back one level down. Falls through to the global attribute- # below only when there is no nested snapshot to restore.+ # Per-layer rope bases are restored from the nested snapshot; the global attribute is used only when none exists.restored = _carry_per_layer_rope_theta(config, parameters, carried)if restored is not None:return restored@@ -3088,9 +2979,7 @@ def _carry_rope_theta_across_assignment(config, carried):# Nothing restored = no-op or refused; a scalar fall-through put the MAPPING here.return Noneelif isinstance(carried, dict):- # Per-layer parameters replaced by a FLAT dict. Passing the mapping through would- # write a dict where a number belongs. One base stands for it only when every- # layer type agreed; otherwise carry nothing rather than invent a scalar.+ # Per-layer params replaced by a flat dict: carry a base only when all layer types agreed.bases = set(carried.values())carried = bases.pop() if len(bases) == 1 else Noneis_flat_dict = isinstance(parameters, dict) and not per_layer@@ -3105,17 +2994,13 @@ def _carry_rope_theta_across_assignment(config, carried):if base is None:return Noneif isinstance(base, dict):- # A base is a number. Also reachable from a config SAVED by the #11037 release,- # whose own rope_theta holds a mapping: refuse, it needs fixing at rest instead.+ # Also reachable from a config saved with a mapping in rope_theta: refuse.return Nonereadable = current is not Noneif is_flat_dict and not readable:try:- # A COPY, never the dict in place: transformers 5 stores the caller's object- # verbatim, so one scaling dict reused across a loop of models would carry the- # first config's base into the second. Measured on 5.0.0, 5.5.4 and 5.17.0: a- # config declaring 10000.0 came out with 500000.0, silently.+ # Copy: transformers 5 stores the caller's dict verbatim, so reuse leaks bases across configs.replacement = dict(parameters)replacement["rope_theta"] = baseconfig.rope_parameters = replacement@@ -3152,8 +3037,7 @@ def _transformers_rope_scaling_assignment_drops_theta():scaling = {"rope_type": "linear", "factor": 4.0}def build():- # Tiny, and a base far from the 10000.0 default so a silent fallback shows up- # as a difference rather than a match.+ # Base far from 10000.0 so a silent fallback shows up as a difference.return LlamaConfig(hidden_size = 64,num_attention_heads = 2,@@ -3164,8 +3048,7 @@ def _transformers_rope_scaling_assignment_drops_theta():rope_scaling = dict(scaling),)- # CPU explicitly: under a "meta" default device the comparison cannot be read, which- # would answer "not affected" for a reason unrelated to the bug.+ # CPU explicitly: under a meta default device the comparison cannot be read.device = torch.device("cpu")try:reference, _attention_factor = rope_init_fn(build(), device)@@ -3870,8 +3753,7 @@ def fix_transformers_remote_rope_scaling_none():and set(value) <= _PLAIN_ROPE_KEYS):return None- # 4.x kept these as config attributes; their copies in a real scaling dict fail 4.x- # validators that expect exactly the checkpoint's keys (InternLM2: len(rope_scaling) == 2).+ # Copies in a real scaling dict fail 4.x validators expecting exact keys (InternLM2).moved = [keyfor key in _ATTRIBUTE_ROPE_KEYS@@ -3913,12 +3795,8 @@ def fix_transformers_rope_scaling_drops_theta():owner = _rope_scaling_property_owner()if owner is not None and _rope_scaling_setter_is_patched(owner):return- # The probe answers through the cached `transformers.LlamaConfig`. After a reload of- # configuration_utils that class still inherits the OLD patched owner while the live- # owner is new and unpatched, so the probe would report the base survives and leave- # the live owner to lose it. A probe that cannot see the owner is no evidence and- # does not get to veto; installing anyway is safe, since the wrapper is a no-op on a- # build that keeps the base.+ # After a reload the cached LlamaConfig still inherits the old owner, so a probe that cannot+ # see the live owner must not veto; the wrapper is a no-op when unneeded.probe_can_see_owner = owner is None or _rope_probe_inherits(owner)if probe_can_see_owner and not _transformers_rope_scaling_assignment_drops_theta():return@@ -3927,15 +3805,12 @@ def fix_transformers_rope_scaling_drops_theta():returnprop = owner.__dict__["rope_scaling"]- # Unwrap first, so a reload that restored upstream's property is re-patched rather- # than wrapped on top of a wrapper.+ # Unwrap first so a reload is re-patched, not double-wrapped.original = getattr(prop.fset, "__wrapped__", prop.fset)@functools.wraps(original)def rope_scaling(self, value):- # Both halves are guarded, since this runs on every model load and an unexpected- # config shape must not turn an assignment into a traceback. The assignment- # itself is not, since swallowing that would be a silent behaviour change.+ # Guard the reads but not the assignment: swallowing that would change behaviour silently.try:carried = _rope_theta_snapshot(self)except Exception:@@ -3947,8 +3822,7 @@ def fix_transformers_rope_scaling_drops_theta():passreturn result- # Set explicitly as well as by wraps: the unwrap above and the tests read it, so a- # wraps-less edit must not make the patch un-probeable.+ # Set explicitly: the unwrap above and tests read __wrapped__.rope_scaling.__wrapped__ = original# The mark travels ON the setter, so a reload that drops it is re-patched.setattr(rope_scaling, _ROPE_SCALING_PATCH_FLAG, True)@@ -4344,9 +4218,8 @@ def fix_vllm_aimv2_issue():logger.info(f"Unsloth: Failed patching vLLM with error = {str(e)}")-# vLLM >= 0.22 (PR #35024) deleted vllm.transformers_utils.tokenizer, which an older-# unsloth_zoo still imports unguarded (#6385). Stub it with a meta path finder appended AFTER-# the real ones, so it only fires when vLLM no longer ships the module.+# vLLM >= 0.22 removed vllm.transformers_utils.tokenizer, which older unsloth_zoo imports;+# a stub finder appended after the real ones fills in only when missing._VLLM_LORA_TOKENIZER_MODULE = "vllm.transformers_utils.tokenizer"_VLLM_TOKENIZER_STUB_SENTINEL = "__unsloth_vllm_tokenizer_stub__"@@ -4453,10 +4326,7 @@ def fix_vllm_guided_decoding_params():def fix_trl_vllm_ascend():- # transformers >= 4.48's _is_package_available returns (bool, version_or_None), which TRL- # caches and returns directly. A non-empty tuple is truthy, so `if is_X_available():` fires- # for an absent X and triggers a failing import -- vllm_ascend blocked `from trl import- # GRPOConfig` off Ascend hosts. Coerce every tuple-cached flag to bool.+ # TRL caches transformers' (bool, version) tuple, which is always truthy; coerce to bool.if importlib.util.find_spec("trl") is None:returntry:@@ -4480,13 +4350,8 @@ def ignore_logger_messages():pass-# huggingface_hub routes to Xet on `is_xet_available()`, which asks importlib.metadata whether the-# hf_xet DISTRIBUTION is installed and never whether it IMPORTS, so an unloadable hf_xet is still-# routed to and dies as transformers' misleading "you need to install the hf_xet package".-# HF_HUB_DISABLE_XET=1 is the Hub's own way off that path, and constants.py freezes it at import-# time, which is why this is wired into the FIRST block of _gpu_init.py, not the late fixes.-# unsloth_zoo.hf_xet_fallback does not cover this: it is a stall watchdog around its own wrappers,-# and an ImportError at import time never reaches it.+# huggingface_hub routes to Xet if hf_xet metadata exists, even if it cannot import.+# HF_HUB_DISABLE_XET is frozen at import, so this runs in the first block of _gpu_init.py._CPU_FAMILY_BY_MACHINE = {"amd64": "x86_64","x86_64": "x86_64",@@ -4507,8 +4372,7 @@ _WINDOWS_PLATFORM_TAG_CPU = {"win32": "x86",}_MULTI_ARCH_PLATFORM_TAG_PREFIXES = ("macosx_", "manylinux", "musllinux", "linux_")-# Header machine ids, for installs whose WHEEL metadata cannot be read. A family absent here reads-# as "cannot tell", which is never a mismatch.+# A family absent here reads as cannot tell, never a mismatch._ELF_MACHINE_CPU = {0x03: "x86",0x15: "ppc64le",@@ -4518,8 +4382,7 @@ _ELF_MACHINE_CPU = {0xB7: "arm64",}_PE_MACHINE_CPU = {0x014C: "x86", 0x01C4: "armv7l", 0x8664: "x86_64", 0xAA64: "arm64"}-# huggingface_hub.constants.ENV_VARS_TRUE_VALUES, matched after .upper(), so an explicit disable-# is read exactly the way the Hub itself would have read it.+# Mirrors huggingface_hub ENV_VARS_TRUE_VALUES (after .upper())._HF_HUB_ENV_TRUE_VALUES = ("1", "ON", "TRUE", "YES")_MACHO_CPU_TYPE_CPU = {7: "x86", 12: "armv7l", 0x01000007: "x86_64", 0x0100000C: "arm64"}@@ -4728,17 +4591,14 @@ def fix_broken_hf_xet_wheel():"""Route Hugging Face downloads over plain HTTPS when hf_xet is installed but unimportable."""explicit = os.environ.get("HF_HUB_DISABLE_XET", "").strip()if explicit != "":- # Set explicitly, in either direction: the user's choice outranks ours. A TRUTHY value set- # after the Hub was already imported is read by nobody, though, so carry it to the frozen- # constant. Falsey values are left alone, so an explicit opt back IN to Xet still wins.+ # Explicit user setting wins. A truthy value set after the Hub imported is carried to the+ # frozen constant; falsey values are left so an opt back in still wins.if explicit.upper() in _HF_HUB_ENV_TRUE_VALUES:_disable_xet_on_already_imported_huggingface_hub()returncached = sys.modules.get("hf_xet", None)if cached is not None:- # Already imported, so it works, and repeat calls stay free. Unless it is the namespace- # shell: huggingface_hub's own `from hf_xet import ...` leaves that cached even though the- # symbols it wanted were missing, so a cached module is not proof of a working one.+ # A cached namespace shell is not proof of a working hf_xet.if _hf_xet_module_is_real(cached):returnsys.modules.pop("hf_xet", None)@@ -4749,10 +4609,7 @@ def fix_broken_hf_xet_wheel():except Exception:returnif spec is None:- # find_spec cannot see it, but huggingface_hub never asks find_spec: a leftover- # hf_xet-*.dist-info with no package beside it still reports Xet available and still dies- # in `from hf_xet import XetFileInfo`. A genuinely absent hf_xet has no metadata either- # and is left alone, since huggingface_hub handles that case correctly.+ # Leftover hf_xet dist-info without the package still reports Xet available to the Hub.if not _hf_xet_distribution_is_installed():returnsuspicion = (@@ -4765,13 +4622,7 @@ def fix_broken_hf_xet_wheel():else:return- # Confirm the suspicion by importing. If it imports after all, we misread the metadata and Xet- # stays on. Only reached for an already-suspect install, so a healthy one never pays for it.- #- # Importing the package is not enough on its own: an hf_xet/ directory with no __init__.py and- # no extension in it is a NAMESPACE package, which imports fine and defines nothing, while- # huggingface_hub does `from hf_xet import PyXetDownloadInfo, download_files` and fails. So the- # module has to carry real code, which a namespace package never does (its __file__ is None).+ # Must carry real code: a namespace hf_xet imports fine but defines nothing (__file__ is None).try:module = importlib.import_module("hf_xet")if _hf_xet_module_is_real(module):@@ -4781,8 +4632,7 @@ def fix_broken_hf_xet_wheel():except Exception as error:failure = f"{type(error).__name__}: {error}"- # The variable is what child processes inherit; the helper is what fixes THIS process when- # something already imported the Hub and froze the constant.+ # The env var covers children; the helper fixes this process if the Hub already froze it.os.environ["HF_HUB_DISABLE_XET"] = "1"_disable_xet_on_already_imported_huggingface_hub()logger.warning(@@ -4798,8 +4648,7 @@ def fix_broken_hf_xet_wheel():def patch_ipykernel_hf_xet():- # HF-XET 1.1.10 with ipykernel 7.0.0 / 7.0.1 raises LookupError on ContextVar 'shell_parent';- # see huggingface/xet-core#526.+ # hf_xet 1.1.10 with ipykernel 7.0.0/7.0.1 raises LookupError on ContextVar 'shell_parent'.if importlib.util.find_spec("hf_xet") is None:returnif importlib.util.find_spec("ipykernel") is None:@@ -4844,16 +4693,13 @@ def patch_datasets():)-# psutil divides the pmgr voltage-states tables by 1e6 for MHz, but Apple switched them from-# Hz to kHz on M4, so psutil <= 7.2.2 reads a 4.5 GHz M4 Pro as 4 MHz (#8519). Upstream fix-# giampaolo/psutil#2824 is merged and unreleased; mirrored here and in-# studio/backend/utils/hardware/hardware.py. Keep both in sync; delete once psutil is fixed.-# Apple clocks are 0.6-4.6 GHz, so a raw Hz entry sits above 1e8 and kHz below.+# psutil <= 7.2.2 reads M4 freq tables (now kHz) as Hz. Mirrored in+# studio/backend/utils/hardware/hardware.py: keep in sync; delete once psutil#2824 ships.+# Apple clocks are 0.6-4.6 GHz: a raw Hz entry is above 1e8, kHz below._APPLE_CPU_FREQ_UNIT_THRESHOLD = 100_000_000_APPLE_MIN_PLAUSIBLE_CPU_MHZ = 500_APPLE_MAX_PLAUSIBLE_CPU_MHZ = 20000-# Below this a table is a GPU/NPU rail: above every Apple GPU peak so far, under the slowest-# CPU cluster shipped (M1 E-core, 2064 MHz).+# Tables peaking below this are GPU/NPU rails; slowest CPU cluster is M1 E-core at 2064 MHz._APPLE_CPU_CLUSTER_MIN_PEAK_MHZ = 2000_APPLE_VOLTAGE_STATES_KEY = re.compile(r"^voltage-states\d+-sram$")# Fixed for the life of the host, so probe once. The sentinel separates "not probed yet" from "probed, unavailable".@@ -4905,8 +4751,7 @@ def _apple_cpu_freq_range_mhz():if _apple_cpu_freq_range != "unprobed":return _apple_cpu_freq_range- # Unlocked, every thread spawns its own ioreg and a slow failing probe landing last overwrites- # a good reading with None.+ # Probe under the lock: unlocked, each thread spawns its own ioreg, and a slow failing probe can overwrite a good reading with None.with _apple_cpu_freq_lock:if _apple_cpu_freq_range != "unprobed":return _apple_cpu_freq_range@@ -4946,8 +4791,7 @@ def _corrected_apple_cpu_freq(sample):return sample._replace(current = peak, min = low, max = peak)if not usable:return sample- # No tables: recover the magnitude instead. psutil truncates in integer arithmetic, so this- # lands on the GHz step (4 -> 4000 MHz), not the peak.+ # No tables: psutil truncates, so this lands on the GHz step, not the peak.return sample._replace(current = current * 1000,min = getattr(sample, "min", 0.0) * 1000,@@ -5006,12 +4850,10 @@ def patch_psutil_cpu_freq():try:result = original_cpu_freq(*args, **kwargs)except TypeError:- # Arguments psutil does not take are the caller's mistake, not psutil declining to answer.- # This replaces psutil's function globally, so swallowing would hide the error everywhere.+ # This replaces psutil globally, so caller argument errors must propagate.raiseexcept Exception:- # psutil raises on M5, whose renumbered tables are not at the indexes it hardcodes. With no- # tables either, its error is the honest answer.+ # psutil raises on M5 because its renumbered tables sit at other indexes; with no tables either, re-raise its error.stand_in = _from_tables(_percpu_requested(args, kwargs))if stand_in is None:raise@@ -5041,8 +4883,7 @@ def check_fbgemm_gpu_version():fbgemm_gpu_version = importlib_version("fbgemm_gpu_genai")except:return- # Lower fbgemm_gpu versions segfault or bad-alloc, so disable FBGEMM and fall back to Triton- # rather than raise.+ # fbgemm_gpu < 1.4.0 segfaults or bad-allocs; fall back to Triton.if Version(fbgemm_gpu_version) < Version("1.4.0"):os.environ["UNSLOTH_HAS_FBGEMM"] = "0"logger.info(@@ -5162,10 +5003,7 @@ def patch_enable_input_require_grads():try:inspect.signature(getter).bind()except TypeError:- # Remote code may declare get_input_embeddings(self, input_ids)- # (stepfun-ai/Step-3.7-Flash). Asked by binding, not by calling: a- # TypeError from INSIDE a working getter must propagate, not cost the- # module its input-gradient hook.+ # Checked by binding, not calling: a TypeError inside a working getter must propagate.continueexcept (ValueError, AttributeError):pass # no introspectable signature; undecidable, so just call it@@ -5278,8 +5116,7 @@ def patch_unsafe_trainer_rng_load():"(CVE-2026-1839 / CVE-2025-32434); upgrade to torch >= 2.6.")- # One process-wide torch.load shim, inert unless the calling thread is inside _load_rng_state,- # so the gate applies at the real rng load with no global-swap race.+ # One process-wide torch.load shim, inert unless the calling thread is inside _load_rng_state; a global swap would race other threads.if not getattr(torch.load, "_unsloth_rng_guard", False):_orig_load = torch.load_rng_active = threading.local()@@ -5670,8 +5507,7 @@ def _is_custom_torch_build(raw_version_str):local = raw_version_str.split("+", 1)[1]if not local:return False- # fullmatch, so the whole local identifier matches: cu/rocm need a trailing digit (cu124,- # rocm6.3), cpu/xpu are exact, and case-insensitive since some builds use uppercase.+ # fullmatch: cu/rocm need a trailing digit, cpu/xpu are exact, case-insensitive.return not re.fullmatch(r"cu\d[\d.]*|rocm\d[\d.]*|cpu|xpu", local, re.IGNORECASE)@@ -5697,21 +5533,11 @@ _TORCHVISION_ABI_MARKERS = ("torchvision.io.video","torchvision.io._video",)-# A loader failure means torchvision only when it names torchvision or the torch libraries it-# links: the probe below imports torchvision where nothing used to, so a box broken for an-# unrelated reason must keep importing unsloth, not get "reinstall torchvision".+# Require torchvision or torch libs in the message so unrelated breakage is not misdiagnosed._LOADER_FAILURE_MARKERS = ("undefined symbol", "cannot open shared object file")_TORCH_LIBRARY_MARKERS = ("torchvision", "libtorch", "libc10", "_C.so", "c10::")-# A lazily-imported torchvision with a dead extension surfaces as this, not a loader error.-# "partially initialized" is load-bearing: without it a typo on a healthy torchvision-# ("module 'torchvision' has no attribute 'nms'") would be answered with "reinstall". Nothing-# AFTER the module name is, because CPython words the rest four ways for the one fault:-# 3.9 - 3.12 partially initialized module 'torchvision' has no attribute 'extension'-# 3.13, 3.14 partially initialized module 'torchvision' from '<file>' has no attribute-# from-import cannot import name 'extension' from partially initialized module 'torchvision'-# submodule cannot access submodule 'ops' of module 'torchvision'-# The first three share "partially initialized module 'torchvision'"; the fourth names it as-# the parent instead, so it gets its own alternative.+# "partially initialized" is required so a typo on a healthy torchvision is not misread;+# the 4th alternative covers "cannot access submodule 'ops' of module 'torchvision'"._TORCHVISION_ATTRIBUTE_RE = re.compile(r"partially initialized module 'torchvision(?:\.[\w.]+)?'"r"|cannot access submodule '[\w.]+' of module 'torchvision(?:\.[\w.]+)?'"@@ -5775,20 +5601,11 @@ def _is_broken_torchvision_error(error) -> bool:return False-# PyPI carries one torchvision build per release, for one CUDA family; every other build lives-# on download.pytorch.org under an index named after torch's local tag. With --no-deps an-# unqualified pin swaps a working wheel for PyPI's and raises the very-# "operator torchvision::nms does not exist" it was handed out to clear.+# Non-default torchvision builds live on download.pytorch.org; a bare PyPI pin breaks them._TORCH_BACKEND_INDEX = re.compile(r"cpu|xpu|cu\d+|rocm\d+(?:\.\d+)*", re.IGNORECASE)-# The same families, matched as a PREFIX. A vendor build carries more than the family in its-# local tag: this repo's AMD extras install torch-2.10.0+rocm7.2.0.lw.gitb6ee5fde and-# triton-3.6.0+rocm7.2.0.gitba5c1517 straight from repo.radeon.com, and neither tag is an-# index name. Those are not PyPI builds, so advice that treats them as PyPI ones would swap a-# working Radeon wheel for the default CUDA build.+# Prefix match: vendor builds (e.g. +rocm7.2.0.lw.git...) carry more than the index name._TORCH_BACKEND_FAMILY = re.compile(r"(cpu|xpu|cu\d+|rocm[\d.]*)", re.IGNORECASE)-# conda keeps the backend in the build string (py3.12_cuda12.4_cudnn9_0) and leaves the version-# plain, so a conda torch looks like a PyPI one by version alone; its-# conda-meta/<name>-<version>-<build>.json tells them apart.+# conda keeps the backend in the build string, so check conda-meta to tell it from PyPI._CONDA_TORCH_PACKAGES = ("pytorch", "pytorch-cpu", "pytorch-gpu", "libtorch")@@ -5801,8 +5618,7 @@ def _torch_local_tag(torch_version_raw):def _is_conda_managed(names, version_raw):"""Did conda install one of `names` at this version, rather than pip?"""conda_meta = os.path.join(sys.prefix, "conda-meta")- # A conda version never carries the +tag, but strip it so a pip install inside a conda prefix is- # still matched on its release numbers.+ # Strip any +tag so a pip install inside a conda prefix still matches on its release numbers.version = (version_raw or "").split("+", 1)[0]if not version or not os.path.isdir(conda_meta):return False@@ -5829,8 +5645,7 @@ def _has_no_matching_public_wheel(torch_version_raw):return Truelocal = _torch_local_tag(torch_version_raw)if not local:- # An absent tag means PyPI for a pip install, but conda never writes one either, and its torch- # may be CPU, ROCm or a CUDA family PyPI does not ship.+ # No tag means PyPI for pip, but conda never writes one either.return _torch_is_conda_managed(torch_version_raw)return not _TORCH_BACKEND_INDEX.fullmatch(local)@@ -5882,10 +5697,7 @@ def _torch_accelerator_note(torch_version_raw):"""local = _torch_local_tag(torch_version_raw)if not local:- # conda never writes a local tag, so an untagged version alone reads like a PyPI- # install. `pip install --upgrade torch` into a conda environment overlays the- # conda-managed files with a PyPI wheel, and the backend it lands on is whatever- # PyPI ships by default rather than the one the channel built.+ # pip install --upgrade torch into conda overlays conda's files with PyPI's default backend.if _torch_is_conda_managed(torch_version_raw):return (" conda installed this torch, so upgrade it the same way "@@ -5898,10 +5710,7 @@ def _torch_accelerator_note(torch_version_raw):vendor = _TORCH_BACKEND_FAMILY.match(local)if vendor is None:return ""- # A tag that names a family but is not an index name is a vendor build, which is- # what this repo's own AMD extras install. PyPI has no such version, and neither- # does download.pytorch.org, so the only advice that keeps the accelerator is to- # go back to the source the wheel came from.+ # A family tag that is not an index name is a vendor build: reinstall from its source.return (f" That takes the default build from PyPI. This torch is a {local} build, "f"which no public index carries, so upgrade it from wherever it came from "@@ -5943,8 +5752,7 @@ def _torchvision_repair_command(required = None, torch_version_raw = None):if required is None:spec = "torchvision"elif len(required) >= 3:- # Exact, because the pair is: torchvision 0.22.0 needs torch 2.7.0 and 0.22.1 needs 2.7.1, so- # a 0.22.* wildcard resolves 0.22.1 while --no-deps keeps the mismatched torch.+ # Exact pin: torch 2.7.0 needs 0.22.0, 2.7.1 needs 0.22.1, and --no-deps keeps torch.spec = f"torchvision=={required[0]}.{required[1]}.{required[2]}"else:spec = f"torchvision=={required[0]}.{required[1]}.*"@@ -5975,8 +5783,7 @@ def _probe_torchvision_binary(except Exception as error:shadow = _shadowing_torchvision_path()if shadow is not None and _TORCHVISION_ATTRIBUTE_RE.search(str(error)):- # Named: the metadata says torchvision is installed and it is, so a reinstall- # changes nothing. The file is the whole fix.+ # Metadata says torchvision is installed and it is, so a reinstall changes nothing; the file is the whole fix.raise ImportError(f"Unsloth: {shadow} is being imported as `torchvision`, ahead of the "f"installed package ({type(error).__name__}: {error}). Rename or move that "@@ -6040,8 +5847,7 @@ def torchvision_compatibility_check():if required is None:return- # Carry torch's own patch into the companion: they move together (2.7.0/0.22.0, 2.7.1/0.22.1),- # so the repair names one wheel instead of a minor-wide range --no-deps cannot satisfy.+ # Pin torchvision to torch's patch number too, since they move together (2.7.1/0.22.1); a minor-wide range fails under --no-deps.if len(torch_release) >= 3:required = (required[0], required[1], torch_release[2])@@ -6068,15 +5874,13 @@ def torchvision_compatibility_check():torchvision_version_raw)- # Nightly/dev/alpha/beta/rc builds mismatch expectedly, so those and source builds only warn;- # a stable mismatch fails fast to prevent runtime operator errors.+ # Prerelease and source builds only warn; stable mismatches fail fast._pre_tags = (".dev", "a0", "b0", "rc", "alpha", "beta", "nightly")is_prerelease = any(t in torch_version_raw for t in _pre_tags) or any(t in torchvision_version_raw for t in _pre_tags)- # Only downgrade to warning for custom/source or prerelease builds. Stable mismatches should fail fast to- # prevent runtime operator errors.+ # Only custom/source and prerelease builds downgrade to a warning; stable mismatches fail fast to avoid runtime operator errors.if is_custom or is_prerelease:reason = "custom/source build" if is_custom else "pre-release build"logger.warning(@@ -6118,8 +5922,7 @@ def _unsatisfied_transformers_requirements():except Exception:continue # Unparseable requirement line - ignore it, never guess.- # extra = "" drops optional-extra requirements and inapplicable python_version / sys_platform- # gates: packages the user is right not to have.+ # extra = "" drops optional-extra and inapplicable platform requirements.if requirement.marker is not None:try:if not requirement.marker.evaluate({"extra": ""}):@@ -6130,8 +5933,7 @@ def _unsatisfied_transformers_requirements():try:installed = importlib_version(requirement.name)except PackageNotFoundError:- # Absent, which --no-deps causes as readily as a stale version: transformers checks its base- # requirements at root import and raises PackageNotFoundError with the same misleading hint.+ # Absent (e.g. after --no-deps) also triggers transformers' misleading root-import error.unsatisfied.append((requirement.name, str(requirement.specifier), None))continueexcept Exception:@@ -6141,8 +5943,7 @@ def _unsatisfied_transformers_requirements():continue # Installed, and no floor it could fall below.try:- # Parse explicitly: SpecifierSet.contains() reports a non-PEP440 version as "not contained"- # rather than raising, which would be a false positive.+ # Parse explicitly: SpecifierSet.contains() treats non-PEP440 as not contained.installed_version = TrueVersion(installed)except Exception:continue # Not a PEP 440 version - we cannot judge it, so stay quiet.@@ -6176,8 +5977,7 @@ def check_transformers_dependency_versions():):returntry:- # find_spec RAISES ValueError rather than returning None for a transformers in sys.modules with- # __spec__ None or unset (a stub, or one mid-teardown). Not worth failing the import over.+ # find_spec raises ValueError when transformers in sys.modules has no __spec__.if importlib.util.find_spec("transformers") is None:returnexcept Exception:@@ -6220,20 +6020,13 @@ def check_transformers_dependency_versions():logger.warning("\n".join(lines))-# torch releases that first provide a given attribute, used only to name the-# upgrade in the message below. Measured against the wheels rather than guessed:-# torch 2.6.0 has neither MX dtype and 2.8.0 has both, and both landed in 2.7.0-# (pytorch/pytorch#146427 and #146578). An attribute that is not in here still-# gets the diagnosis, just without a release to name, which is the point: the-# table is a convenience and never the mechanism.+# Only names the upgrade in the message; MX dtypes landed in torch 2.7.0._TORCH_ATTRIBUTE_FLOORS = {"float8_e8m0fnu": "2.7.0","float4_e2m1fn_x2": "2.7.0",}-# Packages unsloth imports and cannot add a missing torch attribute to. The same-# AttributeError raised from user code is a typo, so it is left exactly as torch-# wrote it.+# The same AttributeError from user code is a typo, so only these packages get the diagnosis._TORCH_ATTRIBUTE_DEPENDENTS = frozenset(("accelerate",@@ -6284,8 +6077,7 @@ def _installed_version(package):def _torch_too_old_message(attribute, package, exception):- # torch.__version__ rather than the metadata version, because it carries the- # build (2.6.0+cu124) and that is what the user reads in every other message.+ # Use torch.__version__ over the metadata version: it carries the build tag (2.6.0+cu124) users see elsewhere.torch_version = getattr(sys.modules.get("torch"), "__version__", None)if not torch_version:torch_version = _installed_version("torch")@@ -6302,8 +6094,7 @@ def _torch_too_old_message(attribute, package, exception):f"a {package} with a torch that cannot serve it.",]if floor is not None:- # A known floor is evidence of the direction: the attribute was ADDED in that- # release, so the torch here is the older half and upgrading it is the remedy.+ # A known floor means the attribute was added in that release, so this torch is the older side and upgrading is the remedy.lines += [f"torch.{attribute} first appears in torch {floor}, so this torch is the "f"older half.",@@ -6312,10 +6103,7 @@ def _torch_too_old_message(attribute, package, exception):f" pip install --upgrade {requirement}{_torch_companion_specs()}",]else:- # No floor is no evidence of direction. The attribute may be newer than this- # torch, and it may equally have been REMOVED by it, which an older dependency- # reaching for a retired API hits; prescribing an upgrade there is the opposite- # remedy. So state both directions and prescribe neither.+ # No known floor: the attribute may be newer or removed, so prescribe neither direction.lines += ["",f"torch.{attribute} is not in this release's table of added attributes, so "@@ -6367,14 +6155,12 @@ def patch_torch_missing_attribute_error():try:import torchexcept Exception:- # A missing or broken torch has its own, clearer error further down- # _gpu_init.py; there is nothing to wrap here.+ # A missing or broken torch raises its own clearer error later in _gpu_init.py, so there is nothing to wrap here.return Falseoriginal = torch.__dict__.get("__getattr__")if original is None:- # No module-level __getattr__ to wrap, so torch raises its AttributeError- # from the interpreter itself and there is nothing to improve.+ # Without a module-level __getattr__, torch raises AttributeError itself and there is nothing to improve.return Falseif getattr(original, "__unsloth_patched__", False):return True@@ -6397,17 +6183,10 @@ def patch_torch_missing_attribute_error():return original(name)except AttributeError as exception:try:- # The frame that made the access, and only that one. Walking- # further up would blame transformers for a typo in a callback- # transformers happened to call.+ # Only the direct caller frame; walking up would blame transformers for a callback typo.requester = sys._getframe(1).f_globals.get("__name__") or ""except Exception:- # sys._getframe is CPython-only and raises an audit event, so a- # hardened interpreter can refuse it. A bare `raise` here would- # rethrow THAT exception instead of torch's AttributeError, and- # `hasattr(torch, name)` only swallows AttributeError, so an- # ordinary feature probe would start propagating a RuntimeError.- # Unattributable is not fatal: leave it to torch's own error.+ # sys._getframe can be refused by audit hooks; re-raising would replace AttributeError.requester = ""package = requester.split(".", 1)[0]if package not in _TORCH_ATTRIBUTE_DEPENDENTS:@@ -6422,12 +6201,10 @@ def patch_torch_missing_attribute_error():return True-# The '#' argument formats in triton's CUDA driver shim need this macro, and-# CPython stopped requiring it in 3.13.+# Triton's CUDA driver shim needs this macro for '#' formats; CPython 3.13 dropped the need._PY_SSIZE_T_CLEAN = "PY_SSIZE_T_CLEAN"-# `#define` / `#undef PY_SSIZE_T_CLEAN` as their own directives, anchored to the start of-# a line so a mention inside a comment or a string literal is neither.+# Match only real define or undef directives for PY_SSIZE_T_CLEAN, anchored to line start so comments and strings are skipped._PY_SSIZE_T_CLEAN_DIRECTIVE = re.compile(r"^[ \t]*#[ \t]*(define|undef)[ \t]+" + _PY_SSIZE_T_CLEAN + r"\b",re.M,@@ -6520,12 +6297,8 @@ def _defines_py_ssize_t_clean_before_python_h(source: str) -> bool:return state-# Every distribution this repository knows of that provides the `triton` import name. Only a-# fallback for interpreters without `packages_distributions`; the mapping is asked for first-# wherever it exists, so a provider added upstream is still found on 3.10 and later.-# Providers published only on download.pytorch.org, so a reinstall of one needs torch's own-# accelerator index rather than PyPI. `pytorch-triton*` is matched by prefix; these are the-# renamed spellings that prefix no longer covers.+# Fallback when packages_distributions is unavailable. Renamed torch-index-only providers+# that the `pytorch-triton*` prefix does not cover._TORCH_INDEX_TRITON_PROVIDERS = ("triton-xpu", "triton-rocm")_TRITON_PROVIDERS = (@@ -6534,11 +6307,7 @@ _TRITON_PROVIDERS = ("pytorch-triton","pytorch-triton-rocm","pytorch-triton-xpu",- # The renamed spellings. Both accelerator providers were renamed on- # download.pytorch.org: `pytorch-triton-rocm` stops at 3.5.1 and `triton-rocm` carries- # 3.7 onwards, the same split `pytorch-triton-xpu` and `triton-xpu` have. Missing here,- # a current ROCm or XPU shim reads as `triton==unknown` on the probing fallback, and- # the repair command then installs generic CUDA `triton` over the installed provider.+ # Missing these, ROCm/XPU shims read as triton==unknown and repair installs CUDA triton."triton-xpu","triton-rocm",)@@ -6605,19 +6374,12 @@ def _distribution_owning_path(names, path):return claimants[0]if not claimants:return None- # Coexisting providers can both RECORD the same file, and then the first entry is- # nothing but ordering. Three tiebreaks, most authoritative first.- #- # 1. The distribution torch itself requires. A renamed provider leaves the old- # dist-info behind (`pytorch-triton-xpu` beside `triton-xpu` after an upgrade), so- # both claim the file and both name the backend; only torch says which one belongs- # to the torch that is installed.+ # Coexisting providers can RECORD the same file; tiebreak 1: what torch requires.required = _torch_required_triton_distributions()named = [name for name in claimants if _canonical_distribution(name) in required]if len(named) == 1:return named[0]- # 2. Failing that, torch's backend family, because the harmful answer is always the one- # that installs a CUDA build over an accelerator one.+ # 2. torch's backend family, so we never install CUDA triton over an accelerator build.local = _torch_local_tag(getattr(sys.modules.get("torch"), "__version__", None)).lower()for family in ("xpu", "rocm"):if family in local:@@ -6651,12 +6413,7 @@ def _triton_distribution(offending_path = None):except Exception:names = []if not names:- # `packages_distributions` is Python 3.10+, and pyproject still admits 3.9, where- # the import above raises and leaves this empty -- reporting `triton==unknown` and- # recommending the CUDA `triton` over the platform build, which is the exact- # failure this helper exists to avoid. The backport answers the same question when- # it is installed; when it is not, ask each provider directly, which needs no- # mapping at all: a provider that is not installed has no version to report.+ # packages_distributions needs 3.10+; on 3.9 the fallback avoids reporting triton==unknown and advising CUDA tritontry:from importlib_metadata import packages_distributions as _backportnames = list(_backport().get("triton") or [])@@ -6664,13 +6421,11 @@ def _triton_distribution(offending_path = None):names = []if not names:names = [name for name in _TRITON_PROVIDERS if _installed_version(name) != "unknown"]- # The distribution that actually ships the offending file wins over ordering, when the- # file is known and the metadata answers.+ # The distribution that ships the offending file is tried first, ahead of list order, when metadata identifies it.owner = _distribution_owning_path(names, offending_path)if owner is not None:names = [owner] + [name for name in names if name != owner]- # Prefer a provider that can actually report a version; a stale empty dist-info- # otherwise wins over the real one purely on ordering.+ # Prefer a provider with a version: a stale empty dist-info could otherwise win on order.for name in names:try:return name, importlib_version(name)@@ -6694,10 +6449,7 @@ def _triton_reinstall_command(distribution, triton_version):pin to give, and an invented one would resolve to nothing at all, so that case stays bare."""index = ""- # `triton-xpu` as well as `pytorch-triton-*`: torch 2.10 renamed the XPU provider and- # pyproject pins the new name straight from download.pytorch.org (studio/setup.ps1- # records the rename too). Matching only the old spelling asked PyPI for `triton-xpu`,- # where that pinned wheel is not published at all.+ # torch 2.10 renamed the XPU provider to triton-xpu, published only on download.pytorch.org.if distribution.startswith("pytorch-triton") or distribution in _TORCH_INDEX_TRITON_PROVIDERS:torch_version_raw = getattr(sys.modules.get("torch"), "__version__", None)index = _torch_wheel_index(torch_version_raw)@@ -6719,10 +6471,7 @@ def _triton_repair_advice(distribution, triton_version):"""command = _triton_reinstall_command(distribution, triton_version)if _is_conda_managed((distribution,), triton_version):- # conda-forge publishes `triton`, and a pip --force-reinstall over a conda-managed- # one overlays conda's own files with a wheel, leaving two package managers owning- # the same paths. Same reasoning, and same remedy shape, as the conda branch of the- # torch upgrade advice.+ # pip over a conda-managed triton leaves two package managers owning the same files.return (f"conda installed this Triton, so repair it the same way "f"(`conda install --force-reinstall {distribution}={triton_version}` on the "@@ -6888,8 +6637,7 @@ def _transformers_rescopes_submodule_prefix_renamings():try:from transformers import core_model_loadingexcept Exception:- # Separate import, allowed to fail: it needs torch, and the two spellings it carries- # are extra evidence. The signature check below has to stand on its own.+ # Separate import that may fail (it needs torch); the two spellings are extra evidence, so the signature check must stand alone.core_model_loading = Noneif core_model_loading is not None:transform = getattr(core_model_loading, "WeightTransform", None)@@ -6942,13 +6690,7 @@ def check_transformers_prequantized_vlm_quant_state():except Exception:transformers_version = "unknown"- # The runtime repair covers exactly these releases, and it is installed in the same- # import. Warning anyway would tell users to downgrade or upgrade away from a version- # that now works, which is worse than saying nothing: the advice contradicts the fix.- # Checked on the live attribute, so a repair that declined to install still warns.- # Either repair counts: when unsloth_zoo installed its copy first,- # `fix_transformers_composite_prefix_renaming` deliberately yields and the live function- # carries the zoo mark instead of ours, which is repaired all the same.+ # Do not warn when either repair (ours or unsloth_zoo's) is live: the advice would contradict it.if _composite_prefix_renaming_repaired():return@@ -7231,8 +6973,7 @@ def fix_triton_compiled_kernel_missing_attrs():except (ImportError, ModuleNotFoundError):return- # Only needed when CompiledKernel lacks num_ctas as a direct attr but has metadata- # (triton >= 3.6.0 with torch < 2.10).+ # Only needed for triton >= 3.6.0 with torch < 2.10 (num_ctas only in metadata)._ck_cls = triton_compiler.CompiledKernelif hasattr(_ck_cls, "num_ctas"):return@@ -7406,8 +7147,8 @@ def fix_dynamo_config_thread_visibility():mirrored_modules = ("torch._dynamo.config", "torch._inductor.config")- # config.patch() and config.load_config() also assign via __setattr__, but their writes are- # thread-local by design, so a per-thread depth counter keeps them out of the global default.+ # config.patch()/load_config() writes are thread-local by design; a per-thread depth counter+ # keeps them out of the global default.import threading_scoped_depth = threading.local()@@ -7490,9 +7231,7 @@ def fix_dynamo_config_thread_visibility():_patched_setattr.__unsloth_patched__ = TrueConfigModule.__setattr__ = _patched_setattr- # No replay of existing overrides: unsloth installs this before setting any dynamo/inductor- # config, so the wrapper mirrors every later assignment, and replaying would bake a- # still-active config.patch override into the global default.+ # No replay of existing overrides: it could bake an active config.patch into the default.logger.info("Unsloth: Patched torch config modules so dynamo/inductor settings ""(e.g. recompile_limit) apply across threads on torch >= 2.12."@@ -7985,9 +7724,7 @@ def patch_torchcodec_audio_decoder():pass-# torch.minor -> compatible torchcodec.minor strings (see notebook_validator.py).-# torchcodec ships no `Requires-Dist: torch`, so pip cannot catch a mismatch and this table-# is the only check. Lockstep releases only; 0.12+ is the ABI-stable rule below.+# torchcodec ships no Requires-Dist on torch, so this table is the only check; it lists lockstep releases only_TORCH_TORCHCODEC_MINORS: dict[str, set[str]] = {"2.11": {"0.11"},"2.10": {"0.10"},@@ -8005,9 +7742,7 @@ _TORCH_TORCHCODEC_EXTRAS: dict[str, str] = {"2.10": "audio-torch210",}-# torchcodec 0.12+ is ABI-stable against torch >=2.11 (its build sets TORCH_TARGET_VERSION-# to 2.11), so that half of the matrix is open-ended rather than a finite set of minors.-# Mirrors notebook_validator.TORCHCODEC_ABI_STABLE_{TORCH,CODEC}.+# torchcodec 0.12+ is ABI-stable against torch >= 2.11, so that half of the matrix is open-ended_TORCHCODEC_ABI_STABLE_TORCH = (2, 11)_TORCHCODEC_ABI_STABLE_CODEC = (0, 12)@@ -8039,15 +7774,11 @@ def _torch_index_url_for_remedy(local_tag: str) -> str:mirror is where the matching build actually is."""if os.environ.get("UNSLOTH_TORCH_INDEX_URL", "").strip():- # The variable, not its value: an authenticated mirror carries credentials in its- # userinfo or query token, and this warning lands in terminals and CI logs. The- # shell expands it, so the command still works and nothing is written down.+ # The variable, not its value: mirror URLs may carry credentials and this lands in logs.return _shell_env_ref("UNSLOTH_TORCH_INDEX_URL")leaf = os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY", "").strip().strip("/") or local_tagif os.environ.get("UNSLOTH_PYTORCH_MIRROR", "").strip():- # UNSLOTH_PYTORCH_MIRROR replaces the base every install_python_stack index is built- # from, so naming the public site fails on an air-gapped host. Expanded, not disclosed,- # as above.+ # UNSLOTH_PYTORCH_MIRROR replaces the base of every install_python_stack index, so naming the public site fails on an air-gapped host.return f"{_shell_env_ref('UNSLOTH_PYTORCH_MIRROR')}/{leaf}"return f"https://download.pytorch.org/whl/{leaf}"@@ -8068,9 +7799,7 @@ def _torchcodec_version_mismatch_hint() -> str | None:return tuple(parts[:2]) + (0,) * (2 - len(parts[:2]))def _at_least(version: str, floor: tuple) -> bool:- # The FULL Version, not its release tuple: PEP 440 sorts `2.11.0rc1` below `2.11`,- # while `.release` drops the rc and read it as being at the ABI floor. That approved a- # pairing outside the ABI-stable contract and silenced this hint on it.+ # Full Version, not .release: 2.11.0rc1 sorts below 2.11 and is outside the ABI contract.return Version(version.split("+", 1)[0]) >= Version(".".join(str(p) for p in floor))try:@@ -8103,8 +7832,7 @@ def _torchcodec_version_mismatch_hint() -> str | None:allowed = _TORCH_TORCHCODEC_MINORS.get(torch_minor)if allowed is None:- # No lockstep row: below the table stays silent; at or past the ABI floor this is a- # pre-0.12 codec, since 0.12+ already returned above.+ # No lockstep row for this torch: silent below the ABI floor, and at or above it the codec must be pre-0.12.if not torch_at_abi:return Noneabi_pin = ".".join(str(p) for p in _TORCHCODEC_ABI_STABLE_CODEC)@@ -8118,9 +7846,7 @@ def _torchcodec_version_mismatch_hint() -> str | None:upper = _torchcodec_exclusive_upper(pin)install_hint = f"`pip install {_index_flag(tuple(int(x) for x in pin.split('.')))}'torchcodec>={pin},{upper}'`"extra = _TORCH_TORCHCODEC_EXTRAS.get(torch_minor)- # Only when no index pin is needed. An extra cannot carry one -- the marker picks the- # version, not the index -- and --index-url on the whole command would resolve unsloth- # from the torch index too, handing back the same unloadable wheel.+ # An extra cannot carry an index pin, and --index-url would resolve unsloth from it too.if extra is not None and not _index_flag(tuple(int(x) for x in pin.split("."))):install_hint += f" or `pip install 'unsloth[{extra}]'`"return (@@ -8176,9 +7902,7 @@ def _torchcodec_provenance_hint() -> "str | None":return None # rocm and xpu publish no torchcodec under this nameindex = _torch_index_url_for_remedy(torch_local)codec_from = codec_local or "the default index"- # The window the table allows, not a bare name: the accelerator indexes carry the whole- # codec line, so `pip install torchcodec` on torch 2.9 trades a wrong-accelerator build- # for a wrong-VERSION one and audio stays disabled. Past the table, the ABI floor pins.+ # Pin the version window: a bare torchcodec on an accelerator index gets a wrong-version buildtry:from packaging.version import Versionparts = Version(str(torch.__version__).split("+", 1)[0]).release@@ -8194,9 +7918,7 @@ def _torchcodec_provenance_hint() -> "str | None":want = f"'torchcodec>={abi}.0'"else:want = "torchcodec"- # "may be", not "is": this only establishes different indexes. torchcodec is published- # per accelerator on every line, 0.12+ included, so a mismatch stays possible -- but the- # load can equally have failed on a missing libavutil, which no reinstall fixes. Name both.+ # Different indexes only make a mismatch possible; a missing libavutil is equally likely.return (f"torchcodec {codec_version or '?'} came from {codec_from} while "f"torch {getattr(torch, '__version__', '?')} is a {torch_local} build, so the codec "@@ -8273,8 +7995,7 @@ def disable_torchcodec_if_broken():import warningswarnings.warn(mismatch_hint, stacklevel = 3)except Exception:- # Warning filters promoted to errors (PYTHONWARNINGS=error, pytest -W error) must not abort the- # disable fallback below.+ # Warnings promoted to errors must not abort the disable fallback below.passtry:@@ -8283,8 +8004,7 @@ def disable_torchcodec_if_broken():_warn_mismatch()return # absent or already disabled- # RuntimeError on dlopen failure, OSError on chained libavutil.so misses, and a damaged or- # version-skewed wheel can raise anything else; the package is present, so every shape is "broken".+ # A broken wheel can raise anything; the package is present, so every shape is broken.from torchcodec.decoders import AudioDecoderexcept Exception as load_error:remedy_hint = mismatch_hint@@ -8322,8 +8042,7 @@ def disable_torchcodec_if_broken():except ImportError:pass- # Drop half-loaded entries and seat the absence sentinel: after this, `import torchcodec` raises- # ModuleNotFoundError and find_spec returns None.+ # Seat the absence sentinel so import raises ModuleNotFoundError and find_spec returns None.for _stale in [nfor n in list(sys.modules)@@ -8361,8 +8080,7 @@ def _audio_av_open(av, source):except TypeError as exc:if "metadata_errors" not in str(exc):raise- # format = None is PyAV's own default (probe the container); spelling it keeps this call- # distinguishable from Path.open for the text-encoding lint.+ # format = None spelled out to distinguish this from Path.open for the encoding lint.return av.open(source, mode = "r", format = None)@@ -8636,10 +8354,7 @@ def disable_torchaudio_if_cuda_mismatched():tf_import_utils._torchaudio_available = Falseexcept AttributeError:pass- # `speech` is transformers' composite backend and is nothing but torchaudio (is_speech_available- # returns is_torchaudio_available()). On 4.x both read one module global; on 5.x each is- # separately lru_cached, so an answer computed before this repair stays True and- # requires_backends(..., "speech") waves callers into a torchaudio that is now a None sentinel.+ # On 5.x is_speech_available is separately lru_cached, so clear both or speech stays True.for _name in ("is_torchaudio_available", "is_speech_available"):is_avail = getattr(tf_import_utils, _name, None)if is_avail is None:@@ -8751,8 +8466,7 @@ def disable_broken_wandb():tf_integration.is_wandb_available = _wandb_falseexcept (ImportError, AttributeError):pass- # Patch accelerate.utils.imports and the accelerate.utils re-export, since- # `from accelerate.utils import is_wandb_available` reads the latter.+ # Patch accelerate.utils.imports and the accelerate.utils re-export; `from accelerate.utils import is_wandb_available` reads the latter.try:import accelerate.utils.imports as acc_importsacc_imports.is_wandb_available = _wandb_false@@ -8766,12 +8480,10 @@ def disable_broken_wandb():os.environ["WANDB_DISABLED"] = "true"-# peft 0.19.x's transformers_weight_conversion.py imports transformers.conversion_mapping and-# transformers.core_model_loading at module top; neither exists on transformers <5, so the-# import raises ModuleNotFoundError, swallowed by the bare except below. Stub the two-# submodules only when broken; peft calls them only behind `if is_transformers_ge_v5:`.+# peft 0.19.x imports transformers.conversion_mapping/core_model_loading, absent on <5;+# stub them only when broken.-# Stamped on stub modules so a second call is a strict no-op and third parties can introspect __unsloth_stub__.+# Stamped on stub modules so a second call is a strict no-op.# ---------------------------------------------------------------------------_UNSLOTH_STUB_SENTINEL = "__unsloth_stub__"@@ -9071,8 +8783,7 @@ def _install_transformers_core_model_loading_stub():return mod-# Names peft's transformers_weight_conversion imports at module top; a real module missing ANY-# of them breaks that import as hard as an absent one.+# Names peft's transformers_weight_conversion imports at module top; a real module missing any breaks it like an absent one._PEFT_REQUIRED_SYMBOLS = {"transformers.conversion_mapping": ("_MODEL_TO_CONVERSION_PATTERN",@@ -9129,8 +8840,7 @@ def _backfill_missing_peft_symbols(name):return tuple(added)-# An empty pattern is peft's own starting point; the rest stand in for real upstream-# behaviour, so those are worth warning about.+# An empty pattern is peft's own starting point; the rest stand in for real upstream behaviour, so those are worth warning about._PEFT_INERT_BACKFILL_IS_FINE = frozenset(("_MODEL_TO_CONVERSION_PATTERN",))@@ -9205,13 +8915,10 @@ def fix_peft_transformers_weight_conversion_import():_install_transformers_core_model_loading_stub()patched_any = True- # Present but incomplete: transformers 5.x kept both modules and dropped names peft still- # imports at module top. The stubs above only fire when a module is ABSENT, so backfill the- # missing names onto the real module, which is strictly additive.+ # transformers 5.x kept both modules but dropped names peft imports; backfill them.patched_any = _backfill_missing_conversion_symbols() or patched_any- # An importable submodule can still lack individual symbols; backfill just those rather than- # replacing a real module wholesale.+ # An importable submodule can still lack single symbols; backfill just those instead of replacing the module wholesale.backfilled = {}for _submodule in _PEFT_REQUIRED_SYMBOLS:added = _backfill_missing_peft_symbols(_submodule)@@ -9247,8 +8954,7 @@ def fix_peft_transformers_weight_conversion_import():return True-# What peft.utils.transformers_weight_conversion imports at module top, kept beside the stubs-# so the two lists cannot drift apart.+# Names peft.utils.transformers_weight_conversion imports at module top; kept beside the stubs_PEFT_CONVERSION_SYMBOLS = {"transformers.conversion_mapping": ("_MODEL_TO_CONVERSION_PATTERN",@@ -9267,20 +8973,14 @@ _PEFT_CONVERSION_SYMBOLS = {),}-# Of those, the ones peft calls rather than merely imports. The stubs are deliberately inert: on-# transformers <5 the whole module is ours and peft's converter never runs. An inert body on a REAL-# transformers is a different matter, since peft would call it and get a wrong answer, so those get a-# placeholder that says what is wrong instead.+# Symbols peft calls; on a real transformers an inert stub would answer wrongly, so raise._PEFT_CONVERSION_RUNTIME_SYMBOLS = frozenset(("transformers.core_model_loading.dot_natural_key","transformers.core_model_loading.rename_source_key","transformers.core_model_loading.WeightRenaming","transformers.core_model_loading.WeightConverter",- # build_peft_weight_mapping buckets entries with isinstance(op, Concatenate) /- # isinstance(op, MergeModulelist) and builds Transpose outright, so an inert stub silences the- # isinstance arms and the conversion is skipped. ConversionOps stays import-only: peft- # subclasses it and never asks about instances.+ # peft uses isinstance on these, so an inert stub silently skips conversion."transformers.core_model_loading.Concatenate","transformers.core_model_loading.MergeModulelist","transformers.core_model_loading.Transpose",@@ -9307,9 +9007,7 @@ def _unsupported_conversion_symbol(qualified, donor_value = None):"transformers that still exports it, or a peft that does not need it.")if isinstance(donor_value, type):- # isinstance has to raise, not answer False: peft buckets conversion entries by type, and a- # placeholder that quietly matches nothing drops the operations instead of reporting that it- # cannot do the job. Subclassing still works, since creating a class constructs nothing.+ # isinstance must raise, not answer False, or peft drops the operations silently.class _RefusingMeta(type):def __instancecheck__(cls, instance):raise RuntimeError(message)@@ -9334,14 +9032,9 @@ def _unsupported_conversion_symbol(qualified, donor_value = None):return _refuse-# The model types peft acts on, snapshotted from conversion_mapping._MODEL_TO_CONVERSION_PATTERN-# because the case handled here is that map being gone. A list and not a rule: deepseek_v3,-# dots1, longcat_flash, minimax, mellum, qwen3_next, solar_open and flex_olmo are all fused MoE-# and none of them say so.+# Snapshot of the conversion map for when it is gone; many fused MoE types lack 'moe' in name._PEFT_MOE_CONVERSION_PATTERNS = {- # The two base patterns map to themselves, and omitting them was not harmless: mixtral says- # nothing about MoE, so the substring hint answered the default and the drift test failed on- # transformers 5.5.0. qwen3_5_moe is here for 5.3.0, where it is a separate key.+ # Base patterns map to themselves; mixtral lacks 'moe'. qwen3_5_moe is separate on 5.3.0."mixtral": "mixtral","qwen2_moe": "qwen2_moe","qwen3_5_moe": "qwen2_moe",@@ -9363,9 +9056,7 @@ _PEFT_MOE_CONVERSION_PATTERNS = {"glm_moe_dsa": "qwen2_moe","hunyuan_v1_moe": "qwen2_moe","longcat_flash": "qwen2_moe",- # Not a transformers type: unsloth/models/longcat_lsa.py registers it into transformers' and- # peft's tables with longcat_flash's family, so once that has run in a process the live map- # carries it and the snapshot has to agree.+ # Registered by unsloth/models/longcat_lsa.py, so the snapshot must agree with the live map."longcat_flash_lsa": "qwen2_moe","mellum": "qwen2_moe","olmoe": "qwen2_moe",@@ -9396,10 +9087,7 @@ _PEFT_MOE_NAMED_NOT_FUSED = frozenset())-# The other half of the carve-out: MoE-named types not in the conversion map AT ALL, where-# peft's .get() answers None and skips the rewrite, so a refusal breaks an ordinary adapter-# load (qwen3_vl_moe, lfm2_moe). A name absent from only one of 5.3.0 / 5.5.0 stays fused:-# refusing a fused type costs a message, answering None is a silent mis-conversion.+# MoE types missing from the map: peft get returns None so raising breaks loads; missing from one version only stays fused_PEFT_MOE_NAMED_NOT_CONVERTED = frozenset(("ernie4_5_vl_moe",@@ -9414,8 +9102,7 @@ _PEFT_MOE_NAMED_NOT_CONVERTED = frozenset())-# How many pairs a candidate map must match before we believe it is the conversion map under a-# new name. Three: a coincidence does not pass, a few renamed types still do.+# Matches needed to accept a renamed map; three rules out coincidence._CONVERSION_MAP_MATCHES = 3@@ -9475,10 +9162,7 @@ class _UnavailableConversionPatternMap(dict):"peft that does not need the conversion.")- # Only fused-MoE lookups are unsafe to answer with a silent None: peft reaches- # _convert_peft_config_moe for any type with a conversion mapping, and there None is what the- # real map gives too, so raising for all would break ordinary adapter loads. The substring- # hints sit on top of the snapshot, for a fused type added later that follows the convention.+ # Only fused-MoE lookups are unsafe to answer with None; raising for all breaks normal loads._MOE_HINTS = ("moe", "mixtral")def _is_moe(self, key):@@ -9539,14 +9223,12 @@ def _backfill_conversion_symbols_once(builders, added):missing = [s for s in symbols if not hasattr(real, s)]if not missing:continue- # Build the stub off to the side rather than installing it, so the real module keeps its- # identity and everything else it exports.+ # Build the stub off to the side rather than installing it, so the real module keeps its identity and its other exports.donor = builders[name]()for symbol in missing:qualified = f"{name}.{symbol}"if symbol == "_MODEL_TO_CONVERSION_PATTERN":- # peft copies this and looks families up in it, so the stub's empty dict silently drops every- # alias. Recover the real one.+ # The stub's empty dict silently drops every alias peft looks up; recover the real one.recovered = _recover_conversion_pattern_map(real)if recovered is None:logger.warning(@@ -9555,10 +9237,7 @@ def _backfill_conversion_symbols_once(builders, added):"targets for fused MoE checkpoints. Adapters for other ""architectures are unaffected.")- # An empty dict is the one shape that fails SILENTLY: peft does- # _MODEL_TO_CONVERSION_PATTERN.copy() at import then .get(model_type, None), and a None makes- # _convert_peft_config_moe return early, so every affected adapter loads with legacy targets- # unconverted and no message anywhere.+ # Empty dict fails silently: peft's .get(model_type, None) returns None, so MoE adapters load with legacy targets unconverted.setattr(real,symbol,@@ -9567,8 +9246,7 @@ def _backfill_conversion_symbols_once(builders, added):added.append(qualified)continueif qualified in _PEFT_CONVERSION_RUNTIME_SYMBOLS:- # peft calls this one. The stub bodies exist to make the import work on transformers <5, where- # peft's converter never runs; on a real transformers it would run and answer wrongly.+ # peft calls this one: the stubs only make the import work on transformers <5; on a real transformers a stub would answer wrongly.setattr(real,symbol,@@ -9588,18 +9266,13 @@ def _backfill_missing_conversion_symbols():Never replaces a module and never overwrites a name transformers defines,so this is a no-op on every release that still exports them."""- # The _build_ variants, not _install_: installing also attaches the stub to the transformers- # package, where `import transformers.conversion_mapping as m` would keep finding it after the- # real module is back in sys.modules.+ # _build_ not _install_: installing also attaches the stub to the transformers package.builders = {"transformers.conversion_mapping": _build_transformers_conversion_mapping_stub,"transformers.core_model_loading": _build_transformers_core_model_loading_stub,}added = []- # One pass is not enough when the drifts coincide: conversion_mapping imports names from- # core_model_loading at module top, so while those are missing its import raises and the pass- # skips it, and _gpu_init calls this guard once. Repeat while a pass adds a symbol and leaves- # a module unimportable; each pass adds one, so the bound is the module count.+ # Repeat: conversion_mapping imports from core_model_loading, so one pass may not suffice.for _attempt in range(len(_PEFT_CONVERSION_SYMBOLS) + 1):before = len(added)skipped = _backfill_conversion_symbols_once(builders, added)@@ -9952,8 +9625,7 @@ def _log_rocm_detection(message):@functools.lru_cache(1)def _is_rocm_torch_build() -> bool:- # Most official ROCm wheels carry a +rocmX.Y local version, but some custom or source builds do- # not, so fall back to runtime hints.+ # Some custom ROCm builds lack a +rocm local version, so fall back to runtime hints.try:torch_version_raw = str(importlib_version("torch")).lower()if "rocm" in torch_version_raw:@@ -10045,13 +9717,8 @@ def configure_amdgpu_asic_id_table_path():return None-# bitsandbytes Windows ROCm fix: cextension.py calls get_rocm_gpu_arch() (bnb >= 0.47) and-# get_rocm_warpsize() (0.49.x) at import, shelling out to rocminfo / hipInfo.exe via PATH. Neither-# is on PATH on Windows (AMD torch wheels put hipInfo.exe in venv Scripts), so ROCM_GPU_ARCH-# becomes "unknown" and warp size defaults to 64, wrong on RDNA (wave 32) and breaking 4-bit-# blocksizes and ALLOW_PREQUANTIZED_MODELS. Upstream fix unmerged (bitsandbytes#1969), so a-# MetaPathFinder swaps both helpers right after bitsandbytes.cuda_specs executes. Must run before-# `import unsloth_zoo`.+# bitsandbytes Windows ROCm fix: rocminfo / hipInfo.exe are not on PATH, so ROCM_GPU_ARCH is "unknown" and warp size defaults to 64 (wrong on RDNA).+# Upstream fix unmerged (bitsandbytes#1969): a MetaPathFinder swaps both helpers right after bitsandbytes.cuda_specs executes. Must run before `import unsloth_zoo`.# ---------------------------------------------------------------------------@@ -10256,8 +9923,7 @@ class _BnbCudaSpecsPatchLoader(importlib.abc.Loader):def exec_module(self, module):self._loader.exec_module(module)- # Patch after the module body ran, before cextension calls it. The finder stays on- # sys.meta_path so importlib.reload(bitsandbytes.cuda_specs) re-patches.+ # Patch after the module body runs but before cextension calls it; the finder stays so reload re-patchestry:_patch_bnb_cuda_specs_module(module)except Exception as e:@@ -10282,8 +9948,7 @@ class _BnbCudaSpecsPatchFinder(importlib.abc.MetaPathFinder):):if fullname != _BNB_CUDA_SPECS_MODULE:return None- # Delegate to the remaining finders (editable installs, frozen apps) and wrap the loader that- # would actually be used.+ # Delegate to the other meta-path finders (editable installs, frozen apps), skipping this one, then wrap the loader used.spec = Nonefor finder in sys.meta_path:if finder is self or getattr(finder, _BNB_ROCM_FIX_FINDER_SENTINEL, False):@@ -10412,8 +10077,7 @@ def _is_broken_causal_conv1d_error(error) -> bool:return False-# Our Linux x86_64 cp313 CUDA 13 builds for torch 2.13 / 2.14, the minors whose extension ABI no-# upstream wheel matches (release prebuilt-wheels-cu13, .github/workflows/prebuilt-cuda-wheels.yml).+# Our Linux x86_64 cp313 CUDA 13 builds for torch 2.13/2.14, which no upstream wheel matches._PREBUILT_KERNEL_RELEASE_URL = ("https://github.com/unslothai/unsloth/releases/download/prebuilt-wheels-cu13")@@ -10440,8 +10104,7 @@ def stale_kernel_hint(package: str, error) -> str:current = errorwhile current is not None and id(current) not in checked:checked.add(id(current))- # A torch ABI break leaves a mangled c10 / at / torch symbol unresolved; other undefined- # symbols (e.g. CUDA libraries out of step) are not fixed by a rebuild.+ # Only an unresolved c10/at/torch symbol means a torch ABI break that a rebuild fixes.if re.search(r"undefined symbol: (?:_ZN\w*?(?:3c10|2at|5torch)|aoti_torch_)", str(current)):breakcurrent = getattr(current, "__cause__", None) or getattr(current, "__context__", None)@@ -10506,8 +10169,7 @@ def _is_broken_vllm_error(error) -> bool:)) or ("vllm" in message and "undefined symbol" in message):return True- # A forced extension load raises the bare loader error with no "vllm._C" wrapper, so match any- # .so failure; callers feed only vLLM imports.+ # Forced extension loads raise the bare loader error without the vllm._C wrapper.if "cannot open shared object file" in message:return Truecurrent = getattr(current, "__cause__", None) or getattr(current, "__context__", None)@@ -10530,8 +10192,7 @@ def _is_vllm_needs_transformers_v5_error(error) -> bool:_VLLM_RELEASES_URL = "https://github.com/vllm-project/vllm/releases"_VLLM_INSTALL_DOCS_URL = "https://docs.vllm.ai/en/latest/getting_started/installation/gpu/"-# A plain release version, e.g. "0.23.0". Anything else (rc / dev / post) has no matching-# GitHub release asset, so never name a wheel for it.+# Plain numeric release only (e.g. 0.23.0): rc, dev and post versions have no GitHub release asset, so never name a wheel._VLLM_RELEASE_VERSION_RE = re.compile(r"^[0-9]+(?:\.[0-9]+)*$")# Normalises platform.machine() onto the arch spelling used in wheel names.@@ -10548,13 +10209,8 @@ def _both_arches(manylinux_tag):return {"x86_64": manylinux_tag, "aarch64": manylinux_tag}-# vLLM ships one CUDA build per release unsuffixed and the other under a +cuXXX tag, and which-# major is default flipped at 0.20.0 while the manylinux tag moved and differs between the two-# wheels of one release. The name cannot be derived: vLLM's documented "+cu${CUDA_VERSION}"-# pattern 404s (vllm-project/vllm#37847) and no release published a +cu128 wheel.-# Each entry is (min_version, max_version, {cuda_major: (local_tag, {arch: manylinux})}),-# transcribed from the real release assets; an absent major or arch was never published for-# that range. Extend on a new release; until then newer versions fall back to the release page.+# vLLM wheel names cannot be derived (+cuXXX tags and manylinux vary per release); transcribed+# from real release assets. Extend on a new release._VLLM_WHEEL_ASSETS = (("0.11.0",@@ -10611,8 +10267,7 @@ _VLLM_WHEEL_ASSETS = (),)-# From this release on, the default wheel is the CUDA 13 build and the CUDA 12 one carries-# +cu129, so the right variant can be named even when the manylinux tag is unknown.+# From this release on the default wheel is the CUDA 13 build and CUDA 12 carries +cu129, so the variant is nameable without a manylinux tag._VLLM_CUDA13_DEFAULT_SINCE = "0.20.0"@@ -10678,15 +10333,6 @@ def _get_vllm_cuda_mismatch_message(error):# Detect what CUDA version is actually available on the systemsystem_cuda_display = None # Human-readable, e.g. "13.0"system_cuda_major = None- # A random name is never reused, so a failed attempt would be litter rather than something the next run- # overwrites.- # torchao also hangs a handler off aten._grouped_mm at import time, and that operator only exists from torch- # 2.8. Same skew, different lookup: supplying the torch.nn.functional names above does not help it.- # Second guard for the same hazard, in case the alias is the file rather than the directory: never chain to- # this very hook.- # Ask the import system rather than probing for a filename, so the package (`sitecustomize/__init__.py`) and- # .pyc forms chain too.- # Debug mode calls find_device(...).type on gather/broadcast inputstry:import torchcuda_version = torch.version.cuda@@ -10877,8 +10523,7 @@ def _clear_vllm_modules():sys.modules.pop(module_name, None)-# vLLM's compiled extensions: a CUDA-major ABI break hits all of them, so probing the eagerly-# loaded _C and its siblings reliably trips it.+# A CUDA-major ABI break hits all of vLLM's compiled extensions, so probing the eagerly loaded _C reliably trips it._VLLM_COMPILED_EXTENSIONS = ("vllm._C","vllm._C_stable_libtorch",@@ -10905,8 +10550,7 @@ def disable_broken_vllm(error = None):try:import vllm # noqa: F401- # Lazy vLLM lets a bare `import vllm` succeed with an ABI-broken extension; force-load each to- # surface the .so failure here. A missing one raises ModuleNotFoundError (skipped below).+ # Lazy vLLM lets import vllm succeed with a broken .so; force-load each, and a missing one is skipped belowfor _ext in _VLLM_COMPILED_EXTENSIONS:try:importlib.import_module(_ext)@@ -11180,11 +10824,7 @@ def patch_accelerate_recursively_apply():pass-# The one ImportError worth answering False to. Matching "torchao" anywhere is too wide: a-# missing submodule ("No module named 'torchao.quantization'") or libtorchao_ops_cuda.so also-# says it and both mean genuinely broken, so match the version complaint itself. peft's wording-# is first; the rest are how other libraries phrase it, so a reword does not silently turn this-# back into a raise.+# Match only the stale-version complaint; other torchao ImportErrors mean genuinely broken._TORCHAO_STALE_VERSION_ERROR = re.compile(r"incompatible version of torchao"r"|torchao.{0,120}?only versions?\s+(?:above|below|>=|<=)"@@ -11238,9 +10878,7 @@ def fix_peft_stale_torchao_import_error():return Falseis_torchao_available.__unsloth_patched__ = True- # peft's is an lru_cache; functools.wraps copies its name and __dict__ but not cache_clear or- # cache_info, which are methods of the cache object. Forward them so the patch stays a drop-in- # for anything that resets the probe after installing or removing torchao.+ # functools.wraps does not copy lru_cache's cache_clear/cache_info; forward them.for name in ("cache_clear", "cache_info"):method = getattr(original, name, None)if method is not None:@@ -11253,9 +10891,7 @@ def fix_peft_stale_torchao_import_error():except Exception:return False- # `from peft.import_utils import is_torchao_available` binds the original into each importing- # module, so patching import_utils alone leaves the real caller, peft.tuners.lora.torchao,- # still raising.+ # Importers bind the original by name, e.g. peft.tuners.lora.torchao; patch them too.for mod_name, mod in tuple(sys.modules.items()):if not mod_name.startswith("peft") or mod is None:continue@@ -11267,8 +10903,7 @@ def fix_peft_stale_torchao_import_error():return patched-# The spellings a torchao removal produces (class, its old module, the whole ``torchao.dtypes`` package on main).-# Only these, so a BROKEN torchao still raises.+# Messages a torchao removal produces (class, old module, torchao.dtypes package); a broken torchao still raises_PEFT_TORCHAO_MISSING_TENSOR_SUBCLASS = re.compile(r"linear_?activation_?quantized_?tensor|affine_?quantized_?tensor"r"|no module named '?torchao\.dtypes'?(?![.\w])",@@ -11307,8 +10942,7 @@ def _guard_peft_torchao_dispatcher(original):remain, so an AffineQuantizedTensor weight still gets a TorchaoLoraLinear."""warned = [False]- # The defining module's own globals, so the degraded path uses the very objects upstream would- # have, including an is_torchao_available already patched by the sibling fix.+ # Use the defining module's globals so the degraded path sees the same objects, including the is_torchao_available patch.namespace = getattr(original, "__globals__", None)if not isinstance(namespace, dict):namespace = {}@@ -11376,9 +11010,7 @@ def _guard_peft_torchao_dispatcher(original):raiseclasses, missing = _peft_torchao_tensor_subclasses()if not missing:- # The message named one of the two classes but both are there, so this came from- # somewhere else in the dispatcher and is a real failure. Redoing the dispatch- # would swallow it and re-run whatever construction already happened.+ # Both classes exist, so the failure came from elsewhere; redoing dispatch would swallow it.raiseif not warned[0]:warned[0] = True@@ -11420,15 +11052,12 @@ def fix_peft_torchao_missing_tensor_subclass():except Exception:return Nonetry:- # Normally already imported, and costs nothing extra: the torchao imports that break live- # inside the functions, not the module body.+ # Usually already imported and free here, since the torchao imports that break live inside functions, not the module body.import peft.tuners.lora.torchao # noqa: F401except Exception:pass- # `from .torchao import dispatch_torchao` copies the function into peft.tuners.lora.model,- # where the dispatch list is built, so patching the definer alone leaves the real caller- # raising. One wrapper per distinct original, shared, so a missing class warns once.+ # dispatch_torchao is copied into peft.tuners.lora.model, so patch that caller too.wrapped = []patched = Falsefor mod_name, mod in tuple(sys.modules.items()):@@ -11458,9 +11087,7 @@ def fix_peft_torchao_missing_tensor_subclass():return patched-# Every name torchao 0.18.0 imports from torch.nn.functional. scaled_grouped_mm is on the path-# of a plain `import torchao`; scaled_dot_product_attention is listed for completeness, and the-# loop below skips symbols torch provides.+# Names torchao 0.18.0 imports from torch.nn.functional; symbols torch provides are skipped._TORCHAO_TORCH_SYMBOLS = ("ScalingType","SwizzleType",@@ -11500,16 +11127,13 @@ def _make_torch_symbol_placeholder(name, detail):return placeholder-# The same skew one layer down: torchao 0.18 does @implements([aten._grouped_mm.default]) at-# module scope in float8/float8_tensor.py, and that op only arrived in torch 2.8, so older torch-# raises AttributeError. This goes through torch.ops, so the schema itself has to exist.+# torchao 0.18 registers on aten._grouped_mm (torch >= 2.8) at import, so the schema must exist._ATEN_GROUPED_MM_SCHEMA = ("_grouped_mm(Tensor self, Tensor mat2, Tensor? offs=None, ""Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor")-# Module level on purpose: a torch.library.Library deregisters everything it defined once-# collected, so a local would undo itself.+# Module level: a Library deregisters its definitions once garbage collected._aten_grouped_mm_library = None@@ -11635,8 +11259,7 @@ def fix_torchao_torch_symbol_skew():torch_version,)- # The aten-op half of the same skew, independent of the loop above: a torch can have every- # functional symbol and still lack the operator, or the reverse.+ # The aten-op check is separate from the symbol loop: torch can have every symbol and miss the operator, or the reverse.op_detail = (f"torchao {torchao_version} registers a handler for it at "f"import time, but torch {torch_version} does not provide it "@@ -11729,8 +11352,7 @@ def _subprocess_fix_directory():raise RuntimeError("refusing a subprocess fix directory owned by another user: " + directory)- # chmod then re-read: some network and FUSE mounts ignore mode bits and report success without- # changing anything.+ # Re-read after chmod: some network/FUSE mounts ignore mode bits silently.if stat.S_IMODE(info.st_mode) & 0o022:try:os.chmod(directory, 0o700)@@ -11980,8 +11602,7 @@ def _write_hook_atomically(target, source):stream.write(payload)os.replace(tmp, target) # atomicexcept BaseException:- # A random name is never reused, so a failed attempt is litter rather than something the next- # run overwrites.+ # A random name is never reused, so a failed attempt is litter rather than something the next run overwrites.try:os.unlink(tmp)except Exception:@@ -12057,9 +11678,7 @@ def propagate_torchao_fix_to_subprocesses():try:import torch.nn.functional as F- # Both halves of the skew must be absent for there to be nothing to do. Today a torch missing- # the operator also misses the functional symbols (2.8 vs 2.10), so the second check never- # fires alone. Our own patches do not count: the in-process fix ran first.+ # Nothing to do only when both the functional symbols and the aten op are missing; our own in-process patches do not count.if (all(_torch_really_has(F, n) for n in _TORCHAO_TORCH_SYMBOLS)and _aten_grouped_mm_library is None@@ -12073,10 +11692,7 @@ def propagate_torchao_fix_to_subprocesses():directory = _subprocess_fix_directory()target = os.path.join(directory, "sitecustomize.py")source = _subprocess_sitecustomize_source()- # Rewrite only when it differs, so concurrent runs do not fight and a reader never sees a- # truncated file. Matching contents count as evidence only when the file is ours. A directory- # in the way makes os.replace raise, which becomes "no subprocess fix" rather than a hook we- # do not trust.+ # Rewrite only when contents differ; matching contents count as evidence only if the file is oursif _existing_hook_is_trustworthy(target):try:existing = open(target, "r", encoding = "utf-8").read()@@ -12096,10 +11712,7 @@ def propagate_torchao_fix_to_subprocesses():# os.pathsep, not ":": Windows uses ";".current = os.environ.get("PYTHONPATH", "")- # An empty component is an import location, not padding: PYTHONPATH="$PYTHONPATH:/opt/lib"- # leaves one when PYTHONPATH was unset, and CPython reads it as the cwd. A SET-BUT-EMPTY- # PYTHONPATH is the opposite: CPython ignores it, so it must not become a lone "" that ADDS- # the cwd.+ # An empty component means cwd, but a set-but-empty PYTHONPATH must not add one.parts = current.split(os.pathsep) if current else []if directory not in parts:os.environ["PYTHONPATH"] = os.pathsep.join([directory] + parts)@@ -12112,10 +11725,7 @@ def propagate_torchao_fix_to_subprocesses():return directory-# torchao 0.18.0 moved torchao/dtypes/nf4tensor.py under quantization/quantize_/workflows/nf4/,-# but torchtune (and xcodec2 through it) still imports the old path. Same shape as the vLLM-# tokenizer stub: a meta path finder APPENDED after the real ones, so an older torchao wins and-# the alias resolves lazily.+# torchao 0.18.0 moved nf4tensor but torchtune imports the old path; appended alias finder._TORCHAO_NF4_OLD = "torchao.dtypes.nf4tensor"_TORCHAO_NF4_NEW = "torchao.quantization.quantize_.workflows.nf4.nf4_tensor"_TORCHAO_NF4_SENTINEL = "__unsloth_torchao_nf4_alias__"@@ -12129,12 +11739,9 @@ class _TorchaoNF4AliasLoader(importlib.abc.Loader):self.real_spec = Nonedef create_module(self, spec):- # Return the RELOCATED module itself, not a stub with a hand-copied surface: torchtune then- # sees whatever torchao ships, and this cannot rot as symbols are added.+ # Return the relocated module itself, not a hand-copied stub, so torchtune sees whatever torchao ships and cannot rot.module = importlib.import_module(_TORCHAO_NF4_NEW)- # module_from_spec is about to overwrite this shared object's __spec__ with the old-name one- # (_bootstrap.py assigns it unconditionally), leaving find_spec reporting the old name and- # making reload run the no-op exec_module below instead of the file.+ # module_from_spec overwrites the shared __spec__ with the old name, so reload runs a no-op exec_module instead of the fileself.real_spec = getattr(module, "__spec__", None)return module@@ -12399,18 +12006,12 @@ def fix_torchao_safe_int_mm_repr_probe():return True-# `datasets` fingerprints through dill, and dill._dill._is_builtin_module pickles a module by-# reference only if its __file__ starts with a sys prefix, ends with an extension suffix, or-# contains the literal `site-packages`. An install matching none (pip install --target, a-# PYTHONPATH overlay, a vendored tree) is pickled BY VALUE, and Dataset.from_dict then walks-# datasets/utils/_dill.py:_save_arrowTable -> create_arrowTable -> its globals -> the pyarrow-# MODULE, dying on pyarrow's Cython MonthDayNano, whose __module__ is `builtins`. Reproduced with-# the DIRECTORY NAME as the only variable.+# dill pickles modules outside site-packages/sys prefixes by value, which breaks datasets+# fingerprinting on pyarrow (e.g. pip --target installs)._DILL_FIX_SENTINEL = "_unsloth_dill_by_reference_fix"_DILL_FIX_ENV = "UNSLOTH_DISABLE_DILL_FIX"-# Never widened for these: dill's by-value contract is about the module the user works IN, and-# `python -m pkg` gives __main__ a real __spec__ that would satisfy the rule below.+# Never widened: python -m gives __main__ a real __spec__ that would pass the rule below._DILL_NEVER_BY_REFERENCE = frozenset(("__main__", "__mp_main__"))@@ -12426,9 +12027,7 @@ def _dill_path_pickles_by_value(origin):real = os.path.realpath(origin)except Exception:return False- # The LITERAL path only, as dill does: it reads 'site-packages' in module.__file__ and resolves- # only for the prefix comparisons. Searching `real` too would answer "not affected" for a- # symlink into a site-packages-named directory dill still pickles by value.+ # Literal path only, as dill does; resolving symlinks would misjudge.if "site-packages" in origin:return Falsefor name in ("base_prefix", "base_exec_prefix", "exec_prefix", "prefix", "real_prefix"):@@ -12473,9 +12072,7 @@ def _dill_install_root(origin):except Exception:return Noneparent = os.path.dirname(real)- # Any initializer, not just the source: a bytecode-only deployment gives pyarrow/__init__.pyc,- # and matching __init__.py exactly would leave the root at .../pyarrow, where no sibling- # metadata is found.+ # Any __init__ form, so bytecode-only deployments (.pyc) still find sibling metadata.if os.path.splitext(os.path.basename(real))[0] == "__init__":parent = os.path.dirname(parent)return parent or None@@ -12518,8 +12115,7 @@ def _dill_distribution_paths(root):full = os.path.realpath(os.path.join(base, *rel.split("/")))except Exception:return- # Inside the root, and not the metadata itself. installed-files.txt entries are relative to the- # egg-info dir and start with `..`, so containment is checked after resolving.+ # installed-files.txt entries start with `..`, so check containment after resolving.if not full.startswith(prefix):returnhead = full[len(prefix) :].split(os.sep, 1)[0]@@ -12547,9 +12143,7 @@ def _dill_distribution_paths(root):breakif listed:continue- # No file list anywhere. A top_level.txt name is honoured only when it resolves to ONE file:- # `dill` -> dill.py is unambiguous, `google` is a directory the metadata cannot account for.- # Declining costs the original loud PicklingError, not a silently pinned fingerprint.+ # No file list, so top_level.txt names count only when they resolve to one file; declining keeps the loud PicklingErrortop_level = os.path.join(meta, "top_level.txt")try:with open(top_level, encoding = "utf-8") as f:@@ -12600,8 +12194,7 @@ def _dill_module_is_importable_by_name(module, files = ()):return Falseif real in files:return True- # A deployment that compiles to adjacent bytecode and drops the sources leaves RECORD naming- # pkg/__init__.py while the live spec points at pkg/__init__.pyc. Same installed file.+ # Bytecode-only deployments: RECORD names .py while the spec points at .pyc.stem, ext = os.path.splitext(real)return ext in (".pyc", ".pyo") and stem + ".py" in files@@ -12649,10 +12242,7 @@ def fix_dill_module_by_value_pickling():if probe is None or not roots:return False- # Every off-prefix path entry carrying installed metadata, not just the one datasets or pyarrow- # lives in: layers can be spread, and a transform reaching a dependency in a second layer hits- # the very failure this prevents. A root with no metadata contributes nothing. Read once, at- # patch time: re-scanning per module would put directory listings in every fingerprint.+ # Scan every off-prefix path entry with metadata, once at patch time.for entry in list(sys.path):if not entry or not os.path.isdir(entry):continue@@ -12686,8 +12276,7 @@ def fix_dill_module_by_value_pickling():setattr(_is_builtin_module, _DILL_FIX_SENTINEL, True)_dill_module._is_builtin_module = _is_builtin_module- # dill.session binds the name at import time, so patching the defining module alone leaves that- # copy on the original.+ # dill.session binds the name at import, so patch it too.session = sys.modules.get("dill.session")if session is not None and getattr(session, "_is_builtin_module", None) is original:session._is_builtin_module = _is_builtin_module@@ -12700,15 +12289,8 @@ def fix_dill_module_by_value_pickling():return True-# Windows refuses sentencepiece's compiled extension on some machines. Smart App Control and-# App Control for Business judge by reputation, one file at a time, so a freshly published-# unsigned .pyd can be refused on a machine where everything else loads. The user sees a Bad-# Image dialog naming the file, and transformers keeps saying the package is available,-# because it decides that from find_spec and installed metadata and loads nothing.-#-# There is no way to ask whether this machine will refuse the file that does not involve-# handing the file to the loader, which is the thing being avoided: a probe IS the dialog. So-# on Windows the extension is simply never imported.+# Windows Smart App Control can refuse sentencepiece's unsigned .pyd, and any probe triggers+# the dialog, so on Windows the extension is never imported.DISABLE_SENTENCEPIECE_VARIABLE = "UNSLOTH_DISABLE_SENTENCEPIECE"_SENTENCEPIECE_TRUTHY = frozenset({"1", "true", "yes", "on"})_SENTENCEPIECE_FALSY = frozenset({"0", "false", "no", "off"})@@ -12756,15 +12338,10 @@ def disable_sentencepiece_on_windows():if not sentencepiece_should_be_disabled():return Falseif "sentencepiece" in sys.modules:- # Already imported by something earlier, or already disabled by an earlier call.- # Replacing a live module here would break whoever is holding it.+ # Replacing a live module here would break whoever holds it.return sys.modules["sentencepiece"] is Noneif "transformers" in sys.modules:- # Too late, and installing it anyway would be worse than doing nothing. transformers- # has already read availability from find_spec and cached "installed", so the sentinel- # would only produce the disagreement described above, and a tokenizer that loads- # today would start raising ModuleNotFoundError. Whoever imported transformers first- # keeps the ordinary behaviour.+ # Too late: transformers already cached sentencepiece as installed, and a sentinel would break tokenizers that load todayreturn Falsesys.modules["sentencepiece"] = Noneif UNSLOTH_ENABLE_LOGGING:diff --git a/unsloth/kernels/cross_entropy_loss.py b/unsloth/kernels/cross_entropy_loss.pyindex 055cf75f5bf..66fbd590756 100644--- a/unsloth/kernels/cross_entropy_loss.py+++ b/unsloth/kernels/cross_entropy_loss.py@@ -242,7 +242,6 @@ def _chunked_cross_entropy_forward().to(tl.float32)# Cohere logit scaling t * x; Gemma 2 softcapping t * tanh(1/t * x).- # Do logit scaling for Cohereif DO_LOGIT_SCALING:logits = LOGIT_SCALE * logitsif DO_SOFTCAPPING:@@ -579,9 +578,7 @@ if (Version(torch.__version__) < Version("2.4.0")) and not hasattr(def patch_loss_functions(torch_compile = True):_patch_loss_functions(fast_cross_entropy_loss, torch_compile = torch_compile)- # Redirect LOSS_MAPPING aliases still pointing at stock ForCausalLMLoss (e.g.- # ForConditionalGeneration for Qwen3.5, Csm). unsloth_zoo also does this; remove once the floor- # pin passes unslothai/unsloth-zoo#656.+ # Redirect LOSS_MAPPING aliases still on stock ForCausalLMLoss; drop once zoo floor has #656.try:import transformers.loss.loss_utils as _lu_unsloth_loss = _lu.LOSS_MAPPING.get("ForCausalLM")diff --git a/unsloth/kernels/flex_attention.py b/unsloth/kernels/flex_attention.pyindex 1560c9f3bb2..a8bb6a03834 100644--- a/unsloth/kernels/flex_attention.py+++ b/unsloth/kernels/flex_attention.py@@ -204,8 +204,7 @@ def slow_inference_attention_softcapping(Q, K, V, causal_mask, self, bsz, kv_lenK = K.reshape(bsz, n_heads, kv_len, head_dim)V = V.reshape(bsz, n_heads, kv_len, head_dim)- # Gemma 9b should use 256, not hidden_size // num_attention_heads (224); 27b uses the derived value,- # so default to the config. See google/gemma_pytorch commit 03e6575.+ # Gemma 9b uses 256, not hidden_size // num_attention_heads, so read the config.s = self.config.query_pre_attn_scalart = self.config.attn_logit_softcappingdiff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.pyindex 2e1fd6a680b..4a5d7871f18 100644--- a/unsloth/kernels/fp8.py+++ b/unsloth/kernels/fp8.py@@ -344,8 +344,7 @@ def weight_dequant(raise ValueError(f"Incompatible shapes {x.shape = }, {s.shape = }")return yelse:- # Block quantized weight: scale shape is (ceil(m/block_m), ceil(n/block_n)). Go through the- # any-shape helper so fast_dequantize's callers get the pre-sm89 fallback too.+ # Block scales: the any-shape helper also gives fast_dequantize callers the pre-sm89 fallback.return _blockwise_weight_dequant_any_shape(x, s, getattr(s, "block_size", None) or [128, 128], dtype)@@ -1611,9 +1610,7 @@ _DEQUANT_CHUNK_ELEMS = 8 * 1024 * 1024def _torch_blockwise_dequant(weight, weight_scale, block_size, out_dtype):- # no_grad to match the triton kernel this stands in for, which builds no graph. Not- # torch.compiled: the callers are already compiled regions, and compiling the loop here- # unrolls one graph per chunk, which measured slower than eager.+ # no_grad like the triton kernel; not compiled, since per-chunk graphs were slower than eager.with torch.no_grad():m, n = weight.shapeout = torch.empty(m, n, dtype = out_dtype, device = weight.device)@@ -1843,10 +1840,7 @@ class FP8BlockQuantLinear(torch.autograd.Function):weight = weight.contiguous()if X.shape[-1] % block_size[1] != 0 or _fp8_kernel_unsupported(weight, torch.float8_e4m3fn):- # Hidden dim not divisible by the activation block, or a dtype this device cannot compile- # (act_quant and the gemm below both take fp8e4nv pointers, so pre-sm89 must skip both):- # dequant plus plain matmul, using the un-expanded scale so a scalar per-tensor scale- # keeps the fast path in forward and backward.+ # Odd hidden dim or pre-sm89 fp8 skips act_quant and gemm: dequant plus matmul, keeping the un-expanded scaleW_deq = _blockwise_weight_dequant_any_shape(weight, original_weight_scale, block_size, X.dtype)@@ -2303,10 +2297,8 @@ if FbgemmFp8Linear is not None:if FP8Linear is not None:FP8Linear.forward = module_forward_patch(fp8_block_quant_linear, "weight_scale_inv")-# FP8GroupedLinear's fused grouped matmul has no autograd formula, so training backward fails:-# dequant the frozen fp8 weight for a differentiable bmm while eval keeps the fused kernel. Gate-# on self.training, not is_grad_enabled, so the grad-checkpoint no-grad forward and its recompute-# match.+# Fused grouped matmul has no backward: dequant for training, gate on self.training so+# the checkpoint no-grad forward and its recompute match.if FP8GroupedLinear is not None:_fp8_grouped_forward_orig = FP8GroupedLinear.forwarddiff --git a/unsloth/kernels/moe/benchmark/benchmark_fused_moe.py b/unsloth/kernels/moe/benchmark/benchmark_fused_moe.pyindex dd68e7ffc50..55a54c5d758 100644--- a/unsloth/kernels/moe/benchmark/benchmark_fused_moe.py+++ b/unsloth/kernels/moe/benchmark/benchmark_fused_moe.py@@ -318,8 +318,7 @@ if __name__ == "__main__":end_time = time.time()print(f"Total time: {end_time - start_time:.4f} seconds")- # Prefer the autotuner: the MoE block needs 2 forward configs (gate_up_proj, down_proj) and 4- # backward (dW + dX each), and this benchmark supports only 1 config at a time.+ # The MoE block needs 6 kernel configs but this benchmark supports one, so prefer autotune.else:assert False, "Use autotune for now"kernel_configs = create_kernel_configs(args, args.permute_x, args.permute_y)diff --git a/unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py b/unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.pyindex 9170515f641..5d22e2fde7b 100644--- a/unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py+++ b/unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py@@ -190,8 +190,7 @@ class Llama4GroupedGemmTextMoe(Llama4TextMoe):hidden_states = hidden_states.sum(dim = 1)hidden_states_after_weight_merge = hidden_states.view(-1, hidden_dim)- # Token counts per expert plus gather indices (token to expert order): auxiliary structs, not- # recorded in the autograd graph.+ # Token counts per expert and gather indices are auxiliary structs, kept out of the autograd graph.token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)@@ -364,8 +363,7 @@ class Llama4TritonTextMoe(Llama4GroupedGemmTextMoe):hidden_states = hidden_states.sum(dim = 1)hidden_states = hidden_states.view(-1, hidden_dim)- # Token counts per expert plus gather indices (token to expert order): auxiliary structs, not- # recorded in the autograd graph.+ # Token counts per expert and gather indices are auxiliary structs, kept out of the autograd graph.token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)diff --git a/unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py b/unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.pyindex 47bd5548e9f..e5ed1db269c 100644--- a/unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py+++ b/unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py@@ -155,8 +155,7 @@ class Qwen3MoeGroupedGEMMBlock(torch.nn.Module):router_logits, routing_weights, selected_experts = self.run_router(hidden_states)- # Token counts per expert plus gather indices (token to expert order): auxiliary structs, not- # recorded in the autograd graph.+ # Token counts per expert and gather indices are auxiliary structs, kept out of the autograd graph.token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)@@ -271,8 +270,7 @@ class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock):hidden_states = hidden_states.view(-1, hidden_dim)router_logits, routing_weights, selected_experts = self.run_router(hidden_states)- # Token counts per expert plus gather indices (token to expert order): auxiliary structs, not- # recorded in the autograd graph.+ # Token counts per expert and gather indices are auxiliary structs, kept out of the autograd graph.token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)diff --git a/unsloth/kernels/moe/grouped_gemm/reference/moe_block.py b/unsloth/kernels/moe/grouped_gemm/reference/moe_block.pyindex 49c970a3f18..16bdf200d20 100644--- a/unsloth/kernels/moe/grouped_gemm/reference/moe_block.py+++ b/unsloth/kernels/moe/grouped_gemm/reference/moe_block.py@@ -96,8 +96,7 @@ class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock):hidden_states = hidden_states.view(-1, hidden_dim)router_logits, routing_weights, selected_experts = self.run_router(hidden_states)- # Tokens per expert and the token-order to expert-order gather indices: auxiliary structs, not- # recorded in the autograd graph.+ # Tokens per expert and token-to-expert gather indices are auxiliary structs, not recorded in the autograd graph.token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.pyindex 945f8de125e..3d9640458c9 100644--- a/unsloth/kernels/utils.py+++ b/unsloth/kernels/utils.py@@ -230,8 +230,7 @@ elif DEVICE_TYPE == "mlx":elif hasattr(torch._C, "_cuda_getCurrentRawStream"):_gpu_getCurrentRawStream = torch._C._cuda_getCurrentRawStreamelse:- # CPU-only torch wheel (no compiled CUDA backend). _get_tensor_stream is only invoked during real- # GPU work, so a no-op binding is safe.+ # CPU-only torch wheel: _get_tensor_stream only runs during real GPU work, so a no-op is safe.def _gpu_getCurrentRawStream(_index = 0):return 0@@ -570,8 +569,7 @@ def get_lora_parameters_bias(proj):if getattr(base_layer, "quant_method", None) == "fp8":W.block_size = getattr(base_layer, "block_size", [128, 128])- # A decompressed compressed-tensors layer keeps quant_method == "fp8" while its weight is back to- # bf16, so it has no quant state to carry the block size.+ # A decompressed compressed-tensors layer keeps quant_method fp8 but has no quant state.if W_quant is not None:W_quant.block_size = W.block_size@@ -1052,8 +1050,7 @@ else:W, quant_state.scale, quant_state.global_scale, quant_state.dtype)if type(quant_state) is not list:- # New quant_state as a class, per TimDettmers/bitsandbytes#763.- # https://github.com/TimDettmers/bitsandbytes/pull/763/files+ # New quant_state as a class, per https://github.com/TimDettmers/bitsandbytes/pull/763absmax = quant_state.absmaxshape = quant_state.shapedtype = quant_state.dtypediff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 128de54b4d5..816820cddf6 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -526,8 +526,7 @@ DISABLE_SDPA_MODEL_NAMES = ["gpt_oss",]_FLASH_EXCLUDED_MODELS = ("gpt_oss", "deepseek_v4", "mllama")-# deepseek_v4's custom attention is sdpa/flash-incompatible: force eager, and it is excluded above so an explicit request cannot re-enable the crash.-# mllama declares flash support, but its vision and cross attention modules have no is_causal, which the flash path reads.+# deepseek_v4 crashes under sdpa/flash, so it is forced to eager and excluded above; mllama cross attention lacks is_causal_EAGER_ONLY_PREFIXES = ("gemma3n", "deepseek_v4")_FLASH_ATTENTION_MAX_HEAD_DIM = 256_FLASH_ATTENTION_DISABLED_WARNED = set()@@ -583,10 +582,7 @@ def _flex_attention_gpu_is_supported():return True-# head_dim > 128 with an explicit mask drops torch <= 2.13 SDPA to an sm80 CUTLASS kernel (8.82x-# the unmasked cost at head_dim 256, T=8192, B200). Flex's BlockMask carries causal, padding and-# packed-sequence masks exactly as sdpa_mask does. Not FA2 (padding needs varlen), FA3 (no sm100-# cubin) or FA4 (Hub build broken against nvidia-cutlass-dsl 4.6.0).+# head_dim above 128 with a mask drops torch 2.13 and older SDPA to a slow sm80 kernel (~8.8x); FA2, FA3, FA4 ruled out_SDPA_FLASH_MAX_HEAD_DIM = 128_FLEX_LARGE_HEAD_DIM_ENV_VAR = "UNSLOTH_FLEX_ATTENTION_FOR_LARGE_HEAD_DIM"# gemma2 measured slower under flex. gemma4 shares one _attn_implementation across all layers, so@@ -629,8 +625,7 @@ def _text_attention_head_dim(config):return max(head_dims) if len(head_dims) != 0 else None-# torch 2.14 lets cuDNN take a masked head_dim 256 on sm100, matching flex with no compile. Measured-# on Blackwell only, so other cards keep flex.+# torch 2.14 cuDNN handles masked head_dim 256 on sm100 as fast as flex (Blackwell only)._CUDNN_LARGE_HEAD_DIM_TORCH_VERSION = "2.14"_CUDNN_LARGE_HEAD_DIM_MIN_CAPABILITY = (10, 0)@@ -662,10 +657,7 @@ def _sdpa_reaches_cudnn_at_head_dim_256():return False-# Inductor's default flex template needs 151552 bytes of shared memory at head_dim 256 (172032 at-# 192), more than sm86/sm89/sm120 cards (101376) or an A100 (166912) have. There the compile-# fails, unsloth_zoo's suppress_errors falls back to unfused eager flex, and training runs slower-# and in more memory than on SDPA. Offer flex only on the 227 KiB class it was measured on.+# Inductor's flex template needs ~148 KiB smem at head_dim 256; smaller cards fall back to slow eager._FLEX_LARGE_HEAD_DIM_MIN_SHARED_MEMORY = 232448@@ -724,8 +716,7 @@ def _prefers_flex_for_head_dim(config):return not _sdpa_reaches_cudnn_at_head_dim_256()-# Above head_dim 256 Inductor's default flex template overflows shared memory and the launch-# faults with `misaligned address` (torch 2.13, 2.14). Measured: 64x64 still faults, 32x32 passes.+# Above head_dim 256 the default flex template faults with misaligned address on torch 2.13 and 2.14; 32x32 blocks pass_FLEX_KERNEL_OPTIONS_SAFE_HEAD_DIM = 256# BLOCK_M/N drive the forward template, BLOCK_M1/N1/M2/N2 the two backward passes._FLEX_LARGE_HEAD_DIM_KERNEL_OPTIONS = {@@ -1108,8 +1099,7 @@ def patch_flex_attention_kernel_options():if wrapped is registered:return True # Already ours.- # __setitem__ covers the shared instance; register() covers the class mapping that models- # building their own AttentionInterface (doge) read.+ # Set both: __setitem__ covers the shared instance, register covers models building their own AttentionInterfacetry:ALL_ATTENTION_FUNCTIONS["flex_attention"] = wrappedexcept Exception:@@ -2666,8 +2656,7 @@ def _resolve_text_causal_lm_class(if not trust_remote_code:return Noneif "--" in str(class_ref):- # Code from another repository, named only in a nested config that remote-code scanners- # (which read the top-level auto_map) never see: keep the full-composite load instead of importing it.+ # Other-repo code named only in a nested config evades remote-code scanners, so do not import it.return Nonefrom transformers.dynamic_module_utils import get_class_from_dynamic_module@@ -2718,8 +2707,7 @@ def _get_remote_composite_text_only(cache_dir = None,code_revision = None,):- # Text-only load plan for a repo-code composite (Nemotron-Omni: llm_config + vision/sound) whose text sub-model is a whole causal LM stored under one prefix.- # Returns (text_config, key_mapping, text_parameter_names) or None; None keeps the previous full-model load.+ # Returns (text_config, key_mapping, text_parameter_names), or None for the full-model load.if not trust_remote_code or not _is_remote_code_config(model_config):return Noneif isinstance(device_map, dict) and any(key != "" for key in device_map):@@ -2859,8 +2847,7 @@ def _trusted_remote_code_commit(cache_dir = None,local_files_only = False,):- # The commit whose repo code a trusted load ran, which the export's trusted config re-read pins to (unsloth-zoo).- # from_pretrained runs a Hub repo's code at code_revision when given, not at the weights' commit.+ # from_pretrained runs Hub repo code at code_revision when given, not the weights' commit.import osif code_revision is None or os.path.isdir(str(model_name)):@@ -3002,8 +2989,7 @@ def resolve_attention_implementation(if prefers_flex_for_head_dim and not supports_flex_attention:if _enable_flex_attention_support(model_class, model_type):supports_flex_attention = _supports_flex_attention(model_class, config, model_type)- # The automatic routing only replaces the sdpa fallback, but an explicit "1" forces flex- # over flash_attention_2 as well, when flex can be scoped to the decoder.+ # An explicit 1 forces flex over flash_attention_2 too, but only when flex can be scoped to the decoderflex_forced_for_head_dim = (_flex_large_head_dim_override() is Trueand supports_flex_attention@@ -3116,38 +3102,19 @@ def resolve_encoder_attention_implementation(return None-# Outcome of the most recent `_run_temporary_patches` pass, keyed by phase, as-# {"completed": [patch, ...], "raised": [(patch, exception), ...]}. A temporary-# patch that raises is warned about rather than propagated, so without this a-# whole patch silently dropping out leaves CI green; the regression gate in-# tests/test_temporary_patch_coverage.py reads it and fails on a non-empty-# "raised" bucket. Which patches legitimately decline depends on the installed-# transformers/TRL/PEFT, so only "raised" is a defect, never the membership of-# "completed".+# Read by tests/test_temporary_patch_coverage.py; only a non-empty raised bucket is a defect, never completedTEMPORARY_PATCH_OUTCOMES = {}def _run_temporary_patches(phase):import inspect- # Bookkeeping is one list append per patch, storing the callables as they- # are so nothing is formatted on the success path, and the per-phase entry- # is replaced rather than extended so repeated model loads cannot grow it.- # Nothing here can raise, which matters because this loop runs inside- # `import unsloth`.+ # Nothing here may raise (this loop runs inside import unsloth); replace the per-phase entry, never extend itcompleted = []raised = []TEMPORARY_PATCH_OUTCOMES[phase] = {"completed": completed, "raised": raised}for temporary_patch in TEMPORARY_PATCHES:- # Two separate questions, kept separate. inspect.signature raises- # ValueError or TypeError for a callable whose signature it cannot read,- # which only tells us we cannot see a `phase` parameter; catching those- # around the CALL as well re-ran a patch that had already half applied,- # and let every other exception out of an optional patch step and- # straight through `import unsloth` (#3130 ended the import- # on a SyntaxError from one of them). A temporary patch is an- # optimisation that reports its own failures through raise_error, so a- # patch that raises anyway is logged, not fatal.+ # Only the signature probe is guarded; a raising patch is logged, never re-run or fatal.try:accepts_phase = "phase" in inspect.signature(temporary_patch).parametersexcept (ValueError, TypeError):@@ -3158,19 +3125,8 @@ def _run_temporary_patches(phase):else:temporary_patch()except Exception as exception:- # Keep the exception, drop what it drags along. An exception holds- # its __traceback__, and a traceback holds every frame in it and- # every local in those frames; __context__ and __cause__ chain to- # more of the same. The "init" entry is written once per process and- # never replaced, so recording a failure as-is would pin the failed- # patch's frames for the lifetime of the process. Nothing reads them- # (the gate and the warning below both use only the type and the- # message), so this loses no diagnosis and bounds the record to the- # exception objects themselves.- # Guarded because these three are ordinary settable attributes and a- # subclass can shadow them with a property that refuses the write- # (measured: a ValueError out of a __traceback__ setter). Losing the- # trim is fine; losing the import over bookkeeping is not.+ # Drop traceback/context so the per-process record does not pin failed frames.+ # Guarded: a subclass property may refuse these writes.try:exception.__traceback__ = Noneexception.__context__ = None@@ -5054,8 +5010,8 @@ _PER_LAYER_DEVICE_MISSING = object()# A single object, because the checks below test it by identity to mean "no instance dict"._NO_INSTANCE_DICT = {}-# Not spelled `_per_layer_device*`: that prefix is what unsloth_zoo publishes and the readers-# grep for. The fast path spells this one out, so a rename must change both (asserted).+# Not `_per_layer_device*`: unsloth_zoo readers grep that prefix. The fast path+# spells it out, so a rename must change both (asserted)._PER_LAYER_DEVICE_MEMO = "_unsloth_resolved_layer_device"# Memo slot 3: what the answer came from, hence what the fast path re-checks by identity.@@ -5161,8 +5117,7 @@ def per_layer_device(module, default = 0):elif derived_from == _MEMO_FROM_DEVICE:if source is module._per_layer_device:return resolved- # _MEMO_FROM_DEFAULT: derived from `default` alone, so only publishing one of the- # two names can stale it.+ # _MEMO_FROM_DEFAULT depends on default alone, so only publishing one of the two names can make it stale.elif ("_per_layer_device_index" not in module.__dict__and "_per_layer_device" not in module.__dict__@@ -5171,8 +5126,7 @@ def per_layer_device(module, default = 0):except (AttributeError, TypeError, ValueError):pass- # Instance dictionary, not getattr: `nn.Module.__getattr__` scans _parameters, _buffers- # and _modules before raising. The getattr fallback keeps class attributes working.+ # Instance dict, not getattr: nn.Module.__getattr__ would scan _parameters, _buffers and _modules firstpublished = getattr(module, "__dict__", _NO_INSTANCE_DICT)device = published.get("_per_layer_device")index = published.get("_per_layer_device_index", _PER_LAYER_DEVICE_MISSING)@@ -5181,13 +5135,11 @@ def per_layer_device(module, default = 0):index = getattr(module, "_per_layer_device_index", _PER_LAYER_DEVICE_MISSING)if device is None and (index.__class__ is int or index.__class__ is str):- # Exact class, not isinstance: bool must not key the memo (False hashes equal to 0),- # and an unhashable value must fall through rather than raise.+ # Exact class: bool must not key the memo (False == 0), and unhashables must fall through.resolved = _resolved_published_index(index, default)if resolved is not None:if default == 0 and published is not _NO_INSTANCE_DICT:- # Memoisable because it depends on the published value alone, so the fast- # path's identity check is a complete invalidation.+ # Safe to memoise: it depends only on the published value, so the fast path's identity check fully invalidates it.published[_PER_LAYER_DEVICE_MEMO] = (index, resolved, _MEMO_FROM_INDEX)return resolved@@ -5220,8 +5172,7 @@ def per_layer_device(module, default = 0):if buffer_index is None:buffer_index = index if isinstance(index, int) and not isinstance(index, bool) else defaultif default == 0 and published is not _NO_INSTANCE_DICT:- # Only when the answer IS the published object: a parameter- or hook-derived device- # moves without it changing, and memoising that sends activations to a dead device.+ # Memoise only the published object: a param/hook-derived device can move unseen.published_device = published.get("_per_layer_device")if published_device is not None and published_device is device:published[_PER_LAYER_DEVICE_MEMO] = (@@ -5917,10 +5868,7 @@ def patch_gradient_accumulation_fix(Trainer):# Fixes "Output 0 of UnslothFusedLossBackward is a view and is being modified inplace" and gradient accumulation.import inspect- # Before the early returns below: the fla patch is unrelated to gradient accumulation, and it- # can only install once fla has been imported. Loading a non-fla model first (llama.py's- # FastLlamaModel.from_pretrained never imports fla) and a gated-deltanet model second would- # otherwise leave it permanently uninstalled, since the second call returns here.+ # Before the early returns: a non-fla model loaded first would leave the fla patch permanently uninstalledpatch_fla_autotuner_fast_path()if hasattr(Trainer, "get_batch_samples"):@@ -7016,8 +6964,7 @@ def apply_accepts_loss_kwargs_fix(model):return f"default (signature inspection, {reason})"-# unsloth/gpt-oss-* generation_config predates upstream adding <|call|> (200012) to eos (#5162):-# tool calls then run on into plain-text harmony markup. Only generation_config is widened.+# unsloth gpt-oss generation_config predates <|call|> (200012) in eos; widen only generation_config, not the model_HARMONY_TOOL_CALL_TOKEN = "<|call|>"_HARMONY_FINGERPRINT_TOKENS = ("<|call|>", "<|channel|>", "<|return|>")@@ -7094,9 +7041,7 @@ def patch_harmony_tool_call_eos(model, tokenizer):return model-# fast_inference builds the vLLM engine before the tokenizer, so widen the generation-config-# dict vLLM re-applies per request (caller SamplingParams too; ignore_eos still opts out).-# Internal and moved between versions: look up defensively, never raise.+# Widen the generation config vLLM re-applies per request; vLLM internals move, so look up defensively, never raise_VLLM_GENERATION_CONFIG_FIELD_PATHS = (("llm_engine", "input_processor"),("input_processor",),@@ -7312,8 +7257,7 @@ def _resolve_ce_callee(func, namespace):def _scan_ce_calls(source, namespace = None):- # A sum / "none" reduction (modern or legacy, keyword or positional) is the model's own objective, not a micro-batch mean.- # Returns (every call is a mean, at least one call was seen).+ # Returns (every call is a mean, at least one seen); a sum or none reduction is the model's own objectivetry:tree = ast.parse(textwrap.dedent(source))except SyntaxError:@@ -7538,8 +7482,7 @@ class EmptyLogits:def raise_getattr_error(self, attr):if attr == "to":return return_none- # unsloth#409: a catch-all __getattr__ answers hasattr() for every name, so FSDP2's- # output cast saw __dataclass_fields__ and called dataclasses.replace() on the sentinel.+ # A catch-all __getattr__ made FSDP2 treat the sentinel as a dataclass.if len(attr) > 4 and attr.startswith("__") and attr.endswith("__"):raise AttributeError(f"{type(self).__name__!r} object has no attribute {attr!r}")return raise_logits_error@@ -11034,10 +10977,7 @@ def get_moe_target_parameters(if _moe_parameter_exists(model, gate_up_name, parameter_names = parameter_names):moe_params.append(gate_up_name)else:- # NemotronH keeps the expert projections unfused, as separate 3D Parameters.- # Without this fallback every gate and up expert weight is silently dropped- # while down_proj still resolves, so the model trains with two thirds of each- # expert frozen and no error anywhere (unsloth#4476).+ # NemotronH keeps unfused 3D expert Parameters; without this gate/up are silently frozen.wanted_leaves = []if "gate_proj" in target_set or "gate_up_proj" in target_set:wanted_leaves.append("gate_proj")@@ -11063,11 +11003,7 @@ def get_moe_target_parameters()return moe_params- # Nothing resolved as a Parameter. That is only a problem if no other route reaches the- # experts either: get_moe_target_modules covers the per-expert Linear ModuleList layout- # (gpt-oss bnb-4bit) and an ordinary suffix match covers the per-expert submodule layout- # transformers 4.x uses for Qwen3-MoE and Mixtral. Warn only when all three miss, which- # is the silent no-experts-trained case.+ # Warn only when no route reaches the experts: the silent no-experts-trained case.if target_set & _MOE_BROAD_MLP_TARGETS:if moe_module_targets is None:moe_module_targets = get_moe_target_modules(model, target_modules)@@ -11164,8 +11100,7 @@ def get_moe_target_modules(model, target_modules = None) -> List[str]:if not hasattr(model, "named_modules"):return []- # Scope the suffixes to the requested leaves, matching get_moe_target_parameters: gate/up/gate_up map to the fused gate_up ModuleList and down_proj to the down one, so a down-only request must not pull in the other projection.- # gate_proj alone must not collect up_proj leaves; only gate_up_proj asks for both.+ # A down-only request must not pull in gate_up; gate_proj alone must not collect up_proj.want_gate = bool(target_set & {"gate_proj", "gate_up_proj"})want_up = bool(target_set & {"up_proj", "gate_up_proj"})want_down = "down_proj" in target_setdiff --git a/unsloth/models/cohere.py b/unsloth/models/cohere.pyindex 425324b8331..02691947189 100644--- a/unsloth/models/cohere.py+++ b/unsloth/models/cohere.py@@ -157,8 +157,7 @@ def CohereAttention_fast_forward("softmax_scale": getattr(self, "softmax_scale", None),},)- # PrefixGrouper seg table rides in **kwargs from the GRPO logprob forward; misuse (KV cache /- # padding mask) raises. None means the byte-identical default.+ # PrefixGrouper seg table rides in kwargs; None is the default path, and KV cache or padding mask misuse raises_pg_seg = resolve_prefix_seg_info(kwargs, past_key_value, attention_mask)context = AttentionContext(bsz = bsz,diff --git a/unsloth/models/diffusion.py b/unsloth/models/diffusion.pyindex 4e4a656db88..2d8dada814f 100644--- a/unsloth/models/diffusion.py+++ b/unsloth/models/diffusion.py@@ -59,8 +59,7 @@ __all__ = [# transformers model_type strings routed to this slow path.DIFFUSION_MODEL_TYPES = ("diffusion_gemma", "diffusion_gemma4")-# Default LoRA targets are the standard nn.Linear modules in the shared Gemma-4 backbone: the 128-# MoE experts are fused 3D Parameters, not nn.Linear, so PEFT LoRA cannot target them.+# The fused 3D MoE experts are not nn.Linear, so PEFT LoRA cannot target them.DIFFUSION_LORA_TARGETS = ["q_proj","k_proj",@@ -212,8 +211,7 @@ def _load_diffusion_config(from transformers import DiffusionGemma4Configaliased = DiffusionGemma4Config.from_dict(cd)- # Only this object knows the rewrite happened: the checkpoint on disk still says diffusion_gemma,- # so anything rebuilding the config from model_name hits the AutoConfig failure just caught.+ # The checkpoint still says diffusion_gemma, so a rebuild from model_name would fail.aliased._unsloth_legacy_alias = Truereturn aliased@@ -319,8 +317,7 @@ class FastDiffusionModel:else:model_cls = _resolve_diffusion_model_class(config)- # Prefetch the whole repo root so the weight load is a cache hit. No subfolder: the pipeline loads- # every component subfolder, so narrowing would leave unet/vae/text_encoder to Xet.+ # No subfolder: the pipeline loads every component; narrowing would leave unet, vae and text_encoder to Xetmaybe_prefetch_hf_snapshot(model_name,token = token,@@ -380,8 +377,7 @@ class FastDiffusionModel:device_map_planner_kwargs,kwargs,),- # This leaf popped local_files_only off kwargs above, so the helper gets the resolved value rather- # than the caller's raw mapping.+ # local_files_only was popped from kwargs above, so planner_hub_kwargs gets the resolved value, not the raw mapping.**planner_hub_kwargs({"cache_dir": cache_dir,diff --git a/unsloth/models/falcon_h1.py b/unsloth/models/falcon_h1.pyindex 8858c40fed5..780b210b66b 100644--- a/unsloth/models/falcon_h1.py+++ b/unsloth/models/falcon_h1.py@@ -602,8 +602,7 @@ def _FalconH1_fast_forward_inference(return FalconH1Model_fast_forward_inference_custom-# Separate prepare_inputs_for_generation for Hybrid FalconH1, which has its own cache type-# FalconHybridMambaAttentionDynamicCache.+# FalconH1 has its own cache type, FalconHybridMambaAttentionDynamicCache.def _fast_prepare_inputs_for_generation(self,input_ids,@@ -618,9 +617,7 @@ def _fast_prepare_inputs_for_generation(# Overwritten -- has a unique cache type, `FalconHybridMambaAttentionDynamicCache`empty_past_kv = past_key_values is None- # Slice input_ids through cache_position to keep only unprocessed tokens, except: with- # input_embeds input_ids may be missing entries; some generation methods slice input_ids- # themselves; and with synced GPUs cache_position may go out of bounds.+ # Slice input_ids to unprocessed tokens, except with input_embeds or synced-GPU overflow.if not empty_past_kv:if (inputs_embeds is not None # Exception 1@@ -701,8 +698,7 @@ class FastFalconH1Model(FastLlamaModel):PeftModelForCausalLM.forward = PeftModel_fast_forwardfix_prepare_inputs_for_generation(FalconH1ForCausalLM)- # Static KV Cache landed in 4.38.0 and made training much slower (#168,- # huggingface/transformers#27931), so the old rotary embeddings are retained.+ # Static KV cache (4.38.0) made training slower, so the old rotary embeddings are kept.import transformers.models.falcon_h1.modeling_falcon_h1transformers.models.falcon_h1.modeling_falcon_h1.FalconH1RotaryEmbedding = (diff --git a/unsloth/models/fp8_to_nf4.py b/unsloth/models/fp8_to_nf4.pyindex 3474038ce84..c1403b2f2c7 100644--- a/unsloth/models/fp8_to_nf4.py+++ b/unsloth/models/fp8_to_nf4.py@@ -48,8 +48,7 @@ _ENV_QUANTIZE_ALL = "UNSLOTH_FP8_TO_NF4_QUANTIZE_16BIT"# None outside a load; True / False once the outermost from_pretrained has looked at its call._EXPLICIT_4BIT = contextvars.ContextVar("unsloth_explicit_load_in_4bit", default = None)-# Configs armed inside the outermost from_pretrained; disarmed when it returns or raises, so an-# exception before the load's own restore (prefetch, device-map planning) cannot leak a stripped config.+# Disarmed on return or raise, so an early exception cannot leak a stripped config._ARMED_CONFIGS = contextvars.ContextVar("unsloth_fp8_to_nf4_armed_configs", default = None)_FP8_DTYPES = tuple(@@ -572,8 +571,7 @@ def _build_classes():):self.generic = genericself.stack = stack- # (patterns in merge order, concat dim): replaces MergeModulelist + Concatenate by writing- # each expert straight into the final stack, the only 16-bit tensor ever held.+ # (patterns in merge order, concat dim): replaces MergeModulelist + Concatenate by writing each expert into the final stack, the only 16-bit tensor held.self.fuse = fusedef _fused(@@ -1009,9 +1007,7 @@ def install_fp8_to_nf4_quantizer() -> bool:_unsloth_fp8_kept = 0def __init__(self, quantization_config, **kwargs):- # The device-map planner builds this from the rewritten config without `pre_quantized`- # (transformers' own load always passes it). An armed load quantizes at runtime, so size- # its expert merges in the load dtype, not as packed 4bit (a 4x smaller transient).+ # The planner omits `pre_quantized`; an armed load quantizes at runtime, so size in load dtype.if "pre_quantized" not in kwargs and _ARMED_CONFIGS.get():kwargs["pre_quantized"] = Falsesuper().__init__(quantization_config, **kwargs)diff --git a/unsloth/models/gemma.py b/unsloth/models/gemma.pyindex 7d804406a74..d3dfa8f83c2 100644--- a/unsloth/models/gemma.py+++ b/unsloth/models/gemma.py@@ -283,8 +283,7 @@ class GemmaFixedRotaryEmbedding(_PerDeviceRopeCache, torch.nn.Module):)def _set_cos_sin_cache(self, seq_len, device, dtype):- # The original Llama codebase creates these on the target device in FP32 and multiplies in FP32; the- # difference here is explicit division t/x rather than t * (1/x).+ # Built on the target device in FP32 like the original Llama code; the one change is t/x division instead of t * (1/x).self.current_rope_size = seq_len# The difference is we do division explicitly instead of t * (1/x) ie we do t/x.@@ -328,8 +327,7 @@ class GemmaFixedLinearScalingRotaryEmbedding(GemmaFixedRotaryEmbedding):)def _set_cos_sin_cache(self, seq_len, device, dtype):- # The original Llama codebase creates these on the target device in FP32 and multiplies in FP32; the- # difference here is explicit division t/x rather than t * (1/x).+ # Built on the target device in FP32 like the original Llama code; the one change is t/x division instead of t * (1/x).self.current_rope_size = seq_len# The difference is we do division explicitly instead of t * (1/x) ie we do t/x.@@ -372,8 +370,7 @@ class FastGemmaModel(FastLlamaModel):PeftModelForCausalLM.forward = PeftModel_fast_forwardfix_prepare_inputs_for_generation(GemmaForCausalLM)- # Static KV Cache landed in 4.38.0 and made training much slower (#168,- # huggingface/transformers#27931), so the old rotary embeddings are retained.+ # Static KV cache (4.38.0) made training slower, so the old rotary embeddings are kept.import transformers.models.gemma.modeling_gemmatransformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding = GemmaFixedRotaryEmbedding@@ -403,8 +400,7 @@ class FastGemmaModel(FastLlamaModel):# Patch RMS Layernormfor name, module in model.named_modules():if isinstance(module, GemmaRMSNorm):- # Must be in float32 (keras-nlp gemma/rms_normalization.py#L36); the +1 is left to the Triton kernel- # itself.+ # Must be float32; the Triton kernel applies the +1 itself.if not hasattr(module, "variance_epsilon"):module.variance_epsilon = module.eps # Gemma doesn't use variance_epsilondiff --git a/unsloth/models/gemma2.py b/unsloth/models/gemma2.pyindex 68c76a224b3..fbaa900da0d 100644--- a/unsloth/models/gemma2.py+++ b/unsloth/models/gemma2.py@@ -233,8 +233,7 @@ def Gemma2Attention_fast_forward(},)- # PrefixGrouper seg table rides in **kwargs from the GRPO logprob forward; misuse (KV cache /- # padding mask) raises. None means the byte-identical default.+ # PrefixGrouper seg table rides in kwargs; None is the default path, and KV cache or padding mask misuse raises_pg_seg = resolve_prefix_seg_info(kwargs, past_key_value, attention_mask)context = AttentionContext(bsz = bsz,@@ -407,10 +406,8 @@ def Gemma2Attention_fast_forward_inference(device = device,)- # Gemma 9b should use 256, not hidden_size // num_attention_heads (224); 27b uses the derived value,- # so default to the config. See google/gemma_pytorch commit 03e6575.+ # Gemma 9b uses query_pre_attn_scalar 256, not hidden_size // heads (224).self.scalar = 1.0 / math_sqrt(self.config.query_pre_attn_scalar)- # self.scalar = 1.0 / math_sqrt(self.config.hidden_size // self.config.num_attention_heads)self.half_head_dim = head_dim // 2self.t = self.config.attn_logit_softcappingself.reciprocal_t = 1.0 / self.config.attn_logit_softcapping@@ -494,15 +491,13 @@ def Gemma2Attention_fast_forward_inference(_, _, cached_len, _ = Knn.shape- # Gemma2 uses manual matmul for all batch sizes since SDPA lacks softcapping (tanh logit scaling);- # if PyTorch adds a softcap param, consider SDPA for bsz > 1 to match llama/qwen3.+ # Manual matmul: SDPA has no softcapping.Qn *= self.scalar# (Q * scalar) @ K beats (Q @ K) * scalar for stopping overflows; see ggerganov/llama.cpp#7805 (comment 2153349963).# Grouped query attention: the KV heads are read in place, not repeated per query head.A = _gqa_decode_scores(Qn, Knn, self.attention[:, :, :, :cached_len])- # Softcapping must happen BEFORE the mask is applied; see google-deepmind/gemma _modules.py and- # transformers gemma2 eager_attention_forward.+ # Softcapping must happen BEFORE the mask is applied.A *= self.reciprocal_tA.tanh_()A *= self.t@@ -672,8 +667,7 @@ class FastGemma2Model(FastLlamaModel):PeftModelForCausalLM.forward = PeftModel_fast_forwardfix_prepare_inputs_for_generation(Gemma2ForCausalLM)- # Static KV Cache landed in 4.38.0 and made training much slower (#168,- # huggingface/transformers#27931), so the old rotary embeddings are retained.+ # Static KV cache (4.38.0) made training slower, so the old rotary embeddings are kept.import transformers.models.gemma2.modeling_gemma2transformers.models.gemma2.modeling_gemma2.Gemma2RotaryEmbedding = GemmaFixedRotaryEmbedding@@ -702,8 +696,7 @@ class FastGemma2Model(FastLlamaModel):for name, module in model.named_modules():if isinstance(module, Gemma2RMSNorm):- # Must be in float32 (keras-nlp gemma/rms_normalization.py#L36); the +1 is left to the Triton kernel- # itself.+ # Must be float32; the Triton kernel applies the +1 itself.if not hasattr(module, "variance_epsilon"):module.variance_epsilon = module.eps # Gemma doesn't use variance_epsilondiff --git a/unsloth/models/glm4_moe.py b/unsloth/models/glm4_moe.pyindex 133e5271423..31b95e01810 100644--- a/unsloth/models/glm4_moe.py+++ b/unsloth/models/glm4_moe.py@@ -52,8 +52,7 @@ try:if _moe_path not in sys.path:sys.path.insert(0, _moe_path)- # Import first to apply the TMA compatibility shim, which patches triton.language for both old and- # new TMA API names.+ # Import first to apply the TMA API compatibility shim to triton.language.import grouped_gemm # noqa: F401 - triggers TMA compatibility shimfrom grouped_gemm.interface import grouped_gemm@@ -368,8 +367,7 @@ class FastGLM47Model(FastLlamaModel):Glm4MoeLiteNaiveMoe.forward = Glm4MoeLiteNaiveMoe_fast_forwardGlm4MoeLiteMoE.forward = Glm4MoeLiteMoE_fast_forward- # Attention/rope/decoder/model forwards are NOT patched: GLM4 uses MLA with different projection- # names and lacks extend_rope_embedding, so the Llama-compatible infrastructure does not apply.+ # GLM4 uses MLA and lacks extend_rope_embedding, so Llama attention patches do not apply.returndiff --git a/unsloth/models/granite.py b/unsloth/models/granite.pyindex e280ee90eba..bd55643b39d 100644--- a/unsloth/models/granite.py+++ b/unsloth/models/granite.py@@ -35,8 +35,7 @@ from .llama import ()from .mistral import *-# Without bnb, peft stops exporting its 4bit LoRA layer too. Both names only feed isinstance checks,-# so placeholders nothing can match are exact stand-ins.+# Without bnb, peft lacks its Linear4bit too. Both only feed isinstance checks, so placeholders suffice.try:from bitsandbytes.nn import Linear4bit as Bnb_Linear4bitfrom peft.tuners.lora import Linear4bit as Peft_Linear4bit@@ -177,8 +176,7 @@ def GraniteAttention_fast_forward(},)- # PrefixGrouper seg table rides in **kwargs from the GRPO logprob forward; misuse (KV cache /- # padding mask) raises. None means the byte-identical default.+ # PrefixGrouper seg table rides in kwargs; None is the default path, and KV cache or padding mask misuse raises_pg_seg = resolve_prefix_seg_info(kwargs, past_key_value, attention_mask)context = AttentionContext(bsz = bsz,@@ -518,8 +516,7 @@ class GraniteRotaryEmbedding(LlamaRotaryEmbedding):def patched_init(original_init):def new_init(self, *args, **kwargs):- # GraniteModel_fast_forward_inference cannot reach residual_multiplier/config, so stash the whole- # config here to pass it around. See transformers models/granite/modeling_granite.py#L243+ # The inference forward cannot reach config, so stash it here.config = kwargs.get("config", args[0] if args else None)if config is not None:self.config = config@@ -562,8 +559,7 @@ class FastGraniteModel(FastLlamaModel):tokenizer,correct_dtype = None,):- # Torch.compile fails on the embedding matrix; this workaround randomly fixes it for torch < 2.2,- # and the same is done for lm_head.+ # torch.compile fails on the embedding matrix; this rebuild only randomly fixes it on torch < 2.2.model.model.embed_tokens = torch.nn.Embedding.from_pretrained(model.model.embed_tokens.weight)@@ -586,8 +582,7 @@ class FastGraniteModel(FastLlamaModel):lm_head.out_features = lm_head.weight.shape[0]model.lm_head = lm_head- # BnB does not allocate the correct type: its default dtype is float16, so patch all dtypes. See- # TimDettmers/bitsandbytes#763.+ # BnB does not allocate the correct type (its default is float16), so patch all dtypes; see bitsandbytes 763correct_dtype = lm_head.weight.dtypefor name, module in model.named_modules():diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 8d82336f615..96586d5661b 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -198,7 +198,6 @@ from transformers import set_seed as transformers_set_seedfrom peft import LoraConfig, TaskType, get_peft_model as _get_peft_modelfrom peft import PeftModelForCausalLM, PeftModelForSequenceClassification# Deferred to first call: a module-scope bind out of `unsloth.save` closes an import cycle.-# See the note in unsloth/models/vision.py and tests/test_cold_import_order.py.def patch_saving_functions(*args, **kwargs):@@ -221,10 +220,7 @@ except:from huggingface_hub.utils._token import get_tokenfrom triton import __version__ as triton_version-# Not `xformers is not None`: attention_dispatch turns HAS_XFORMERS off when the library imports-# but has no kernel that runs here. Recomputing from the import alone left the model on the-# xFormers path, and Mistral then skipped the 4D sliding-window mask, so every sequence longer-# than config.sliding_window attended to the whole causal history on SDPA.+# Not xformers is not None: HAS_XFORMERS is off when no kernel runs here, and then Mistral skips its sliding-window maskBlockDiagonalCausalMask = xformers.attn_bias.BlockDiagonalCausalMask if HAS_XFORMERS else None@@ -298,10 +294,8 @@ def _offload_frozen_module_for_training(# Tesla T4 must use float32 and not float16; see #1200.new_dtype = torch.float32- # `device_type` is bare ("cuda") and .to("cuda") resolves to the CURRENT device, so on a split- # model it drags the trainable copy off its card. Prefer the index the copy already has; under- # use_gradient_checkpointing="unsloth" it has none (rebuilt on CPU), so fall back to the- # placement recorded before that, then the bare type.+ # Bare .to("cuda") resolves to the current device and moves a split model's copy off its card,+ # so prefer the copy's own index, then the placement recorded before GC rebuilt it on CPU.wanted_type = torch.device(device_type).typetarget_device = device_typefor candidate in (module.modules_to_save.default.weight.device, original_device):@@ -745,8 +739,7 @@ def LlamaAttention_fast_forward_inference(# Must be done 2 steps before hitting full on a short KV cache, or it errors.if position_ids.dim() == 1:position_ids = position_ids[:, None]- # Transformers 5.x accumulates position_ids as [batch, full_seq_len] across decode steps;- # single-token inference only needs the last position.+ # Transformers 5.x accumulates position_ids as [batch, full_seq_len] across decode steps, so keep only the last position.if position_ids.shape[-1] > 1:position_ids = position_ids[:, -1:]position_ids = position_ids.to(Qn.device)@@ -1140,9 +1133,7 @@ def LlamaAttention_fast_forward(flash_dense_kwargs = {"causal": True},flash_varlen_kwargs = {"dropout_p": 0.0, "causal": True},)- # PrefixGrouper seg table rides in **kwargs from the GRPO logprob forward (same route as- # packed_seq_lengths); misuse (KV cache / padding mask) raises. None means the byte-identical- # default. Reuse of this forward carries the branch to qwen2 and gemma.+ # PrefixGrouper seg table rides in kwargs; None is the default path, and KV cache or padding mask misuse raises_pg_seg = resolve_prefix_seg_info(kwargs, past_key_value, attention_mask)context = AttentionContext(bsz = bsz,@@ -1406,8 +1397,7 @@ def LlamaModel_fast_forward(inputs_embeds = inputs_embeds.to(_get_dtype(dtype_from_config(self.config)))- # Normalized from Gemma: cast to bfloat16/float16 to match it exactly, since 3072**0.5 is- # 55.5000 in bfloat16 against 55.4256 in float32.+ # Match Gemma exactly by casting the normalizer: 3072**0.5 is 55.5 in bf16 vs 55.4256 in fp32.IS_GEMMA = self.config.model_type.startswith("gemma")IS_GEMMA2 = self.config.model_type.startswith("gemma2")IS_COHERE = self.config.model_type.startswith("cohere")@@ -1518,8 +1508,7 @@ def LlamaModel_fast_forward(self.SWA_mask = Trueself.GA_mask = Falseelif attention_mask is not None and not unpadded_prefill:- # Unsloth needs a 2D mask, not [2, 1, n, n] (#853), converted to float not bool- # (pytorch/pytorch#103749).+ # Unsloth needs a 2D mask converted to float, not bool (pytorch/pytorch#103749).if attention_mask.dim() == 2:# The SDPA helper returns None for an all-ones mask; the softcapping kernels need a tensor.@@ -1871,8 +1860,8 @@ _FALLBACK_TRANSFORM_FIELDS = (("logit_scale_divide", ("logits_scaling",)),)_FALLBACK_TRANSFORM_BUCKETS = tuple(bucket for bucket, _ in _FALLBACK_TRANSFORM_FIELDS)-# `logits_scaling` is not one knob: Granite divides by it, HyperCLOVA X multiplies (MuP),-# and MiniCPM3 scales the hidden states before the head, so it is not a logit transform.+# `logits_scaling` differs per model: Granite divides, HyperCLOVA X multiplies, and MiniCPM3+# scales hidden states before the head, so it is not a logit transform there._FALLBACK_BUCKET_OVERRIDES = {("logits_scaling", "hyperclovax"): "logit_scale_multiply",("logits_scaling", "minicpm3"): None,@@ -2120,17 +2109,13 @@ def CausalLM_fast_forward(fast_forward_inference):# Now folded into the hidden states, so the kernel must not scale again.logit_scale_multiply = 0- # Packed-boundary guard on raw labels (the fused kernel shifts internally). This branch RETURNS,- # so mask_packed_sequence_boundaries() below is dead on packed paths: it needs- # UNSLOTH_RETURN_LOGITS=1, which forces packing off. Out-of-place, no-op without- # packed_seq_lengths.+ # Raw-label boundary guard; this return leaves mask_packed_sequence_boundaries() dead on packed paths (needs UNSLOTH_RETURN_LOGITS=1)labels = mask_packed_boundary_labels(labels,kwargs.get("packed_seq_lengths"),)- # fused_linear_cross_entropy is disabled: T4 raises OutOfResources (needs 98304 shared memory- # against a 65536 limit).+ # fused_linear_cross_entropy is disabled: T4 raises OutOfResources (needs 98304 shared memory).loss = unsloth_fused_ce_loss(trainer = None,hidden_states = hidden_states,@@ -2366,9 +2351,8 @@ def _compute_config_rope_inv_freq(config, rope_scaling):original_rope_scaling = rope_scalingrope_scaling = _rope_scaling_as_dict(rope_scaling)rope_type = rope_scaling.get("rope_type", None) or rope_scaling.get("type", None)- # "default"/unset means unscaled RoPE: transformers >= 5 reports rope_type="default" for every- # plain config and dropped "default" from ROPE_INIT_FUNCTIONS, so compute it directly instead- # of warning per load.+ # transformers >= 5 reports rope_type="default" for plain configs and dropped it from+ # ROPE_INIT_FUNCTIONS, so compute unscaled RoPE directly.if rope_type in (None, "default"):return _vanilla_inv_freq_from_config(config).to(dtype = torch.float32, device = "cpu"), 1.0try:@@ -2595,9 +2579,8 @@ class LlamaRotaryEmbedding(_PerDeviceRopeCache, torch.nn.Module):super().__init__()# cos/sin multiplier (1.0 except yarn / longrope); set before any cache build.self.attention_scaling = 1.0- # Base-class-from-config path (modern transformers): derive inv_freq like transformers so- # config.rope_scaling is not dropped (#2405). Scaled subclasses excluded to avoid- # double-scaling.+ # Derive inv_freq from the config like transformers so rope_scaling is not dropped; scaled+ # subclasses are excluded to avoid double-scaling.if config is not None:base = _get_rope_theta(config, default = base)partial_rotary_factor = (@@ -2637,8 +2620,7 @@ class LlamaRotaryEmbedding(_PerDeviceRopeCache, torch.nn.Module):return inv_freqdef _unsloth_recompute_inv_freq(self):- # Config scaling (llama3/yarn) first, else vanilla plus subclass scaling. Shared by __init__ and- # the v5 rope repair so they cannot diverge.+ # Config scaling (llama3/yarn) first, else vanilla plus subclass scaling; shared with the v5 rope repairconfig = getattr(self, "_unsloth_rope_config", None)config_inv_freq = Nonerope_scaling = getattr(config, "rope_scaling", None) if config is not None else None@@ -2755,8 +2737,7 @@ class LlamaExtendedRotaryEmbedding(LlamaRotaryEmbedding):# From meta-llama/llama-models llama3_1/api/model.py#L41def _apply_inv_freq_scaling(self, freqs: torch.Tensor):- # llama3 factors come from the config, with Llama-3.1 defaults when built without one: hardcoding- # 8 is wrong for Llama-3.2 (32). v5 renames rope_scaling to rope_parameters, so read either.+ # llama3 factors come from the config (Llama-3.2 uses 32, not 8); v5 renames rope_scaling to rope_parameters.config = getattr(self, "_unsloth_rope_config", None)rope_scaling = _rope_scaling_as_dict(getattr(config, "rope_scaling", None) or getattr(config, "rope_parameters", None) or {}@@ -2969,8 +2950,7 @@ def _generation_max_len(self, args, kwargs):def unsloth_fast_generate(self, *args, **kwargs):restore_training_mode = self.training- # Snapshot the real GC mode (e.g. "unsloth") before for_inference clears it, so the restore- # preserves it rather than collapsing to a plain bool.+ # Snapshot the real GC mode (e.g. unsloth) before for_inference clears it, so restore does not collapse it to a booluse_gradient_checkpointing = next((v for v in (getattr(m, "gradient_checkpointing", False) for m in self.modules()) if v),False,@@ -2978,8 +2958,7 @@ def unsloth_fast_generate(self, *args, **kwargs):FastLlamaModel.for_inference(self)- # Unpack a BatchEncoding passed as input_ids (old notebooks do generate(input_ids=tokenizer(...))):- # v5 generate() calls .shape on it and crashes.+ # Unpack a BatchEncoding passed as input_ids: v5 generate() calls .shape on it._maybe_encoding = kwargs.get("input_ids", None)if (_maybe_encoding is not None@@ -3022,8 +3001,7 @@ def unsloth_fast_generate(self, *args, **kwargs):kwargs.setdefault("disable_compile", True)else:kwargs["cache_implementation"] = "dynamic"- # transformers 4.50 renamed num_logits_to_keep to logits_to_keep; pop both and re-emit under the- # spelling forward() accepts.+ # transformers 4.50 renamed num_logits_to_keep to logits_to_keep; re-emit the spelling forward() accepts._provided_num = kwargs.pop("num_logits_to_keep", None)_provided_logits = kwargs.pop("logits_to_keep", None)_provided = _provided_logits if _provided_logits is not None else _provided_num@@ -3558,9 +3536,8 @@ class FastLlamaModel:raise RuntimeError("Unsloth: `unsloth_vllm_standby` is True, but environment variable `UNSLOTH_VLLM_STANDBY` is not set to 1!")- # Only vLLM cannot take a revision, and fast_inference may have just been cleared above while a- # num_labels load stays in-process, so both can honour the pin. vLLM fetches the default branch,- # so pinning only the config and tokenizer would mix two refs in one model.+ # vLLM cannot take a revision and fetches the default branch, so pinning only config and+ # tokenizer would mix two refs in one model.if _vllm_will_load_weights(fast_inference, num_labels) and revision is not None:logger.warning_once(f"Unsloth: Ignoring revision = `{revision}` since vLLM loads weights from "@@ -3639,8 +3616,7 @@ class FastLlamaModel:assert dtype == torch.float16 or dtype == torch.bfloat16 or dtype == torch.float32- # Respect a user-provided config so it is the single config object used everywhere below; else- # HF gets it again through **kwargs alongside our config= and fails with a duplicate kwarg.+ # Pop a user config so HF does not receive it again via **kwargs beside our config= (duplicate kwarg).user_config = kwargs.pop("config", None)offload_layers = legacy_offload_layers(kwargs, kwargs.pop("offload_layers", None))_offload_layers_requested = offload_layers@@ -3672,8 +3648,7 @@ class FastLlamaModel:)if user_config is not None:model_config = user_config- # model_name may have been remapped to a prequantized repo whose checkpoint needs its- # quantization_config; graft it on, or the 4bit weights load without their quant state.+ # A remapped prequantized repo needs its quantization_config, or 4bit weights load without quant state.if getattr(model_config, "quantization_config", None) is None:_checkpoint_config = AutoConfig.from_pretrained(model_name,@@ -3706,17 +3681,14 @@ class FastLlamaModel:model_function, model_config, dtype = dtype)- # Prefetch the repo (killable child) so the weight load is a cache hit. Runs after the- # AutoConfig/model-class check so an unsupported repo fails on its small config fetch, and warms- # the revision the load uses or the repo downloads twice.+ # Prefetch after the model-class check so bad repos fail early, and at the load revision or it downloads twice_prefetched = maybe_prefetch_hf_snapshot(model_name,token = token,revision = revision,cache_dir = kwargs.get("cache_dir"),local_files_only = kwargs.get("local_files_only", False),- # Skip the warm only for a real vLLM load; a num_labels classification load still goes- # in-process below, so it must be warmed even under fast_inference.+ # A num_labels load still runs in-process, so it must be warmed even under fast_inference.fast_inference = fast_inference and num_labels is None,subfolder = kwargs.get("subfolder"),force_download = kwargs.get("force_download", False),@@ -3734,9 +3706,7 @@ class FastLlamaModel:if _prefetched and kwargs.get("force_download", False):kwargs["force_download"] = False- # The tokenizer always loads in-process, and without an explicit cache_dir Colab/Kaggle route it- # to a special tokenizer cache rather than the one the base snapshot warmed, so resolve the- # cache_dir the tokenizer load will actually use.+ # Colab/Kaggle route the tokenizer to a special cache, so resolve the cache_dir it will actually use.from ..tokenizer_utils import (IS_COLAB_ENVIRONMENT,IS_KAGGLE_ENVIRONMENT,@@ -3752,8 +3722,7 @@ class FastLlamaModel:_tokenizer_cache_dir = "huggingface_tokenizers_cache"elif IS_KAGGLE_ENVIRONMENT:_tokenizer_cache_dir = os.path.join(KAGGLE_TMP, "huggingface_tokenizers_cache")- # Warm the tokenizer repo into the cache the load will use whenever the base warm did not cover- # it: a distinct tokenizer repo, fast_inference (base warm skipped), or a differing cache_dir.+ # Warm the tokenizer repo into the load's cache when the base warm missed it: a distinct repo, fast_inference, or a differing cache_dir._warm_tokenizer_repo = (isinstance(_tokenizer_repo, str)and bool(_tokenizer_repo)@@ -3848,7 +3817,6 @@ class FastLlamaModel:load_in_8bit = kwargs.get("load_in_8bit", False)- # Disable bitsandbytes loading if the model has non-bitsandbytes quantization.# The loader passes load_in_4bit=False with an explicit config, so a bnb 4-bit config is the request._user_quantization_config = kwargs.get("quantization_config", None)_explicit_bnb_4bit = _user_quantization_config is not None and (@@ -3874,8 +3842,7 @@ class FastLlamaModel:"local_files_only": kwargs.get("local_files_only", False),},)- # Only an explicit bnb 4-bit config the check kept keeps the caller's flags: a pre-quantized- # checkpoint left unarmed (vLLM reads it itself) must not reach vLLM as a bitsandbytes load.+ # A pre-quantized checkpoint left unarmed for vLLM must not reach vLLM as a bitsandbytes load.if not (_explicit_bnb_4bit and _checked_4bit):load_in_4bit, load_in_8bit = _checked_4bit, _checked_8bit# vLLM reads the checkpoint itself and picks its own GPTQ kernel.@@ -3920,13 +3887,10 @@ class FastLlamaModel:if _modelopt_rewritten and num_labels is not None:keep_task_heads_unquantized(model_config, AutoModelForSequenceClassification)pop_modelopt_key_mapping(model_config, kwargs)- # Correct UNSLOTH_MODEL_NAME's bnb tokens now the effective bnb state is known (the per-load env- # was built before remap/disable). gpt-oss only.+ # Correct UNSLOTH_MODEL_NAME's bnb tokens once the effective bnb state is known; the per-load env predates remap or disable. gpt-oss only.sync_unsloth_model_name_bnb_flags(load_in_4bit, load_in_8bit)- # num_labels sends the load to AutoModelForSequenceClassification, whose `score` replaces the- # lm_head the planner named off the repo's config, so dispatch_model refuses the map. The weights- # load against user_config while the planner rebuilds the repo's from model_name.+ # num_labels swaps lm_head for `score`, so dispatch_model would refuse the planner's map._planner_skip_reason = Noneif user_config is not None:_planner_skip_reason = (@@ -3945,12 +3909,8 @@ class FastLlamaModel:or "num_labels loads a task head the repo config does not describe")- # A prequantized checkpoint is always sized by its own config.json: merge_quantization_configs- # overlays loading attributes for GPTQ / AWQ / AutoRound / FbgemmFp8 / CompressedTensors / Mxfp4- # and never for bitsandbytes, so neither the merge below (#5027) nor any argument here reaches the- # plan. Worth refusing over only for mamba, whose out_proj stacks are GiBs of error; the other- # reachable gap is MoE routers, ~70 MiB even on Qwen3-235B-A22B, inside the planner's 256 MiB- # margin.+ # Prequantized bnb checkpoints are sized by their own config.json, which the plan cannot see; only+ # mamba out_proj stacks are large enough to refuse over (MoE routers fit the 256 MiB margin).if _planner_skip_reason is None and IS_FALCON_H1 and _ckpt_quant_method == "bitsandbytes":_bundled = getattr(model_config, "quantization_config", None)_bundled_skip = (@@ -4020,11 +3980,9 @@ class FastLlamaModel:trust_remote_code = trust_remote_code,**planner_hub_kwargs(kwargs),revision = revision,- # The dtype the load gets, not the checkpoint's: from_pretrained overrides config.json, and- # planning the wrong one mis-sizes weights 2x either way.+ # The dtype the load gets, not the checkpoint's; planning the wrong one mis-sizes weights 2x.**add_dtype_kwargs(dtype),- # The caller's own config, still untouched in kwargs here, overrides the flags: loader.py clears- # them whenever it forwards one.+ # The caller's own config, still untouched in kwargs, overrides these flags; loader.py clears them whenever it forwards one.**planner_quantization_kwargs(**compressed_tensors_planner_quantization(model_config,@@ -4086,8 +4044,7 @@ class FastLlamaModel:max_position_embeddings = max(max_seq_length, model_max_seq_length)kwargs.pop("attn_implementation", None) # No need since we auto call it- # Cannot be None, since HF now checks for the config.- # A caller's own BitsAndBytesConfig stays authoritative (fast_inference forwards load_in_4bit=True).+ # Must not be None (HF now checks for the config); a BitsAndBytesConfig passed by the caller stays authoritativeif load_in_4bit and not _explicit_bnb_4bit:kwargs["quantization_config"] = bnb_config@@ -4106,8 +4063,7 @@ class FastLlamaModel:raise_handler = RaiseUninitialized()try:if num_labels is not None:- # Transformers 5.x @strict config classes reject unexpected kwargs like num_labels and- # max_position_embeddings, so set them on the config object and pass config= instead.+ # Transformers 5.x @strict configs reject unexpected kwargs, so set them on the config instead.set_task_config_attr(model_config, "num_labels", num_labels)if max_position_embeddings is not None:model_config.max_position_embeddings = max_position_embeddings@@ -4133,8 +4089,7 @@ class FastLlamaModel:)finally:disarm_fp8_to_nf4(model_config)- # Defensive: ensure the task head is in a floating dtype, guarding against any path leaving it- # as integer storage (#5027).+ # Task head must be a floating dtype; guard against any load path that leaves it in integer storage.for _head_name in ("score", "classifier", "qa_outputs"):_head = getattr(model, _head_name, None)if (@@ -4164,8 +4119,7 @@ class FastLlamaModel:offload_embedding = False,fast_inference = _vllm_will_load_weights(fast_inference, num_labels),)- # Re-apply block-fp8 weight_scale_inv tensors transformers dropped on load (#6200), reading- # scales from the same revision as the weights.+ # Re-apply block-fp8 weight_scale_inv tensors transformers dropped on load, from the same revision._restore_dropped_fp8_scales(model,model_name,@@ -4192,8 +4146,7 @@ class FastLlamaModel:or _fp8_to_nf4or _block_swap_saved is not None):- # Transformers 5.x @strict model init rejects extra kwargs next to config=, so set the override- # on the config and pass the single config object through.+ # Transformers 5.x @strict init rejects extra kwargs alongside config=, so set overrides on the config instead.if max_position_embeddings is not None:model_config.max_position_embeddings = max_position_embeddings_rope_scaling = kwargs.pop("rope_scaling", None)@@ -4248,8 +4201,7 @@ class FastLlamaModel:offload_embedding = False,fast_inference = False,)- # Re-apply block-fp8 weight_scale_inv tensors transformers dropped on load (#6200), reading- # scales from the same revision as the weights.+ # Re-apply block-fp8 weight_scale_inv tensors transformers dropped on load, from the same revision._restore_dropped_fp8_scales(model,model_name,@@ -4493,10 +4445,7 @@ class FastLlamaModel:"is_torch_tpu_available()","False",)- # Wire the stray-forward compile-cache reset into the plain Trainer path: get_peft_model arms- # the detector for every LoRA model, but only the TRL SFT/RL wrappers run the reset, so a- # grad-enabled probe before a bare Trainer.train() would keep the poisoned Dynamo cache.- # Anchored on the first body statement; a harmless no-op if upstream drops that line.+ # Plain Trainer.train() lacks the stray-forward cache reset; a grad-enabled probe would poison the Dynamo cacheinner_training_loop = inner_training_loop.replace("self.accelerator.free_memory()","self.accelerator.free_memory()\n"@@ -4584,10 +4533,7 @@ class FastLlamaModel:zero_pad_embedding_rows(model, tokenizer)- # LAST: post_patch replaces the embedding modules and the QKV/MLP patching below replaces the- # forwards a hook wraps, so an earlier attach is lost. Skipped under vLLM, which owns the- # weights. Not the raw flag: a num_labels load stayed in-process above, so the weights this- # repairs are the weights that run.+ # LAST: post_patch and the QKV/MLP patching below replace what a hook wraps, so an earlier attach is lost.if not _vllm_will_load_weights(fast_inference, num_labels):try:from unsloth.models.vision import _repair_dispatch_hooks@@ -4691,8 +4637,7 @@ class FastLlamaModel:)if os.environ.get("UNSLOTH_ENABLE_FULL_FINETUNING", "0") == "1":print("Unsloth: Full finetuning is enabled, so .get_peft_model has no effect")- # Full finetuning still compiles, so a stray pre-train forward can poison the cache; install the- # detector here too (idempotent).+ # Full finetuning still compiles, so a stray pre-train forward can poison the cache._unsloth_install_pretrain_detector(model)# checkpoint_skip_layers / UNSLOTH_GC_KEEP_LAYERS apply to full finetuning too.skip_checkpointing(model, checkpoint_skip_layers)@@ -4757,15 +4702,12 @@ class FastLlamaModel:for param in check_parameters:check_all = check_all and (peft_config[param] == eval(param))- # use_dora arrives via **kwargs, not as a named parameter, so it cannot go in check_parameters- # (which evals each entry as a bound local); compare it explicitly, or a DoRA request against an- # existing plain-LoRA adapter silently passes through unchanged.+ # use_dora arrives via kwargs, so it cannot go in check_parameters; else a DoRA request silently passes as plain LoRAcheck_all = check_all and (bool(peft_config.get("use_dora", False)) == bool(kwargs.get("use_dora", False)))- # Everything the stored adapter trains, wherever PEFT filed it: tying moves the counterpart to- # modules_to_tie, which to_dict() drops, so read the config object.+ # Tying moves the counterpart to modules_to_tie, which to_dict() drops, so read the config object.requested_modules_to_save = modules_to_savemodules_to_save = list(peft_config["modules_to_save"] or [])@@ -4773,8 +4715,7 @@ class FastLlamaModel:def _as_list(targets):return [targets] if isinstance(targets, str) else list(targets or [])- # The new side is what THIS call asks for, through the same redirect; built from the stored- # lists instead, a narrowed request would compare equal.+ # The new side must be this call's request, run through the same redirect; built from stored lists, a narrowed request compares equal.requested_targets, requested_saved, _ = _redirect_embedding_targets(target_modules,requested_modules_to_save,@@ -4797,13 +4738,9 @@ class FastLlamaModel:)new_target_modules = _as_list(requested_targets) + list(requested_saved or [])if isinstance(model, PeftModelForSequenceClassification):- # PeftModelForSequenceClassification.__init__ extends modules_to_save with these- # unconditionally, so the stored config names modules the caller never asked for. Mirror it, or- # an unchanged request looks different.+ # PeftModelForSequenceClassification always adds these to modules_to_save, so mirror it.new_target_modules += ["classifier", "score"]- # Tying is not in check_parameters and leaves both lists looking the same, so compare it- # separately, on what it does rather than what was asked: on an untied model the request changes- # nothing either way.+ # Tying is missed by check_parameters and leaves both lists looking alike, so compare its effective state separately._requested_ties = _effective_weight_tying(model,requested_saved,@@ -4812,15 +4749,12 @@ class FastLlamaModel:_stored_ties = bool(getattr(model.peft_config["default"], "modules_to_tie", None))check_all = check_all and (_requested_ties == _stored_ties)if _requested_ties:- # PEFT files the counterpart under modules_to_tie, which the old side counts, so name it here- # even when the caller listed only one side.+ # PEFT files the counterpart under modules_to_tie, which the old side counts, so name it here even when the caller listed only one side.new_target_modules += list(EMBEDDING_MODULES)- # Per-expert Linear MoE experts (gpt-oss bnb-4bit) were auto-added to the saved target_modules- # at creation, so recompute them and keep a repeat get_peft_model call idempotent.+ # Per-expert Linear MoE experts were auto-added at creation; recompute them to stay idempotent.new_target_modules += get_moe_target_modules(model, target_modules)- # Fold away PEFT's model.embed_tokens alias, and only that one: layers.0.q_proj is a real target- # and is not layers.1.q_proj.+ # Fold only PEFT's model.embed_tokens alias; a real target such as layers.0.q_proj must not merge with layers.1.q_proj.def _leaf_name(module):return _embedding_leaf(module) or module@@ -4850,11 +4784,9 @@ class FastLlamaModel:model.get_output_embeddings(), DEVICE_TYPE_TORCH)- # A pre-wrapped PEFT model passes through here; still arm the detector so an RL trainer can- # reset a compile cache poisoned by a pre-train forward.+ # Pre-wrapped PEFT models pass through here too; still arm the pretrain detector so RL trainers can reset a poisoned compile cache._unsloth_install_pretrain_detector(model)- # This branch returns before patch_peft_model, so record here too;- # apply_unsloth_gradient_checkpointing above already re-patched global state to match (#4735).+ # This branch returns before patch_peft_model, so record the GC mode here too.model._unsloth_gradient_checkpointing = use_gradient_checkpointingmodel = _exclude_rope_inv_freq_from_ddp(model)install_block_swap(@@ -4945,8 +4877,7 @@ class FastLlamaModel:train_lm_head = Falsetrain_embed_tokens = Falsefinal_modules = []- # LoRA on these never trains (see _redirect_embedding_targets); modules_to_save does, and is- # what embedding_learning_rate matches.+ # LoRA on embeddings never trains; modules_to_save does, and embedding_learning_rate matches it.target_modules, modules_to_save, _moved_embedding_modules = _redirect_embedding_targets(target_modules,modules_to_save,@@ -4994,8 +4925,7 @@ class FastLlamaModel:)if hasattr(model, "_need_to_train_embeddings"):- # embed_tokens/lm_head may already be trained, either as LoRA targets in final_modules or via- # modules_to_save.+ # embed_tokens and lm_head may already be trained, as LoRA targets in final_modules or via modules_to_save._embed_already_trained = train_embed_tokens or "embed_tokens" in final_modules_lm_head_already_trained = train_lm_head or "lm_head" in final_modulesif not _lm_head_already_trained or not _embed_already_trained:@@ -5057,9 +4987,7 @@ class FastLlamaModel:# Does not get lora yet, so take the name from model, not base model.is_classification = "Classification" in str(type(model))- # Per-expert Linear expert layouts (gpt-oss bnb-4bit) are Linear modules, not fused Parameters,- # so target them via target_modules. Resolved before the Parameter detection below so the- # two share one walk of the model; neither call mutates anything.+ # Per-expert Linear expert layouts (gpt-oss bnb-4bit) are Linear modules, so use target_modules._moe_module_targets = get_moe_target_modules(model, target_modules)# Auto-detect MoE models and populate target_parameters for expert layers.@@ -5223,8 +5151,7 @@ class FastLlamaModel:)target_module.register_parameter("weight", weight)- # Tie the trainable copies created by ModulesToSaveWrapper first, since those are used in- # forward, then the original_module references if present.+ # Tie the ModulesToSaveWrapper trainable copies first, since forward uses those.if hasattr(input_embeddings, "modules_to_save") and hasattr(output_embeddings, "modules_to_save"):@@ -5293,8 +5220,7 @@ class FastLlamaModel:m.for_training = functools.partial(FastBaseModel.for_training, m)m.for_inference = functools.partial(FastBaseModel.for_inference, m)m = m.model- # Detect a stray pre-train forward so train() can drop the torch.compile graph cache it would- # otherwise poison (see prepare_for_training_mode).+ # Detect a stray pre-train forward so train() can drop the torch.compile graph cache it would poison (see prepare_for_training_mode)._unsloth_install_pretrain_detector(model)model = _exclude_rope_inv_freq_from_ddp(model)# Not at load: the frozen set matches across ranks only after PEFT; custom loops skip Trainer.@@ -5303,9 +5229,8 @@ class FastLlamaModel:@staticmethoddef patch_peft_model(model, use_gradient_checkpointing = "unsloth"):- # Persist the effective GC mode so the trainer restores it verbatim: for_inference() clears the- # module flags every GRPO step, and TrainingArguments defaults it to False, which would silently- # disable it at train time (#4735). Recorded here so loader.py's from_pretrained path is covered.+ # Persist the GC mode: for_inference() clears it every GRPO step and TrainingArguments defaults+ # it to False, which would silently disable it at train time.model._unsloth_gradient_checkpointing = use_gradient_checkpointingreject_alora(model)if os.environ.get("UNSLOTH_USE_NEW_MODEL", "0") == "1" or _is_text_seq2seq_config(@@ -5516,8 +5441,7 @@ class FastLlamaModel:internal_model.max_seq_length = max_seq_lengthinternal_model = internal_model.modelinternal_model.max_seq_length = max_seq_length- # Since transformers 4.53, must turn on explicitly- # Since transformers 4.53, must turn off explicitly+ # Since transformers 4.53, must turn on explicitly and must turn off explicitlyfor module in model.modules():module.max_seq_length = max_seq_lengthmark_unsloth_fast_path(model)@@ -5582,8 +5506,7 @@ class FastLlamaModel:if hasattr(embeddings, "training"):embeddings.training = False- # Restore use_cache values that prepare_model_for_training disabled for gradient checkpointing- # (older unsloth_zoo has no restore helper).+ # Restore use_cache that prepare_model_for_training disabled for gradient checkpointing; older unsloth_zoo lacks restore_use_cache.try:from unsloth_zoo.training_utils import restore_use_cacherestore_use_cache(model)@@ -5650,8 +5573,7 @@ class FastLlamaModel:from .rl import PatchFastRL-# Auto-enable grouped-GEMM MoE (tf<5 ModuleList experts) on built / PEFT'd models. Wrap the-# loader leaves before PatchFastRL so downstream patchers see the wrapped versions.+# Wrap the loader leaves before PatchFastRL so downstream patchers see the wrapped versions.try:from unsloth_zoo.temporary_patches.moe_grouped_modulelist import wrap_loader_for_grouped_moeFastLlamaModel.from_pretrained = staticmethod(diff --git a/unsloth/models/llama4.py b/unsloth/models/llama4.pyindex 25dd87cc347..882006d4828 100644--- a/unsloth/models/llama4.py+++ b/unsloth/models/llama4.py@@ -9,5 +9,3 @@# See the License for the specific language governing permissions and# limitations under the License.-# from unsloth_studio.models import patch_llama4-# patch_llama4()diff --git a/unsloth/models/loader.py b/unsloth/models/loader.pyindex 4a361dd98c7..adf81493298 100644--- a/unsloth/models/loader.py+++ b/unsloth/models/loader.py@@ -350,8 +350,7 @@ def _config_uses_remote_code(config):for k in auto_map)- # Sub-configs go beyond text/vision/audio (Qwen-Omni thinker_config, nested llm_config) and nest;- # a remote child read as native puts the compiler on untraceable code, so walk every level.+ # Sub-configs nest: walk every level, since a remote child read as native breaks the compilertry:from transformers import PretrainedConfig as _config_classexcept Exception:@@ -477,10 +476,7 @@ def _has_sequence_classification_architecture(config):return any(str(arch).endswith("ForSequenceClassification") for arch in architectures)-# Most to least specific, so a config mapped under several gets its own family's-# class. Every name must also be in vision.py's _multimodal_auto_classes(), since-# the class picked here decides processor selection (asserted by-# test_every_class_the_resolver_can_return_takes_a_processor).+# Each name must also be in vision.py _multimodal_auto_classes(), since it picks the processor_OMNI_AUTO_CLASS_NAMES = ("AutoModelForImageTextToText","AutoModelForTextToWaveform",@@ -753,8 +749,7 @@ def _resolve_omni_auto_model(return auto_classexcept Exception:continue- # Falling back to the concrete class the checkpoint names is WRONG: it is in no- # auto mapping, so it leaves the processor set and downgrades to AutoTokenizer.+ # Never fall back to the concrete class: no auto mapping holds it, so it downgrades to AutoTokenizerreturn None@@ -3280,8 +3275,7 @@ class FastModel(FastBaseModel):auto_model = AutoModelelse:auto_model = AutoModelForVision2Seq- # Only when the image-text class has no mapping, so anything that- # resolves today keeps the class it resolves to now.+ # Only when the image-text class has no mapping, so anything that resolves today keeps the class it resolves to now.if resolve_model_class(auto_model, model_config, **_probe_hub_kwargs) is None:auto_model = (_resolve_omni_auto_model(model_config, **_probe_hub_kwargs)diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.pyindex adaec60fa5b..7b1c81d9dd0 100644--- a/unsloth/models/loader_utils.py+++ b/unsloth/models/loader_utils.py@@ -1849,8 +1849,7 @@ def get_model_name(if new_model_name is None:new_model_name = model_nameelse:- # Also when the result equals the input: main returned it lowercased, so that is what is cached.- # The loader drops the revision on a real remap (_revision_for_resolved_repo), so probe main then.+ # Also when equal to the input: main returned it lowercased. A real remap drops the revision.same_repo = new_model_name.lower() == str(model_name).lower()new_model_name = _prefer_legacy_lowercase_cache(new_model_name, local_files_only, cache_dir, revision if same_repo else None@@ -2496,7 +2495,7 @@ def _route_compressed_tensors_fp8_to_unsloth(skip = (),default = "0",):- # Opt-in for FP8 checkpoints (on-the-fly dequant trains slower than bf16); default beside NVFP4, where the+ # Opt-in for FP8 checkpoints (on-the-fly dequant trains slower than bf16); default beside NVFP4.# decompressed FP8 layers would keep compressed-tensors' graph-breaking fake-quant forward.if os.environ.get("UNSLOTH_COMPRESSED_TENSORS_FP8_KERNELS", default) != "1":return 0@@ -2657,8 +2656,7 @@ class _UnslothNVFP4Linear(torch.nn.Linear):fn,recurse = True,):- # model.to(dtype) / .half() may move the packed weight and its scales but never cast them: an fp16 global- # scale overflows past 65504 and dequantizes the layer to zeros.+ # model.to(dtype) must never cast the packed weight or scales: an fp16 global scale overflows.quant = {}for name in ("weight_packed", "weight_scale", "weight_global_scale", "input_global_scale"):param = self._parameters.get(name)diff --git a/unsloth/models/mapper.py b/unsloth/models/mapper.pyindex 6fb21f389e3..075cf8b2716 100644--- a/unsloth/models/mapper.py+++ b/unsloth/models/mapper.py@@ -1108,8 +1108,7 @@ __INT_TO_FLOAT_MAPPER = \"unsloth/Magistral-Small-2509-bnb-4bit",),},- # No Unsloth 16bit repo exists at this size, so this is a 1-tuple naming the real upstream, like the- # other 70B and 405B rows.+ # No Unsloth 16bit repo at this size: 1-tuple naming the real upstream."unsloth/Apertus-70B-Instruct-2509-unsloth-bnb-4bit" : ("swiss-ai/Apertus-70B-Instruct-2509",),diff --git a/unsloth/models/mistral.py b/unsloth/models/mistral.pyindex a8d749818cb..a514feab80e 100644--- a/unsloth/models/mistral.py+++ b/unsloth/models/mistral.py@@ -119,9 +119,7 @@ def MistralAttention_fast_forward(past_key_value = (K, V) if use_cache else Nonesw_cfg = getattr(self.config, "sliding_window", None)- # A non-positive window means "no local attention", the same as absent: passing 0 through made- # window_size (0, 0) for flash and an all-false SDPA mask, since q_pos - (0 - 1) sits above the- # causal upper bound.+ # A non-positive window means no local attention: 0 would give an all-false SDPA mask.if sw_cfg is None or sw_cfg == "null" or (isinstance(sw_cfg, int) and sw_cfg <= 0):sw = kv_seq_lenelse:@@ -144,8 +142,7 @@ def MistralAttention_fast_forward("window_size": window_size,},)- # PrefixGrouper seg table rides in **kwargs from the GRPO logprob forward; misuse (KV cache /- # padding mask) raises. None means the byte-identical default.+ # PrefixGrouper seg table rides in **kwargs; misuse (KV cache or padding mask) raises; None is default_pg_seg = resolve_prefix_seg_info(kwargs, past_key_value, attention_mask)context = AttentionContext(bsz = bsz,@@ -158,10 +155,8 @@ def MistralAttention_fast_forward(training = self.training,attention_mask = attention_mask,causal_mask = causal_mask,- # The window the flash path already gets through window_size. SDPA needs it too, and not only in- # the branch above: training takes `elif self.training: pass`, so no 4D mask is synthesized, and- # with xformers off and flash absent every sequence past config.sliding_window silently attended- # its whole causal history.+ # SDPA needs the window too: training builds no 4D mask, so without it every sequence past+ # sliding_window attended its whole causal history.sliding_window = None if window_size == (-1, -1) else sw,prefix_seg_info = _pg_seg,)@@ -194,9 +189,7 @@ def MistralForCausalLM_fast_forward(past_key_values = _cache_as_legacy_tuple(past_key_values)if past_key_values is not None and len(past_key_values) == 0:past_key_values = None- # PrefixGrouper brings its own mask: a synthesized causal attention_mask would trip- # resolve_prefix_seg_info on the no-xFormers path and force a fallback.- # Not using xformers - need to create attention masks+ # PrefixGrouper brings its own mask; a synthesized one would force a fallback.if (causal_mask is Noneand past_key_values is None@@ -318,8 +311,7 @@ def MistralForCausalLM_fast_forward(if labels is not None:labels = labels.to(lm_head_device)- # Merge legacy / new spellings before branching so the decode-time last-token slice fires on the- # normal path too. Skip int max() if either is a tensor (HF selective-decode form).+ # Merge spellings first so the decode last-token slice hits the normal path; no int max() on tensorsif isinstance(num_logits_to_keep, torch.Tensor) or isinstance(logits_to_keep, torch.Tensor):num_logits_to_keep = 0else:@@ -360,8 +352,7 @@ def MistralForCausalLM_fast_forward(self.config)- # Packed-boundary guard, see llama.py. This branch returns, so mask_packed_sequence_boundaries()- # below is never reached.+ # This branch returns early, so mask_packed_sequence_boundaries() below is never reachedlabels = mask_packed_boundary_labels(labels,kwargs.get("packed_seq_lengths"),@@ -482,8 +473,7 @@ class FastMistralModel(FastLlamaModel):PeftModelForCausalLM.forward = PeftModel_fast_forwardfix_prepare_inputs_for_generation(MistralForCausalLM)- # Static KV Cache landed in 4.38.0 and made training much slower (#168,- # huggingface/transformers#27931), so the old rotary embeddings are retained.+ # Static KV cache (4.38.0) slowed training (#168), so the old rotary embeddings are retained.import transformers.models.mistral.modeling_mistraltransformers.models.mistral.modeling_mistral.MistralRotaryEmbedding = LlamaRotaryEmbeddingdiff --git a/unsloth/models/mxfp4_compressed_linear.py b/unsloth/models/mxfp4_compressed_linear.pyindex 759be0c2905..eaa7a63a783 100644--- a/unsloth/models/mxfp4_compressed_linear.py+++ b/unsloth/models/mxfp4_compressed_linear.py@@ -733,8 +733,7 @@ def install_compressed_tensors_keep_packed() -> bool:return True-# PEFT merge on a packed base: `weight.data += delta` would hit a throwaway decode, silently a no-op.-# Merge densifies to an exact-decode nn.Linear (bytes kept aside); unmerging the last adapter restores them.+# PEFT merge: weight.data += delta silently no-ops on packed base; merge densifies, unmerge restores_PACKED_STATE = "_unsloth_mxfp4_packed_state"diff --git a/unsloth/models/qwen2.py b/unsloth/models/qwen2.pyindex 32939926fa9..916863f6cce 100644--- a/unsloth/models/qwen2.py+++ b/unsloth/models/qwen2.py@@ -54,8 +54,7 @@ class FastQwen2Model(FastLlamaModel):PeftModelForCausalLM.forward = PeftModel_fast_forwardfix_prepare_inputs_for_generation(Qwen2ForCausalLM)- # Static KV Cache landed in 4.38.0 and made training much slower (#168,- # huggingface/transformers#27931), so the old rotary embeddings are retained.+ # Static KV cache (4.38.0) slowed training (#168), so the old rotary embeddings are retained.import transformers.models.qwen2.modeling_qwen2transformers.models.qwen2.modeling_qwen2.Qwen2RotaryEmbedding = LlamaRotaryEmbeddingdiff --git a/unsloth/models/qwen3.py b/unsloth/models/qwen3.pyindex 6ff87dad734..40a8f37f191 100644--- a/unsloth/models/qwen3.py+++ b/unsloth/models/qwen3.py@@ -149,8 +149,7 @@ def Qwen3Attention_fast_forward("softmax_scale": getattr(self, "softmax_scale", None),},)- # PrefixGrouper seg table rides in **kwargs from the GRPO logprob forward; misuse (KV cache /- # padding mask) raises. None means the byte-identical default.+ # PrefixGrouper seg table rides in **kwargs; misuse (KV cache or padding mask) raises; None is default_pg_seg = resolve_prefix_seg_info(kwargs, past_key_value, attention_mask)context = AttentionContext(bsz = bsz,@@ -382,8 +381,7 @@ class FastQwen3Model(FastLlamaModel):PeftModelForCausalLM.forward = PeftModel_fast_forwardfix_prepare_inputs_for_generation(Qwen3ForCausalLM)- # Retain the old rotary embeddings: the static KV cache (transformers 4.38.0) slowed training.- # See unslothai/unsloth#168 and huggingface/transformers#27931.+ # Static KV cache (4.38.0) slowed training (#168), so the old rotary embeddings are retained.import transformers.models.qwen3.modeling_qwen3transformers.models.qwen3.modeling_qwen3.Qwen3RotaryEmbedding = LlamaRotaryEmbeddingdiff --git a/unsloth/models/qwen3_moe.py b/unsloth/models/qwen3_moe.pyindex 56e717cb4f4..d5076ab3ad8 100644--- a/unsloth/models/qwen3_moe.py+++ b/unsloth/models/qwen3_moe.py@@ -30,8 +30,7 @@ from transformers.models.qwen3_moe.modeling_qwen3_moe import (Qwen3MoeForCausalLM,)-# For Pytorch 2.1.1-# Transformers moved to attention_interface, so the Sdpa/FlashAttention2 aliases may no longer be needed.+# For torch 2.1.1: transformers moved to attention_interface, so the Sdpa/FlashAttention2 aliases may be unneeded.from unsloth_zoo.utils import Version, _get_dtype@@ -175,8 +174,7 @@ class FastQwen3MoeModel(FastQwen3Model):PeftModelForCausalLM.forward = PeftModel_fast_forwardfix_prepare_inputs_for_generation(Qwen3MoeForCausalLM)- # Static KV Cache landed in 4.38.0 and made training much slower (#168,- # huggingface/transformers#27931), so the old rotary embeddings are retained.+ # Static KV cache (4.38.0) slowed training (#168), so the old rotary embeddings are retained.import transformers.models.qwen3_moe.modeling_qwen3_moetransformers.models.qwen3_moe.modeling_qwen3_moe.Qwen3MoeRotaryEmbedding = (diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 22c4122b2fb..658bd0e65e0 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -269,8 +269,7 @@ def PatchRL(FastLanguageModel):@contextmanagerdef unsloth_unwrap_model_for_generation(model, *args, **kwargs):- # Snapshot before TRL's unwrap CM, which calls gradient_checkpointing_disable() before- # yielding. Keep the mode value (e.g. "unsloth"), not a bool, so the finally restore matches.+ # Snapshot before the TRL unwrap CM turns checkpointing off; keep the mode, not a bool, to restore ituse_gradient_checkpointing = next((v@@ -400,8 +399,7 @@ def PatchRL(FastLanguageModel):if self.args.past_index >= 0:self._past = outputs[self.args.past_index - 1]finally:- # An eval that raises must not leave logits forced on: UNSLOTH_RETURN_LOGITS=1 also- # blocks packing and padding-free for the next train() in this process.+ # A raising eval must not leave UNSLOTH_RETURN_LOGITS=1 on, which blocks packing and padding-freeos.environ["UNSLOTH_RETURN_LOGITS"] = _old_return_logitsif prediction_loss_only:return (loss, None, None)@@ -1451,10 +1449,8 @@ _DENSE_ROUTER_AUX_LOSS_OFF = ("pass\n")-# The one assignment of `self.aux_loss_enabled` in TRL's GRPOTrainer.__init__, whatever its right-hand-# side. TRL 1.7.0 wrote `is_moe and args.router_aux_loss_coef != 0.0`; TRL main (#7248) reads the-# coefficient from the model config when it is None. Anchoring on the exact expression lost the-# fail-fast below on the first rewrite. Read without importing by tests/version_compat.+# Matches the one assignment of `self.aux_loss_enabled` in GRPOTrainer.__init__, whatever its RHS.+# Read without importing by tests/version_compat._GRPO_AUX_LOSS_ENABLED_LINE = r"^([ \t]*)self\.aux_loss_enabled = [^\n]+$"_GRPO_AUX_LOSS_REJECT = ('if self.aux_loss_enabled: raise NotImplementedError("Unsloth GRPO does not compute the MoE router '@@ -1479,12 +1475,7 @@ def _guard_kbit_prep_against_peft_models():if Version(trl.__version__) >= Version("0.24.0"):return Falseexcept Exception:- # A TRL run from a source tree with no distribution metadata sets- # __version__ = "unknown", which does not parse. Fall through to the- # source check rather than bailing, because bailing leaves exactly the- # pre-0.24 installs this exists for on the upcast. The source check is- # self-guarding: 0.24.0 and above already carry the clause, so they- # spell the branch differently and never match OLD.+ # Unknown version from a source-tree TRL: fall through, do not bail, or pre-0.24 installs skip upcastpasstry:from trl.models import utils as trl_models_utils@@ -1501,21 +1492,14 @@ def _guard_kbit_prep_against_peft_models():source = inspect.getsource(original)except Exception:return False- # Bail rather than guess: if the branch is not spelled the way we expect, a- # blind edit is worse than leaving the upcast in place.+ # Bail rather than blindly edit an unexpected spelling.if source.count(OLD) != 1:return Falseimport functools, textwrapsource = textwrap.dedent(source).replace(OLD, NEW)- # exec against the module's LIVE __dict__, not a copy of it. The body closes- # over PeftModel, prepare_model_for_kbit_training, get_peft_model,- # dataclasses and version, and a copy would freeze those at patch time: a- # later rebinding in trl.models.utils (another library patching it, a test- # swapping it out) would be invisible to the replacement while the original- # would have seen it. The exec defines only this one name, which is the name- # we are replacing anyway.+ # exec against the module's LIVE __dict__ so later rebindings of its globals stay visible.namespace = vars(trl_models_utils)exec(compile(source, getattr(trl_models_utils, "__file__", "<unsloth>"), "exec"), namespace)patched = namespace.get("prepare_peft_model")@@ -1524,10 +1508,7 @@ def _guard_kbit_prep_against_peft_models():functools.update_wrapper(patched, original)setattr(patched, _UNSLOTH_KBIT_PREP_GUARD_FLAG, True)- # Rebind everywhere, not just at the definition. Each trainer module does- # `from ..models import prepare_peft_model` at import time, so it holds its- # own reference; in TRL 0.22.2 that is seven modules, and sft_trainer is the- # one GKD actually inherits.+ # Rebind everywhere: each trainer module holds its own `from ..models import prepare_peft_model`.rebound = 0for module in list(sys.modules.values()):if module is None:@@ -1578,26 +1559,14 @@ def _widen_sft_config_instance_check(patched_config):shim = _WidenedInstanceCheck(installed.__name__,(installed,),- # Carry the patched-config marker in the shim's OWN __dict__, not only by- # inheritance. Callers that walk back to TRL's pristine class do it with- # `while "_unsloth_patched_rl_config" in cls.__dict__`, which is the right- # test because the generated subclass is renamed onto TRL's own name; a- # shim without the marker stops that walk on itself and answers with- # Unsloth's field set (tests/version_compat/test_trl_padding_free_max_length.py).+ # Carry the marker in the shim's OWN __dict__: callers walk back to TRL's pristine class with+ # `while "_unsloth_patched_rl_config" in cls.__dict__`.{_UNSLOTH_SFT_CONFIG_SHIM_FLAG: True,_UNSLOTH_PATCHED_CONFIG_FLAG: True,},)- # Answer to the module the shim is actually installed at, NOT to the module- # the class it stands in for calls home. Pickle stores a class as __module__- # plus __qualname__ and refuses unless the object living there IS the class,- # so a shim claiming `trl.trainer.sft_config` while the patched class still- # sits there is unpicklable, and `torch.save(trainer.args, ...)` from- # Trainer._save raises PicklingError. That is the failure- # _patch_config_pickle_identity exists to prevent, so point the shim at its- # own home and leave the patched class's home alone: both then pickle, and- # every other binding of the name keeps resolving exactly as it did before.+ # Point the shim at its own module: pickle refuses unless __module__.__qualname__ IS the class.shim.__qualname__ = installed.__name__shim.__name__ = installed.__name__shim.__module__ = getattr(sft_trainer_module, "__name__", installed.__module__)@@ -2194,11 +2163,8 @@ def _install_grpo_hidden_states_forward_wrapper(model):_note_grpo_hidden_states_success(target_model)return _replace_outputs_logits(outputs, hidden_states)- # generate() validates its kwargs against inspect.signature(self.forward), so a bare- # (*args, **kwargs) wrapper makes every forward-only vision kwarg look unused.- # __signature__ and NOT functools.wraps: wraps sets __wrapped__, and accelerate's- # extract_model_from_parallel(keep_fp32_wrapper = False) walks that chain every GRPO- # step and rebinds past this wrapper, losing it. inspect.unwrap() stops at __signature__.+ # generate() validates kwargs against inspect.signature(self.forward). Use __signature__, not+ # functools.wraps: accelerate unwraps __wrapped__ every GRPO step and would drop this wrapper.wrapped_forward.__signature__ = forward_signaturefor _attribute in ("__name__", "__qualname__", "__doc__", "__module__"):try:@@ -2804,9 +2770,7 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):model_length_default = "model.max_seq_length"explicit_max_length = ""if trainer_file == "sft_trainer":- # A model limit must not widen a limit the CALLER asked for, and `SFTConfig.max_length`- # defaults to 1024 on every TRL from 0.22 to 1.x, so capping on "positive" instead- # would cap every run that named no length at all down to 1024.+ # Never widen a caller's limit; SFTConfig.max_length defaults to 1024, so do not cap on positive.explicit_max_length = ("_unsloth_explicit_max_length = None\n""try:\n"@@ -3359,8 +3323,6 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):"logging_steps": 1,"max_seq_length": None,"num_generations": 8,- # "steps_per_generation": 1, # Otherwise defaults to ga_steps, which is wrong- # "generation_batch_size": None, # Useless. If steps_per_generation is set, generation_batch_size clashes"vllm_mode": "colocate","generation_kwargs": {},"bf16": False,@@ -3580,8 +3542,7 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):+ "\n")- # Check for loss_type = dr_grpo and scale_rewards for GRPO; DAPO uses per-token loss, so BNPO loss is used. See huggingface/trl#3130 (comment 2746947835).- # TRL >= 0.22 defaults scale_rewards to "group" (= True).+ # Check dr_grpo loss_type with scale_rewards for GRPO; TRL >= 0.22 defaults scale_rewards to group.if "loss_type" in call_args and "scale_rewards" in call_args:check_dr_grpo = ("if loss_type.lower() == 'dr_grpo':\n"@@ -3690,34 +3651,9 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):RLConfig_extra_args = extra_argsRLConfig_call_args = call_args- # Unsloth gradient checkpointing requires the reentrant path. The- # non-reentrant one recomputes every packed forward during backward and- # compares what each pass saved, so a region packed compiled and recomputed- # eagerly aborts the backward with "A different number of tensors was saved- # during the original forward and recomputation".- #- # Two different things push it to non-reentrant, and deleting the key only- # answers one of them:- #- # TRL 0.27.0+ sets use_reentrant=False explicitly, which the delete below- # used to handle on its own.- #- # transformers substitutes {"use_reentrant": False} whenever- # gradient_checkpointing_kwargs is None (see gradient_checkpointing_enable- # in modeling_utils). A config on older TRL never sets the key at all, so- # there is nothing to delete and transformers picks False for us.- #- # So the value is pinned rather than removed, for every TRL version. This is- # not hypothetical on older TRL: GKDConfig turns gradient_checkpointing on by- # default, so a distillation run reaches the non-reentrant path without ever- # having asked for gradient checkpointing at all.- #- # Only touched when gradient checkpointing is actually on, since otherwise- # transformers never reads these kwargs.- # A config asking for context_fn or debug is left alone. torch accepts- # neither under use_reentrant=True and raises as soon as a checkpointed- # forward runs, so pinning those would turn a working non-reentrant setup- # into a crash. determinism_check carries over fine and is not excluded.+ # Unsloth gradient checkpointing requires use_reentrant=True: non-reentrant recompute aborts on+ # packed compiled regions. Pinned (not deleted) because transformers substitutes False when the kwargs+ # are None. context_fn / debug configs are left alone: torch rejects them under reentrant.RLConfig_post = (" # Unsloth: keep the reentrant checkpoint path\n"" if getattr(self, 'gradient_checkpointing', False):\n"@@ -4078,10 +4014,7 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):except Exception as e:logger.info(f"Unsloth: Could not widen the {RLConfig_name} isinstance check: {e}")try:- # Idempotent: the flag on the replacement makes repeat calls no-ops.- # Called from here rather than at import so TRL's trainer modules,- # which each hold their own reference to the name, are already- # imported and can be rebound in one pass.+ # Called here, not at import, so TRL's trainer modules exist and are rebound in one pass._guard_kbit_prep_against_peft_models()except Exception as e:logger.info(f"Unsloth: Could not guard the kbit prep against PEFT models: {e}")@@ -4137,8 +4070,7 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):)-# TRL 1.10+ rejects the list train_dataset the vision notebooks pass; Dataset.from_list is no fix (re-encodes images).-# Only list / tuple: a torch IterableDataset would skip TRL's streaming handling (dispatch_batches, RepeatSampler).+# TRL 1.10+ rejects list train_dataset; only list or tuple, since IterableDataset skips TRL streaming_LIST_TRAIN_DATASET_TRAINERS = frozenset(("sft_trainer", "grpo_trainer", "rloo_trainer"))_TRL_TRAIN_DATASET_TYPE_CHECK = re.compile(r"(elif\s+not\s+isinstance\(\s*train_dataset\s*,\s*)\(?\s*(Dataset(?:\s*,\s*IterableDataset)?)\s*\)?(\s*\)\s*:)"@@ -4235,8 +4167,7 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, import+ "if (getattr(args, 'use_vllm', False) == False):\n"+ " " * 16+ "args.use_vllm = True\n"- # TRL >= 0.27 hands args.top_k to vLLM's SamplingParams unchanged, and it rejects None;- # the config-time guard misses this when vLLM comes only from fast_inference.+ # TRL 0.27+ passes top_k to vLLM unchanged and vLLM rejects None; config guard misses fast_inference+ " " * 12+ "if getattr(args, 'top_k', -1) is None or getattr(args, 'top_k', -1) == 0:\n"+ " " * 16diff --git a/unsloth/models/rl_config_compat.py b/unsloth/models/rl_config_compat.pyindex 3db293cf8ea..bb0945199d6 100644--- a/unsloth/models/rl_config_compat.py+++ b/unsloth/models/rl_config_compat.py@@ -41,9 +41,7 @@ __all__ = []-# Straight renames from TRL's own deprecation warnings. Only entries where the-# old value can be handed to the new name unchanged belong here, so anything-# needing a different value or setting goes in the advice table below.+# Straight renames only: anything needing a different value goes in the advice table.TRL_CONFIG_RENAMES = {# Deprecated in TRL 0.26.0 (DPO) / 0.27.0 (GRPO), removed in 0.28.0."use_liger_loss": "use_liger_kernel",@@ -54,10 +52,7 @@ TRL_CONFIG_RENAMES = {}-# What TRL tells users to do instead, keyed on the retired argument name. Only-# consulted for arguments the installed config rejects, so an entry is harmless-# for a config that still accepts the field (`max_completion_length` is retired-# on `DPOConfig` but current on `GRPOConfig`).+# Only consulted for arguments the installed config rejects.TRL_REMOVED_FIELD_ADVICE = {# GRPOConfig, removed in TRL 0.28.0."max_prompt_length": ("filter overlong prompts out of your dataset before training instead"),@@ -78,9 +73,7 @@ TRL_REMOVED_FIELD_ADVICE = {}-# Every trl config subclasses `transformers.TrainingArguments`, so transformers 5-# removals land here too. From transformers' MIGRATION_GUIDE_V5.md, whose-# `warmup_step` is a typo for `warmup_steps` (which does take a float).+# transformers 5 removals (MIGRATION_GUIDE_V5.md; its `warmup_step` is a typo for warmup_steps).TRANSFORMERS_CONFIG_RENAMES = {"warmup_ratio": "warmup_steps","push_to_hub_token": "hub_token",@@ -91,13 +84,9 @@ TRANSFORMERS_CONFIG_RENAMES = {# transformers 5 removals whose value cannot be carried across.TRANSFORMERS_REMOVED_FIELD_ADVICE = {- # Not a rename: `include_num_input_tokens_seen` is `str | bool` and normalises- # a bool to "no"/"all" in `__post_init__`, which the trainer's `setattr` path- # does not run, so a migrated `False` would read as truthy.+ # Not a rename: a migrated bool False would read as truthy (normalised only in __post_init__)."include_tokens_per_second": ('set `include_num_input_tokens_seen = "all"` instead'),- # Also not a rename. `__post_init__` reads `device`, which is a cached_property,- # and settles `_n_gpu` with it, so assigning `use_cpu` afterwards is a no-op- # (measured: device stays cuda:0). Reporting it as forwarded would be a lie.+ # Not a rename: __post_init__ already settled `device`, so use_cpu afterwards is a no-op."no_cuda": "set `use_cpu = True` on the config you construct instead","group_by_length": 'set `train_sampling_strategy = "group_by_length"` instead',"include_inputs_for_metrics": 'add "inputs" to the `include_for_metrics` list instead',@@ -320,8 +309,7 @@ def filter_config_init_kwargs(notify = _default_notifierconfig_name = getattr(config_class, "__name__", str(config_class))- # Two passes so the outcome does not depend on dict ordering: take what the- # config accepts, then rename or drop the leftovers.+ # Two passes so the outcome does not depend on dict ordering.forwarded = {key: value for key, value in kwargs.items() if key in accepted}for key, value in kwargs.items():@@ -332,9 +320,7 @@ def filter_config_init_kwargs(if verdict == "rename":renamed = detail- # The new name is a mirrored parameter, so it is already in the dict- # carrying either the caller's value or the class default. Only- # overwrite the default: an explicitly set new name wins.+ # The new name is mirrored, so it holds the caller's value or the default; only overwrite the default.existing = kwargs.get(renamed, _MISSING)who = rename_source(key)if rename_value_is_unset(config_class, renamed, value):@@ -343,11 +329,7 @@ def filter_config_init_kwargs(config_class, renamed, existing, mirrored_from = mirrored_from):forwarded[renamed] = value- # A mirrored parameter carries no record of whether it was passed,- # so a caller who set it to exactly this default cannot be told- # apart from one who left it alone. Say which value won instead of- # letting the other disappear. The trainer path knows for certain- # which names arrived, so it never reaches this.+ # A mirrored parameter cannot tell an explicit default from unset, so report which value won.ambiguous = existing is not _MISSING and mirrored_from is not Nonenotify(f"Unsloth: {who} renamed `{key}` to `{renamed}`. Forwarding your "diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex c8f354f8834..09eeff27678 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -1731,15 +1731,9 @@ def _unsloth_grpo_split_vision_by_sample(batch):num_images = _counts(batch.get("num_images", None))if isinstance(pixel_values, list):- # TRL split it. From 1.1.0 split_pixel_values_by_grid splits by SAMPLE, off num_images;- # 0.22.x-0.23.x splits by GRID ROW -- "lengths = batch["image_grid_thw"].prod(dim=1)",- # one element per image -- and leaves image_grid_thw itself flat. The shuffle right- # after takes its length from the first entry of the batch and indexes everything by- # sample, so on a row holding two images that list is both permuted wrongly and- # truncated to the sample count. Regroup it, and split the grid the way 1.1.0 does.- # all-ones, not len(pixel_values) == len(num_images): over two samples num_images = [0, 2]- # makes those two numbers agree while the axes still differ, and the early return would- # hand both of the second sample's images to the first.+ # TRL 1.1.0+ splits by sample; 0.22.x-0.23.x splits by grid row and leaves image_grid_thw flat, so+ # a two-image row is mis-shuffled. Regroup it. Not len(pixel_values) == len(num_images): [0, 2]+ # makes them agree while the axes differ._prompt_ids = batch.get("prompt_ids", None)if (image_grid_thw is None@@ -1804,12 +1798,7 @@ def _unsloth_grpo_split_vision_by_sample(batch):# One padded row per sample already (Idefics, SmolVLM): TRL leaves this alone.return batchif rows == len(num_images) and any(_count != 1 for _count in num_images):- # A padded sample axis and a flat image axis are the same length here, and only the- # padded reading keeps each row with the sample it came from: num_images = [2, 0]- # over two padded rows would hand both of them to the first sample and the second an- # empty tensor. Nothing in the batch tells the two apart, so keep TRL's layout, which- # is what every version does today. The all-ones case is excluded because the two- # readings agree there. Same hazard the list branch above guards against.+ # Padded-sample and flat-image axes are ambiguous: keep TRL layout, else [2, 0] misassigns imagesreturn batchsplit["pixel_values"] = list(torch.split(pixel_values, num_images, dim = 0))_image_sizes = batch.get("image_sizes", None)@@ -2057,9 +2046,7 @@ def _unsloth_reject_grpo_image_list(inputs, trainer = None):returnif getattr(trainer, "vllm_mode", None) != "server":return- # Every row, not just the first: one list cell anywhere in the batch is enough to put the- # images and the placeholders out of step, and a dataset that mixes a bare image with a- # list is exactly the shape that puts the list somewhere other than row 0.+ # Every row: one list cell anywhere desyncs the images and the placeholders.try:rows = list(inputs)except Exception:@@ -2249,19 +2236,9 @@ def grpo_trainer__generate_and_score_completions(function_name, function):_use_gc = self.model._unsloth_gradient_checkpointing if hasattr(self.model, '_unsloth_gradient_checkpointing') else getattr(self.args, 'gradient_checkpointing', True)self.model.for_training(use_gradient_checkpointing=_use_gc)"""- # TRL 0.22.x-0.23.x has neither `forward_kwargs` nor `num_images`: it hardcoded one image per- # example, counted nothing, and saved only four processor keys. The singular `image` column- # normalisation below lets a cell hold several, and every consumer of a multi image batch --- # the shared chunker, and the per sample split in _prepare_inputs -- reads those counts, so- # without them a two image row is sliced as if it were two rows and the images are handed to- # the wrong samples. Built at this anchor rather than in the output block, because the no-grad- # old/reference logprob calls a few lines below take it too and the output block only runs once- # they have already returned. Counted off the same normalised cells the processor was given, so- # the two can never disagree; a row with no image counts zero.- #- # Inserted only for the versions whose call sites it feeds. 0.24.0 and up leave prompt_inputs- # unbound here, so the try below would fall straight through, but not emitting it at all is- # what keeps their generated source byte for byte what it was.+ # TRL 0.22.x-0.23.x has no forward_kwargs / num_images, so a multi-image row is sliced as several+ # rows. Count images off the same normalised cells. Emitted only for those versions so newer+ # generated source stays byte-identical._legacy_vision_prologue = """_unsloth_legacy_vision = {}try:@@ -2317,9 +2294,7 @@ def grpo_trainer__generate_and_score_completions(function_name, function):function = function.replace(line_to_replace, replacement_lines)- # TRL 0.22.x-0.23.x calls the no-grad old/reference logprob pass with four hand named- # processor tensors and no counts, so the shared chunker cannot tell one sample's images- # from the next and slices an image indexed grid by sample index.+ # TRL 0.22.x-0.23.x passes four tensors and no counts, so the chunker cannot split images per sample_legacy_vision_call = re.compile(r"(^[ \t]+)pixel_values=prompt_inputs\.get\(\"pixel_values\"\),\n"r"[ \t]+image_grid_thw=prompt_inputs\.get\(\"image_grid_thw\"\),\n"@@ -2331,8 +2306,7 @@ def grpo_trainer__generate_and_score_completions(function_name, function):r"\1**_unsloth_legacy_vision,\n",function,)- # Every TRL from 0.22.2 to 0.23.1 takes all three rewrites, and 0.24.0 and up pass- # forward_kwargs instead and need none, so this is a guard against a future drift.+ # Guard against future drift: 0.22.2-0.23.1 take all three rewrites, 0.24.0+ need none._legacy_vision_unplumbed = (_legacy_vision_calls == 0 and 'prompt_inputs.get("pixel_values")' in function)@@ -2377,15 +2351,11 @@ def grpo_trainer__generate_and_score_completions(function_name, function):if (sum(re.match(rf"{spacing}[^\s]", x) is not None for x in splits) == 2and len(spacing) >= 8- # The regex above also matches trl 0.18.2 and 0.19.1, which the declared window- # admits and which have none of the symbols the replacement below emits; TRL's own- # call to the helper is the discriminator (0.20.0-0.23.1 have it, those two do not),- # and without it TRL's native slicing must stay. tests/version_compat/- # test_grpo_protected_tokens_guard.py measures this per version.+ # The regex also matches trl 0.18.2 / 0.19.1, which lack the emitted symbols; TRL's own helper call+ # discriminates (tests/version_compat/test_grpo_protected_tokens_guard.py).and "truncate_with_protected_tokens" in replace_part):- # getattr: the next emitted line drops None, so an id a fork or subclass leaves- # unset means "nothing to protect" rather than AttributeError in generated code.+ # getattr: an unset id means nothing to protect, not AttributeError in generated code.new_replacement = f"""\n{spacing}if self.max_prompt_length is not None:# If max_prompt_length is set, we trim the prompt to keep only the last `max_prompt_length` tokens.# Then we decode those tokens back into text. We manually remove leading pad tokens from the decoded text,@@ -2424,10 +2394,7 @@ def grpo_trainer__generate_and_score_completions(function_name, function):string_to_find = """ if "image_sizes" in prompt_inputs:output["image_sizes"] = prompt_inputs["image_sizes"]"""- # 0.22.x-0.23.x saves the four keys above and nothing else, so a processor that emits- # spatial_shapes, num_tiles or the Gemma position ids loses them between generation and the- # gradient forward, and there is no `if images is not None` anchor here to hang the generic- # copy on. Same mapping the no-grad calls above were given, so both policies see one batch.+ # 0.22.x-0.23.x saves only four processor keys; copy the rest so both policies see one batch.replacement_string = """ if "image_sizes" in prompt_inputs:output["image_sizes"] = prompt_inputs["image_sizes"]try:@@ -2659,12 +2626,7 @@ def grpo_trainer__generate_and_score_completions(function_name, function):" if isinstance(prompt, list): # i.e., when using conversational data\n"" prepare_multimodal_messages(prompt, num_images=1)")- # An empty cell takes zero placeholders, not one: the prologue already counts it as zero,- # and a batch mixing an image bearing row with an empty one otherwise reaches the processor- # a placeholder short of its images. An all empty column is a text batch wearing an image- # one, which TRL demotes itself from 0.24.0; ported here, because zero placeholders against- # `[[], []]` is an IndexError inside the processor rather than a text run. The guard mirrors- # TRL's `all(img_list == [] ...)`, so a `None` cell still fails exactly as it does on main.+ # Empty cells take zero placeholders; all-empty column becomes text (TRL 0.24.0+), else IndexError_placeholder_new = (' if kwargs.get("images") and all(\n'' _unsloth_cell == [] for _unsloth_cell in kwargs["images"]\n'@@ -2677,25 +2639,14 @@ def grpo_trainer__generate_and_score_completions(function_name, function):" prompt, num_images=len(_unsloth_cell) if _unsloth_cell else 0\n"" )")- # TRL 0.24.0 and up size the placeholders themselves, off the cell they were handed, so the- # rewrite above is the whole job there. TRL 0.20.0 and 0.21.0 are the gap: they take the- # legacy cell spelling but predate `prepare_multimodal_messages` entirely and inline one- # `{"type": "image"}` per user message with no count, so a normalised two image cell would- # reach the processor with one placeholder. Nothing else in the batch disagrees, because the- # prologue counts the same cells, so it surfaces inside the processor.+ # TRL 0.24.0+ sizes placeholders itself; 0.20.0 / 0.21.0 inline one per message, so not sized._placeholder_sized = not _legacy_image_cellif _placeholder_old in function:function = function.replace(_placeholder_old, _placeholder_new)_placeholder_sized = True- # Rewriting the cell is only half of a multi image row: on a legacy TRL the reference- # logprob call sites have to carry the counts too, or the images are sliced by sample- # index and all but the first are dropped. That surfaces as a token/feature mismatch- # raised inside the model, naming neither the column nor the fix, so refuse it here- # instead. A single image cell is unaffected either way and keeps working.- # `self` and not nothing: on a legacy TRL every other path now carries a multi image row,- # so the refusal has to narrow to the vLLM server mode that still cannot. Passing the- # trainer moves that decision to runtime, where `vllm_mode` is actually known.+ # On a legacy TRL the reference logprob calls need counts too, else a multi-image row fails deep in+ # the model; refuse it. `self` narrows the refusal to vLLM server mode at runtime._guard_argument = ""if not _image_cell_normalised or _legacy_vision_unplumbed or not _placeholder_sized:pass@@ -4296,8 +4247,7 @@ def _unsloth_resolve_logit_scales(model_config):Only reached when the installed unsloth_zoo predates that helper. Must stay in step with ``resolve_logit_transforms`` in unsloth/models/llama.py: if the forward applies a transform GRPO does not, the policy log-probabilities come from different logits than the ones generated, which silently shifts every importance ratio."""- # ``logits_scaling`` is not one knob: Granite divides, HyperCLOVA X multiplies (MuP),- # MiniCPM3 scales the hidden states so it is not a logit transform.+ # Granite divides, HyperCLOVA X multiplies, MiniCPM3 scales hidden states (not a logit transform).overrides = {("logits_scaling", "hyperclovax"): "multiply",("logits_scaling", "minicpm3"): None,@@ -4912,16 +4862,8 @@ def grpo_trainer_compute_loss(function_name, function):num_processes = num_processes,)else:- # The gradient path needs the same zoo the no-grad path checks for, and nothing- # has checked it here: with beta = 0 and num_iterations = 1 there are no reference- # or old logprobs to compute, so _get_per_token_logps_and_entropies -- where that- # gate lives -- never runs at all. An older grpo_accumulated_loss accepts- # arbitrary kwargs, ignores the keys it does not know (spatial_shapes, num_tiles,- # the position ids) and, for a model that carries no image_grid_thw to slice by,- # replaces pixel_values with None outright, so training would compute its gradient- # logprobs from the text alone and report nothing. Import-probed rather than- # signature-probed, and body-local like the one in the no-grad path: this source is- # copied out without this module's imports (#6960).+ # With beta = 0 and num_iterations = 1 the no-grad path (and its zoo gate) never runs, and an older+ # grpo_accumulated_loss silently drops pixel_values. Body-local: copied out without imports (#6960).if pixel_values is not None and not getattr(self, "_unsloth_grpo_vision_zoo_checked", False):diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex 7a9a8e2d7a1..da271ce1029 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -49,8 +49,8 @@ import refrom transformers import AutoModel, AutoConfigimport tempfilefrom huggingface_hub import HfApi, get_token-# Deferred to first call: a module-scope bind out of `unsloth.save` closes an import cycle.-# See the note in unsloth/models/vision.py and tests/test_cold_import_order.py.+# Deferred: a module-scope bind from `unsloth.save` closes an import cycle+# (tests/test_cold_import_order.py).def unsloth_save_pretrained_torchao(*args, **kwargs):@@ -84,9 +84,8 @@ def _ensure_sentence_attention_masks(model):getattr(config, "_attn_implementation", "")):return False- # Zoo's Gemma3 attention preserves FP32 Q/K but consumes SDPA masks. With- # a Flash backend, Transformers omits those masks and ST can flatten rows;- # that implementation does not consume the resulting sequence boundaries.+ # Zoo's Gemma3 attention keeps FP32 Q/K but needs SDPA masks; with Flash, Transformers omits+ # them and ST's flattened rows lose their sequence boundaries.patched = any(getattr(module.forward, "__module__", "").startswith("unsloth_zoo.temporary_patches.gemma")for module in model.modules()@@ -1456,26 +1455,7 @@ class FastSentenceTransformer(FastModel):"sentence_transformers.base.modules.transformer.Transformer",}- # Which config key each loader resolves as a dotted import path, keyed by the class- # that resolves it. Dense imports AND CALLS config["activation_function"],- # WordEmbeddings imports config["tokenizer_class"], Router and Asym import every- # config["types"] value, all ungated on some versions, so an allowed in-namespace- # "type" reaches them. The prefixes are upstream's own rules and are applied on every- # version: util.import_module_class is not a version test, since 5.5 exports it while- # its WordEmbeddings.load still calls import_from_string on tokenizer_class.- #- # By class and not by key name: SpladePooling lists- # activation_function in its own config_keys too, but the value there is the literal- # "relu" or "log1p_relu" and it is compared, never imported (SpladePooling.py:- # `if self.activation_function == "log1p_relu"`). Matching on the key name alone- # refused every SPLADE sparse model for naming a value that no loader imports.- #- # Complete for the module path as of 5.1: the only config-driven import_from_string- # calls in the package are Dense.load on activation_function, WordEmbeddings.load on- # tokenizer_class, Router.load on types, and SentenceTransformer's own modules.json- # type, which _resolve_module_class covers. Asym is an alias of Router from 5.0- # (`Asym = Router`), so it arrives here as Router; the entry is kept for versions- # where it is its own class.+ # Match dotted-path keys per loader class, not key name (SpladePooling is literal); keep Asym pre-5.0_MODULE_CONFIG_CLASS_REFS = {"Dense": (("activation_function", "torch."),),"WordEmbeddings": (("tokenizer_class", "sentence_transformers."),),@@ -1517,17 +1497,12 @@ class FastSentenceTransformer(FastModel):if trust_remote_code:return- # Nothing to check unless this class is one that resolves a dotted path out of its- # own config. Every other module reads plain values, so looking for these keys in- # its config found a name nobody imports and refused a load that works.+ # Only classes that resolve dotted paths from their own config need this check; others would wrongly refuse working loads.rules = FastSentenceTransformer._class_ref_rules(module_class)if not rules:return- # Read what the loader will read: each module names its own file (Router- # "router_config.json", WordEmbeddings "wordembedding_config.json"), and Router falls back to- # "config.json", which is also Module's default and so Dense's. Hard-coding "config.json"- # would skip exactly the two modules this check exists for.+ # Read the file the loader will read; hard-coding config.json would skip Router and WordEmbeddings.config_names = []config_file_name = getattr(module_class, "config_file_name", None)if isinstance(config_file_name, str):@@ -1549,12 +1524,7 @@ class FastSentenceTransformer(FastModel):with open(config_path, encoding = "utf8") as f:config = json.load(f)except (OSError, ValueError) as exception:- # The file is there and cannot be read, which is not the same as not being- # there: the loader opens this same path next and its read may succeed, so- # skipping here meant a Dense activation, a WordEmbeddings tokenizer or a- # Router type could be imported with nothing having checked it. The- # refusal the caller's message promised was only ever about the fetch;- # this is the read.+ # Present but unreadable is not absent: the loader may read it next, so refuse.import sentence_transformersif Version(sentence_transformers.__version__).major < 6:@@ -1593,11 +1563,7 @@ class FastSentenceTransformer(FastModel):elif isinstance(config.get(key), str):refs.append((key, config[key], prefix))- # Upstream reads its own file and only falls back when the parsed content is- # falsey (Router.py: `if not config:`), so once a real config has been read- # there is no second file the loader will look at. Reading both and taking the- # union refused a repository whose router_config.json is clean because an- # unrelated config.json sat beside it, which is a load upstream completes.+ # Upstream falls back only when its own file parses falsey, so never union both files.if config:break@@ -1733,11 +1699,7 @@ class FastSentenceTransformer(FastModel):)if path:if resolved is not None:- # _module_path resolves through hf_hub_download, so online this is the- # commit the branch points at right now and offline it is the cached- # snapshot, which is the only thing the load could use either. Both are- # the snapshot the load would reach on its own, so recording it here- # pins the load to what was checked without asking the hub again.+ # Pin the load to the snapshot that was checked.resolved["revision"] = FastSentenceTransformer._snapshot_revision(path)return path@@ -1753,11 +1715,7 @@ class FastSentenceTransformer(FastModel):def _cached_answer():"""What the local cache already knows, or None if it knows nothing."""try:- # No default of our own: HUGGINGFACE_HUB_CACHE is the legacy constant and- # does not follow HF_HUB_CACHE, so naming it searched a different cache- # from the one hf_hub_download writes, and a recorded absence there was- # missed. Passing None lets the hub apply the same default it applies to- # the download below.+ # None: HUGGINGFACE_HUB_CACHE is legacy and does not follow HF_HUB_CACHE.return try_to_load_from_cache(model_name,"modules.json",@@ -1767,14 +1725,8 @@ class FastSentenceTransformer(FastModel):except Exception:return None- # Deliberately not consulted before the download. A recorded absence is keyed to- # whatever commit the local refs file points at, which for a branch is a stale- # pointer, so answering "this repo has no modules.json" from it decided a security- # question against a snapshot nobody had checked was current, and reported no- # commit, which left the load unpinned. A branch that gains a modules.json between- # the two then loads an unchecked module type. The cache is still the answer when- # the hub cannot be reached, which is what the LocalEntryNotFoundError handler- # below uses it for, so an offline load behaves as it did.+ # Not consulted before the download: a cached absence is keyed to a possibly stale branch ref.+ # Still used offline (LocalEntryNotFoundError below).try:downloaded = hf_hub_download(model_name,@@ -1787,26 +1739,15 @@ class FastSentenceTransformer(FastModel):resolved["revision"] = FastSentenceTransformer._snapshot_revision(downloaded)return downloadedexcept LocalEntryNotFoundError as exception:- # Checked before EntryNotFoundError, which it subclasses: not reachable is not the same- # answer as not present, and catching it there read one as the other.+ # Before EntryNotFoundError, which it subclasses: unreachable is not absent.cached = _cached_answer()if isinstance(cached, str):if resolved is not None:resolved["revision"] = FastSentenceTransformer._snapshot_revision(cached)return cachedif cached is not None:- # Unreachable, and the cache already recorded that this repo has no- # modules.json. "The load can only use the cache too" was the reasoning- # here and it is wrong: this request failed, not every request, so the- # delegated load can recover and fetch the current branch, which may have- # gained a module type since the cached answer. Returning success with no- # pin let exactly that through.- #- # So the load is pinned to the commit the cache holds for this revision,- # recovered from a file that lives in the same snapshot. That is the- # snapshot whose absence was recorded, which makes the load consistent- # with what was checked, and offline it is what would have been served- # anyway.+ # Unreachable with a cached absence: pin the load to the cached snapshot's commit, since the load+ # itself may reach a newer branch.snapshot_commit = ""for probe in ("config.json",@@ -1831,9 +1772,7 @@ class FastSentenceTransformer(FastModel):if resolved is not None:resolved["revision"] = snapshot_commitreturn None- # No commit to pin to, so there is no way to make the load match what was- # checked. Fail closed below 6.0, the same rule as every other branch that- # could not establish an answer.+ # No commit to pin: fail closed below 6.0.import sentence_transformersif Version(sentence_transformers.__version__).major >= 6:@@ -1857,31 +1796,16 @@ class FastSentenceTransformer(FastModel):) from exceptionunverifiable = exceptionexcept EntryNotFoundError as exception:- # The repo really has no modules.json at this revision. Pin anyway: absence is- # the thing being validated, and a branch that gains one before the load would- # otherwise bring in an unchecked module type.- #- # The commit comes off the 404 itself, not from a second lookup. Resolving the- # branch again could answer with a newer commit than the one that established- # the absence, which would pin the load to a snapshot nothing had checked: the- # same inversion as validating one commit and loading another, moved one step- # along. The hub returns x-repo-commit on the 404, so the response names- # exactly the commit whose answer was "no modules.json", and it costs nothing.+ # Pin even a true absence, since a branch may gain modules.json; commit from 404 x-repo-commitif resolved is not None:sha = FastSentenceTransformer._commit_of_response(exception)if not sha and FastSentenceTransformer._is_commit(revision):- # The caller already named an immutable commit, so the 404 was- # answered at it and there is nothing for a second resolution to- # disagree with. No header needed.+ # A caller-supplied commit SHA is immutable, so the 404 was answered at it and needs no second resolution.sha = revision.lower()if sha:resolved["revision"] = shaelse:- # No commit from the response and none from the caller, so there is no- # way to make the load match the absence that was just established:- # the delegated request resolves the branch again and can get one that- # has since gained a modules.json. Fail closed below 6.0, the same- # rule as every other branch that cannot establish an answer.+ # No commit to pin: fail closed below 6.0.import sentence_transformersif Version(sentence_transformers.__version__).major < 6:raise ValueError(@@ -1945,26 +1869,18 @@ class FastSentenceTransformer(FastModel):immutable commit, and whenever there was no modules.json to read, and the callerthen loads exactly as it did before."""- # Consent means the code may run, so there is nothing to gate and nothing to import here.- # Resolving anyway would also break a repo-local class: below 6 the delegated loader fetches- # it with get_class_from_dynamic_module, where this helper's fallback cannot.+ # Consent means the code may run; resolving would also break a repo-local class below 6.if trust_remote_code:return ""- # The delegated loads honour SENTENCE_TRANSFORMERS_HOME, and hf_hub_download does not, so- # resolve it here too: otherwise _module_path looks in the wrong cache, swallows the miss,- # and the gate passes on a modules.json it never read.+ # Resolve the cache here: hf_hub_download ignores SENTENCE_TRANSFORMERS_HOME, else gate passes unreadcache_dir = cache_dir or os.environ.get("SENTENCE_TRANSFORMERS_HOME")resolved = {}modules_json_path = FastSentenceTransformer._modules_json_for_gating(model_name, token, cache_dir = cache_dir, revision = revision, resolved = resolved)validated = resolved.get("revision", "")- # Everything below this point reads from the snapshot modules.json came out of, not- # from the caller's revision. Passing the original through meant modules.json could- # resolve commit A while each module config resolved commit B, and since the caller- # pins the load to A, a clean config in B was validated while A's unchecked value- # was the one that ran. That inverts the race rather than closing it.+ # Read configs from modules.json snapshot, not the caller revision; mixed commits go uncheckedconfig_revision = validated or revisionif not modules_json_path:return validated@@ -1972,12 +1888,7 @@ class FastSentenceTransformer(FastModel):with open(modules_json_path, encoding = "utf8") as f:modules_config = json.load(f)except (OSError, ValueError) as exception:- # Fail closed, for the same reason the fetch error does. The file is in hand- # and still unreadable, and the delegated loader opens the very same path- # straight afterwards: a transient read error or a retry that succeeds there- # would import a type nothing ever looked at. "Could not check" is not- # "nothing to check". Only worth refusing over below 6.0, where- # sentence-transformers does not gate the type itself.+ # Fail closed: unreadable now, the loader opens the same path next. Only below 6.0.import sentence_transformersif Version(sentence_transformers.__version__).major >= 6:logging.debug(@@ -1997,8 +1908,7 @@ class FastSentenceTransformer(FastModel):f"`trust_remote_code=True` to allow custom code to be run.") from exceptionif not isinstance(modules_config, list):- # Not a refusal: a modules.json that is not a list names no modules at all,- # and the loader iterates it, so it cannot build a module from this either.+ # Not a refusal: a non-list modules.json names no modules, so the loader builds none either.return validatedfor module_config in modules_config:@@ -2043,10 +1953,7 @@ class FastSentenceTransformer(FastModel):return validated- # The module classes whose own loader resolves a dotted path out of their config: Dense- # reads activation_function, WordEmbeddings reads tokenizer_class, Router and Asym read- # types. Every other shipped class reads plain values only, so an ordinary embedder- # (Transformer, Pooling, Normalize) costs no extra request below.+ # Classes whose loader imports a dotted path from their config._CONFIG_REF_MODULE_CLASSES = frozenset({"Asym", "Dense", "Router", "WordEmbeddings"})@staticmethod@@ -2079,10 +1986,7 @@ class FastSentenceTransformer(FastModel):import sentence_transformersif Version(sentence_transformers.__version__).major >= 6:- # Upstream resolves these through its own gate from 6.0, so there is nothing- # to add and no reason to spend a request. Deliberately the version and not- # hasattr(import_module_class): 5.5 exports that helper while its module- # loaders still resolve the name ungated.+ # The version, not hasattr(import_module_class): 5.5 exports it while still resolving ungated.returnfolder = module_config.get("path")@@ -2101,21 +2005,14 @@ class FastSentenceTransformer(FastModel):if isinstance(config_file_name, str):config_names.append(config_file_name)else:- # config_file_name only exists from 5, so on 3.x and 4.x a WordEmbeddings has- # no such attribute while its loader still opens wordembedding_config.json.- # Asking only for config.json got a 404, left nothing to check, and passed,- # after which the loader read the legacy file and imported its tokenizer_class- # ungated. The local checker already consults this table; so does this now.+ # 3.x/4.x WordEmbeddings opens wordembedding_config.json; check it or tokenizer_class goes uncheckedlegacy = FastSentenceTransformer._LEGACY_MODULE_CONFIG_FILES.get(getattr(module_class, "__name__", ""))if legacy is not None:config_names.append(legacy)config_names.append("config.json")- # Only Router and Asym fall back to config.json when their own file is absent.- # The others open exactly one file, and requesting a second one the loader never- # reads can fail on a cache that is complete for the load but carries no recorded- # 404 for the unused name, turning a loadable offline model into a refusal.+ # Only Router and Asym fall back to config.json; asking for unused files can fail offline.if (getattr(module_class, "__name__", "") in ("Asym", "Router")and "config.json" not in config_names@@ -2144,8 +2041,7 @@ class FastSentenceTransformer(FastModel):revision = revision,)except LocalEntryNotFoundError as exception:- # Checked first: it subclasses EntryNotFoundError, so catching the parent- # above it would read "could not reach" as "not present".+ # Check LocalEntryNotFoundError first: it subclasses EntryNotFoundError; unreachable is not absentraise ValueError(f"Unsloth: Could not read {config_name} of the module {class_ref} in "f"{model_name} to check the class it names "@@ -2155,8 +2051,7 @@ class FastSentenceTransformer(FastModel):f"`trust_remote_code=True` to allow custom code to be run.") from exceptionexcept EntryNotFoundError:- # A genuine 404: this module ships no such config, so there is no class- # ref in it to check.+ # A genuine 404 means this module ships no such config, so there is no class ref in it to check.continueexcept Exception as exception:raise ValueError(@@ -2168,18 +2063,13 @@ class FastSentenceTransformer(FastModel):f"`trust_remote_code=True` to allow custom code to be run.") from exceptionfolders.append(os.path.dirname(downloaded))- # Router.load falls back to config.json when the parsed content is falsey,- # not merely when its own file is absent (Router.py: `if not config:`).- # Stopping at the first file that downloaded therefore validated an empty- # router_config.json and never fetched the fallback, so the `types` the- # loader does resolve went unchecked. A real config is a non-empty dict and- # still stops here, so a working model asks for nothing extra.+ # Router.load falls back to config.json when the parsed content is falsey (`if not config:`),+ # so an empty router_config.json must not stop the walk.try:with open(downloaded, encoding = "utf8") as handle:content = json.load(handle)except (OSError, ValueError):- # Unreadable is not "checked": let the fallback be fetched too, and- # leave the refusal to the reader below, which sees both files.+ # Unreadable is not "checked": fetch the fallback too and let the reader below refuse.content = Noneif content:break@@ -2243,9 +2133,7 @@ class FastSentenceTransformer(FastModel):class_ref = module_config["type"]name = module_config.get("name", str(module_config.get("idx", len(modules))))- # Gate before any download: a refused type must fail the load outright, not fall- # through the "could not download" skip below. Resolved once, since a consented- # repo-local ref costs a Hub round trip.+ # Gate before any download: a refused type must fail the load, not hit the download skip below.module_class = Noneif FastSentenceTransformer._is_transformer_module_ref(class_ref):is_transformer_module = True@@ -2508,8 +2396,7 @@ class FastSentenceTransformer(FastModel):use_unpadding = False,**kwargs,):- # use_unpadding: "auto" packs eligible training batches with >= 8192 padded slots,- # True packs every eligible batch (saves memory, can cost speed).+ # "auto" packs eligible batches with >= 8192 padded slots; True packs every eligible batch.if use_unpadding not in (False, True, "auto") or type(use_unpadding) not in (bool, str):raise ValueError('use_unpadding must be "auto", True, or False')try:@@ -3014,20 +2901,13 @@ class FastSentenceTransformer(FastModel):f"so Unsloth falls back to merge_and_unload, which can only "f"produce 'merged_16bit'.")- # Imported here rather than at module scope: a module-scope bind out of- # unsloth.save closes an import cycle, which is why the two shims above are- # deferred too. See tests/test_cold_import_order.py.+ # Imported here: a module-scope bind out of unsloth.save closes an import cycle+ # (tests/test_cold_import_order.py).from ..save import _is_adapter_save_methodif _is_adapter_save_method(save_method):- # Refused because nothing here writes base weights: self.save_pretrained writes the- # sentence-transformers scaffolding and, for a PEFT auto_model, an adapter, and the- # lines below then delete that adapter and hand the transformer module to- # save_pretrained_merged, leaving modules.json and an adapter with no config.json- # and no weights, which SentenceTransformer cannot load. Before unsloth#11067- # "lora" matched no branch in merge_and_overwrite_lora and fell through to a 16bit- # merge, which happened to write something loadable; an error is the honest- # replacement. Save the adapter with self[0].auto_model.save_pretrained(...).+ # Nothing here writes base weights: the result would be modules.json plus an orphan adapter.+ # Save the adapter with self[0].auto_model.save_pretrained(...).raise NotImplementedError(f"Unsloth: save_method = {save_method!r} is not supported for a "f"SentenceTransformer: `save_pretrained_merged` writes a loadable "@@ -3567,14 +3447,12 @@ def _patch_st_trainer_load_from_checkpoint():raise RuntimeError(f"Unsloth: Bad checkpoint module path for index {idx}.")if not hasattr(module_cls, "load"):raise RuntimeError(f"Unsloth: Module {idx} cannot be reloaded.")- # The class is trusted, coming from the live model, but load() reads the checkpoint's- # own configs and some versions import dotted paths out of them.+ # load() reads the checkpoint's configs, and some versions import dotted paths out of them.FastSentenceTransformer._check_module_config_class_refs(module_dir,saved_type or module_cls.__name__,root,- # The consent the model was loaded with. Hard-coding False would make a resume- # impossible for a model that legitimately needed it, with no way to say so here.+ # The consent the model was loaded with, not False, which would block resuming such modelsgetattr(self.model, "_unsloth_trust_remote_code", False),module_cls,)diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex f47066b8bdc..ac22a9bd2b9 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -51,8 +51,7 @@ def _multimodal_auto_classes():"""import transformers- # Looked up, not referenced: which names exist varies (4.51.3 has both, 5.5.0- # dropped AutoModelForVision2Seq), so only the alias above is always bound.+ # Looked up: which names exist varies (5.5.0 dropped AutoModelForVision2Seq).classes = [AutoModelForVision2Seq]# AutoModelForSpeechSeq2Seq is deliberately absent: it would move Granite Speech in# _is_text_seq2seq_config on transformers 4.57; from_pretrained adds its processor itself.@@ -970,13 +969,8 @@ def _patch_trainer_move_keeps_host_embeddings():def _pin_device_to_decoder(model):- # `model.device` is the device of the first parameter, and the embedding we offload is it, so- # the documented `inputs.to(model.device)` hands a CUDA model CPU ids. The lookup itself still- # works through the hooks above, but `cache_position` is built from `input_ids.device`, so- # `position_ids` stays on the CPU while the hidden states are already on CUDA and the rotary- # embedding dies on a cpu/cuda matmul. Report the first parameter still on an accelerator- # instead, read live so `model.to()` moves are followed and a whole-model move to the CPU- # falls back to the original answer.+ # `model.device` is the offloaded embedding's (CPU), so `inputs.to(model.device)` would leave+ # position_ids on CPU. Report the first parameter on an accelerator instead, read live.cls = type(model)if not cls.__dict__.get("_unsloth_device_skips_offload", False):original = getattr(cls, "device", None)@@ -1059,9 +1053,7 @@ def _resolve_offload_embedding(model.get_output_embeddings() if hasattr(model, "get_output_embeddings") else None)except Exception:- # Honouring an explicit request here is WRONG: the caller goes straight on- # to call get_input_embeddings() unguarded, turning an inapplicable VRAM- # optimisation into a failed load.+ # Not honoured even if explicit: the caller calls get_input_embeddings() unguarded next.return _decline("its embeddings cannot be inspected.")if _embeddings_are_tied(in_embed, out_embed):return _decline("this model ties embed_tokens to lm_head, so offloading saves no VRAM.")@@ -1205,8 +1197,7 @@ VLLM_SUPPORTED_VLM = ["mistral3","qwen3_vl","qwen3_vl_moe",- # Qwen3.5 ships as Qwen3_5ForConditionalGeneration with a vision_config, so it- # reaches this gate even for the text-only checkpoints.+ # Qwen3.5 text-only checkpoints still have a vision_config, so they reach this gate"qwen3_5","idefics3",# Exact-membership gate: "qwen3_5" does not match qwen3_5_moe.@@ -1357,10 +1348,8 @@ _compile_config = CompileConfig()_compile_config.disable = True # Must set manually-# For these model types, eager decode steps skip Unsloth's compiled regions (on by default,-# UNSLOTH_EAGER_DECODE=0 opts out), and UNSLOTH_COMPILE_DECODE=1 opts into CUDA graphs over the-# static cache. Off by default: each new shape costs 35-130 s to compile (A100, 2B), so mixed-# sessions came out ~3x slower overall even though a compiled step is ~5x faster.+# Eager decode skips compiled regions (UNSLOTH_EAGER_DECODE=0 opts out); UNSLOTH_COMPILE_DECODE=1 opts+# into CUDA graphs. Off by default: each new shape compiles for 35-130 s.COMPILE_DECODE_MODELS = ("qwen3_5", "qwen3_5_moe", "gpt_oss")# gpt-oss decode only traces as one CUDA graph with unsloth_zoo's routed experts patch._COMPILE_DECODE_NEEDS_ZOO = {"gpt_oss": "unsloth_zoo.temporary_patches.gpt_oss_routed"}@@ -1428,8 +1417,7 @@ class _EagerDecodeSteps:return self.forward(*args, **kwargs)def __enter__(self):- # transformers reads signature(self.forward) (logits_to_keep, attention_mask,- # position_ids), so the stand-in has to present the real one.+ # transformers reads signature(self.forward), so the stand-in must present the real one.step = self._forward@functools.wraps(self.forward)@@ -1451,8 +1439,7 @@ def _compiles_decode(model):return Falseif os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") in ("1", "partial"):return False- # Mirror transformers' own auto-compile exceptions: when it will not compile the step,- # leave the eager decode path exactly as it was.+ # Mirror transformers' own auto-compile exceptions.quantizer = getattr(model, "hf_quantizer", None)if quantizer is not None and not getattr(quantizer, "is_compileable", False):return False@@ -1463,8 +1450,7 @@ def _compiles_decode(model):def _match_compiled_call(model, compile_decode):- # CompileConfig equality ignores the `disable` attribute, so transformers would keep- # reusing the callable built for the other mode: drop it when the mode changes.+ # CompileConfig equality ignores `disable`, so drop the cached callable when the mode changes.if model.__dict__.get("_unsloth_compile_decode", compile_decode) != compile_decode:model.__dict__.pop("_compiled_call", None)model.__dict__.pop("_last_compile_config", None)@@ -1472,8 +1458,7 @@ def _match_compiled_call(model, compile_decode):def _decode_cache_bucket(length):- # A static cache of a new length recompiles the decode step; round it up to a power of- # two (>= 1024) so later calls with a different max_new_tokens reuse it.+ # Round the static cache length up to a power of two (>= 1024) to reuse compiled steps.if type(length) is not int or length <= 0:return lengthreturn max(1024, 1 << (length - 1).bit_length())@@ -1506,8 +1491,7 @@ class _CompileDecodeOnRepeat:seen = self.model._unsloth_decoded_shapes = set()self.model._unsloth_compiled_batches = {}compiled = self.model._unsloth_compiled_batches.setdefault(key[1], set())- # Once two batch sizes compiled at this length, Dynamo has made batch dynamic (sizes >= 2- # share that graph), so a new batch size costs no compile: skip its eager warm-up call.+ # After two batch sizes compile at a length, Dynamo marks batch dynamic for sizes >= 2; skip warm-upself.compile = key in seen or (type(batch_size) is int and batch_size >= 2 and len(compiled) >= 2)@@ -1982,7 +1966,6 @@ def unsloth_base_fast_generate(self, *args, **kwargs):enabled = dtype in (torch.float16, torch.bfloat16),)# Prepare LoRA- # state_dict = convert_lora_modules(self, dtype = dtype)# FlashAttention breaks on the forced static cache below (unfilled slots stay unmasked while decoding), so delegate after normalization but before it._clear_generation_caches(self)@@ -2029,8 +2012,7 @@ def unsloth_base_fast_generate(self, *args, **kwargs):cache_implementation = "static"if do_bfloat16_mixed_precision:cache_implementation = None- # A static cache drops the media block mask at prefill (#6028). Name the cache- # rather than None, which _prepare_generation_config refills from the default.+ # A static cache drops the media block mask at prefill (#6028); None would be refilled from default.force_dynamic_cache = kwargs.get("past_key_values") is None and _needs_bidirectional_multimodal_mask(self, kwargs)@@ -2047,8 +2029,7 @@ def unsloth_base_fast_generate(self, *args, **kwargs):cache_implementation == "static"and not force_dynamic_cacheand _compiles_decode(self)- # transformers compiles only on these devices and without disable_compile; anywhere- # else a bucketed cache would only cost memory.+ # transformers compiles only on these devices; elsewhere a bucketed cache only costs memory.and getattr(getattr(self, "device", None), "type", None) == "cuda"and not kwargs.get("disable_compile", getattr(generation_config, "disable_compile", False))and hasattr(self, "_prepare_static_cache")@@ -2432,8 +2413,7 @@ def _mxfp4_lora_keeps_experts_packed(device_map = str(getattr(torch, "get_default_device", lambda: "cpu")())except Exception:device_map = "cpu"- # unsloth_zoo only sees offload after this config is built, so check explicit maps here. Its guard- # unpacks every expert on ANY cpu / disk entry, so offloading even lm_head rules packed out.+ # zoo sees offload only after config build, so check maps here; any cpu or disk entry unpacks expertsif isinstance(device_map, dict) and any(str(value).split(":")[0] in ("cpu", "disk") for value in device_map.values()):@@ -2446,8 +2426,7 @@ def _mxfp4_lora_keeps_experts_packed(zoo_mxfp4 = sys.modules["unsloth_zoo.temporary_patches.mxfp4"]except Exception:return False- # zoo's offload flag belongs to the previous load (it clears it only once this load validates);- # this load's offload is judged above and below.+ # Reset the zoo offload flag: it belongs to the previous load, and this load is judged above and belowoffloads = getattr(zoo_mxfp4, "_LOAD_OFFLOADS", None)if isinstance(offloads, list) and offloads:offloads[0] = False@@ -3411,8 +3390,7 @@ class FastBaseModel:auto_model = AutoModelForCausalLMis_vlm = auto_model in [AutoModelForVision2Seq, AutoModelForImageTextToText]is_whisper = whisper_language is not None and whisper_task is not None- # Audio and omni classes need a processor but are NOT image models, so they- # must not widen is_vlm, which arms the image-processor repair path below.+ # Audio and omni classes need a processor but must not widen is_vlm (image-processor repair).needs_processor = is_vlm or auto_model in _multimodal_auto_classes()# FastModel routes Whisper here without auto_model (#2726); audio features need the processor.needs_processor = needs_processor or auto_model is AutoModelForSpeechSeq2Seq@@ -3437,9 +3415,7 @@ class FastBaseModel:# A repo-code VLM may register only AutoModel / AutoModelForCausalLM (DeepSeek-OCR, Nemotron-VL), so auto_model is not a VLM class though the config is a vision model. Keep is_vlm for processor selection, but treat it as a VLM on the vLLM path so a vision_config model is never silently loaded as text-only.is_vlm_config = (is_vlm- # An omni checkpoint hides its vision config under thinker_config, so the- # hasattr below misses it and fast_inference would enter the vLLM- # language-model path with is_vision_model=False.+ # Omni checkpoints nest vision_config in thinker_config, so hasattr misses it: is_vision_model Falseor needs_processoror (not text_only and hasattr(auto_config, "vision_config")))@@ -3719,8 +3695,7 @@ class FastBaseModel:"local_files_only": local_files_only,},)- # Only an explicit bnb 4-bit config the check kept keeps the caller's flags: a pre-quantized- # checkpoint left unarmed (vLLM reads it itself) must not reach vLLM as a bitsandbytes load.+ # A pre-quantized checkpoint left unarmed must not reach vLLM as a bitsandbytes load.if not (_explicit_bnb_4bit and _checked_4bit):load_in_4bit, load_in_8bit = _checked_4bit, _checked_8bitfrom .modelopt_fp8 import (@@ -4035,8 +4010,7 @@ class FastBaseModel:if quant_method == "compressed-tensors" or quantizer is None:passelse:- # Cannot dequantize, since gpt-oss-20b MXFP4 would become gpt-oss-20b-BF16.- # Except LoRA with zoo's packed experts: stays MXFP4 and has a backward.+ # Cannot dequantize (MXFP4 would become BF16), except LoRA with zoo's packed experts.if (load_in_16bitor _mxfp4_lora_keeps_experts_packed(@@ -4165,8 +4139,8 @@ class FastBaseModel:_cast_text_only_prequantized_params(model, torch_dtype)# transformers 5 leaves remote code's non-persistent buffers (RoPE inv_freq, decay slopes) uninitialised.restore_remote_code_non_persistent_buffers(model)- # Must precede _attach_bnb_multidevice_hooks: it returns early while offload_embedding is True.- # Repair remote code first so the offload decision reads the real input embeddings.+ # Before _attach_bnb_multidevice_hooks (it returns early while offload_embedding is True), and after+ # remote code repair so the offload reads the real input embeddings.apply_remote_code_shims(model)offload_embedding = _resolve_offload_embedding(model,@@ -4709,8 +4683,7 @@ class FastBaseModel:"or set HF_HUB_OFFLINE=1 to force local loading. ""Otherwise please check that the model has a tokenizer.") from _last_resort_err- # FastModel never calls load_correct_tokenizer; heal Gemma 4 base BOS from- # the finalized processor / model config (unslothai/unsloth#7903).+ # FastModel never calls load_correct_tokenizer; heal Gemma 4 base BOS here (#7903).from ..tokenizer_utils import _apply_post_load_tokenizer_fixestokenizer = _apply_post_load_tokenizer_fixes(@@ -4797,8 +4770,7 @@ class FastBaseModel:)mark_auto_offload_for_ddp(model, _ddp_auto_swap)- # LAST, like the llama loader: patch_model_and_tokenizer below REPLACES the embedding and lm_head with fresh modules carrying the weights but not the _hf_hook, so a model split across cards would still meet the original cross-device index_select. Idempotent.- # Embeddings offloaded later sit on the host on purpose: a dispatch hook would pull them back.+ # Run last: patch_model_and_tokenizer drops embedding _hf_hook; split models hit cross-device lookups_base = model.get_base_model() if hasattr(model, "get_base_model") else modelif (not fast_inference@@ -5135,8 +5107,7 @@ class FastBaseModel:_moe_module_detect,moe_module_targets = _moe_module_targets,)- # A forward-less wrapper's config hides the thinker's experts; resolve on the core and- # name full paths, since PEFT suffix-matches and would also hit the talker's experts.+ # Resolve on the core: wrapper config hides thinker experts; full paths stop PEFT hitting talker_core_name = getattr(model, "_unsloth_text_core", None)_core = getattr(model, _core_name, None) if isinstance(_core_name, str) else Noneif target_parameters is None and _core is not None:diff --git a/unsloth/optimizers/q_galore_adamw.py b/unsloth/optimizers/q_galore_adamw.pyindex a8575440e0b..4cf54871944 100644--- a/unsloth/optimizers/q_galore_adamw.py+++ b/unsloth/optimizers/q_galore_adamw.py@@ -216,8 +216,8 @@ class QGaLoreAdamW8bit(Optimizer2State):self.update_step(group, p, gindex, pindex)if "rank" in group:- # Decay the pre-update weight BEFORE adding the update; it touches only- # p._saved_data, so p.data still holds the low-rank update below.+ # Decay the pre-update weight BEFORE adding the update; only p._saved_data is touched,+ # so p.data still holds the low-rank update below.if "_wd_saved" in group:p._saved_data.add_(p._saved_data,@@ -241,8 +241,7 @@ class QGaLoreAdamW8bit(Optimizer2State):p._q_scales = scalesp._q_zeros = zerosp._q_shape = shape- # Scalar placeholder to free float memory; the forward pre-hook (install_weight_quant_hooks)- # dequantizes before the next forward pass.+ # Placeholder to free memory; the forward pre-hook dequantizes before the next forward.p.data = torch.empty(1, dtype = p.data.dtype, device = p.data.device)device_synchronize()@@ -280,8 +279,7 @@ class QGaLoreAdamW8bit(Optimizer2State):for name, p in model.named_parameters():if id(p) in weight_quant_params:- # Store metadata without converting weights to uint8; the first step() quantizes after the update,- # and dummy scales/zeros keep _has_weight_quant() True on that first step.+ # The first step() quantizes; dummy scales keep _has_weight_quant() True on that step.p._q_scales = Nonep._q_zeros = Nonep._q_shape = p.data.shapediff --git a/unsloth/optimizers/q_galore_projector.py b/unsloth/optimizers/q_galore_projector.pyindex d3cfa629823..5dc2e3b265c 100644--- a/unsloth/optimizers/q_galore_projector.py+++ b/unsloth/optimizers/q_galore_projector.py@@ -150,8 +150,7 @@ class GaLoreProjector:assert self.proj_type == "std", "Only proj_type='std' is supported."if full_rank_grad.shape[0] >= full_rank_grad.shape[1]:- # A "tall" matrix takes the right projection (grad @ Q^T), a "wide" one the left (Q^T @ grad).- # "wide" matrix → left projection (Q^T @ grad)+ # "tall" takes the right projection (grad @ Q^T), "wide" the left (Q^T @ grad).if self.ortho_matrix is None or step % self.update_proj_gap == 0:float_ortho = self._compute_orthogonal(full_rank_grad,@@ -224,8 +223,7 @@ class GaLoreProjector:U, s, Vh = torch.linalg.svd(matrix, full_matrices = False)result = Vh[:rank, :] if side == "right" else U[:, :rank]else:- # Oversampling p=10, per Halko et al. 2009 (arXiv:0909.4061), which recommends p=5..10 for large- # low-rank matrices.+ # Oversampling p=10, per Halko et al. 2009 (arXiv:0909.4061).q = min(rank + 10, min(m, n))U, s, V = torch.svd_lowrank(matrix, q = q, niter = 2)result = V[:, :rank].t() if side == "right" else U[:, :rank]diff --git a/unsloth/registry/_qwen.py b/unsloth/registry/_qwen.pyindex 31719cd95a1..c6f0cc1c957 100644--- a/unsloth/registry/_qwen.py+++ b/unsloth/registry/_qwen.py@@ -74,8 +74,7 @@ QwenQwQMeta = ModelMeta(quant_types = [QuantType.NONE, QuantType.BNB, QuantType.UNSLOTH, QuantType.GGUF],)-# No QuantType.NONE: the unquantized mirror unsloth/QVQ-72B-Preview was removed from the Hub,-# leaving only the bnb-4bit build; upstream Qwen/QVQ-72B-Preview is still registered.+# No QuantType.NONE: the unquantized unsloth/QVQ-72B-Preview mirror was removed from the Hub.QwenQVQPreviewMeta = ModelMeta(org = "Qwen",base_name = "QVQ",diff --git a/unsloth/registry/registry.py b/unsloth/registry/registry.pyindex 143fbb8c472..45247b0d3de 100644--- a/unsloth/registry/registry.py+++ b/unsloth/registry/registry.py@@ -1,6 +1,4 @@-# ModelMeta.quant_types below is a dataclass field annotated with a PEP 604 union,-# which evaluates at class creation and is a TypeError on the 3.9 floor pyproject-# declares.+# PEP 604 union in a dataclass field annotation is a TypeError on the 3.9 floor without this.from __future__ import annotationsimport warnings@@ -171,8 +169,7 @@ def _register_models(model_meta: ModelMeta, include_original_model: bool = Falseelse:_quant_types = quant_typesfor quant_type in _quant_types:- # NOTE: models registered with org="unsloth" and QUANT_TYPE.NONE are aliases of- # QUANT_TYPE.UNSLOTH+ # org="unsloth" with QuantType.NONE is an alias of QuantType.UNSLOTH._org = "unsloth" # quantized versions of the original modelregister_model(model_info_cls = model_info_cls,diff --git a/unsloth/save.py b/unsloth/save.pyindex b123646b075..8fb3dd427be 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -1356,9 +1356,8 @@ def unsloth_save_model(if isinstance(tokenizer, (PreTrainedTokenizerBase, ProcessorMixin)):tokenizer = patch_saving_functions(tokenizer)- # Normalised before `save_pretrained_settings` is captured, so every writer below gets- # the real value. `_force_safe_serialization` remembers the caller asked for the- # override, which the low-CPU downgrade further down honours.+ # Normalised before `save_pretrained_settings` is captured; `_force_safe_serialization` records the+ # caller's None for the low-CPU downgrade below._force_safe_serialization = safe_serialization is Nonesafe_serialization = _normalize_safe_serialization(safe_serialization)@@ -6209,8 +6208,7 @@ def _push_merged_to_hub_revision(save_kwargs):dict.fromkeys([*(card.data.tags or []), *(save_kwargs["tags"] or []), "unsloth"]))card.save(card_path)- # The staged save prints the temp folder it wrote, which is not where the user asked the- # model to go and is deleted a moment later. Name the destination instead.+ # Name the destination, not the staged temp folder.print(f"Unsloth: Uploading the merged model to '{repo_id}' ...")commit = api.create_commit(repo_id = repo_id,@@ -6232,13 +6230,11 @@ def _push_merged_to_hub_revision(save_kwargs):),commit_description = save_kwargs["commit_description"],)- # Where the files ACTUALLY landed: a branch or a pull request is not the repository- # page, which for a fresh PR upload holds no model files at all.+ # Where the files actually landed: a branch or PR, not the repository page.destination = getattr(commit, "pr_url", None)if destination is None:destination = f"https://huggingface.co/{repo_id}"- # A pull request is checked first: with `create_pr` the files are in the PR, not on- # `revision`, which is only the branch it was opened against.+ # With `create_pr` the files are in the PR, not on `revision`.if save_kwargs["create_pr"]:destination += "/discussions"elif revision is not None:@@ -6348,8 +6344,7 @@ def unsloth_generic_save()_refuse_unsaveable_text_core(model, save_method)- # Rebound rather than kept in a new local, because the `locals()` below is forwarded as- # this function's own keywords.+ # Rebound, not a new local: `locals()` below is forwarded as keywords.safe_serialization = _normalize_safe_serialization(safe_serialization)# Inline, builtins only (no new locals: they are forwarded below), and before the Hub revision@@ -6423,11 +6418,7 @@ def unsloth_generic_save(max_shard_size = max_shard_size,variant = variant,)- # Asked for a pickle and this transformers cannot give one: say so, rather than upload a- # format the caller explicitly declined. The same report `_filter_push_to_hub_kwargs`- # makes for the adapter path, which never reaches this branch. Against the ORIGINAL- # method, since `patch_saving_functions` wraps it in a `(*args, **kwargs)` passthrough- # that would hide a transformers which does honour the request.+ # Raise rather than upload a pickle the caller declined (MTP head attached); check the original method_real_save = getattr(model, "original_model_save_pretrained", model.save_pretrained)if safe_serialization is False and _attached_mtp_head(model) is not None:# The trained head is stitched into safetensors checkpoints only; refuse before writing.@@ -6463,10 +6454,7 @@ def unsloth_generic_save(if state_dict is not None:_save_kwargs["state_dict"] = state_dict- # BEFORE the write: transformers 5 pops each tensor out of a supplied state dict as it- # writes the shard holding it ("remove it from state_dict to avoid keeping the ref",- # modeling_utils.py), so reading the keys afterwards reports an export with no tensors- # at all and would strip an `mtp_num_hidden_layers` the weights really do carry.+ # BEFORE the write: transformers 5 pops tensors out of a supplied state dict as it writes._written_tensor_names = list(state_dict.keys()) if state_dict is not None else Noneprint(f"Unsloth: Saving full fine-tuned model to '{save_directory}' ...")@@ -6483,10 +6471,7 @@ def unsloth_generic_save(try:from unsloth_zoo.saving_utils import reconcile_mtp_config- # The names we just wrote, when we know them: `_checkpoint_tensor_names` declines to- # unpickle an unindexed `pytorch_model.bin`, so a `safe_serialization = False` export- # would otherwise read back "unknown" and keep an `mtp_num_hidden_layers` the weights- # do not carry. Free here -- this state dict is already materialised.+ # `_checkpoint_tensor_names` declines to unpickle an unindexed .bin, so pass the written names.reconcile_mtp_config(save_directory, tensor_names = _written_tensor_names)except ImportError:pass@@ -6499,20 +6484,12 @@ def unsloth_generic_save(print(f"Unsloth: Model saved successfully to '{save_directory}'")elif _is_adapter_save_method(save_method):- # "lora" means "do not merge", so it must not go to the merge. It used to:- # `merge_and_overwrite_lora` has no `"lora"` branch, so the value fell through to a- # 16bit merge and a caller asking for an adapter got a full-size checkpoint with no- # adapter_config.json (2.47 GB for a 1B base, no config.json either). Routed back to- # `unsloth_save_model`, the same adapter save `save_lora_to_custom_dir` and the MLX- # `save_pretrained_merged` already perform for this value.+ # "lora" must not go to the merge (it fell through to a 16bit merge); route to unsloth_save_model.unsloth_save_model(model,tokenizer,save_directory = save_directory,- # The canonical spelling, not the caller's. `unsloth_save_model` normalises with- # `.lower().replace(" ", "_")` and then rejects anything that is not exactly- # "lora", so forwarding `" lora "` verbatim would turn it into `"_lora_"` and- # raise, which is a worse answer than the merge it replaces.+ # Canonical spelling: unsloth_save_model would turn " lora " into "_lora_" and raise.save_method = "lora",push_to_hub = push_to_hub,token = token,@@ -8729,8 +8706,7 @@ def patch_saving_functions(model, vision = False):elif getattr(model, "tokenizer", None) is not None:patch_saving_functions(model.tokenizer)- # A separate attribute name from the tokenizer wrapper above, so a processor that is- # both a tokenizer holder and a model-like object cannot have one shadow the other.+ # A separate attribute name so a tokenizer holder that is also model-like cannot shadow the other.if (not isinstance(model, (PreTrainedTokenizerBase, ProcessorMixin))and hasattr(model, "config")@@ -8818,10 +8794,7 @@ def patch_saving_functions(model, vision = False):return model-# Publish the deferred names back to unsloth.models. Those modules bind shims instead of-# these names to avoid an import cycle (see unsloth/models/vision.py); this module and-# `.models` are both complete by the time this runs, so hand the real objects over and the-# attributes regain their identity, signature and docstring.+# Hand the real objects back to unsloth.models so the shims regain identity, signature and docstring_DEFERRED_INTO_MODELS = {"unsloth.models.vision": ("patch_saving_functions",),"unsloth.models.llama": ("patch_saving_functions",),diff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.pyindex dd768ff08c3..7dce9658fc4 100644--- a/unsloth/tokenizer_utils.py+++ b/unsloth/tokenizer_utils.py@@ -64,9 +64,8 @@ IGNORED_TOKENIZER_NAMES = frozenset()os.environ["UNSLOTH_IGNORED_TOKENIZER_NAMES"] = "\n".join(IGNORED_TOKENIZER_NAMES)-# gemma-4 base mirrors do not prepend <bos> (post_processor.single = [A], google's is [<bos>, A]).-# Not keyed on add_bos_token (google omits it on E4B/31B/26B-A4B and still prepends) nor on repo-# name. -it is skipped: its chat_template emits BOS. unslothai/unsloth#7903+# gemma-4 base mirrors do not prepend <bos>. Not keyed on add_bos_token or repo name; -it is+# skipped since its chat_template emits BOS. unslothai/unsloth#7903_GEMMA4_INSTRUCT_EOS = "<turn|>"# Anchored: a future gemma-4.5 / gemma_45 has its own BOS policy, and DiffusionGemma4... is not gemma 4.@@ -1351,8 +1350,8 @@ def _fix_chat_template(chat_template, is_sharegpt = False):dash_r = "-" if end["dash_right"] else ""open_tag = lambda body: "{%" + dash_l + " " + body + " " + dash_r + "%}"- # Case 1: the template ends with a single trailing {{ expr }} that is the generation prefix, so wrap it in an {% if add_generation_prompt %} block.- # Surrounding whitespace allowed (ERNIE-4.5: `{%- endfor %}\n {{- "..." }}`); it moves inside the block.+ # Case 1: a single trailing {{ expr }} is the generation prefix; wrap it in an agp block.+ # Surrounding whitespace allowed (ERNIE-4.5).trailing = after_endfor.strip()if ("{%" + dash_l + " if" not in after_endfordiff --git a/unsloth/trainer.py b/unsloth/trainer.pyindex 8058052c7d8..0411aff9b5d 100644--- a/unsloth/trainer.py+++ b/unsloth/trainer.py@@ -198,9 +198,8 @@ PADDING_FREE_BLOCKLIST = {"gemma2", # - gemma2: Uses slow_attention_softcapping which has torch.compile issues"gpt_oss", # - gpt_oss: Uses Flex Attention which doesn't handle padding_free correctly}-# Hybrid linear-attention / state-space models (Qwen3.5, Qwen3-Next) carry a recurrent gated-delta-# state plus a causal conv1d that leak across sequence boundaries once packing flattens the batch.-# Detected structurally by _is_hybrid_linear_attention_model, not by model name.+# Hybrid linear-attention / SSM models leak recurrent and conv1d state across packed sequences;+# detected structurally by _is_hybrid_linear_attention_model.def _should_pack(config) -> bool:@@ -623,13 +622,10 @@ def _forward_accepts_packing_kwargs(model, name = "packed_seq_lengths") -> bool:"""if model is None or isinstance(model, str):return True- # Adapter wrappers only: they forward **kwargs through, so the wrapper always- # answers yes while the checkpoint underneath is the one that raises. Stop there,- # since the inner decoder may take **kwargs and answer for a model that does not.+ # Adapter wrappers forward **kwargs, so stop at the checkpoint underneath, not the inner decoder.target = modelfor _ in range(4):- # Delegating wrappers (DataParallel, DDP, FSDP, torch.compile) first. Exact- # isinstance, so nothing else carrying the same attribute name is followed.+ # Exact isinstance, so nothing else with the same attribute name is followed.inner = next((held@@ -643,8 +639,7 @@ def _forward_accepts_packing_kwargs(model, name = "packed_seq_lengths") -> bool:if inner is not None:target = innercontinue- # `PeftMixedModel` next: no `get_base_model`, so the unwrap below would stop on- # a variadic forward that merely delegates.+ # PeftMixedModel lacks get_base_model, so the unwrap below would stop on a delegating forwardmixed = next((held@@ -658,9 +653,7 @@ def _forward_accepts_packing_kwargs(model, name = "packed_seq_lengths") -> bool:if mixed is not None:target = mixedcontinue- # PEFT's own unwrap only: `PreTrainedModel.base_model` is a property returning- # the inner decoder, which usually does take **kwargs, so it answers for the- # wrong module.+ # PEFT own unwrap only: base_model is the inner decoder, which may take kwargs and misanswerunwrap = getattr(target, "get_base_model", None)if not callable(unwrap):break@@ -703,8 +696,7 @@ def _resolve_string_model_class(model_name, model_config, config_arg):if not isinstance(model_name, str) or model_config is None:return None- # In-tree first, which is also TRL's order: `create_model_from_path` does- # `getattr(transformers, config.architectures[0])` and never consults `auto_map`.+ # In-tree first, TRL's order: create_model_from_path never consults `auto_map`.for architecture in getattr(model_config, "architectures", None) or ():try:import transformers@@ -749,10 +741,7 @@ def _resolve_string_model_class(model_name, model_config, config_arg):auto_map = getattr(model_config, "auto_map", None) or {}if not trust_remote_code or not isinstance(auto_map, dict):return None- # The same auth keys the config fetch forwards, `use_auth_token` included:- # transformers honours it as a deprecated alias for `token` across the supported- # range (dynamic_module_utils.py:584 in 4.57.6), so dropping it would authenticate- # one fetch and not the other.+ # Same auth keys as the config fetch, including the deprecated `use_auth_token` alias.forward = {key: init_kwargs[key]for key in (@@ -852,9 +841,7 @@ def _resolve_string_model_config(model_name, config_arg):from transformers import AutoConfiginit_kwargs = getattr(config_arg, "model_init_kwargs", None) or {}- # Forward auth and cache args too: dropping token/use_auth_token made a private hybrid fail to- # load (resolving as None), so it was treated as non-hybrid and packing was enabled without the- # shim.+ # Forward auth and cache args, or a private hybrid resolves as None and skips the shim.forward = {key: init_kwargs[key]for key in (@@ -868,9 +855,7 @@ def _resolve_string_model_config(model_name, config_arg):)if key in init_kwargs}- # TRL merges top-level args.trust_remote_code into the load via setdefault before- # create_model_from_path, so honor it here (model_init_kwargs wins), else a remote-code hybrid- # resolves as None and skips the guard.+ # Honour top-level trust_remote_code as TRL setdefault does, or a remote hybrid skips the guardtop_level_trust_remote_code = getattr(config_arg, "trust_remote_code", None)if top_level_trust_remote_code is not None:forward.setdefault("trust_remote_code", top_level_trust_remote_code)@@ -1091,11 +1076,8 @@ def _create_unsloth_optimizer()if require_embedding_match and not param_groups["embeddings"]:- # Only checked on the delayed path, where the model has been through- # accelerator.prepare. FSDP1 renames parameters to _fsdp_wrapped_module._flat_param,- # so the modules_to_save match above finds nothing and embedding_learning_rate would- # be dropped without a word. Off the delayed path an empty group is ordinary: plenty- # of models simply do not train their embeddings.+ # FSDP1 renames parameters, so modules_to_save matches nothing and the embedding lr would be dropped.+ # Only on the delayed path: elsewhere an empty group is ordinary.raise ValueError("Unsloth: embedding_learning_rate was requested but no embedding parameter ""matched after the model was wrapped, so the embeddings would train at the "@@ -1210,8 +1192,7 @@ def _migrate_legacy_optimizer_state(cursor, migrated_groups = 0, []for group, role in zip(optimizer.param_groups, group_roles):size = len(group["params"])- # Saved group as the base so per-group optimizer state survives (schedule-free- # keeps k, weight_sum, lr_max there); only params and weight_decay are overridden.+ # Saved group as the base so per-group optimizer state survives.migrated = {key: value for key, value in group.items() if key != "params"}migrated.update({key: value for key, value in saved_of_role[role].items() if key != "params"}@@ -1305,9 +1286,8 @@ def _install_legacy_scheduler_resume(scheduler, optimizer):if getattr(base, "_unsloth_legacy_resume", False):return scheduler- # On a per-instance subclass, NOT the instance: a scheduler's state_dict is its __dict__- # minus the optimizer, so an instance attribute puts this closure in every checkpoint and- # torch.save cannot pickle it, failing the first save even with no resume.+ # On a per-instance subclass, not the instance: an instance attribute lands in state_dict and+ # torch.save cannot pickle it.def load_state_dict(self, state_dict):state_dict = dict(state_dict)if getattr(built, "_unsloth_loaded_previous", False):@@ -1552,8 +1532,7 @@ class UnslothTrainer(SFTTrainer):group_size = config.weight_group_size,stochastic = config.stochastic_round,)- # Pre-hooks dequantize INT8 weights to float before each forward, letting the optimizer free float- # weight memory between steps.+ # Pre-hooks dequantize INT8 before each forward, so the optimizer frees float memory between stepsinstall_weight_quant_hooks(model)n_galore = sum(len(g["params"]) for g in param_groups if "rank" in g)@@ -1676,8 +1655,7 @@ def _route_unknown_trainer_kwargs(rename_value_is_unset,)except Exception:- # tests/ AST-load this function into a bare namespace with no package to- # import from, and supply the classifier through globals() instead.+ # tests/ AST-load this function into a bare namespace and supply the classifier through globals().classify_config_kwarg = globals().get("classify_config_kwarg")rename_source = globals().get("rename_source", lambda key: "TRL")removal_source = globals().get("removal_source", lambda key: "TRL")@@ -1702,8 +1680,7 @@ def _route_unknown_trainer_kwargs(if verdict == "accepted":to_config[key] = valueelif verdict == "rename":- # A legacy Optional forwarded at its `None` default says nothing, so- # it must not replace a real value. Same rule as the config path.+ # A legacy Optional at its `None` default says nothing, so it must not replace a real value.if rename_value_is_unset(config_class, detail, value):continueif already_supplied and detail in already_supplied:@@ -1755,8 +1732,7 @@ def _backwards_compatible_trainer(trainer_class, config_class):if ("args" in kwargs) and (Version(trl) >= Version("0.13.0.dev0")):training_args = kwargs.pop("args", None)- # `discard`, not `remove`: a trainer naming its config something other- # than `args` would otherwise die with a bare KeyError here.+ # `discard`, not `remove`: a trainer may name its config something other than `args`.trainer_params.discard("self")trainer_params.discard("args")@@ -1802,8 +1778,7 @@ def _backwards_compatible_trainer(trainer_class, config_class):config_dict.update(additional_config_kwargs)- # Only build the config if the previous init was not TrainingArguments: reinitialising it would re-- # trigger the mutually-exclusive param checks (trl grpo_config.py#L499-L502).+ # Reinitialising TrainingArguments would re-trigger the mutually-exclusive param checks.if not isinstance(training_args, TrainingArguments):config = config_class(**config_dict)elif not isinstance(training_args, _config_family(config_class)):@@ -1813,8 +1788,7 @@ def _backwards_compatible_trainer(trainer_class, config_class):dict_args.pop("push_to_hub_token", None)config = config_class(**{**dict_args, **additional_config_kwargs})else:- # Every trl config subclasses TrainingArguments, so this is the branch real calls take and- # config_dict was going nowhere: set the moved values on the caller's config rather than rebuild it.+ # Every trl config subclasses TrainingArguments: set moved values on the caller's config.config = training_argsfor key, value in additional_config_kwargs.items():# `migrated` keys are already known to be accepted here.@@ -1913,9 +1887,7 @@ def _patch_sft_trainer_auto_packing(trl_module):# Disable padding-free for VLMs / custom collators / blocklisted modelsforward_rejects_packing = not _forward_accepts_packing_kwargs(model)_packing_gate_deferred = model is None or isinstance(model, str)- # Resolve the class a string names, so that case is an ordinary silent block like- # every other reason: after __init__ the only move left is to refuse, the collator- # and transformed datasets having been built from the flags by then.+ # Resolve the class a string names so it is a silent block like the rest; after __init__ only refuse._resolved_class = Noneif _packing_gate_deferred and isinstance(model, str):try:@@ -1976,9 +1948,7 @@ def _patch_sft_trainer_auto_packing(trl_module):elif is_ring_context_parallel:reason = "ring context parallelism"elif forward_rejects_packing:- # Name the real blocker, else this falls through to the- # UNSLOTH_RETURN_LOGITS branch and points at an unset flag. For a string- # `model=` that is the resolved class, not `str`.+ # Name the real blocker (for a string `model=`, the resolved class).blocker = (_resolved_class.__name__if _resolved_class is not None@@ -1986,8 +1956,7 @@ def _patch_sft_trainer_auto_packing(trl_module):)reason = f"{blocker}.forward() does not accept packed_seq_lengths"elif data_collator is None:- # compute_metrics, preprocess_logits_for_metrics, for_inference() and the user can all set it, so- # name the flag and not a setter.+ # Several places can set it, so name the flag, not a setter.reason = "UNSLOTH_RETURN_LOGITS=1"logger.warning(f"Unsloth: packing=True ignored ({reason}).")@@ -2061,13 +2030,8 @@ def _patch_sft_trainer_auto_packing(trl_module):else:raise- # Backstop for the deferred cases: a `model_init=`, or a string whose class could- # not be resolved. It refuses rather than undoing the flags, because TRL has built- # its collator from them and (under packing) transformed the datasets, so clearing- # them would leave batches flattened with nothing naming the sequence boundaries --- # attention and loss crossing examples silently, worse than the TypeError. Re-running- # `__init__` would rebuild them but materialize the checkpoint twice, an OOM in- # exactly the large-model case this is for.+ # Backstop for deferred cases: refuse rather than clear the flags, since TRL already built its+ # collator and datasets from them; clearing would silently cross example boundaries.if _packing_gate_deferred and not _forward_accepts_packing_kwargs(getattr(self, "model", None)):@@ -2158,8 +2122,8 @@ def _patch_trl_trainer():trl_configs = set(x[: -len("Config")] for x in trl_classes if x.endswith("Config"))trl_classes = list(trl_trainers & trl_configs)- # Auto-packing wraps first so it lands INSIDE the backwards-compatible wrapper: a moved `packing`- # kwarg must reach the config before packing is decided, else the block is undone right after.+ # Auto-packing wraps first, inside the backwards-compatible wrapper, so a moved `packing` kwarg+ # reaches the config before packing is decided.try:_patch_sft_trainer_auto_packing(trl)except Exception as exc:diff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.pyindex 82d6529d249..963bcb7f724 100644--- a/unsloth/utils/attention_dispatch.py+++ b/unsloth/utils/attention_dispatch.py@@ -80,8 +80,7 @@ def _xformers_disabled_for_capability(return False-# FlashAttention always wins in select_attention_backend and nothing downgrades flash to xformers,-# so when it is installed xformers is never selected: skip the probe.+# FlashAttention always wins in select_attention_backend, so skip the probe when installed.if HAS_XFORMERS and not HAS_FLASH_ATTENTION and torch.cuda.is_available():if _xformers_disabled_for_capability(torch.cuda.get_device_capability()):HAS_XFORMERS = False@@ -1014,10 +1013,8 @@ SDPA = "sdpa"XFORMERS_BLOCK_DIAG_CLS = xformers.attn_bias.BlockDiagonalCausalMask if HAS_XFORMERS else None-# flash-attn 2 varlen backward int32 overflow guard: the varlen BACKWARD kernel allocates-# dq_accum = zeros(total_q + 128 * n_seqs, n_heads, round_up(head_dim, 32)) and indexes it with-# int32, so at 2**31 elements the kernel faults with an illegal memory access and poisons the CUDA-# context. Forward-only never allocates dq_accum, so the guard requires a backward to be possible.+# flash-attn 2 varlen backward indexes dq_accum with int32: at 2**31 elements it faults and poisons+# the CUDA context. Forward-only never allocates it._INT32_ELEMENTS = 2**31_VARLEN_INT32_GUARD_DISABLED = os.environ.get("UNSLOTH_DISABLE_VARLEN_INT32_GUARD", "0"@@ -1117,8 +1114,7 @@ class AttentionContext:attention_mask: Optional[Tensor]causal_mask: Optional[Any]sliding_window: Optional[int] = None- # PrefixGrouper: non-None routes Q/K/V through the FlexAttention shared-prefix kernel; None leaves- # every existing construction and behavior unchanged.+ # PrefixGrouper: non-None routes Q/K/V via the FlexAttention shared-prefix kernel; None is unchangedprefix_seg_info: Optional[Any] = Noneis_causal: bool = True# The attention module's .training: also true for a checkpointed forward run without grad.@@ -1218,9 +1214,7 @@ def resolve_prefix_seg_info(kwargs, past_key_value, attention_mask):return seg-# One dense window mask per (device, shape, window), reused across layers: every layer of a-# Mistral-style model asks for the identical mask, and at 32K that tensor is 1 GiB with two more-# alive while it is built, so rebuilding it 32 times OOMs the run.+# One dense window mask per (device, shape, window) shared by all layers: at 32K it is 1 GiB._WINDOW_MASK_CACHE: dict = {}@@ -1230,8 +1224,7 @@ def _windowed_causal_mask(q_len: int, k_len: int, sliding_window: int, device) -entry = _WINDOW_MASK_CACHE.get(device)if entry is not None and entry["params"] == params:return entry["mask"]- # Drop the outgoing mask first: it is dead either way, and holding it while the replacement and its- # temporaries are allocated would make a shape change peak a whole mask higher.+ # Drop the outgoing mask first so a shape change does not peak a whole mask higher._WINDOW_MASK_CACHE.pop(device, None)entry = Noneq_pos = torch.arange(k_len - q_len, k_len, device = device)@@ -1300,8 +1293,7 @@ def _run_attention()backend = device_backend- # Flash/xFormers do not support arbitrary attn masks, so with a padding mask present (left-padded- # generation) fall back to SDPA.+ # Flash/xFormers do not support arbitrary attn masks, so a padding mask falls back to SDPA.if context.attention_mask is not None and backend in (FLASH_DENSE,FLASH_VARLEN,@@ -1309,13 +1301,10 @@ def _run_attention():backend = SDPA- # Both varlen-capable backends land in the same flash-attn 2 backward kernel, so guard both before- # the int32 overflow aborts the process. Integer arithmetic plus one cached sync per step.+ # Both varlen backends hit the flash-attn 2 backward kernel, so guard both.if backend in (FLASH_VARLEN, XFORMERS) and not _VARLEN_INT32_GUARD_DISABLED:- # Both terms are needed. Q/K/V: a frozen hidden state feeding trainable LoRA q/k/v still yields a- # Q that requires grad. context.requires_grad: gradient checkpointing runs its FIRST forward under- # no_grad and recomputes with grad on, so keying only on the tensors would pick a different- # backend per pass.+ # LoRA q/k/v yield a grad-requiring Q from frozen inputs; checkpointing's first forward runs under+ # no_grad, so tensors alone would pick a different backend per pass.will_backward = context.requires_grad or (torch.is_grad_enabled() and (Q.requires_grad or K.requires_grad or V.requires_grad))@@ -1329,8 +1318,7 @@ def _run_attention(else context.bsz)if _varlen_backward_overflows_int32(n_seqs, total_q, context.n_heads, context.head_dim):- # SDPA cannot apply logit softcapping, so rerouting a softcapped model (Gemma 2) would keep it- # training on wrong logits and gradients, worse than the fault this guard avoids.+ # SDPA cannot apply logit softcapping, so rerouting Gemma 2 would train on wrong logits.softcap = _configured_softcap(config)if softcap:raise RuntimeError(@@ -1394,8 +1382,7 @@ def _run_attention(torch.is_grad_enabled() and (Q.requires_grad or K.requires_grad or V.requires_grad))sliding_window = context.sliding_window- # A non-positive window means "no local attention", not "a window of nothing": a config spelling- # it 0 would put the mask's lower bound above its causal upper bound.+ # A non-positive window means no local attention.if sliding_window is not None and sliding_window <= 0:sliding_window = None@@ -1585,8 +1572,7 @@ def _run_attention(local_mask = local_mask.to(device = Q.device)if local_mask.dim() == 2:- # Key padding keep mask (bsz, k_len), where 1/True is a real token; the tokenizer attention_mask is- # typically int 0/1.+ # Key padding keep mask (bsz, k_len), 1/True is a real token.if local_mask.dtype == torch.bool:key_keep = local_maskelse:@@ -1627,8 +1613,7 @@ def _run_attention(local_mask = local_mask | no_allowedif local_mask is None and sliding_window is not None and k_len_local > sliding_window:- # SDPA's is_causal is FULL causal and has no window, so with no padding mask to hang the window- # off, a model whose config declares one attended its whole history.+ # SDPA's is_causal has no window, so build the windowed mask explicitly.local_mask = _windowed_causal_mask(q_len_local, k_len_local, sliding_window, Q.device)@@ -1659,8 +1644,7 @@ def _run_attention(and local_mask.dim() >= 3and local_mask.shape[0] > 1):- # Batched masked inference has shown row-coupled drift with SDPA GQA, so fall back to explicit KV- # expansion for deterministic row-wise behavior.+ # Batched masked inference drifts with SDPA GQA, so expand KV explicitly.use_sdpa_gqa = Falseif use_sdpa_gqa and not _sdpa_takes_gqa(diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.pyindex 9972e11c1eb..e63c75d5f7b 100644--- a/unsloth/utils/packing.py+++ b/unsloth/utils/packing.py@@ -92,9 +92,8 @@ def move_xformers_attention_bias(attn_bias: Any, device: torch.device):):return attn_bias- # Move the device-bearing metadata instead of the top-level mask: older xFormers versions demote- # causal masks in their inherited `to` method, and copies also keep later model shards from- # rewriting masks retained for backward.+ # Move the metadata, not the mask: older xFormers demote causal masks in `to`, and copies keep+ # later shards from rewriting masks retained for backward.moved_bias = copy.copy(attn_bias)moved_seqinfos = {}for name, seqinfo in seqinfos:@@ -1784,8 +1783,7 @@ def _host_segment_lengths(seq_lengths) -> Tuple[int, ...]:def _with_padding_segment(lengths: Tuple[int, ...], total_tokens: Optional[int]) -> Tuple[int, ...]:- # TRL pads the flattened padding-free row to pad_to_multiple_of after the lengths are- # taken; the tail gets its own block, since a row outside every block softmaxes to NaN.+ # TRL pads the flattened row to pad_to_multiple_of after lengths are taken; the tail gets its own block or a softmax row goes NaN.if total_tokens is None:return lengthspadding = total_tokens - sum(lengths)diff --git a/unsloth/utils/prefix_grouper.py b/unsloth/utils/prefix_grouper.pyindex c71a0251bcd..9efdcc95b9b 100644--- a/unsloth/utils/prefix_grouper.py+++ b/unsloth/utils/prefix_grouper.py@@ -82,8 +82,7 @@ def tol_ok() -> float:return _TOL_OK-# A diff at or above TOL_KILL means a broken mask/isolation, so the structure is permanently unsafe;-# between tol_ok and TOL_KILL, fall back for this shape but keep trying others.+# TOL_KILL or above means broken mask or isolation: unsafe forever. Between tol_ok and TOL_KILL, fall back for this shape only.TOL_KILL = 1.5@@ -118,8 +117,7 @@ class GroupLayout:) -> torch.Tensor:"""hidden: [1, T, Hdim] (pre-lm_head hidden states, UNSLOTH_RETURN_HIDDEN_STATES=1).Returns [total_rows, W] float32, byte-compatible with the packed path result."""- # In a sharded model hidden may live on the lm-head device, so move the small index maps to- # hidden.device before indexing.+ # In a sharded model hidden may live on the lm-head device.device = hidden.devicepred_h = hidden[0, self.tgt_pred.to(device), :].unsqueeze(0) # [1, N, Hdim]tgt_ids = self.flat_ids[0, self.tgt_flat].to(device).unsqueeze(0) # [1, N]@@ -234,8 +232,7 @@ def build_group_layout(cstart = ((L - logits_to_keep) - left_pad_tokens_per_prompt).to(torch.long)cstart_cpu = cstart.tolist()ids_cpu = input_ids.tolist()- # Per-row real (non-pad) columns: GRPO rows are one contiguous real run, so derive [first, first+n)- # on GPU; the O(B*L) scan is only a non-contiguous fallback.+ # GRPO rows are one contiguous real run; the O(B*L) scan is only a fallback.n_real = keep.sum(dim = 1)first = torch.argmax(keep.to(torch.int8), dim = 1)ar = torch.arange(L, device = device)@@ -284,8 +281,7 @@ def build_group_layout(flat_src_rows.extend([r0] * P)flat_src_cols.extend(prefix_cols)pos_list.extend(range(P))- # Suffixes: every suffix token is a completion-region target, scattered like the packed path, with- # completion_mask hiding prompt-tail positions.+ # Every suffix token is a completion-region target, scattered like the packed path; completion_mask hides prompt-tail positions.for i, r in enumerate(rows):cols = gm["suf_cols"][i]r_i = len(cols)@@ -311,8 +307,7 @@ def build_group_layout(max_left_pad = int(left_pad_tokens_per_prompt.max().item()) if total_rows else 0W = logits_to_keep + max_left_pad- # Self-verify cache key: the mask/index-map/scatter logic is structural, so key on (num_groups,- # group_sizes), not exact lengths.+ # The logic is structural, so key on (num_groups, group_sizes), not exact lengths.grp_sizes = tuple(sorted(len(gm["R_list"]) for gm in groups))sig = (len(groups), grp_sizes)diff --git a/unsloth/utils/prefix_grouper_kernel.py b/unsloth/utils/prefix_grouper_kernel.pyindex 7480f35aa18..8140db7c591 100644--- a/unsloth/utils/prefix_grouper_kernel.py+++ b/unsloth/utils/prefix_grouper_kernel.py@@ -57,22 +57,19 @@ from torch.nn.attention.flex_attention import (flex_attention,)-# GRPO feeds many distinct segment lengths, and at dynamo's default recompile_limit (8) the compiled-# kernel silently reuses a mismatched specialisation, giving wrong results.+# Many distinct segment lengths: at the default recompile_limit (8) the kernel silently reuses a+# mismatched specialisation.torch._dynamo.config.recompile_limit = max(getattr(torch._dynamo.config, "recompile_limit", 8), 256)torch._dynamo.config.accumulated_recompile_limit = max(getattr(torch._dynamo.config, "accumulated_recompile_limit", 256), 2048)-# Compiled kernels: torch.compile fuses the sparse mask into one kernel, and dynamic=True is-# required, since T changes almost every GRPO batch and dynamic=False recompiles per T (~14s each).+# dynamic=True is required: T changes almost every GRPO batch, and dynamic=False recompiles per T (~14s each)._flex_attention_compiled = torch.compile(flex_attention, dynamic = True)_create_block_mask_compiled = torch.compile(create_block_mask, dynamic = True)-# Flash block sizes by Q dtype (env-overridable): the two disjoint key runs stress online-softmax-# accumulation, so fp32 needs 32/32 for a ~1e-6 floor, while bf16 passes parity at 128/64 and is-# ~5x faster (128/128 OOMs Triton on B200).+# fp32 needs 32/32 for a ~1e-6 floor (two disjoint key runs stress online softmax); bf16 128/64 is ~5x faster; 128/128 OOMs Triton on B200._FP32_BLOCK_M = int(os.environ.get("PG_FLEX_BLOCK_M", "32"))_FP32_BLOCK_N = int(os.environ.get("PG_FLEX_BLOCK_N", "32"))_BF16_BLOCK_M = int(os.environ.get("PG_FLEX_BF16_BLOCK_M", "128"))@@ -89,9 +86,7 @@ def _kernel_options_for_dtype(dtype):# Backward-compat constant (fp32 default)._FLEX_KERNEL_OPTIONS = {"BLOCK_M": _FP32_BLOCK_M, "BLOCK_N": _FP32_BLOCK_N}-# The compiled backward trips an Inductor assertion when T is not a multiple of 128, so pad the-# flat sequence: pad tokens attend to and are attended by nothing (all-masked rows return 0) and-# are sliced off the output.+# The compiled backward asserts unless T is a multiple of 128; pad tokens are fully masked and sliced off._PAD_MULTIPLE = 128_PAD_GROUP = -99 # sentinel group id / suffix id for pad tokens@@ -247,8 +242,7 @@ def build_seg_info_multigroup(return seg, group_meta-# Block-mask builder and cache, keyed on (signature, device): the mask depends only on the per-token-# labels and T, so it is reused across layers and steps.+# Block-mask cache, keyed on (signature, device): the mask depends only on per-token labels and T._BLOCK_MASK_CACHE: Dict[Tuple, BlockMask] = {}@@ -299,10 +293,8 @@ def get_block_mask(if bm is not None:return bm- # Move labels to the consumer (Q) device: with a sharded model the seg tensors live on- # input_ids.device and would index cross-device. These copies must also run with inference mode- # DISABLED, like the mask build: built under the no-grad forward's inference_mode, a .to(device)- # copy would be an inference tensor that mask_mod captures and could not be saved for backward.+ # Move labels to the Q device (sharded models), outside inference mode: an inference tensor+ # captured by mask_mod could not be saved for backward.builder = _create_block_mask_compiled if compile_mask else create_block_maskwith torch.inference_mode(False):mask_mod = _make_mask_mod(diff --git a/unsloth_cli/__init__.py b/unsloth_cli/__init__.pyindex fe5ac87f5b6..554d0463bcc 100644--- a/unsloth_cli/__init__.py+++ b/unsloth_cli/__init__.py@@ -54,7 +54,7 @@ if _is_entry_point:_reconfigure_entry_point_streams()# Before typer and the command imports: notebooks run this right after `pip install --no-deps unsloth`.-# `-m` alone could be a host package that imports us, so name the module it runs.+# `-m` alone could be a host package importing us._orig_argv = getattr(_sys, "orig_argv", [])_runs_unsloth_cli = "-munsloth_cli" in _orig_argv or any(a == "-m" and b == "unsloth_cli" for a, b in zip(_orig_argv, _orig_argv[1:])@@ -71,9 +71,7 @@ if (_is_entry_point or (_entry_base == "-m" and _runs_unsloth_cli)) and _sys.argfrom unsloth_cli._system_dir_guard import check_working_directory as _check_working_directory-# Running from System32 or a subdir breaks commands; move out before the command imports, since-# commands.studio resolves STUDIO_HOME at import time (issue #8510).-# A relative UNSLOTH_STUDIO_HOME would otherwise resolve against System32.+# Move out of System32 before command imports: STUDIO_HOME resolves at import, and a relative UNSLOTH_STUDIO_HOME would hit System32._startup_guard = (_check_working_directory(_sys.argv[1:], _os.environ, _sys.platform) if _is_entry_point else None)@@ -82,8 +80,7 @@ from unsloth_cli._ssl_keylog import (drop_unwritable_ssl_keylog_file as _drop_unwritable_ssl_keylog_file,)-# After the move out of System32, so a relative path is judged where ssl will open it, and-# before any command module builds an HTTPS client; the Studio backend's workers inherit it.+# After the move, so a relative path is judged where ssl opens it; before any HTTPS client, since backend workers inherit it.if _is_entry_point:_drop_unwritable_ssl_keylog_file()diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.pyindex 2cc4f427d94..20ad486e680 100644--- a/unsloth_cli/_inference.py+++ b/unsloth_cli/_inference.py@@ -14,9 +14,7 @@ from typing import List, Literal, Optionalimport typer-# Canonical speculative-decoding modes, mirroring the backend's _CANONICAL_SPEC_MODES. Named once-# so the CLI's option annotations, the HTTP payload builders and the in-process loader cannot-# drift apart; typer reads it at runtime to validate --speculative-type.+# Mirrors the backend's _CANONICAL_SPEC_MODES; typer validates --speculative-type with it.SpeculativeType = Literal["auto", "mtp", "dspark", "dflash", "ngram", "mtp+ngram", "off", "ngram-simple"]@@ -25,8 +23,7 @@ _THINK_OPEN = "<think>"_THINK_BLOCK = re.compile(rf"{re.escape(_THINK_OPEN)}.*?</think>", re.DOTALL)_STREAMED_ERROR_PREFIX = "Error: "-# Cloudflare (in front of remote Unsloth proxies like RunPod) 403s the default-# "Python-urllib/X.Y" User-Agent as a bot; send a real one on every request.+# Cloudflare 403s the default urllib User-Agent as a bot._USER_AGENT = "unsloth-cli"_MPI_ENV_PAIRS = (("OMPI_COMM_WORLD_RANK", "OMPI_COMM_WORLD_SIZE"),@@ -74,10 +71,7 @@ def urlopen_local(request, timeout):return _opener(True, True).open(request, timeout = timeout)-# /api/inference/load and /unload pad their body so a proxy cannot time a slow load out,-# committing the 200 before the work finishes. A failure found after that travels only in-band-# under this key, so a client that treats any 200 as success reports a failed load as a-# successful one.+# load and unload pad the body and commit 200 early, so a late failure rides only in-band under this key; a bare 200 reads as success._DEFERRED_ERROR_KEY = "_deferred_error"@@ -186,8 +180,7 @@ def ensure_studio_backend_path(*, seed_cache_env: bool = True) -> None:def configure_quiet_logging() -> None:import logging- # The CLI never configures structlog, so without this every backend INFO line prints. LOG_LEVEL- # is exported so the worker subprocess inherits it.+ # The CLI never configures structlog; LOG_LEVEL is exported so the worker inherits it.level_name = os.environ.setdefault("LOG_LEVEL", "WARNING").upper()level = getattr(logging, level_name, logging.WARNING)os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")@@ -325,8 +318,7 @@ def visible_text(def stream_to_stdout(stream, show_thinking: bool) -> str:- # Backends yield the full text-so-far on each step (llama.cpp ends with a metadata dict,- # skipped); print the growing tail, return the raw text.+ # Backends yield the full text-so-far each step (llama.cpp ends with a metadata dict, skipped).raw = ""shown = ""for chunk in stream:@@ -374,8 +366,7 @@ def collect_stream(stream, show_thinking: bool) -> str:def raise_on_streamed_error(stream):- # Match real backend errors by type (GenStreamError), not the "Error:" text prefix, so a- # completion whose text opens with "Error:" is not misread as a backend failure.+ # Match backend errors by GenStreamError type, not the Error: text prefix, so completion text opening with Error: is not misread.try:ensure_studio_backend_path()from core.inference.orchestrator import GenStreamError@@ -529,8 +520,7 @@ class ChatBackend:self.reply_hit_token_limit = stats_hit_token_limit(holder.get("stats"))def close(self) -> None:- # Shut the worker down directly: the graceful unload_model waits for an ack that compare mode can- # swallow, hanging exit for minutes.+ # Kill the worker directly: unload_model waits for an ack compare mode can swallow.try:if self._kind == "gguf":self._backend.unload_model()@@ -864,9 +854,7 @@ def verify_studio_identity(base: str, timeout: float = 3.0) -> bool:parsed = urlparse(base)host = parsed.hostname or ""port = parsed.port or (443 if parsed.scheme == "https" else 80)- # Resolve to one concrete address and talk to *that* address, then bind the proof to (address,- # port). A name like localhost can resolve to a squatter on ::1 while the real Unsloth is on- # 127.0.0.1.+ # Resolve once and talk to that concrete address, binding the proof to (address, port): localhost may hit a squatter on ::1.try:ip = socket.getaddrinfo(host, port, type = socket.SOCK_STREAM)[0][4][0]except Exception:@@ -879,8 +867,7 @@ def verify_studio_identity(base: str, timeout: float = 3.0) -> bool:headers = {"User-Agent": _USER_AGENT, "Host": parsed.netloc},)try:- # No redirects: a 302 could relay a real Unsloth's proof (see urlopen_no_redirect). Cap the read:- # the server is still unverified.+ # No redirects: a 302 could relay a real Unsloth's proof. Cap the read: still unverified.with urlopen_no_redirect(request, timeout = timeout) as response:proof = json.loads(response.read(65536).decode() or "{}").get("proof")except Exception:@@ -984,8 +971,7 @@ class HttpChatBackend:payload["gguf_variant"] = resident_variantself.gguf_variant = resident_varianttry:- # Read the body, don't close at the headers: a slow load commits its 200 early and pads until- # done, so closing here would generate mid-load and discard the only report of a late failure.+ # Read the whole body, not just headers: closing early discards the only in-band report of a late load failure.read_json_checking_deferred_error(self._base + "/api/inference/load",self._request("POST", "/api/inference/load", payload),@@ -1058,8 +1044,7 @@ class HttpChatBackend:self.reply_hit_token_limit = Falsedef cumulative():- # Accumulate SSE deltas into the full-text-so-far convention the stream helpers expect.- # The server splits reasoning into delta.reasoning_content: re-wrap it in <think> for visible_text.+ # Accumulate SSE deltas into the full-text-so-far form; re-wrap delta.reasoning_content in think tags for visible_text.text = ""thinking = Falsewith resp:@@ -1101,8 +1086,7 @@ class HttpChatBackend:if not (reasoning or delta):continuetext += delta or ""- # An emoji can arrive split across two deltas as lone surrogate halves: hold back a trailing- # half, merge pairs.+ # An emoji can arrive as lone surrogate halves across deltas.visible = textif "\ud800" <= visible[-1] <= "\udbff":visible = visible[:-1]@@ -1138,8 +1122,7 @@ def connect_studio_server(if not base_url:return None- # Explicit server (UNSLOTH_STUDIO_URL) we can't safely attach to means fail loudly; opportunistic- # local discovery just falls back to a local load.+ # Explicit UNSLOTH_STUDIO_URL we cannot safely attach to fails loudly; local discovery falls back.explicit = bool(os.environ.get("UNSLOTH_STUDIO_URL"))def _refuse(reason: str):@@ -1152,8 +1135,7 @@ def connect_studio_server()raise typer.Exit(code = 1)- # Only hand the self-issued JWT (signed with the local secret) to loopback: a remote URL is- # unverified and a real remote Unsloth would reject it anyway.+ # Only hand the self-issued JWT to loopback: a remote URL is unverified.if not is_loopback_url(base_url):return _refuse("it isn't a local Unsloth, so a self-issued token can't "diff --git a/unsloth_cli/_model_catalog.py b/unsloth_cli/_model_catalog.pyindex c609c78edbd..8d3b39882c6 100644--- a/unsloth_cli/_model_catalog.py+++ b/unsloth_cli/_model_catalog.py@@ -137,17 +137,13 @@ def exported_entries() -> List[ModelEntry]:if export_type == "gguf" and _gguf_export_task(path, name, base) in NON_CHAT_TASKS:continueif export_type == "gguf":- # No complete quant means every candidate is zero-byte or short a shard, which survives- # resolve_model_config() and fails only at load time. Drop it only when positively unloadable: a- # falsy result also means "could not tell".+ # Drop only when positively unloadable: a falsy result also means "could not tell".load_id = _preferred_complete_gguf(path)if not load_id and not _local_dir_holds_a_payload(Path(path)):continueelse:load_id = None- # Positively loadable, not merely "not torn". scan_exported_models types a checkpoint as "lora" on- # adapter_config.json alone, so an interrupted export leaves a config and no weights and the- # picker offered a directory load_peft_weights raises ValueError on.+ # scan_exported_models calls a dir "lora" on adapter_config.json alone; require weights.if not _local_dir_holds_a_payload(Path(path)):continueentries.append(ModelEntry("Fine-tunes", name, export_type, load_id or path))@@ -188,13 +184,10 @@ def _reachable_snapshots(repo_path: Path, load_id: Optional[str] = None) -> Listreturn []pinned = _pinned_snapshot(repo_path, load_id)if pinned is not None:- # Returned as validated, not re-checked against `available`: inventory_scan resolves the snapshot- # it pins while cache_path keeps the configured spelling, so under a symlinked cache root the two- # name one directory and fail lexical equality, and the membership test would drop a good pin.+ # Not re-checked against `available`: under a symlinked cache root the two spellings differ.return [pinned]try:- # ValueError too: an undecodable ref raises UnicodeDecodeError, which is not an OSError, and- # uncaught it leaves _safe hiding every Downloaded row over one repo.+ # ValueError too: an undecodable ref raises UnicodeDecodeError, not OSError.ref = (repo_path / "refs" / "main").read_text(encoding = "utf-8").strip()except (OSError, ValueError):ref = ""@@ -216,8 +209,7 @@ def _complete_quants(snapshot: Path) -> Optional[set]:complete = complete_snapshot_variants(str(snapshot))except Exception:return None- # Empty here means the check could not tell, not that nothing loads: a genuinely incomplete repo- # arrives partial and never reaches the picker.+ # Empty means the check could not tell, not that nothing loads.return set(complete) or None@@ -480,8 +472,7 @@ def cached_entries() -> List[ModelEntry]:# A cached embedding/CLIP repo has task None like any chat repo; can_chat is the gate.if row.get("capabilities", {}).get("can_chat") is False:continue- # A diffusion repo also carries no task, and its pipeline root has no config for can_chat to read,- # so neither gate above catches it.+ # A diffusion repo carries no task and no root config, so neither gate catches it.if row.get("diffusers"):continueentries.append(ModelEntry("Downloaded", row["repo_id"], "", _cached_model_load_id(row)))@@ -539,15 +530,12 @@ def _local_dir_holds_a_payload(path: Path) -> bool:)from utils.paths.path_utils import is_appledouble_metadata- # A pipeline keeps its weights in component subdirs, so the torn test below reads an empty root- # and would call every pipeline unserviceable.+ # A pipeline keeps its weights in component subdirs; the torn test would reject every one.if _is_diffusers_pipeline_dir(path):return Trueif _local_payload_is_torn(path):return False- # iterdir, not glob("*.gguf"): the glob is case-sensitive on Linux and macOS while- # _is_main_gguf_filename lowercases first, so a folder holding Model.GGUF was classified as a- # GGUF model and then dropped by this gate.+ # iterdir, not glob("*.gguf"): the glob is case-sensitive on Linux and macOS.try:children = list(path.iterdir())except OSError:@@ -627,8 +615,7 @@ def local_folder_entries() -> List[ModelEntry]:) or model.partial:continueis_gguf = model.model_format == "gguf" or model.path.lower().endswith(".gguf")- # No format gate: _dir_model_format reports only "gguf" or None, so a safetensors checkpoint- # arrives as None and a "safetensors" literal dropped every non-GGUF model.+ # No format gate: _dir_model_format yields only gguf or None, so a safetensors literal would drop every non-GGUF model.if _local_model_task(model) in NON_CHAT_TASKS:continue# No format gate, so embedding and CLIP exports get through; only this stops them.@@ -667,8 +654,7 @@ def _safe(fn) -> List[ModelEntry]:# Same truthy set the rest of the tree uses (utils.utils, utils.transformers_version).if os.environ.get("UNSLOTH_DEBUG", "").strip().lower() in ("1", "true", "yes", "on"):raise- # Not at module scope: this module must pull in nothing beyond the inventory layer- # (test_catalog_inventory_works_without_fastapi_or_routes).+ # Not at module scope: this module must pull in nothing beyond the inventory layer (test_catalog_inventory_works_without_fastapi_or_routes).import typertyper.echo(@@ -680,8 +666,7 @@ def _safe(fn) -> List[ModelEntry]:def _shorten_names(entries: List[ModelEntry]) -> None:- # Counted over EVERY visible label, not just the prefixed ones: a fine-tune already named- # Qwen3-0.6B is what an unsloth/Qwen3-0.6B row would collide with once shortened.+ # Count every visible label: an unprefixed fine-tune can collide once prefixes are shortened.counts = {}for entry in entries:short = entry.name.split("/")[-1].lower()diff --git a/unsloth_cli/_studio_deps.py b/unsloth_cli/_studio_deps.pyindex b5db9d270cf..7cd280efd1b 100644--- a/unsloth_cli/_studio_deps.py+++ b/unsloth_cli/_studio_deps.py@@ -194,8 +194,7 @@ def _venv_site_packages(root: Path) -> List[Path]:if versioned.is_dir():return [versioned]- # Test fixtures and incomplete venvs may not have a runnable interpreter or version entry yet.- # One directory is unambiguous; several are not.+ # Fixtures and incomplete venvs may lack a runnable interpreter, so accept the site-packages dir only when exactly one exists.candidates = sorted(root.glob("lib/python*/site-packages"))return candidates if len(candidates) == 1 else []@@ -237,9 +236,7 @@ def _distributions_in(root: Path) -> Optional[tuple[Dict[str, str], set[str]]]:if name:canonical = _canonical(name)version = dist.version or ""- # pip renames the outgoing record to a `~` sibling while laying the replacement down, so a kill- # there can leave the backup as the only record: it reads as one healthy version, but pip calls- # it an invalid distribution and the payload is renamed with it.+ # pip renames the old record to a ~ sibling mid-install; a kill can leave only that backup, which reads as healthy but is invalid to pip.if not version or canonical in found or stem.startswith("~"):conflicts.add(canonical)if canonical not in found:@@ -259,9 +256,7 @@ def _requirements_root_in(root: Path) -> Optional[Path]:reqs = path / "studio" / "backend" / "requirements"if reqs.is_dir():return reqs- # An editable install can keep studio/ only in its source checkout. Ask the foreign interpreter- # to follow its .pth/finder instead of treating the absent site-packages copy as an incomplete- # environment.+ # An editable install may keep studio/ only in its checkout: ask the interpreter to follow its .pth or finder, not call it incomplete.probe = ("import json, pathlib, studio; ""print(json.dumps(str(pathlib.Path(studio.__file__).resolve().parent / "@@ -323,9 +318,7 @@ def install_state(extra_roots: Sequence[Path] = (), deep: bool = False) -> dict:installed_conflicts = foreign_distributions[1] if foreign_distributions is not None else set()req_root = _requirements_root_in(root) if foreign else Noneif foreign and (foreign_distributions is None or req_root is None):- # Never answer for the caller when the requested environment cannot be inspected: that can turn- # a torn or ambiguous managed venv into a healthy result merely because the external CLI has- # matching packages.+ # Never answer for an uninspectable environment: that could report a torn venv as healthy.return {"ok": False,"manifest_ok": False,@@ -345,15 +338,13 @@ def install_state(extra_roots: Sequence[Path] = (), deep: bool = False) -> dict:kwargs["installed_conflicts"] = installed_conflictsif deep and _verify_install_supports(module, "deep"):kwargs["deep"] = True- # Without that venv's site-packages the scan answers for this interpreter's tree. Guarded- # separately: a module new enough for `deep` may predate `scan_paths`.+ # Without the venv's site-packages the scan covers this interpreter's tree, so pass scan_paths; guard it separately (deep may predate it).if _verify_install_supports(module, "scan_paths"):paths = [str(path) for path in _venv_site_packages(root)]if paths:kwargs["scan_paths"] = pathsreturn module.verify_install(**kwargs)- # Off for `desktop-capabilities`: the Tauri preflight times it out at 10s and a probe that- # overruns repairs a healthy venv. `verify-install` is untimed, so it opts in.+ # Off for `desktop-capabilities`: its 10s preflight timeout would repair a healthy venv.deep_kwargs = {"deep": True} if (deep and _verify_install_supports(module, "deep")) else {}state = module.verify_install(root = root, **deep_kwargs)if foreign and not state["deps_ok"]:@@ -404,10 +395,8 @@ def _scan_paths() -> Dict[str, list]:return {"path": paths} if paths else {}-# Top-level dirs several wheels write into, so one uninstall deletes another's files and the-# survivor's RECORD describes a file nothing recreates. einx and torchao both ship-# test/conftest.py and install_python_stack.py force-reinstalls torchao every update;-# unsloth_zoo <= 2026.8.5 shipped tests/ and scripts/ into the same squatted namespace.+# Top-level dirs several wheels write into (einx and torchao both ship test/conftest.py), so one+# uninstall deletes another's files._SHARED_NON_RUNTIME_ROOTS = frozenset(("test",@@ -424,9 +413,7 @@ _SHARED_NON_RUNTIME_ROOTS = frozenset())-# Rewritten in place by our own setup: setup.ps1/setup.sh run `npm install` inside the installed-# tree, and npm dedupes hoisted entries under legacy-peer-deps, shrinking the lockfile below its-# recorded size.+# setup.ps1/setup.sh run `npm install` inside the installed tree, shrinking the lockfile._INSTALLER_REWRITTEN_NAMES = frozenset(("package-lock.json",))@@ -484,8 +471,7 @@ def _installed_distribution_groups():version = Nonegroups.setdefault(_canonical(name), []).append((dist, name, bool(version)))continue- # Wheel metadata directory names escape name separators as underscores, so splitting off the- # final version is unambiguous.+ # Wheel metadata directory names escape name separators as underscores, so splitting off the final version is unambiguous.path = getattr(dist, "_path", None)stem = os.path.basename(os.fspath(path)) if path is not None else ""path_name, separator, _version = stem.removesuffix(".dist-info").rpartition("-")@@ -586,8 +572,7 @@ def damaged_installed_files(limit: int = 8) -> List[str]:try:record = dist.read_text("RECORD")except Exception:- # An unreadable or absent RECORD says nothing about damage: editable installs and system- # packages legitimately have none.+ # Editable installs and system packages legitimately have no RECORD.continueif not record:continue@@ -596,8 +581,7 @@ def damaged_installed_files(limit: int = 8) -> List[str]:# A trailing slash is a directory entry, which has nothing to check.if not rel or rel.endswith("/"):continue- # Installer-owned metadata is rewritten in place and drifts from the size recorded inside- # itself; .pyc is regenerated from source.+ # Installer-owned metadata drifts from its recorded size; .pyc is regenerated.if ".dist-info/" in rel or ".egg-info/" in rel or rel.endswith(".pyc"):continuetry:@@ -605,13 +589,11 @@ def damaged_installed_files(limit: int = 8) -> List[str]:except Exception:continuekey = os.path.normcase(str(target))- # Before either filter: a row we cannot verify still owns the path it claims, so another- # distribution's size is ambiguous too.+ # Before either filter: an unverifiable row still owns its path.owners[key] = owners.get(key, 0) + 1if ambiguous or _shared_non_runtime(rel):continue- # The size field is optional and real wheels do leave it blank. Keep the row with an unknown- # size: existence is still checkable, and dropping it meant a deletion went unreported.+ # The size field is optional; keep the row so existence is still checked.recorded: Optional[int] = Noneif len(row) >= 3 and row[2] and not _installer_rewritten(rel):try:@@ -625,13 +607,11 @@ def damaged_installed_files(limit: int = 8) -> List[str]:try:info = target.stat()except OSError:- # Multiple ownership makes the recorded SIZES ambiguous; it cannot explain the file being gone,- # so this branch runs for shared paths too.+ # Shared paths too: shared ownership makes sizes ambiguous, not a missing file.found.append(f"{name}: {rel} is missing")else:if not stat.S_ISREG(info.st_mode):- # A directory standing in for a recorded module still imports as something else, and on POSIX- # its st_size (commonly 4096) can sail past the shrinkage test.+ # A directory in place of a module imports as something else, and its st_size can pass.found.append(f"{name}: {rel} is not a regular file")elif owners[key] == 1 and recorded is not None and info.st_size < recorded:found.append(f"{name}: {rel} is {info.st_size} bytes, expected {recorded}")@@ -647,9 +627,7 @@ def running_outside_managed_venv(extra_roots: Sequence[Path] = ()) -> bool:anything answered from this interpreter would then describe the wrong tree."""if not (Path(sys.prefix) / "pyvenv.cfg").is_file():- # Not a venv at all. On Colab setup.sh deliberately installs the backend into the system Python,- # whose distro-packaged RECORDs legitimately list files the distro never installed (PEP 627), so- # a file check here describes the distro rather than Unsloth.+ # Not a venv: on Colab the system Python RECORDs legitimately list files the distro never installed.return Truereturn _managed_root(extra_roots) is not None@@ -665,9 +643,7 @@ def _missing_studio_packages() -> List[str]:return []-# studio.txt names distributions, ModuleNotFoundError names the import. Only pairs differing by-# more than PEP 503 normalisation need an entry, and each import name below is itself a real but-# unrelated PyPI project.+# Only pairs differing beyond PEP 503 normalisation; each import name is an unrelated PyPI project._IMPORT_TO_DISTRIBUTION = {"jwt": "pyjwt","docx": "python-docx",@@ -694,11 +670,9 @@ def studio_backend_imports(feature: str = "This command", *, studio_only: bool =yieldexcept ModuleNotFoundError as exc:studio_missing = _missing_studio_packages()- # The failed import may not be a studio dependency at all: `train` reaches torch through the same- # wrapper, so only offer the extra when it helps.+ # The failed import may not be a studio dependency: only offer the extra when it helps.trigger = exc.name or ""- # Match on the owning distribution, never the import: `pip install jwt` (or fastmcp.server)- # installs the wrong thing or nothing at all.+ # Match on the owning distribution: `pip install jwt` installs the wrong thing.top = trigger.split(".", 1)[0]needed = _IMPORT_TO_DISTRIBUTION.get(top, top)wanted = _canonical(needed)diff --git a/unsloth_cli/_studio_runtime_gate.py b/unsloth_cli/_studio_runtime_gate.pyindex fa10fad8811..c86f7835a00 100644--- a/unsloth_cli/_studio_runtime_gate.py+++ b/unsloth_cli/_studio_runtime_gate.py@@ -333,10 +333,8 @@ def ensure_managed_environment_is_idle(studio_home: Path) -> None:if int(process.get("ProcessId") or -1) > 0}- # Exempt verified launcher ancestors only: a managed backend starting an update as its child must- # still block replacement.- # venv Scripts\python.exe is a redirector (bpo-34977), so exempt that one hop: our image is base- # Python while sys.executable names the shim.+ # Exempt verified launcher ancestors only: a managed backend child starting an update must still block replacement+ # venv python.exe in Scripts is a redirector (bpo-34977), so exempt that one hop.excluded_pids = {os.getpid()}descendant_pid = os.getpid()self_executable = (process_by_pid.get(os.getpid()) or {}).get("ExecutablePath")diff --git a/unsloth_cli/_studio_stage.py b/unsloth_cli/_studio_stage.pyindex 33a4e049c0b..01b582eb82d 100644--- a/unsloth_cli/_studio_stage.py+++ b/unsloth_cli/_studio_stage.py@@ -17,8 +17,8 @@ from pathlib import PathSTAGE_DIR_NAME = ".update-stage"STAGE_ROOT_ENV = "UNSLOTH_STUDIO_STAGE_ROOT"-# Where a staged update parks the uv cache it used; the live marker is written only once the-# stage is accepted, so an update that never activates cannot redirect the environment.+# Where a staged update parks its uv cache; the live marker is written only once the stage is+# accepted, so an update that never activates cannot redirect the environment.UV_CACHE_MARKER = "uv-cache-dir"SHELL_VERSION_ENV = "UNSLOTH_TAURI_SHELL_VERSION"VENV_NAME = "unsloth_studio"diff --git a/unsloth_cli/_system_dir_guard.py b/unsloth_cli/_system_dir_guard.pyindex 54038007e8c..b6799629a47 100644--- a/unsloth_cli/_system_dir_guard.py+++ b/unsloth_cli/_system_dir_guard.py@@ -19,8 +19,7 @@ STUDIO_HOME against the working directory.import os as _os-# Set by Unsloth Desktop on every CLI child it owns (process.rs); forging it grants nothing,-# the move lands in the caller's own account.+# Set by Unsloth Desktop on every CLI child (process.rs); forging it grants nothing.DESKTOP_MANAGED_ENV = "UNSLOTH_DESKTOP_MANAGED"# The directory process.rs pins, so an older desktop lands in the same place.@@ -142,8 +141,7 @@ def _outside_windows(candidate, windirs, pathmod, sep):norm = _normalize(candidate, pathmod)for windir in windirs:windir_norm = _normalize(windir, pathmod)- # A root-relative candidate carries no drive, so compare that spelling too:- # "\Windows\System32\config\systemprofile" is SYSTEM's profile on whichever drive.+ # A root-relative candidate carries no drive, so compare that spelling too.for form in (windir_norm, pathmod.splitdrive(windir_norm)[1]):if not form:continue@@ -189,9 +187,8 @@ def safe_user_dir(return None-# Commands the desktop runs that take no path from a user; `update` is here so an older desktop-# can still upgrade from the tray. Matched whole, since `studio update --local <path>`-# resolves against the working directory.+# Desktop commands that take no user path (`update` lets an older desktop upgrade). Matched+# whole, since `studio update --local <path>` resolves against the working directory._STUDIO_COMMANDS = (("provision-desktop-auth",),("desktop-capabilities",),@@ -220,8 +217,7 @@ def _is_desktop_backend_launch(rest):return True-# Subcommands that take a path from the caller: `run` takes --model and a raw llama-server-# tail, `update --local` a checkout.+# Subcommands taking a caller path: `run` (--model and a raw llama-server tail) and `update --local` (a checkout)._PATH_TAKING_STUDIO_COMMANDS = ("run", "update")@@ -243,8 +239,7 @@ def _takes_a_path(rest):return Falseif rest[0] in _PATH_TAKING_STUDIO_COMMANDS:return tuple(rest) not in _STUDIO_COMMANDS- # rest[0] is the subcommand name, skipped unless it is a flag. A leading dash does not clear- # an attached value: Click reads `--frontend=.\dist` and `-f.\dist` as values with a path.+ # rest[0] is the subcommand, skipped unless a flag; a leading dash does not clear attached values, as in --frontend=.\dist and -f.\dist.tail = rest if rest[0].startswith("-") else rest[1:]return any(_carries_a_value(arg) for arg in tail)@@ -262,14 +257,11 @@ def is_relocatable_invocation(argv, environ):if all(arg in _HELP_FLAGS for arg in args):return Trueif args[0] != "studio":- # The marker is inherited by everything the backend spawns, so it authorises the desktop's- # studio commands only: rebasing `train --dataset .\data.json` under a stray one is worse- # than refusing.+ # The marker is inherited by everything the backend spawns, so it authorises studio commands only.return Falserest = args[1:]if environ.get(DESKTOP_MANAGED_ENV) == "1" and not _takes_a_path(rest):- # The marker covers desktop builds whose command shape this CLI does not know yet, but must- # not widen to path-carrying commands like `studio run --model .\local.gguf`.+ # Unknown desktop command shapes are allowed, but never path-carrying ones.return Trueif rest and all(arg in _HELP_FLAGS for arg in rest):return True@@ -278,8 +270,7 @@ def is_relocatable_invocation(argv, environ):return tuple(rest) in _STUDIO_COMMANDS-# Path overrides written relative to the folder being left: Unsloth resolves them with-# Path.resolve(), so moving first would silently retarget them.+# Unsloth resolves these with Path.resolve(), so moving first would silently retarget them._RELATIVE_PATH_ENV = (# Unsloth roots: storage_roots.py."UNSLOTH_HOME",@@ -300,14 +291,12 @@ _RELATIVE_PATH_ENV = ("AUDIOCPP_SERVER_PATH","SD_CLI_PATH","SD_SERVER_PATH",- # Model files llama-server reads from the environment and Unsloth reads back when sizing a- # launch (llama_cpp.py). URL and HF-repo spellings are absent: they name no local file.+ # Model file env vars llama-server reads and Unsloth reads back when sizing a launch; URL and HF-repo spellings are excluded."LLAMA_ARG_MODEL","LLAMA_ARG_MMPROJ","LLAMA_ARG_MODEL_DRAFT","LLAMA_ARG_SPEC_DRAFT_MODEL",- # Read straight from the environment as a file path: the ASIC table (import_fixes.py) and the- # vLLM cache root when the caller set it (storage_roots.py fills only a blank one).+ # Read from the environment as file paths: the ASIC table (import_fixes.py) and the vLLM cache root if set (storage_roots.py fills only a blank one)."AMDGPU_ASIC_ID_TABLE_PATH","VLLM_CACHE_ROOT",# A custom ggml backend, preserved into the llama.cpp child (llama_cpp.py).@@ -325,8 +314,7 @@ _RELATIVE_PATH_ENV = ("UNSLOTH_DG_SHIM","UNSLOTH_COMPILE_LOCATION","TORCHINDUCTOR_CACHE_DIR",- # storage_roots.py fills these only when blank, so a relative value the user set is kept as- # written and would name a different folder after the move.+ # storage_roots.py fills these only when blank, so a relative value the user set is kept as written and names another folder after a move."TORCH_EXTENSIONS_DIR","TORCH_HOME","TRITON_HOME",@@ -345,13 +333,11 @@ _RELATIVE_PATH_ENV = ("HF_XET_CACHE","HF_DATASETS_CACHE","HF_ASSETS_CACHE",- # transformers appends this to sys.path, so a relative value would import a different- # generated module after the move.+ # transformers appends this to sys.path, so a relative value would import a different generated module after the move."HF_MODULES_CACHE",# The credential file: a relative value would follow the child and lose access to gated repos."HF_TOKEN_PATH",- # Authoritative when non-blank (storage_roots.py), so `unsloth studio update` would install- # from a different cache after a move.+ # Authoritative when non-blank (storage_roots.py), so a relative value would send unsloth studio update to another cache after a move."UV_CACHE_DIR","TRANSFORMERS_CACHE","SENTENCE_TRANSFORMERS_HOME",@@ -364,9 +350,7 @@ _RELATIVE_PATH_ENV = ("CUDA_ROOT",)-# Pinned when possible, never at the cost of the move: only `studio update --local` reads-# STUDIO_LOCAL_REPO and it keeps the hard error, so an unresolvable one is left behind rather-# than defeating the fallback.+# Best effort, never at the move's cost: leave an unresolvable value behind; only studio update --local reads it and keeps its hard error._BEST_EFFORT_ENV = frozenset(("STUDIO_LOCAL_REPO",))# The most a Windows environment variable holds, terminator included.@@ -375,9 +359,8 @@ _WINDOWS_ENV_VALUE_LIMIT = 32767# The separator is Windows', not the host's: os.pathsep would split "D:\shared" apart anywhere else._PATH_LIST_SEPARATOR = ";"-# Multi-directory values, anchored entry by entry: a relative PYTHONPATH entry is resolved at-# import time and would let the new directory shadow a managed import. PATH is left out:-# refusing the whole move over one unresolvable entry costs more than it protects.+# Anchored entry by entry: a relative PYTHONPATH entry would let the new directory shadow a+# managed import. PATH is left out: one unresolvable entry is not worth refusing the move._PATH_LIST_ENV = ("UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH","CUDA_RUNTIME_DLL_DIR",@@ -409,8 +392,7 @@ def pin_relative_overrides(continueif anchored is not None:if len(anchored) >= _WINDOWS_ENV_VALUE_LIMIT:- # Anchoring a value already near the limit can cross it, and a variable Windows will not- # accept is a failure to report here.+ # Anchoring can push a value near the limit over it; Windows would reject that variable, so raise here instead.raise ValueError(f"{name} does not fit in an environment variable once it ""names its folder in full"@@ -439,17 +421,12 @@ def pin_relative_overrides(return pinned-# Values a consumer does not read as a plain path: anchoring one changes its meaning. Each-# exemption names the reader that proves it, since a directory really called "[llama]" is-# legal on Windows.+# Anchoring these changes their meaning. A directory really called "[llama]" is legal on Windows.# MLX_HOSTFILE holds either a filename or the host list itself as JSON (_inference.py, _json_rank_count_from_env)._INLINE_JSON_ENV = frozenset(("MLX_HOSTFILE", "MLX_IBV_DEVICES"))-# Readers disagree about %VAR%/$VAR: huggingface_hub expandvars HF_HOME, XDG_CACHE_HOME,-# HF_HUB_CACHE and HF_ASSETS_CACHE and Unsloth does SENTENCE_TRANSFORMERS_HOME, but-# hf_cache_settings._canonical() does not. Expanding here makes both readers see one absolute-# path.+# huggingface_hub expandvars these but hf_cache_settings._canonical() does not: expand here._EXPANDED_ENV = frozenset(("HF_HOME",@@ -462,8 +439,7 @@ _EXPANDED_ENV = frozenset())-# The pre-quant allowlist skips a bare on/off token so there is no "allow all" mode-# (diffusion_prequant.py); anchoring one would make it a real allowlisted directory.+# Pre-quant allowlist skips bare on/off tokens, so no allow-all mode exists (diffusion_prequant.py); anchoring one would make it a real dir._TOGGLE_ENV = frozenset(("UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH",))_TOGGLE_TOKENS = frozenset(("1", "true", "yes", "on", "0", "false", "no", "off"))@@ -514,8 +490,7 @@ def pin_relative_sys_path("PYTHONPATH", entry, cwd, pathmod, abspath, None, expanduser)except Exception:- # Best effort, unlike the environment: an import root this process already holds is not worth- # refusing the move over.+ # Best effort: an import root this process already holds is not worth refusing the move over.continueif anchored != entry:syspath[index] = anchored@@ -577,17 +552,14 @@ def _anchor("""original = value = (value or "").strip()if value.startswith("~"):- # Written out rather than skipped: llama_cpp.py hands UNSLOTH_LLAMA_CPP_PATH straight to- # Path(), so a move would leave it naming a folder called "~".+ # llama_cpp.py hands UNSLOTH_LLAMA_CPP_PATH straight to Path(), so expand ~ now.value = (expanduser or pathmod.expanduser)(value)if name in _EXPANDED_ENV and value:- # Written out, so the reader that expands and the one that does not land in the same folder.- # An unset variable is left as written.+ # Written out so the expanding reader and the non-expanding one land in one folder; an unset variable is left as written.expandvars = expandvars or _os.path.expandvarssettled = _expand_settled(value, expandvars)if settled is None:- # One pass does not settle it, so writing the result back would have the reader expand twice;- # if one pass does not name a folder on its own, the move has to be refused.+ # If one pass does not settle it, the reader would expand twice: refuse the move.once = expandvars(value)if _is_fully_qualified(once, pathmod):return None@@ -596,14 +568,12 @@ def _anchor(if not value:return Noneif _is_fully_qualified(value, pathmod):- # Already names one folder, but write back if expanding is what made it name one: the reader- # that does not expand cannot see that.+ # Write back when expanding is what made the value name one folder, because readers that do not expand cannot see it.return value if value != original else Noneif not _names_a_path(name, value):return Noneif pathmod.splitdrive(value)[0] or value.startswith(("\\", "/")):- # Ask the OS: "D:cache" is drive D's current directory and "\cache" the current drive's root,- # neither of which join() knows.+ # Ask the OS: "D:cache" and "\cache" depend on per-drive state join() does not know.return (abspath or pathmod.abspath)(value)return pathmod.join(cwd, value)@@ -623,8 +593,7 @@ def relocation_target(return Noneif home_isdir is None:home_isdir = pathmod.isdir- # A profile that has not mounted yet still has a writable parent, so makedirs would build an- # empty second one that shadows the real one.+ # An unmounted profile still has a writable parent; makedirs would shadow the real one.if not home_isdir(home):return Nonework_dir = pathmod.join(home, WORK_DIR_NAME)@@ -649,8 +618,7 @@ def blocked_message(# allow_public here only: relocating to C:\Users\Public would share one account's state with every other account.home = safe_user_dir(environ, windir, pathmod, sep, expanduser, allow_public = True)if home:- # Quote it, or C:\Users\Jane Doe reaches Set-Location as two arguments. PowerShell single- # quotes are verbatim; cmd needs double quotes once extensions are off.+ # Quote it (spaces); PowerShell single quotes are verbatim, cmd needs double quotes.home_ps = "'" + home.replace("'", "''") + "'"home_cmd = '"' + home + '"'cd_lines = (@@ -720,18 +688,15 @@ def check_working_directory(return None, None, Falseif not relocate or not is_relocatable_invocation(argv, environ):- # `relocate = False` is the imported-as-a-library case: command modules already resolved their- # roots at import time.+ # `relocate = False` is the library case: command modules already resolved their roots.return blocked_message(cwd, argv, environ, windirs, pathmod, sep, expanduser), "red", Truetarget = relocation_target(environ, windirs, pathmod, sep, expanduser, makedirs, home_isdir)unpinnable = None- # The caller's own process state when the guard runs inside a host, so nothing stays rewritten- # unless the move happens.+ # Snapshot so nothing stays rewritten unless the move happens.environ_before = dict(environ)if syspath is None:- # Resolved here rather than inside the pinning, or the console script (which passes nothing)- # would rewrite the real sys.path with no snapshot to restore.+ # Resolved here, or the console script would rewrite sys.path with no snapshot.import sys as _syssyspath = _sys.pathsyspath_before = list(syspath)@@ -739,12 +704,10 @@ def check_working_directory(try:# Before moving, or a relative override would name a folder under the new directory instead of theirs.pin_relative_overrides(environ, cwd, pathmod, abspath, expandvars, expanduser)- # This interpreter read PYTHONPATH before the guard ran and resolves relative entries on every- # import, so it needs anchoring here too.+ # This interpreter resolves relative PYTHONPATH entries on every import.pin_relative_sys_path(cwd, pathmod, syspath, abspath, exists, expanduser)except Exception as error:- # An environment we cannot pin is one we must not move underneath: a drive with no current- # directory, or a list that no longer fits in a Windows variable.+ # An environment we cannot pin is one we must not move underneath.unpinnable = errortarget = Nonemoved = False@@ -762,8 +725,7 @@ def check_working_directory(except OSError:target = Noneif target is None:- # It landed somewhere the CLI still refuses, so go back: the values written for the move only- # mean the same folder from where they were written.+ # The pinned values only mean the same folder from where they were written: go back.try:chdir(cwd)except OSError:@@ -778,8 +740,7 @@ def check_working_directory(if syspath_before != syspath:syspath[:] = syspath_beforeif unpinnable is not None:- # Named separately from the profile case below: blaming the user folder for an unpinnable- # override sends them looking in the wrong place.+ # Named separately: blaming the user folder would mislead.return ((f"Unsloth cannot run from {cwd}, and could not move out of it\n"@@ -791,8 +752,7 @@ def check_working_directory(True,)if target is None:- # Fail closed: nowhere usable outside the Windows tree. This text lands in the desktop's logs,- # so it describes that case, not a shell.+ # Fail closed when nowhere usable exists outside the Windows tree; text goes to desktop logs, so describe that case, not a shell.return ((f"Unsloth cannot run from {cwd}, and no folder outside {windir} was\n"diff --git a/unsloth_cli/claude_subagent_mcp.py b/unsloth_cli/claude_subagent_mcp.pyindex 3f5662ae878..8f3ce13cc09 100644--- a/unsloth_cli/claude_subagent_mcp.py+++ b/unsloth_cli/claude_subagent_mcp.py@@ -373,8 +373,7 @@ def serve(cancel_event.set()def handle_shutdown(_signum: int, _frame: Any) -> None:- # Claude Code may send SIGINT repeatedly; only the first unwinds stdin, later ones must not- # interrupt process-tree cleanup.+ # Only the first SIGINT unwinds stdin; later ones must not interrupt process-tree cleanup.first_signal = not shutdown_started.is_set()shutdown_started.set()cancel_active()diff --git a/unsloth_cli/commands/_password_prompt.py b/unsloth_cli/commands/_password_prompt.pyindex 7afcd4ccd63..1391f04d31c 100644--- a/unsloth_cli/commands/_password_prompt.py+++ b/unsloth_cli/commands/_password_prompt.py@@ -17,8 +17,7 @@ import osimport sysfrom typing import Callable, TextIO-# Keep in sync with studio/backend/models/auth.py ChangePasswordRequest and auth/storage.py.-# The bound is `new_password` min_length.+# Keep in sync with ChangePasswordRequest new_password min_length (studio/backend/models/auth.py) and auth/storage.py.MIN_PASSWORD_LENGTH = 8# Mirror of studio/backend/auth/terminal_prompt.py; keep the name in sync.@@ -125,19 +124,15 @@ def _read_masked_posix(chars: list[str] = []try:with _RestoreTtyOnSignals(fd, old_attrs):- # cbreak + ISIG off (mirrors terminal_prompt.py): with ISIG on, Ctrl-Z suspends mid-read and leaves- # the shell no-echo.+ # ISIG off (mirrors terminal_prompt.py): Ctrl-Z would suspend mid-read and leave no-echo.tty.setcbreak(fd)new_attrs = termios.tcgetattr(fd)new_attrs[3] &= ~termios.ISIGtermios.tcsetattr(fd, termios.TCSADRAIN, new_attrs)- # FIRST keystroke only: a detached pty is a terminal nobody will type- # into, and blocking there means the socket never binds.+ # First keystroke only: a detached pty would block forever and the socket never binds.if first_key_timeout is not None and not _wait_for_first_key(first_key_timeout):raise PromptUnattended- # os.read + incremental decoder with errors="replace": text-mode read(1) can raise or yield a lone- # surrogate that later crashes pbkdf2.- # It raises UnicodeDecodeError.+ # os.read with incremental decoder, errors=replace: text-mode read(1) can raise or yield a lone surrogate that crashes pbkdf2.decoder = codecs.getincrementaldecoder(sys.stdin.encoding or "utf-8")("replace")submitted = Falsewhile not submitted:diff --git a/unsloth_cli/commands/chat.py b/unsloth_cli/commands/chat.pyindex cf0a2d3379f..79609d89d3d 100644--- a/unsloth_cli/commands/chat.py+++ b/unsloth_cli/commands/chat.py@@ -99,8 +99,7 @@ def _get_base_load_in_4bit(model_config) -> bool:def _compare_needs_second_model() -> bool:- # MLX cannot toggle the adapter off, so compare loads the base separately; probe MLX quietly since- # detect_hardware() prints into the chat and imports torch.+ # MLX cannot toggle the adapter off; probe quietly since detect_hardware() prints and imports torch.try:from studio.backend.utils.hardware import hardware as hwdiff --git a/unsloth_cli/commands/eval.py b/unsloth_cli/commands/eval.pyindex 2c77c3b0012..3443c5c7ffd 100644--- a/unsloth_cli/commands/eval.py+++ b/unsloth_cli/commands/eval.py@@ -362,8 +362,7 @@ def resolve_tasks(elif suffix in _DATASET_SUFFIXES:if not path.exists():raise FileNotFoundError(f"Dataset file not found: {entry}")- # an include-path task overrides a registered one of the same name, so keep clear of- # names requested alongside (gsm8k,./gsm8k.jsonl)+ # An include-path task overrides a registered one of the same name, so avoid names requested alongside (gsm8k,./gsm8k.jsonl).name, counter = path.stem, 2while name in names or name in plain:name, counter = f"{path.stem}_{counter}", counter + 1diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex 534b4600fc2..a813c01e28c 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -262,9 +262,7 @@ _CLAUDE_ENV_UNSET = ("CLAUDE_CODE_USE_MANTLE",)_CODEX_ENV_UNSET = ("OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN")-# OpenClaw tries CODEX_API_KEY before OPENAI_API_KEY, so dropping only the latter still embeds-# via OpenAI. CODEX_ACCESS_TOKEN is not a provider candidate but its host exec tool inherits it-# (it is absent from host-env-security-policy.json), and the codex CLI on PATH logs in with it.+# Unset all three: OpenClaw tries CODEX_API_KEY before OPENAI_API_KEY, and CODEX_ACCESS_TOKEN reaches its exec tool and the codex CLI._OPENCLAW_ENV_UNSET = ("OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN")_OPENCLAW_PROFILE_RE = re.compile(r"[a-z0-9][a-z0-9_-]{0,63}", re.IGNORECASE)@@ -731,8 +729,7 @@ def _dsh_command(args: list[str], patch: Optional[str] = None) -> list[str]:else:command = ["dsh", "web", *args]if patch is not None and command[1] not in _DSH_NO_PROFILE_ARGS:- # `dsh <name>` only expands to `--profile <name>` when the name comes first, so the- # overlay goes after a bare profile name and ahead of a leading launcher option.+ # dsh name expands to --profile name only when the name comes first, so put the overlay after a bare name and before any leading option.at = 1 if command[1].startswith("-") else 2command[at:at] = ["--patch", patch]return command@@ -1034,8 +1031,7 @@ def _http_json(# A server that WE auto-started (never one we merely found). Kept at module scope so failure paths and the atexit backstop can tear it down without threading a handle through all six agent commands. Only one agent runs per process, so one slot is enough._auto_served_server: Optional[subprocess.Popen] = None-# Model download + load can be slow, so this caps time since the download last-# advanced, not total elapsed time (see `_start_studio_server`).+# Caps time since the download last advanced, not total elapsed._SERVER_START_TIMEOUT_S = 900_DOWNLOAD_POLL_INTERVAL_S = 1.0# Ceiling on the doubling back-off the progress reader uses after a polling error.@@ -1323,10 +1319,7 @@ class _ModelDownloadProgress:if active in readings:self._display.update(readings[active], active)except Exception:- # Progress is best-effort and never fails the load, but `_start_studio_server`- # reads `downloaded_bytes` to tell a live transfer from a wedged one. Backing- # off keeps a broken endpoint cheap; giving up for good would kill the very- # download this exists to protect, so it never stops probing.+ # downloaded_bytes drives _start_studio_server liveness: back off on failure but never stop probing, or the download it protects dies.self._failures += 1self._retry_at = time.monotonic() + min(2.0**self._failures, _DOWNLOAD_POLL_MAX_BACKOFF_S@@ -1564,8 +1557,7 @@ def _start_studio_server(_shutdown_auto_served()_fail(f"The Unsloth server stopped before it was ready. Last log lines:\n{tail}")tail = _log_tail(log_path, lines = 400)- # `unsloth run` falls forward off a taken port, so poll the port it reports. Printed- # once, so read the whole log, not the tail below.+ # `unsloth run` falls forward off a taken port; it prints the port once, so read the whole log.if not port_followed:bound_port = re.search(rf"^{re.escape(_START_PORT_PREFIX)}(\d+)$",@@ -1591,17 +1583,13 @@ def _start_studio_server()if progress is not None:progress.poll()- # Fresh bytes are the one unambiguous sign the child is moving, so the cap- # measures time since the transfer last advanced rather than total elapsed.- # Server log growth deliberately does NOT count: the loop's own health poll,- # echoed tracebacks and the loader's watchdog heartbeat all keep the log- # growing while nothing loads, which would make this deadline unreachable.+ # The cap measures time since bytes last arrived; log growth does not count (health polls and+ # heartbeats keep it growing while nothing loads).bytes_now = progress.downloaded_bytes if progress is not None else 0if bytes_now > downloaded_bytes:deadline = time.monotonic() + _SERVER_START_TIMEOUT_Sdownloaded_bytes = bytes_now- # New children emit an early key marker, so wait for the final model banner;- # older children only print the key after load, so fall back to that.+ # New children emit an early key marker, so wait for the Model loaded banner; older ones print the key only after load.ready_signal = "Model loaded:" in tail if early_key_seen else "sk-unsloth-" in tailif _studio_healthy(base) and ready_signal:if progress is not None:@@ -1867,14 +1855,11 @@ def _loaded_models_response(answer = _http_json("GET", f"{base}/api/inference/loaded-models", key, timeout = timeout)if isinstance(answer.get("data"), list):return answer- # A Studio older than the 404-ing catch-all answers an unknown /api path with a- # 200 and {"error": ...}, which read as an empty listing reports a resident model- # as unloaded. Anything without a "data" list means the route is not there.+ # Older Studio returns 200 with error JSON for unknown /api paths; no data list means no route, not an empty one that hides a loaded model.except urllib.error.HTTPError as exc:if exc.code != 404:raise- # Fall back, never on an auth or server error. An older Studio still answers on- # /v1/models, with the unloaded catalog entries every caller below already filters out.+ # Fall back, but never on an auth or server error; older Studios still answer /v1/models.return _http_json("GET", f"{base}/v1/models", key, timeout = timeout)@@ -2369,8 +2354,7 @@ def _resolve_model(preload_check(base, key, requested, load.gguf_variant)active_id = active.get("id") if active else Noneannounced_switch = False- # Public IDs can collide, and status hides paths from API keys.- # Wait for the load result to distinguish reuse from replacement.+ # Public IDs can collide and status hides paths: wait for the load result.switch_unknown = Falseif attach_public_id is not None:# An inferred attach never switches model, so the comparison below would misreport a switch and print the server's path.@@ -2516,8 +2500,7 @@ def _resolve_model(elif switch_unknown:typer.echo(f"Loaded {requested} in place of {active_id}.")typer.echo("This unloaded the previous model for every attached session.")- # Match public IDs and load-response names, since the listing may omit paths.- # Keep attach_public_id for inferred requests using opaque identifiers.+ # Match public IDs and load-response names, since the listing may omit paths; keep attach_public_id for inferred opaque IDs.wanted = ({requested, attach_public_id} - {None}) | _public_model_ids(requested)if isinstance(loaded, dict):wanted |= {loaded.get("model"), loaded.get("display_name")} - {None}@@ -2555,8 +2538,7 @@ def _resolve_model()if _inference_status(base, key).get("yours") is False:_fail(_OTHER_ACCOUNT_RESIDENT)- # An empty listing and one holding only unloaded entries are the same situation- # to the user, and which one a server sends depends only on its version.+ # Empty and unloaded-only listings mean the same; the server version decides which it sends._fail("No model is loaded in Unsloth. Load one from the model dropdown in ""the UI, or pass --model <hf-id-or-path> to load it from here."@@ -2786,8 +2768,7 @@ def _answer_offers_variant(for row in variants:if not isinstance(row, dict):return True- # A torn local row proves a load llama cannot serve, so its labels do not vouch in- # strict mode; hub partials stay resumable and count.+ # A torn local row cannot vouch in strict mode; hub partials stay resumable.if strict and row.get("partial") is True:continuequant = row.get("quant")@@ -2800,13 +2781,11 @@ def _answer_offers_variant(if wanted in (label, re.sub(r"-[0-9]+(?:\.[0-9]+)?bpw$", "", label)):return Trueif isinstance(filename, str):- # The local resolver also takes the exact shard-stripped stem: full relative- # spelling only, never a nested file's bare basename.+ # Local resolver also takes the exact shard-stripped stem, full relative spelling only, never a nested file's bare basename.stem = re.sub(r"-\d{3,}-of-\d{3,}$", "", filename.rsplit(".", 1)[0]).lower()if wanted == stem:return True- # Also any whole quant token of the BASENAME, which is how the listing's default- # can name the file by its other label (F16-checkpoint-Q4_K_M -> Q4_K_M).+ # Any whole quant token of the basename (F16-checkpoint-Q4_K_M -> Q4_K_M).if any(wantedin (@@ -2890,8 +2869,7 @@ def _preflight_agent_gguf(if find_studio_server() is not None:returnrepo, _ = _split_repo_variant(model)- # A bare foo.gguf naming no local file is a shorthand, not a path: the load- # canonicalizes it like any other owner-less name.+ # A bare foo.gguf naming no local file is a shorthand, canonicalized like any owner-less name.if "/" not in repo and (not _is_model_path(repo) or repo.lower().endswith(".gguf")):# The server canonicalizes owner-less shorthands to unsloth/<name>.try:@@ -2914,17 +2892,13 @@ def _attach_gguf_check(model: Optional[str],variant: Optional[str] = None,) -> None:- # Attach path: the server resolves the identifier with its own cwd, cache and token, so- # ask it before the load evicts the resident model. A live empty list is definitive;- # any error (an older server included) defers.+ # Ask the server before the load evicts the resident model: only a live empty list is definitive; any error, older servers included, defers.if not model:returnrepo, inline_variant = _split_repo_variant(model)# `--model repo:QUANT` is split before the gate runs, so the caller passes the quant on.variant = variant or inline_variant- # A .gguf filesystem path is GGUF by definition; only the hub-id shape (owner/name.gguf)- # gets probed. A bare foo.gguf naming no local file takes the shorthand route, since the- # load canonicalizes it to unsloth/foo.gguf.+ # A .gguf filesystem path is GGUF by definition; only the hub-id shape owner/name.gguf is probed.bare_missing_gguf = Falseif repo.lower().endswith(".gguf") and not _is_model_path(repo.rsplit(".", 1)[0]):try:@@ -2941,24 +2915,16 @@ def _attach_gguf_check(and "\\" not in repo)):- # detect_gguf_model refuses a companion or big-endian build, so the load falls through- # to transformers and unloads llama-server before failing. Settled by name: the probe's- # empty answer defers whenever the path exists here, which on a loopback attach is- # exactly when it does. The quant never redirects a direct file (from_identifier- # consults it only for a DIRECTORY), though an explicit one still reaches the probe.+ # Refuse companion or big-endian builds by name: otherwise load falls to transformers and unloads llama-server before failing.refused = _direct_gguf_is_companion(repo) or _direct_gguf_is_big_endian(repo)if refused:_fail_agent_needs_gguf(agent, repo)# A drafter folder further up is the server's call.uncertain = _direct_gguf_companion_is_uncertain(repo)- # The variant does not exempt this: a direct file is loaded as itself, so a complete- # sibling matching the quant is never substituted for it.+ # A direct file loads as itself; a matching sibling is never substituted.if not refused and not uncertain:- # Only when this process really shares the server's filesystem: the .gguf suffix- # alone gets an incomplete file loaded, and llama-server finds the missing bytes- # only after teardown. Loopback does not prove that -- 127.0.0.1 may be an SSH or- # container forward where a server-valid path is simply absent here -- so confirm- # this machine's Unsloth and otherwise defer to the probe.+ # Only when this machine shares the server's filesystem, confirmed by identity (loopback may be an SSH or container forward), else defer.+ # Otherwise an incomplete file loads and llama-server finds bytes missing only after teardown.if is_loopback_url(base) and verify_studio_identity(base):# A .gguf-NAMED DIRECTORY is scanned, not loaded, so the suffix proves nothing.try:@@ -2966,16 +2932,11 @@ def _attach_gguf_check(except OSError:is_gguf_dir = Falseif not is_gguf_dir:- # On loopback this reads the server's filesystem, so a name absent from a- # listable directory is absent for the load too, and the .gguf suffix- # still makes it a load that fails after teardown. An unreadable parent- # stays unknowable and defers.+ # On loopback this reads the server's filesystem: a name missing from a listable dir is missing for the load too; unreadable parent defers.try:probe = Path(os.path.expanduser(repo))missing = (- # Only a path this OS spells: a Windows path seen from WSL parses- # to nonsense (C:\... has parent '.') and the server may hold the- # real file, so it defers to the probe.+ # A Windows path seen from WSL parses to nonsense, so defer._path_syntax_is_native(repo)and not probe.is_symlink()and probe.parent.is_dir()@@ -2993,19 +2954,12 @@ def _attach_gguf_check(f"{repo} is incomplete (zero bytes or a split missing shards); "f"re-download or re-copy it before pointing {agent.label} at it.")- # Only a spelling this OS can judge is settled here: a Windows path read- # from WSL skipped the absence check above and reads as ready, so returning- # would vouch for a file nobody looked at. An explicit variant also goes to- # the probe, which judges the marked parent.+ # Settle here only a spelling this OS can judge: a WSL-read Windows path would vouch for an unchecked file; explicit variant goes to probe.if not variant and _path_syntax_is_native(repo):return- # A remote server's filesystem is not ours to read, and the load takes the .gguf- # suffix as authoritative, so ask the server instead. Its errors defer as always.- # Mirrors the load path's shorthand precedence: the raw name first (it may be a directory- # under the server's cwd), then the unsloth/<name> form the load falls back to only when- # the raw name resolves to nothing. A live answer settles that exact id, so the canonical- # form must not vouch for a raw name already answered, else a non-GGUF directory in the- # server's cwd passes the gate and evicts. Only an error falls through.+ # Do not read a remote server's filesystem; the load treats the .gguf suffix as authoritative, so ask the server. Errors still defer.+ # Check the raw name first, as the load does; fall back to unsloth/<name> only when the raw name errors.+ # A live answer settles the raw id; otherwise a non-GGUF directory in the server's cwd would pass the gate and evict.candidates = [repo]if "/" not in repo and (not _is_model_path(repo) or bare_missing_gguf):candidates.append(f"unsloth/{repo}")@@ -3018,14 +2972,11 @@ def _attach_gguf_check(continuevariants = info.get("variants") if isinstance(info, dict) else Noneif isinstance(variants, list):- # A cleanable row is an empty leftover <quant>/ folder: it offers a delete, never- # weights, so it cannot stand in for the load finding something.+ # A cleanable row is an empty leftover <quant>/ folder, never weights.variants = [row for row in variants if not (isinstance(row, dict) and row.get("cleanable"))]- # The load uses a bare name only when it resolves locally, else it canonicalizes to- # unsloth/<name>, so a raw answer the server calls non-local settles nothing. Without- # the flag (older server) the raw answer is still the best evidence there is.+ # Non-local raw answers settle nothing; a server lacking the flag still counts its raw answer.if ("/" not in candidateand candidate != candidates[-1]@@ -3034,13 +2985,10 @@ def _attach_gguf_check(and not info["resolved_locally"]):continue- # The server can answer the gate's real question with the load resolver itself, so it- # settles the round -- even an EMPTY listing, since a root-blind lister can miss a file- # detect_gguf_model still resolves. No filename grammar beats the code that loads.+ # Server answer from the load resolver settles the round, even empty: a root-blind lister can miss a file the load still finds.if isinstance(variants, list) and isinstance(info, dict):offered = info.get("loadable_variants")- # No allow-list means a direct file, which loads as itself whatever the quant, so- # the variantless verdict decides. Only a server omitting the field falls through.+ # No allow-list means a direct file, which loads as itself whatever the quant, so the variantless verdict decides.if variant and offered is None and isinstance(info.get("loadable"), bool):if not info["loadable"]:_fail_agent_needs_gguf(agent, candidate)@@ -3057,13 +3005,8 @@ def _attach_gguf_check(_fail_agent_needs_gguf(agent, candidate)returnif isinstance(variants, list) and variants:- # llama.cpp kills the resident model before resolving the quant, so a quant this- # answer cannot serve is settled here. Local answers take exact labels only; the- # looser filename-token tier is for hub answers.- # "Local" means the server says so (resolved_locally) or, predating that field,- # path syntax / bare names, which resolve locally anyway. owner/name.gguf is- # exempted like the direct-file branch (_is_model_path sees only the suffix),- # since a remote answer wrongly judged local would face local-only rules.+ # llama.cpp kills the resident model before resolving the quant, so settle it here; local answers take exact labels only.+ # owner/name.gguf is exempt like a direct file, since a remote answer judged local would face local-only rules.hub_shaped = (candidate.count("/") == 1and not candidate.startswith(("/", ".", "~"))@@ -3073,8 +3016,7 @@ def _attach_gguf_check(local_answer = bool(info.get("resolved_locally")) or (not hub_shaped and (_is_model_path(candidate) or "/" not in candidate))- # A local answer of only torn rows has no resumable side: llama-server would get- # the incomplete split only after teardown.+ # Only torn local rows: llama-server would fail after teardown.if local_answer and all(isinstance(row, dict) and row.get("partial") is True for row in variants):@@ -3082,9 +3024,7 @@ def _attach_gguf_check(f"{candidate} has only incomplete GGUF weights on the server; "f"finish or re-copy the download before pointing {agent.label} at it.")- # A variantless local load picks from the directory's top level, so rows living- # only in quant subdirectories need the variant that resolves them -- else this- # answer evicts for a load that finds nothing.+ # Variantless local load reads only the top level, so subdirectory-only rows need the variant; else it evicts for a load finding nothing.if (local_answerand not variant@@ -4261,8 +4201,7 @@ def _refresh_windows_path() -> None:def _managed_node_tools() -> Optional[tuple[Path, Path, bool]]:# Best-effort: any failure here means "no managed Node", never a broken launch.try:- # Discovery only: this answers "is there a managed Node", including for a launch aimed- # at a remote server, so it must not create the cache tree on the way past.+ # Discovery only: must not create the cache tree (the launch may target a remote server).ensure_studio_backend_path(seed_cache_env = False)from utils.node_runtime import managed_node_binary, resolve_node_executablenode = Path(managed_node_binary())@@ -4355,8 +4294,7 @@ def _prefer_windows_cmd_sibling(executable: Optional[str]) -> Optional[str]:def _which_with_install_dirs(name: str) -> Optional[str]:- # shutil.which(name), but searching the known agent install dirs too, so a version probe resolves the same binary _launch() will (it augments PATH before it runs). Without this an agent present only in ~/.local/bin / %APPDATA%- # pm is missed, wrongly assumed current, and launched with flags an older build rejects. PATH is restored afterward: only _launch() should persist the augmentation for the child process.+ # Probe lookup also searches agent install dirs so it matches _launch(); else flags reach an older build it rejects; PATH is restored.original = os.environ.get("PATH")_augment_path_with_install_dirs()try:@@ -5821,8 +5759,7 @@ def _vibe_env("VIBE_PROVIDERS": json.dumps([provider]),"VIBE_MODELS": json.dumps([entry]),"VIBE_ACTIVE_MODEL": _VIBE_MODEL_ALIAS,- # Only this model: an inherited allowlist or a resumed cloud session would otherwise- # select a hosted model. An escaped `re:` pattern matches the id exactly.+ # An inherited allowlist or resumed cloud session would select a hosted model."VIBE_ALLOWED_MODELS": json.dumps(["re:" + re.escape(model["id"])]),"VIBE_ENABLE_TELEMETRY": "false","VIBE_ENABLE_UPDATE_CHECKS": "false",@@ -5908,8 +5845,7 @@ def _pi_local_entry(target = os.path.join(source, value)target = os.path.normpath(target)if agents_skills is not None:- # Pi reads ~/.agents/skills through HOME, which moved, so a rule naming the- # user's copy must follow it or it stops matching.+ # Pi reads ~/.agents/skills via HOME, which moved; rules naming the user copy must follow it.user_root, session_root = agents_skillstry:inside = os.path.relpath(target, user_root)@@ -5923,8 +5859,7 @@ def _pi_local_entry(relative = os.path.relpath(target, source)except ValueError: # on another Windows drivereturn target- # Session-relative only where the link landed: a real session directory blocks- # the link, and the entry would then point into it instead of at the user's.+ # Session-relative only where the link landed; where a real session directory blocks it, the entry would point into that directory instead.if relative.split(os.sep)[0] in linked:return relativereturn target@@ -5956,8 +5891,7 @@ def _pi_settings_entries(if not prefix and "*" not in entry and "?" not in entry:entry = _pi_local_entry(entry, source, home, linked, agents_skills)elif not pattern.strip().startswith("~"): # Pi does not expand ~ in patterns- # Pi matches patterns against paths relative to the agent directory, which moved.- # Keep the original too: it still matches basenames and linked directories.+ # The agent directory moved; keep the original too, it still matches basenames.anchored = prefix + _pi_local_entry(pattern,source,@@ -6010,8 +5944,7 @@ def _clear_pi_user_resources(agent_dir: Path, home: Path) -> None:def write_pi_user_resources(agent_dir: Path, home: Path) -> None:"""Expose selected user Pi resources inside an isolated session."""if _wsl_windows_executable(["pi"]):- # Windows Pi cannot reliably follow WSL links into mounted drives, and a session- # an earlier Linux pi prepared still holds them, so drop those before returning.+ # Windows Pi cannot follow WSL links into mounted drives; drop those._clear_pi_user_resources(agent_dir, home)returnuser_home = Path.home()@@ -6096,16 +6029,14 @@ def write_pi_user_resources(agent_dir: Path, home: Path) -> None:continueown = [item for item in own or [] if item not in stale and item not in entries]if entries or own:- # Pi de-dupes packages by identity keeping the FIRST, so session entries- # lead. Patterns apply in order instead, so those stay user-first.+ # Pi keeps the FIRST duplicate package, so session entries lead; patterns stay user-first.settings[key] = own + entries if key == "packages" else entries + ownelse:settings.pop(key, None)if entries:copied[key] = entriesfor key in _PI_USER_VERBATIM_SETTINGS:- # Pi runs every package lookup and install through npmCommand, so inheriting- # the package list without it falls back to an npm that cannot find them.+ # Pi runs every package lookup and install through npmCommand; inherit it along with the package list or npm cannot find them.value = user_settings.get(key)own = settings.get(key)if own is not None and own != previous.get(key):@@ -7635,8 +7566,7 @@ def openclaw(request_body = server_options.request_body(),max_tokens = max_tokens,)- # Scope both config and state so OpenClaw never touches the user's ~/.openclaw.- # Off, else OpenClaw re-imports any provider key it cannot see from a login shell.+ # Scope config and state so OpenClaw never touches ~/.openclaw. Shell env off, else it re-imports keys.env = {"OPENCLAW_CONFIG_PATH": str(config_path),"OPENCLAW_STATE_DIR": str(cfg),@@ -8262,8 +8192,7 @@ def vibe(server_options = server_options,)command = ["vibe", *_yolo_command_flags("vibe", yolo), *ctx.args]- # Like claude, Vibe keeps its own home (~/.vibe: instructions, hooks, trust, agents,- # sessions); the env layer pins the Unsloth provider and model above its config files.+ # Vibe keeps its own home; the env layer pins provider and model above its config files.request_body = server_options.request_body()if "temperature" not in request_body:# Vibe always sends a temperature, which the server honours over the model'sdiff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex cf1a51e4c2e..3225055c2f2 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -48,9 +48,8 @@ def _enable_verbose_access_logs() -> None:os.environ["LOG_LEVEL"] = "DEBUG"-# Root order: UNSLOTH_STUDIO_HOME, STUDIO_HOME, UNSLOTH_HOME/studio, sys.prefix,-# legacy ~/.unsloth/studio. Keep this aligned with storage_roots.studio_root().-# Shim markers mirror install.ps1 / uninstall.ps1 and are matched as bytes.+# Root order: UNSLOTH_STUDIO_HOME, STUDIO_HOME, UNSLOTH_HOME/studio, sys.prefix, legacy+# ~/.unsloth/studio; keep aligned with storage_roots.studio_root(). Markers mirror install.ps1._CMD_SHIM_MARKERS = (b"unsloth-studio-managed-launcher", b"from unsloth_cli import app")_CMD_SHIM_MAX_BYTES = 8192@@ -149,11 +148,7 @@ def _recorded_master_root() -> Optional[Path]:here = STUDIO_HOME.resolve()if not (master.is_dir() and (here == master or master in here.parents)):return None- # A legacy-rooted install has no master root, and both uninstallers already refuse what- # that shape records. storage_roots._is_legacy_studio_tree declines it too, and- # test_unsloth_home_root_agreement.py holds the two together: without this the CLI would- # export UNSLOTH_HOME for a note the backend has declined. Keyed on the TREE, so a note- # naming $HOME or any other ancestor goes with it.+ # Decline a legacy-rooted note, keyed on the tree so a note naming $HOME or an ancestor goes too, like storage_roots._is_legacy_studio_tree.try:if here == (Path.home() / ".unsloth" / "studio").resolve():return None@@ -189,14 +184,8 @@ def _ensure_studio_env_exported() -> None:"""Re-export UNSLOTH_STUDIO_HOME / UNSLOTH_LLAMA_CPP_PATH for custom roots, and for a masterroot the resolver above declined, per subcommand rather than at import, so unrelatedimporters see no env changes."""- # storage_roots.studio_root() honours UNSLOTH_HOME with no install check, so the fallback- # keeping this CLI on an installed legacy root must be told to the backend too: unexported,- # `unsloth studio` runs the legacy venv while the backend inside it writes studio.db, auth- # and the pid file under <master>/studio. Exporting the root does not make it custom, since- # the value equals the legacy path both installers compare against.- # The note, when this run has no UNSLOTH_HOME of its own. Exported rather than merely read,- # because setup runs as a subprocess and would otherwise refresh the runtimes at- # <master>/studio/ while the backend kept launching the ones at <master>/.+ # storage_roots.studio_root() honours UNSLOTH_HOME unconditionally, so export the root this CLI chose,+ # or the backend and setup subprocess write elsewhere.if not (os.environ.get("UNSLOTH_HOME") or "").strip():_recorded = _recorded_master_root()if _recorded is not None:@@ -211,8 +200,7 @@ def _ensure_studio_env_exported() -> None:_is_legacy = STUDIO_HOME.resolve() == _legacy_studioexcept (OSError, ValueError):_is_legacy = STUDIO_HOME == (Path.home() / ".unsloth" / "studio")- # The runtimes are siblings of studio/, at the master root, so STUDIO_HOME/llama.cpp is one- # level too deep. run.py keeps a non-blank value, so a wrong export here wins everywhere.+ # Runtimes are siblings of studio/; run.py keeps a non-blank value, so a wrong export wins everywhere._llama_dir = _master_root_llama_dir()if _llama_dir is None:_llama_dir = (@@ -586,11 +574,8 @@ def _torch_requires_rocm_metapackage(venv_dir: Path) -> bool:return False-# The single gfx arch this install carries kernels for, published for the backend.-# Read by studio/backend/utils/desktop_shell_env.py, which imports ROCm variables a-# desktop launch never received out of the login shell: that profile is where the-# #7331 override lives, so the backend needs the same arbiter this guard uses, not-# just the outcome of running it against a GUI environment that never had the value.+# Read by studio/backend/utils/desktop_shell_env.py, which imports the login shell's ROCm variables+# (where the #7331 override lives), so it needs this arbiter.ROCM_INSTALLED_ARCH_ENV = "UNSLOTH_ROCM_INSTALLED_ARCH"@@ -654,9 +639,7 @@ def _clear_hsa_override_before_launch(silent: bool = False) -> Optional[str]:_venv = STUDIO_HOME / "unsloth_studio"_root = Path(sys.prefix) if _running_in_studio_venv(_venv) else _venv_arch = _clear_hsa_override_contradicting_install(_root)- # Published whether or not anything was cleared here: on a desktop launch the GUI- # environment never carried the override, so the clear above is a no-op and the- # contradicting value is still sitting in the profile the backend is about to read.+ # Published regardless: a desktop launch never had the override, but the profile still does._installed = _installed_rocm_single_arch(_root)if _installed and platform.system() != "Windows":os.environ[ROCM_INSTALLED_ARCH_ENV] = _installed@@ -907,9 +890,7 @@ def _create_api_key_inprocess(name: str) -> str:username = storage.DEFAULT_ADMIN_USERNAME,name = name,)- # Best-effort: the key is already committed and the caller shuts the server- # down on any exception, so raising here would kill a healthy launch and- # re-mint on every retry. Same trade-off as start.py's _write_private_json.+ # Best-effort: raising would kill a healthy launch and re-mint on every retry.try:_write_auth_secret(_cli_api_key_secret_path(name), raw_key)except OSError as exc:@@ -956,8 +937,7 @@ def _load_backend_auth_storage():def _write_auth_secret(path: Path, secret: str) -> None:path.parent.mkdir(parents = True, exist_ok = True)- # mkdir under a 022 umask leaves auth/ world-readable when this runs before the DB connection does it; the files- # below are 0600 either way, but the directory listing names them. Best-effort, like the chmods below.+ # mkdir under a 022 umask leaves auth/ world-readable; the listing names the files.try:os.chmod(path.parent, 0o700)except OSError:@@ -1302,8 +1282,7 @@ def _cli_update_password(returnstale_files = [BOOTSTRAP_PASSWORD_FILE, DESKTOP_SECRET_FILE]if revoke_api_keys:- # Reset only: the rows are gone, so each cached key is now plaintext for a- # dead credential. An ordinary change keeps the rows, so its cache stays valid.+ # Reset only: the rows are gone, so each cached key is plaintext for a dead credential.try:stale_files += sorted(p.name for p in (STUDIO_HOME / "auth").glob(f"{CLI_API_KEY_FILE_PREFIX}*")@@ -3695,11 +3674,8 @@ _PS_PROXY_DEFAULTS_PRELUDE = (_UV_CACHE_BUCKETS = ("archive", "builds", "built-wheels", "wheels", "sdists")-# The subset `uv pip install` CREATES, which is the only uv command studio/setup.sh runs. The-# rule is what uv is measured to write: a `git+` requirement creates git-v0 and builds-v0, so-# those are in, while flat-index-v2 is not created even by `--find-links --no-index`, and-# binaries, environments, osv and python belong to uv self-update, uv venv and uv python.-# Probing a store uv never touches only throws warm caches away. Re-measure on a pin bump.+# Only the stores `uv pip install` creates (setup.sh runs nothing else); probing others discards+# warm caches. Re-measure on a uv pin bump._UV_PIP_STORES = ("archive","builds",@@ -3719,8 +3695,7 @@ def _uv_is_bucket_name(name: str) -> bool:install.ps1, over the narrower kind list: this one only answers whether a bucket holdspackage BYTES, where the installers also probe the kinds uv merely writes."""kind, marker, version = name.rpartition("-v")- # isascii too: str.isdigit() is true for Arabic-Indic and superscript digits, which the sh- # `*[!0-9]*` case and the PowerShell \A[0-9]+\z both reject. uv writes ASCII.+ # isascii too: isdigit() accepts non-ASCII digits, which the sh and PowerShell checks reject.return bool(marker) and version.isascii() and version.isdigit() and kind in _UV_CACHE_BUCKETS@@ -3777,8 +3752,7 @@ def _uv_platform_cache_dir() -> Optional[Path]:return Path(home) / ".cache" / "uv" if home else None-# clap's literals, which is what uv binds UV_NO_CACHE to (BoolishValueParser). `y` and `t` are-# real spellings uv honours, and were missing here, in install.sh and in install.ps1 alike.+# clap's BoolishValueParser literals for UV_NO_CACHE._UV_TRUE = ("1", "y", "yes", "t", "true", "on")@@ -3907,39 +3881,27 @@ def _uv_cache_is_writable(cache_dir: Path) -> bool:probes = [cache_dir]folds = _uv_cache_folds_case(cache_dir)try:- # Only the directories uv OWNS: an unrelated read-only one must not disqualify a- # usable cache, and that is what the kind list above is for.+ # Only the directories uv owns.for entry in cache_dir.iterdir():if not _uv_is_store_name(entry.name):- # On APFS or NTFS `Python-V0` is the same path uv opens as `python-v0`, so- # skipping it would report a cache writable that uv then aborts on.+ # On APFS or NTFS `Python-V0` is the same path as `python-v0`.if not (folds and _uv_is_store_name(entry.name.lower())):continueif not entry.is_dir():- # A file, or a symlink dangling or not, is an existing path to mkdir, so uv- # cannot make the store and aborts. Skipping it would report the cache writable.+ # A file or any symlink is an existing path uv cannot mkdir.return Falseprobes.append(entry)- # One level inside the index stores, and only those. uv REWRITES this metadata on- # every resolve, so a shard another account owns aborts it. Measured on BOTH the- # pinned uv 0.12.1 and 0.10.7: a 0555 `simple-*/pypi` or `wheels-*/pypi` gives- # "Failed to write to the client cache", exit 2. One level is the leaf on both:- # 0.12.1 lays this out as `simple-v24/pypi`, not `simple-v24/index/<hash>`, and a- # 0555 `wheels-v6/pypi/requests` one deeper installs fine. Bounded on purpose.+ # One level inside the index stores: uv rewrites this metadata every resolve, so a foreign-owned+ # shard aborts it (measured on uv 0.12.1 and 0.10.7). Bounded on purpose.if entry.name.lower().startswith(("simple-", "wheels-")):- # `index/<hash>`, one per CUSTOM index, is where uv puts metadata when- # --index-url is set, which Studio does for the torch wheels. Measured on the- # pinned uv 0.12.1: a 0555 `simple-v24/index/<hash>` passes a one-level probe- # and then aborts with "Failed to write to the client cache".+ # `index/<hash>` holds custom-index metadata (Studio's torch index); a read-only one aborts uv.shards = list(entry.iterdir())index_dir = entry / "index"if index_dir.is_dir():shards.extend(index_dir.iterdir())for shard in shards:if not shard.is_dir():- # Same rule as the store level: a file, or a symlink dangling or not, is- # an existing path uv can neither open nor mkdir. Measured on the pinned- # uv 0.12.1, both abort with "Failed to write to the client cache".+ # A file or any symlink here aborts uv too.return Falseprobes.append(shard)except OSError:@@ -3950,17 +3912,13 @@ def _uv_cache_is_writable(cache_dir: Path) -> bool:passexcept OSError:return False- # Only the names uv is measured to need writable: rejecting more throws away the warm cache- # this path exists to find. Every control file at 0444 against uv 0.10.7: the root .lock- # aborts (exit 2) and sdists-v9/.git aborts (exit 2); root CACHEDIR.TAG and .gitignore, and- # .git/.gitignore/.lock under archive-v0, interpreter-v4, simple-v20 and wheels-v6, all- # install fine. uv creates only the three root files, so a per-store .git is someone else's.+ # Only names uv is measured to need writable (root .lock, sdists-v9/.git); rejecting more throws+ # away the warm cache.for target in probes:if target == cache_dir:names = (".lock",)elif target.name.lower().startswith("sdists-"):- # The one store measured to abort on a read-only .git. Rejecting a cache uv accepts- # costs the warm cache this path exists to find, so the rest are left alone.+ # The one store measured to abort on a read-only .git; rejecting a cache uv accepts loses the warm cache this path exists to find.names = (".git",)else:continue@@ -3968,9 +3926,7 @@ def _uv_cache_is_writable(cache_dir: Path) -> bool:control = target / nameif not control.exists() and not control.is_symlink():continue- # Not a regular file, so uv cannot open it at all: measured on uv 0.10.7, a `.lock`- # DIRECTORY or a symlink to one exits 2 with "Could not acquire lock ... Is a- # directory". is_file() alone skipped it and reported the cache usable.+ # A `.lock` directory or symlink to one also aborts uv.if not control.is_file() or not os.access(control, os.R_OK | os.W_OK):return Falsereturn True@@ -3982,10 +3938,7 @@ def _with_studio_uv_cache(env: Optional[dict], cwd: Optional[Path] = None) -> Opif (os.environ.get("UV_CACHE_DIR") or "").strip():return envif _uv_no_cache_requested():- # Removed, not left alone: uv parses an exported EMPTY value as `--cache-dir ''` even- # under --no-cache and exits 2, "a value is required for '--cache-dir'". setup.sh unsets- # it in its own no-cache branch; setup.ps1 has no cache handling at all, so on Windows a- # blank inherited value reached uv and failed the update before no-cache took effect.+ # Removed: uv reads an exported EMPTY value as `--cache-dir ''` and exits 2, even with --no-cache.no_cache = {**(env or os.environ)}no_cache.pop("UV_CACHE_DIR", None)return no_cache@@ -3996,12 +3949,9 @@ def _with_studio_uv_cache(env: Optional[dict], cwd: Optional[Path] = None) -> Opand _uv_cache_has_packages(recorded)and _uv_cache_is_writable(recorded)):- # Only while it holds something and uv can still write to it: a marker for an emptied cache loses to a warm one, and setup treats- # the value this hands it as the caller's choice, so a cache gone read-only since the install would abort every uv command.+ # Only while non-empty and writable: setup treats this as the caller's choice, so a read-only one would abort every uv command.return {**(env or os.environ), "UV_CACHE_DIR": str(recorded)}- # Content cannot settle it: one on-demand wheel warms the Studio cache even in shared mode,- # so uv's default goes first and a warm Studio cache is the fallback below. The installers- # order the same three the same way.+ # Order by location, not content: one wheel warms the Studio cache even in shared mode, so uv's default goes first, then a warm Studio cache.default_cache = _uv_default_cache_dir(cwd)if (default_cache is not None@@ -4009,22 +3959,14 @@ def _with_studio_uv_cache(env: Optional[dict], cwd: Optional[Path] = None) -> Opand _uv_cache_is_writable(default_cache)):return {**(env or os.environ), "UV_CACHE_DIR": str(default_cache)}- # setup.sh treats an inherited UV_CACHE_DIR as the caller's choice and skips its own write- # probe, so handing it an unwritable Studio cache aborts every uv command in the update --- # the one branch here that was still unprobed. Left unset, setup.sh probes and falls back.- #- # Only for a root that already exists, and the root is never created here: setup.sh fails- # fast on a STUDIO_HOME override that does not, exactly so a typo cannot materialise an- # empty workspace, and making the cache under it first would satisfy that guard and let the- # update run on against a tree with no venv.+ # setup.sh skips its probe for inherited UV_CACHE_DIR, so probe here; never create the root, or setup's fail-fast on a typo is defeated.if STUDIO_HOME.is_dir():try:studio_cache.mkdir(parents = True, exist_ok = True)except OSError:passif not _uv_cache_is_writable(studio_cache):- # Explicitly absent rather than a bare `return env`: the other branches all hand back- # a dict, and setup.sh's own probe wants the variable gone, not inherited from here.+ # Explicitly absent: setup.sh's own probe wants the variable gone.unset = {**(env or os.environ)}unset.pop("UV_CACHE_DIR", None)return unset@@ -4254,8 +4196,7 @@ def _refresh_desktop_shortcuts(*, verbose: bool = False) -> None:# -NoProfile unconditionally, as in _run_setup_script: the visible console path loads a profile.ps_argv.append("-NoProfile")if _should_hide_windows_subprocesses():- # Avoid the same Hidden/Bypass detection pair as setup above;- # both local and fetched runners set CREATE_NO_WINDOW.+ # Avoid the Hidden/Bypass detection pair, as in setup above.ps_argv.extend(["-NoLogo", "-NonInteractive"])# Stops at the first candidate that launched; only an unlaunchable one moves on.@@ -5003,31 +4944,19 @@ def _llama_runtime_to_grade() -> Optional[Path]:``default_managed_llama_dir`` already grades the tree it names."""pinned = os.environ.get("LLAMA_SERVER_PATH", "").strip()- # Nonblank is not the test: _scan_pinned treats an absent pin as no pin and- # falls through to the managed tree, so suppressing the verdict for a path- # that was deleted would leave a quarantined managed runtime reporting Ready.- # The line is the finder's own _file_status, not the directory entry: a pin- # that exists but is denied or not executable does stop the finder, while a- # symlink whose target was deleted or quarantined is is_file() False, reads as- # "absent" there, and falls through like any missing pin. lexists called that- # a pin and left the managed tree the backend really loads ungraded.+ # Use the finder's own _file_status: an absent pin (including a dangling symlink) falls through to the+ # managed tree, which must then be graded.if pinned:try:stops_the_finder = Path(pinned).is_file()except PermissionError:- # is_file raises rather than answering for a locked file on Windows;- # _file_status retries and then calls it "denied", which halts the- # finder with no fallback.+ # is_file raises for a locked file on Windows; _file_status calls it "denied", halting the finder.stops_the_finder = Trueexcept OSError:stops_the_finder = Falseif stops_the_finder:return None- # studio/backend on sys.path first. llama_cpp_path_settings imports- # storage.studio_db as a top level package and swallows the failure, so- # without this the stored selection always reads as absent and a user whose- # custom folder is set in Studio would be sent to repair a tree their backend- # never opens. Mirrors the backend_dir insert the other commands here do.+ # Put studio/backend first on sys.path: else llama_cpp_path_settings swallows a failed storage.studio_db import and selection reads absent.backend_dir = _PACKAGE_ROOT / "studio" / "backend"if backend_dir.is_dir() and str(backend_dir) not in sys.path:sys.path.insert(0, str(backend_dir))@@ -5039,57 +4968,29 @@ def _llama_runtime_to_grade() -> Optional[Path]:)from studio.install_llama_prebuilt import default_managed_llama_direxcept Exception:- # No settings module means no stored selection to honour, and no way to- # ask whether a folder holds a server, so the managed root stands.+ # Without a settings module there is no stored selection and no way to check for a server, so use the managed root.from studio.install_llama_prebuilt import default_managed_llama_dirreturn default_managed_llama_dir()- # UNSLOTH_LLAMA_CPP_PATH outranks the stored folder in the finder (1b before- # 2), and default_managed_llama_dir points at exactly that tree, so it is ours- # to grade even when an older selection is still in the settings database.- # Reading the setting first left the tree the backend actually opens ungraded.- # The managed marker is the exception: the finder skips the override when the- # desktop set it, so the stored folder wins again.+ # UNSLOTH_LLAMA_CPP_PATH outranks the stored folder, unless the desktop set it (managed marker).override = (os.environ.get("UNSLOTH_LLAMA_CPP_PATH") or "").strip()- # Classified, not merely read off the marker. studio/backend/main.py calls- # mark_managed_llama_cpp_path(managed) before discovery, which marks any- # override equal to the managed tree however it got there, and the finder then- # skips it. _ensure_studio_env_exported writes exactly that value under a- # custom STUDIO_HOME and sets no marker, so trusting the marker alone made- # this grade the managed tree as a user pin while the backend walked past it- # to the stored selection: a damaged managed tree blocked launch and was sent- # for repair though nothing would ever open it.+ # Classify the override rather than trust the marker: a custom STUDIO_HOME export equals the managed tree yet sets no marker.managed_override = os.environ.get("UNSLOTH_STUDIO_MANAGED_LLAMA_CPP_PATH") == "1"if override and not managed_override:- # Against the tree the studio home names with the override out of the way,- # never default_managed_llama_dir(): that reads the override first and- # would call every user pin managed. The backend compares against exactly- # this value, STUDIO_ROOT/llama.cpp computed before it exported anything.+ # Compare against STUDIO_ROOT/llama.cpp, never default_managed_llama_dir(), which reads the override first and would call every pin managed.managed_override = _same_runtime_tree(expanded_user_path(override), _managed_llama_dir_ignoring_the_override())if override and not managed_override:- # Only a folder that holds a server stops discovery. _scan_pinned finds no- # candidate under an empty or missing override and walks on, so a tree behind- # it is still ours to grade; one that holds a server is not.- # Not graded, because nothing can repair it: setup.sh derives LLAMA_CPP_DIR- # from STUDIO_HOME and setup.ps1 from Get-ManagedLlamaCppDir, and neither- # reads UNSLOTH_LLAMA_CPP_PATH at all, so an update sent here would rebuild a- # different tree, report success, and leave the next launch offering the same- # repair forever. LLAMA_SERVER_PATH is skipped for the same reason.- # expanded_user_path, not Path.expanduser: the finder reads the same- # variable through it, and a "~name" naming no account makes expanduser- # raise RuntimeError out of a doctor whose whole job is to answer.+ # Only a folder holding a server stops discovery. Not graded: setup.sh / setup.ps1 never read+ # UNSLOTH_LLAMA_CPP_PATH, so a repair would loop. expanded_user_path: expanduser can raise.if _layout_stops_discovery(llama_server_candidates(expanded_user_path(override))):return Noneif get_stored_custom_llama_cpp_path() is not None:return Noneif managed_override:- # The finder skips an override that names the managed tree, and that tree- # is the one this install owns, so it is still the answer.+ # The finder skips an override naming the managed tree, which is still ours.return default_managed_llama_dir()- # The finder has walked past the override, so the tree it reaches is the one- # the managed root names with that override out of the way. Reading it with- # the variable still set would name the folder just ruled out.+ # Read with the override out of the way, or it names the folder just ruled out.return _managed_llama_dir_ignoring_the_override()@@ -5145,11 +5046,7 @@ def _managed_llama_dir_ignoring_the_override() -> Path:"""from studio.install_llama_prebuilt import default_managed_llama_dir- # A master root first, for the same reason the export computes it that way: the- # runtimes sit beside studio/, and default_managed_llama_dir reads only the studio- # home, so it would answer <master>/studio/llama.cpp and grade the tree the- # installer exported -- the one actually in use -- as somebody's own pin, which- # left these installs out of the health check entirely.+ # Master root first: runtimes sit beside studio/, which default_managed_llama_dir does not see.master_dir = _master_root_llama_dir()if master_dir is not None:return master_dir@@ -5157,8 +5054,7 @@ def _managed_llama_dir_ignoring_the_override() -> Path:saved = os.environ.pop("UNSLOTH_LLAMA_CPP_PATH", None)had_home = "UNSLOTH_STUDIO_HOME" in os.environsaved_home = os.environ.get("UNSLOTH_STUDIO_HOME")- # Truthy-check, not a bare presence one, the way _ensure_studio_env_exported reads- # it: a blank UNSLOTH_STUDIO_HOME= is not a root either.+ # Truthy-check: a blank UNSLOTH_STUDIO_HOME= is not a root either.if _STUDIO_HOME_IS_CUSTOM and not (saved_home or "").strip():os.environ["UNSLOTH_STUDIO_HOME"] = str(STUDIO_HOME)try:@@ -5191,15 +5087,12 @@ def desktop_capabilities(# Did the install finish and are the backend boot deps still there."studio_install_ok": bool(state["ok"]),"studio_install_reason": state["reason"],- # And is the llama.cpp runtime the backend loads still intact. Null when- # nothing is installed yet (NotInstalled, not a broken install). Older- # desktops ignore both keys.+ # Null when nothing is installed yet. Older desktops ignore both keys."llama_runtime_ok": None,"llama_runtime_reason": "","version": "unknown",}- # Best effort: a probe that cannot answer must not turn a working install into- # a stale one, so a failure here leaves llama_runtime_ok null.+ # A probe that cannot answer must not turn a working install stale.try:from studio.install_llama_prebuilt import installed_runtime_healthruntime_root = _llama_runtime_to_grade()@@ -5208,20 +5101,11 @@ def desktop_capabilities(if health is not None:payload["llama_runtime_ok"], payload["llama_runtime_reason"] = healthelse:- # Null with a reason, because the two nulls are not the same thing.- # Nothing installed is a fact about the machine and stays true until- # the tree changes, so the desktop may cache it. This one is a fact- # about a selection the desktop's fingerprint does not watch, so the- # answer expires the moment the user clears their custom folder, and- # managed.rs declines to cache it on the strength of this reason.- # The verdict itself is still null, so nothing turns stale on it.+ # A null that must not be cached: it depends on a selection the desktop does not watch+ # (managed.rs keys off this reason).payload["llama_runtime_reason"] = "llama_runtime_not_managed"except Exception:- # The third null, and the one that must not be kept. Nothing-installed is a- # fact about the machine; this is a fact about one attempt, and it shares the- # damaged tree's fingerprint, so caching it froze a Ready that was never- # reached over a runtime the probe would have rejected. Same reason string- # shape as the skip, so managed.rs refuses both without a second rule.+ # Never cache a failed attempt: it shares the damaged tree's fingerprint.payload["llama_runtime_ok"] = Nonepayload["llama_runtime_reason"] = "llama_runtime_probe_failed"try:diff --git a/unsloth_cli/commands/train.py b/unsloth_cli/commands/train.pyindex 82cfe3e7d6f..cedb299802b 100644--- a/unsloth_cli/commands/train.py+++ b/unsloth_cli/commands/train.py@@ -352,8 +352,7 @@ def train(data = cfg.model_dump()data["training"]["output_dir"] = str(data["training"]["output_dir"])- # model_dump carries the config file's tokens verbatim, and this goes to stdout: CI logs,- # notebook output, scrollback. Mask only what is set, so an unset token still reads as null.+ # This goes to stdout (CI logs, notebooks): mask set tokens, keep unset ones null.for name in ("hf_token", "wandb_token"):if data["logging"].get(name) is not None:data["logging"][name] = "[redacted]"diff --git a/unsloth_cli/pi_subagent.ts b/unsloth_cli/pi_subagent.tsindex 5853bb4956c..889d30d6c8d 100644--- a/unsloth_cli/pi_subagent.ts+++ b/unsloth_cli/pi_subagent.ts@@ -215,8 +215,7 @@ async function runLocalAgent(}if (event.type !== "message_end") return;const message = event.message;- // Pi reports model/API failures as message_end events while still exiting 0, so the exit status- // alone cannot surface them.+ // Pi reports model/API failures as message_end events while still exiting 0.if (message?.stopReason === "error" || message?.stopReason === "aborted") {childError =(typeof message.errorMessage === "string" && message.errorMessage) ||