On this page

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.

  1. Export from PyTorch. Both torch.onnx.export(..., dynamo=False) and dynamo=True work. With dynamo=True the 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)
    
  2. 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 of model.layers.0...). load_lora_adapters notices this, matches the names anyway, and logs a warning saying so.

  3. Smaller copy of the model. Adapter layers the model doesn’t have are skipped with a warning, as peft does 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.

  4. 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

Linear (exported as MatMul or Gemm), Conv1d / Conv2d / Conv3d

Grouped or dilated convolutions, Conv with auto_pad

Adapter type

LoRA

Other peft methods (IA3, prefix tuning, …)

Adapter settings

r, lora_alpha, target_modules, lora_dropout, init_lora_weights = True, False or "gaussian"

bias, use_rslora, use_dora, rank_pattern, alpha_pattern, modules_to_save, and any other setting changed from its default

Weights file

adapter_model.safetensors

adapter_model.bin (save with safe_serialization=True)

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 model.half() for a float16 base

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

TestLoadLoraAdapters.test_worked_example_two_adapters

The complete example. Export a model, save two adapters with peft, call load_lora_adapters, run the result, and check it against peft in PyTorch

TestLoadLoraAdapters.test_each_layer_kind_matches_torch_peft

Layer forms beyond the worked example (Gemm, Conv1d)

TestLoadLoraAdapters.test_quantsim_quantizes_the_lora_tensors

Putting the result into QuantizationSimModel

TestLoadLoraAdapters.test_adapter_layers_missing_from_base_are_skipped

An adapter trained on more layers than the model has

TestLoadLoraAdapters.test_pad_rank

pad_rank=True: every path gets the same size, and the output doesn’t change

TestLoadLoraAdapters.test_external_data_base

Large models with weights in separate files

Common errors

Error message

What it means

What to do

No MatMul/Gemm/Conv with a static weight matches module path '...'

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

... call fix_node_names_pass first

The model was exported with dynamo=True and its node names weren’t fixed

Run fix_node_names_pass on the model first

LoraConfig.<setting>=... is not supported

The adapter uses a setting that isn’t supported

See What is supported

... re-save the adapter in the base model's dtype

The adapter and the model use different number types (e.g. float32 and float16)

Save the adapter in the model’s type

... doesn't fit the base layer

The adapter’s weights are the wrong size for the layer

Check that the adapter was trained on this model

The model already contains LoRA branches

The model passed in already has adapters

Call load_lora_adapters on the original base model

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 s holds adapter_scales * alpha / r per rank. Every adapter passed in is active; to run with a different set or scaling, call this again on the base model. The order of adapters sets 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 peft add_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_pass on the model first. For large models, load the base with onnx.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 holds adapter_model.safetensors and adapter_config.json), in rank-slice order. Names must be unique.

  • adapter_scales (Sequence[tuple[str, float]] | None) – (name, multiplier) pairs, in the same form as adapters. The multiplier is finite and applies to the checkpoint’s alpha / 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 model already 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 (no adapter_scales, no pad_rank), but their A and B are 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_like of 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 A and B are transposed into the graph’s layout, and lora_scale is the adapter’s alpha / 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 A and B input and lora_scale)

Raises:

ValueError – If an adapter is invalid or incompatible with the first, or load_lora_adapters raises 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_adapters returned, 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 the adapter_utils helpers with it.

Parameters:

model (ModelProto) – Model built by load_lora_adapters

Raises:

ValueError – If a branch is missing a node, tensor or initializer, or has a stray scale

Return type:

LoraTensorNames

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; the adapter_utils helpers take it.

property quantizer_names: tuple[str, ...]

params and activations, not the scales.

Type:

The LoRA tensors that are quantized