Skip to content
data

LoraConfig

extends_LoraFields
LoraConfig(task_type: TaskType | str | None = None, peft_type: PeftType | str | None = None, auto_mapping: dict[str, str] | None = None, peft_version: str | None = None, base_model_name_or_path: str | None = None, revision: str | None = None, inference_mode: bool = False, r: int = 8, target_modules: str | list[str] | set[str] | None = None, exclude_modules: str | list[str] | set[str] | None = None, lora_alpha: float = 8, lora_dropout: float = 0.0, fan_in_fan_out: bool = False, bias: Literal['none', 'all', 'lora_only'] = 'none', use_rslora: bool = False, modules_to_save: list[str] | None = None, init_lora_weights: bool | str = True, layers_to_transform: int | list[int] | None = None, layers_pattern: str | list[str] | None = None, rank_pattern: dict[str, int] = dict(), alpha_pattern: dict[str, float] = dict(), megatron_config: dict[str, object] | None = None, megatron_core: str | None = 'megatron.core', trainable_token_indices: list[int] | dict[str, list[int]] | None = None, loftq_config: dict[str, object] = dict(), eva_config: EvaConfig | None = None, corda_config: object | None = None, lora_ga_config: LoraGAConfig | None = None, use_dora: bool = False, velora_config: VeloraConfig | None = None, alora_invocation_tokens: list[int] | None = None, use_qalora: bool = False, qalora_group_size: int = 16, monteclora_config: MontecloraConfig | None = None, layer_replication: list[tuple[int, int]] | None = None, runtime_config: LoraRuntimeConfig = LoraRuntimeConfig(), lora_bias: bool = False, target_parameters: list[str] | None = None, use_bdlora: BdLoraConfig | None = None, arrow_config: ArrowConfig | None = None, kasa_config: KasaConfig | None = None, ensure_weight_tying: bool = False)

How lucid.peft.get_peft_model adapts a model with LoRA.

LoRA (Hu et al., 2021, arXiv:2106.09685) freezes a pretrained weight WW and learns a low-rank update beside it, so a targeted nn.Linear computes Wx+s BAxW x + s \, B A x with A∈Rr×dinA \in \mathbb{R}^{r \times d_{in}}, B∈Rdout×rB \in \mathbb{R}^{d_{out} \times r} and scale s=α/rs = \alpha / r (or α/r\alpha / \sqrt{r} with rsLoRA).

Field names, their order, defaults and adapter_config.json are the reference adapter library's. The reference's options for features this package lacks (eva_config, loftq_config, use_qalora …) are fields too, at the reference's defaults; any other value raises NotImplementedError naming the field.

Parameters

task_typeTaskType | str | None= None
As in lucid.peft.PeftConfig.
peft_typeTaskType | str | None= None
As in lucid.peft.PeftConfig.
auto_mappingTaskType | str | None= None
As in lucid.peft.PeftConfig.
peft_versionTaskType | str | None= None
As in lucid.peft.PeftConfig.
base_model_name_or_pathTaskType | str | None= None
As in lucid.peft.PeftConfig.
revisionTaskType | str | None= None
As in lucid.peft.PeftConfig.
inference_modeTaskType | str | None= None
As in lucid.peft.PeftConfig.
rint= 8
Rank of the update.
target_modulesstr or list of str= None
The modules to adapt: nn.Linear, nn.Embedding, nn.Conv1d / nn.Conv2d / nn.Conv3d, their nn.ConvTranspose counterparts and nn.MultiheadAttention; the module's type picks the LoRA layer that wraps it (lucid.peft.tuners.lora). A list matches a module whose dotted name equals an entry or ends with "." + entry; a string is a regular expression the whole name must match; "all-linear" selects every nn.Linear except the output head and any layer whose weight is shared with another module. None takes the default for the base model's model_type (DEFAULT_LORA_TARGET_MODULES in lucid.peft._target_defaults); a model type with no row raises ValueError.
exclude_modulesstr or list of str= None
Modules never adapted, matched like target_modules.
lora_alphafloat= 8
α\alpha in the scale.
lora_dropoutfloat= 0.0
Dropout on the update's input, in [0, 1).
fan_in_fan_outbool= False
For bases that store their weight (in, out). nn.Linear does not, so True warns and is reset to False.
bias(none, all, lora_only)= "none"
Which biases also train: none, every parameter named bias, or only the biases of the adapted layers.
use_rslorabool= False
Scale by α/r\alpha / \sqrt{r} (Kalajdzievski, 2023).
modules_to_savelist of str= None
Modules trained in full beside the adapter (a classifier head); a trainable copy is kept and saved with it, the original stays. An entry matches a module whose dotted name equals it or ends with "." + entry — on a dot boundary, so classifier does not also catch pre_classifier as the reference's bare suffix test does. Nothing inside these modules is adapted.
init_lora_weightsbool or str= True
True: Kaiming-uniform AA (a = \sqrt 5) and zero BB, so the adapted model starts as the base. "gaussian": A∼N(0,1/r2)A \sim \mathcal N(0, 1/r^2), zero BB. False: both keep nn.Linear's initialisation (the update is non-zero from the start — for tests). "pissa" (Meng et al., 2024) puts the weight's top-rr singular components into BABA and the residual into the base weight; "pissa_niter_<k>" does it with a randomised SVD of k power iterations. "olora" (Büyükakyüz, 2024) puts the first rr columns of a QR decomposition's QQ and rows of RR there instead. Both rewrite the base weight in place (the adapted layer still starts as the original), so an adapter trained from them is relative to that rewritten base — save one with save_pretrained(..., path_initial_model_for_weight_conversion=) to get a plain LoRA of twice the rank that fits the original base; they apply to nn.Linear targets only. "eva", "corda", "loftq" and the reference's other initialisations raise NotImplementedError.
layers_to_transformint or list of int= None
Adapt only these layer indices (the number after the layer list's name, transformer.h.3.attn → 3). Applies to modules matched by suffix; one named in full is adapted regardless. The index is the reference's current rule: the first (outer) <list>.<n>. in the name, so encoder.layers.0.blocks.1.qkv is layer 0. A layer list at the model's root (h.3.attn) is indexed too, where the reference finds no index without a layers_pattern.
layers_patternstr or list of str= None
Name of the layer list ("h", "layers"), a regex fragment; the first match in the name gives the index. Needs layers_to_transform.
rank_patterndict of str to int= dict()
Per-module rank overrides, keyed by name or regex suffix.
alpha_patterndict of str to float= dict()
Per-module α\alpha overrides, keyed the same way.
megatron_configdict= None
Megatron tensor-parallel layers do not exist here. Accepted at the reference's default only: any other value raises NotImplementedError.
megatron_corestr= 'megatron.core'
Megatron tensor-parallel layers do not exist here. Accepted at the reference's default only: any other value raises NotImplementedError.
trainable_token_indiceslist of int or dict of str to list of int= None
Use TrainableTokensConfig for trainable tokens. Accepted at the reference's default only: any other value raises NotImplementedError.
loftq_configdict= dict()
LoftQ quantisation-aware initialisation is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
eva_configobject= None
EVA initialisation is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
corda_configobject= None
CorDA initialisation is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
lora_ga_configobject= None
LoRA-GA initialisation is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
use_dorabool= False
Weight-decomposed low-rank adaptation (Liu et al., 2024): a trainable magnitude per output unit beside BABA, so the adapted weight is m (W+sBA)/∥W+sBA∥m\,(W + sBA)/\lVert W + sBA\rVert row by row. Supported on nn.Linear, nn.Embedding and the convolutions (not grouped ones); nn.MultiheadAttention and target_parameters refuse it, as the reference does. Costs a norm of the full weight per forward pass; merge before inference.
velora_configVeloraConfig= None
VeLoRA is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
alora_invocation_tokenslist of int= None
Activated LoRA is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
use_qalorabool= False
Quantisation-aware LoRA needs a quantised base layer. Accepted at the reference's default only: any other value raises NotImplementedError.
qalora_group_sizeint= 16
Quantisation-aware LoRA needs a quantised base layer. Accepted at the reference's default only: any other value raises NotImplementedError.
monteclora_configMontecloraConfig= None
MonteCLoRA is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
layer_replicationlist of tuple of int= None
Layer replication is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
runtime_configLoraRuntimeConfig= LoraRuntimeConfig()
Settings valid at runtime only, never written to a file. Only the default (ephemeral_gpu_offload=False) is supported.
lora_biasbool= False
Give BB a bias, folded into the base bias on merge. For adapters extracted from a fully fine-tuned layer; needs init_lora_weights of True or False and not use_dora. nn.Linear and convolutions only.
target_parameterslist of str= None
Raw nn.Parameters to adapt, for a parameter that no layer reads through a module of its own (an attention's fused in_proj_weight, a mixture-of-experts weight stack). An entry matches a parameter whose dotted name equals it or ends with "." + entry. The parameter is (out, in), or a stack of them, (experts, out, in); lora_dropout must be 0 for it. The holding module cannot also be in target_modules. With no target_modules, no module is adapted (the model-type default is not taken).
use_bdloraBdLoraConfig= None
Block-diagonal LoRA is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
arrow_configArrowConfig= None
Make this adapter an Arrow router over the adapters the model already holds (Arrow, Ostapenko et al., 2024): each token is sent through the top_k task adapters whose prototype, the top singular vector of their update, it is most aligned with. Add it after the task adapters (lucid.peft.create_arrow_model does). The router cannot be merged; nn.Linear layers only; not with use_dora; its own init_lora_weights must be True, False or "gaussian", since its own factors are never used.
kasa_configKasaConfig= None
KaSA is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.
ensure_weight_tyingbool= False
Weight-tying bookkeeping is not implemented. Accepted at the reference's default only: any other value raises NotImplementedError.

Raises

TypeError
A field holds a value of the wrong type.
ValueError
A field is out of range or two fields conflict.
NotImplementedError
An init_lora_weights the library lacks ("eva", "loftq" …).

Examples

>>> from lucid.peft import LoraConfig
>>> config = LoraConfig(r=4, lora_alpha=8, target_modules=["q_proj", "v_proj"])
>>> sorted(config.target_modules), config.peft_type
(['q_proj', 'v_proj'], <PeftType.LORA: 'LORA'>)
>>> LoraConfig.from_dict(config.to_dict()) == config
True
>>> dora = LoraConfig(use_dora=True, init_lora_weights="PiSSA_niter_4")
>>> dora.use_dora, dora.init_lora_weights
(True, 'pissa_niter_4')

Used by 8

Properties

2
prop

is_adaption_prompt

→boolfrom PeftConfig
is_adaption_prompt: bool

Whether this config is the adaption prompt (AdaptionPromptConfig).

prop

is_prompt_learning

→boolfrom PeftConfig
is_prompt_learning: bool

Whether this config is a prompt-learning method (PromptLearningConfig).

Class methods

5
cls

check_kwargs

→dict of str to objectfrom PeftConfig
check_kwargs(kwargs: object = {})

Check the fields about to build a config; the reference's hook for a class to refuse a file it cannot read.

from_pretrained calls it on the keys of an adapter file, on the class the file names and before any key is dropped for being unknown, as the reference does. A config class overrides it to refuse or warn about a file written for an older release of its method (OFTConfig.check_kwargs); the base accepts everything. from_dict and from_peft_type do not call it.

Parameters

**kwargsobject= {}
The config's fields, by name.

Returns

dict of str to object

The fields to build the config with: kwargs itself.

Examples

>>> from lucid.peft import LoraConfig
>>> LoraConfig.check_kwargs(r=4, peft_type="LORA")
{'r': 4, 'peft_type': 'LORA'}
cls

from_dict

→PeftConfigfrom PeftConfig
from_dict(config_dict: Mapping[str, object])

Build a config from a dict such as a parsed adapter_config.json.

The constructor cannot do this: a file from the reference carries keys v1 has no field for. Such a key is accepted only at a value that turns its feature off — null, false or empty ("loftq_config": {}, "megatron_config": null) — and dropped (with a warning if v1 does not know the key); at any other value it raises, as it would change what the adapter computes. The peft_version provenance key is kept as the field it is.

The dict's peft_type picks the class, whichever class this is called on, as the reference's from_peft_type does: LoraConfig.from_dict of an OFT dict is an OFTConfig. A dict that names no method is read as the calling class (as LoRA on PeftConfig).

Parameters

config_dictMapping of str to object
The config's fields, by the reference's names.

Returns

PeftConfig

The validated config, of the class the dict's method names.

Raises

KeyError
peft_type names no method of this library.
NotImplementedError
The dict turns on a feature v1 lacks.

Examples

>>> from lucid.peft import LoraConfig
>>> config = LoraConfig.from_dict(
...     {"peft_type": "LORA", "r": 4, "target_modules": ["c_attn"],
...      "use_dora": False, "loftq_config": {}, "peft_version": "0.17.0"})
>>> config.r, config.target_modules
(4, {'c_attn'})
>>> type(LoraConfig.from_dict({"peft_type": "OFT", "target_modules": ["q"]})).__name__
'OFTConfig'
cls

from_json_file

→dict of str to objectfrom PeftConfig
from_json_file(path_json_file: str | os.PathLike[str], kwargs: object = {})

Read a config file into the dict it holds, unchanged but for runtime_config.

What from_pretrained reads before it chooses a config class: the file's content as a dict, as the reference's from_json_file returns it. from_dict turns it into a config.

Parameters

path_json_filestr or os.PathLike
The path of a JSON file such as adapter_config.json.
**kwargsobject= {}
Accepted for the reference's signature; it passes none to the reader, and any key given here raises.

Returns

dict of str to object

The file's object, without a runtime_config key: the reference warns that such a key is ignored, since a runtime configuration is valid at runtime only.

Raises

FileNotFoundError
There is no file at path_json_file.
ValueError
The file does not hold a JSON object.
NotImplementedError
kwargs is not empty.

Examples

>>> import os, tempfile
>>> from lucid.peft import LoraConfig, PeftConfig
>>> with tempfile.TemporaryDirectory() as d:
...     LoraConfig(r=2, target_modules=["fc"]).save_pretrained(d)
...     raw = PeftConfig.from_json_file(os.path.join(d, "adapter_config.json"))
>>> raw["peft_type"], raw["r"]
('LORA', 2)
cls

from_peft_type

→PeftConfigfrom PeftConfig
from_peft_type(kwargs: object = {})

Build a config from its fields given as keyword arguments, the class chosen by peft_type.

The reference's way to turn the keys of a config file into a config: the peft_type argument names the method and so the class, whichever class this is called on. Without one, the calling class is built. The fields are read as from_dict reads them, so a key this library has no field for is accepted at a value that turns its feature off (dropped, with a warning when the key is unknown), where the reference drops it at any value.

Parameters

**kwargsobject= {}
The config's fields, by name; peft_type is a PeftType or its string.

Returns

PeftConfig

The validated config, of the class peft_type names.

Raises

KeyError
peft_type names no method of this library.
TypeError
No peft_type is given and this is PeftConfig itself, which builds no config of its own.
NotImplementedError
A key turns on a feature this library does not implement.

Examples

>>> from lucid.peft import LoraConfig, PeftConfig
>>> config = PeftConfig.from_peft_type(peft_type="LORA", r=4, target_modules=["q"])
>>> type(config).__name__, config.r
('LoraConfig', 4)
>>> LoraConfig.from_peft_type(r=2, target_modules=["q"]).r
2
cls

from_pretrained

→PeftConfigfrom PeftConfig
from_pretrained(pretrained_model_name_or_path: str | os.PathLike[str], subfolder: str | None = None, kwargs: object = {})

Read adapter_config.json from a local adapter directory.

The file's peft_type picks the config class, whichever class this is called on (PeftConfig.from_pretrained of a LoRA adapter is a LoraConfig, and LoraConfig.from_pretrained of an OFT adapter an OFTConfig), as the reference's does. The file's keys go through that class's check_kwargs first, before any is dropped for being unknown, and then through from_dict. The reference calls the check_kwargs of the class this is called on, which is the file's class on the paths that load a model; here it is the file's class on every path, so an OFT file is checked when read through PeftConfig too.

Parameters

pretrained_model_name_or_pathstr or os.PathLike
A directory holding adapter_config.json — one written by save_pretrained or by the reference library. Hub ids are not resolved; download the adapter first.
subfolderstr= None
A directory under pretrained_model_name_or_path that holds the file, e.g. the sub-directory save_pretrained gives each adapter but the one named "default".
**kwargsobject= {}
The reference forwards these to its hub download (revision, token, cache_dir …). Adapters are read from a local directory, so any key given here raises.

Returns

PeftConfig

The config, read through from_dict, of the class the file's peft_type names.

Raises

FileNotFoundError
The directory has no adapter_config.json.
ValueError
The file does not hold a JSON object, or its class's check_kwargs refuses it (an OFT file of the reference's before 0.14.0).
KeyError
The file's peft_type names no method of this library.
NotImplementedError
kwargs is not empty, or the file turns on a feature this library lacks.

Examples

>>> import tempfile
>>> from lucid.peft import LoraConfig
>>> with tempfile.TemporaryDirectory() as d:
...     LoraConfig(r=16, lora_alpha=32, target_modules="all-linear").save_pretrained(d)
...     loaded = LoraConfig.from_pretrained(d)
>>> loaded.r, loaded.lora_alpha, loaded.target_modules
(16, 32, 'all-linear')

Instance methods

2
fn

save_pretrained

→Nonefrom PeftConfig
save_pretrained(save_directory: str | os.PathLike[str], kwargs: object = {})

Write adapter_config.json into save_directory.

The file is the reference's: to_dict with its keys sorted, indented by two spaces. The directory is created if missing.

Parameters

save_directorystr or os.PathLike
Directory to write into.
**kwargsobject= {}
auto_mapping_dict replaces the auto_mapping the file records. The reference forwards any other keyword to its hub upload; there is no hub here, so another key raises.

Raises

NotADirectoryError
save_directory names an existing file.
NotImplementedError
kwargs holds a key other than auto_mapping_dict.

Examples

>>> import tempfile
>>> from lucid.peft import LoraConfig
>>> with tempfile.TemporaryDirectory() as d:
...     LoraConfig(r=2, target_modules=["fc"]).save_pretrained(d)
...     LoraConfig.from_pretrained(d).r
2
fn

to_dict

→dict of str to objectfrom PeftConfig
to_dict()

Return the config as the JSON-ready dict adapter_config.json holds.

Enums become their strings and sets of module names sorted lists, so the result goes straight to json.dumps and back through from_dict. A field the reference's config of this method lacks (IA3Config.layers_to_transform) is written only when it is set, so a file that does not use it is one the reference reads too.

Returns

dict of str to object

One entry per field, keyed by the reference's field names.

Examples

>>> from lucid.peft import LoraConfig
>>> d = LoraConfig(target_modules=["v", "q"], task_type="CAUSAL_LM").to_dict()
>>> d["target_modules"], d["task_type"], d["peft_type"]
(['q', 'v'], 'CAUSAL_LM', 'LORA')