PEFT documentation

X-LoRA

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

X-LoRA

LoRA 专家混合(X-LoRA)是一种 PEFT 方法,它基于高粒度(token、层、序列)的缩放矩阵,实现 LoRA 专家的稀疏或稠密混合。该方法利用冻结的 LoRA 适配器和冻结的基础模型,大幅减少了需要微调的参数数量。

X-LoRA 的一个独特之处在于其通用性:它可以应用于任何带有 LoRA 适配器的 transformers 基础模型。这意味着,尽管采用了混合专家策略,但无需对模型代码进行任何更改。

下图展示了每个 token 在不同提示词下缩放因子的变化情况。这凸显了随着生成过程的推进以及序列创建新的上下文,不同适配器被激活的情况。

Token-by-token scalings

在每个步骤中,X-LoRA 需要运行两次基础模型:首先,在不使用任何 LoRA 适配器的情况下运行以获取隐藏状态;其次,利用这些隐藏状态计算缩放因子,将其应用于 LoRA 适配器,然后第二次运行模型。第二次运行的输出即为该模型步骤的结果。

最终,得益于双前向传播机制,X-LoRA 使模型能够反思其知识并动态重构架构。

该论文的摘要如下:

我们提出了一种混合专家策略,用于基于低秩适应(LoRA)的深度逐层、逐 token 方法创建微调后的大语言模型。从一组预训练的 LoRA 适配器开始,我们的门控策略利用隐藏状态动态混合经过适配的层,使得生成的 X-LoRA 模型能够调用不同的能力,并创建前所未有的深度逐层组合来解决任务。该设计受到生物普遍性和多样性原则的启发,其中神经网络构建模块在不同的层级表现中被复用。因此,X-LoRA 模型可以轻松应用于任何现有大语言模型(LLM),而无需修改其底层结构。我们开发了一个定制的 X-LoRA 模型,提供包括正向/逆向分析任务和增强推理能力在内的科学能力,专注于生物材料分析、蛋白质力学与设计。这项工作的影响包括获得易于扩展和适应、具有强大领域知识以及跨知识领域整合能力的模型。该模型具备生物学、数学、推理、仿生材料、力学与材料、化学、蛋白质生物物理、力学以及基于量子力学的分子性质等方面的专家。我们进行了一系列以物理为重点的案例研究。我们考察了知识回忆、蛋白质力学正向/逆向任务、蛋白质设计、对抗性智能体建模(包括本体知识图谱构建)以及分子设计。该模型不仅能够对蛋白质的纳米力学性质或量子力学分子性质进行定量预测,还能对结果进行推理,并正确预测解释不同分子行为的潜在机制。

请引用 X-LoRA 为:

@article{10.1063/5.0203126,
    author = {Buehler, Eric L. and Buehler, Markus J.},
    title = "{X-LoRA: Mixture of low-rank adapter experts, a flexible framework for large language models with applications in protein mechanics and molecular design}",
    journal = {APL Machine Learning},
    volume = {2},
    number = {2},
    pages = {026119},
    year = {2024},
    month = {05},
    abstract = "{We report a mixture of expert strategy to create fine-tuned large language models using a deep layer-wise token-level approach based on low-rank adaptation (LoRA). Starting with a set of pre-trained LoRA adapters, our gating strategy uses the hidden states to dynamically mix adapted layers, allowing the resulting X-LoRA model to draw upon different capabilities and create never-before-used deep layer-wise combinations to solve tasks. The design is inspired by the biological principles of universality and diversity, where neural network building blocks are reused in different hierarchical manifestations. Hence, the X-LoRA model can be easily implemented for any existing large language model without a need for modifications of the underlying structure. We develop a tailored X-LoRA model that offers scientific capabilities, including forward/inverse analysis tasks and enhanced reasoning capability, focused on biomaterial analysis, protein mechanics, and design. The impact of this work includes access to readily expandable and adaptable models with strong domain knowledge and the capability to integrate across areas of knowledge. Featuring experts in biology, mathematics, reasoning, bio-inspired materials, mechanics and materials, chemistry, protein biophysics, mechanics, and quantum-mechanics based molecular properties, we conduct a series of physics-focused case studies. We examine knowledge recall, protein mechanics forward/inverse tasks, protein design, adversarial agentic modeling including ontological knowledge graph construction, and molecular design. The model is capable not only of making quantitative predictions of nanomechanical properties of proteins or quantum mechanical molecular properties but also reasoning over the results and correctly predicting likely mechanisms that explain distinct molecular behaviors.}",
    issn = {2770-9019},
    doi = {10.1063/5.0203126},
    url = {https://doi.org/10.1063/5.0203126},
    eprint = {https://pubs.aip.org/aip/aml/article-pdf/doi/10.1063/5.0203126/19964043/026119\_1\_5.0203126.pdf},
}

API

XLoraConfig

类 peft.XLoraConfig

< >

( task_type: Optional[Union[str, TaskType]] = Nonepeft_type: Optional[Union[str, PeftType]] = Noneauto_mapping: Optional[dict] = Nonepeft_version: Optional[str] = Nonebase_model_name_or_path: Optional[str] = Nonerevision: Optional[str] = Noneinference_mode: bool = Falsehidden_size: int = Noneadapters: dict[str, str] = Noneenable_softmax: bool = Trueenable_softmax_topk: bool = Falselayerwise_scalings: bool = Falsexlora_depth: int = 1xlora_size: int = 2048xlora_dropout_p: float = 0.2use_trainable_adapters: bool = Falsesoftmax_temperature: float = 1.0top_k_lora: Optional[int] = Nonescaling_pass_value: float = 0.0global_scaling_weight: float = 1.0 )

参数

  • hidden_size (int) — 基础模型的隐藏层大小。
  • adapters (dict) — 适配器名称到 LoRA 适配器 id 的映射,遵循 PeftModel.load_adapter 的规范。它们将被自动加载,用作 LoRA 专家。在使用 from_pretrained 时,请将新的适配器字典作为关键字参数传入。
  • enable_softmax (bool,可选,默认为 True) — 为 X-LoRA 分类器启用 softmax 应用。
  • enable_softmax_topk (bool,可选,默认为 False) — 为 top-k LoRA 适配器启用 softmax 应用。与 enable_softmax 互斥,且仅在设置了 top_k_lora 时才能设置。
  • softmax_temperature (float,可选,默认为 1.0) — Softmax 温度,值越低,预测结果越尖锐
  • layerwise_scalings (bool,可选,默认为 False) — 如果为 True,则为每个 LoRA 适配器(每一层)生成缩放系数。如果为 False,则缩放系数将广播到每一层,即所有层使用相同的值。
  • top_k_lora (int, 可选,默认为 None) — 稀疏选择 top_k 个 LoRA 专家,而不是使用默认的稠密方法。
  • xlora_depth (int, 可选, 默认为 1) — X-LoRA 分类器的深度。
  • xlora_size (int, 可选, 默认为 2048) — X-LoRA 分类器的隐藏层大小,如果 xlora_depth=1 则无关紧要。
  • xlora_dropout_p (float, 可选, 默认值为 0.2) — X-LoRA 分类器的 Dropout 概率,如果 xlora_depth=1 则无关紧要。
  • use_trainable_adapters (bool,可选,默认为 False) — 使适配器可训练。
  • scaling_pass_value (float,可选,默认为 0) — 缩放通过值。
  • global_scaling_weight (float,可选,默认为 1) — 用于乘以每个 LoRA 适配器输出的权重。

这是用于存储XLoraModel配置的类。当重新加载配置时,adapters字段中的路径将被忽略,转而使用已保存的适配器。因此,在加载过程中,只有键名是重要的。

XLoraModel

类 peft.XLoraModel

< >

( model: nn.Moduleconfig: Union[dict[str, XLoraConfig], XLoraConfig]adapter_name: strtorch_device: Optional[str] = Noneephemeral_gpu_offload: bool = Falseautocast_adapter_dtype: bool = True**kwargs ) → torch.nn.Module

参数

  • model (torch.nn.Module) — 要适配的模型。
  • config (XLoraConfig) — Lora 模型的配置。
  • adapter_name (str) — 适配器的名称,不影响 LoRA 适配器的名称。

返回值

torch.nn.Module

X-LoRA 模型。

从预训练的 transformers 模型创建一个 X-LoRA(LoRA 专家混合)模型。目前,此 X-LoRA 实现仅适用于具有 transformer 架构的模型。

该方法的详细描述见 https://huggingface.co/papers/2402.07148。

示例:

>>> import torch
>>> from transformers import AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
>>> from peft import XLoraConfig, get_peft_model, prepare_model_for_kbit_training

>>> model_config = AutoConfig.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1")
>>> config = XLoraConfig(
...     task_type="CAUSAL_LM",
...     hidden_size=model_config.hidden_size,
...     xlora_depth=4,
...     adapters={
...         "adapter_1": "./path/to/the/checkpoint/",
...         "adapter_2": "./path/to/the/checkpoint/",
...         "adapter_n": "./path/to/the/checkpoint/",
...     },
... )
>>> int8_config = BitsAndBytesConfig(load_in_8bit=True)
>>> model = AutoModelForCausalLM.from_pretrained(
...     "mistralai/Mistral-7B-Instruct-v0.1",
...     trust_remote_code=True,
...     attn_implementation="flash_attention_2",
...     device_map="cuda:0",
...     torch_dtype=torch.bfloat16,
...     quantization_config=int8_config,
... )
>>> model = prepare_model_for_kbit_training(model)
>>> xlora_model = get_peft_model(model, config)

clear_scalings_log

< >

( )

清除缩放日志。

disable_scalings_logging

< >

( )

禁用缩放日志记录,但不清除日志。

enable_scalings_logging

< >

( )

启用缩放日志记录。

get_bucketed_scalings_log

< >

( )

返回按 seq_len 分桶的缩放值。每个值由位置(第一个元素)和相关的张量组成。位置与相关的张量配对,并给出缩放日志中的位置。

get_global_scaling_weight

< >

( )

获取全局 LoRA 权重。

get_latest_scalings

< >

( )

返回最新的缩放预测,如果尚未进行任何缩放预测,则返回 None。该张量的形状为 (batch_size, seq_len, n_layers, n_classes)。

get_scalings_log

< >

( )

返回包含缩放日志的列表的浅拷贝(仅复制列表本身,不复制张量)。 编辑该列表不会更改底层日志。张量的形状为 (batch_size, seq_len, n_layers, n_classes)。seq_len 维度可能会随输入维度而变化。

set_global_scaling_weight

< >

( weight: float )

设置全局 LoRA 权重,这是一个标量,用于乘以每个 LoRA 适配器的输出。默认值为 1。此设置会反映在配置中。

set_scaling_pass_value

< >

( value: float | None )

设置缩放通道值,即在缩放通道期间要设置的缩放值。如果该值为 None,则缩放通道值将为 1/n,其中 n 是适配器的数量。

set_topk_lora

< >

( value: Optional[int] )

稀疏选择指定的 top_k 个 LoRA 专家,而不是默认的稠密方法。设置为 None 以使用稠密方法。 这反映在配置中。

Update on GitHub