From 88679e4f99994fc1972bee70fd858b2c735f2f33 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 2 Aug 2025 03:36:05 -0700 Subject: [PATCH 1/4] Update --- pyproject.toml | 4 ++-- unsloth/models/_utils.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index a596ffe3cc..1919c07f59 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,7 +37,7 @@ triton = [ ] huggingface = [ - "unsloth_zoo>=2025.7.11", + "unsloth_zoo>=2025.8.1", "packaging", "tyro", "transformers>=4.51.3,!=4.47.0,!=4.52.0,!=4.52.1,!=4.52.2,!=4.52.3,!=4.53.0", @@ -381,7 +381,7 @@ colab-ampere-torch220 = [ "flash-attn>=2.6.3", ] colab-new = [ - "unsloth_zoo>=2025.7.11", + "unsloth_zoo>=2025.8.1", "packaging", "tyro", "transformers>=4.51.3,!=4.47.0,!=4.52.0,!=4.52.1,!=4.52.2,!=4.52.3,!=4.53.0", diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py index 4fad9cfa05..ab831dbaab 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__ = "2025.7.11" +__version__ = "2025.8.1" __all__ = [ "SUPPORTS_BFLOAT16", From 759193cfa5e329dfa76e9e19a9278e5bab56169b Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 2 Aug 2025 03:39:17 -0700 Subject: [PATCH 2/4] Update __init__.py --- unsloth/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/unsloth/__init__.py b/unsloth/__init__.py index 7fb0093c7b..f856b64f50 100644 --- a/unsloth/__init__.py +++ b/unsloth/__init__.py @@ -222,7 +222,7 @@ elif DEVICE_TYPE == "xpu": # Check for unsloth_zoo try: unsloth_zoo_version = importlib_version("unsloth_zoo") - if Version(unsloth_zoo_version) < Version("2025.7.7"): + if Version(unsloth_zoo_version) < Version("2025.8.1"): print( "Unsloth: Please update Unsloth and Unsloth-Zoo to the latest version!\n"\ "Do this via `pip install --upgrade --force-reinstall --no-cache-dir --no-deps unsloth unsloth_zoo`" From 432f2ca681e1f81d205d4cc06bc0db94acf5942b Mon Sep 17 00:00:00 2001 From: DoubleMathew Date: Tue, 5 Aug 2025 22:58:33 -0500 Subject: [PATCH 3/4] GPT-OSS support (#3099) --- unsloth/models/loader.py | 3 +++ unsloth/models/vision.py | 1 + 2 files changed, 4 insertions(+) diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py index a5b7d18164..023234413a 100644 --- a/unsloth/models/loader.py +++ b/unsloth/models/loader.py @@ -589,6 +589,9 @@ class FastModel(FastBaseModel): "float16;torch.float32;torch.float16;"\ "if name.endswith(('q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj', 'head')): module.to(torch.float16);" os.environ["TRITON_F32_DEFAULT"] = "ieee" + elif "gpt-oss" in lowered_model_name: + os.environ["UNSLOTH_MODEL_NAME"] = "gpt_oss" + os.environ["UNSLOTH_DISABLE_STATIC_GENERATION"] = "1" else: for check_model_name in DISABLE_COMPILE_MODEL_NAMES: if check_model_name in lowered_model_name: diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py index 246e5d5671..ab95231507 100644 --- a/unsloth/models/vision.py +++ b/unsloth/models/vision.py @@ -626,6 +626,7 @@ class FastBaseModel: r = r, lora_alpha = lora_alpha, target_modules = target_modules, + target_parameters = kwargs.get("target_parameters", None), lora_dropout = lora_dropout, bias = bias, task_type = task_type, From c0d0c3cb0c1d8f46b656e63393641d72414a0cce Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 6 Aug 2025 06:21:28 -0700 Subject: [PATCH 4/4] GPT-OSS --- pyproject.toml | 4 +- unsloth/chat_templates.py | 503 ++++++++++++++++++++++++++++++++++++++ unsloth/models/_utils.py | 2 +- unsloth/models/loader.py | 8 +- unsloth/models/mapper.py | 22 ++ unsloth/models/vision.py | 52 ++-- 6 files changed, 564 insertions(+), 27 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 1919c07f59..8cdd90ea99 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,7 +37,7 @@ triton = [ ] huggingface = [ - "unsloth_zoo>=2025.8.1", + "unsloth_zoo>=2025.8.2", "packaging", "tyro", "transformers>=4.51.3,!=4.47.0,!=4.52.0,!=4.52.1,!=4.52.2,!=4.52.3,!=4.53.0", @@ -381,7 +381,7 @@ colab-ampere-torch220 = [ "flash-attn>=2.6.3", ] colab-new = [ - "unsloth_zoo>=2025.8.1", + "unsloth_zoo>=2025.8.2", "packaging", "tyro", "transformers>=4.51.3,!=4.47.0,!=4.52.0,!=4.52.1,!=4.52.2,!=4.52.3,!=4.53.0", diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.py index 66d4b1c9aa..efd3f74fe7 100644 --- a/unsloth/chat_templates.py +++ b/unsloth/chat_templates.py @@ -1262,6 +1262,509 @@ CHAT_TEMPLATES["gemma3n"] = (gemma3n_template, gemma3n_template_eos_token, False DEFAULT_SYSTEM_MESSAGE["gemma3n"] = None # No system message in Gemma-3n pass +# =========================================== GPT-OSS +# Obtained via +# print(tokenizer.chat_template.replace("}\n", "####").replace("\n", "\\n").replace("####", "}\n")) +gptoss_template = \ +"""{#- + In addition to the normal inputs of `messages` and `tools`, this template also accepts the + following kwargs: + - "builtin_tools": A list, can contain "browser" and/or "python". + - "model_identity": A string that optionally describes the model identity. + - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium". + #} + +{#- Tool Definition Rendering ============================================== #} +{%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%} + {%- if param_spec.type == "array" -%} + {%- if param_spec['items'] -%} + {%- if param_spec['items']['type'] == "string" -%} + {{- "string[]" }} + {%- elif param_spec['items']['type'] == "number" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "integer" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "boolean" -%} + {{- "boolean[]" }} + {%- else -%} + {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%} + {%- if inner_type == "object | object" or inner_type|length > 50 -%} + {{- "any[]" }} + {%- else -%} + {{- inner_type + "[]" }} + {%- endif -%} + {%- endif -%} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- else -%} + {{- "any[]" }} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%} + {#- Handle array of types like ["object", "object"] from Union[dict, list] #} + {%- if param_spec.type | length > 1 -%} + {{- param_spec.type | join(" | ") }} + {%- else -%} + {{- param_spec.type[0] }} + {%- endif -%} + {%- elif param_spec.oneOf -%} + {#- Handle oneOf schemas - check for complex unions and fallback to any #} + {%- set has_object_variants = false -%} + {%- for variant in param_spec.oneOf -%} + {%- if variant.type == "object" -%} + {%- set has_object_variants = true -%} + {%- endif -%} + {%- endfor -%} + {%- if has_object_variants and param_spec.oneOf|length > 1 -%} + {{- "any" }} + {%- else -%} + {%- for variant in param_spec.oneOf -%} + {{- render_typescript_type(variant, required_params) -}} + {%- if variant.description %} + {{- "// " + variant.description }} + {%- endif -%} + {%- if variant.default is defined %} + {{ "// default: " + variant.default|tojson }} + {%- endif -%} + {%- if not loop.last %} + {{- " | " }} + {% endif -%} + {%- endfor -%} + {%- endif -%} + {%- elif param_spec.type == "string" -%} + {%- if param_spec.enum -%} + {{- '"' + param_spec.enum|join('" | "') + '"' -}} + {%- else -%} + {{- "string" }} + {%- if param_spec.nullable %} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type == "number" -%} + {{- "number" }} + {%- elif param_spec.type == "integer" -%} + {{- "number" }} + {%- elif param_spec.type == "boolean" -%} + {{- "boolean" }} + + {%- elif param_spec.type == "object" -%} + {%- if param_spec.properties -%} + {{- "{\n" }} + {%- for prop_name, prop_spec in param_spec.properties.items() -%} + {{- prop_name -}} + {%- if prop_name not in (param_spec.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{ render_typescript_type(prop_spec, param_spec.required or []) }} + {%- if not loop.last -%} + {{-", " }} + {%- endif -%} + {%- endfor -%} + {{- "}" }} + {%- else -%} + {{- "object" }} + {%- endif -%} + {%- else -%} + {{- "any" }} + {%- endif -%} +{%- endmacro -%} + +{%- macro render_tool_namespace(namespace_name, tools) -%} + {{- "## " + namespace_name + "\n\n" }} + {{- "namespace " + namespace_name + " {\n\n" }} + {%- for tool in tools %} + {%- set tool = tool.function %} + {{- "// " + tool.description + "\n" }} + {{- "type "+ tool.name + " = " }} + {%- if tool.parameters and tool.parameters.properties -%} + {{- "(_: " }} + {{- "{\n" }} + {%- for param_name, param_spec in tool.parameters.properties.items() %} + {{- "// " + param_spec.description + "\n" }} + {{- param_name }} + {%- if param_name not in (tool.parameters.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{- render_typescript_type(param_spec, tool.parameters.required or []) }} + {%- if param_spec.default is defined -%} + {%- if param_spec.enum %} + {{- ", // default: " + param_spec.default }} + {%- elif param_spec.oneOf %} + {{- "// default: " + param_spec.default }} + {%- else %} + {{- ", // default: " + param_spec.default|tojson }} + {%- endif -%} + {%- endif -%} + {%- if not loop.last %} + {{- ",\n" }} + {%- else %} + {{- "\n" }} + {%- endif -%} + {%- endfor %} + {{- "}) => any;\n\n" }} + {%- else -%} + {{- "() => any;\n\n" }} + {%- endif -%} + {%- endfor %} + {{- "} // namespace " + namespace_name }} +{%- endmacro -%} + +{%- macro render_builtin_tools(browser_tool, python_tool) -%} + {%- if browser_tool %} + {{- "## browser\n\n" }} + {{- "// Tool for browsing.\n" }} + {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }} + {{- "// Cite information from the tool using the following format:\n" }} + {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }} + {{- "// Do not quote more than 10 words directly from the tool output.\n" }} + {{- "// sources=web (default: web)\n" }} + {{- "namespace browser {\n\n" }} + {{- "// Searches for information related to `query` and displays `topn` results.\n" }} + {{- "type search = (_: {\n" }} + {{- "query: string,\n" }} + {{- "topn?: number, // default: 10\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }} + {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }} + {{- "// If `cursor` is not provided, the most recent page is implied.\n" }} + {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }} + {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }} + {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }} + {{- "type open = (_: {\n" }} + {{- "id?: number | string, // default: -1\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "loc?: number, // default: -1\n" }} + {{- "num_lines?: number, // default: -1\n" }} + {{- "view_source?: boolean, // default: false\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }} + {{- "type find = (_: {\n" }} + {{- "pattern: string,\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "}) => any;\n\n" }} + {{- "} // namespace browser\n\n" }} + {%- endif -%} + + {%- if python_tool %} + {{- "## python\n\n" }} + {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }} + {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }} + {%- endif -%} +{%- endmacro -%} + +{#- System Message Construction ============================================ #} +{%- macro build_system_message() -%} + {%- if model_identity is not defined %} + {{- "You are ChatGPT, a large language model trained by OpenAI.\n" -}} + {%- else %} + {{- model_identity }} + {%- endif %} + {{- "Knowledge cutoff: 2024-06\n" }} + {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }} + {%- if reasoning_effort is not defined %} + {%- set reasoning_effort = "medium" %} + {%- endif %} + {{- "Reasoning: " + reasoning_effort + "\n\n" }} + {%- if builtin_tools is defined %} + {{- "# Tools\n\n" }} + {%- set available_builtin_tools = namespace(browser=false, python=false) %} + {%- for tool in builtin_tools %} + {%- if tool == "browser" %} + {%- set available_builtin_tools.browser = true %} + {%- elif tool == "python" %} + {%- set available_builtin_tools.python = true %} + {%- endif %} + {%- endfor %} + {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }} + {%- endif -%} + {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }} + {%- if tools is defined -%} + {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }} + {%- endif -%} +{%- endmacro -%} + +{#- Main Template Logic ================================================= #} +{#- Set defaults #} + +{#- Render system message #} +{{- "<|start|>system<|message|>" }} +{{- build_system_message() }} +{{- "<|end|>" }} + +{#- Extract developer message #} +{%- if messages[0].role == "developer" or messages[0].role == "system" %} + {%- set developer_message = messages[0].content %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set developer_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} + +{#- Render developer message #} +{%- if developer_message or tools %} + {{- "<|start|>developer<|message|>" }} + {%- if developer_message %} + {{- "# Instructions\n\n" }} + {{- developer_message }} + {%- endif %} + {%- if tools -%} + {{- "\n\n" }} + {{- "# Tools\n\n" }} + {{- render_tool_namespace("functions", tools) }} + {%- endif -%} + {{- "<|end|>" }} +{%- endif %} + +{#- Render messages #} +{%- set last_tool_call = namespace(name=none) %} +{%- for message in loop_messages -%} + {#- At this point only assistant/user/tool messages should remain #} + {%- if message.role == 'assistant' -%} + {%- if "tool_calls" in message %} + {#- We assume max 1 tool call per message, and so we infer the tool call name #} + {#- in "tool" messages from the most recent assistant tool call name #} + {%- set tool_call = message.tool_calls[0] %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if message.content %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }} + {%- endif %} + {{- "<|start|>assistant to=" }} + {{- "functions." + tool_call.name + "<|channel|>commentary json<|message|>" }} + {{- tool_call.arguments|tojson }} + {{- "<|call|>" }} + {%- set last_tool_call.name = tool_call.name %} + {%- elif "thinking" in message and loop.last and not add_generation_prompt %} + {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #} + {#- This is a situation that should only occur in training, never in inference. #} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {#- <|return|> indicates the end of generation, but <|end|> does not #} + {#- <|return|> should never be an input to the model, but we include it as the final token #} + {#- when training, so the model learns to emit it. #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }} + {%- set last_tool_call.name = none %} + {%- elif "thinking" in message %} + {#- CoT is dropped during all previous turns, so we never render it for inference #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }} + {%- set last_tool_call.name = none %} + {%- elif loop.last and not add_generation_prompt %} + {#- <|return|> indicates the end of generation, but <|end|> does not #} + {#- <|return|> should never be an input to the model, but we include it as the final token #} + {#- when training, so the model learns to emit it. #} + {{- "<|start|>assistant<|message|>" + message.content + "<|return|>" }} + {%- else %} + {{- "<|start|>assistant<|message|>" + message.content + "<|end|>" }} + {%- set last_tool_call.name = none %} + {%- endif %} + {%- elif message.role == 'tool' -%} + {%- if last_tool_call.name is none %} + {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }} + {%- endif %} + {{- "<|start|>functions." + last_tool_call.name }} + {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }} + {%- else -%} + {{- "<|start|>user<|message|>" + message.content + "<|end|>" }} + {%- endif -%} +{%- endfor -%} + +{#- Generation prompt #} +{%- if add_generation_prompt -%} +<|start|>assistant +{%- endif -%}""" + +# Ollama from https://ollama.com/library/gemma3n/blobs/e0a42594d802 +gptoss_ollama = \ +'''<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI. +Knowledge cutoff: 2024-06 +Current date: {{ currentDate }} +{{- if and .IsThinkSet .Think (ne .ThinkLevel "") }} + +Reasoning: {{ .ThinkLevel }} +{{- else if or (not .IsThinkSet) (and .IsThinkSet .Think) }} + +Reasoning: medium +{{- end }} + +{{- $hasNonBuiltinTools := false }} +{{- if .Tools -}} +{{- $hasBrowserSearch := false }} +{{- $hasBrowserOpen := false }} +{{- $hasBrowserFind := false }} +{{- $hasPython := false }} + {{- range .Tools }} + {{- if eq .Function.Name "browser.search" -}}{{- $hasBrowserSearch = true -}} + {{- else if eq .Function.Name "browser.open" -}}{{- $hasBrowserOpen = true -}} + {{- else if eq .Function.Name "browser.find" -}}{{- $hasBrowserFind = true -}} + {{- else if eq .Function.Name "python" -}}{{- $hasPython = true -}} + {{- else }}{{ $hasNonBuiltinTools = true -}} + {{- end }} + {{- end }} +{{- if or $hasBrowserSearch $hasBrowserOpen $hasBrowserFind $hasPython }} + +# Tools +{{- if or $hasBrowserSearch $hasBrowserOpen $hasBrowserFind }} + +## browser + +// Tool for browsing. +// The `cursor` appears in brackets before each browsing display: `[{cursor}]`. +// Cite information from the tool using the following format: +// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`. +// Do not quote more than 10 words directly from the tool output. +// sources=web (default: web) +namespace browser { +{{- if $hasBrowserSearch }} + +// Searches for information related to `query` and displays `topn` results. +type search = (_: { +query: string, +topn?: number, // default: 10 +source?: string, +}) => any; +{{- end }} +{{- if $hasBrowserOpen }} + +// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines. +// Valid link ids are displayed with the formatting: `【{id}†.*】`. +// If `cursor` is not provided, the most recent page is implied. +// If `id` is a string, it is treated as a fully qualified URL associated with `source`. +// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available. +// Use this function without `id` to scroll to a new location of an opened page. +type open = (_: { +id?: number | string, // default: -1 +cursor?: number, // default: -1 +loc?: number, // default: -1 +num_lines?: number, // default: -1 +view_source?: boolean, // default: false +source?: string, +}) => any; +{{- end }} +{{- if $hasBrowserFind }} + +// Finds exact matches of `pattern` in the current page, or the page given by `cursor`. +type find = (_: { +pattern: string, +cursor?: number, // default: -1 +}) => any; +{{- end }} + +} // namespace browser +{{- end }}{{/* end if has browser tools */}} +{{- if $hasPython }} + +## python + +Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files). + +When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster. +{{- end }}{{/* end if hasPython */}} +{{- end }}{{/* end if has any built-in tools */}} +{{- end }}{{/* end if .Tools */}} + +# Valid channels: analysis, commentary, final. Channel must be included for every message.{{ if $hasNonBuiltinTools }} +Calls to these tools must go to the commentary channel: 'functions'. +{{- end -}}<|end|>{{/* end of system */ -}} +{{- if or $hasNonBuiltinTools .System -}} +<|start|>developer<|message|>{{- if $hasNonBuiltinTools }}# Tools + +## functions + +namespace functions { +{{- range .Tools }} +{{- if not (or (eq .Function.Name "browser.search") (eq .Function.Name "browser.open") (eq .Function.Name "browser.find") (eq .Function.Name "python")) }} +{{if .Function.Description }} +// {{ .Function.Description }} +{{- end }} +{{- if and .Function.Parameters.Properties (gt (len .Function.Parameters.Properties) 0) }} +type {{ .Function.Name }} = (_: { +{{- range $name, $prop := .Function.Parameters.Properties }} +{{- if $prop.Description }} + // {{ $prop.Description }} +{{- end }} + {{ $name }}: {{ if gt (len $prop.Type) 1 }}{{ range $i, $t := $prop.Type }}{{ if $i }} | {{ end }}{{ $t }}{{ end }}{{ else }}{{ index $prop.Type 0 }}{{ end }}, +{{- end }} +}) => any; +{{- else }} +type {{ .Function.Name }} = () => any; +{{- end }} +{{- end }}{{/* end if not browser tool */}} +{{- end }}{{/* end of range .Tools */}} + +} // namespace functions +{{- end }}{{/* end if hasNonBuiltinTools */}} +{{- if .System}} + +# Instructions + +{{ .System }} +{{- end -}} +<|end|> +{{- end -}} +{{- /* Find the index of the last user message */ -}} +{{- $lastUserIdx := -1 }} +{{- $prefillingContent := false }} +{{- $prefillingThinkingOnly := false }} +{{- range $i, $msg := .Messages }} + {{- $last := eq (len (slice $.Messages $i)) 1 -}} + {{- if eq $msg.Role "user" }} + {{- $lastUserIdx = $i }} + {{- end -}} + {{- if and $last (eq $msg.Role "assistant") (gt (len $msg.Content) 0) }} + {{- $prefillingContent = true }} + {{- else if and $last (eq $msg.Role "assistant") (gt (len $msg.Thinking) 0) }} + {{- $prefillingThinkingOnly = true }} + {{- end }} +{{- end -}} +{{- /* Now render messages */ -}} +{{- range $i, $msg := .Messages }} + {{- $last := eq (len (slice $.Messages $i)) 1 -}} + {{- if (ne $msg.Role "system") -}} + {{- if eq $msg.Role "tool" -}} + {{- if or (eq $msg.ToolName "python") (eq $msg.ToolName "browser.search") (eq $msg.ToolName "browser.open") (eq $msg.ToolName "browser.find") -}} + <|start|>{{ $msg.ToolName }} to=assistant<|message|>{{ $msg.Content }}<|end|> + {{- else -}} + <|start|>functions.{{ $msg.ToolName }} to=assistant<|message|>{{ $msg.Content }}<|end|> + {{- end -}} + {{- else if eq $msg.Role "assistant" -}} + {{- if and $msg.Thinking (gt $i $lastUserIdx) -}}{{- /* Show thinking only after last user message */ -}} + <|start|>assistant<|channel|>analysis<|message|>{{ $msg.Thinking }}{{- if not $prefillingThinkingOnly -}}<|end|>{{- end -}} + {{- end -}} + {{- if gt (len $msg.Content) 0 -}} + <|start|>assistant<|channel|>final<|message|>{{ $msg.Content }}{{- if not $prefillingContent -}}<|end|>{{- end -}} + {{- end -}} + {{- if gt (len $msg.ToolCalls) 0 -}} + {{- range $j, $toolCall := $msg.ToolCalls -}} + {{- $isBuiltin := or (eq $toolCall.Function.Name "python") (eq $toolCall.Function.Name "browser.search") (eq $toolCall.Function.Name "browser.open") (eq $toolCall.Function.Name "browser.find") -}} + <|start|>assistant<|channel|>{{ if $isBuiltin }}analysis{{ else }}commentary{{ end }} to={{ if not $isBuiltin}}functions.{{end}}{{ $toolCall.Function.Name }} <|constrain|>json<|message|>{{ $toolCall.Function.Arguments }}<|call|> + {{- end -}} + {{- end -}} + {{- else if eq $msg.Role "user" -}} + <|start|>{{ $msg.Role }}<|message|>{{ $msg.Content }}<|end|> + {{- end }} + {{- else }} + {{- end }} +{{- end -}} +{{- if not (or $prefillingContent $prefillingThinkingOnly) -}} +<|start|>assistant +{{- end -}}''' + +gptoss_template_template_eos_token = "<|return|>" +CHAT_TEMPLATES["gpt-oss"] = (gptoss_template, gptoss_template_template_eos_token, False, gptoss_ollama,) +DEFAULT_SYSTEM_MESSAGE["gpt-oss"] = None # No system message in GPT-oss + +CHAT_TEMPLATES["gptoss"] = (gptoss_template, gptoss_template_template_eos_token, False, gptoss_ollama,) +DEFAULT_SYSTEM_MESSAGE["gptoss"] = None # No system message in GPT-oss +pass + + def _change_system_message(template: str, type_chat_template: str, system_message: str = None): system_message_pattern = r"\{system_message\}" diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py index ab831dbaab..7f0c2f6959 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__ = "2025.8.1" +__version__ = "2025.8.2" __all__ = [ "SUPPORTS_BFLOAT16", diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py index 023234413a..b3218d2498 100644 --- a/unsloth/models/loader.py +++ b/unsloth/models/loader.py @@ -58,7 +58,7 @@ SUPPORTS_QWEN3 = transformers_version >= Version("4.50.3") SUPPORTS_QWEN3_MOE = transformers_version >= Version("4.50.3") SUPPORTS_FALCON_H1 = transformers_version >= Version("4.53.0") SUPPORTS_GEMMA3N = transformers_version >= Version("4.53.0") - +SUPPORTS_GPTOSS = transformers_version >= Version("4.55.0") if SUPPORTS_GEMMA: from .gemma import FastGemmaModel if SUPPORTS_GEMMA2: @@ -545,6 +545,7 @@ class FastModel(FastBaseModel): # Check versions lowered_model_name = model_name.lower() + os.environ["UNSLOTH_MODEL_NAME"] = lowered_model_name LATEST = '\nPlease use transformers via `pip install --no-deps git+https://github.com/huggingface/transformers.git`' NIGHTLY = '\nPlease use nightly transformers via pip install --upgrade "transformers>=4.49.0"`' # Pixtral @@ -587,10 +588,9 @@ class FastModel(FastBaseModel): elif "falcon-h1" in lowered_model_name: os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"] = \ "float16;torch.float32;torch.float16;"\ - "if name.endswith(('q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj', 'head')): module.to(torch.float16);" - os.environ["TRITON_F32_DEFAULT"] = "ieee" + "if name.endswith(('q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj', 'head')): module.to(torch.float16); "\ + "os.environ['TRITON_F32_DEFAULT'] = 'ieee';" elif "gpt-oss" in lowered_model_name: - os.environ["UNSLOTH_MODEL_NAME"] = "gpt_oss" os.environ["UNSLOTH_DISABLE_STATIC_GENERATION"] = "1" else: for check_model_name in DISABLE_COMPILE_MODEL_NAMES: diff --git a/unsloth/models/mapper.py b/unsloth/models/mapper.py index 28fa163e65..bba8f982da 100644 --- a/unsloth/models/mapper.py +++ b/unsloth/models/mapper.py @@ -909,6 +909,28 @@ __INT_TO_FLOAT_MAPPER = \ "mistralai/Devstral-Small-2507", "unsloth/Devstral-Small-2507-bnb-4bit", ), + "unsloth/Qwen3-30B-A3B-Thinking-2507" : ( + "unsloth/Qwen3-30B-A3B-Thinking-2507", + "Qwen/Qwen3-30B-A3B-Thinking-2507", + ), + "unsloth/Qwen3-30B-A3B-Instruct-2507" : ( + "unsloth/Qwen3-30B-A3B-Instruct-2507", + "Qwen/Qwen3-30B-A3B-Instruct-2507", + ), + "unsloth/Qwen3-Coder-30B-A3B-Instruct" : ( + "unsloth/Qwen3-Coder-30B-A3B-Instruct", + "Qwen/Qwen3-Coder-30B-A3B-Instruct", + ), + "unsloth/gpt-oss-20b-unsloth-bnb-4bit" : ( + "unsloth/gpt-oss-20b", + "openai/gpt-oss-20b", + "unsloth/gpt-oss-20b-bnb-4bit", + ), + "unsloth/gpt-oss-120b-unsloth-bnb-4bit" : ( + "unsloth/gpt-oss-120b", + "openai/gpt-oss-120b", + "unsloth/gpt-oss-120b-bnb-4bit", + ), } INT_TO_FLOAT_MAPPER = {} diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py index ab95231507..9529794e1a 100644 --- a/unsloth/models/vision.py +++ b/unsloth/models/vision.py @@ -272,6 +272,8 @@ class FastBaseModel: raise RuntimeError( "Unsloth: Please use FastModel or FastVisionModel and not use FastBaseModel directly!" ) + if os.environ.get("UNSLOTH_MODEL_NAME", "") == "": + os.environ["UNSLOTH_MODEL_NAME"] = model_name.lower() os.environ["UNSLOTH_USE_NEW_MODEL"] = "1" if trust_remote_code: @@ -427,16 +429,23 @@ class FastBaseModel: if do_forced_float32: torch_dtype = torch.bfloat16 raise_handler = RaiseUninitialized() - model = auto_model.from_pretrained( - model_name, - device_map = device_map, - torch_dtype = torch_dtype, - # quantization_config = bnb_config, - token = token, - trust_remote_code = trust_remote_code, - # attn_implementation = attn_implementation, - **kwargs, - ) + # MXFP4 -> BF16 GPT-OSS check + if "gpt-oss" in os.environ.get("UNSLOTH_MODEL_NAME", "") and \ + "quantization_config" not in kwargs: + + from unsloth_zoo.temporary_patches.gpt_oss import load_gpt_oss_MXFP4 + model = load_gpt_oss_MXFP4(model_name, torch_dtype) + else: + model = auto_model.from_pretrained( + model_name, + device_map = device_map, + torch_dtype = torch_dtype, + # quantization_config = bnb_config, + token = token, + trust_remote_code = trust_remote_code, + # attn_implementation = attn_implementation, + **kwargs, + ) raise_handler.remove() # Return old flag os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = old_hf_transfer @@ -622,17 +631,20 @@ class FastBaseModel: max_seq_length = model.max_seq_length # if we pass loftq_config = None we will get an error loftq_config = validate_loftq_config(loftq_config, lora_dropout, bias, init_lora_weights, model) + lora_config_dict = { + "r" : r, + "lora_alpha" : lora_alpha, + "target_modules" : target_modules, + "target_parameters" : kwargs.get("target_parameters", None), + "lora_dropout" : lora_dropout, + "bias" : bias, + "task_type" : task_type, + "use_rslora" : use_rslora, + "init_lora_weights" : init_lora_weights, + "loftq_config" : loftq_config, + } lora_config = LoraConfig( - r = r, - lora_alpha = lora_alpha, - target_modules = target_modules, - target_parameters = kwargs.get("target_parameters", None), - lora_dropout = lora_dropout, - bias = bias, - task_type = task_type, - use_rslora = use_rslora, - init_lora_weights = init_lora_weights, - loftq_config = loftq_config, + **{k:v for k,v in lora_config_dict.items() if key in LoraConfig.__doc__}, ) model = prepare_model_for_kbit_training( model,