Logo Llm Finetuning

Llm Finetuning

Cộng đồng
j4flmao
llm-finetuning

Use this skill when the user says 'fine-tune an LLM', 'LoRA', 'QLoRA', 'PEFT', 'SFT', 'instruction tuning', 'TRL SFTTrainer', 'DPO', 'train on my data', 'merge adapter'. Decides whether fine-tuning is the right tool, prepares chat-format datasets, configures LoRA/QLoRA with PEFT and TRL, evaluates against the base model, and exports or serves adapters. Do NOT use for: pre-training or full-parameter distributed training (ai model-training skills), post-training quantization for serving (ai/llm-engineering/model-quantization), or prompt-only improvements (prompt-engineering/*).

Tổng quan

Nhà phát hànhj4flmao
Kho mãagent-skills
Tên kỹ năngllm-finetuning
Sao
41
Bản fork
6
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được j4flmao công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Llm Finetuning trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-finetuning
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/ai/llm-finetuning .claude/skills/llm-finetuning
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Llm Finetuning trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Llm Finetuning ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Llm Finetuning với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

LLM Fine-Tuning (PEFT / LoRA)

Purpose

Fine-tuning changes model behaviour (format, style, task skill, domain language) from examples. It is the wrong tool for injecting frequently changing facts; use retrieval for that. Parameter-efficient methods such as LoRA train small low-rank adapters on frozen base weights, making single-GPU training of 7-8B models routine and letting one base model serve many adapters.

Agent Protocol

Trigger

"fine-tune", "LoRA", "QLoRA", "PEFT", "SFT", "instruction tuning", "DPO", "preference tuning", "adapter", "merge_and_unload".

Input Context

  • Goal and why prompting/RAG is insufficient (with failing examples).
  • Dataset: size, source, license, format, PII status.
  • Base model and license; GPU type/VRAM; serving target.
  • Eval set and success metric.

Output Artifact

Go/no-go decision, dataset spec, training config, eval plan, export/serving instructions.

Response Format

Decision: {fine-tune|RAG|prompting} because {reason}
Base model: {id} (license {x})  Method: {LoRA|QLoRA|full}  Stage: {SFT|DPO}
Data: {n} examples, chat format, split {train/val/test}
LoRA: r={r} alpha={a} dropout={p} targets={modules}
Train: lr={lr} epochs={e} eff_batch={b} max_len={L}
Eval: base vs tuned on {metric}; regression suite {name}
Export: {adapter|merged} -> {engine}

Completion Criteria

  • Baseline (prompted base model, RAG) measured first.
  • Held-out test set never used for tuning decisions.
  • Chat template of the base model applied consistently in training and inference.
  • Tuned model beats baseline on the target metric without regressions on general checks.

Should You Fine-Tune?

GoalBest tool
New/changing facts, citationsRAG
Output format, tone, strict schemaPrompting + structured outputs first; SFT if still unreliable
Narrow task at lower cost/latencySFT a smaller model (often distilled from a larger one)
Preference (helpfulness, style ranking)DPO/ORPO after SFT
Domain vocabulary/styleSFT (or continued pre-training for large corpora)

Dataset

  • Use the conversational format and let the tokenizer's chat template render it:
    json
    {"messages": [{"role": "system", "content": "You extract invoice fields as JSON."},
                  {"role": "user", "content": "<invoice text>"},
                  {"role": "assistant", "content": "{\"total\": 129.5, \"currency\": \"EUR\"}"}]}
  • Quality over quantity: a few hundred to a few thousand clean, diverse examples often suffice for format/task tuning.
  • Deduplicate (exact + near-duplicate), remove PII/secrets, check licenses, balance classes, and keep a stratified held-out test split.
  • Train on assistant tokens only (loss masking of prompts) unless you have a reason not to; TRL supports this via its completion/assistant-only loss options.

LoRA / QLoRA Training (PEFT + TRL)

python
from __future__ import annotations

import torch
from datasets import load_dataset
from peft import LoraConfig
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer

BASE = "meta-llama/Llama-3.1-8B-Instruct"
USE_QLORA = True

tokenizer = AutoTokenizer.from_pretrained(BASE)
quant = BitsAndBytesConfig(
    load_in_4bit=True, bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True,
) if USE_QLORA else None

model = AutoModelForCausalLM.from_pretrained(
    BASE,
    dtype=torch.bfloat16,          # transformers >= 4.56; older versions use torch_dtype=
    quantization_config=quant,
    device_map="auto",
)

lora = LoraConfig(
    r=16, lora_alpha=32, lora_dropout=0.05, bias="none",
    target_modules="all-linear",   # attention + MLP projections; better than q/v only
    task_type="CAUSAL_LM",
)

data = load_dataset("json", data_files={"train": "train.jsonl", "validation": "val.jsonl"})

args = SFTConfig(
    output_dir="out/invoice-lora",
    num_train_epochs=2,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,       # effective batch 16
    learning_rate=2e-4,                  # LoRA tolerates higher LR than full FT (~1e-5)
    lr_scheduler_type="cosine",
    warmup_ratio=0.03,
    bf16=True,
    gradient_checkpointing=True,
    logging_steps=10,
    eval_strategy="steps",
    eval_steps=100,
    save_steps=100,
    report_to="none",
)

trainer = SFTTrainer(
    model=model, args=args, processing_class=tokenizer,
    train_dataset=data["train"], eval_dataset=data["validation"], peft_config=lora,
)
trainer.train()
trainer.save_model("out/invoice-lora/final")   # saves the adapter only

TRL and transformers rename arguments between releases (e.g. tokenizer → processing_class, max_seq_length → max_length); pin versions in pyproject.toml and check the installed release's docs.

Hyperparameter Guide

ParamStartNotes
r8-32Higher for harder/new skills; diminishing returns
lora_alpha2·rEffective scale = alpha/r (or alpha/√r with rsLoRA)
LR1e-4 to 2e-4 (LoRA)Lower for larger models/datasets
Epochs1-3Watch val loss; more epochs → memorization
Max lengthCover p95 of examplesTruncation silently drops labels

Evaluation

  1. Task metric on the held-out test set: base (best prompt) vs tuned.
  2. Regression checks: general instruction following, safety refusals, a few unrelated tasks.
  3. Inspect outputs manually; loss curves alone hide format collapse.

Export & Serving

  • Adapter serving: vLLM --enable-lora --lora-modules invoice=out/invoice-lora/final serves many adapters on one base.
  • Merge: PeftModel.from_pretrained(base_bf16, path).merge_and_unload() then save_pretrained. Merge into a bf16 base, not the 4-bit one; quantize afterwards if needed.

Anti-Patterns

  • Fine-tuning to teach facts that change weekly.
  • Training on the test set or tuning hyperparameters against it.
  • Inconsistent chat templates between training and inference.
  • Only targeting q_proj/v_proj by habit when quality matters.
  • Hardcoding .to("cuda"); use device_map="auto".
  • Ignoring base-model license terms for derivatives.

Checklist

  • Baseline measured; decision documented.
  • Dataset cleaned, deduped, PII-free, licensed, split.
  • Chat template + assistant-only loss.
  • Config versioned; library versions pinned.
  • Eval: target metric + regressions.
  • Export path tested in the serving engine.

References

  • Hu et al., "LoRA" (ICLR 2022); Dettmers et al., "QLoRA" (NeurIPS 2023); Rafailov et al., "DPO" (NeurIPS 2023).
  • Hugging Face PEFT and TRL documentation (SFTTrainer, DPOTrainer).

Câu hỏi thường gặp

Kỹ năng AI Llm Finetuning làm được gì?

Use this skill when the user says 'fine-tune an LLM', 'LoRA', 'QLoRA', 'PEFT', 'SFT', 'instruction tuning', 'TRL SFTTrainer', 'DPO', 'train on my data', 'merge adapter'. Decides whether fine-tuning is the right tool, prepares chat-format datasets, configures LoRA/QLoRA with PEFT and TRL, evaluates against the base model, and exports or serves adapters. Do NOT use for: pre-training or full-parameter distributed training (ai model-training skills), post-training quantization for serving (ai/llm-engineering/model-quantization), or prompt-only improvements (prompt-engineering/*).

Vì sao nên dùng Llm Finetuning trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Llm Finetuning là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Llm Finetuning trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-finetuning. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Llm Finetuning?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Llm Finetuning với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Llm Finetuning với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Llm Finetuning có miễn phí không?

Có. Kỹ năng này được j4flmao phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇