LoraModel
_BaseTunerLoraModel(model: nn.Module, peft_config: PeftConfig, adapter_name: str, low_cpu_mem_usage: bool = False, state_dict: dict[str, Tensor] | None = None)A model with LoRA layers put into it, and the tools to take them out.
Construction replaces each module config selects with a LoRA layer
around it — lucid.peft.tuners.lora.Linear, Embedding,
Conv1d / Conv2d / Conv3d or MultiheadAttention, by the
module's type — each module holding a parameter target_parameters
names with a lucid.peft.tuners.lora.ParamWrapper for that
parameter, and each modules_to_save entry with a frozen-original /
trainable-copy pair, then 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 "all-linear" spelled out as the
names it chose.
The model can hold any number of adapters, each under its own name:
add_adapter puts another beside the first (frozen and inactive),
set_adapter chooses which one — or which several — the forward pass
applies, add_weighted_adapter makes one out of others and
delete_adapter removes one. active_adapter is the name, or the
list of names, in use.
Parameters
modelnn.Modulepeft_ configLoraConfigadapter_ namestrlora_A / lora_B.low_ cpu_ mem_ usagebool= FalseTrue raises
NotImplementedError.None raises NotImplementedError.Raises
ValueErrortarget_modules (and no parameter
target_parameters), a match is a module type with no LoRA
layer, modules_to_save matches nothing, or the model already
holds adapters of another method or one named adapter_name.Examples
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, LoraModel
>>> net = nn.Sequential(nn.Linear(8, 8), nn.ReLU(), nn.Linear(8, 2))
>>> lora = LoraModel(net, LoraConfig(r=2, target_modules=["0"]), "default")
>>> lora.targeted_module_names
['0']
>>> net[0].base_layer.weight.requires_grad, net[0].lora_A["default"].weight.requires_grad
(False, True)
>>> lora.add_adapter("other", LoraConfig(r=4, target_modules=["0"]))
>>> lora.active_adapters, sorted(lora.peft_config)
(['default'], ['default', 'other'])
>>> lora.set_adapter("other")
>>> lora.active_adapters, net[0].lora_A["default"].weight.requires_grad
(['other'], False)
>>> lora.unload() is net, type(net[0]) is nn.Linear
(True, True)Used by 3
Properties
1Static methods
1get_model_config
→dict of str to objectfrom _AdapterHostget_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
modelnn.ModuleReturns
dict of str to objectThe config's entries; a new dict, whose changes do not reach the model.
Raises
TypeErrormodel.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
14Add 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_ namestrconfigPeftConfigRaises
ValueErrorTypeErrorconfig is not an adapter config.add_weighted_adapter
→Noneadd_weighted_adapter(adapters: list[str], weights: list[float], adapter_name: str, combination_type: _CombinationType = 'svd', svd_rank: int | None = None, svd_clamp: float | None = None, svd_full_matrices: bool = True, svd_driver: str | None = None, density: float | None = None, majority_sign_method: Literal['total', 'frequency'] = 'total')Add an adapter that is a weighted combination of existing ones.
The new adapter is frozen and inactive, like any added adapter, and has , so its scale is 1 and the weights live in its matrices. It targets the union of the sources' modules; a layer one source does not reach combines the sources it has.
Parameters
adapterslist of strweightslist of floatadapter_ namestrcombination_ typestr= "svd""svd": the rank-svd_rank truncation of
. "cat": that sum exactly,
at the sum of the ranks. "linear": A and B weighted
apart (adding cross terms ); one rank. With one
adapter every type is "linear". "ties", "dare_linear",
"dare_ties" and "magnitude_prune" (which take a
density) merge A and B apart; their *_svd forms
merge the updates and truncate like "svd". TIES trims to the
largest elements and elects a sign; DARE drops elements at random
(lucid.manual_seed repeats it) and rescales.svd_ rankint= None"svd" result; the largest source rank by default.svd_ clampfloat= None[0, 1]; "svd" factors are clamped to the
symmetric range holding that share of their values.svd_ full_ matricesbool= TrueU / Vh.svd_ driverstr= Nonelucid.linalg.svd accepts None only.densityfloat= None[0, 1]; required by the
TIES, DARE and magnitude-prune types.majority_ sign_ method(total, frequency)= "total"Raises
ValueErrormodules_to_save module),
combination_type is unknown, or a type that prunes got no
density.NotImplementedErrorlora_bias adapter.Examples
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, LoraModel
>>> net = nn.Sequential(nn.Linear(6, 5))
>>> config = LoraConfig(r=2, target_modules=["0"], init_lora_weights=False)
>>> lora = LoraModel(net, config, adapter_name="a")
>>> lora.add_adapter("b", config)
>>> lora.add_weighted_adapter(["a", "b"], [0.5, 0.5], "mix", combination_type="cat")
>>> net[0].r["mix"]
4Remove 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
ValueErrorRun the base model alone: LoRA updates off, original modules_to_save.
With bias other than "none" the trained biases are base
parameters and stay as trained, so the output is not the base
model's; a warning says so.
Apply the adapter again after disable_adapter_layers.
Call the adapted model; its adapter layers do their work inside the call.
inject_adapter
→Nonefrom _BaseTunerinject_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
modelnn.Modulemodel.adapter_ namestrpeft_config and no layer of it in the model yet.autocast_ adapter_ dtypebool= TrueFalse raises NotImplementedError.low_ cpu_ mem_ usagebool= FalseTrue raises
NotImplementedError.None raises NotImplementedError.Raises
ValueErrormodel 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).TypeErrorNotImplementedErrorautocast_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'])merge_adapter
→Nonefrom _BaseTunermerge_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= Nonesafe_ mergebool= FalseRaises
RuntimeErrordisable_adapter()).ValueErrorsafe_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
Truemerge_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= Falsesafe_ mergebool= Falseadapter_ nameslist of str= NoneReturns
nn.ModuleThe model, merged, with no adapter layer left in it.
Raises
RuntimeErrormodules_to_save module shared one (its trained copy would
break the tie).set_adapter
→Nonefrom _BaseTunerset_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 strinference_ modebool= FalseRaises
ValueErrormodules_to_save module.set_requires_grad
→Nonefrom _BaseTunerset_requires_grad(adapter_names: str | Sequence[str], requires_grad: bool = True)Enable or disable gradients on the parameters of the named adapter(s).
Raises
ValueErrorsupports_lora_conversion
→boolfrom _BaseTunersupports_lora_conversion(adapter_name: str = 'default')Whether every adapted layer in this tuner supports conversion to LoRA.
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.
Take every merged adapter update back out of its base weight.