Skip to content
class

AdaLoraModel

extends_FileFormat_BaseTuner
AdaLoraModel(model: nn.Module, config: AdaLoraConfig, adapter_name: str, kwargs: object = {})

A model with AdaLoRA layers put into it, the rank allocation and the tools to take them out.

Construction replaces each module config selects with an AdaLoRA layer around it — lucid.peft.tuners.adalora.SVDLinear or SVDConv2d, by the module's type — and freezes every other parameter. The model is changed in place and kept as model; a public name this wrapper lacks is read from it. config itself is not changed: peft_config holds a copy with the default target_modules spelled out.

Training. Call update_and_allocate once per step, after loss.backward() and before the gradients are cleared; it records how much each singular triplet matters and, on the schedule tinit / tfinal / deltaT / total_step define, masks the least important ones until target_r per layer remain. The forward pass adds the orthogonality penalty orth_reg_weight * mean(||Q Q^T - I||, ||P^T P - I||) to the output's loss when it has one, so the model has to be called through this wrapper (or a PeftModel) to be penalised.

One trainable adapter. Several adapters may be held, but only one may train: give every other config inference_mode=True. The rank allocator follows the one that trains.

In a mixed model (mixed=True) AdaLoRA is for inference: MixedModel neither runs the rank allocator nor adds the orthogonality penalty, which are this class's.

Parameters

The model to adapt.
What to adapt and how.
adapter_namestr
Name of the adapter, the key in every lora_* table.
**kwargsobject= {}
low_cpu_mem_usage and state_dict of lucid.peft.LoraModel, which the reference's AdaLoRA tuner forwards. Neither is implemented: a value other than the default raises NotImplementedError, and any other key TypeError.

Raises

ValueError
No module matches target_modules, a match is a module type with no AdaLoRA layer, modules_to_save matches nothing, or a second trainable adapter is asked for.
NotImplementedError
The model already holds adapter layers (wrap it once; add adapters with add_adapter).

Examples

>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft.tuners.adalora import AdaLoraConfig, AdaLoraModel
>>> net = nn.Sequential(nn.Linear(8, 8), nn.ReLU(), nn.Linear(8, 2))
>>> config = AdaLoraConfig(init_r=4, target_r=2, total_step=10, target_modules=["0"])
>>> ada = AdaLoraModel(net, config, "default")
>>> ada.targeted_module_names, net[0].r["default"]
(['0'], 4)
>>> ada(lucid.randn(3, 8)).sum().backward()
>>> ada.update_and_allocate(1)
>>> ada.unload() is net, type(net[0]) is nn.Linear
(True, True)

Used by 1

Constructors

1
dunder

__init__

→None
__init__(model: nn.Module, config: AdaLoraConfig, adapter_name: str, kwargs: object = {})

Adapt model in place, building AdaLoRA's triplets as adapter_name.

Properties

3
prop

active_adapters

→list[str]from _BaseTuner
active_adapters: list[str]

The adapters the forward pass applies, as a list.

prop

rankallocator

→RankAllocator
rankallocator: RankAllocator

The RankAllocator of the trainable adapter (built on first use, rebuilt if that adapter changes).

Raises

RuntimeError
Every adapter is for inference: there is nothing to allocate.
prop

trainable_adapter_name

→str | None
trainable_adapter_name: str | None

The one adapter whose config is not inference_mode, or None if every adapter is for inference.

Static methods

1
static

get_model_config

→dict of str to objectfrom _AdapterHost
get_model_config(model: nn.Module)

model's config as a dict, whatever it is held as.

A config with a to_dict method is converted by it, a dataclass by asdict, a mapping is copied. A model with no config (or one that is None) has the reference's stand-in, {"model_type": "custom"}, which is what the default target modules and the prompt geometry read for a model of no known type.

Parameters

The model to read the config of.

Returns

dict of str to object

The config's entries; a new dict, whose changes do not reach the model.

Raises

TypeError
model.config is none of a mapping, a dataclass or an object with to_dict.

Examples

>>> import lucid.nn as nn
>>> from lucid.peft import LoraModel
>>> LoraModel.get_model_config(nn.Linear(2, 2))
{'model_type': 'custom'}

Instance methods

16
fn

add_adapter

→Nonefrom _BaseTuner
add_adapter(adapter_name: str, config: PeftConfig)

Add an adapter beside the ones the model holds.

The new adapter starts frozen and inactive: the forward pass keeps applying the adapters it applied, and every parameter keeps the requires_grad it had. set_adapter switches to it. A module an earlier adapter already wraps takes the new one beside it; any other target is wrapped. The model is left as it was if the adapter cannot be added.

Layers that hold merged adapters stay merged, bit for bit, and the adapter starts from the weights as they were before the merge, as it would on the unmerged model. An initialisation that writes the base weights (PiSSA, OLoRA, LoRA-GA) cannot be applied where adapters are merged: unmerge_adapter first.

Parameters

adapter_namestr
Name of the new adapter; unique among the model's adapters.
What to adapt and how — the config class of this tuner's method.

Raises

ValueError
The name is taken or malformed, the config is another method's, no module matches it, it cannot sit beside the adapters held (two adapters training biases), or its initialisation writes the base weights of a layer that holds merged adapters.
TypeError
config is not an adapter config.
fn

add_weighted_adapter

→None
add_weighted_adapter(args: object = (), kwargs: object = {})

Not supported for AdaLoRA: its pruned, masked triplets have no weighted sum.

Raises

TypeError
Always.
fn

delete_adapter

→Nonefrom _BaseTuner
delete_adapter(adapter_name: str)

Remove an adapter: its parameters, its config, its modules_to_save copies.

If it was active, the adapters still active stay so; when none remain the first of the others (by name) takes over, with a warning, and trains. Deleting the last adapter leaves the layers in the model, applying nothing; unload() removes them.

Raises

ValueError
The adapter does not exist, or it is merged — unmerge first.
fn

disable_adapter_layers

→Nonefrom _BaseTuner
disable_adapter_layers()

Run the base model alone: adapter updates off, original modules_to_save.

fn

enable_adapter_layers

→Nonefrom _BaseTuner
enable_adapter_layers()

Apply the adapter again after disable_adapter_layers.

fn

forward

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

Call the model, adding the orthogonality penalty to its loss.

When the output carries a loss and an adapter trains, orth_reg_weight times the penalty that keeps PP and QQ near-orthogonal is added to it; otherwise the output is returned as it is.

fn

inject_adapter

→Nonefrom _BaseTuner
inject_adapter(model: nn.Module, adapter_name: str, autocast_adapter_dtype: bool = True, low_cpu_mem_usage: bool = False, state_dict: dict[str, Tensor] | None = None)

Build the layers of adapter adapter_name into model, from the config peft_config holds for it.

The reference's spelling of what add_adapter does: the config is not an argument but is read from peft_config[adapter_name], which the caller has set. The adapter is added as add_adapter adds it (one path): beside the adapters held, frozen and inactive, with merged layers left merged and the new adapter built from the weights as they were; a failure leaves the model as it was and peft_config[adapter_name] as the caller set it. On success peft_config[adapter_name] is the stored config (its default targets spelled out), not the object the caller set.

Parameters

The model to adapt; this tuner's own model.
adapter_namestr
Name of the adapter, with its config in peft_config and no layer of it in the model yet.
autocast_adapter_dtypebool= True
The reference's option to keep a half-precision base's adapter in its own dtype; False raises NotImplementedError.
low_cpu_mem_usagebool= False
The reference's option to build the adapter on the meta device; True raises NotImplementedError.
state_dictdict of str to Tensor= None
The reference's option to match targets against state-dict keys rather than the model's modules; anything but None raises NotImplementedError.

Raises

ValueError
model is not this tuner's model, peft_config has no entry for adapter_name, the model already holds an adapter of that name, or the adapter cannot be applied (as in add_adapter).
TypeError
The config set is not a config of this tuner's method.
NotImplementedError
autocast_adapter_dtype, low_cpu_mem_usage or state_dict holds a value the library cannot honour.

Examples

>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, LoraModel
>>> net = nn.Sequential(nn.Linear(4, 4), nn.Linear(4, 4))
>>> tuner = LoraModel(net, LoraConfig(r=2, target_modules=["0"]), "default")
>>> tuner.peft_config["two"] = LoraConfig(r=2, target_modules=["1"])
>>> tuner.inject_adapter(net, "two")
>>> sorted(tuner.targeted_module_names), tuner.active_adapters
(['0', '1'], ['default'])
fn

merge_adapter

→Nonefrom _BaseTuner
merge_adapter(adapter_names: list[str] | None = None, safe_merge: bool = False)

Fold adapter updates into their base weights, keeping the adapter layers.

A merged model runs at the base model's cost; unmerge_adapter takes the updates out again. Every refusal is made before any weight is written: nothing is merged if a layer's base weight is shared with another module (a tied LM head — merging would change that module too) or if the adapter is disabled.

Merging some of the active adapters leaves the others applying: a merged layer runs its folded weights and then the active adapters it has not folded, so the model computes what it did unmerged. The reference runs a merged layer's base alone, which drops the others; Lucid departs from that on purpose (LCD-971). Merging an adapter that is not active adds it: the layers then run the weights with it folded in and the active adapters they have not folded (the base with that adapter alone, in the reference). A method whose adapters do not compute the same function once split refuses it: those that apply in order (OFT, BOFT, HRA, RoAd's road_2 and road_4, MiSS / Bone's bat) take only the first of the active adapters, in their order; a LoRA layer refuses to fold some adapters while a DoRA one stays unmerged; LN tuning, which runs one adapter's copy at a time, refuses to fold an active adapter while another is active.

Parameters

adapter_nameslist of str= None
Adapters to merge; the active ones by default. A layer holding only some of them merges those.
safe_mergebool= False
Check every merged weight for NaN / inf before writing any.

Raises

RuntimeError
A base weight is shared with another module, or the adapter is disabled (inside disable_adapter()).
ValueError
A name is not one of the model's adapters, safe_merge found a non-finite merged weight, or a layer's method cannot go on applying the active adapters that stay unmerged.

Examples

>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, get_peft_model
>>> config = LoraConfig(r=2, target_modules=["0"], init_lora_weights=False)
>>> peft = get_peft_model(nn.Sequential(nn.Linear(4, 4)), config)
>>> peft.add_adapter("two", config)
>>> peft.base_model.set_adapter(["default", "two"])
>>> x = lucid.randn(3, 4)
>>> both = peft(x)
>>> peft.base_model.merge_adapter(adapter_names=["default"])
>>> peft.base_model.model[0].merged_adapters
['default']
>>> bool(lucid.allclose(peft(x), both, atol=1e-5))   # "two" still applies
True
fn

merge_and_unload

→nn.Modulefrom _BaseTuner
merge_and_unload(progressbar: bool = False, safe_merge: bool = False, adapter_names: list[str] | None = None)

Merge the adapters into the base weights and return the plain model.

Each adapter layer is replaced by its merged base module — the base model's own module, holding its own Parameter objects — and each modules_to_save entry by the active adapter's trained copy (the original when that adapter has none). Adapters not merged are dropped with their layers. Every base parameter gets back the requires_grad it had before injection.

Parameters

progressbarbool= False
Accepted for the reference's signature; there is no progress bar.
safe_mergebool= False
Check every merged weight for NaN / inf before writing any.
adapter_nameslist of str= None
Adapters to merge; the active ones by default.

Returns

nn.Module

The model, merged, with no adapter layer left in it.

Raises

RuntimeError
A base weight is shared with another module, or a modules_to_save module shared one (its trained copy would break the tie).
fn

resize_modules_by_rank_pattern

→None
resize_modules_by_rank_pattern(rank_pattern: Mapping[str, list[bool]], adapter_name: str)

Drop the triplets a rank pattern marks as pruned from the layers, for good.

The scale of what is kept does not change. A layer already as small as its pattern asks is left alone.

Parameters

rank_patterndict of str to list of bool
"<module>.lora_E" to one flag per initial triplet, as the config stores it.
adapter_namestr
The adapter to resize.

Raises

ValueError
A pattern entry names no layer, or its length is neither the layer's rank nor the number of triplets kept.
fn

set_adapter

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

Apply the named adapter(s) in the forward pass, and train exactly those.

Every other adapter is frozen; the activated ones train unless inference_mode. A merged layer is unmerged first. Layers that hold none of the named adapters run their base alone. The parameters bias makes trainable follow the adapter that asked for them.

Parameters

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

Raises

ValueError
A name is not one of the model's adapters, or two named adapters train the same modules_to_save module.
fn

set_requires_grad

→Nonefrom _BaseTuner
set_requires_grad(adapter_names: str | Sequence[str], requires_grad: bool = True)

Enable or disable gradients on the parameters of the named adapter(s).

Raises

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

supports_lora_conversion

→boolfrom _BaseTuner
supports_lora_conversion(adapter_name: str = 'default')

Whether every adapted layer in this tuner supports conversion to LoRA.

fn

unload

→nn.Modulefrom _BaseTuner
unload()

Remove every adapter without merging and return the original model.

Every adapter layer is replaced by the module it wrapped (a merged one is unmerged first), every modules_to_save entry by its original module, and every base parameter gets back the requires_grad it had before injection.

fn

unmerge_adapter

→Nonefrom _BaseTuner
unmerge_adapter()

Take every merged adapter update back out of its base weight.

fn

update_and_allocate

→None
update_and_allocate(global_step: int)

Record the importance of every triplet and, on schedule, mask the least important ones.

Call it every training step, after loss.backward() and before the gradients are cleared. tinit, tfinal and deltaT are handled here: until total_step - tfinal the allocator masks down to the falling budget; at that step it masks to target_r per layer, stores the rank pattern in the config and forgets the importances; afterwards it keeps the dropped triplets at zero.

Parameters

global_stepint
The current training step.

Raises

RuntimeError
The adapter has no gradient (backward was not called), or every adapter is for inference.