Skip to content

Export: add save_pretrained_openvino and push_to_hub_openvino support - #11907

Merged
mahiatlinux merged 19 commits into
unslothai:mainfrom
goodmai:feature/openvino-export
Sep 26, 2026
Merged

mahiatlinux merged 19 commits into
unslothai:mainfrom
goodmai:feature/openvino-export

Conversation

@goodmai

@goodmai goodmai commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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

  1. LoRA adapters (or a full fine-tune) are merged to 16-bit with unsloth_generic_save. The merge is staged beside the destination rather than in /tmp.
  2. The staged checkpoint is converted by python -m optimum.commands.optimum_cli export openvino in a separate process under the same interpreter.
    • Converting in-process cannot work: optimum-intel traces the reloaded model through transformers classes Unsloth has already patched, and the trace fails.
    • The CLI also writes openvino_tokenizer.xml / openvino_detokenizer.xml, which openvino_genai needs.
    • The task is passed explicitly (text-generation-with-past, or image-text-to-text for vision models), because the CLI cannot infer it from a local directory.
  3. The staging directory is always removed, including on failure or interrupt. The child process gets no Hub credential. --trust-remote-code is passed only when the model was loaded through remote code.

Options

quantization_type Export
None / "fp16" unquantized 16-bit weights (without an explicit format, optimum-intel int8-compresses every model over 1B parameters)
"int8" --weight-format int8 --sym
"int4" --weight-format int4 --sym --group-size 128

Other keywords map to optimum-cli export openvino options and override the preset, for example group_size = 64, ratio = 0.8, sym = False, awq = True, dataset = "wikitext2". push_to_hub_openvino also takes private, commit_message, commit_description, create_pr and revision.

These are checked before the merge, so a bad request fails in seconds instead of after writing a full 16-bit checkpoint:

  • the quantization type and every option, against optimum-intel's own argument parser;
  • that optimum-intel is installed;
  • encoder-decoder models, which need an explicit task = ... (T5/BART and Whisper export under different tasks);
  • optimum-intel's per-architecture transformers bounds. For example, optimum-intel 2.2.0 caps qwen2_vl, qwen2_5_vl, qwen3_vl and gemma3_text at transformers 5.0, so those fail early with the required range under transformers 5.5.0.

Usage

model.save_pretrained_openvino("model_ov", tokenizer = tokenizer, quantization_type = "int4")
import openvino_genai as ov_genai

pipe = ov_genai.LLMPipeline("model_ov", "CPU")  # "GPU" for Intel Arc / iGPU, "NPU" for Core Ultra
print(pipe.generate("What is the capital of France?", max_new_tokens = 64))

Vision-language exports load with ov_genai.VLMPipeline or optimum.intel.OVModelForVisualCausalLM.

Testing

  • Unit tests: tests/saving/test_openvino_export.py runs 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.
  • Live GPU runs, each with save_pretrained_openvino and then generation in a clean process:
    • Llama-3.2-1B: fp16, int8 and int4. The top-1 token matches the merged 16-bit reference, and LLMPipeline generates.
    • Qwen3-0.6B: int4.
    • An fp32 full fine-tune: exported as 16-bit.
    • Qwen2-VL-2B: fp16 on transformers 4.57.3 with optimum-intel 1.27.0. It gives the same greedy answer as PyTorch on identical image and text inputs.
  • Native Windows, macOS (arm64) and Linux: real exports into paths with spaces and unicode.
  • Dependency range: optimum-intel 1.24.0 (transformers 4.52.4, Python 3.10) through optimum-intel main, and Python 3.13.

Details and evidence: #11907 (comment)

@goodmai
goodmai force-pushed the feature/openvino-export branch from cb26943 to 2100452 Compare September 25, 2026 08:42
@goodmai
goodmai force-pushed the feature/openvino-export branch from 2100452 to d370ef8 Compare September 25, 2026 08:47
@goodmai

goodmai commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Self-review fixes (force-pushed)

Three issues spotted and fixed in d370ef86e:

  1. Removed fragile _is_vlm guard — _is_vlm() is defined at module scope (line 808) and all other callers (unsloth_save_pretrained_gguf, _unsloth_save_torchao) call it directly without a "_is_vlm" in globals() guard. Made the OpenVINO path consistent.

  2. Fixed return value for push_to_hub=True — Previously returned final_dir which pointed inside the temp work_tmp directory that gets cleaned up by finally. Now returns the repo_id (Hub identifier) after upload, matching the pattern used by other Hub-push methods.

  3. Used tmp_path fixture in tests — Replaced hardcoded /tmp/dummy_ov_dir with pytest's tmp_path for proper test isolation and cleanup.

All CI-equivalent checks pass locally:

  • python -m compileall ✅
  • ruff check --select E9,F63,F7,F82 ✅ (the one F821 on unsloth_push_to_hub is pre-existing upstream — it's dynamically generated via exec())
  • lint_duplicate_definitions.py ✅ (6 findings, all pre-existing)
  • pytest tests/saving/ — 11/11 passed ✅

@goodmai

goodmai commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

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!

@mahiatlinux

Copy link
Copy Markdown
Contributor

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: save_pretrained_openvino does not work yet from an Unsloth session, and the Studio / Intel Arc changes do not do what the description says. I'd suggest turning this into an export-only PR once the export runs, and dropping the Studio, CLI and doc changes in favour of #9084 / #8931.

Tested at 3e84dc26. The only commit since then (17233220) is the pre-commit.ci reflow of two lines outside these code paths, so everything below still applies. Line numbers are at 17233220.

Blocker: save_pretrained_openvino fails on every model I tried

Flow: FastLanguageModel / FastModel / FastVisionModel.from_pretrained(..., load_in_4bit=True), then get_peft_model, then model.save_pretrained_openvino(dir, tokenizer=tok, quantization_type=...).

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.

  1. quantization_type="fp16" (and the default None) produce int8 weights for any model with 1B+ parameters (save.py:6961, docstring save.py:7038). With no quantization config and no load_in_8bit, optimum-intel's _apply_model_size_based_quantization applies {"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.

  2. The output doesn't load in openvino_genai, which is the inference path the PR description documents.

    • from_pretrained(export=True) calls main_export with convert_tokenizer=False, so no openvino_tokenizer.xml / openvino_detokenizer.xml is written.
    • LLMPipeline(dir, "CPU") fails with Either openvino_tokenizer.xml was not provided or it was not loaded correctly. Tokenizer::encode is not available.
    • The description's VLMPipeline example fails on a text model with Could 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 openvino converts tokenizers by default.
  3. push_to_hub_openvino(..., private=True) is ignored. There is no private parameter, so it lands in **kwargs, gets passed to ov_cls.from_pretrained, and is silently dropped there.

    • create_repo (save.py:6998) gets only repo_id and exist_ok. With recorders in place of HfApi, it logged create_repo {'repo_id': 'me/secret-model', 'exist_ok': True}.
    • create_pr, revision and commit_message are dropped the same way; the commit message is hardcoded at save.py:7002.
    • A user who asks for a private repo can end up with a public one. _unsloth_save_torchao forwards private (save.py:6690).
  4. 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 TemporaryDirectory and 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 only staging_dir is removed (save.py:7011).
  5. The non-PEFT branch skips the normal save path. save.py:6931-6932 calls model.save_pretrained(staging_dir) directly instead of unsloth_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.
  6. An invalid quantization_type is rejected only after the full merge is written. The mapping (save.py:6952) runs after the merge (save.py:6931). With quantization_type="nf4" on Llama-3.2-1B, the merge ran for 6.7 s before the ValueError. Moving the mapping above step 1 fixes it.

  7. 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_process guard
    • 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.

  8. Dead shim. unsloth_save_pretrained_openvino in unsloth/models/sentence_transformer.py:62 is never called. FastSentenceTransformer only wires up the torchao and gguf wrappers, so sentence-transformer models don't get the method.

Studio / CLI / docs

  1. 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 :1339 on Windows), and _get_gpu_memory returns the Vulkan inventory first (llama_cpp.py:13193).
    • A SYCL build is still classified as CPU-only, because _installed_ggml_backends has 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.xpu ordinals to placement code that pins devices through CUDA_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.
  2. --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 at studio.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.ps1 autodetects Arc on Windows, UNSLOTH_TORCH_INDEX_FAMILY=xpu works on Linux, and studio/backend/run.py runs 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.
  3. INTEL_ARC_BUILD.md:

    • L79: the ~/.local/bin wrapper is not used "automatically". _find_llama_server_binary only checks PATH at step 8 (llama_cpp.py:8562), after ~/.unsloth/llama.cpp, so any existing Studio install wins. The supported overrides are LLAMA_SERVER_PATH, UNSLOTH_LLAMA_CPP_PATH and 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 sourcing setvars.sh before unsloth studio is 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.

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=False and validates the type before merging;
  • forwards private and 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 bitsandbytes into a fresh venv. optimum-intel 2.2.0 pins huggingface-hub<1.22 and the studio extra 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 check and scripts/run_ruff_format.py are clean on the changed files.
  • The existing _get_gpu_memory tests (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.xpu plus 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 = ....
@mahiatlinux

Copy link
Copy Markdown
Contributor

I pushed fixes for everything in my review above to this branch (17233220..3b35c751, maintainer edit). Each commit is focused:

Commit Change
072d5a03 Drop the Studio XPU probe, --force-global-env and INTEL_ARC_BUILD.md. They restore main exactly. Intel SYCL support for Studio is tracked in #8931 / #9084.
f5bf2f82 Export OpenVINO IR with optimum-cli in a separate process.
aedcf062 Remove the unused sentence-transformers shim.
26e9adfa Add tests/saving/test_openvino_export.py to the consolidated CI list. tests/saving is not auto-discovered, so it never ran before.
39b5f925 Check optimum-intel's per-architecture transformers bounds before the merge.
94060b5f Warn about a missing OpenVINO tokenizer after the export, not before.
4e12fc4e Consolidate the tests.
3b35c751 Require an explicit task for encoder-decoder models, from Codex review on the mirror. T5/BART and Whisper need different tasks, so this fails before the merge instead of after it.

What the export does now

  • Merge: everything goes through unsloth_generic_save(..., "merged_16bit"), LoRA and full fine-tunes alike. The staging directory sits beside the destination, not in /tmp.
  • Export: the CLI runs as python -m optimum.commands.optimum_cli export openvino --model <staging> --task <text-generation-with-past | image-text-to-text> --library transformers --weight-format ... under the same interpreter. The child never imports Unsloth, so the trace sees stock transformers.
  • Task: it is passed explicitly, because the CLI cannot infer it from a local directory (optimum-intel export docs).
  • Tokenizer: the CLI converts it, so openvino_tokenizer.xml and openvino_detokenizer.xml are written.
  • quantization_type:
    • None / "fp16": --weight-format fp16 (unquantized 16-bit). Without it, "models larger than 1 billion parameters are exported with 8-bit weights by default" (same docs).
    • "int8": int8 --sym.
    • "int4": int4 --sym --group-size 128.
    • Extra keywords map to CLI options and override the preset, e.g. group_size = 64, ratio = 0.8, sym = False, awq = True. The in-process quantization_config object cannot cross the process boundary, so it is replaced by these keywords.
  • Checked before the merge:
    • the quantization type and every option, against optimum-intel's own argument parser;
    • that optimum-intel is installed;
    • that the architecture is inside optimum-intel's transformers bounds, read in a short child process. Under Unsloth's default transformers 5.5.0, optimum-intel 2.2.0 caps qwen2_vl, qwen2_5_vl, qwen3_vl and gemma3_text at 5.0 and qwen3_5 at 5.2.x. Those models now fail in seconds with the needed range, not after a full merge.
  • Hub push: push_to_hub_openvino checks the repo before the merge. It forwards private, commit_message, commit_description, create_pr and revision.
  • Cleanup: the staging directory is always removed, including on failure and on Ctrl+C. The child gets no Hub credential. --trust-remote-code is passed only when the model or tokenizer was loaded through remote code.

Before and after, live on GPU

Same venv, same inputs. Unsloth FastLanguageModel/FastVisionModel, 4-bit load, then get_peft_model with non-zero LoRA B, then save_pretrained_openvino:

PR head 17233220 This branch
Llama-3.2-1B int4 RuntimeError: Couldn't get TorchScript module by tracing. ('LlamaForCausalLM' object has no attribute 'max_seq_length') exports in 28 s, 757 MB, top-1 matches the merged 16-bit reference, LLMPipeline generates "The capital of France is Paris."
Llama-3.2-1B fp16 / None same error (and would have been int8) weights float16 (1.236B elements), 2.38 GB, top-1 matches, max logit diff 0.12
Llama-3.2-1B int8 same error weights int8_t, 1.21 GB, top-1 matches
Qwen3-0.6B int4 same error exports, top-1 matches, LLMPipeline generates
fp32 full fine-tune (Qwen3-0.6B, no LoRA) would stage fp32 staged and exported as bf16
Qwen2-VL-2B fp16, transformers 4.57.3 + optimum-intel 1.27.0 trace error exports the language, text-embedding, vision and merger IRs (4.7 GB). VLMPipeline and OVModelForVisualCausalLM load and generate. Against PyTorch on identical processed image+text inputs: same greedy answer, same first token, identical top-4, max first-step logit diff 0.26.
Qwen2-VL-2B / gemma-3-270m on transformers 5.5.0 trace error after a full merge RuntimeError: optimum-intel cannot export qwen2_vl under transformers 5.5.0; it needs transformers <= 5.0 before any merge
quantization_type = "nf5" ValueError after 8.0 s of merging ValueError in 0.0 s
leftover /tmp/unsloth-openvino-* 2 empty dirs per run none

Also checked on the fixed branch:

  • The Unsloth session still works after exporting: generate returns the same text as before.
  • Awkward paths: spaces, unicode and missing parent directories work, as do a relative path with a trailing slash and a pathlib.Path.
  • Re-exporting into an existing directory works.
  • Anonymous token = False works.
  • Extra options apply: group_size = 64, ratio = 0.8 produce int4 groups of 64 mixed with int8.
  • Ctrl+C: SIGINT to the Unsloth process during the export kills the optimum-cli child and removes the staging directory.
  • Cost (Llama-3.2-1B int4): 35 s wall. Staging is 2.32 GB on disk (2 bytes per parameter). Peak RSS is 6.2 GB in the Unsloth process and 15.1 GB in the optimum-cli child. The child figure is optimum's own int4 export cost, now outside the training process.

Native OS and dependency range

A disposable workflow on my fork, run 36202074264 at 3b35c751, passes all 7 jobs. On its first attempt the Windows job died with exit code 132 (illegal instruction) inside openvino_genai.LLMPipeline, after the export and every export check had passed. The same step passed in the earlier runs and on the rerun, so it points at the hosted runner's CPU rather than the export.

  • Native export on ubuntu-latest, windows-latest (Server 2025) and macos-latest (26, arm64). It does a real optimum-cli export of a tiny Llama into dir with space/ünïcødé/ov out while LlamaModel.forward is broken in-process the way Unsloth's patch breaks it. It then loads the result with openvino_genai.LLMPipeline and OVModelForCausalLM.
  • Consolidated Bucket-A environment, all three transformers cells (4.57.6, latest 5.x, pyproject 5.5.0), plus one cell with optimum-intel installed so the real-export test runs.

The negative control is the same workflow on the PR head before these fixes (17233220): run 36193298832. Its native export fails on all three OSes with Couldn't get TorchScript module by tracing / 'LlamaModel' object has no attribute 'max_seq_length'.

test_openvino_export.py, test_export_api_surface.py and test_export_dispatch.py pass with no skips, so the real export ran in every cell:

optimum-intel transformers Python Other pins
1.24.0 4.52.4 3.10 OpenVINO 2025.2, nncf 2.17
1.27.0 4.57.3 3.12
2.2.0 5.5.0 3.12 (GPU) and 3.13
main (2.3.0.dev0) 5.5.0 3.12

Codex

Converged on a mirror of this branch merged onto current main (staging-review#56): "Didn't find any major issues". The only finding along the way (encoder-decoder task, staging-review#55) is fixed in 3b35c751.

Tests

tests/saving/test_openvino_export.py has 15 tests and is under 30% of the PR's added lines.

  • Unit tests: the merge and child are faked, so they run on CPU CI without optimum-intel.
  • Real-export test: it exports a tiny Llama with LlamaModel.forward patched in-process. It skips without optimum-intel.
  • Mutation check: I broke each behaviour once, 21 mutations, and every one fails a test. That includes putting the export back in-process (the original design), which the real-export test catches.
  • Other suites: tests/test_cold_import_order.py and the consolidated CI tests/saving list pass except test_save_method_lora_routing.py, which fails identically on main (NameError: _refuse_unsaveable_text_core).
  • Lint and format: ruff 0.15.18 and scripts/run_ruff_format.py are clean. The branch merges cleanly into current main, and the same tests pass on the merge.

Not run live: a real Hub push. It is covered by the recorder test and the native harness (create_repo(private = True), then upload of the IR, then TMPDIR clean).

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 quantization_type and CLI-option keywords.

Environment
  • Linux x86_64, RTX 5060 Ti 16 GB, driver 595.91.07.
  • 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.
  • Python 3.12. Models: unsloth/Llama-3.2-1B-Instruct, unsloth/Qwen3-0.6B, unsloth/Qwen2-VL-2B-Instruct, unsloth/gemma-3-270m-it.

@mahiatlinux
mahiatlinux self-requested a review September 25, 2026 23:51

@mahiatlinux mahiatlinux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Ready to merge, all manually checked.

@mahiatlinux

Copy link
Copy Markdown
Contributor
image

@mahiatlinux
mahiatlinux merged commit 8de51b1 into unslothai:main Sep 26, 2026
24 of 25 checks passed
thealidev pushed a commit to RMAAPK/unsloth that referenced this pull request Sep 26, 2026
…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.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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]>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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.
@danielhanchen danielhanchen mentioned this pull request Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants