Repository files navigation

olive text

PyPI releaseDocumentation

AI Model Optimization Toolkit for the ONNX Runtime

Given a model and targeted hardware, Olive (abbreviation of Onnx LIVE) composes the best suitable optimization techniques to output the most efficient ONNX model(s) for inferencing on the cloud or edge, while taking a set of constraints such as accuracy and latency into consideration.

✅ Benefits of using Olive

  • Reduce frustration of manual trial-and-error model optimization experimentation. Define your target and precision and let Olive automatically produce the best model for you.
  • 40+ built-in model optimization components covering industry-leading techniques across model compression, optimization, finetuning, and compilation.
  • Easy-to-use CLI for common model optimization tasks.
  • Workflows to orchestrate model transformations and optimizations steps.
  • Support for compiling LoRA adapters for MultiLoRA serving.
  • Seamless integration with Hugging Face and Azure AI.
  • Built-in caching mechanism to improve productivity.

📰 News Highlights

Here are some recent videos, blog articles and labs that highlight Olive:

For a full list of news and blogs, read the news archive.

🚀 Getting Started

Notebooks available!

The following notebooks are available that demonstrate key optimization workflows with Olive and include the application code to inference the optimized models on the ONNX Runtime.

TitleTaskDescriptionTime RequiredNotebook Links
QuickstartText GenerationLearn how to quantize & optimize an SLM for the ONNX Runtime using a single Olive command.5minsDownload / Open in Colab
Optimizing popular SLMsText GenerationChoose from a curated list of over 20 popular SLMs to quantize & optimize for the ONNX runtime.5minsDownload / Open in Colab
How to finetune models for on-device inferenceText GenerationLearn how to Quantize (using AWQ method), fine-tune, and optimize an SLM for on-device inference.15minsDownload / Open in Colab

✨ Quickstart

If you prefer using the command line directly instead of Jupyter notebooks, we've outlined the quickstart commands here.

1. Install Olive CLI

We recommend installing Olive in a virtual environment or a conda environment.

pip install olive-ai[ort-genai,auto-opt]
pip install transformers==4.44.2

Note

Olive has optional dependencies that can be installed to enable additional features. Please refer to Olive package config for the list of extras and their dependencies.

2. Automatic Optimizer

In this quickstart you'll be optimizing HuggingFaceTB/SmolLM2-135M-Instruct, which has many model files in the Hugging Face repo for different precisions that are not required by Olive. To minimize the download, cache the original Hugging Face model files (safetensors and configuration) in the main folder of the Hugging Face repo using:

huggingface-cli download HuggingFaceTB/SmolLM2-135M-Instruct *.json *.safetensors *.txt

Next, run the automatic optimization:

olive auto-opt \
--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct \
--output_path models/smolm2 \
--device cpu \
--provider CPUExecutionProvider \
--use_ort_genai \
--precision int4 \
--log_level 1

Tip

PowerShell Users Line continuation between Bash and PowerShell are not interchangable. If you are using PowerShell, then you can copy-and-paste the following command that uses compatible line continuation.
olive auto-opt `--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct `--output_path models/smolm2 `--device cpu `--provider CPUExecutionProvider `--use_ort_genai `--precision int4 `--log_level 1

The automatic optimizer will:

  1. Acquire the model from the local cache (note: if you skipped the model download step then the entire contents of the Hugging Face model repo will be downloaded).
  2. Capture the ONNX Graph and store the weights in an ONNX data file.
  3. Optimize the ONNX Graph.
  4. Quantize the model to int4 using RTN method.

Olive can automatically optimize popular model architectures like Llama, Phi, Qwen, Gemma, etc out-of-the-box - see detailed list here. Also, you can optimize other model architectures by providing details on the input/outputs of the model (io_config).

3. Inference on the ONNX Runtime

The ONNX Runtime (ORT) is a fast and light-weight cross-platform inference engine with bindings for popular programming language such as Python, C/C++, C#, Java, JavaScript, etc. ORT enables you to infuse AI models into your applications so that inference is handled on-device.

The following code creates a simple console-based chat interface that inferences your optimized model - select Python and/or C# to expand the code:

PythonCreate a Python file called app.py and copy and paste the following code:

# app.pyimportonnxruntime_genaiasogmodel_folder="models/smolm2/model"# Load the base model and tokenizermodel=og.Model(model_folder)
tokenizer=og.Tokenizer(model)
tokenizer_stream=tokenizer.create_stream()
# Set the max length to something sensible by default,# since otherwise it will be set to the entire context lengthsearch_options= {}
search_options['max_length'] =200search_options['past_present_share_buffer'] =Falsechat_template="<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n"text=input("Input: ")
# Keep asking for input phraseswhiletext!="exit":
ifnottext:
print("Error, input cannot be empty")
exit# generate prompt (prompt template + input)prompt=f'{chat_template.format(input=text)}'# encode the prompt using the tokenizerinput_tokens=tokenizer.encode(prompt)
params=og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids=input_tokensgenerator=og.Generator(model, params)
print("Output: ", end='', flush=True)
# stream the outputtry:
whilenotgenerator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token=generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
exceptKeyboardInterrupt:
print(" --control+c pressed, aborting generation--")
print()
text=input("Input: ")

To run the code, execute python app.py. You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

C#

Create a new C# Console app and install the Microsoft.ML.OnnxRuntimeGenAI Nuget package into your project:

mkdir ortapp
cd ortapp
dotnet new console
dotnet add package Microsoft.ML.OnnxRuntimeGenAI --version 0.5.2

Next, copy-and-paste the following code into your Program.cs file and update modelPath variable to be the absolute path of where you stored your optimized model.

// Program.csusingMicrosoft.ML.OnnxRuntimeGenAI;internalclassProgram{privatestaticvoidMain(string[]args){stringmodelPath@"models/smolm2/model";Console.Write("Loading model from "+modelPath+"...");usingModelmodel=new(modelPath);Console.Write("Done\n");usingTokenizertokenizer=new(model);usingTokenizerStreamtokenizerStream=tokenizer.CreateStream();while(true){Console.Write("User:");stringprompt="<|im_start|>user\n"+Console.ReadLine()+"<|im_end|>\n<|im_start|>assistant\n";varsequences=tokenizer.Encode(prompt);usingGeneratorParamsgParams=newGeneratorParams(model);gParams.SetSearchOption("max_length",200);gParams.SetInputSequences(sequences);gParams.SetSearchOption("past_present_share_buffer",false);Console.Out.Write("\nAI:");usingGeneratorgenerator=new(model,gParams);while(!generator.IsDone()){generator.ComputeLogits();generator.GenerateNextToken();vartoken=generator.GetSequence(0)[^1];Console.Out.Write(tokenizerStream.Decode(token));Console.Out.Flush();}Console.WriteLine();}}}

Run the application:

dotnet run

You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

🎓 Learn more

🤝 Contributions and Feedback

⚖️ License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

Pipeline Status

Build StatusBuild StatusBuild Status

About

Olive: Simplify ML Model Finetuning, Conversion, Quantization, and Optimization for CPUs, GPUs and NPUs.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

olive text

PyPI releaseDocumentation

AI Model Optimization Toolkit for the ONNX Runtime

Given a model and targeted hardware, Olive (abbreviation of Onnx LIVE) composes the best suitable optimization techniques to output the most efficient ONNX model(s) for inferencing on the cloud or edge, while taking a set of constraints such as accuracy and latency into consideration.

✅ Benefits of using Olive

  • Reduce frustration of manual trial-and-error model optimization experimentation. Define your target and precision and let Olive automatically produce the best model for you.
  • 40+ built-in model optimization components covering industry-leading techniques across model compression, optimization, finetuning, and compilation.
  • Easy-to-use CLI for common model optimization tasks.
  • Workflows to orchestrate model transformations and optimizations steps.
  • Support for compiling LoRA adapters for MultiLoRA serving.
  • Seamless integration with Hugging Face and Azure AI.
  • Built-in caching mechanism to improve productivity.

📰 News Highlights

Here are some recent videos, blog articles and labs that highlight Olive:

For a full list of news and blogs, read the news archive.

🚀 Getting Started

Notebooks available!

The following notebooks are available that demonstrate key optimization workflows with Olive and include the application code to inference the optimized models on the ONNX Runtime.

TitleTaskDescriptionTime RequiredNotebook Links
QuickstartText GenerationLearn how to quantize & optimize an SLM for the ONNX Runtime using a single Olive command.5minsDownload / Open in Colab
Optimizing popular SLMsText GenerationChoose from a curated list of over 20 popular SLMs to quantize & optimize for the ONNX runtime.5minsDownload / Open in Colab
How to finetune models for on-device inferenceText GenerationLearn how to Quantize (using AWQ method), fine-tune, and optimize an SLM for on-device inference.15minsDownload / Open in Colab

✨ Quickstart

If you prefer using the command line directly instead of Jupyter notebooks, we've outlined the quickstart commands here.

1. Install Olive CLI

We recommend installing Olive in a virtual environment or a conda environment.

pip install olive-ai[ort-genai,auto-opt]
pip install transformers==4.44.2

Note

Olive has optional dependencies that can be installed to enable additional features. Please refer to Olive package config for the list of extras and their dependencies.

2. Automatic Optimizer

In this quickstart you'll be optimizing HuggingFaceTB/SmolLM2-135M-Instruct, which has many model files in the Hugging Face repo for different precisions that are not required by Olive. To minimize the download, cache the original Hugging Face model files (safetensors and configuration) in the main folder of the Hugging Face repo using:

huggingface-cli download HuggingFaceTB/SmolLM2-135M-Instruct *.json *.safetensors *.txt

Next, run the automatic optimization:

olive auto-opt \
--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct \
--output_path models/smolm2 \
--device cpu \
--provider CPUExecutionProvider \
--use_ort_genai \
--precision int4 \
--log_level 1

Tip

PowerShell Users Line continuation between Bash and PowerShell are not interchangable. If you are using PowerShell, then you can copy-and-paste the following command that uses compatible line continuation.
olive auto-opt `--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct `--output_path models/smolm2 `--device cpu `--provider CPUExecutionProvider `--use_ort_genai `--precision int4 `--log_level 1

The automatic optimizer will:

  1. Acquire the model from the local cache (note: if you skipped the model download step then the entire contents of the Hugging Face model repo will be downloaded).
  2. Capture the ONNX Graph and store the weights in an ONNX data file.
  3. Optimize the ONNX Graph.
  4. Quantize the model to int4 using RTN method.

Olive can automatically optimize popular model architectures like Llama, Phi, Qwen, Gemma, etc out-of-the-box - see detailed list here. Also, you can optimize other model architectures by providing details on the input/outputs of the model (io_config).

3. Inference on the ONNX Runtime

The ONNX Runtime (ORT) is a fast and light-weight cross-platform inference engine with bindings for popular programming language such as Python, C/C++, C#, Java, JavaScript, etc. ORT enables you to infuse AI models into your applications so that inference is handled on-device.

The following code creates a simple console-based chat interface that inferences your optimized model - select Python and/or C# to expand the code:

PythonCreate a Python file called app.py and copy and paste the following code:

# app.pyimportonnxruntime_genaiasogmodel_folder="models/smolm2/model"# Load the base model and tokenizermodel=og.Model(model_folder)
tokenizer=og.Tokenizer(model)
tokenizer_stream=tokenizer.create_stream()
# Set the max length to something sensible by default,# since otherwise it will be set to the entire context lengthsearch_options= {}
search_options['max_length'] =200search_options['past_present_share_buffer'] =Falsechat_template="<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n"text=input("Input: ")
# Keep asking for input phraseswhiletext!="exit":
ifnottext:
print("Error, input cannot be empty")
exit# generate prompt (prompt template + input)prompt=f'{chat_template.format(input=text)}'# encode the prompt using the tokenizerinput_tokens=tokenizer.encode(prompt)
params=og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids=input_tokensgenerator=og.Generator(model, params)
print("Output: ", end='', flush=True)
# stream the outputtry:
whilenotgenerator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token=generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
exceptKeyboardInterrupt:
print(" --control+c pressed, aborting generation--")
print()
text=input("Input: ")

To run the code, execute python app.py. You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

C#

Create a new C# Console app and install the Microsoft.ML.OnnxRuntimeGenAI Nuget package into your project:

mkdir ortapp
cd ortapp
dotnet new console
dotnet add package Microsoft.ML.OnnxRuntimeGenAI --version 0.5.2

Next, copy-and-paste the following code into your Program.cs file and update modelPath variable to be the absolute path of where you stored your optimized model.

// Program.csusingMicrosoft.ML.OnnxRuntimeGenAI;internalclassProgram{privatestaticvoidMain(string[]args){stringmodelPath@"models/smolm2/model";Console.Write("Loading model from "+modelPath+"...");usingModelmodel=new(modelPath);Console.Write("Done\n");usingTokenizertokenizer=new(model);usingTokenizerStreamtokenizerStream=tokenizer.CreateStream();while(true){Console.Write("User:");stringprompt="<|im_start|>user\n"+Console.ReadLine()+"<|im_end|>\n<|im_start|>assistant\n";varsequences=tokenizer.Encode(prompt);usingGeneratorParamsgParams=newGeneratorParams(model);gParams.SetSearchOption("max_length",200);gParams.SetInputSequences(sequences);gParams.SetSearchOption("past_present_share_buffer",false);Console.Out.Write("\nAI:");usingGeneratorgenerator=new(model,gParams);while(!generator.IsDone()){generator.ComputeLogits();generator.GenerateNextToken();vartoken=generator.GetSequence(0)[^1];Console.Out.Write(tokenizerStream.Decode(token));Console.Out.Flush();}Console.WriteLine();}}}

Run the application:

dotnet run

You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

🎓 Learn more

🤝 Contributions and Feedback

⚖️ License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

Pipeline Status

Build StatusBuild StatusBuild Status

About

Olive: Simplify ML Model Finetuning, Conversion, Quantization, and Optimization for CPUs, GPUs and NPUs.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

olive text

PyPI releaseDocumentation

AI Model Optimization Toolkit for the ONNX Runtime

Given a model and targeted hardware, Olive (abbreviation of Onnx LIVE) composes the best suitable optimization techniques to output the most efficient ONNX model(s) for inferencing on the cloud or edge, while taking a set of constraints such as accuracy and latency into consideration.

✅ Benefits of using Olive

  • Reduce frustration of manual trial-and-error model optimization experimentation. Define your target and precision and let Olive automatically produce the best model for you.
  • 40+ built-in model optimization components covering industry-leading techniques across model compression, optimization, finetuning, and compilation.
  • Easy-to-use CLI for common model optimization tasks.
  • Workflows to orchestrate model transformations and optimizations steps.
  • Support for compiling LoRA adapters for MultiLoRA serving.
  • Seamless integration with Hugging Face and Azure AI.
  • Built-in caching mechanism to improve productivity.

📰 News Highlights

Here are some recent videos, blog articles and labs that highlight Olive:

For a full list of news and blogs, read the news archive.

🚀 Getting Started

Notebooks available!

The following notebooks are available that demonstrate key optimization workflows with Olive and include the application code to inference the optimized models on the ONNX Runtime.

TitleTaskDescriptionTime RequiredNotebook Links
QuickstartText GenerationLearn how to quantize & optimize an SLM for the ONNX Runtime using a single Olive command.5minsDownload / Open in Colab
Optimizing popular SLMsText GenerationChoose from a curated list of over 20 popular SLMs to quantize & optimize for the ONNX runtime.5minsDownload / Open in Colab
How to finetune models for on-device inferenceText GenerationLearn how to Quantize (using AWQ method), fine-tune, and optimize an SLM for on-device inference.15minsDownload / Open in Colab

✨ Quickstart

If you prefer using the command line directly instead of Jupyter notebooks, we've outlined the quickstart commands here.

1. Install Olive CLI

We recommend installing Olive in a virtual environment or a conda environment.

pip install olive-ai[ort-genai,auto-opt]
pip install transformers==4.44.2

Note

Olive has optional dependencies that can be installed to enable additional features. Please refer to Olive package config for the list of extras and their dependencies.

2. Automatic Optimizer

In this quickstart you'll be optimizing HuggingFaceTB/SmolLM2-135M-Instruct, which has many model files in the Hugging Face repo for different precisions that are not required by Olive. To minimize the download, cache the original Hugging Face model files (safetensors and configuration) in the main folder of the Hugging Face repo using:

huggingface-cli download HuggingFaceTB/SmolLM2-135M-Instruct *.json *.safetensors *.txt

Next, run the automatic optimization:

olive auto-opt \
--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct \
--output_path models/smolm2 \
--device cpu \
--provider CPUExecutionProvider \
--use_ort_genai \
--precision int4 \
--log_level 1

Tip

PowerShell Users Line continuation between Bash and PowerShell are not interchangable. If you are using PowerShell, then you can copy-and-paste the following command that uses compatible line continuation.
olive auto-opt `--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct `--output_path models/smolm2 `--device cpu `--provider CPUExecutionProvider `--use_ort_genai `--precision int4 `--log_level 1

The automatic optimizer will:

  1. Acquire the model from the local cache (note: if you skipped the model download step then the entire contents of the Hugging Face model repo will be downloaded).
  2. Capture the ONNX Graph and store the weights in an ONNX data file.
  3. Optimize the ONNX Graph.
  4. Quantize the model to int4 using RTN method.

Olive can automatically optimize popular model architectures like Llama, Phi, Qwen, Gemma, etc out-of-the-box - see detailed list here. Also, you can optimize other model architectures by providing details on the input/outputs of the model (io_config).

3. Inference on the ONNX Runtime

The ONNX Runtime (ORT) is a fast and light-weight cross-platform inference engine with bindings for popular programming language such as Python, C/C++, C#, Java, JavaScript, etc. ORT enables you to infuse AI models into your applications so that inference is handled on-device.

The following code creates a simple console-based chat interface that inferences your optimized model - select Python and/or C# to expand the code:

PythonCreate a Python file called app.py and copy and paste the following code:

# app.pyimportonnxruntime_genaiasogmodel_folder="models/smolm2/model"# Load the base model and tokenizermodel=og.Model(model_folder)
tokenizer=og.Tokenizer(model)
tokenizer_stream=tokenizer.create_stream()
# Set the max length to something sensible by default,# since otherwise it will be set to the entire context lengthsearch_options= {}
search_options['max_length'] =200search_options['past_present_share_buffer'] =Falsechat_template="<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n"text=input("Input: ")
# Keep asking for input phraseswhiletext!="exit":
ifnottext:
print("Error, input cannot be empty")
exit# generate prompt (prompt template + input)prompt=f'{chat_template.format(input=text)}'# encode the prompt using the tokenizerinput_tokens=tokenizer.encode(prompt)
params=og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids=input_tokensgenerator=og.Generator(model, params)
print("Output: ", end='', flush=True)
# stream the outputtry:
whilenotgenerator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token=generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
exceptKeyboardInterrupt:
print(" --control+c pressed, aborting generation--")
print()
text=input("Input: ")

To run the code, execute python app.py. You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

C#

Create a new C# Console app and install the Microsoft.ML.OnnxRuntimeGenAI Nuget package into your project:

mkdir ortapp
cd ortapp
dotnet new console
dotnet add package Microsoft.ML.OnnxRuntimeGenAI --version 0.5.2

Next, copy-and-paste the following code into your Program.cs file and update modelPath variable to be the absolute path of where you stored your optimized model.

// Program.csusingMicrosoft.ML.OnnxRuntimeGenAI;internalclassProgram{privatestaticvoidMain(string[]args){stringmodelPath@"models/smolm2/model";Console.Write("Loading model from "+modelPath+"...");usingModelmodel=new(modelPath);Console.Write("Done\n");usingTokenizertokenizer=new(model);usingTokenizerStreamtokenizerStream=tokenizer.CreateStream();while(true){Console.Write("User:");stringprompt="<|im_start|>user\n"+Console.ReadLine()+"<|im_end|>\n<|im_start|>assistant\n";varsequences=tokenizer.Encode(prompt);usingGeneratorParamsgParams=newGeneratorParams(model);gParams.SetSearchOption("max_length",200);gParams.SetInputSequences(sequences);gParams.SetSearchOption("past_present_share_buffer",false);Console.Out.Write("\nAI:");usingGeneratorgenerator=new(model,gParams);while(!generator.IsDone()){generator.ComputeLogits();generator.GenerateNextToken();vartoken=generator.GetSequence(0)[^1];Console.Out.Write(tokenizerStream.Decode(token));Console.Out.Flush();}Console.WriteLine();}}}

Run the application:

dotnet run

You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

🎓 Learn more

🤝 Contributions and Feedback

⚖️ License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

Pipeline Status

Build StatusBuild StatusBuild Status

About

Olive: Simplify ML Model Finetuning, Conversion, Quantization, and Optimization for CPUs, GPUs and NPUs.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

olive text

PyPI releaseDocumentation

AI Model Optimization Toolkit for the ONNX Runtime

Given a model and targeted hardware, Olive (abbreviation of Onnx LIVE) composes the best suitable optimization techniques to output the most efficient ONNX model(s) for inferencing on the cloud or edge, while taking a set of constraints such as accuracy and latency into consideration.

✅ Benefits of using Olive

  • Reduce frustration of manual trial-and-error model optimization experimentation. Define your target and precision and let Olive automatically produce the best model for you.
  • 40+ built-in model optimization components covering industry-leading techniques across model compression, optimization, finetuning, and compilation.
  • Easy-to-use CLI for common model optimization tasks.
  • Workflows to orchestrate model transformations and optimizations steps.
  • Support for compiling LoRA adapters for MultiLoRA serving.
  • Seamless integration with Hugging Face and Azure AI.
  • Built-in caching mechanism to improve productivity.

📰 News Highlights

Here are some recent videos, blog articles and labs that highlight Olive:

For a full list of news and blogs, read the news archive.

🚀 Getting Started

Notebooks available!

The following notebooks are available that demonstrate key optimization workflows with Olive and include the application code to inference the optimized models on the ONNX Runtime.

TitleTaskDescriptionTime RequiredNotebook Links
QuickstartText GenerationLearn how to quantize & optimize an SLM for the ONNX Runtime using a single Olive command.5minsDownload / Open in Colab
Optimizing popular SLMsText GenerationChoose from a curated list of over 20 popular SLMs to quantize & optimize for the ONNX runtime.5minsDownload / Open in Colab
How to finetune models for on-device inferenceText GenerationLearn how to Quantize (using AWQ method), fine-tune, and optimize an SLM for on-device inference.15minsDownload / Open in Colab

✨ Quickstart

If you prefer using the command line directly instead of Jupyter notebooks, we've outlined the quickstart commands here.

1. Install Olive CLI

We recommend installing Olive in a virtual environment or a conda environment.

pip install olive-ai[ort-genai,auto-opt]
pip install transformers==4.44.2

Note

Olive has optional dependencies that can be installed to enable additional features. Please refer to Olive package config for the list of extras and their dependencies.

2. Automatic Optimizer

In this quickstart you'll be optimizing HuggingFaceTB/SmolLM2-135M-Instruct, which has many model files in the Hugging Face repo for different precisions that are not required by Olive. To minimize the download, cache the original Hugging Face model files (safetensors and configuration) in the main folder of the Hugging Face repo using:

huggingface-cli download HuggingFaceTB/SmolLM2-135M-Instruct *.json *.safetensors *.txt

Next, run the automatic optimization:

olive auto-opt \
--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct \
--output_path models/smolm2 \
--device cpu \
--provider CPUExecutionProvider \
--use_ort_genai \
--precision int4 \
--log_level 1

Tip

PowerShell Users Line continuation between Bash and PowerShell are not interchangable. If you are using PowerShell, then you can copy-and-paste the following command that uses compatible line continuation.
olive auto-opt `--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct `--output_path models/smolm2 `--device cpu `--provider CPUExecutionProvider `--use_ort_genai `--precision int4 `--log_level 1

The automatic optimizer will:

  1. Acquire the model from the local cache (note: if you skipped the model download step then the entire contents of the Hugging Face model repo will be downloaded).
  2. Capture the ONNX Graph and store the weights in an ONNX data file.
  3. Optimize the ONNX Graph.
  4. Quantize the model to int4 using RTN method.

Olive can automatically optimize popular model architectures like Llama, Phi, Qwen, Gemma, etc out-of-the-box - see detailed list here. Also, you can optimize other model architectures by providing details on the input/outputs of the model (io_config).

3. Inference on the ONNX Runtime

The ONNX Runtime (ORT) is a fast and light-weight cross-platform inference engine with bindings for popular programming language such as Python, C/C++, C#, Java, JavaScript, etc. ORT enables you to infuse AI models into your applications so that inference is handled on-device.

The following code creates a simple console-based chat interface that inferences your optimized model - select Python and/or C# to expand the code:

PythonCreate a Python file called app.py and copy and paste the following code:

# app.pyimportonnxruntime_genaiasogmodel_folder="models/smolm2/model"# Load the base model and tokenizermodel=og.Model(model_folder)
tokenizer=og.Tokenizer(model)
tokenizer_stream=tokenizer.create_stream()
# Set the max length to something sensible by default,# since otherwise it will be set to the entire context lengthsearch_options= {}
search_options['max_length'] =200search_options['past_present_share_buffer'] =Falsechat_template="<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n"text=input("Input: ")
# Keep asking for input phraseswhiletext!="exit":
ifnottext:
print("Error, input cannot be empty")
exit# generate prompt (prompt template + input)prompt=f'{chat_template.format(input=text)}'# encode the prompt using the tokenizerinput_tokens=tokenizer.encode(prompt)
params=og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids=input_tokensgenerator=og.Generator(model, params)
print("Output: ", end='', flush=True)
# stream the outputtry:
whilenotgenerator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token=generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
exceptKeyboardInterrupt:
print(" --control+c pressed, aborting generation--")
print()
text=input("Input: ")

To run the code, execute python app.py. You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

C#

Create a new C# Console app and install the Microsoft.ML.OnnxRuntimeGenAI Nuget package into your project:

mkdir ortapp
cd ortapp
dotnet new console
dotnet add package Microsoft.ML.OnnxRuntimeGenAI --version 0.5.2

Next, copy-and-paste the following code into your Program.cs file and update modelPath variable to be the absolute path of where you stored your optimized model.

// Program.csusingMicrosoft.ML.OnnxRuntimeGenAI;internalclassProgram{privatestaticvoidMain(string[]args){stringmodelPath@"models/smolm2/model";Console.Write("Loading model from "+modelPath+"...");usingModelmodel=new(modelPath);Console.Write("Done\n");usingTokenizertokenizer=new(model);usingTokenizerStreamtokenizerStream=tokenizer.CreateStream();while(true){Console.Write("User:");stringprompt="<|im_start|>user\n"+Console.ReadLine()+"<|im_end|>\n<|im_start|>assistant\n";varsequences=tokenizer.Encode(prompt);usingGeneratorParamsgParams=newGeneratorParams(model);gParams.SetSearchOption("max_length",200);gParams.SetInputSequences(sequences);gParams.SetSearchOption("past_present_share_buffer",false);Console.Out.Write("\nAI:");usingGeneratorgenerator=new(model,gParams);while(!generator.IsDone()){generator.ComputeLogits();generator.GenerateNextToken();vartoken=generator.GetSequence(0)[^1];Console.Out.Write(tokenizerStream.Decode(token));Console.Out.Flush();}Console.WriteLine();}}}

Run the application:

dotnet run

You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

🎓 Learn more

🤝 Contributions and Feedback

⚖️ License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

Pipeline Status

Build StatusBuild StatusBuild Status

About

Olive: Simplify ML Model Finetuning, Conversion, Quantization, and Optimization for CPUs, GPUs and NPUs.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

olive text

PyPI releaseDocumentation

AI Model Optimization Toolkit for the ONNX Runtime

Given a model and targeted hardware, Olive (abbreviation of Onnx LIVE) composes the best suitable optimization techniques to output the most efficient ONNX model(s) for inferencing on the cloud or edge, while taking a set of constraints such as accuracy and latency into consideration.

✅ Benefits of using Olive

  • Reduce frustration of manual trial-and-error model optimization experimentation. Define your target and precision and let Olive automatically produce the best model for you.
  • 40+ built-in model optimization components covering industry-leading techniques across model compression, optimization, finetuning, and compilation.
  • Easy-to-use CLI for common model optimization tasks.
  • Workflows to orchestrate model transformations and optimizations steps.
  • Support for compiling LoRA adapters for MultiLoRA serving.
  • Seamless integration with Hugging Face and Azure AI.
  • Built-in caching mechanism to improve productivity.

📰 News Highlights

Here are some recent videos, blog articles and labs that highlight Olive:

For a full list of news and blogs, read the news archive.

🚀 Getting Started

Notebooks available!

The following notebooks are available that demonstrate key optimization workflows with Olive and include the application code to inference the optimized models on the ONNX Runtime.

TitleTaskDescriptionTime RequiredNotebook Links
QuickstartText GenerationLearn how to quantize & optimize an SLM for the ONNX Runtime using a single Olive command.5minsDownload / Open in Colab
Optimizing popular SLMsText GenerationChoose from a curated list of over 20 popular SLMs to quantize & optimize for the ONNX runtime.5minsDownload / Open in Colab
How to finetune models for on-device inferenceText GenerationLearn how to Quantize (using AWQ method), fine-tune, and optimize an SLM for on-device inference.15minsDownload / Open in Colab

✨ Quickstart

If you prefer using the command line directly instead of Jupyter notebooks, we've outlined the quickstart commands here.

1. Install Olive CLI

We recommend installing Olive in a virtual environment or a conda environment.

pip install olive-ai[ort-genai,auto-opt]
pip install transformers==4.44.2

Note

Olive has optional dependencies that can be installed to enable additional features. Please refer to Olive package config for the list of extras and their dependencies.

2. Automatic Optimizer

In this quickstart you'll be optimizing HuggingFaceTB/SmolLM2-135M-Instruct, which has many model files in the Hugging Face repo for different precisions that are not required by Olive. To minimize the download, cache the original Hugging Face model files (safetensors and configuration) in the main folder of the Hugging Face repo using:

huggingface-cli download HuggingFaceTB/SmolLM2-135M-Instruct *.json *.safetensors *.txt

Next, run the automatic optimization:

olive auto-opt \
--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct \
--output_path models/smolm2 \
--device cpu \
--provider CPUExecutionProvider \
--use_ort_genai \
--precision int4 \
--log_level 1

Tip

PowerShell Users Line continuation between Bash and PowerShell are not interchangable. If you are using PowerShell, then you can copy-and-paste the following command that uses compatible line continuation.
olive auto-opt `--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct `--output_path models/smolm2 `--device cpu `--provider CPUExecutionProvider `--use_ort_genai `--precision int4 `--log_level 1

The automatic optimizer will:

  1. Acquire the model from the local cache (note: if you skipped the model download step then the entire contents of the Hugging Face model repo will be downloaded).
  2. Capture the ONNX Graph and store the weights in an ONNX data file.
  3. Optimize the ONNX Graph.
  4. Quantize the model to int4 using RTN method.

Olive can automatically optimize popular model architectures like Llama, Phi, Qwen, Gemma, etc out-of-the-box - see detailed list here. Also, you can optimize other model architectures by providing details on the input/outputs of the model (io_config).

3. Inference on the ONNX Runtime

The ONNX Runtime (ORT) is a fast and light-weight cross-platform inference engine with bindings for popular programming language such as Python, C/C++, C#, Java, JavaScript, etc. ORT enables you to infuse AI models into your applications so that inference is handled on-device.

The following code creates a simple console-based chat interface that inferences your optimized model - select Python and/or C# to expand the code:

PythonCreate a Python file called app.py and copy and paste the following code:

# app.pyimportonnxruntime_genaiasogmodel_folder="models/smolm2/model"# Load the base model and tokenizermodel=og.Model(model_folder)
tokenizer=og.Tokenizer(model)
tokenizer_stream=tokenizer.create_stream()
# Set the max length to something sensible by default,# since otherwise it will be set to the entire context lengthsearch_options= {}
search_options['max_length'] =200search_options['past_present_share_buffer'] =Falsechat_template="<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n"text=input("Input: ")
# Keep asking for input phraseswhiletext!="exit":
ifnottext:
print("Error, input cannot be empty")
exit# generate prompt (prompt template + input)prompt=f'{chat_template.format(input=text)}'# encode the prompt using the tokenizerinput_tokens=tokenizer.encode(prompt)
params=og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids=input_tokensgenerator=og.Generator(model, params)
print("Output: ", end='', flush=True)
# stream the outputtry:
whilenotgenerator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token=generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
exceptKeyboardInterrupt:
print(" --control+c pressed, aborting generation--")
print()
text=input("Input: ")

To run the code, execute python app.py. You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

C#

Create a new C# Console app and install the Microsoft.ML.OnnxRuntimeGenAI Nuget package into your project:

mkdir ortapp
cd ortapp
dotnet new console
dotnet add package Microsoft.ML.OnnxRuntimeGenAI --version 0.5.2

Next, copy-and-paste the following code into your Program.cs file and update modelPath variable to be the absolute path of where you stored your optimized model.

// Program.csusingMicrosoft.ML.OnnxRuntimeGenAI;internalclassProgram{privatestaticvoidMain(string[]args){stringmodelPath@"models/smolm2/model";Console.Write("Loading model from "+modelPath+"...");usingModelmodel=new(modelPath);Console.Write("Done\n");usingTokenizertokenizer=new(model);usingTokenizerStreamtokenizerStream=tokenizer.CreateStream();while(true){Console.Write("User:");stringprompt="<|im_start|>user\n"+Console.ReadLine()+"<|im_end|>\n<|im_start|>assistant\n";varsequences=tokenizer.Encode(prompt);usingGeneratorParamsgParams=newGeneratorParams(model);gParams.SetSearchOption("max_length",200);gParams.SetInputSequences(sequences);gParams.SetSearchOption("past_present_share_buffer",false);Console.Out.Write("\nAI:");usingGeneratorgenerator=new(model,gParams);while(!generator.IsDone()){generator.ComputeLogits();generator.GenerateNextToken();vartoken=generator.GetSequence(0)[^1];Console.Out.Write(tokenizerStream.Decode(token));Console.Out.Flush();}Console.WriteLine();}}}

Run the application:

dotnet run

You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

🎓 Learn more

🤝 Contributions and Feedback

⚖️ License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

Pipeline Status

Build StatusBuild StatusBuild Status

About

Olive: Simplify ML Model Finetuning, Conversion, Quantization, and Optimization for CPUs, GPUs and NPUs.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

olive text

PyPI releaseDocumentation

AI Model Optimization Toolkit for the ONNX Runtime

Given a model and targeted hardware, Olive (abbreviation of Onnx LIVE) composes the best suitable optimization techniques to output the most efficient ONNX model(s) for inferencing on the cloud or edge, while taking a set of constraints such as accuracy and latency into consideration.

✅ Benefits of using Olive

  • Reduce frustration of manual trial-and-error model optimization experimentation. Define your target and precision and let Olive automatically produce the best model for you.
  • 40+ built-in model optimization components covering industry-leading techniques across model compression, optimization, finetuning, and compilation.
  • Easy-to-use CLI for common model optimization tasks.
  • Workflows to orchestrate model transformations and optimizations steps.
  • Support for compiling LoRA adapters for MultiLoRA serving.
  • Seamless integration with Hugging Face and Azure AI.
  • Built-in caching mechanism to improve productivity.

📰 News Highlights

Here are some recent videos, blog articles and labs that highlight Olive:

For a full list of news and blogs, read the news archive.

🚀 Getting Started

Notebooks available!

The following notebooks are available that demonstrate key optimization workflows with Olive and include the application code to inference the optimized models on the ONNX Runtime.

TitleTaskDescriptionTime RequiredNotebook Links
QuickstartText GenerationLearn how to quantize & optimize an SLM for the ONNX Runtime using a single Olive command.5minsDownload / Open in Colab
Optimizing popular SLMsText GenerationChoose from a curated list of over 20 popular SLMs to quantize & optimize for the ONNX runtime.5minsDownload / Open in Colab
How to finetune models for on-device inferenceText GenerationLearn how to Quantize (using AWQ method), fine-tune, and optimize an SLM for on-device inference.15minsDownload / Open in Colab

✨ Quickstart

If you prefer using the command line directly instead of Jupyter notebooks, we've outlined the quickstart commands here.

1. Install Olive CLI

We recommend installing Olive in a virtual environment or a conda environment.

pip install olive-ai[ort-genai,auto-opt]
pip install transformers==4.44.2

Note

Olive has optional dependencies that can be installed to enable additional features. Please refer to Olive package config for the list of extras and their dependencies.

2. Automatic Optimizer

In this quickstart you'll be optimizing HuggingFaceTB/SmolLM2-135M-Instruct, which has many model files in the Hugging Face repo for different precisions that are not required by Olive. To minimize the download, cache the original Hugging Face model files (safetensors and configuration) in the main folder of the Hugging Face repo using:

huggingface-cli download HuggingFaceTB/SmolLM2-135M-Instruct *.json *.safetensors *.txt

Next, run the automatic optimization:

olive auto-opt \
--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct \
--output_path models/smolm2 \
--device cpu \
--provider CPUExecutionProvider \
--use_ort_genai \
--precision int4 \
--log_level 1

Tip

PowerShell Users Line continuation between Bash and PowerShell are not interchangable. If you are using PowerShell, then you can copy-and-paste the following command that uses compatible line continuation.
olive auto-opt `--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct `--output_path models/smolm2 `--device cpu `--provider CPUExecutionProvider `--use_ort_genai `--precision int4 `--log_level 1

The automatic optimizer will:

  1. Acquire the model from the local cache (note: if you skipped the model download step then the entire contents of the Hugging Face model repo will be downloaded).
  2. Capture the ONNX Graph and store the weights in an ONNX data file.
  3. Optimize the ONNX Graph.
  4. Quantize the model to int4 using RTN method.

Olive can automatically optimize popular model architectures like Llama, Phi, Qwen, Gemma, etc out-of-the-box - see detailed list here. Also, you can optimize other model architectures by providing details on the input/outputs of the model (io_config).

3. Inference on the ONNX Runtime

The ONNX Runtime (ORT) is a fast and light-weight cross-platform inference engine with bindings for popular programming language such as Python, C/C++, C#, Java, JavaScript, etc. ORT enables you to infuse AI models into your applications so that inference is handled on-device.

The following code creates a simple console-based chat interface that inferences your optimized model - select Python and/or C# to expand the code:

PythonCreate a Python file called app.py and copy and paste the following code:

# app.pyimportonnxruntime_genaiasogmodel_folder="models/smolm2/model"# Load the base model and tokenizermodel=og.Model(model_folder)
tokenizer=og.Tokenizer(model)
tokenizer_stream=tokenizer.create_stream()
# Set the max length to something sensible by default,# since otherwise it will be set to the entire context lengthsearch_options= {}
search_options['max_length'] =200search_options['past_present_share_buffer'] =Falsechat_template="<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n"text=input("Input: ")
# Keep asking for input phraseswhiletext!="exit":
ifnottext:
print("Error, input cannot be empty")
exit# generate prompt (prompt template + input)prompt=f'{chat_template.format(input=text)}'# encode the prompt using the tokenizerinput_tokens=tokenizer.encode(prompt)
params=og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids=input_tokensgenerator=og.Generator(model, params)
print("Output: ", end='', flush=True)
# stream the outputtry:
whilenotgenerator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token=generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
exceptKeyboardInterrupt:
print(" --control+c pressed, aborting generation--")
print()
text=input("Input: ")

To run the code, execute python app.py. You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

C#

Create a new C# Console app and install the Microsoft.ML.OnnxRuntimeGenAI Nuget package into your project:

mkdir ortapp
cd ortapp
dotnet new console
dotnet add package Microsoft.ML.OnnxRuntimeGenAI --version 0.5.2

Next, copy-and-paste the following code into your Program.cs file and update modelPath variable to be the absolute path of where you stored your optimized model.

// Program.csusingMicrosoft.ML.OnnxRuntimeGenAI;internalclassProgram{privatestaticvoidMain(string[]args){stringmodelPath@"models/smolm2/model";Console.Write("Loading model from "+modelPath+"...");usingModelmodel=new(modelPath);Console.Write("Done\n");usingTokenizertokenizer=new(model);usingTokenizerStreamtokenizerStream=tokenizer.CreateStream();while(true){Console.Write("User:");stringprompt="<|im_start|>user\n"+Console.ReadLine()+"<|im_end|>\n<|im_start|>assistant\n";varsequences=tokenizer.Encode(prompt);usingGeneratorParamsgParams=newGeneratorParams(model);gParams.SetSearchOption("max_length",200);gParams.SetInputSequences(sequences);gParams.SetSearchOption("past_present_share_buffer",false);Console.Out.Write("\nAI:");usingGeneratorgenerator=new(model,gParams);while(!generator.IsDone()){generator.ComputeLogits();generator.GenerateNextToken();vartoken=generator.GetSequence(0)[^1];Console.Out.Write(tokenizerStream.Decode(token));Console.Out.Flush();}Console.WriteLine();}}}

Run the application:

dotnet run

You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

🎓 Learn more

🤝 Contributions and Feedback

⚖️ License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

Pipeline Status

Build StatusBuild StatusBuild Status

About

Olive: Simplify ML Model Finetuning, Conversion, Quantization, and Optimization for CPUs, GPUs and NPUs.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

olive text

PyPI releaseDocumentation

AI Model Optimization Toolkit for the ONNX Runtime

Given a model and targeted hardware, Olive (abbreviation of Onnx LIVE) composes the best suitable optimization techniques to output the most efficient ONNX model(s) for inferencing on the cloud or edge, while taking a set of constraints such as accuracy and latency into consideration.

✅ Benefits of using Olive

  • Reduce frustration of manual trial-and-error model optimization experimentation. Define your target and precision and let Olive automatically produce the best model for you.
  • 40+ built-in model optimization components covering industry-leading techniques across model compression, optimization, finetuning, and compilation.
  • Easy-to-use CLI for common model optimization tasks.
  • Workflows to orchestrate model transformations and optimizations steps.
  • Support for compiling LoRA adapters for MultiLoRA serving.
  • Seamless integration with Hugging Face and Azure AI.
  • Built-in caching mechanism to improve productivity.

📰 News Highlights

Here are some recent videos, blog articles and labs that highlight Olive:

For a full list of news and blogs, read the news archive.

🚀 Getting Started

Notebooks available!

The following notebooks are available that demonstrate key optimization workflows with Olive and include the application code to inference the optimized models on the ONNX Runtime.

TitleTaskDescriptionTime RequiredNotebook Links
QuickstartText GenerationLearn how to quantize & optimize an SLM for the ONNX Runtime using a single Olive command.5minsDownload / Open in Colab
Optimizing popular SLMsText GenerationChoose from a curated list of over 20 popular SLMs to quantize & optimize for the ONNX runtime.5minsDownload / Open in Colab
How to finetune models for on-device inferenceText GenerationLearn how to Quantize (using AWQ method), fine-tune, and optimize an SLM for on-device inference.15minsDownload / Open in Colab

✨ Quickstart

If you prefer using the command line directly instead of Jupyter notebooks, we've outlined the quickstart commands here.

1. Install Olive CLI

We recommend installing Olive in a virtual environment or a conda environment.

pip install olive-ai[ort-genai,auto-opt]
pip install transformers==4.44.2

Note

Olive has optional dependencies that can be installed to enable additional features. Please refer to Olive package config for the list of extras and their dependencies.

2. Automatic Optimizer

In this quickstart you'll be optimizing HuggingFaceTB/SmolLM2-135M-Instruct, which has many model files in the Hugging Face repo for different precisions that are not required by Olive. To minimize the download, cache the original Hugging Face model files (safetensors and configuration) in the main folder of the Hugging Face repo using:

huggingface-cli download HuggingFaceTB/SmolLM2-135M-Instruct *.json *.safetensors *.txt

Next, run the automatic optimization:

olive auto-opt \
--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct \
--output_path models/smolm2 \
--device cpu \
--provider CPUExecutionProvider \
--use_ort_genai \
--precision int4 \
--log_level 1

Tip

PowerShell Users Line continuation between Bash and PowerShell are not interchangable. If you are using PowerShell, then you can copy-and-paste the following command that uses compatible line continuation.
olive auto-opt `--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct `--output_path models/smolm2 `--device cpu `--provider CPUExecutionProvider `--use_ort_genai `--precision int4 `--log_level 1

The automatic optimizer will:

  1. Acquire the model from the local cache (note: if you skipped the model download step then the entire contents of the Hugging Face model repo will be downloaded).
  2. Capture the ONNX Graph and store the weights in an ONNX data file.
  3. Optimize the ONNX Graph.
  4. Quantize the model to int4 using RTN method.

Olive can automatically optimize popular model architectures like Llama, Phi, Qwen, Gemma, etc out-of-the-box - see detailed list here. Also, you can optimize other model architectures by providing details on the input/outputs of the model (io_config).

3. Inference on the ONNX Runtime

The ONNX Runtime (ORT) is a fast and light-weight cross-platform inference engine with bindings for popular programming language such as Python, C/C++, C#, Java, JavaScript, etc. ORT enables you to infuse AI models into your applications so that inference is handled on-device.

The following code creates a simple console-based chat interface that inferences your optimized model - select Python and/or C# to expand the code:

PythonCreate a Python file called app.py and copy and paste the following code:

# app.pyimportonnxruntime_genaiasogmodel_folder="models/smolm2/model"# Load the base model and tokenizermodel=og.Model(model_folder)
tokenizer=og.Tokenizer(model)
tokenizer_stream=tokenizer.create_stream()
# Set the max length to something sensible by default,# since otherwise it will be set to the entire context lengthsearch_options= {}
search_options['max_length'] =200search_options['past_present_share_buffer'] =Falsechat_template="<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n"text=input("Input: ")
# Keep asking for input phraseswhiletext!="exit":
ifnottext:
print("Error, input cannot be empty")
exit# generate prompt (prompt template + input)prompt=f'{chat_template.format(input=text)}'# encode the prompt using the tokenizerinput_tokens=tokenizer.encode(prompt)
params=og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids=input_tokensgenerator=og.Generator(model, params)
print("Output: ", end='', flush=True)
# stream the outputtry:
whilenotgenerator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token=generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
exceptKeyboardInterrupt:
print(" --control+c pressed, aborting generation--")
print()
text=input("Input: ")

To run the code, execute python app.py. You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

C#

Create a new C# Console app and install the Microsoft.ML.OnnxRuntimeGenAI Nuget package into your project:

mkdir ortapp
cd ortapp
dotnet new console
dotnet add package Microsoft.ML.OnnxRuntimeGenAI --version 0.5.2

Next, copy-and-paste the following code into your Program.cs file and update modelPath variable to be the absolute path of where you stored your optimized model.

// Program.csusingMicrosoft.ML.OnnxRuntimeGenAI;internalclassProgram{privatestaticvoidMain(string[]args){stringmodelPath@"models/smolm2/model";Console.Write("Loading model from "+modelPath+"...");usingModelmodel=new(modelPath);Console.Write("Done\n");usingTokenizertokenizer=new(model);usingTokenizerStreamtokenizerStream=tokenizer.CreateStream();while(true){Console.Write("User:");stringprompt="<|im_start|>user\n"+Console.ReadLine()+"<|im_end|>\n<|im_start|>assistant\n";varsequences=tokenizer.Encode(prompt);usingGeneratorParamsgParams=newGeneratorParams(model);gParams.SetSearchOption("max_length",200);gParams.SetInputSequences(sequences);gParams.SetSearchOption("past_present_share_buffer",false);Console.Out.Write("\nAI:");usingGeneratorgenerator=new(model,gParams);while(!generator.IsDone()){generator.ComputeLogits();generator.GenerateNextToken();vartoken=generator.GetSequence(0)[^1];Console.Out.Write(tokenizerStream.Decode(token));Console.Out.Flush();}Console.WriteLine();}}}

Run the application:

dotnet run

You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

🎓 Learn more

🤝 Contributions and Feedback

⚖️ License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

Pipeline Status

Build StatusBuild StatusBuild Status

About

Olive: Simplify ML Model Finetuning, Conversion, Quantization, and Optimization for CPUs, GPUs and NPUs.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

olive text

PyPI releaseDocumentation

AI Model Optimization Toolkit for the ONNX Runtime

Given a model and targeted hardware, Olive (abbreviation of Onnx LIVE) composes the best suitable optimization techniques to output the most efficient ONNX model(s) for inferencing on the cloud or edge, while taking a set of constraints such as accuracy and latency into consideration.

✅ Benefits of using Olive

  • Reduce frustration of manual trial-and-error model optimization experimentation. Define your target and precision and let Olive automatically produce the best model for you.
  • 40+ built-in model optimization components covering industry-leading techniques across model compression, optimization, finetuning, and compilation.
  • Easy-to-use CLI for common model optimization tasks.
  • Workflows to orchestrate model transformations and optimizations steps.
  • Support for compiling LoRA adapters for MultiLoRA serving.
  • Seamless integration with Hugging Face and Azure AI.
  • Built-in caching mechanism to improve productivity.

📰 News Highlights

Here are some recent videos, blog articles and labs that highlight Olive:

For a full list of news and blogs, read the news archive.

🚀 Getting Started

Notebooks available!

The following notebooks are available that demonstrate key optimization workflows with Olive and include the application code to inference the optimized models on the ONNX Runtime.

TitleTaskDescriptionTime RequiredNotebook Links
QuickstartText GenerationLearn how to quantize & optimize an SLM for the ONNX Runtime using a single Olive command.5minsDownload / Open in Colab
Optimizing popular SLMsText GenerationChoose from a curated list of over 20 popular SLMs to quantize & optimize for the ONNX runtime.5minsDownload / Open in Colab
How to finetune models for on-device inferenceText GenerationLearn how to Quantize (using AWQ method), fine-tune, and optimize an SLM for on-device inference.15minsDownload / Open in Colab

✨ Quickstart

If you prefer using the command line directly instead of Jupyter notebooks, we've outlined the quickstart commands here.

1. Install Olive CLI

We recommend installing Olive in a virtual environment or a conda environment.

pip install olive-ai[ort-genai,auto-opt]
pip install transformers==4.44.2

Note

Olive has optional dependencies that can be installed to enable additional features. Please refer to Olive package config for the list of extras and their dependencies.

2. Automatic Optimizer

In this quickstart you'll be optimizing HuggingFaceTB/SmolLM2-135M-Instruct, which has many model files in the Hugging Face repo for different precisions that are not required by Olive. To minimize the download, cache the original Hugging Face model files (safetensors and configuration) in the main folder of the Hugging Face repo using:

huggingface-cli download HuggingFaceTB/SmolLM2-135M-Instruct *.json *.safetensors *.txt

Next, run the automatic optimization:

olive auto-opt \
--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct \
--output_path models/smolm2 \
--device cpu \
--provider CPUExecutionProvider \
--use_ort_genai \
--precision int4 \
--log_level 1

Tip

PowerShell Users Line continuation between Bash and PowerShell are not interchangable. If you are using PowerShell, then you can copy-and-paste the following command that uses compatible line continuation.
olive auto-opt `--model_name_or_path HuggingFaceTB/SmolLM2-135M-Instruct `--output_path models/smolm2 `--device cpu `--provider CPUExecutionProvider `--use_ort_genai `--precision int4 `--log_level 1

The automatic optimizer will:

  1. Acquire the model from the local cache (note: if you skipped the model download step then the entire contents of the Hugging Face model repo will be downloaded).
  2. Capture the ONNX Graph and store the weights in an ONNX data file.
  3. Optimize the ONNX Graph.
  4. Quantize the model to int4 using RTN method.

Olive can automatically optimize popular model architectures like Llama, Phi, Qwen, Gemma, etc out-of-the-box - see detailed list here. Also, you can optimize other model architectures by providing details on the input/outputs of the model (io_config).

3. Inference on the ONNX Runtime

The ONNX Runtime (ORT) is a fast and light-weight cross-platform inference engine with bindings for popular programming language such as Python, C/C++, C#, Java, JavaScript, etc. ORT enables you to infuse AI models into your applications so that inference is handled on-device.

The following code creates a simple console-based chat interface that inferences your optimized model - select Python and/or C# to expand the code:

PythonCreate a Python file called app.py and copy and paste the following code:

# app.pyimportonnxruntime_genaiasogmodel_folder="models/smolm2/model"# Load the base model and tokenizermodel=og.Model(model_folder)
tokenizer=og.Tokenizer(model)
tokenizer_stream=tokenizer.create_stream()
# Set the max length to something sensible by default,# since otherwise it will be set to the entire context lengthsearch_options= {}
search_options['max_length'] =200search_options['past_present_share_buffer'] =Falsechat_template="<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n"text=input("Input: ")
# Keep asking for input phraseswhiletext!="exit":
ifnottext:
print("Error, input cannot be empty")
exit# generate prompt (prompt template + input)prompt=f'{chat_template.format(input=text)}'# encode the prompt using the tokenizerinput_tokens=tokenizer.encode(prompt)
params=og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids=input_tokensgenerator=og.Generator(model, params)
print("Output: ", end='', flush=True)
# stream the outputtry:
whilenotgenerator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token=generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
exceptKeyboardInterrupt:
print(" --control+c pressed, aborting generation--")
print()
text=input("Input: ")

To run the code, execute python app.py. You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

C#

Create a new C# Console app and install the Microsoft.ML.OnnxRuntimeGenAI Nuget package into your project:

mkdir ortapp
cd ortapp
dotnet new console
dotnet add package Microsoft.ML.OnnxRuntimeGenAI --version 0.5.2

Next, copy-and-paste the following code into your Program.cs file and update modelPath variable to be the absolute path of where you stored your optimized model.

// Program.csusingMicrosoft.ML.OnnxRuntimeGenAI;internalclassProgram{privatestaticvoidMain(string[]args){stringmodelPath@"models/smolm2/model";Console.Write("Loading model from "+modelPath+"...");usingModelmodel=new(modelPath);Console.Write("Done\n");usingTokenizertokenizer=new(model);usingTokenizerStreamtokenizerStream=tokenizer.CreateStream();while(true){Console.Write("User:");stringprompt="<|im_start|>user\n"+Console.ReadLine()+"<|im_end|>\n<|im_start|>assistant\n";varsequences=tokenizer.Encode(prompt);usingGeneratorParamsgParams=newGeneratorParams(model);gParams.SetSearchOption("max_length",200);gParams.SetInputSequences(sequences);gParams.SetSearchOption("past_present_share_buffer",false);Console.Out.Write("\nAI:");usingGeneratorgenerator=new(model,gParams);while(!generator.IsDone()){generator.ComputeLogits();generator.GenerateNextToken();vartoken=generator.GetSequence(0)[^1];Console.Out.Write(tokenizerStream.Decode(token));Console.Out.Flush();}Console.WriteLine();}}}

Run the application:

dotnet run

You'll be prompted to enter a message to the SLM - for example, you could ask what is the golden ratio, or def print_hello_world():. To exit type exit in the chat interface.

🎓 Learn more

🤝 Contributions and Feedback

⚖️ License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

Pipeline Status

Build StatusBuild StatusBuild Status

About

Olive: Simplify ML Model Finetuning, Conversion, Quantization, and Optimization for CPUs, GPUs and NPUs.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages