Skip to content
class

PeftModel

extends_AdaptedModel
PeftModel(model: nn.Module, peft_config: PeftConfig, adapter_name: str = 'default', autocast_adapter_dtype: bool = True, low_cpu_mem_usage: bool = False)

A model with adapters, saved and loaded as the adapters alone.

Wraps the model in its method's tuner (LoraModel for a LoraConfig), kept as base_model (the user's model is base_model.model), so the state dict reads base_model.model....lora_A.default.weight and the adapter file base_model.model....lora_A.weight, the reference library's layouts. Calling it runs the wrapped model, and any public name it lacks — generate, config, a head — is read from that model, so code written for the bare model keeps working.

The model holds any number of adapters by name. add_adapter and load_adapter bring one in beside the others (frozen and inactive), set_adapter switches which one the model computes with — and trains — and delete_adapter drops one. save_pretrained writes them all, the "default" one at the directory itself and each other in a sub-directory of its own name.

Usually made by lucid.peft.get_peft_model, or by from_pretrained for a saved adapter. Both pick the class from the config's task_type: the wrappers (PeftModelForCausalLM and the others, MODEL_TYPE_TO_PEFT_MODEL_MAPPING) are subclasses of this one, each registered for its task by class Wrapper(PeftModel, task_type=TaskType.X); an adapter with no task, or a task no wrapper is registered for, gets this class itself.

Parameters

The model to adapt, changed in place.
peft_configPeftConfig
What to adapt and how — a LoraConfig.
adapter_namestr= "default"
Name of the adapter.
autocast_adapter_dtypebool= True
Cast a half-precision base's adapter weights to float32. Always the case here; False raises NotImplementedError.
low_cpu_mem_usagebool= False
Build the adapter on the meta device. Not implemented: True raises NotImplementedError.

Raises

TypeError
peft_config is not an adapter config.
NotImplementedError
autocast_adapter_dtype or low_cpu_mem_usage holds a value the library cannot honour.

Examples

>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftModel
>>> net = nn.Sequential(nn.Linear(8, 8), nn.ReLU(), nn.Linear(8, 2))
>>> peft = PeftModel(net, LoraConfig(r=2, target_modules=["0"]))
>>> peft.get_nb_trainable_parameters()
(32, 122)
>>> peft(lucid.randn(4, 8)).shape
(4, 2)

Used by 8

Constructors

1
dunder

__init__

→None
__init__(model: nn.Module, peft_config: PeftConfig, adapter_name: str = 'default', autocast_adapter_dtype: bool = True, low_cpu_mem_usage: bool = False)

Adapt model in place with peft_config and wrap it.

adapter_name names the first adapter.

Properties

7
prop

active_adapter

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

Name of the adapter in use (a list once delete_adapter leaves several or none).

prop

active_adapters

→list[str]
active_adapters: list[str]

The adapters in use, as a list.

prop

active_peft_config

→PeftConfig
active_peft_config: PeftConfig

The config of the adapter in use.

Raises

ValueError
No adapter is in use, or several are (active_adapter is a list).
prop

base_model_dtype

→lucid.dtype | None
base_model_dtype: lucid.dtype | None

The dtype of the base model: its first floating-point parameter's; None if it has none.

The reference spells this member with its framework's name; that spelling cannot appear in this library's source.

prop

has_active_enabled_adapter

→bool
has_active_enabled_adapter: bool

Whether the adapters are enabled — the reference's rule, as it computes it.

For a prompt-learning adapter: True unless inside disable_adapter(). For the other methods the reference also answers True when no adapter is in use, so inside disable_adapter() the answer is False only while an adapter is in use.

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 ("all-linear" spelled out).

Class methods

1
cls

from_pretrained

→PeftModel
from_pretrained(model: nn.Module, model_id: str | os.PathLike[str], adapter_name: str = 'default', is_trainable: bool = False, config: PeftConfig | None = None, autocast_adapter_dtype: bool = True, ephemeral_gpu_offload: bool = False, low_cpu_mem_usage: bool = False, key_mapping: Mapping[str, str] | None = None, subfolder: str | None = None, convert: ConvertMode = 'auto', kwargs: object = {})

Adapt model with the adapter saved in model_id.

Reads adapter_config.json (unless config is given) and adapter_model.safetensors — written by save_pretrained or by the reference library — injects the adapter into model in place and loads its tensors. The adapter is built without its initialisation's effect on the base, so an adapter saved from a PiSSA or OLoRA start loads onto the (rewritten) base it was trained beside as it was trained, and a pristine base is left as it is. If the tensors do not fit the model, the injection is undone before the error is raised. The class returned follows the config's task_type as in lucid.peft.get_peft_model; only an adapter with no task is built as cls.

Parameters

The base model the adapter was trained on.
model_idstr or os.PathLike
A local adapter directory. Hub ids are not resolved.
adapter_namestr= "default"
Name to give the adapter.
is_trainablebool= False
Keep the adapter trainable. By default it is frozen and the model is put in eval() mode, for inference.
configPeftConfig= None
Use this config instead of the directory's.
autocast_adapter_dtypebool= True
Cast a half-precision base's adapter weights to float32. Always the case here; False raises NotImplementedError.
ephemeral_gpu_offloadbool= False
Not implemented: True raises NotImplementedError.
low_cpu_mem_usagebool= False
Build the adapter on the meta device. Not implemented: True raises NotImplementedError.
key_mappingdict of str to str= None
Renames the adapter file's keys before they are loaded: for each key, with its base_model.model. prefix set aside, the first pattern (a regular expression) that matches is replaced by its value, as the reference does. Applied before convert.
subfolderstr= None
The directory under model_id that holds the adapter. (The reference takes it among **kwargs; it is named here.)
convertbool or auto= "auto"
Convert an adapter written for the reference library's model to the zoo model's layout (lucid.peft lists what each converter does): gpt2 (the score head), roformer, t5 (renamed modules) and vit (query / key / value fused into qkv, LoRA only). "auto" converts when the model's type has a converter and the file is in a layout it changes; True always converts and refuses a type with none; False reads it as it is.
**kwargsobject= {}
The reference forwards these to its hub download (revision, token, cache_dir …). Any key raises NotImplementedError.

Returns

PeftModel

model, adapted and loaded — a task wrapper if the adapter names a task.

Raises

FileNotFoundError
The directory lacks adapter_config.json or the weights.
NotImplementedError
The weights are a pickle (adapter_model.bin), the config describes something lucid.peft does not implement, or an option the library cannot honour is set (see the parameters).
ValueError
The adapter's tensors do not fit model, or convert cannot apply.

Examples

>>> import tempfile
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftModel, get_peft_model
>>> net = nn.Sequential(nn.Linear(4, 2))
>>> base_state = {k: v.clone() for k, v in net.state_dict().items()}
>>> trained = get_peft_model(net, LoraConfig(r=2, target_modules=["0"],
...                                         init_lora_weights=False))
>>> x = lucid.randn(3, 4)
>>> with tempfile.TemporaryDirectory() as d:
...     trained.save_pretrained(d)
...     fresh = nn.Sequential(nn.Linear(4, 2))
...     _ = fresh.load_state_dict(base_state)
...     loaded = PeftModel.from_pretrained(fresh, d)
>>> bool(lucid.allclose(loaded(x), trained(x)))
True

Instance methods

21