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

Mixture of LoRA Experts(X-LoRA)는 고세부(token, layer, sequence) 스케일링 행렬을 기반으로 LoRA 전문가의 희소 또는 밀집 혼합을 가능하게 하는 PEFT 방법입니다. 이는 동결된 LoRA 어댑터와 동결된 베이스 모델을 활용하여 미세 조정해야 하는 매개변수의 수를 크게 줄입니다.

A unique aspect of X-LoRA is its versatility: it can be applied to any transformers base model with LoRA adapters. This means that, despite the mixture of experts strategy, no changes to the model code must be made.

아래 그래픽은 각 토큰별로 프롬프트에 따라 스케일링이 어떻게 변하는지를 보여줍니다. 이는 생성이 진행되고 시퀀스가 새로운 컨텍스트를 생성하는 동안 다양한 어댑터가 활성화되는 점을 강조합니다.

Token-by-token scalings

각 단계에서 X-LoRA는 베이스 모델을 두 번 실행해야 합니다. 먼저, LoRA 어댑터 없이 hidden states를 얻기 위해 모델을 실행하고, 두 번째로 해당 hidden states를 사용하여 scaling을 계산한 뒤 이를 LoRA 어댑터에 적용하고 모델을 두 번째로 실행합니다. 두 번째 실행의 출력이 모델 단계의 결과입니다.

결국 X-LoRA는 이중 순전파(dual forward pass) 방식 덕분에 모델이 자신의 지식을 되돌아보고 아키텍처를 동적으로 재구성할 수 있게 합니다.

해당 논문의 초록은 다음과 같습니다:

저희는 저순위 적응(LoRA)에 기반한 심층 레이어별 토큰 레벨 접근법을 사용하여 미세 조정된 대규모 언어 모델을 생성하기 위한 전문가 혼합 전략을 보고합니다. 사전 학습된 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) — PeftModel.load_adapter에 따라 어댑터 이름에서 LoRA 어댑터 id로 매핑된 값입니다. 자동으로 로드되어 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) — 기본적인 dense 방식 대신 top_k LoRA 전문가를 희소하게 선택합니다.
  • xlora_depth (int, 선택 사항, 기본값 1) — X-LoRA 분류기의 깊이입니다.
  • xlora_size (int, 선택 사항, 기본값 2048) — xlora_depth=1인 경우 관련이 없는 X-LoRA 분류기의 hidden size입니다.
  • xlora_dropout_p (float, 선택 사항, 기본값 0.2) — xlora_depth=1인 경우 관련이 없는 X-LoRA 분류기의 Dropout 확률입니다.
  • 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(Mixture of LoRA experts) 모델을 생성합니다. 현재 이 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가 아닌 경우 최신 scalings 예측을 반환합니다. scalings 예측이 없으면 None을 반환합니다. 텐서의 shape은 (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입니다. 이는 config에 반영됩니다.

set_scaling_pass_value

< >

( value: float | None )

스케일링 패스 값, 즉 스케일링 패스 중에 스케일링을 설정할 값을 설정합니다. 값이 None인 경우, 스케일링 패스 값은 어댑터의 수 n에 대해 1/n이 됩니다.

set_topk_lora

< >

( value: Optional[int] )

기본 dense 방식 대신 지정된 top_k LoRA expert를 희소하게 선택합니다. dense를 사용하려면 None으로 설정합니다. 이는 config에 반영됩니다.

Update on GitHub