OFTConfig
_TargetedConfigOFTConfig(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 = 0, oft_block_size: int = 32, module_dropout: float = 0.0, target_modules: str | list[str] | set[str] | None = None, fan_in_fan_out: bool = False, bias: Literal['none', 'all', 'oft_only'] = 'none', exclude_modules: str | list[str] | set[str] | None = None, init_weights: bool = True, layers_to_transform: int | list[int] | None = None, layers_pattern: str | list[str] | None = None, modules_to_save: list[str] | None = None, coft: bool = False, eps: float = 6e-05, block_share: bool = False, use_cayley_neumann: bool = True, num_cayley_neumann_terms: int = 5)How lucid.peft.get_peft_model adapts a model with OFT.
OFT (Qiu et al., 2023, arXiv:2306.07280 — Orthogonal Finetuning) rotates the input space of each targeted layer instead of adding to its weight: with block-diagonal, each block an orthogonal matrix of a learned skew-symmetric . A rotation keeps the pairwise angles between the weight's neurons, which is what OFT tunes while the weight's spectrum stays. The s start at zero, so the adapted model starts as the base; the rotation folds into the weight, so a merged model costs what the base does.
Field names, their order, defaults and adapter_config.json are the reference
adapter library's.
Parameters
lucid.peft.PeftConfig.lucid.peft.PeftConfig.lucid.peft.PeftConfig.lucid.peft.PeftConfig.lucid.peft.PeftConfig.lucid.peft.PeftConfig.lucid.peft.PeftConfig.rint= 0r and
oft_block_size (their product is the layer's input size): the default
r=0 leaves the choice to oft_block_size.oft_ block_ sizeint= 32oft_block_size=0 when you set r. A size
that does not divide a layer's input size is moved to the nearest one that
does, with a warning.module_ dropoutfloat= 0.0target_ modulesstr or list of str= Nonenn.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).fan_ in_ fan_ outbool= False(in, out). nn.Linear does not,
so True warns and is reset to False.biasnone= "none""all" and "oft_only"; here the adapter
trains its own tensors only, and those raise NotImplementedError.exclude_ modulesstr or list of str= Nonetarget_modules.init_ weightsbool= TrueTrue: every starts at zero (the update is the identity).
False: (for tests).layers_ to_ transformint or list of int= Nonelucid.peft.LoraConfig.layers_ patternstr or list of str= Nonelucid.peft.LoraConfig.modules_ to_ savelist of str= Nonelucid.peft.LoraConfig.coftbool= Falseeps around zero every time the rotation is computed.epsfloat= 6e-5coft is set.block_ sharebool= Falseuse_ cayley_ neumannbool= Truenum_ cayley_ neumann_ termsint= 5Raises
TypeErrorValueErrorr and oft_block_size are both set or both zero.NotImplementedErrorbias is not "none".Examples
>>> from lucid.peft import OFTConfig
>>> config = OFTConfig(oft_block_size=16, target_modules=["q_proj", "v_proj"])
>>> sorted(config.target_modules), config.peft_type
(['q_proj', 'v_proj'], <PeftType.OFT: 'OFT'>)
>>> OFTConfig.from_dict(config.to_dict()) == config
True
>>> OFTConfig(r=4, oft_block_size=0, target_modules=["x"]).r
4Used by 3
Properties
2Class methods
5Refuse an adapter file written for the OFT the reference had before 0.14.0, and warn about one from before 0.18.0.
The reference changed OFT in 0.14.0 (oft_block_size replaced the block count as
the way to size the blocks) and its Cayley-Neumann form in 0.18.0. A file with no
oft_block_size holds weights of the old OFT; one with use_cayley_neumann
set and a peft_version older than 0.18.0 holds the old form.
lucid.peft.PeftConfig.from_pretrained calls this on an OFT file.
A file with no peft_version is not warned about, where the reference reads a missing
version as 0.0.0. This library writes none and use_cayley_neumann defaults to set, so
the reference's rule would warn on every file this library saved. The cost is that a
reference file older than 0.18.0, which holds no version either (the reference added the
key in 0.18.0), loads without the warning.
Parameters
**kwargsobject= {}Returns
dict of str to objectkwargs itself, as the base's does.
Raises
ValueErrorkwargs has no oft_block_size, or, with use_cayley_neumann set, its
peft_version is not a version.TypeErroruse_cayley_neumann is set and peft_version is neither a string nor None.Examples
>>> from lucid.peft import OFTConfig
>>> OFTConfig.check_kwargs(oft_block_size=32, peft_version="0.18.0")
{'oft_block_size': 32, 'peft_version': '0.18.0'}
>>> OFTConfig.check_kwargs(r=8)
Traceback (most recent call last):
...
ValueError: OFT has been updated since version 0.14.0 of the reference adapter library: ...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 objectReturns
PeftConfigThe validated config, of the class the dict's method names.
Raises
KeyErrorpeft_type names no method of this library.NotImplementedErrorExamples
>>> 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'from_json_file
→dict of str to objectfrom PeftConfigfrom_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.PathLikeadapter_config.json.**kwargsobject= {}Returns
dict of str to objectThe 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
FileNotFoundErrorpath_json_file.ValueErrorNotImplementedErrorkwargs 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)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= {}peft_type is a PeftType or its string.Returns
PeftConfigThe validated config, of the class peft_type names.
Raises
KeyErrorpeft_type names no method of this library.TypeErrorpeft_type is given and this is PeftConfig itself, which builds no config of its own.NotImplementedErrorExamples
>>> 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
2from_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.PathLikeadapter_config.json — one written by
save_pretrained or by the reference library. Hub ids
are not resolved; download the adapter first.subfolderstr= Nonepretrained_model_name_or_path that holds
the file, e.g. the sub-directory save_pretrained gives each
adapter but the one named "default".**kwargsobject= {}revision,
token, cache_dir …). Adapters are read from a local
directory, so any key given here raises.Returns
PeftConfigThe config, read through from_dict, of the class the file's peft_type names.
Raises
FileNotFoundErroradapter_config.json.ValueErrorcheck_kwargs refuses it
(an OFT file of the reference's before 0.14.0).KeyErrorpeft_type names no method of this library.NotImplementedErrorkwargs 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
2save_pretrained
→Nonefrom PeftConfigsave_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**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
NotADirectoryErrorsave_directory names an existing file.NotImplementedErrorkwargs 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
2Return 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 objectOne 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')