Skip to content
class

PeftModelForTokenClassification

extends_TextForward
PeftModelForTokenClassification(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

The model to adapt, changed in place.
peft_configPeftConfig= None
What to adapt and how; required, though the reference's signature gives it a default.
adapter_namestr= "default"
Name of the adapter.
**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
dunder

__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

7
prop

active_adapter

→str | list[str]from PeftModel
active_adapter: str | list[str]

Name of the adapter in use (a list once delete_adapter leaves several or none).

prop

active_adapters

→list[str]from PeftModel
active_adapters: list[str]

The adapters in use, as a list.

prop

active_peft_config

→PeftConfigfrom PeftModel
active_peft_config: PeftConfig

The config of the adapter in use.

Raises

ValueError
No adapter is in use, or several are (active_adapter is a list).
prop

base_model_dtype

→lucid.dtype | Nonefrom PeftModel
base_model_dtype: lucid.dtype | None

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.

prop

has_active_enabled_adapter

→boolfrom PeftModel
has_active_enabled_adapter: bool

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.

prop

modules_to_save

→set[str] | Nonefrom PeftModel
modules_to_save: set[str] | None

The names of the modules trained in full beside the adapters, over every adapter; None if there are none.

prop

peft_config

→dict[str, PeftConfig]from PeftModel
peft_config: dict[str, PeftConfig]

Each adapter's config by adapter name ("all-linear" spelled out).

Class methods

1
cls

from_pretrained

→PeftModelfrom PeftModel
from_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

The base model the adapter was trained on.
model_idstr or os.PathLike
A local adapter directory. Hub ids are not resolved.
adapter_namestr= "default"
Name to give the adapter.
is_trainablebool= False
Keep the adapter trainable. By default it is frozen and the model is put in eval() mode, for inference.
configPeftConfig= None
Use this config instead of the directory's.
autocast_adapter_dtypebool= True
Cast a half-precision base's adapter weights to float32. Always the case here; False raises NotImplementedError.
ephemeral_gpu_offloadbool= False
Not implemented: True raises NotImplementedError.
low_cpu_mem_usagebool= False
Build the adapter on the meta device. Not implemented: True raises NotImplementedError.
key_mappingdict of str to str= None
Renames the adapter file's keys before they are loaded: for each key, with its base_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= None
The directory under model_id that holds the adapter. (The reference takes it among **kwargs; it is named here.)
convertbool or auto= "auto"
Convert an adapter written for the reference library's model to the zoo model's layout (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= {}
The reference forwards these to its hub download (revision, token, cache_dir …). Any key raises NotImplementedError.

Returns

PeftModel

model, adapted and loaded — a task wrapper if the adapter names a task.

Raises

FileNotFoundError
The directory lacks adapter_config.json or the weights.
NotImplementedError
The weights are a pickle (adapter_model.bin), the config describes something lucid.peft does not implement, or an option the library cannot honour is set (see the parameters).
ValueError
The adapter's tensors do not fit model, 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)))
True

Instance methods

21