PeftModelForTokenClassification
_TextForwardPeftModelForTokenClassification(model: nn.Module, peft_config: PeftConfig | None = None, adapter_name: str = 'default', kwargs: object = {})An adapted token classifier: the PeftModel for task_type="TOKEN_CLS".
As for lucid.peft.PeftModelForSequenceClassification, the
model's classifier / score head is trained in full beside the
adapter. With a prompt (prompt tuning, p-tuning) in front of the input, the
head reads the input's positions alone, so the logits and the labels are as
long as the input the caller gave.
Parameters
modelnn.Moduleadapter_ namestr= "default"**kwargsobject= {}autocast_adapter_dtype and low_cpu_mem_usage of
lucid.peft.PeftModel.Examples
>>> from collections import OrderedDict
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftModelForTokenClassification
>>> net = nn.Sequential(OrderedDict(body=nn.Linear(6, 6), score=nn.Linear(6, 9)))
>>> peft = PeftModelForTokenClassification(net, LoraConfig(r=2, target_modules=["body"]))
>>> peft.peft_config["default"].modules_to_save
['score']Used by 2
Constructors
1__init__
→None__init__(model: nn.Module, peft_config: PeftConfig | None = None, adapter_name: str = 'default', kwargs: object = {})Adapt model in place with peft_config and wrap it for token classification.
peft_config has a default only because the reference's signature does; leaving it
out raises TypeError.
Properties
7Name of the adapter in use (a list once delete_adapter leaves several or none).
The adapters in use, as a list.
active_peft_config: PeftConfigThe config of the adapter in use.
Raises
ValueErroractive_adapter is a list).The dtype of the base model: its first floating-point parameter's; None if it has none.
The reference spells this member with its framework's name; that spelling cannot appear in this library's source.
Whether the adapters are enabled — the reference's rule, as it computes it.
For a prompt-learning adapter: True unless inside disable_adapter(). For the other
methods the reference also answers True when no adapter is in use, so inside
disable_adapter() the answer is False only while an adapter is in use.
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 ("all-linear" spelled out).
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, autocast_adapter_dtype: bool = True, ephemeral_gpu_offload: bool = False, low_cpu_mem_usage: bool = False, key_mapping: Mapping[str, str] | None = None, subfolder: str | None = None, convert: ConvertMode = 'auto', kwargs: object = {})Adapt model with the adapter saved in model_id.
Reads adapter_config.json (unless config is given) and
adapter_model.safetensors — written by save_pretrained
or by the reference library — injects the adapter into model in
place and loads its tensors. The adapter is built without its
initialisation's effect on the base, so an adapter saved from a PiSSA
or OLoRA start loads onto the (rewritten) base it was trained beside
as it was trained, and a pristine base is left as it is. If the
tensors do not fit the model, the injection is undone before the error
is raised. The class
returned follows the config's task_type as in
lucid.peft.get_peft_model; only an adapter with no task
is built as cls.
Parameters
modelnn.Modulemodel_ idstr or os.PathLikeadapter_ namestr= "default"is_ trainablebool= Falseeval() mode, for inference.autocast_ adapter_ dtypebool= TrueFalse raises NotImplementedError.ephemeral_ gpu_ offloadbool= FalseTrue raises NotImplementedError.low_ cpu_ mem_ usagebool= FalseTrue raises
NotImplementedError.key_ mappingdict of str to str= Nonebase_model.model. prefix set aside, the first pattern (a regular expression)
that matches is replaced by its value, as the reference does. Applied before
convert.subfolderstr= Nonemodel_id that holds the adapter. (The reference takes
it among **kwargs; it is named here.)convertbool or auto= "auto"lucid.peft lists what each converter does):
gpt2 (the score head), roformer, t5 (renamed
modules) and vit (query / key / value fused into
qkv, LoRA only). "auto" converts when the model's type has
a converter and the file is in a layout it changes; True always
converts and refuses a type with none; False reads it as it is.**kwargsobject= {}revision, token,
cache_dir …). Any key raises NotImplementedError.Returns
PeftModelmodel, adapted and loaded — a task wrapper if the adapter
names a task.
Raises
FileNotFoundErroradapter_config.json or the weights.NotImplementedErroradapter_model.bin), the config
describes something lucid.peft does not implement, or an option the
library cannot honour is set (see the parameters).ValueErrormodel, or convert cannot apply.Examples
>>> import tempfile
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftModel, get_peft_model
>>> net = nn.Sequential(nn.Linear(4, 2))
>>> base_state = {k: v.clone() for k, v in net.state_dict().items()}
>>> trained = get_peft_model(net, LoraConfig(r=2, target_modules=["0"],
... init_lora_weights=False))
>>> x = lucid.randn(3, 4)
>>> with tempfile.TemporaryDirectory() as d:
... trained.save_pretrained(d)
... fresh = nn.Sequential(nn.Linear(4, 2))
... _ = fresh.load_state_dict(base_state)
... loaded = PeftModel.from_pretrained(fresh, d)
>>> bool(lucid.allclose(loaded(x), trained(x)))
TrueInstance methods
21add_adapter
→Nonefrom PeftModeladd_adapter(adapter_name: str, peft_config: PeftConfig, low_cpu_mem_usage: bool = False, autocast_adapter_dtype: bool = True)Add an adapter beside the ones the model holds.
The new adapter is initialised, not trained, and starts frozen and inactive: the model
computes what it computed, and every parameter keeps its requires_grad. Switch to it
with set_adapter. Modules an earlier adapter wraps take the new one beside it; a
classification or question-answering task_type adds the model's head to
modules_to_save as get_peft_model does. Merged layers stay merged, and the adapter
starts from their weights as they were before the merge.
Parameters
adapter_ namestrpeft_ configPeftConfiglow_ cpu_ mem_ usagebool= FalseTrue
raises NotImplementedError.autocast_ adapter_ dtypebool= TrueFalse raises NotImplementedError.Raises
ValueErrorbase_model.unmerge_adapter() first). The model is left as it was.NotImplementedErrorlow_cpu_mem_usage or autocast_adapter_dtype holds a value
the library cannot honour.Examples
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, get_peft_model
>>> net = nn.Sequential(nn.Linear(4, 4), nn.Linear(4, 2))
>>> peft = get_peft_model(net, LoraConfig(r=2, target_modules=["0"]))
>>> peft.add_adapter("second", LoraConfig(r=4, target_modules=["0", "1"]))
>>> peft.active_adapter, sorted(peft.peft_config)
('default', ['default', 'second'])
>>> peft.set_adapter("second")
>>> peft.get_base_model()[1].lora_A["second"].weight.shape
(4, 4)create_or_update_model_card
→Nonefrom PeftModelcreate_or_update_model_card(output_dir: str)Refused: the reference writes a hub model card, which this library has no use for.
Raises
NotImplementedErrorRemove an adapter, its config and its modules_to_save copies from the model.
If it was the one in use, the first of the others (by name) takes
over, with a warning. Deleting the last adapter leaves a model
that applies nothing; unload() takes the layers out.
Raises
ValueErrorRun the base model alone inside the with block.
LoRA updates are skipped (a merged layer is unmerged on entry, and
stays unmerged after) and every modules_to_save module runs as
the original; the adapter comes back when the block exits, even on
an exception. Blocks nest: the adapter stays off until the
outermost one exits. Merging inside the block is refused. A
compiled model follows the switch: the state it branches on is
part of its cache key.
Examples
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, get_peft_model
>>> net = nn.Sequential(nn.Linear(4, 4))
>>> x = lucid.randn(2, 4)
>>> base_out = net(x)
>>> peft = get_peft_model(net, LoraConfig(r=2, target_modules=["0"],
... init_lora_weights=False))
>>> with peft.disable_adapter():
... bool((peft(x) == base_out).all().item())
Trueforward
→objectfrom _TextForwardforward(input_ids: Tensor | None = None, attention_mask: Tensor | None = None, inputs_embeds: Tensor | None = None, labels: Tensor | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, task_ids: Tensor | None = None, kwargs: object = {})Run the adapted model; the arguments given go to it as they are.
Parameters
input_ids.output_ attentionsbool= Noneoutput_ hidden_ statesbool= Nonereturn_ dictbool= None(batch,)
integers in [0, num_tasks).**kwargsobject= {}forward, and adapter_names
as for lucid.peft.PeftModel.forward.Returns
objectWhat the model's forward returns.
Raises
TypeErrorforward has no parameter for an argument that was given.Generate with the adapted model: its own generate, called as given.
The adapter applies at every step, since the model's layers are
the adapted ones; with model.disable_adapter(): generates with
the base model alone.
Parameters
*argsobject= ()generate.**kwargsobject= {}generate, and two of the adapter's own:
adapter_names (sequence of str)
One adapter per prompt, as for forward: every step of prompt i
uses adapter_names[i] alone ("__base__": the base model). With beam
search (num_beams) each name covers that prompt's beams; an encoder, if
the model has one, sees the prompts once.
task_ids (Tensor)
For multitask prompt tuning: the task of each prompt of the batch, as for
forward.Returns
objectWhat the model's generate returns.
Raises
AttributeErrorgenerate.Return the adapted model itself — the one passed in, now holding adapter layers.
get_layer_status()The state of each adapter layer: see lucid.peft.get_layer_status.
get_model_status()The state of the model's adapters as a whole: see lucid.peft.get_model_status.
Return (trainable, total) parameter counts, each shared parameter once.
Returns
tuple of intElements in parameters that require grad, and in all of them.
get_prompt(batch_size: int, task_ids: Tensor | None = None, max_cache_len: int | None = None)The virtual prompt the model is given, for batch_size rows.
Only for a prompt-learning method. A method that goes in front of the input embeddings
gives the rows, (batch_size, rows, token_dim); a method that goes in the attention
(prefix tuning, Cartridge) gives a key/value cache holding the prefix, in the model's dtype,
that a decoder starts from (an encoder-decoder's carries the decoder's half).
Parameters
batch_ sizeint(batch_size,).max_ cache_ lenint= NoneNone raises NotImplementedError.Returns
Raises
TypeErrorNotImplementedErrormax_cache_len is given.Examples
>>> from lucid.models import create_model
>>> from lucid.peft import PromptTuningConfig, get_peft_model
>>> lm = create_model("gpt2_small_lm", vocab_size=32, hidden_size=16, num_hidden_layers=1,
... num_attention_heads=2, intermediate_size=32, max_position_embeddings=16)
>>> peft = get_peft_model(lm, PromptTuningConfig(num_virtual_tokens=3, task_type="CAUSAL_LM"))
>>> peft.get_prompt(batch_size=2).shape
(2, 3, 16)get_prompt_embedding_to_save(adapter_name: str)The adapter's prompt as save_pretrained writes it: (rows, width), on the CPU.
Only for a prompt-learning method. The rows are what the method's encoder makes of its virtual tokens — the finished prompt, whether the adapter trains through a projection or holds the rows directly.
Parameters
adapter_ namestrReturns
TensorOne row per virtual token.
Raises
TypeErrorValueErrorExamples
>>> from lucid.models import create_model
>>> from lucid.peft import PrefixTuningConfig, get_peft_model
>>> lm = create_model("gpt2_small_lm", vocab_size=32, hidden_size=8, num_hidden_layers=1,
... num_attention_heads=2, intermediate_size=16, max_position_embeddings=16)
>>> prefix = PrefixTuningConfig(num_virtual_tokens=2, task_type="CAUSAL_LM")
>>> get_peft_model(lm, prefix).get_prompt_embedding_to_save("default").shape
(2, 16)load_adapter
→_IncompatibleKeysfrom PeftModelload_adapter(model_id: str | os.PathLike[str], adapter_name: str, is_trainable: bool = False, device: str | None = None, autocast_adapter_dtype: bool = True, ephemeral_gpu_offload: bool = False, low_cpu_mem_usage: bool = False, key_mapping: Mapping[str, str] | None = None, subfolder: str | None = None, convert: ConvertMode = 'auto', 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; the weights of one the model
already holds replace the values it has. The loaded adapter is not
made the one in use — set_adapter does that. Nothing changes
if the files are missing or their tensors do not fit.
Parameters
model_ idstr or os.PathLikeadapter_config.json
and adapter_model.safetensors; for an adapter saved by
save_pretrained beside others, that is its sub-directory.adapter_ namestris_ trainablebool= Falseeval() mode, for inference.devicestr= Noneautocast_ adapter_ dtypebool= TrueFalse raises NotImplementedError.ephemeral_ gpu_ offloadbool= FalseTrue raises NotImplementedError.low_ cpu_ mem_ usagebool= FalseTrue raises
NotImplementedError.key_ mappingdict of str to str= Nonefrom_pretrained.subfolderstr= Nonemodel_id that holds the adapter. (The reference takes
it among **kwargs; it is named here.)convertbool or auto= "auto"from_pretrained: convert an adapter written for the
reference library's model to the zoo model's layout.**kwargsobject= {}ignore_mismatched_sizes is accepted at its default False; any other key
raises NotImplementedError.Returns
_IncompatibleKeysWhat model.load_state_dict(..., strict=False) returned, as
set_peft_model_state_dict hands it back.
Raises
FileNotFoundErroradapter_config.json or the weights.NotImplementedErrorValueErrorExamples
>>> import tempfile
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, PeftModel, get_peft_model
>>> config = LoraConfig(r=2, target_modules=["0"])
>>> source = get_peft_model(nn.Sequential(nn.Linear(4, 2)), config)
>>> mine = get_peft_model(nn.Sequential(nn.Linear(4, 2)), config)
>>> with tempfile.TemporaryDirectory() as d:
... source.save_pretrained(d)
... _ = mine.load_adapter(d, "loaded")
>>> sorted(mine.peft_config), mine.active_adapter
(['default', 'loaded'], 'default')merge_and_unload(progressbar: bool = False, safe_merge: bool = False, adapter_names: list[str] | None = None)Fold the adapter(s) into the base model and hand the base model back.
For deployment: the result runs at the base model's cost and saves, exports and compiles as an ordinary model. This wrapper is spent afterwards, and adapters that were not folded in are gone with it.
Parameters
progressbarbool= Falsesafe_ mergebool= Falseadapter_ nameslist of str= NoneReturns
nn.Moduleget_base_model(), with plain nn.Linear layers again.
Raises
RuntimeErrormodules_to_save module was trained apart from a tie.Examples
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, get_peft_model
>>> peft = get_peft_model(nn.Sequential(nn.Linear(4, 2)),
... LoraConfig(r=2, target_modules=["0"], init_lora_weights=False))
>>> x = lucid.randn(3, 4)
>>> adapted = peft(x)
>>> plain = peft.merge_and_unload()
>>> type(plain[0]) is nn.Linear, bool(lucid.allclose(plain(x), adapted, atol=1e-5))
(True, True)prepare_model_for_gradient_checkpointing(model: nn.Module)Make a model's embedding output require a gradient, so a checkpointed stack trains.
What use_reentrant=True checkpointing needs when the embeddings are frozen: the segment
has an input that requires a gradient. A model with enable_input_require_grads is asked
to; otherwise a forward hook on its input embeddings (or, with none, a pre-hook on the model
itself) marks the first floating-point tensor. A quantized model is left as it is. Unlike
the reference, the constructor does not call this: no Lucid model reports
is_gradient_checkpointing, and the default use_reentrant=False needs nothing.
Parameters
modelnn.ModuleReturns
nn.Modulemodel, prepared.
Examples
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, get_peft_model
>>> net = nn.Sequential(nn.Embedding(10, 4), nn.Linear(4, 4))
>>> peft = get_peft_model(net, LoraConfig(r=2, target_modules=["1"]))
>>> peft.prepare_model_for_gradient_checkpointing(net) is net
TruePrint the trainable / total parameter counts and their ratio.
Examples
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, get_peft_model
>>> peft = get_peft_model(nn.Sequential(nn.Linear(8, 8)),
... LoraConfig(r=2, target_modules=["0"]))
>>> peft.print_trainable_parameters()
trainable params: 32 || all params: 104 || trainable%: 30.7692save_pretrained
→Nonefrom PeftModelsave_pretrained(save_directory: str | os.PathLike[str], safe_serialization: bool = True, selected_adapters: list[str] | None = None, save_embedding_layers: bool | Literal['auto'] = 'auto', is_main_process: bool = True, path_initial_model_for_weight_conversion: str | os.PathLike[str] | None = None, kwargs: object = {})Write the adapters — not the base model — under save_directory.
Per adapter, the reference library's two files:
adapter_config.json (with inference_mode set, as the
reference stores it, and the base model's class as auto_mapping)
and adapter_model.safetensors, keyed by
lucid.peft.get_peft_model_state_dict. The adapter named
"default" goes into save_directory itself, every other into
a sub-directory of its own name, as the reference lays it out; an
adapter is read back from the directory that holds its two files
(PeftModel.from_pretrained / load_adapter).
Parameters
save_ directorystr or os.PathLikesafe_ serializationbool= TrueTrue: the pickle format the reference writes for
False is not one Lucid can produce.selected_ adapterslist of str= Nonesave_ embedding_ layersbool or auto= "auto"modules_to_save), so "auto" and False write that; True raises
NotImplementedError.is_ main_ processbool= TrueFalse writes nothing, for the processes of a distributed run that are not the
main one.path_ initial_ model_ for_ weight_ conversionstr or os.PathLike= None"pissa", "pissa_niter_<k>"
or "olora", which rewrote the base weight: the directory
where save_pretrained wrote that adapter right after
initialisation, before any training. The adapter is written
converted to a plain LoRA of twice the rank
(, init_lora_weights=True),
which loads onto the original, unmodified base model and sits
beside other adapters. It converts one adapter, so pass
selected_adapters if the model holds several; the directory
is only read.**kwargsobject= {}NotImplementedError.Raises
NotImplementedErrorsafe_serialization=False, save_embedding_layers=True, or a key in kwargs.ValueErrorselected_adapters names an adapter the model lacks, or
path_initial_model_for_weight_conversion is given with
several adapters to write, for a method other than LoRA, for a
DoRA adapter, for use_rslora with a rank or alpha pattern,
or the directory's adapter does not match the trained one.FileNotFoundErrorpath_initial_model_for_weight_conversion holds no adapter.RuntimeErrorNotADirectoryErrorsave_directory names an existing file.Examples
>>> import tempfile, os
>>> import lucid.nn as nn
>>> from lucid.peft import LoraConfig, get_peft_model
>>> peft = get_peft_model(nn.Sequential(nn.Linear(4, 2)),
... LoraConfig(r=2, target_modules=["0"]))
>>> peft.add_adapter("style", LoraConfig(r=2, target_modules=["0"]))
>>> with tempfile.TemporaryDirectory() as d:
... peft.save_pretrained(d)
... sorted(os.listdir(d)), sorted(os.listdir(os.path.join(d, "style")))
(['adapter_config.json', 'adapter_model.safetensors', 'style'], ['adapter_config.json', 'adapter_model.safetensors'])set_adapter
→Nonefrom PeftModelset_adapter(adapter_name: str, inference_mode: bool = False)Make adapter_name the adapter in use.
Only the one adapter applies. It trains, and every other adapter is
frozen, unless inference_mode. A merged model is unmerged
first; layers that hold nothing of the adapter run their base alone.
Parameters
adapter_ namestrinference_ modebool= FalseRaises
ValueErrorset_requires_grad
→Nonefrom PeftModelset_requires_grad(adapter_names: str | Sequence[str], requires_grad: bool = True)Enable or disable gradients on the named adapter(s), leaving the rest as they are.
Parameters
adapter_ namesstr or sequence of strrequires_ gradbool= TrueRaises
ValueErrorsupports_lora_conversion
→boolfrom PeftModelsupports_lora_conversion(adapter_name: str = 'default')Whether the adapter adapter_name on this model can be converted to LoRA.
Remove the adapter without merging and return the original model.
Returns
nn.ModuleThe model, each adapter layer replaced by the module it wrapped.