PEFT documentation
X-LoRA
X-LoRA
Mixture of LoRA Experts (X-LoRA) は、高粒度(トークン、レイヤー、シーケンス)のスケーリング行列に基づいて、LoRA エキスパートのスパーズまたはデンスな混合を可能にする PEFT 手法です。この手法は、凍結された LoRA アダプターと凍結されたベースモデルを活用することで、ファインチューニングが必要なパラメータの数を大幅に削減します。
X-LoRAのユニークな点は、その汎用性にあります。LoRAアダプターを備えたtransformersベースモデルのいずれにも適用できます。つまり、エキスパートの混合戦略を採用していても、モデルコードに変更を加える必要はありません。
以下の図は、各トークンにおいてプロンプトごとにスケーリングがどのように変化するかを示しています。これにより、生成が進行し、シーケンスが新しいコンテキストを生成するにつれて、異なるアダプターがどのように活性化されるかが明確になります。

各ステップにおいて、X-LoRA はベースモデルを2回実行する必要があります。まず、LoRA アダプターなしで隠れ状態を取得するために1回実行し、次にその隠れ状態を用いてスケーリングを計算し、LoRA アダプターに適用してモデルを2回目に実行します。2回目の実行の出力が、モデルステップの結果となります。
最終的に、X-LoRAはデュアルフォワードパス方式により、モデルが自身の知識を振り返り、アーキテクチャを動的に再構成することを可能にします。
論文の抄録は以下の通りです:
低ランク適応(LoRA)に基づく深いレイヤー毎のトークンレベルのアプローチを用いて、ファインチューニングされた大規模言語モデル(LLM)を作成するためのエキスパートの混合戦略について報告する。事前学習済みの 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
< source >( 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) — PeftModel.load_adapter に従い、アダプター名から LoRA アダプター ID へのマッピングです。自動的に読み込まれ、LoRA エキスパートとして使用されます。from_pretrained を使用する場合は、新しいアダプター dict をキーワード引数として渡してください。 - 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)— デフォルトの dense 方式ではなく、top_k 個の LoRA エキスパートをスパースに選択します。 - xlora_depth (
int、省略可能、デフォルトは 1) — X-LoRA クラスIFIER の深さ。 - xlora_size (
int, 任意、デフォルトは 2048) — X-LoRA クラスIFIER の隠れ層サイズ。xlora_depth=1の場合は無関係です。 - xlora_dropout_p (
float, 任意、デフォルト値は 0.2) — X-LoRA クラスIFIER の 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
< source >( 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)スケーリングのログをクリアします。
ログをクリアせずに、スケーリングのログ出力を無効にします。
スケーリングのログ出力を有効にします。
seq_len ごとにバケット化されたスケーリングを返します。各値は、位置(先頭)と関連するテンソルで構成されています。位置は関連するテンソルとペアになり、スケーリングログ内の位置を示します。
グローバルLoRA重みを取得します。
最新のスケーリング予測を返します。スケーリングが予測されていない場合はNoneを返します。テンソルの形状は(batch_size, seq_len, n_layers, n_classes)です。
スケーリングのログを含むリストの浅いコピー(テンソルではなくリスト自体のみをコピー)を返します。リストを編集しても、元のログは変更されません。テンソルの形状は (batch_size, seq_len, n_layers, n_classes) です。seq_len 次元は入力次元によって変化し得ます。
グローバル LoRA 重みを設定します。これは、各 LoRA アダプターの出力に乗算するスカラー値です。デフォルト値は 1 です。この値は設定に反映されます。
スケーリングパスの値を設定します。スケーリングパス中にスケーリングを設定する値です。値がNoneの場合、スケーリングパスの値は1/nになります。ここでnはアダプタの数です。
デフォルトのdense方式ではなく、指定されたtop_kのLoRAエキスパートをスパースに選択します。denseを使用するにはNoneに設定します。 これはconfigに反映されます。