Repository navigation
Export: add save_pretrained_openvino and push_to_hub_openvino support - #11907
Conversation
cb26943 to
2100452
Compare
2100452 to
d370ef8
Compare
Self-review fixes (force-pushed)Three issues spotted and fixed in
All CI-equivalent checks pass locally:
|
|
Hi @shimmyshimmer @mahiatlinux! Since Daniel might be busy, I'd really appreciate it if either of you could take a quick look at this PR when you have a moment. It adds OpenVINO export and Intel Arc support (via SYCL/llama.cpp) to Unsloth, all tests are passing. Thanks! |
|
Thanks for putting this together. I pulled the branch, ran the export for real on a GPU, and went through the Studio side as well. Short version: Tested at Blocker:
|
| Model | Result |
|---|---|
| unsloth/Llama-3.2-1B-Instruct (fp16, None, int8, int4) | RuntimeError: Couldn't get TorchScript module by tracing. Cause: 'LlamaForCausalLM' object has no attribute 'max_seq_length' |
| unsloth/Qwen3-0.6B (int8) | same, 'Qwen3ForCausalLM' object has no attribute 'max_seq_length' |
| unsloth/Qwen2-VL-2B-Instruct (int8, VLM path) | Couldn't get TorchScript module by tracing. Cause: Detected that you are using FX to torch.jit.trace a dynamo-optimized function. |
| unsloth/gemma-3-270m-it (int8) | optimum-intel refuses: The current version of Transformers does not allow for the export of the model. Maximum required is 5.0, got: 5.5.0 |
Why: ov_cls.from_pretrained(staging_dir, export=True) (unsloth/save.py:6981) reloads the staged checkpoint as a plain transformers model in the same process and traces it. By then, importing Unsloth has already replaced those classes' forwards at class level, for example LlamaForCausalLM.forward = CausalLM_fast_forward(...) at unsloth/models/llama.py:2315. That forward reads self.max_seq_length (unsloth/models/llama.py:920), which only exists on instances Unsloth loaded itself. Vision models hit Unsloth's compiled forwards instead.
Control: I took the same merged checkpoint and made the same OVModelForCausalLM.from_pretrained(..., export=True, compile=False, quantization_config=...) call in an interpreter that never imported unsloth. It exports fine and generates " Paris. The Eiffel Tower is located in Paris.", matching the merged 16-bit reference. So the merge is fine; the export needs to run out of process. A subprocess call to optimum-cli export openvino --model <staging> --weight-format int4 <out> would do it, and it also fixes item 2 below.
The new tests don't catch this because none of them run an export (item 7).
Other defects in the export path (unsloth/save.py)
Each of these is confirmed either by the clean-process export above or by running the PR's _unsloth_save_openvino against a tiny random Llama.
-
quantization_type="fp16"(and the defaultNone) produce int8 weights for any model with 1B+ parameters (save.py:6961, docstringsave.py:7038). With no quantization config and noload_in_8bit, optimum-intel's_apply_model_size_based_quantizationapplies{"bits": 8, "sym": False}once the model is over_MAX_UNCOMPRESSED_SIZE = 1e9. For Llama-3.2-1B (1.236B params):- "fp16" export: 1180 MB, weights uint8.
- with
load_in_8bit=False: 2357 MB, weights bf16.
Fix:
kwargs.setdefault("load_in_8bit", False)in that branch. -
The output doesn't load in openvino_genai, which is the inference path the PR description documents.
from_pretrained(export=True)callsmain_exportwithconvert_tokenizer=False, so noopenvino_tokenizer.xml/openvino_detokenizer.xmlis written.LLMPipeline(dir, "CPU")fails withEither openvino_tokenizer.xml was not provided or it was not loaded correctly. Tokenizer::encode is not available.- The description's
VLMPipelineexample fails on a text model withCould not open the file: ".../openvino_language_model.xml", so "works for both standard LLMs and VLMs" does not hold. - The description's export example passes no
tokenizer, so its output has no tokenizer at all, and nothing warns about it. optimum-cli export openvinoconverts tokenizers by default.
-
push_to_hub_openvino(..., private=True)is ignored. There is noprivateparameter, so it lands in**kwargs, gets passed toov_cls.from_pretrained, and is silently dropped there.create_repo(save.py:6998) gets onlyrepo_idandexist_ok. With recorders in place ofHfApi, it loggedcreate_repo {'repo_id': 'me/secret-model', 'exist_ok': True}.create_pr,revisionandcommit_messageare dropped the same way; the commit message is hardcoded atsave.py:7002.- A user who asks for a private repo can end up with a public one.
_unsloth_save_torchaoforwardsprivate(save.py:6690).
-
Temporary storage.
- The full 16-bit merge is staged in
tempfile.mkdtemp()(save.py:6919), with none of the space checks the torchao path has. - optimum also writes the uncompressed IR into its own
TemporaryDirectoryand keeps it alive on the class (cls._model_save_dir_tempdirectory_instance) until the next export or interpreter exit. On a tmpfs/tmp, that is RAM held for the rest of the notebook session. - Every local save leaves an empty
/tmp/unsloth-openvino-*directory behind, because onlystaging_diris removed (save.py:7011).
- The full 16-bit merge is staged in
-
The non-PEFT branch skips the normal save path.
save.py:6931-6932callsmodel.save_pretrained(staging_dir)directly instead ofunsloth_generic_save(..., save_method="merged_16bit"), which torchao uses for both cases.- An fp32 full fine-tune (what Unsloth does on fp16-only GPUs) is staged and exported as fp32, even with
quantization_type="fp16". - The Qwen3.5 VLM key remap and the MTP config reconcile are skipped too.
- An fp32 full fine-tune (what Unsloth does on fp16-only GPUs) is staged and exported as fp32, even with
-
An invalid
quantization_typeis rejected only after the full merge is written. The mapping (save.py:6952) runs after the merge (save.py:6931). Withquantization_type="nf4"on Llama-3.2-1B, the merge ran for 6.7 s before theValueError. Moving the mapping above step 1 fixes it. -
The tests don't exercise the export. The two test files pass locally (11 passed), but neither calls an export. I reverted production hunks one at a time. Each of these still left every test green:
- removing the vision-branch attachments
- removing the
__all__entries - removing the shim
- skipping the PEFT merge
- removing
ov_model.save_pretrained - removing the tokenizer save
- removing the
is_main_processguard - flipping
push_to_hub - changing int4 to 8-bit
Only the ValueError branch, the ImportError wrapper and the non-vision attachments are covered. A real tiny-model CPU export takes about 10 s and would have caught the blocker plus items 1, 2 and 6.
-
Dead shim.
unsloth_save_pretrained_openvinoinunsloth/models/sentence_transformer.py:62is never called.FastSentenceTransformeronly wires up the torchao and gguf wrappers, so sentence-transformer models don't get the method.
Studio / CLI / docs
-
The XPU block in
_get_gpu_memory(studio/backend/core/inference/llama_cpp.py:13260) is not reached on a normal Studio Intel install.- On Intel hosts, Studio installs the Vulkan llama.cpp prebuilt (
studio/install_llama_prebuilt.py:1434, and:1339on Windows), and_get_gpu_memoryreturns the Vulkan inventory first (llama_cpp.py:13193). - A SYCL build is still classified as CPU-only, because
_installed_ggml_backendshas no sycl entry (llama_cpp.py:9494). - Nothing in the diff installs or selects a SYCL build, so "native support for Intel Arc GPUs has been added to Unsloth Studio (via llama.cpp SYCL backend)" is not what the change does.
Where the block does run (XPU torch plus a non-Vulkan build):
- It hands
torch.xpuordinals to placement code that pins devices throughCUDA_VISIBLE_DEVICES/ HIP masks. A SYCL server ignores those. - Studio already deliberately refuses XPU device indices (
studio/backend/main.py:2172,studio/backend/routes/inference.py:13831). - With a CPU-only llama-server on an XPU host, it now reports GPUs where it reported none before. With a simulated
torch.xpu, base returns[]and head returns[(0, 10240, 12288), (1, 3072, 16384)]. - No test covers the new block.
- On Intel hosts, Studio installs the Vulkan llama.cpp prebuilt (
-
--force-global-env(unsloth_cli/commands/studio.py:1717,:2162):unsloth studio --force-global-env run ...silently drops the flag (exit 1, "Unsloth Studio not set up"). Every other launcher-only option gets "put the flag after the subcommand" from the guard atstudio.py:1799; this one is missing from it.- The help text mentions OpenVINO, but Studio has no OpenVINO runtime.
- XPU torch already has supported routes:
install.ps1autodetects Arc on Windows,UNSLOTH_TORCH_INDEX_FAMILY=xpuworks on Linux, andstudio/backend/run.pyruns under any interpreter. - Under the flag, the training worker's on-demand package installs (
studio/backend/core/training/worker.py:1449,sys.executable -m pip install) go into the user's global Python.
-
INTEL_ARC_BUILD.md:- L79: the
~/.local/binwrapper is not used "automatically"._find_llama_server_binaryonly checks PATH at step 8 (llama_cpp.py:8562), after~/.unsloth/llama.cpp, so any existing Studio install wins. The supported overrides areLLAMA_SERVER_PATH,UNSLOTH_LLAMA_CPP_PATHand the custom llama.cpp folder setting. - L58: llama-server is not launched in a clean environment. The child env starts from
os.environ(studio/backend/utils/native_path_leases.py:112), so sourcingsetvars.shbeforeunsloth studiois enough. - L7: the xe driver was merged in Linux 6.8, not 7.0.
- The file sits at the repo root and nothing links to it.
- L79: the
Scope
CONTRIBUTING.md asks to keep PRs focused on a single change. This one bundles four independent pieces: the OpenVINO export, an XPU memory probe, a CLI flag and a build doc. None depends on another. Intel SYCL support for Studio is already tracked in #8931 and #8556, with #9084 open for it. CI hasn't run yet (the workflow runs are waiting for approval), so "all tests are passing" currently means the 11 local tests.
Suggested path for the export: an export-only PR that
- runs the conversion in a subprocess via
optimum-cli export openvino, so tokenizers are converted too; - stages through
unsloth_generic_save, next to the destination rather than in TMPDIR; - maps fp16 to
load_in_8bit=Falseand validates the type before merging; - forwards
privateand the other hub arguments; - adds one real tiny-model export test.
Environment and checks run
- Live GPU runs: RTX 5060 Ti 16 GB, driver 595.91.07, Linux, Python 3.12, torch 2.11.0+cu130, transformers 5.5.0, peft 0.21.0, unsloth-zoo 2026.9.7, optimum 2.3.0, optimum-intel 2.2.0, openvino 2026.4.0, openvino-genai 2026.4.0, nncf 3.4.0.
- Install:
pip install -e ".[huggingfacenotorch]" "optimum[openvino]" openvino-genai bitsandbytesinto a fresh venv. optimum-intel 2.2.0 pinshuggingface-hub<1.22and thestudioextra requires>=1.31, so the two can't share the Studio venv. python -m pytest tests/saving/test_export_api_surface.py tests/saving/test_openvino_export.py -q: 11 passed.tests/test_cold_import_order.py: 12 passed.ruff checkandscripts/run_ruff_format.pyare clean on the changed files.- The existing
_get_gpu_memorytests (7 files, 207 tests) and the CLI tests (193) give the same results at base and head. The new Studio and CLI code has no tests. - There's no Intel GPU here. The Studio XPU findings come from a monkeypatched
torch.xpuplus code reading. - Everything in the blocker table is a live GPU run through
model.save_pretrained_openvino. The clean-process control and the tiny-model reproductions ran on CPU.
In-process vs clean-process export, Llama-3.2-1B + LoRA
# PR method, inside the Unsloth process
fp16 -> RuntimeError: Couldn't get TorchScript module by tracing.
'LlamaForCausalLM' object has no attribute 'max_seq_length'
None -> same
int8 -> same
int4 -> same
nf4 -> ValueError after 6.7s (full merge written first)
# same merged checkpoint, same optimum call, interpreter without unsloth
fp16 (quantization_config=None): 1180.2 MB, weight constants uint8 1,236,251,904
fp16 + load_in_8bit=False: 2357.3 MB, weight constants bfloat16 1,235,746,816
int8: 1179.7 MB, int8_t greedy " Paris. The Eiffel Tower is located in Paris." (matches merged 16-bit reference)
int4: 729.6 MB, int4_t greedy " Paris. Paris is a city located in the north of France"
files: chat_template.jinja, config.json, generation_config.json, openvino_model.bin,
openvino_model.xml, tokenizer.json, tokenizer_config.json
LLMPipeline(dir, "CPU"): Either openvino_tokenizer.xml was not provided or it was not loaded correctly.
VLMPipeline(dir, "CPU"): Could not open the file: ".../openvino_language_model.xml"
The torch.xpu block in _get_gpu_memory is never reached on a Studio Intel install, which runs the Vulkan llama.cpp build, and where it is reached it feeds XPU ordinals to placement that pins through CUDA_VISIBLE_DEVICES. --force-global-env is ignored before a subcommand and duplicates UNSLOTH_TORCH_INDEX_FAMILY=xpu and running studio/backend/run.py directly. The build doc says a ~/.local/bin wrapper is picked up automatically, but Studio checks PATH only after its own managed llama.cpp. Intel SYCL support for Studio is tracked in unslothai#8931 and unslothai#9084.
save_pretrained_openvino failed for every model: optimum-intel reloads the staged merge in this process and traces it through transformers classes whose forwards Unsloth has already patched (Llama and Qwen3 read self.max_seq_length, the vision models hit compiled forwards), so the TorchScript trace always failed. The merge itself is fine: the same checkpoint exports cleanly in an interpreter that never imported unsloth. Merge through unsloth_generic_save for LoRA and full fine-tunes alike, then run `python -m optimum.commands.optimum_cli export openvino` on the staging checkpoint with an explicit --task, which the CLI cannot infer from a local directory. The CLI also writes openvino_tokenizer.xml and openvino_detokenizer.xml, which openvino_genai pipelines require. Also: - None and "fp16" pass --weight-format fp16; with no weight format optimum-intel int8-compresses every model over 1B parameters. - quantization_type and any extra optimum-cli options, now passed as keywords, are checked with optimum-intel's own parser before the merge. - push_to_hub_openvino forwards private, commit_message, commit_description, create_pr and revision, and checks the repo first. - Local exports stage beside the destination instead of in TMPDIR, and the whole staging directory is removed, including on failure. - The child process gets no Hub credential and trusts remote code only when the model was loaded through it.
Nothing in unsloth/models/sentence_transformer.py calls unsloth_save_pretrained_openvino; FastSentenceTransformer only wires the torchao and GGUF exports.
tests/saving is excluded from the auto-discovered repo tests, and the consolidated job only runs the files it lists, so test_openvino_export.py never ran. The real-export test inside it skips without optimum-intel.
… merging optimum-intel declares per-architecture transformers bounds and enforces them only inside the export, after the 16bit merge has been written. Under Unsloth's default transformers 5.5.0, optimum-intel 2.2.0 refuses qwen2_vl, qwen2_5_vl, qwen3_vl, qwen3_5 and gemma3_text that way. Read the bounds first in a short child process (optimum's export registry loads the OpenVINO runtime) and raise before the merge, as the compressed export does for llm-compressor's ceiling. Any probe failure defers to the export.
A LoRA merge copies the base model's tokenizer even when none is passed, so the export usually has openvino_tokenizer.xml and the up-front warning was wrong. Warn when the output actually lacks it, which also covers a missing openvino-tokenizers install.
Same behaviours covered in fewer, denser tests. The real export now uses hf-internal-testing/tiny-random-LlamaForCausalLM and skips when optimum-intel is not installed or the model is not reachable.
Every non-VLM defaulted to text-generation-with-past, so a T5/BART-style model wrote a full 16bit merge before optimum-cli rejected the task. No single default fits encoder-decoder models (T5/BART export as text2text-generation, Whisper as speech recognition), so ask for the task before merging and honour one passed as task = ....
|
I pushed fixes for everything in my review above to this branch (
What the export does now
Before and after, live on GPUSame venv, same inputs.
Also checked on the fixed branch:
Native OS and dependency rangeA disposable workflow on my fork, run 36202074264 at
The negative control is the same workflow on the PR head before these fixes (
CodexConverged on a mirror of this branch merged onto current Tests
Not run live: a real Hub push. It is covered by the recorder test and the native harness ( The PR description still describes the removed Studio / Intel Arc pieces and the in-process export. It should be updated to match: OpenVINO export only, with Environment
|
mahiatlinux
left a comment
There was a problem hiding this comment.
LGTM! Ready to merge, all manually checked.
…decode the bounds probe as UTF-8 (unslothai#12012) unslothai#11907 passed --trust-remote-code to optimum-cli when either the model or the tokenizer had been loaded through remote code. The flag covers both loads, so an approved custom tokenizer let the reload run a built-in-loaded model's unvetted auto_map code, which test_compressed_and_gguf_lora_paths_drop_auto_map_trust forbids. The flag now follows the model, as the GGUF-LoRA converter does, and a tokenizer-only case warns instead. The optimum-intel bounds probe decoded its output in the locale encoding, which test_save_subprocess_text_calls_declare_utf8_encoding forbids (unslothai#2660); it now pins utf-8.
…unslothai#11907) * Export: add save_pretrained_openvino and push_to_hub_openvino support * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * CLI: add --force-global-env to studio launcher * style: fix ruff formatting for --force-global-env * fix: detect Intel XPU in llama.cpp GPU memory probe * style: fix ruff formatting for llama_cpp.py (Intel XPU patch) * docs: add instructions for Intel Arc SYCL compilation * docs: add wrapper script instructions for Intel Arc SYCL build * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Drop the Studio XPU probe, --force-global-env and INTEL_ARC_BUILD.md The torch.xpu block in _get_gpu_memory is never reached on a Studio Intel install, which runs the Vulkan llama.cpp build, and where it is reached it feeds XPU ordinals to placement that pins through CUDA_VISIBLE_DEVICES. --force-global-env is ignored before a subcommand and duplicates UNSLOTH_TORCH_INDEX_FAMILY=xpu and running studio/backend/run.py directly. The build doc says a ~/.local/bin wrapper is picked up automatically, but Studio checks PATH only after its own managed llama.cpp. Intel SYCL support for Studio is tracked in unslothai#8931 and unslothai#9084. * Export OpenVINO IR with optimum-cli in a separate process save_pretrained_openvino failed for every model: optimum-intel reloads the staged merge in this process and traces it through transformers classes whose forwards Unsloth has already patched (Llama and Qwen3 read self.max_seq_length, the vision models hit compiled forwards), so the TorchScript trace always failed. The merge itself is fine: the same checkpoint exports cleanly in an interpreter that never imported unsloth. Merge through unsloth_generic_save for LoRA and full fine-tunes alike, then run `python -m optimum.commands.optimum_cli export openvino` on the staging checkpoint with an explicit --task, which the CLI cannot infer from a local directory. The CLI also writes openvino_tokenizer.xml and openvino_detokenizer.xml, which openvino_genai pipelines require. Also: - None and "fp16" pass --weight-format fp16; with no weight format optimum-intel int8-compresses every model over 1B parameters. - quantization_type and any extra optimum-cli options, now passed as keywords, are checked with optimum-intel's own parser before the merge. - push_to_hub_openvino forwards private, commit_message, commit_description, create_pr and revision, and checks the repo first. - Local exports stage beside the destination instead of in TMPDIR, and the whole staging directory is removed, including on failure. - The child process gets no Hub credential and trusts remote code only when the model was loaded through it. * Remove the unused sentence-transformers OpenVINO shim Nothing in unsloth/models/sentence_transformer.py calls unsloth_save_pretrained_openvino; FastSentenceTransformer only wires the torchao and GGUF exports. * Run the OpenVINO export tests in CI tests/saving is excluded from the auto-discovered repo tests, and the consolidated job only runs the files it lists, so test_openvino_export.py never ran. The real-export test inside it skips without optimum-intel. * Check optimum-intel's transformers bounds for the architecture before merging optimum-intel declares per-architecture transformers bounds and enforces them only inside the export, after the 16bit merge has been written. Under Unsloth's default transformers 5.5.0, optimum-intel 2.2.0 refuses qwen2_vl, qwen2_5_vl, qwen3_vl, qwen3_5 and gemma3_text that way. Read the bounds first in a short child process (optimum's export registry loads the OpenVINO runtime) and raise before the merge, as the compressed export does for llm-compressor's ceiling. Any probe failure defers to the export. * Warn about a missing OpenVINO tokenizer after the export, not before A LoRA merge copies the base model's tokenizer even when none is passed, so the export usually has openvino_tokenizer.xml and the up-front warning was wrong. Warn when the output actually lacks it, which also covers a missing openvino-tokenizers install. * Consolidate the OpenVINO export tests Same behaviours covered in fewer, denser tests. The real export now uses hf-internal-testing/tiny-random-LlamaForCausalLM and skips when optimum-intel is not installed or the model is not reachable. * Require an explicit task for encoder-decoder OpenVINO exports Every non-VLM defaulted to text-generation-with-past, so a T5/BART-style model wrote a full 16bit merge before optimum-cli rejected the task. No single default fits encoder-decoder models (T5/BART export as text2text-generation, Whisper as speech recognition), so ask for the task before merging and honour one passed as task = .... --------- Co-authored-by: Aleksei Boklag <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Maheswar Kumar <[email protected]> Co-authored-by: mahiatlinux <[email protected]>
…decode the bounds probe as UTF-8 (unslothai#12012) unslothai#11907 passed --trust-remote-code to optimum-cli when either the model or the tokenizer had been loaded through remote code. The flag covers both loads, so an approved custom tokenizer let the reload run a built-in-loaded model's unvetted auto_map code, which test_compressed_and_gguf_lora_paths_drop_auto_map_trust forbids. The flag now follows the model, as the GGUF-LoRA converter does, and a tokenizer-only case warns instead. The optimum-intel bounds probe decoded its output in the locale encoding, which test_save_subprocess_text_calls_declare_utf8_encoding forbids (unslothai#2660); it now pins utf-8.

Summary
Adds OpenVINO IR export for fine-tuned models, for deployment on Intel CPUs, GPUs (Arc, iGPU) and NPUs through OpenVINO Runtime, optimum-intel and openvino_genai:
model.save_pretrained_openvino(save_directory, tokenizer = ..., quantization_type = ...)model.push_to_hub_openvino(repo_id, tokenizer = ..., quantization_type = ..., private = ...)Requires
pip install 'optimum[openvino]'.How it works
unsloth_generic_save. The merge is staged beside the destination rather than in/tmp.python -m optimum.commands.optimum_cli export openvinoin a separate process under the same interpreter.openvino_tokenizer.xml/openvino_detokenizer.xml, which openvino_genai needs.text-generation-with-past, orimage-text-to-textfor vision models), because the CLI cannot infer it from a local directory.--trust-remote-codeis passed only when the model was loaded through remote code.Options
quantization_typeNone/"fp16""int8"--weight-format int8 --sym"int4"--weight-format int4 --sym --group-size 128Other keywords map to
optimum-cli export openvinooptions and override the preset, for examplegroup_size = 64, ratio = 0.8, sym = False, awq = True, dataset = "wikitext2".push_to_hub_openvinoalso takesprivate,commit_message,commit_description,create_prandrevision.These are checked before the merge, so a bad request fails in seconds instead of after writing a full 16-bit checkpoint:
task = ...(T5/BART and Whisper export under different tasks);qwen2_vl,qwen2_5_vl,qwen3_vlandgemma3_textat transformers 5.0, so those fail early with the required range under transformers 5.5.0.Usage
Vision-language exports load with
ov_genai.VLMPipelineoroptimum.intel.OVModelForVisualCausalLM.Testing
tests/saving/test_openvino_export.pyruns on CPU CI (added to the consolidated test list). It includes a real tiny-Llama export with the model forward patched in-process, which runs when optimum-intel is installed.save_pretrained_openvinoand then generation in a clean process:LLMPipelinegenerates.Details and evidence: #11907 (comment)