Skip to content
class

PeftMixedModel

extends_AdaptedModel
PeftMixedModel(model: nn.Module, peft_config: PeftConfig, adapter_name: str = 'default')

A model holding the adapters of several methods at once, loaded from files and not saved.

The first adapter of a method puts that method's layer on each module it targets; the layers of other methods stand on it, so the forward pass runs them lowest first. The tuner is a lucid.peft.tuners.MixedModel, kept as base_model (the user's model is base_model.model), and the state dict reads base_model.model.... as a lucid.peft.PeftModel's does. Calling it runs the wrapped model, and any public name it lacks is read from that model, so code written for the bare model keeps working.

It is not a PeftModel: there is no task wrapper, no adapter_names routing of a batch and no save_pretrained. An adapter is written by the PeftModel of its own method and read here with load_adapter or from_pretrained, which fill it from the single-method file, before or after the layers of other methods are stacked on it. The reference's mixed model writes nothing either, and says so with the same NotImplementedError.

The methods that can be mixed are the keys of PEFT_TYPE_TO_MIXED_MODEL_MAPPING; any other is refused with ValueError where it is added. Adding an adapter that cannot sit where it would land raises ValueError and leaves the model as it was. AdaLoRA takes part for inference only.

Parameters

The model to adapt, changed in place; it must hold no adapters yet.
peft_configPeftConfig
The first adapter's config: any mixable method's.
adapter_namestr= "default"
Name of the first adapter.

Raises

TypeError
peft_config is not an adapter config.
ValueError
The method is not mixable, the model already holds adapters, or the adapter cannot be applied.

Examples

>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoHaConfig, LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(8, 8), nn.ReLU(), nn.Linear(8, 2))
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"]), "lora")
>>> mixed.add_adapter("loha", LoHaConfig(r=2, target_modules=["0"]))
>>> mixed.set_adapter(["lora", "loha"])
>>> mixed.active_adapters
['lora', 'loha']
>>> mixed(lucid.randn(4, 8)).shape
(4, 2)

Used by 2

Constructors

1
dunder

__init__

→None
__init__(model: nn.Module, peft_config: PeftConfig, adapter_name: str = 'default')

Adapt model in place with peft_config's method as adapter_name and wrap it.

Properties

4
prop

active_adapter

→str | list[str]
active_adapter: str | list[str]

Name of the adapter in use (a list once several are).

prop

active_adapters

→list[str]
active_adapters: list[str]

The adapters in use, as a list.

prop

modules_to_save

→set[str] | None
modules_to_save: set[str] | None

The names of the modules trained in full beside the adapters, over every adapter; None if there are none.

prop

peft_config

→dict[str, PeftConfig]
peft_config: dict[str, PeftConfig]

Each adapter's config by adapter name.

Class methods

1
cls

from_pretrained

→PeftMixedModel
from_pretrained(model: nn.Module, model_id: str | os.PathLike[str], adapter_name: str = 'default', is_trainable: bool = False, config: PeftConfig | None = None, kwargs: object = {})

Adapt model with the adapter saved in model_id, ready to take the adapters of other methods.

Reads adapter_config.json (unless config is given) and adapter_model.safetensors — what a single-method lucid.peft.PeftModel.save_pretrained wrote — injects the adapter into model in place and loads its tensors; if they do not fit, the injection is undone before the error is raised. Only a method of PEFT_TYPE_TO_MIXED_MODEL_MAPPING can be loaded.

Parameters

The model the adapter was trained beside; it must hold no adapters.
model_idstr or os.PathLike
The local directory of the adapter's two files; hub ids are not resolved.
adapter_namestr= "default"
The name the adapter gets.
is_trainablebool= False
Leave the adapter training. Otherwise it is frozen and the model goes to eval() mode, for inference.
configPeftConfig= None
A config to use in place of the directory's.
**kwargsobject= {}
subfolder, convert, key_mapping and the other options of load_adapter, by name, as for lucid.peft.PeftModel.from_pretrained.

Returns

PeftMixedModel

model, adapted and loaded.

Raises

FileNotFoundError
The directory lacks adapter_config.json or the weights.
NotImplementedError
An option the library cannot honour is set.
TypeError
config is not an adapter config, or an option is of the wrong type.
ValueError
The adapter's method is not in the mixed-model mapping, or its tensors do not fit model.

Examples

>>> import tempfile
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftMixedModel, get_peft_model
>>> def base():
...     lucid.manual_seed(0)
...     return nn.Sequential(nn.Linear(4, 2))
>>> config = LoraConfig(r=2, target_modules=["0"], init_lora_weights=False)
>>> trained = get_peft_model(base(), config)
>>> x = lucid.randn(3, 4)
>>> with tempfile.TemporaryDirectory() as d:
...     trained.save_pretrained(d)
...     loaded = PeftMixedModel.from_pretrained(base(), d)
>>> bool(lucid.allclose(loaded(x), trained(x)))
True

Instance methods

16
fn

add_adapter

→None
add_adapter(adapter_name: str, peft_config: PeftConfig, low_cpu_mem_usage: bool = False, autocast_adapter_dtype: bool = True)

Add an adapter, of any mixable method, beside the ones the model holds.

The new adapter starts frozen and inactive; set_adapter switches to it. A module that a method already adapts takes this adapter in that method's layer, and a module another method adapted gets this method's layer stacked on top. A merged stack stays merged; the new adapter reads the weight beneath every layer of it.

Parameters

adapter_namestr
The new adapter's name, which no adapter of the model has.
peft_configPeftConfig
The adapter's config: a method of the mixed-model mapping.
low_cpu_mem_usagebool= False
The reference's meta-device build; True raises NotImplementedError.
autocast_adapter_dtypebool= True
The reference's float32 cast for a half-precision base, always done here; False raises NotImplementedError.

Raises

ValueError
The name is taken, the method is not mixable, no module matches, the adapter cannot stand where it would land, or a LoRA initialisation that writes the base weights (PiSSA, OLoRA, LoRA-GA) meets merged layers. The model is left as it was.
NotImplementedError
low_cpu_mem_usage or autocast_adapter_dtype holds a value the library cannot honour.

Examples

>>> import lucid.nn as nn
>>> from lucid.peft import LoHaConfig, LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(4, 4), nn.Linear(4, 2))
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"]), "lora")
>>> mixed.add_adapter("loha", LoHaConfig(r=2, target_modules=["0", "1"]))
>>> sorted(mixed.peft_config)
['loha', 'lora']
fn

create_or_update_model_card

→None
create_or_update_model_card(output_dir: str)

Refused: the reference writes a hub model card, which this library has no use for.

Raises

NotImplementedError
Always.
fn

delete_adapter

→None
delete_adapter(adapter_name: str | list[str])

Remove the named adapter(s), their configs and their layers' tables.

Every name is checked before the first is removed, so a refusal leaves the model as it was. If an adapter in use is removed and none remains in use, the first of the others (by name) takes over, with a warning.

Parameters

adapter_namestr or list of str
The adapter, or adapters, to remove.

Raises

ValueError
A name is not one of the model's adapters, or one of them is merged.
fn

disable_adapter

→AbstractContextManager[None]
disable_adapter()

Run the base model alone inside the with block, whatever stack of adapters is in use.

The adapters come back when the block exits, even on an exception. Blocks nest: they stay off until the outermost one exits.

Examples

>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(4, 4))
>>> x = lucid.randn(2, 4)
>>> base_out = net(x)
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"],
...                                        init_lora_weights=False))
>>> with mixed.disable_adapter():
...     bool((mixed(x) == base_out).all().item())
True
fn

forward

→object
forward(args: object = (), kwargs: object = {})

Run the adapted model; every argument goes to it as given.

Parameters

*argsobject= ()
Positional arguments of the model's forward.
**kwargsobject= {}
Keyword arguments of the model's forward. Unlike lucid.peft.PeftModel.forward there is no adapter_names here.

Returns

object

What the model's forward returns.

fn

generate

→object
generate(args: object = (), kwargs: object = {})

Generate with the adapted model: its own generate, called as given.

Parameters

*argsobject= ()
Positional arguments of the model's generate.
**kwargsobject= {}
Keyword arguments of the model's generate.

Returns

object

What the model's generate returns.

Raises

AttributeError
The adapted model has no generate.
fn

get_layer_status

→NoReturn
get_layer_status()

Not supported: the status of a layer is read off one method's tuner.

Raises

TypeError
Always, as the reference's mixed model does.
fn

get_model_status

→NoReturn
get_model_status()

Not supported: the status of a model is read off one method's tuner.

Raises

TypeError
Always, as the reference's mixed model does.
fn

get_nb_trainable_parameters

→tuple of int
get_nb_trainable_parameters()

Return (trainable, total) parameter counts, each shared parameter once.

Returns

tuple of int

Elements in parameters that require grad, and in all of them.

fn

load_adapter

→_IncompatibleKeys
load_adapter(model_id: str | os.PathLike[str], adapter_name: str, args: object = (), kwargs: object = {})

Load a saved adapter into the model, beside the ones it holds.

An adapter the model does not hold is added from the directory's config and filled from its weights, stacked on the modules it targets; the weights of one the model already holds replace the values it has. The directory holds what a single-method lucid.peft.PeftModel.save_pretrained wrote, and loads before or after other methods' layers are stacked on its modules. The loaded adapter is not made the one in use — set_adapter does that. Nothing changes if the files are missing or do not fit.

Parameters

model_idstr or os.PathLike
The local directory that holds the adapter's adapter_config.json and adapter_model.safetensors.
adapter_namestr
Name to give the adapter.
*argsobject= ()
In order: is_trainable, device, autocast_adapter_dtype, ephemeral_gpu_offload, low_cpu_mem_usage, key_mapping — as for lucid.peft.PeftModel.load_adapter.
**kwargsobject= {}
Those by name, and subfolder, convert and ignore_mismatched_sizes, as for lucid.peft.PeftModel.load_adapter; any other key raises NotImplementedError (the reference's hub options).

Returns

_IncompatibleKeys

What set_peft_model_state_dict hands back.

Raises

FileNotFoundError
The directory lacks adapter_config.json or the weights.
NotImplementedError
An option the library cannot honour is set.
TypeError
An argument is of the wrong type.
ValueError
The tensors do not fit, or the adapter's method cannot be mixed or cannot stand where it would land.

Examples

>>> import tempfile
>>> import lucid.nn as nn
>>> from lucid.peft import LoHaConfig, LoraConfig, PeftMixedModel, get_peft_model
>>> source = get_peft_model(nn.Sequential(nn.Linear(4, 2)), LoHaConfig(r=2, target_modules=["0"]))
>>> mixed = PeftMixedModel(nn.Sequential(nn.Linear(4, 2)), LoraConfig(r=2, target_modules=["0"]), "lora")
>>> with tempfile.TemporaryDirectory() as d:
...     source.save_pretrained(d)
...     _ = mixed.load_adapter(d, "loha")
>>> sorted(mixed.peft_config), mixed.active_adapter
(['loha', 'lora'], 'lora')
fn

merge_and_unload

→nn.Module
merge_and_unload(args: object = (), kwargs: object = {})

Fold the adapters into the base model and hand the base model back.

Each module's layers are folded lowest first, and the adapters that were not folded in are gone with their layers. A merge that would fold a layer's update under a layer that transforms it differently is refused before any weight is written.

Parameters

*argsobject= ()
progressbar, safe_merge and adapter_names, positionally and in that order.
**kwargsobject= {}
The same, by name. progressbar is kept for call compatibility and ignored; safe_merge refuses, before changing any weight, a merged weight holding NaN or inf; adapter_names (a list of str) picks the adapters to fold in, the ones in use by default.

Returns

nn.Module

The base model, with its plain layers again.

Raises

TypeError
An argument is not one of those, or is of the wrong type.
ValueError
A name is not an adapter of the model, or the merge would fold an update under a layer that transforms it.

Examples

>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoHaConfig, LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(4, 4))
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"],
...                                        init_lora_weights=False), "lora")
>>> mixed.add_adapter("loha", LoHaConfig(r=2, target_modules=["0"]))
>>> mixed.set_adapter(["lora", "loha"])
>>> x = lucid.randn(3, 4)
>>> stacked = mixed(x)
>>> plain = mixed.merge_and_unload()
>>> type(plain[0]) is nn.Linear, bool(lucid.allclose(plain(x), stacked, atol=1e-5))
(True, True)
fn→None
print_trainable_parameters()

Print the trainable / total parameter counts and their ratio.

Examples

>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftMixedModel
>>> mixed = PeftMixedModel(nn.Sequential(nn.Linear(8, 8)),
...                        LoraConfig(r=2, target_modules=["0"]))
>>> mixed.print_trainable_parameters()
trainable params: 32 || all params: 104 || trainable%: 30.7692
fn

save_pretrained

→None
save_pretrained(save_directory: str | os.PathLike[str], safe_serialization: bool = False, selected_adapters: list[str] | None = None, kwargs: object = {})

Refused: a mixed model is not saved, as the reference's is not.

Write each adapter from a lucid.peft.PeftModel of its own method; the file is read back here by load_adapter.

Parameters

save_directorystr or os.PathLike
Where the adapters would go; not read, and not created.
safe_serializationbool= False
The reference's default for a format the reference's mixed model never writes; not read.
selected_adapterslist of str= None
The adapters to write; not read.
**kwargsobject= {}
Not read.

Raises

NotImplementedError
Always; nothing is written.
fn

set_adapter

→None
set_adapter(adapter_name: str | list[str], inference_mode: bool = False)

Make the named adapter(s), of any methods, the ones in use.

Each layer applies those of the names it holds and passes its input through otherwise; the named adapters train, and every other adapter is frozen, unless inference_mode. A merged model is unmerged first.

Parameters

adapter_namestr or list of str
The adapter, or adapters, to apply.
inference_modebool= False
Freeze the named adapters too.

Raises

ValueError
A name is not one of the model's adapters.
fn

set_modules_to_save

→None
set_modules_to_save(peft_config: PeftConfig, adapter_name: str)

Check that the modules peft_config trains in full are held by adapter_name.

The reference wraps those modules after its tuner has built the adapter. Here the tuner wraps them as the adapter goes in, so by the time adapter_name exists its modules are wrapped, and this method confirms it: it changes nothing. The modules_to_save of an adapter cannot be widened afterwards; add the adapter with a config that names them.

Parameters

peft_configPeftConfig
The config naming the modules, normally peft_config[adapter_name].
adapter_namestr
An adapter the model holds.

Raises

ValueError
The model has no adapter of that name, or a module the config names is not trained for it.

Examples

>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(4, 4), nn.Linear(4, 2))
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"], modules_to_save=["1"]))
>>> mixed.set_modules_to_save(mixed.peft_config["default"], "default")
>>> mixed.modules_to_save
{'1'}
fn

unload

→nn.Module
unload(args: object = (), kwargs: object = {})

Remove every adapter without merging and return the original model.

Parameters

*argsobject= ()
None: the reference's tuner ignores them, and here they raise TypeError.
**kwargsobject= {}
None, as for args.

Returns

nn.Module

The model, each adapter layer replaced by the module it stood on.

Raises

TypeError
An argument was given.