PeftMixedModel
_AdaptedModelPeftMixedModel(model: nn.Module, peft_config: PeftConfig, adapter_name: str = 'default')A model holding the adapters of several methods at once, loaded from files and not saved.
The first adapter of a method puts that method's layer on each module it targets; the layers of
other methods stand on it, so the forward pass runs them lowest first. The tuner is a
lucid.peft.tuners.MixedModel, kept as base_model (the user's model is
base_model.model), and the state dict reads base_model.model.... as a
lucid.peft.PeftModel's does. Calling it runs the wrapped model, and any public name
it lacks is read from that model, so code written for the bare model keeps working.
It is not a PeftModel: there is no task wrapper, no adapter_names routing of a batch
and no save_pretrained. An adapter is written by the PeftModel of its own method
and read here with load_adapter or from_pretrained, which fill it from the
single-method file, before or after the layers of other methods are stacked on it. The
reference's mixed model writes nothing either, and says so with the same NotImplementedError.
The methods that can be mixed are the keys of
PEFT_TYPE_TO_MIXED_MODEL_MAPPING; any other is refused with ValueError where it is
added. Adding an adapter that cannot sit where it would land raises
ValueError and leaves the model as it was. AdaLoRA takes part for inference only.
Parameters
modelnn.Modulepeft_ configPeftConfigadapter_ namestr= "default"Raises
TypeErrorpeft_config is not an adapter config.ValueErrorExamples
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoHaConfig, LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(8, 8), nn.ReLU(), nn.Linear(8, 2))
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"]), "lora")
>>> mixed.add_adapter("loha", LoHaConfig(r=2, target_modules=["0"]))
>>> mixed.set_adapter(["lora", "loha"])
>>> mixed.active_adapters
['lora', 'loha']
>>> mixed(lucid.randn(4, 8)).shape
(4, 2)Used by 2
Constructors
1Properties
4Name of the adapter in use (a list once several are).
The adapters in use, as a list.
The names of the modules trained in full beside the adapters, over every adapter; None if there are none.
peft_config: dict[str, PeftConfig]Each adapter's config by adapter name.
Class methods
1from_pretrained(model: nn.Module, model_id: str | os.PathLike[str], adapter_name: str = 'default', is_trainable: bool = False, config: PeftConfig | None = None, kwargs: object = {})Adapt model with the adapter saved in model_id, ready to take the adapters of other methods.
Reads adapter_config.json (unless config is given) and adapter_model.safetensors
— what a single-method lucid.peft.PeftModel.save_pretrained wrote — injects the
adapter into model in place and loads its tensors; if they do not fit, the injection is
undone before the error is raised. Only a method of PEFT_TYPE_TO_MIXED_MODEL_MAPPING can
be loaded.
Parameters
modelnn.Modulemodel_ idstr or os.PathLikeadapter_ namestr= "default"is_ trainablebool= Falseeval()
mode, for inference.**kwargsobject= {}subfolder, convert, key_mapping and the other options of
load_adapter, by name, as for lucid.peft.PeftModel.from_pretrained.Returns
PeftMixedModelmodel, adapted and loaded.
Raises
FileNotFoundErroradapter_config.json or the weights.NotImplementedErrorTypeErrorconfig is not an adapter config, or an option is of the wrong type.ValueErrormodel.Examples
>>> import tempfile
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftMixedModel, get_peft_model
>>> def base():
... lucid.manual_seed(0)
... return nn.Sequential(nn.Linear(4, 2))
>>> config = LoraConfig(r=2, target_modules=["0"], init_lora_weights=False)
>>> trained = get_peft_model(base(), config)
>>> x = lucid.randn(3, 4)
>>> with tempfile.TemporaryDirectory() as d:
... trained.save_pretrained(d)
... loaded = PeftMixedModel.from_pretrained(base(), d)
>>> bool(lucid.allclose(loaded(x), trained(x)))
TrueInstance methods
16add_adapter
→Noneadd_adapter(adapter_name: str, peft_config: PeftConfig, low_cpu_mem_usage: bool = False, autocast_adapter_dtype: bool = True)Add an adapter, of any mixable method, beside the ones the model holds.
The new adapter starts frozen and inactive; set_adapter switches to it. A module that
a method already adapts takes this adapter in that method's layer, and a module another
method adapted gets this method's layer stacked on top. A merged stack stays merged; the
new adapter reads the weight beneath every layer of it.
Parameters
adapter_ namestrpeft_ configPeftConfiglow_ cpu_ mem_ usagebool= FalseTrue raises NotImplementedError.autocast_ adapter_ dtypebool= TrueFalse
raises NotImplementedError.Raises
ValueErrorNotImplementedErrorlow_cpu_mem_usage or autocast_adapter_dtype holds a value the library cannot
honour.Examples
>>> import lucid.nn as nn
>>> from lucid.peft import LoHaConfig, LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(4, 4), nn.Linear(4, 2))
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"]), "lora")
>>> mixed.add_adapter("loha", LoHaConfig(r=2, target_modules=["0", "1"]))
>>> sorted(mixed.peft_config)
['loha', 'lora']Refused: the reference writes a hub model card, which this library has no use for.
Raises
NotImplementedErrorRemove the named adapter(s), their configs and their layers' tables.
Every name is checked before the first is removed, so a refusal leaves the model as it was. If an adapter in use is removed and none remains in use, the first of the others (by name) takes over, with a warning.
Parameters
adapter_ namestr or list of strRaises
ValueErrorRun the base model alone inside the with block, whatever stack of adapters is in use.
The adapters come back when the block exits, even on an exception. Blocks nest: they stay off until the outermost one exits.
Examples
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(4, 4))
>>> x = lucid.randn(2, 4)
>>> base_out = net(x)
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"],
... init_lora_weights=False))
>>> with mixed.disable_adapter():
... bool((mixed(x) == base_out).all().item())
TrueRun the adapted model; every argument goes to it as given.
Parameters
*argsobject= ()forward.**kwargsobject= {}forward. Unlike
lucid.peft.PeftModel.forward there is no adapter_names here.Returns
objectWhat the model's forward returns.
Generate with the adapted model: its own generate, called as given.
Parameters
*argsobject= ()generate.**kwargsobject= {}generate.Returns
objectWhat the model's generate returns.
Raises
AttributeErrorgenerate.Not supported: the status of a layer is read off one method's tuner.
Raises
TypeErrorNot supported: the status of a model is read off one method's tuner.
Raises
TypeErrorReturn (trainable, total) parameter counts, each shared parameter once.
Returns
tuple of intElements in parameters that require grad, and in all of them.
load_adapter
→_IncompatibleKeysload_adapter(model_id: str | os.PathLike[str], adapter_name: str, args: object = (), kwargs: object = {})Load a saved adapter into the model, beside the ones it holds.
An adapter the model does not hold is added from the directory's config and filled from its
weights, stacked on the modules it targets; the weights of one the model already holds
replace the values it has. The directory holds what a single-method
lucid.peft.PeftModel.save_pretrained wrote, and loads before or after other
methods' layers are stacked on its modules. The loaded adapter is not made the one in use
— set_adapter does that. Nothing changes if the files are missing or do not fit.
Parameters
model_ idstr or os.PathLikeadapter_config.json and
adapter_model.safetensors.adapter_ namestr*argsobject= ()is_trainable, device, autocast_adapter_dtype,
ephemeral_gpu_offload, low_cpu_mem_usage, key_mapping — as for
lucid.peft.PeftModel.load_adapter.**kwargsobject= {}subfolder, convert and ignore_mismatched_sizes, as for
lucid.peft.PeftModel.load_adapter; any other key raises
NotImplementedError (the reference's hub options).Returns
_IncompatibleKeysWhat set_peft_model_state_dict hands back.
Raises
FileNotFoundErroradapter_config.json or the weights.NotImplementedErrorTypeErrorValueErrorExamples
>>> import tempfile
>>> import lucid.nn as nn
>>> from lucid.peft import LoHaConfig, LoraConfig, PeftMixedModel, get_peft_model
>>> source = get_peft_model(nn.Sequential(nn.Linear(4, 2)), LoHaConfig(r=2, target_modules=["0"]))
>>> mixed = PeftMixedModel(nn.Sequential(nn.Linear(4, 2)), LoraConfig(r=2, target_modules=["0"]), "lora")
>>> with tempfile.TemporaryDirectory() as d:
... source.save_pretrained(d)
... _ = mixed.load_adapter(d, "loha")
>>> sorted(mixed.peft_config), mixed.active_adapter
(['loha', 'lora'], 'lora')Fold the adapters into the base model and hand the base model back.
Each module's layers are folded lowest first, and the adapters that were not folded in are gone with their layers. A merge that would fold a layer's update under a layer that transforms it differently is refused before any weight is written.
Parameters
*argsobject= ()progressbar, safe_merge and adapter_names, positionally and in that order.**kwargsobject= {}progressbar is kept for call compatibility and ignored;
safe_merge refuses, before changing any weight, a merged weight holding NaN or
inf; adapter_names (a list of str) picks the adapters to fold in, the ones in use
by default.Returns
nn.ModuleThe base model, with its plain layers again.
Raises
TypeErrorValueErrorExamples
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoHaConfig, LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(4, 4))
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"],
... init_lora_weights=False), "lora")
>>> mixed.add_adapter("loha", LoHaConfig(r=2, target_modules=["0"]))
>>> mixed.set_adapter(["lora", "loha"])
>>> x = lucid.randn(3, 4)
>>> stacked = mixed(x)
>>> plain = mixed.merge_and_unload()
>>> type(plain[0]) is nn.Linear, bool(lucid.allclose(plain(x), stacked, atol=1e-5))
(True, True)Print the trainable / total parameter counts and their ratio.
Examples
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftMixedModel
>>> mixed = PeftMixedModel(nn.Sequential(nn.Linear(8, 8)),
... LoraConfig(r=2, target_modules=["0"]))
>>> mixed.print_trainable_parameters()
trainable params: 32 || all params: 104 || trainable%: 30.7692save_pretrained
→Nonesave_pretrained(save_directory: str | os.PathLike[str], safe_serialization: bool = False, selected_adapters: list[str] | None = None, kwargs: object = {})Refused: a mixed model is not saved, as the reference's is not.
Write each adapter from a lucid.peft.PeftModel of its own method; the file is
read back here by load_adapter.
Parameters
save_ directorystr or os.PathLikesafe_ serializationbool= Falseselected_ adapterslist of str= None**kwargsobject= {}Raises
NotImplementedErrorset_adapter
→Noneset_adapter(adapter_name: str | list[str], inference_mode: bool = False)Make the named adapter(s), of any methods, the ones in use.
Each layer applies those of the names it holds and passes its input through otherwise;
the named adapters train, and every other adapter is frozen, unless inference_mode.
A merged model is unmerged first.
Parameters
adapter_ namestr or list of strinference_ modebool= FalseRaises
ValueErrorCheck that the modules peft_config trains in full are held by adapter_name.
The reference wraps those modules after its tuner has built the adapter. Here the tuner
wraps them as the adapter goes in, so by the time adapter_name exists its modules are
wrapped, and this method confirms it: it changes nothing. The modules_to_save of an
adapter cannot be widened afterwards; add the adapter with a config that names them.
Parameters
peft_ configPeftConfigpeft_config[adapter_name].adapter_ namestrRaises
ValueErrorExamples
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftMixedModel
>>> net = nn.Sequential(nn.Linear(4, 4), nn.Linear(4, 2))
>>> mixed = PeftMixedModel(net, LoraConfig(r=2, target_modules=["0"], modules_to_save=["1"]))
>>> mixed.set_modules_to_save(mixed.peft_config["default"], "default")
>>> mixed.modules_to_save
{'1'}Remove every adapter without merging and return the original model.
Parameters
*argsobject= ()TypeError.**kwargsobject= {}args.Returns
nn.ModuleThe model, each adapter layer replaced by the module it stood on.
Raises
TypeError