Skip to content
data

AdaLoraConfig

extends_LoraFields
AdaLoraConfig(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 = True, layers_to_transform: int | list[int] | None = None, layers_pattern: str | list[str] | None = None, rank_pattern: dict[str, list[bool]] | None = None, 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, target_r: int = 8, init_r: int = 12, tinit: int = 0, tfinal: int = 0, deltaT: int = 1, beta1: float = 0.85, beta2: float = 0.85, orth_reg_weight: float = 0.5, total_step: int | None = None)

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

AdaLoRA (Zhang et al., 2023, arXiv:2303.10512) writes the update of a targeted nn.Linear (or nn.Conv2d) as a truncated SVD,

P∈Rdout×r,  λ∈Rr,  Q∈Rr×din,\qquad P \in \mathbb{R}^{d_{out} \times r},\; \lambda \in \mathbb{R}^{r},\; Q \in \mathbb{R}^{r \times d_{in}},

with P,QP, Q kept near-orthogonal by a penalty on the loss, and learns how many of the rr singular triplets each layer deserves: the importance of each triplet is tracked during training and the least important are masked away on a schedule until the model holds target_r triplets per layer on average (lucid.peft.tuners.adalora.AdaLoraModel.update_and_allocate).

Training has three phases, set by tinit, tfinal and total_step: the first tinit steps train every triplet; then the budget falls on a cubic schedule until step total_step - tfinal, where it reaches target_r per layer; the last tfinal steps fine-tune what is left. With tinit = 10, tfinal = 20 and total_step = 100, 10 steps warm up, 70 steps shrink the budget and 20 steps fine-tune.

Field names, their order, defaults and adapter_config.json are the reference adapter library's. Its LoraConfig fields that AdaLoRA does not use (use_rslora, use_dora, lora_bias, alpha_pattern …) and the ones this package lacks (eva_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
Not used by AdaLoRA (it warns when set): the initial rank is init_r.
target_modulesstr or list of str= None
The nn.Linear / nn.Conv2d modules to adapt, matched as LoraConfig.target_modules is. None takes the default for the base model's model_type — the LoRA table, as the reference does.
exclude_modulesstr | list[str] | set[str] | None= None
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
lora_alphafloat= 8
The numerator of the scale; the update is multiplied by lora_alpha / ranknum (ranknum being the initial rank). A value of 0 or below takes the rank itself, which makes the scale 1.
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.
biasnone= "none"
The reference also offers "all" and "lora_only"; here the adapter trains its own tensors only, and those raise NotImplementedError.
use_rslorabool= False
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
modules_to_savebool= False
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
init_lora_weightsbool= True
True: the singular values start at zero and the vectors are N(0,0.022)\mathcal{N}(0, 0.02^2), so the adapted model starts as the base. False: everything is N(0,1)\mathcal{N}(0, 1) (for tests).
layers_to_transformint | list[int] | None= None
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
layers_patternint | list[int] | None= None
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
rank_patterndict of str to list of bool= None
The triplets the allocator kept, per layer — "<module>.lora_E" to one flag per initial triplet. Filled in by training and saved with the adapter; the adapter's tensors are saved without the dropped ones.
alpha_patterndict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
megatron_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
megatron_coredict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
trainable_token_indicesdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
loftq_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
eva_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
corda_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
lora_ga_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
use_doradict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
velora_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
alora_invocation_tokensdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
use_qaloradict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
qalora_group_sizedict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
monteclora_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
layer_replicationdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
runtime_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
lora_biasdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
target_parametersdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
use_bdloradict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
arrow_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
kasa_configdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
ensure_weight_tyingdict[str, float]= dict()
As in lucid.peft.LoraConfig; fields AdaLoRA does not use are accepted at their defaults only.
target_rint= 8
The target average rank of the update: the budget the allocator shrinks to is target_r triplets per adapted layer.
init_rint= 12
The rank each layer starts with (its number of singular triplets).
tinitint= 0
Steps of initial fine-tuning before the budget starts to fall.
tfinalint= 0
Steps of final fine-tuning, after the budget has reached target_r.
deltaTint= 1
Steps between two budget allocations.
beta1float= 0.85
Weight of the previous value in the moving average that smooths a triplet's sensitivity; in (0, 1).
beta2float= 0.85
Weight of the previous value in the moving average that tracks the uncertainty of the sensitivity; in (0, 1).
orth_reg_weightfloat= 0.5
Coefficient of the orthogonality penalty added to the loss.
total_stepint= None
The number of training steps; required, and must exceed tinit + tfinal.

Raises

TypeError
A field holds a value of the wrong type.
ValueError
A field is out of range, total_step is missing, or the schedule leaves no room for the budget to fall (tinit >= total_step - tfinal).
NotImplementedError
bias is not "none".

Examples

>>> from lucid.peft.tuners.adalora import AdaLoraConfig
>>> config = AdaLoraConfig(init_r=12, target_r=4, total_step=100, target_modules=["q", "v"])
>>> sorted(config.target_modules), config.peft_type
(['q', 'v'], <PeftType.ADALORA: 'ADALORA'>)
>>> AdaLoraConfig.from_dict(config.to_dict()) == config
True

Used by 4

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')