Logotipo de Llm Finetuning

Llm Finetuning

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

Descripción general

Editorj4flmao
Repositorioagent-skills
Nombre de la habilidadllm-finetuning
Estrellas
41
Forks
6
Archivos incluidos
Solo instrucciones
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por j4flmao en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Llm Finetuning en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-finetuning
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese 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
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Llm Finetuning en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Llm Finetuning automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Llm Finetuning no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo 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).

Preguntas frecuentes

¿Qué hace la habilidad de 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/*).

¿Por qué usar Llm Finetuning en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Llm Finetuning está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Llm Finetuning en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-finetuning. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Llm Finetuning?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Llm Finetuning?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Llm Finetuning con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Llm Finetuning?

Sí. j4flmao la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇