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
Bug fixes (#1458)
Daniel Han6bf5d8d626db
diff --git a/pyproject.toml b/pyproject.tomlindex 51c3037235e..49347c8ab0a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -36,7 +36,7 @@ huggingface = ["unsloth_zoo>=2024.11.8","packaging","tyro",- "transformers>=4.46.1",+ "transformers>=4.46.1,<=4.46.3","datasets>=2.16.0","sentencepiece>=0.2.0","tqdm",@@ -247,7 +247,7 @@ colab-new = ["unsloth_zoo>=2024.11.8","packaging","tyro",- "transformers>=4.46.1",+ "transformers>=4.46.1,<=4.46.3","datasets>=2.16.0","sentencepiece>=0.2.0","tqdm",diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex f1dc15aca49..5b5ceefc667 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -12,7 +12,7 @@# See the License for the specific language governing permissions and# limitations under the License.-__version__ = "2024.12.4"+__version__ = "2024.12.5"__all__ = ["prepare_model_for_kbit_training",@@ -1127,6 +1127,7 @@ def unsloth_compile_transformers(shape_padding = True,cudagraphs = False,debug = False,+ fullgraph = True,import_from_cache = False,disable = False,return_logits = False,@@ -1170,6 +1171,7 @@ def unsloth_compile_transformers(shape_padding = shape_padding,cudagraphs = cudagraphs,debug = debug,+ fullgraph = fullgraph,import_from_cache = import_from_cache,disable = disable,return_logits = return_logits,diff --git a/unsloth/models/cohere.py b/unsloth/models/cohere.pyindex aa0bcb55ee1..cbbebeec5ce 100644--- a/unsloth/models/cohere.py+++ b/unsloth/models/cohere.py@@ -75,6 +75,7 @@ def CohereAttention_fast_forward(output_attentions: bool = False,use_cache: bool = False,padding_mask: Optional[torch.LongTensor] = None,+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,*args, **kwargs,) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:@@ -112,12 +113,11 @@ def CohereAttention_fast_forward(if past_key_value is not None:kv_seq_len += past_key_value[0].shape[-2]+ cos, sin = position_embeddingsif position_ids is None:- cos = self.rotary_emb.cos_cached- sin = self.rotary_emb.sin_cachedQ, K = fast_rope_embedding(Q, K, cos, sin)else:- cos, sin = self.rotary_emb(V, seq_len = kv_seq_len)+ cos, sin = cos[position_ids], sin[position_ids]Q, K = inplace_rope_embedding(Q, K, cos, sin, position_ids)pass@@ -190,6 +190,7 @@ def CohereDecoderLayer_fast_forward(output_attentions: Optional[bool] = False,use_cache: Optional[bool] = False,padding_mask: Optional[torch.LongTensor] = None,+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,*args, **kwargs,):if use_cache and hasattr(self, "_flag_for_generation"): #past_key_value is not None:diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex cc41a8b2660..f8fb7d945d7 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -329,14 +329,15 @@ pass# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L320def LlamaAttention_fast_forward(self,- hidden_states: torch.Tensor,- causal_mask: Optional[xformers.attn_bias.BlockDiagonalCausalMask] = None,- attention_mask: Optional[torch.Tensor] = None,- position_ids: Optional[torch.LongTensor] = None,- past_key_value: Optional[Tuple[torch.Tensor]] = None,- output_attentions: bool = False,- use_cache: bool = False,- padding_mask: Optional[torch.LongTensor] = None,+ hidden_states: torch.Tensor,+ causal_mask: Optional[xformers.attn_bias.BlockDiagonalCausalMask] = None,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_value: Optional[Tuple[torch.Tensor]] = None,+ output_attentions: bool = False,+ use_cache: bool = False,+ padding_mask: Optional[torch.LongTensor] = None,+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,*args, **kwargs,) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:@@ -368,20 +369,24 @@ def LlamaAttention_fast_forward(if past_key_value is not None:kv_seq_len += past_key_value[0].shape[-2]- # Extend RoPE dynamically to fit in VRAM- rotary_emb = self.rotary_emb- rotary_emb.extend_rope_embedding(V, seq_len = kv_seq_len)-- if position_ids is None:- # Useful for LongRoPE- cos, sin = rotary_emb.get_cached(kv_seq_len)- # cos = self.rotary_emb.cos_cached- # sin = self.rotary_emb.sin_cached- Q, K = fast_rope_embedding(Q, K, cos, sin)+ if position_embeddings:+ cos, sin = position_embeddingselse:- cos, sin = rotary_emb(V, seq_len = kv_seq_len)- Q, K = inplace_rope_embedding(Q, K, cos, sin, position_ids)- pass+ # Extend RoPE dynamically to fit in VRA+ rotary_emb = self.rotary_emb+ rotary_emb.extend_rope_embedding(V, seq_len=kv_seq_len)++ if position_ids is None:+ # Useful for LongRoPE+ cos, sin = rotary_emb.get_cached(kv_seq_len)+ else:+ cos, sin = rotary_emb(V, seq_len=kv_seq_len)++ Q, K = (+ fast_rope_embedding(Q, K, cos, sin)+ if position_ids is None+ else inplace_rope_embedding(Q, K, cos, sin, position_ids)+ )if past_key_value is not None:K = torch.cat([past_key_value[0], K], dim = 2)@@ -444,14 +449,15 @@ pass# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L590def LlamaDecoderLayer_fast_forward(self,- hidden_states: torch.Tensor,- causal_mask = None,- attention_mask: Optional[torch.Tensor] = None,- position_ids: Optional[torch.LongTensor] = None,- past_key_value: Optional[Tuple[torch.Tensor]] = None,- output_attentions: Optional[bool] = False,- use_cache: Optional[bool] = False,- padding_mask: Optional[torch.LongTensor] = None,+ hidden_states: torch.Tensor,+ causal_mask = None,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_value: Optional[Tuple[torch.Tensor]] = None,+ output_attentions: Optional[bool] = False,+ use_cache: Optional[bool] = False,+ padding_mask: Optional[torch.LongTensor] = None,+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,*args, **kwargs,) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:"""@@ -471,14 +477,15 @@ def LlamaDecoderLayer_fast_forward(residual = hidden_stateshidden_states = fast_rms_layernorm_inference(self.input_layernorm, hidden_states)hidden_states, self_attn_weights, present_key_value = self.self_attn(- hidden_states=hidden_states,- causal_mask=causal_mask,- attention_mask=attention_mask,- position_ids=position_ids,- past_key_value=past_key_value,- output_attentions=output_attentions,- use_cache=use_cache,- padding_mask=padding_mask,+ hidden_states = hidden_states,+ causal_mask = causal_mask,+ attention_mask = attention_mask,+ position_ids = position_ids,+ past_key_value = past_key_value,+ output_attentions = output_attentions,+ use_cache = use_cache,+ padding_mask = padding_mask,+ position_embeddings = position_embeddings,)hidden_states += residual@@ -491,14 +498,15 @@ def LlamaDecoderLayer_fast_forward(residual = hidden_stateshidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states)hidden_states, self_attn_weights, present_key_value = self.self_attn(- hidden_states=hidden_states,- causal_mask=causal_mask,- attention_mask=attention_mask,- position_ids=position_ids,- past_key_value=past_key_value,- output_attentions=output_attentions,- use_cache=use_cache,- padding_mask=padding_mask,+ hidden_states = hidden_states,+ causal_mask = causal_mask,+ attention_mask = attention_mask,+ position_ids = position_ids,+ past_key_value = past_key_value,+ output_attentions = output_attentions,+ use_cache = use_cache,+ padding_mask = padding_mask,+ position_embeddings = position_embeddings,)hidden_states = residual + hidden_states@@ -776,9 +784,10 @@ def LlamaModel_fast_forward(passpass-- if IS_GRANITE:- position_embeddings = self.rotary_emb(hidden_states, position_ids, self.max_position_embeddings)+ if transformers_version > "4.47.1" and hasattr(self, "rotary_emb"):+ # Transformers main has made it mandatory to pass position_embeddings+ # https://github.com/huggingface/transformers/pull/34858+ position_embeddings = self.rotary_emb(hidden_states, position_ids, self.config.max_position_embeddings)else:position_embeddings = None@@ -832,13 +841,13 @@ def LlamaModel_fast_forward(layer_outputs = decoder_layer(hidden_states,causal_mask=mask,- attention_mask=attention_mask,- position_ids=position_ids,- past_key_value=past_key_value,- output_attentions=output_attentions,- use_cache=use_cache,- padding_mask=padding_mask,- position_embeddings = position_embeddings+ attention_mask = attention_mask,+ position_ids = position_ids,+ past_key_value = past_key_value,+ output_attentions = output_attentions,+ use_cache = use_cache,+ padding_mask = padding_mask,+ position_embeddings = position_embeddings,)hidden_states = layer_outputs[0]pass@@ -993,6 +1002,9 @@ def CausalLM_fast_forward(fast_forward_inference):logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :].to(lm_head.dtype))else:RETURN_LOGITS = os.environ.get("UNSLOTH_RETURN_LOGITS", "0") == "1"+ # < 1024 Normal Unsloth uses less VRAM!+ if bsz*q_len <= 1024: RETURN_LOGITS = True+if not RETURN_LOGITS and HAS_CUT_CROSS_ENTROPY and labels is not None:n_items = kwargs.get("num_items_in_batch", None) or kwargs.get("n_items", None)loss = fused_linear_cross_entropy(@@ -1041,7 +1053,6 @@ def CausalLM_fast_forward(fast_forward_inference):# Fixes https://github.com/unslothai/unsloth/issues/10self.extra_ignored_labels = torch.full((self.max_seq_length, 1), -100, device = "cuda:0")pass-shift_labels = torch.hstack((labels[..., 1:], self.extra_ignored_labels[:labels.shape[0]]))loss = fast_cross_entropy_loss(logits = shift_logits,@@ -1570,7 +1581,7 @@ class FastLlamaModel:max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)statistics = \- f"==((====))== Unsloth {__version__}: Fast {model_patcher.__name__[4:-5]} patching. Transformers:{transformers_version}.\n"\+ f"==((====))== Unsloth {__version__}: Fast {model_patcher.__name__[4:-5]} patching. Transformers: {transformers_version}.\n"\f" \\\ /| GPU: {gpu_stats.name}. Max memory: {max_memory} GB. Platform: {platform_system}.\n"\f"O^O/ \_/ \\ Torch: {torch.__version__}. CUDA: {gpu_stats.major}.{gpu_stats.minor}. CUDA Toolkit: {torch.version.cuda}. Triton: {triton_version}\n"\f"\ / Bfloat16 = {str(SUPPORTS_BFLOAT16).upper()}. FA [Xformers = {xformers_version}. FA2 = {HAS_FLASH_ATTENTION}]\n"\diff --git a/unsloth/models/loader.py b/unsloth/models/loader.pyindex 3b2c8ffefee..5ecd667f513 100644--- a/unsloth/models/loader.py+++ b/unsloth/models/loader.py@@ -131,7 +131,8 @@ class FastLanguageModel(FastLlamaModel):exist_config = os.path.exists(os.path.join(model_name, "config.json"))both_exist = exist_adapter_config and exist_configelse:- files = HfFileSystem(token = token).glob(os.path.join(model_name, "*.json"))+ # Because HfFileSystem assumes linux paths, we need to set the path with forward slashes, even on Windows.+ files = HfFileSystem(token = token).glob(f"{model_name}/*.json")files = (os.path.split(x)[-1] for x in files)if sum(x == "adapter_config.json" or x == "config.json" for x in files) >= 2:both_exist = True@@ -352,6 +353,7 @@ class FastVisionModel(FastBaseVisionModel):resize_model_vocab = None, # [TODO] No effectrevision = None,return_logits = False, # Return logits+ fullgraph = True, # No graph breaks*args, **kwargs,):if token is None: token = get_token()@@ -473,6 +475,7 @@ class FastVisionModel(FastBaseVisionModel):shape_padding = True,cudagraphs = False,debug = False,+ fullgraph = fullgraph,import_from_cache = False,disable = False,return_logits = return_logits,diff --git a/unsloth/models/mistral.py b/unsloth/models/mistral.pyindex 00dcc5cd1d5..dda430459a8 100644--- a/unsloth/models/mistral.py+++ b/unsloth/models/mistral.py@@ -39,14 +39,15 @@ passdef MistralAttention_fast_forward(self,- hidden_states: torch.Tensor,- causal_mask: Optional[xformers.attn_bias.BlockDiagonalCausalMask] = None,- attention_mask: Optional[torch.Tensor] = None,- position_ids: Optional[torch.LongTensor] = None,- past_key_value: Optional[Tuple[torch.Tensor]] = None,- output_attentions: bool = False,- use_cache: bool = False,- padding_mask: Optional[torch.LongTensor] = None,+ hidden_states: torch.Tensor,+ causal_mask: Optional[xformers.attn_bias.BlockDiagonalCausalMask] = None,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_value: Optional[Tuple[torch.Tensor]] = None,+ output_attentions: bool = False,+ use_cache: bool = False,+ padding_mask: Optional[torch.LongTensor] = None,+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,*args, **kwargs,) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:diff --git a/unsloth/save.py b/unsloth/save.pyindex cf78bf58978..ce5ee5d38eb 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -577,7 +577,7 @@ def unsloth_save_model(# max_ram = max(max_ram - W.nbytes, 0)else:# Save to Disk- logger.warning_once("We will save to Disk and not RAM now.")+ logger.warning_once("\nWe will save to Disk and not RAM now.")filename = os.path.join(temporary_location, f"{name}.pt")torch.save(W, filename, pickle_module = pickle, pickle_protocol = pickle.HIGHEST_PROTOCOL,)# weights_only = True weirdly fails?@@ -2129,17 +2129,31 @@ def unsloth_generic_save():if token is None and push_to_hub: token = get_token()- merge_and_overwrite_lora(- get_model_name,- create_huggingface_repo,- model,- save_location = save_directory,- push_to_hub = push_to_hub,- token = token,- upload_location = save_directory if push_to_hub else None,- low_disk_space_usage = True,- private = private,- )+ import unsloth_zoo+ if Version(unsloth_zoo.__version__) <= Version("2024.12.1"):+ merge_and_overwrite_lora(+ get_model_name,+ create_huggingface_repo,+ model,+ save_location = save_directory,+ push_to_hub = push_to_hub,+ token = token,+ upload_location = save_directory if push_to_hub else None,+ low_disk_space_usage = True,+ private = private,+ )+ else:+ merge_and_overwrite_lora(+ get_model_name,+ model,+ save_directory = save_directory,+ push_to_hub = push_to_hub,+ private = private,+ token = token,+ low_disk_space_usage = False,+ use_temp_file = False,+ )+ passreturnpassdiff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.pyindex 302017d5665..384b4bbca56 100644--- a/unsloth/tokenizer_utils.py+++ b/unsloth/tokenizer_utils.py@@ -585,26 +585,43 @@ def load_correct_tokenizer(pass+def _find_end_position(template, endfor, endif):+ where_endfor = template.find(endfor)+ where_endif = template.find(endif)+ if where_endfor == where_endif == -1:+ return None+ elif where_endfor > where_endif:+ return endfor+ else:+ return endif+ pass+pass++def _fix_chat_template(chat_template):- endfor = "{% endif %}"- where = chat_template.find(endfor)- if where == -1:- endfor = "{%- endif %}"- where = chat_template.find(endfor)- if where == -1:+ endfor = "{% endfor %}"+ endif = "{% endif %}"+ chosen_end = _find_end_position(chat_template, endfor, endif)+ if chosen_end is None:+ endfor = "{%- endfor %}"+ endif = "{%- endif %}"+ chosen_end = _find_end_position(chat_template, endfor, endif)+ if chosen_end is None:return chat_template++ where = chat_template.find(chosen_end)- after_endfor = chat_template[where + len(endfor):]+ after_endfor = chat_template[where + len(chosen_end):]- dash = "-" if endfor.startswith("{%-") else ""+ dash = "-" if chosen_end.startswith("{%-") else ""if "{%" + dash + " if" not in after_endfor and "{%" + dash + " set " not in after_endfor and \after_endfor.startswith("{{") and after_endfor.endswith("}}") and \after_endfor.count("{{") == 1 and after_endfor.count("}}") == 1:- after_endfor = "{%" + dash + " if add_generation_prompt %}" + after_endfor + endfor+ after_endfor = "{%" + dash + " if add_generation_prompt %}" + after_endfor + endif- chat_template = chat_template[:where + len(endfor)] + after_endfor+ chat_template = chat_template[:where + len(chosen_end)] + after_endforpassreturn chat_templatepass