Chuyển tới nội dung chính

{/* Trang này được tạo tự động từ SKILL.md của kỹ năng bởi website/scripts/generate-skill-docs.py. Chỉnh sửa nguồn SKILL.md, không phải trang này. */}

Tinh chỉnh Peft

Tinh chỉnh tham số hiệu quả cho LLM bằng các phương pháp LoRA, QLoRA và 25+. Sử dụng khi tinh chỉnh các mô hình lớn (7B-70B) có bộ nhớ GPU hạn chế, khi bạn cần huấn luyện <1% tham số với mức độ mất độ chính xác tối thiểu hoặc để phân phối nhiều bộ chuyển đổi. Thư viện chính thức của HuggingFace được tích hợp với hệ sinh thái máy biến áp.

Siêu dữ liệu kỹ năng

NguồnTùy chọn — cài đặt với
`Hermes skills install official/mlops/peft
`
Đường dẫn

optional-skills/mlops/peft ` | | Phiên bản |

1.0.0 ` | | Tác giả | Nghiên cứu dàn nhạc | | Giấy phép | MIT | | Phụ thuộc |

peft>=0.13.0

, `transformers>=4.45.0

, `torch>=2.0.0

, bitsandbytes>=0.43.0 | | Nền tảng | Linux, macOS, Windows | | Thẻ |

Fine-Tuning

, `PEFT

, `LoRA

, `QLoRA

, `Parameter-Efficient

, `Adapters

, `Low-Rank

, `Memory Optimization

, Multi-Adapter |

Tham khảo: đầy đủ SKILL.md

thông tin

Sau đây là định nghĩa kỹ năng đầy đủ mà Hermes tải khi kỹ năng này được kích hoạt. Đây là những gì tác nhân coi là hướng dẫn khi kỹ năng được kích hoạt.

PEFT (Tinh chỉnh hiệu quả tham số)

Tinh chỉnh LLM bằng cách đào tạo <1% tham số bằng cách sử dụng các phương pháp bộ chuyển đổi LoRA, QLoRA và 25+.

Khi nào nên sử dụng PEFT`Sử dụng PEFT/LoRA khi:

  • Tinh chỉnh các mô hình 7B-70B trên GPU tiêu dùng (RTX 4090, A100)
  • Cần huấn luyện thông số <1% (bộ điều hợp 6MB so với model đầy đủ 14GB)
  • Muốn lặp lại nhanh với nhiều bộ điều hợp dành riêng cho nhiệm vụ
  • Triển khai nhiều biến thể tinh chỉnh từ một mô hình cơ sở`Sử dụng QLoRA (PEFT + lượng tử hóa) khi:
  • Tinh chỉnh các model 70B trên GPU 24GB đơn
  • Trí nhớ là hạn chế chính
  • Có thể chấp nhận sự đánh đổi chất lượng ~5% so với tinh chỉnh hoàn toàn`Thay vào đó, hãy sử dụng tính năng tinh chỉnh đầy đủ khi:
  • Huấn luyện các mô hình nhỏ (<1B tham số)
  • Cần chất lượng tối đa và có ngân sách tính toán
  • Sự thay đổi tên miền đáng kể yêu cầu cập nhật tất cả các trọng số

Bắt đầu nhanh

Cài đặt


# Basic installation
pip install peft

# With quantization support (recommended)
pip install peft bitsandbytes

# Full stack
pip install peft transformers accelerate bitsandbytes datasets

`

### Tinh chỉnh LoRA (tiêu chuẩn)

``` python
from transformers import AutoModelForCausaLLM, AutoTokenizer, TrainingArguments, Trainer
from peft import get_peft_model, LoraConfig, TaskType
from datasets import load_dataset

# Load base model
model_name = "meta-Llama/Llama-3.1-8B"
model = AutoModelForCausaLLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token

# LoRA configuration
lora_config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=16, # Rank (8-64, higher = more capacity)
lora_alpha=32, # Scaling factor (typically 2*r)
lora_dropout=0.05, # Dropout for regularization
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], # Attention layers
bias="none" # Don't train biases
)

# Apply LoRA
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()

# Output: trainable params: 13,631,488 || all params: 8,043,307,008 || trainable%: 0.17%

# Prepare dataset
dataset = load_dataset("databricks/databricks-dolly-15k", split="train")

def tokenize(example):
text = f"### Instruction:\n\&#123;example['instruction']&#125;\n\n### Response:\n\&#123;example['response']&#125;"
return tokenizer(text, truncation=True, max_length=512, padding="max_length")

tokeniZed = dataset.map(tokenize, remove_columns=dataset.column_names)

# Training
training_args = TrainingArguments(
output_dir="./lora-Llama",
num_train_epochs=3,
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=2e-4,
fp16=True,
logging_steps=10,
save_strategy="epoch"
)

trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokeniZed,
data_collator=lambda data: \&#123;"input_ids": torch.stack([f["input_ids"] for f in data]),
"attention_mask": torch.stack([f["attention_mask"] for f in data]),
"labels": torch.stack([f["input_ids"] for f in data])&#125;
)

trainer.train()

# Save adapter only (6MB vs 16GB)
model.save_pretrained("./lora-Llama-adapter")

`

### Tinh chỉnh QLoRA (tiết kiệm bộ nhớ)

``` python
from transformers import AutoModelForCausaLLM, BitsAndBytesConfig
from peft import get_peft_model, LoraConfig, prepare_model_for_kbit_training

# 4-bit quantization config
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4", # NormalFloat4 (best for LLMs)
bnb_4bit_compute_dtype="bfloat16", # Compute in bf16
bnb_4bit_use_double_quant=True # Nested quantization
)

# Load quantiZed model
model = AutoModelForCausaLLM.from_pretrained(
"meta-Llama/Llama-3.1-70B",
quantization_config=bnb_config,
device_map="auto"
)

# Prepare for training (enables gradient checkpointing)
model = prepare_model_for_kbit_training(model)

# LoRA config for QLoRA
lora_config = LoraConfig(
r=64, # Higher rank for 70B
lora_alpha=128,
lora_dropout=0.1,
target_modules=["q_proj", "v_proj", "k_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
bias="none",
task_type="CAUSAL_LM"
)

model = get_peft_model(model, lora_config)

# 70B model now fits on single 24GB GPU!

`

## Lựa chọn tham số LoRA

### Hạng (r) - năng lực so với hiệu quả

| Xếp hạng | Thông số có thể đào tạo | Ký ức | Chất lượng | Trường hợp sử dụng |
|------|--------|--------|----------|----------|
| 4 | ~3 triệu | Tối thiểu | Hạ | Nhiệm vụ đơn giản, tạo mẫu |
| **8** | ~7 triệu | Thấp | Tốt | **Điểm bắt đầu được đề xuất** |
| **16** | ~14 triệu | Trung bình | Tốt hơn | **Tinh chỉnh chung** |
| 32 | ~27 triệu | Cao hơn | Cao | Nhiệm vụ phức tạp |
| 64 | ~54 triệu | Cao | Cao nhất | Thích ứng miền, mô hình 70B |

### Alpha (lora_alpha) - hệ số tỷ lệ

``` python

# Rule of thumb: alpha = 2 * rank
LoraConfig(r=16, lora_alpha=32) # Standard
LoraConfig(r=16, lora_alpha=16) # Conservative (lower learning rate effect)
LoraConfig(r=16, lora_alpha=64) # Aggressive (higher learning rate effect)

`

### Mô-đun mục tiêu theo kiến trúc

``` python

# Llama / Mistral / Qwen
target_modules = ["q_proj", "v_proj", "k_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]

# GPT-2 / GPT-Neo
target_modules = ["c_attn", "c_proj", "c_fc"]

# Falcon
target_modules = ["query_key_value", "dense", "dense_h_to_4h", "dense_4h_to_h"]

# BLOOM
target_modules = ["query_key_value", "dense", "dense_h_to_4h", "dense_4h_to_h"]

# Auto-detect all linear layers
target_modules = "all-linear" # PEFT 0.6.0+

`

## Đang tải và hợp nhất các bộ điều hợp

### Tải bộ điều hợp đã được huấn luyện

``` python
from peft import PeftModel, AutoPeftModelForCausaLLM
from transformers import AutoModelForCausaLLM

# Option 1: Load with PeftModel
base_model = AutoModelForCausaLLM.from_pretrained("meta-Llama/Llama-3.1-8B")
model = PeftModel.from_pretrained(base_model, "./lora-Llama-adapter")

# Option 2: Load directly (recommended)
model = AutoPeftModelForCausaLLM.from_pretrained(
"./lora-Llama-adapter",
device_map="auto"
)

`

### Hợp nhất bộ điều hợp vào mô hình cơ sở

`Python

# Merge for deployment (no adapter overhead)
merged_model = model.merge_and_unload()

# Save merged model
merged_model.save_pretrained("./Llama-merged")
tokenizer.save_pretrained("./Llama-merged")

# Push to Hub
merged_model.push_to_hub("username/Llama-finetuned")

`

### Phân phối nhiều bộ chuyển đổi

``` python
from peft import PeftModel

# Load base with first adapter
model = AutoPeftModelForCausaLLM.from_pretrained("./adapter-task1")

# Load additional adapters
model.load_adapter("./adapter-task2", adapter_name="task2")
model.load_adapter("./adapter-task3", adapter_name="task3")

# Switch between adapters at runtime
model.set_adapter("task1") # Use task1 adapter
output1 = model.generate(**inputs)

model.set_adapter("task2") # Switch to task2
output2 = model.generate(**inputs)

# Disable adapters (use base model)
with model.disable_adapter():
base_output = model.generate(**inputs)

`
``##So sánh các phương pháp PEFT

| Phương pháp | Có thể đào tạo % | Ký ức | Tốc độ | Tốt nhất cho |
|--------|-------------|--------|-------|----------|
| **LoRA** | 0,1-1% | Thấp | Nhanh | Tinh chỉnh chung |
| **QLoRA** | 0,1-1% | Rất Thấp | Trung bình | Hạn chế về bộ nhớ |
| AdaLoRA | 0,1-1% | Thấp | Trung bình | Lựa chọn cấp bậc tự động |
| IA3 | 0,01% | Tối thiểu | Nhanh nhất | Chuyển thể ít cảnh quay |
| Điều chỉnh tiền tố | 0,1% | Thấp | Trung bình | Kiểm soát thế hệ |
| Điều chỉnh nhanh chóng | 0,001% | Tối thiểu | Nhanh | Thích ứng nhiệm vụ đơn giản |
| P-Điều chỉnh v2 | 0,1% | Thấp | Trung bình | nhiệm vụ NLU |

### IA3 (tham số tối thiểu)

`Python
from peft import IA3Config`ia3_config = IA3Config(
target_modules=["q_proj", "v_proj", "k_proj", "down_proj"],
feedforward_modules=["down_proj"]
)
model = get_peft_model(model, ia3_config)

# Trains only 0.01% of parameters!

`

### Điều chỉnh tiền tố

``` python
from peft import PrefixTuningConfig`prefix_config = PrefixTuningConfig(
task_type="CAUSAL_LM",
num_virtual_tokens=20, # Prepended tokens
prefix_projection=True # Use MLP projection
)
model = get_peft_model(model, prefix_config)

`

## Mẫu tích hợp

### Với TRL (SFTTrainer)

`Python
from trl import SFTTrainer, SFTConfig
from peft import LoraConfig`lora_config = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear")

trainer = SFTTrainer(
model=model,
args=SFTConfig(output_dir="./output", max_seq_length=512),
train_dataset=dataset,
peft_config=lora_config, # Pass LoRA config directly
)
trainer.train()

`

### Với Axolotl (cấu hình YAML)

`YAML

# axolotl config.yaml
adapter: lora
lora_r: 16
lora_alpha: 32
lora_dropout: 0.05
lora_target_modules:
- q_proj
- v_proj
- k_proj
- o_proj
lora_target_linear: true # Target all linear layers

`

### Với vLLM (suy luận)

``` python
from vLLM import LLM
from vLLM.lora.request import LoRARequest

# Load base model with LoRA support
LLM = LLM(model="meta-Llama/Llama-3.1-8B", enable_lora=True)

# Serve with adapter
outputs = LLM.generate(
prompts,
lora_request=LoRARequest("adapter1", 1, "./lora-adapter")
)

`

## Điểm chuẩn hiệu suất

### Mức sử dụng bộ nhớ (Llama 3.1 8B)

| Phương pháp | Bộ nhớ GPU | Thông số có thể đào tạo |
|--------|-------------|-------------------|
| Tinh chỉnh đầy đủ | 60+ GB | 8B (100%) |
| LoRA r=16 | 18GB | 14 triệu (0,17%) |
| QLoRA r=16 | 6GB | 14 triệu (0,17%) |
| IA3 | 16 GB | 800K (0,01%) |

###Tốc độ luyện tập (A100 80GB)

| Phương pháp | Mã thông báo/giây | so với FT đầy đủ |
|--------|-------------|-------------|
| FT đầy đủ | 2.500 | 1x |
| LoRA | 3.200 | 1,3x |
| QLoRA | 2.100 | 0,84x |

### Chất lượng (điểm chuẩn MMLU)| Người mẫu | FT đầy đủ | LoRA | QLoRA |
|-------|----------|------|-------|
| Lạc đà 2-7B | 45,3 | 44,8 | 44.1 |
| Lạc đà 2-13B | 54,8 | 54,2 | 53,5 |

## Các vấn đề thường gặp

### CUDA OOM trong quá trình tập luyện

`Python

# Solution 1: Enable gradient checkpointing
model.gradient_checkpointing_enable()

# Solution 2: Reduce batch size + increase accumulation
TrainingArguments(
per_device_train_batch_size=1,
gradient_accumulation_steps=16
)

# Solution 3: Use QLoRA
from transformers import BitsAndBytesConfig
bnb_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4")

`

### Adaptor không hoạt động

``` python

# Verify adapter is active
print(model.active_adapters) # Should show adapter name

# Check trainable parameters
model.print_trainable_parameters()

# Ensure model in training mode
model.train()

`

### Suy giảm chất lượng

``` python

# Increase rank
LoraConfig(r=32, lora_alpha=64)

# Target more modules
target_modules = "all-linear"

# Use more training data and epochs
TrainingArguments(num_train_epochs=5)

# Lower learning rate
TrainingArguments(learning_rate=1e-4)

`

## Các phương pháp hay nhất
1. **Bắt đầu với r=8-16**, tăng nếu chất lượng không đủ
2. **Sử dụng alpha = 2 * xếp hạng** làm điểm bắt đầu
3. **Sự chú ý mục tiêu + lớp MLP** để có chất lượng/hiệu quả tốt nhất
4. **Bật tính năng kiểm tra độ dốc** để tiết kiệm bộ nhớ
5. **Lưu bộ điều hợp thường xuyên** (tệp nhỏ, khôi phục dễ dàng)
6. **Đánh giá dữ liệu được giữ lại** trước khi hợp nhất
7. **Sử dụng QLoRA cho các mẫu 70B+** trên phần cứng tiêu dùng

## Tài liệu tham khảo
- **[Advanced Usage](https://GitHub.com/NousResearch/Hermes-agent/blob/main/optional-skills/mlops/peft/references/advanced-usage.md)** - DoRA, LoftQ, ổn định thứ hạng, mô-đun tùy chỉnh
- **[Troubleshooting](https://GitHub.com/NousResearch/Hermes-agent/blob/main/optional-skills/mlops/peft/references/troubleshooting.md)** - Các lỗi thường gặp, gỡ lỗi, tối ưu hóa

## Tài nguyên
- **GitHub**: https://GitHub.com/huggingface/peft
- **Tài liệu**: https://huggingface.co/docs/peft
- **Giấy LoRA**: arXiv:2106.09685
- **Giấy QLoRA**: arXiv:2305.14314
- **Người mẫu**: https://huggingface.co/models?library=peft