Skip to content
class

XLoraModel

extends_FileFormat_AdapterHost
XLoraModel(model: nn.Module, config: PeftConfig, adapter_name: str, device: str | None = None, ephemeral_gpu_offload: bool = False, autocast_adapter_dtype: bool = True, kwargs: object = {})

A model whose LoRA experts are weighed per token by a classifier on its hidden states.

Construction loads the LoRA adapters config.adapters names (as "0", "1", ... through the multi-adapter API, all active together), switches their layers to the base module and hooks each to add the experts' updates, scaled. A call then runs twice: a scalings pass, without gradients, on the model with every expert held at scaling_pass_value, whose final hidden states the classifier (internal_xlora_classifier) turns into one weight per expert and token; and the real pass, in which each adapted layer adds g∑kuk(sk⊙x)g\sum_k u_k(s_k\odot x). The classifier is the only thing that trains (the experts as well with use_trainable_adapters), and the only thing the adapter file holds.

The scalings need the whole sequence at every step: generate with use_cache=False. Layers of the experts must be nn.Linear LoRA layers, without DoRA. Nothing merges. The model keeps one X-LoRA adapter.

Parameters

The base model; its trunk (base_model_prefix) should return last_hidden_state.
The experts and the classifier.
adapter_namestr
Name of the X-LoRA adapter (the experts keep their own names).
devicestr= None
The reference loads the experts onto this device. They load onto the model's own; anything but None raises NotImplementedError.
ephemeral_gpu_offloadbool= False
Not implemented: True raises NotImplementedError.
autocast_adapter_dtypebool= True
Always the case here; False raises NotImplementedError.
**kwargsobject= {}
Accepted for the reference's signature (it forwards them to its loader); any key raises NotImplementedError.

Raises

ValueError
The model already holds adapters, config.adapters is empty or names a directory that holds no LoRA adapter, an expert uses DoRA, or the model gives no hidden size.
NotImplementedError
An expert adapts a layer that is not an nn.Linear.

Examples

>>> import lucid
>>> import lucid.nn as nn
>>> import tempfile
>>> from lucid.models import create_model
>>> from lucid.peft import LoraConfig, XLoraConfig, XLoraModel, get_peft_model
>>> arch = dict(vocab_size=32, hidden_size=16, num_hidden_layers=2, num_attention_heads=2,
...             intermediate_size=32, max_position_embeddings=16)
>>> with tempfile.TemporaryDirectory() as d:
...     for name in ("a", "b"):
...         get_peft_model(create_model("gpt2_small_lm", **arch),
...                        LoraConfig(r=2, target_modules=["c_attn"])).save_pretrained(f"{d}/{name}")
...     lm = create_model("gpt2_small_lm", **arch)
...     xlora = XLoraModel(lm, XLoraConfig(adapters={"a": f"{d}/a", "b": f"{d}/b"}), "default")
...     out = xlora(lucid.randint(0, 32, (1, 5)))
>>> out.logits.shape, xlora.get_latest_scalings().shape   # (batch, tokens, layers, experts)
((1, 5, 32), (1, 5, 2, 2))

Used by 1

Constructors

1
dunder

__init__

→None
__init__(model: nn.Module, config: PeftConfig, adapter_name: str, device: str | None = None, ephemeral_gpu_offload: bool = False, autocast_adapter_dtype: bool = True, kwargs: object = {})

Load the experts into model, build the classifier and hook the model; model is as given if that fails.

Properties

3
prop

active_adapters

→list[str]
active_adapters: list[str]

The X-LoRA adapter, as a list.

prop

lora_model

→PeftModel
lora_model: PeftModel

The LoRA experts' holder (a PeftModel over the same model): the multi-adapter API they were loaded by.

prop

xlora_config

→XLoraConfig
xlora_config: XLoraConfig

The stored config of the X-LoRA adapter, which the settings below change.

Attributes

1
attr

scalings

scalings: Tensor | None

The scalings the call in progress mixes with, and the last ones the classifier made.

Static methods

1
static

get_model_config

→dict of str to objectfrom _AdapterHost
get_model_config(model: nn.Module)

model's config as a dict, whatever it is held as.

A config with a to_dict method is converted by it, a dataclass by asdict, a mapping is copied. A model with no config (or one that is None) has the reference's stand-in, {"model_type": "custom"}, which is what the default target modules and the prompt geometry read for a model of no known type.

Parameters

The model to read the config of.

Returns

dict of str to object

The config's entries; a new dict, whose changes do not reach the model.

Raises

TypeError
model.config is none of a mapping, a dataclass or an object with to_dict.

Examples

>>> import lucid.nn as nn
>>> from lucid.peft import LoraModel
>>> LoraModel.get_model_config(nn.Linear(2, 2))
{'model_type': 'custom'}

Instance methods

23