Skip to content
class

MultiheadAttention

extends_WeightSpace[tuple[Tensor, Tensor | None]]
MultiheadAttention(base_layer: nn.Module, adapter_name: str, r: int = 0, lora_alpha: float = 1, lora_dropout: float = 0.0, init_lora_weights: bool | str = True, use_rslora: bool = False, use_dora: bool = False, lora_bias: bool = False, arrow_config: ArrowConfig | None = None)

An nn.MultiheadAttention with LoRA on its input and output projections.

The attention holds its projections as raw parameters and reads them inside its forward, so the adapter is a change of those weights (see _WeightSpace). There is no way to adapt one projection alone: each adapter has a pair of factors for every weight.

  • With one fused input projection (kdim and vdim equal to embed_dim, no grouped key/value heads) the weights are in_proj_weight (3E,E)(3E, E) — lora_A (r,E)(r, E), lora_B (3E,r)(3E, r) — and out_proj_weight (E,E)(E, E) — out_proj_lora_A (r,E)(r, E), out_proj_lora_B (E,r)(E, r).
  • With separate projections (kdim or vdim apart from embed_dim, as in a cross-attention over a context of another width, or grouped key/value heads) the query, key and value weights each have a pair: q_proj_lora_* (r,E)(r, E) / (E,r)(E, r), k_proj_lora_* (r,Ek)(r, E_k) / (Ekv,r)(E_{kv}, r) and v_proj_lora_* likewise, beside the output projection's. The reference refuses this layout; constructing the layer on such an attention returns the layout's own subclass, which is still a MultiheadAttention.

In an adapter file the tables that the reference would nest under a module are keyed as it keys them, ....base_layer.out_proj.lora_A.weight. The attention's public attributes (embed_dim, num_heads, batch_first, in_proj_weight …) read through to the wrapped module. lora_dropout is not applied: the update is folded into the weights, with no activations to drop.

Parameters

The attention to adapt; kept as base_layer, its parameters shared.
adapter_namestr
Name of the adapter, the key in every factor table.
rint= 0
The adapter's hyper-parameters, as LoraLayer.update_layer takes them; r must be positive. lora_dropout is accepted but the update is folded into the weights, so there is nothing to drop (a nonzero value warns). use_dora and lora_bias are refused (the reference does not support DoRA here either), as are the initialisations that factorise a weight.
lora_alphaint= 0
The adapter's hyper-parameters, as LoraLayer.update_layer takes them; r must be positive. lora_dropout is accepted but the update is folded into the weights, so there is nothing to drop (a nonzero value warns). use_dora and lora_bias are refused (the reference does not support DoRA here either), as are the initialisations that factorise a weight.
lora_dropoutint= 0
The adapter's hyper-parameters, as LoraLayer.update_layer takes them; r must be positive. lora_dropout is accepted but the update is folded into the weights, so there is nothing to drop (a nonzero value warns). use_dora and lora_bias are refused (the reference does not support DoRA here either), as are the initialisations that factorise a weight.
init_lora_weightsint= 0
The adapter's hyper-parameters, as LoraLayer.update_layer takes them; r must be positive. lora_dropout is accepted but the update is folded into the weights, so there is nothing to drop (a nonzero value warns). use_dora and lora_bias are refused (the reference does not support DoRA here either), as are the initialisations that factorise a weight.
use_rsloraint= 0
The adapter's hyper-parameters, as LoraLayer.update_layer takes them; r must be positive. lora_dropout is accepted but the update is folded into the weights, so there is nothing to drop (a nonzero value warns). use_dora and lora_bias are refused (the reference does not support DoRA here either), as are the initialisations that factorise a weight.
use_doraint= 0
The adapter's hyper-parameters, as LoraLayer.update_layer takes them; r must be positive. lora_dropout is accepted but the update is folded into the weights, so there is nothing to drop (a nonzero value warns). use_dora and lora_bias are refused (the reference does not support DoRA here either), as are the initialisations that factorise a weight.
lora_biasint= 0
The adapter's hyper-parameters, as LoraLayer.update_layer takes them; r must be positive. lora_dropout is accepted but the update is folded into the weights, so there is nothing to drop (a nonzero value warns). use_dora and lora_bias are refused (the reference does not support DoRA here either), as are the initialisations that factorise a weight.

Raises

ValueError
r is not positive.

Examples

>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft.tuners.lora import MultiheadAttention
>>> base = nn.MultiheadAttention(8, 2, batch_first=True)
>>> layer = MultiheadAttention(base, "default", r=2, lora_alpha=4)
>>> tuple(layer.lora_B["default"].weight.shape), layer.embed_dim
((24, 2), 8)
>>> x = lucid.randn(1, 5, 8)
>>> bool((layer(x, x, x)[0] == base(x, x, x)[0]).all().item())   # every B starts at zero
True
>>> cross = nn.MultiheadAttention(8, 2, kdim=6, vdim=6, batch_first=True)
>>> tuple(MultiheadAttention(cross, "default", r=2).k_proj_lora_A["default"].weight.shape)
(2, 6)

Used by 2

Properties

8
prop

active_adapters

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

The adapters the forward pass applies, as a list.

prop

bias

→Tensor | Nonefrom _BaseTunerLayer
bias: Tensor | None

The base layer's bias (a buffer on a quantized base), or None.

prop

lora_alpha

→Mapping[str, float]from LoraLayer
lora_alpha: Mapping[str, float]

α\alpha of each adapter, by name (read-only).

prop

lora_bias

→Mapping[str, bool]from LoraLayer
lora_bias: Mapping[str, bool]

Whether each adapter's second factor carries a bias, by name (read-only).

prop

r

→Mapping[str, int]from LoraLayer
r: Mapping[str, int]

Rank of each adapter, by name (read-only).

prop

scaling

→Mapping[str, float]from LoraLayer
scaling: Mapping[str, float]

The scale ss each adapter's update is multiplied by, by name (read-only).

prop

use_dora

→Mapping[str, bool]from LoraLayer
use_dora: Mapping[str, bool]

Whether each adapter is a DoRA adapter, by name (read-only).

prop

weight

→Parameterfrom _BaseTunerLayer
weight: Parameter

The base layer's weight (unchanged unless an adapter is merged into it).

Attributes

3
attr

active_adapter

from _BaseTunerLayer
active_adapter: str | list[str]

Name (or names) of the adapter the forward pass applies.

attr

disable_adapters

from _BaseTunerLayer
disable_adapters

Whether the forward pass runs the base layer alone.

attr

merged

from _BaseTunerLayer
merged

Whether an adapter is folded into the base weight (merged_adapters non-empty).

Class methods

1
cls

holds

→bool
holds(base: nn.MultiheadAttention)

Whether this layout adapts base: the one with a fused input projection.

Instance methods

13
fn

delete_adapter

→Nonefrom LoraLayer
delete_adapter(adapter_name: str)

Remove adapter_name: its factors, its dropout and its recorded settings.

fn

enable_adapters

→Nonefrom _BaseTunerLayer
enable_adapters(enabled: bool)

Apply the adapter in the forward pass (True) or run the base alone (False).

Disabling a merged layer unmerges it first, here rather than on the next call, so the forward pass never writes a weight — a compiled forward must not replay that write.

Parameters

enabledbool
Whether the adapter takes part. Gradient flags are left as they are: a frozen adapter stays frozen when it is re-enabled.
fn

extra_repr

→strfrom LoraLayer
extra_repr()

The active adapter, its rank and lora_alpha, and whether it is merged or disabled.

fn

forward

→Outfrom _WeightSpace
forward(args: object = (), kwargs: object = {})

Run the module with each adapted weight shifted by the active adapters' update.

The base module alone when adapters are disabled, every active adapter is merged or none applies; a layer merged for some of its adapters shifts the weights that hold the merged ones by the others. The shifted weights are in force for the one call only.

fn

get_base_layer

→nn.Modulefrom _BaseTunerLayer
get_base_layer()

Return the wrapped module, whose parameters are the base model's own.

One step down: where another tuner layer stands between, that layer, not the user's module (_root goes all the way).

fn

get_delta_weight

→Tensor
get_delta_weight(adapter: str)

Return s BAs\,BA for the first input projection: the fused one, (3E, E).

The other weights' updates are s * B @ A of their own tables (the output projection's is s * out_proj_lora_B @ out_proj_lora_A); a merge writes all of them.

Parameters

adapterstr
The adapter's name.

Returns

Tensor

(3 * embed_dim, embed_dim) with a fused input projection, the query projection's (embed_dim, embed_dim) with separate ones, in the adapter's dtype.

fn

merge

→Nonefrom _BaseTunerLayer
merge(safe_merge: bool = False, adapter_names: list[str] | None = None)

Fold the update into the base weights, in place.

The weights keep their identity — they are written, not replaced — so whatever holds them (an optimizer, a tied embedding) sees the merged values. That is also why a weight shared with another module must not be merged into; the tuner's merge_adapter and merge_and_unload refuse it, as this layer alone cannot see the rest of the model.

Merging some of the active adapters leaves the rest applying: the layer's forward pass runs the folded weights and then the active adapters that are not folded, so it computes what it did unmerged. The reference runs a merged layer's base alone, which drops the others — a deliberate departure (LCD-971). A method whose adapters would not compute the same function that way (rotations that must apply in order, DoRA reading the weight) refuses the split in the tuner's merge_adapter, before it writes anything; this method, called on a layer directly, does not check it. Merging an adapter that is not active adds it: the layer then runs the weights with it folded in and the active adapters it has not folded (the base with that adapter alone, in the reference).

Parameters

safe_mergebool= False
Check the merged weights for NaN / inf first and leave the base untouched if there are any.
adapter_nameslist of str= None
Adapters to merge; the active ones this layer holds by default.

Raises

ValueError
An adapter name this layer does not hold, or safe_merge found a non-finite merged weight.
RuntimeError
The adapter is disabled, or the layer's own rules refuse the merge (lora_bias on a base with no bias).
NotImplementedError
This layer's update cannot be written into its base weights.
fn

reset_lora_parameters

→Nonefrom LoraLayer
reset_lora_parameters(adapter_name: str, init_lora_weights: bool | str)

Initialise adapter adapter_name the way init_lora_weights asks.

True: every AA Kaiming-uniform with a = sqrt(5) (what nn.Linear uses) and every B=0B = 0, so the update starts at zero. "gaussian": A∼N(0,1/r2)A \sim \mathcal N(0, 1/r^2), B=0B = 0. False: leave both as the layers made them. "pissa", "pissa_niter_<k>" and "olora" factorise the base weight and write the residual back into it, in place.

Parameters

adapter_namestr
The adapter to initialise.
init_lora_weightsbool or str
The initialisation, as update_layer takes it.
fn

set_adapter

→Nonefrom _BaseTunerLayer
set_adapter(adapter_names: str | list[str], inference_mode: bool = False)

Apply the named adapters, and train exactly those unless inference_mode.

The names this layer holds nothing for are skipped by the forward pass. A merged layer is unmerged first, since the active adapters are no longer the merged ones.

Parameters

adapter_namesstr or list of str
The adapter, or adapters, to apply.
inference_modebool= False
Freeze the activated adapters as well.
fn

set_requires_grad

→Nonefrom _BaseTunerLayer
set_requires_grad(adapter_names: str | Sequence[str], requires_grad: bool = True)

Set requires_grad on the parameters of the named adapters this layer holds.

fn

supports_lora_conversion

→boolfrom _BaseTunerLayer
supports_lora_conversion(adapter_name: str = 'default')

Whether adapter_name on this layer can be converted to a plain LoRA update.

fn

unmerge

→Nonefrom _BaseTunerLayer
unmerge()

Take every merged update back out of the base weights, in place.

The result equals the original weights up to the rounding of the round trip.

fn

update_layer

→Nonefrom LoraLayer
update_layer(adapter_name: str, r: int, lora_alpha: float, lora_dropout: float, init_lora_weights: bool | str, use_rslora: bool, use_dora: bool = False, lora_bias: bool = False, arrow_config: ArrowConfig | None = None)

Create adapter adapter_name: its factors, dropout and scale.

The adapter lives on the base weight's device. Its dtype is the base's, except that a float16 / bfloat16 base gets a float32 adapter — the reference's default, which keeps the low-rank update from underflowing in training. A layer that holds an adapter already keeps applying the adapters it applied: the new one is inactive until set_adapter names it. A layer with none starts applying this one.

Everything the layer cannot do is refused before anything is allocated or any base weight is touched.

Parameters

adapter_namestr
Key of the adapter in each table.
rint
Rank; positive.
lora_alphafloat
Numerator of the scale.
lora_dropoutfloat
Dropout on the update's input, in [0, 1).
init_lora_weightsbool or str
True, False, "gaussian", "pissa", "pissa_niter_<k>" or "olora" (see LoraConfig). PiSSA and OLoRA rewrite the base weight (the residual), in place.
use_rslorabool
Scale by α/r\alpha/\sqrt r instead of α/r\alpha/r.
use_dorabool= False
Weight-decomposed update (DoRA): a magnitude vector per output unit beside the factors.
lora_biasbool= False
Give the second factor a bias.
arrow_configArrowConfig= None
Make the adapter an Arrow router over the plain LoRA adapters the layer holds (nn.Linear layers only; not with use_dora). Its own factors are never used.

Raises

NotImplementedError
An initialisation lucid.peft does not have.
ValueError
The layer already holds an adapter of this name, the rank does not fit the base layer, or the layer type cannot host the variant, the bias or the initialisation asked for.