ModulesToSaveWrapper
_ForwardsAttributesModulesToSaveWrapper(module_to_save: nn.Module, adapter_name: str)Hold module beside a trained copy per adapter; the active adapter's copy runs.
Building one changes nothing about module — the tuner builds them
while it is still planning, and a plan that fails must leave the model
as it was. Which of the copies train is the tuner's freezing step. It
answers the tuner's _AdapterSlot protocol, as a tuner layer does.
At most one adapter is active here: two copies of one module would have
no rule for whose weights the forward pass uses. active_adapter is
the active adapter that has a copy, or "" when none does, in which
case the original runs.
get_peft_model(..., modules_to_save=[...]) puts one of these where each
named module was, so isinstance(m, ModulesToSaveWrapper) finds them in an
adapted model. The module as the base model had it is original_module,
and the trained copies are in the modules_to_save dict, keyed by adapter.
Parameters
module_ to_ savenn.Moduleadapter_ namestrmodules_to_save.Examples
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, ModulesToSaveWrapper, get_peft_model
>>> net = nn.Sequential(nn.Linear(4, 4), nn.Linear(4, 2))
>>> config = LoraConfig(r=2, target_modules=["0"], modules_to_save=["1"])
>>> _ = get_peft_model(net, config)
>>> head = net[1]
>>> isinstance(head, ModulesToSaveWrapper), head.active_adapter
(True, 'default')
>>> head.get_base_layer() is head.original_module, list(head.modules_to_save)
(True, ['default'])Used by 8
Constructors
1Instance methods
8Drop adapter_name's copy; if it was the active one the original runs.
Run the trained copy (True) or the original module (False).
The active adapter and whether adapters are disabled.
Run the active adapter's copy of the module.
The original runs when no adapter is active or adapters are disabled.
Return the original module, the one the base model had.
set_adapter
→Noneset_adapter(adapter_names: str | list[str], inference_mode: bool = False)Run the named adapter's copy, and train it unless inference_mode.
The names this module has no copy for are skipped: it runs the original while only such adapters are active.
Parameters
adapter_ namesstr or list of strinference_ modebool= FalseRaises
ValueErrorset_requires_grad
→Noneset_requires_grad(adapter_names: str | Sequence[str], requires_grad: bool = True)Set requires_grad on the copies of the named adapters.
Give adapter_name a trained copy of the original, if it has none yet.