XLoraModel
_FileFormat_AdapterHostXLoraModel(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
. 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
modelnn.Modulebase_model_prefix) should return last_hidden_state.configXLoraConfigadapter_ namestrdevicestr= NoneNone raises NotImplementedError.ephemeral_ gpu_ offloadbool= FalseTrue raises NotImplementedError.autocast_ adapter_ dtypebool= TrueFalse raises NotImplementedError.**kwargsobject= {}NotImplementedError.Raises
ValueErrorconfig.adapters is empty or names a directory
that holds no LoRA adapter, an expert uses DoRA, or the model gives no hidden size.NotImplementedErrornn.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__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
3The X-LoRA adapter, as a list.
The LoRA experts' holder (a PeftModel over the same model): the multi-adapter API they were loaded by.
xlora_config: XLoraConfigThe stored config of the X-LoRA adapter, which the settings below change.
Attributes
1Static methods
1get_model_config
→dict of str to objectfrom _AdapterHostget_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
modelnn.ModuleReturns
dict of str to objectThe config's entries; a new dict, whose changes do not reach the model.
Raises
TypeErrormodel.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
23Refused: an X-LoRA model holds one classifier; build another model to mix other experts.
Forget the logged scalings.
Refused: the classifier is the model's only adapter; unload() removes it.
Run the base model alone.
Stop recording; the log is kept.
Weigh the experts again after disable_adapter_layers.
Record the scalings of every call from now on.
Call the model; the hooks weigh and mix the experts.
get_bucketed_scalings_log()The log grouped by sequence length: {tokens: (positions in the log, scalings)}.
The factor on every expert's update.
The last scalings the classifier made, (batch, tokens, layers, experts); None before the first call.
A copy of the list of logged scalings (the tensors are not copied).
inject_adapter
→Noneinject_adapter(model: nn.Module, adapter_name: str, autocast_adapter_dtype: bool = True, low_cpu_mem_usage: bool = False, state_dict: dict[str, Tensor] | None = None)Refused: the experts are loaded from config.adapters when the model is built; X-LoRA has no layer of its own to inject.
Parameters
Raises
NotImplementedErrormerge_adapter
→Nonemerge_adapter(adapter_names: list[str] | None = None, safe_merge: bool = False)Refused: the experts' weights change with every token, so there is nothing to merge.
This departs from the reference on purpose. Its merge_adapter merges every expert at
weight 1 into the base weights, after which its layers skip the scalings, so the model
runs the sum of the experts and the classifier's mixture is silently dropped.
Parameters
adapter_ nameslist of str= Nonesafe_ mergebool= FalseRaises
NotImplementedErrormerge_and_unload(progressbar: bool = False, safe_merge: bool = False, adapter_names: list[str] | None = None)Refused: the experts' weights change with every token, so there is nothing to merge.
set_adapter
→Noneset_adapter(adapter_name: str | list[str], inference_mode: bool = False)Select the X-LoRA adapter — the only one — and train its classifier unless inference_mode.
Multiply every expert's update by weight.
set_requires_grad
→Noneset_requires_grad(adapter_names: str | Sequence[str], requires_grad: bool = True)Enable or disable gradients on the classifier.
Hold every expert at value in the scalings pass (None: one over the number of experts).
Keep only the value heaviest experts per token (None: all of them).
Whether the adapter converts to a LoRA one: it does not (False).
This departs from the reference on purpose, which answers True from the experts'
LoRA layers. X-LoRA's update is a different mixture of the experts for every token, not
a weight delta that a LoRA adapter could stand for.
Parameters
adapter_ namestr= "default"Take the hooks and the experts out and give every parameter its old requires_grad.
Take every merged update back out of the base weights: none is ever merged, so nothing changes.
merge_adapter is refused, so an X-LoRA model holds no merged weight; this is what the
reference's does on a model it has not merged.