This guide demonstrates how to convert the Qwen3-8B model to ONNX format using Microsoft Olive and Microsoft ONNXRuntime GenAI.
1# Update your transformers library
2pip install transformers -U
3
4# Install Microsoft Olive
5pip install git+https://github.com/microsoft/Olive.git
6
7# Install Microsoft ONNXRuntime GenAI
8git clone https://github.com/microsoft/onnxruntime-genai
9cd onnxruntime-genai && python build.py --config Release
1# Convert the model using Microsoft Olive
2olive auto-opt \
3 --model_name_or_path {Qwen3-8B_PATH} \
4 --device cpu \
5 --provider CPUExecutionProvider \
6 --use_model_builder \
7 --precision int4 \
8 --output_path {Your_Qwen3-8B_ONNX_Output_Path} \
9 --log_level 1
1import onnxruntime_genai as og
2import json
3
4# Set your model path
5model_folder = "Your_Qwen3-8B_ONNX_Path"
6
7# Initialize model and tokenizer
8model = og.Model(model_folder)
9tokenizer = og.Tokenizer(model)
10tokenizer_stream = tokenizer.create_stream()
11
12# Configuration for thinking mode
13search_options = {
14 'temperature': 0.6,
15 'top_p': 0.95,
16 'top_k': 20,
17 'max_length': 32768,
18 'repetition_penalty': 1
19}
20chat_template = "<|im_start|>user\n/think {input}<|im_end|><|im_start|>assistant\n"
21text = 'What is the derivative of x^2?'
22
23# Alternative configuration for non-thinking mode
24# search_options = {
25# 'temperature': 0.7,
26# 'top_p': 0.8,
27# 'top_k': 20,
28# 'max_length': 4096,
29# 'repetition_penalty': 1
30# }
31# chat_template = "<|im_start|>user\n/no_think {input}<|im_end|><|im_start|>assistant\n"
32# text = 'Can you introduce yourself?'
33
34# Prepare the prompt and generate response
35prompt = chat_template.format(input=text)
36input_tokens = tokenizer.encode(prompt)
37
38params = og.GeneratorParams(model)
39params.set_search_options(**search_options)
40generator = og.Generator(model, params)
41
42generator.append_tokens(input_tokens)
43
44# Generate and stream the response
45while not generator.is_done():
46 generator.generate_next_token()
47 new_token = generator.get_next_tokens()[0]
48 print(tokenizer_stream.decode(new_token), end='', flush=True)