Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

llm-fine-tuning-guide

БесплатноЗапускает вложенные скриптыНе проверен

Master fine-tuning of large language models for specific domains and tasks. Covers data preparation, training techniques, optimization strategies, and…

qodex-aiот qodex-ai★ 50 звёзд на GitHub

Об этом скилле

LLM Fine-Tuning Guide

Master the art of fine-tuning large language models to create specialized models optimized for your specific use cases, domains, and performance requirements.

Overview

Fine-tuning adapts pre-trained LLMs to specific tasks, domains, or styles by training them on curated datasets. This improves accuracy, reduces hallucinations, and optimizes costs.

When to Fine-Tune

  • Domain Specialization: Legal documents, medical records, financial reports
  • Task-Specific Performance: Better results on specific tasks than base model
  • Cost Optimization: Smaller fine-tuned model replaces expensive large model
  • Style Adaptation: Match specific writing styles or tones
  • Compliance Requirements: Keep sensitive data within your infrastructure
  • Latency Requirements: Smaller models deploy faster

When NOT to Fine-Tune

  • One-off queries (use prompting instead)
  • Rapidly changing information (use RAG instead)
  • Limited training data (< 100 examples typically insufficient)
  • General knowledge questions (base model sufficient)

Quick Start

Full Fine-Tuning:

python examples/full_fine_tuning.py

LoRA (Recommended for most cases):

python examples/lora_fine_tuning.py

QLoRA (Single GPU):

python examples/qlora_fine_tuning.py

Data Preparation:

python scripts/data_preparation.py

Fine-Tuning Approaches

1. Full Fine-Tuning

Update all model parameters during training.

Pros:

  • Maximum performance improvement
  • Can completely rewrite model behavior
  • Best for significant domain shifts

Cons:

  • High computational cost
  • Requires large dataset (1000+ examples)
  • Risk of catastrophic forgetting
  • Long training time
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer

model_id = "meta-llama/Llama-2-7b"
model = AutoModelForCausalLM.from_pretrained(model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)

training_args = TrainingArguments(
    output_dir="./fine-tuned-llama",
    num_train_epochs=3,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,
    learning_rate=2e-5,
    weight_decay=0.01,
    logging_steps=10,
    save_steps=100,
    eval_strategy="steps",
    eval_steps=50,
    load_best_model_at_end=True,
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
)

trainer.train()

2. Parameter-Efficient Fine-Tuning (PEFT)

Train only a small fraction of parameters.

LoRA (Low-Rank Adaptation)

Adds trainable low-rank matrices to existing weights.

Pros:

  • 99% fewer trainable parameters
  • Maintains base model knowledge
  • Fast training (10-20x faster)
  • Easy to switch between adapters

Cons:

  • Slightly lower performance than full fine-tuning
  • Requires base model at inference
from peft import get_peft_model, LoraConfig, TaskType
from transformers import AutoModelForCausalLM, AutoTokenizer

base_model_id = "meta-llama/Llama-2-7b"
model = AutoModelForCausalLM.from_pretrained(base_model_id)
tokenizer = AutoTokenizer.from_pretrained(base_model_id)

# Configure LoRA
lora_config = LoraConfig(
    r=8,  # Rank of low-rank matrices
    lora_alpha=16,  # Scaling factor
    target_modules=["q_proj", "v_proj"],  # Which layers to adapt
    lora_dropout=0.05,
    bias="none",
    task_type=TaskType.CAUSAL_LM
)

# Wrap model with LoRA
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# Output: trainable params: 4,194,304 || all params: 6,738,415,616 || trainable%: 0.06

# Train as normal
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
)
trainer.train()

# Save only LoRA weights
model.save_pretrained("./llama-lora-adapter")

QLoRA (Quantized LoRA)

Combines LoRA with quantization for extreme efficiency.

from peft import prepare_model_for_kbit_training, get_peft_model, LoraConfig
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

# Quantization config
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype="float16",
    bnb_4bit_use_double_quant=True
)

# Load quantized model
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b",
    quantization_config=bnb_config,
    device_map="auto"
)

# Prepare for training
model = prepare_model_for_kbit_training(model)

# Apply LoRA
lora_config = LoraConfig(
    r=8,
    lora_alpha=32,
    target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type=TaskType.CAUSAL_LM
)

model = get_peft_model(model, lora_config)

# Train on single GPU
trainer = Trainer(
    model=model,
    args=TrainingArguments(
        output_dir="./qlora-output",
        per_device_train_batch_size=1,
        gradient_accumulation_steps=4,
        learning_rate=5e-4,
        num_train_epochs=3
Полный SKILL.md на GitHub

Установить llm-fine-tuning-guide в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

README.mdexamples/full_fine_tuning.pyexamples/lora_fine_tuning.pyexamples/qlora_fine_tuning.pyscripts/data_preparation.pyscripts/evaluation_metrics.py

FAQ

Что делает скилл llm-fine-tuning-guide?

Master fine-tuning of large language models for specific domains and tasks. Covers data preparation, training techniques, optimization strategies, and evaluation methods. Use when adapting models for specialized applications, reducing inference costs, or improving domain-specific performance.

Как установить скилл llm-fine-tuning-guide?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл llm-fine-tuning-guide запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить llm-fine-tuning-guide с