Logo di Llm Finetuning

Llm Finetuning

Community
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/*).

Panoramica

Pubblicato daj4flmao
Repositoryagent-skills
Nome della skillllm-finetuning
Stelle
41
Fork
6
File inclusi
Solo istruzioni
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • Tutto nelle istruzioni

    Tutto ciò che serve al modello è nelle istruzioni: nessun file aggiuntivo da sincronizzare.

  • Open source

    Pubblicata da j4flmao su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Llm Finetuning in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-finetuning
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Aggiungi skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella della skill nella directory delle skill di quell'agente.

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
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Llm Finetuning in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Llm Finetuning non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Llm Finetuning non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

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).

Domande frequenti

Cosa fa la skill IA 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/*).

Perché usare Llm Finetuning su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Llm Finetuning è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che la skill smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Llm Finetuning in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-finetuning. TypingMind legge il file SKILL.md e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Llm Finetuning?

Qualsiasi modello che colleghi a TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Llm Finetuning?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Llm Finetuning: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Llm Finetuning è gratuita?

Sì. È pubblicata su GitHub da j4flmao con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, template o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Elenco completo

Crea subito il tuo spazio di lavoro AI

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇