aimet_onnx.peft¶
Note
This API is experimental and may change between releases.
aimet_onnx.peft adds one or more LoRA adapters to an ONNX model. The result runs like any
other ONNX model, or can be quantized with AIMET. To quantize a model with adapters, see
aimet_onnx.experimental.lora.
What is a LoRA adapter?¶
A LoRA adapter is a small add-on that changes what a model does without changing the model’s own weights. It is trained with the Hugging Face peft library and saved as a folder with two files:
my_adapter/
adapter_config.json # settings: rank (r), alpha, which layers it changes
adapter_model.safetensors # the adapter's weights
For each layer it changes, an adapter has two small weight matrices, A and B. The layer’s
output becomes:
output = original_layer(x) + (x @ A) @ B * (alpha / r)
r (the rank) is the size of A and B. Both r and alpha come from
adapter_config.json.
Quick start¶
import onnx
from aimet_onnx.peft import load_lora_adapters
base_model = onnx.load("base_model.onnx")
lora_model = load_lora_adapters(
base_model,
[("math", "adapters/math"), ("code", "adapters/code")], # (name, adapter folder)
)
onnx.save(lora_model, "lora_model.onnx")
lora_model is an ordinary ONNX model: run it in onnxruntime, or pass it to
aimet_onnx.QuantizationSimModel. base_model is not changed.
peft and safetensors must be installed.
What load_lora_adapters does¶
For every layer that an adapter changes, load_lora_adapters adds a small extra path next to
the layer and adds its output to the layer’s output.
When you pass several adapters, they are all active at the same time, and their effects add
up. If two adapters change the same layer, that layer gets one extra path that holds both
adapters’ weights side by side. Its size r is the sum of their sizes. For example, adapters
with r=4 and r=2 on the same layer give one path with r=6.
The names of the base model’s inputs, outputs and tensors stay the same. This matters for quantization: encodings computed on the base model can be loaded into the model with adapters.
To change which adapters are active or their scales, call load_lora_adapters again on the
base model. You can’t add adapters to a model that already has them.
Note
The order of the adapters list decides where each adapter’s weights sit inside the shared
path. If you reuse encodings across runs, always pass the adapters in the same order.
Preparing the base model¶
load_lora_adapters finds layers by name. An adapter refers to a layer as, for example,
model.layers.0.self_attn.q_proj, and load_lora_adapters looks for an ONNX node with the
same name.
Export from PyTorch. Both
torch.onnx.export(..., dynamo=False)anddynamo=Truework. Withdynamo=Truethe nodes get generic names, so fix them first:from aimet_onnx.prepare_passes.fix_node_names_in_dynamo_exported_onnx import ( fix_node_names_pass, ) base_model = fix_node_names_pass(base_model)
Extra wrapper around the model. If the model was exported inside another module, every layer name may start with an extra
model.(model.model.layers.0...instead ofmodel.layers.0...).load_lora_adaptersnotices this, matches the names anyway, and logs a warning saying so.Smaller copy of the model. Adapter layers the model doesn’t have are skipped with a warning, as
peftdoes in PyTorch. So an adapter trained on a 28-layer model works on a 2-layer copy for quick tests. If none of the adapter’s layers are in the model, it raises an error.Large models. Load the model without reading its weights into memory:
base_model = onnx.load("base_model.onnx", load_external_data=False)
The new model still points to the same weight files, so save it in the same folder as the base model (or copy the weight files next to it).
What is supported¶
Supported |
Not supported |
|
|---|---|---|
Layers |
|
Grouped or dilated convolutions, |
Adapter type |
LoRA |
Other |
Adapter settings |
|
|
Weights file |
|
|
Number types |
float32, float16 or float64. The adapter must use the same type as the base model |
bfloat16 adapters. Nothing is converted for you; save the adapter with |
If an adapter uses something that isn’t supported, load_lora_adapters raises an error that
names the setting instead of producing a model that gives wrong results.
Adapters as model inputs¶
load_lora_adapters_as_inputs adds the same extra paths as load_lora_adapters, but their
A and B weights and the scale are model inputs, so you switch adapters by feeding
different inputs instead of rebuilding the model. It raises if the adapters have different layers,
ranks or number types. See One set of encodings for every adapter (LoRA v1) for how to quantize such a model.
Examples¶
The tests show the complete flows, with every step written out and checked.
TrainingExtensions/onnx/test/python/test_onnx_peft.py:
Test |
What it shows |
|---|---|
|
The complete example. Export a model, save two adapters with |
|
Layer forms beyond the worked example ( |
|
Putting the result into |
|
An adapter trained on more layers than the model has |
|
|
|
Large models with weights in separate files |
Common errors¶
Error message |
What it means |
What to do |
|---|---|---|
|
None of the adapter’s layers are in the model. The message lists the closest names found |
Check that the adapter was trained on this model |
|
The model was exported with |
Run |
|
The adapter uses a setting that isn’t supported |
|
|
The adapter and the model use different number types (e.g. float32 and float16) |
Save the adapter in the model’s type |
|
The adapter’s weights are the wrong size for the layer |
Check that the adapter was trained on this model |
|
The model passed in already has adapters |
Call |
API¶
- aimet_onnx.peft.load_lora_adapters(model, adapters, adapter_scales=None, *, pad_rank=False)[source]¶
Attach LoRA adapters to a base ONNX model as one concatenated branch per layer.
Each adapter owns a slice of the rank axis, and the scale
sholdsadapter_scales * alpha / rper rank. Every adapter passed in is active; to run with a different set or scaling, call this again on the base model. The order ofadapterssets each adapter’s rank slice, so use the same order every time if encodings are reused.Adapter layers are found by module path (
model.layers.0.self_attn.q_proj) matched against the node names. If the base was exported with an extra wrapper module, so that every path differs from the adapter’s by one shared prefix, that prefix is ignored and logged.Adapter layers the base doesn’t have (e.g. a 28-layer adapter on a 2-layer base) are skipped with a warning, as torch peft does.
A layer’s branch rank is the sum of the ranks of the adapters that target it. With
pad_rank, every branch instead gets the sum of all the adapters’ ranks, with zeros after the slices of the adapters that target it (as peftadd_weighted_adapter(combination_type= "cat")). The output is the same; layers targeted by only some adapters cost more.The returned model keeps the base’s external-data locations (relative paths), so save it next to the base’s weight files or copy them along.
For dynamo exports, run
fix_node_names_passon the model first. For large models, load the base withonnx.load(path, load_external_data=False)so its weights are not copied.- Parameters:
model (
ModelProto) – Base model without LoRA branches. Not modified.adapters (
Sequence[tuple[str,str|Path]]) –(name, PEFT checkpoint directory)pairs (the directory holdsadapter_model.safetensorsandadapter_config.json), in rank-slice order. Names must be unique.adapter_scales (
Sequence[tuple[str,float]] |None) –(name, multiplier)pairs, in the same form asadapters. The multiplier is finite and applies to the checkpoint’salpha / r. Adapters not listed get 1.0.pad_rank (
bool) – Give every branch the same rank, the sum of all the adapters’ ranks
- Return type:
ModelProto- Returns:
A new model with the LoRA branches
- Raises:
ValueError – If an adapter or scaling value is invalid, none of the adapter layers are in the model, a layer doesn’t fit the adapter, or
modelalready contains LoRA branches
- aimet_onnx.peft.load_lora_adapters_as_inputs(model, adapters)[source]¶
Add LoRA branches whose weights are graph inputs, and read every adapter’s values for them.
The branches are the ones
load_lora_adapters(model, adapters[:1])adds (noadapter_scales, nopad_rank), but theirAandBare graph inputs named like its initializers, and every branch reads its scale from one[1]graph input,lora_scale. One model then serves every adapter: merge an adapter’s inputs into a run’s inputs to run it, e.g. a different adapter per calibration batch. Merge them after batching: the LoRA inputs have no batch dimension. To run the model without an adapter, feed zeros, e.g.np.zeros_likeof every value of one adapter’s inputs.Every adapter must be compatible with the first: the same checkpoint keys, shapes and dtypes, so the same target layers and rank. Their alphas may differ. Linear
AandBare transposed into the graph’s layout, andlora_scaleis the adapter’salpha / r.- Parameters:
model (
ModelProto) – Base model without LoRA branches. Not modified.adapters (
Sequence[tuple[str,str|Path]]) –(name, PEFT checkpoint directory)pairs. Names must be unique. The adapters’ values are not in the model.
- Return type:
tuple[ModelProto,dict[str,dict[str,ndarray]]]- Returns:
The model, and adapter name -> its inputs (input name -> value, for every
AandBinput andlora_scale)- Raises:
ValueError – If an adapter is invalid or incompatible with the first, or
load_lora_adaptersraises for the first
- aimet_onnx.peft.get_lora_tensor_names(model)[source]¶
The LoRA tensors of a model built by
load_lora_adapters, in branch (Add node) order.Call it on the model
load_lora_adaptersreturned, not on a sim’s graph: QuantSim inserts quantize nodes between the branch tensors. The names are the same in the sim, so the result can be passed to theadapter_utilshelpers with it.- Parameters:
model (
ModelProto) – Model built byload_lora_adapters- Raises:
ValueError – If a branch is missing a node, tensor or initializer, or has a stray scale
- Return type:
- class aimet_onnx.peft.LoraTensorNames(params, activations, scales, merges)[source]¶
The tensors that only the LoRA branches have, and where each branch merges into the base.
Built by
get_lora_tensor_names; theadapter_utilshelpers take it.- property quantizer_names: tuple[str, ...]¶
params and activations, not the scales.
- Type:
The LoRA tensors that are quantized