# Comparación de herramientas de ajuste fino

Elige el marco de ajuste fino adecuado para entrenar LLMs en los servidores GPU de Clore.ai.

{% hint style="info" %}
**Ajuste fino** adapta un LLM preentrenado a tu tarea o dominio específico. Esta guía compara las cuatro herramientas de código abierto líderes: Unsloth, Axolotl, LLaMA-Factory y TRL — cubriendo velocidad, eficiencia de memoria, modelos compatibles y facilidad de uso.
{% endhint %}

***

## Matriz de decisión rápida

|                             | Unsloth                             | Axolotl                               | LLaMA-Factory           | TRL                  |
| --------------------------- | ----------------------------------- | ------------------------------------- | ----------------------- | -------------------- |
| **Mejor para**              | Velocidad + memoria                 | Entrenamiento basado en configuración | Apto para principiantes | Investigación + RLHF |
| **Velocidad vs línea base** | 2-5× más rápido                     | \~1× (estándar)                       | \~1× (estándar)         | \~1× (estándar)      |
| **Reducción de memoria**    | 70-80% menos                        | Estándar QLoRA                        | Estándar QLoRA          | Estándar             |
| **RLHF/DPO/PPO**            | Básico                              | ✅                                     | ✅                       | ✅ (nativo)           |
| **Interfaz web**            | ❌                                   | ❌                                     | ✅                       | ❌                    |
| **Estrellas en GitHub**     | 23K+                                | 9K+                                   | 37K+                    | 10K+                 |
| **Licencia**                | LGPL (gratis para uso no comercial) | Apache 2.0                            | Apache 2.0              | Apache 2.0           |

***

## Resumen

### Unsloth

Unsloth se centra por completo en una cosa: hacer que el ajuste fino sea lo más rápido y eficiente en memoria posible. Reescribe operaciones clave en Triton y optimiza kernels CUDA.

**Filosofía**: Velocidad máxima, VRAM mínima — sin compromisos.

```python
from unsloth import FastLanguageModel
import torch

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Llama-3.2-8B-Instruct",
    max_seq_length=2048,
    load_in_4bit=True,  # cuantización a 4 bits
)

model = FastLanguageModel.get_peft_model(
    model,
    r=16,              # rango LoRA
    target_modules=["q_proj", "k_proj", "v_proj", "up_proj", "down_proj"],
    lora_alpha=16,
    lora_dropout=0,
    bias="none",
    use_gradient_checkpointing="unsloth",  # ~30% más de tamaño de batch
    random_state=42,
)
```

### Axolotl

Axolotl envuelve HuggingFace Transformers con un sistema de configuración basado en YAML. Maneja la complejidad de la configuración del entrenamiento para que puedas concentrarte en los datos y los hiperparámetros.

**Filosofía**: Todo en YAML, flexibilidad total debajo.

```yaml
# config.yml
base_model: meta-llama/Meta-Llama-3-8B
model_type: LlamaForCausalLM
tokenizer_type: AutoTokenizer

datasets:
  - path: mhenrichsen/alpaca_data_cleaned
    type: alpaca

load_in_4bit: true
adapter: qlora

lora_r: 32
lora_alpha: 16
lora_target_modules:
  - q_proj
  - k_proj
  - v_proj
  - o_proj

num_epochs: 3
micro_batch_size: 2
gradient_accumulation_steps: 4
learning_rate: 2e-4
```

### LLaMA-Factory

LLaMA-Factory admite la gama más amplia de modelos (100+) y métodos de entrenamiento, con una interfaz web para la configuración. Es la opción más accesible para personas no dedicadas a la investigación.

**Filosofía**: Todo funciona, para todos.

```bash
# Entrenar vía línea de comandos
llamafactory-cli train \
  --model_name_or_path meta-llama/Meta-Llama-3-8B \
  --stage sft \
  --do_train \
  --dataset alpaca_gpt4_en \
  --template llama3 \
  --finetuning_type lora \
  --lora_rank 8 \
  --output_dir saves/llama3-8b-lora \
  --num_train_epochs 3.0 \
  --per_device_train_batch_size 2

# O usar WebUI
llamafactory-cli webui
```

### TRL (Transformer Reinforcement Learning)

TRL es la biblioteca oficial de HuggingFace para RLHF. Es el estándar para PPO, DPO, ORPO y otros métodos de entrenamiento de alineación.

**Filosofía**: Investigación primero, entrenamiento de alineación nativo.

```python
from trl import SFTTrainer, SFTConfig
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset

model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B")
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B")

training_args = SFTConfig(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=2,
    gradient_accumulation_steps=4,
    learning_rate=2e-4,
    logging_steps=10,
)

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    args=training_args,
    train_dataset=load_dataset("tatsu-lab/alpaca", split="train"),
)

trainer.train()
```

***

## Benchmarks de velocidad

### Comparación de velocidad de entrenamiento (tokens/segundo)

Configuración de prueba: LLaMA 3.1 8B, LoRA r=16, cuantización a 4 bits, tamaño de batch 4, A100 80GB

| Herramienta               | Tokens/seg | vs Línea base | Memoria (VRAM) |
| ------------------------- | ---------- | ------------- | -------------- |
| Unsloth (4-bit)           | \~4,200    | **2.8×**      | \~8GB          |
| Axolotl (QLoRA)           | \~1,500    | 1.0×          | \~16GB         |
| LLaMA-Factory (QLoRA)     | \~1,480    | \~1.0×        | \~16GB         |
| TRL (QLoRA)               | \~1,450    | \~0.97×       | \~18GB         |
| Unsloth (16-bit completo) | \~2,800    | **1.9×**      | \~22GB         |

{% hint style="success" %}
**La ventaja de Unsloth es real**: La velocidad 2-5× proviene de kernels Triton personalizados para atención, entropía cruzada, RoPE y LoRA. No es solo marketing.
{% endhint %}

### Comparación de uso de VRAM

Entrenando LLaMA 3.1 8B, longitud de secuencia 2048:

| Método                        | Unsloth | Axolotl | LLaMA-Factory | TRL  |
| ----------------------------- | ------- | ------- | ------------- | ---- |
| Ajuste fino completo (bf16)   | 60GB    | 70GB    | 72GB          | 74GB |
| LoRA (bf16)                   | 18GB    | 24GB    | 25GB          | 26GB |
| QLoRA (4 bits)                | **8GB** | 16GB    | 16GB          | 18GB |
| QLoRA (4-bit, contexto largo) | 12GB    | 24GB    | 24GB          | 26GB |

**GPU mínima para modelo 8B**:

* Unsloth: RTX 3080 (10GB) ✅
* Otros: se requiere RTX 3090 (24GB)

***

## Modelos compatibles

### Matriz de compatibilidad de modelos

| Familia de modelos | Unsloth | Axolotl | LLaMA-Factory | TRL |
| ------------------ | ------- | ------- | ------------- | --- |
| LLaMA 3.x          | ✅       | ✅       | ✅             | ✅   |
| LLaMA 2            | ✅       | ✅       | ✅             | ✅   |
| Mistral            | ✅       | ✅       | ✅             | ✅   |
| Mixtral MoE        | ✅       | ✅       | ✅             | ✅   |
| Gemma 2            | ✅       | ✅       | ✅             | ✅   |
| Phi-3/3.5          | ✅       | ✅       | ✅             | ✅   |
| Qwen 2.5           | ✅       | ✅       | ✅             | ✅   |
| DeepSeek           | ✅       | ✅       | ✅             | ✅   |
| Falcon             | ✅       | ✅       | ✅             | ✅   |
| GPT-NeoX           | Parcial | ✅       | ✅             | ✅   |
| T5/FLAN            | ❌       | ✅       | ✅             | ✅   |
| BERT/RoBERTa       | ❌       | ✅       | ✅             | ✅   |
| Vision LLMs        | Parcial | Parcial | ✅             | ✅   |

### Soporte de métodos de entrenamiento

| Método                            | Unsloth | Axolotl | LLaMA-Factory | TRL        |
| --------------------------------- | ------- | ------- | ------------- | ---------- |
| Ajuste fino completo              | ✅       | ✅       | ✅             | ✅          |
| LoRA                              | ✅       | ✅       | ✅             | ✅          |
| QLoRA                             | ✅       | ✅       | ✅             | ✅          |
| DoRA                              | ✅       | ✅       | ✅             | ❌          |
| PEFT                              | ✅       | ✅       | ✅             | ✅          |
| SFT                               | ✅       | ✅       | ✅             | ✅ (nativo) |
| DPO                               | ✅       | ✅       | ✅             | ✅ (nativo) |
| PPO                               | ❌       | ✅       | ✅             | ✅ (nativo) |
| ORPO                              | ✅       | ✅       | ✅             | ✅          |
| KTO                               | ❌       | ✅       | ✅             | ✅ (nativo) |
| GRPO                              | ✅       | ❌       | ✅             | ✅          |
| CPT (preentrenamiento continuado) | ✅       | ✅       | ✅             | ✅          |

***

## Unsloth: Análisis en profundidad

### Qué lo hace rápido

1. **Kernels Triton**: Reescribe Flash Attention, la pérdida de entropía cruzada y LoRA en Triton
2. **Operaciones fusionadas**: Combina múltiples operaciones CUDA en un solo kernel
3. **Checkpointing de gradiente inteligente**: El modo "unsloth" ahorra \~30% más de memoria
4. **Backprop eficiente**: Evita materializar grandes tensores intermedios

### Instalación en Clore.ai

```bash
# CUDA 12.1
pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
pip install --no-deps trl peft accelerate bitsandbytes

# O con conda
conda create --name unsloth_env python=3.11
conda activate unsloth_env
conda install pytorch-cuda=12.1 pytorch cudatoolkit xformers -c pytorch -c nvidia -c xformers -y
pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
pip install --no-deps trl peft accelerate bitsandbytes
```

### Script de entrenamiento completo

```python
from unsloth import FastLanguageModel
from trl import SFTTrainer
from transformers import TrainingArguments
from datasets import load_dataset
import torch

# 1. Cargar modelo con la optimización de Unsloth
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Meta-Llama-3.1-8B-Instruct",
    max_seq_length=2048,
    dtype=None,        # Detección automática
    load_in_4bit=True,
)

# 2. Añadir adaptador LoRA
model = FastLanguageModel.get_peft_model(
    model,
    r=16,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                    "gate_proj", "up_proj", "down_proj"],
    lora_alpha=16,
    lora_dropout=0,
    bias="none",
    use_gradient_checkpointing="unsloth",
    random_state=3407,
)

# 3. Cargar y formatear dataset
dataset = load_dataset("tatsu-lab/alpaca", split="train")

def format_prompt(example):
    return {"text": f"### Instruction:\n{example['instruction']}\n\n### Response:\n{example['output']}"}

dataset = dataset.map(format_prompt)

# 4. Entrenar
trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset,
    dataset_text_field="text",
    max_seq_length=2048,
    args=TrainingArguments(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        warmup_steps=5,
        num_train_epochs=1,
        learning_rate=2e-4,
        fp16=not torch.cuda.is_bf16_supported(),
        bf16=torch.cuda.is_bf16_supported(),
        logging_steps=1,
        optim="adamw_8bit",
        weight_decay=0.01,
        lr_scheduler_type="linear",
        seed=3407,
        output_dir="outputs",
    ),
)
trainer.train()

# 5. Guardar
model.save_pretrained("lora_model")
model.save_pretrained_gguf("model_gguf", tokenizer, quantization_method="q4_k_m")
```

**Debilidades**: No hay PPO, limitado a la lista de modelos compatibles, licencia LGPL (verificar uso comercial)

***

## Axolotl: Análisis en profundidad

### Enfoque centrado en la configuración

Axolotl destaca cuando quieres configuraciones de entrenamiento reproducibles y versionadas:

```yaml
# axolotl_config.yml — ejemplo completo
base_model: meta-llama/Meta-Llama-3-8B-Instruct
model_type: LlamaForCausalLM
tokenizer_type: AutoTokenizer

# Datos
datasets:
  - path: tatsu-lab/alpaca
    type: alpaca
  - path: ./my_custom_data.jsonl
    type: sharegpt
dataset_prepared_path: ./prepared_data
val_set_size: 0.01

# Cuantización
load_in_4bit: true
adapter: qlora
bf16: true
tf32: true

# LoRA
lora_r: 32
lora_alpha: 16
lora_dropout: 0.05
lora_target_modules:
  - q_proj
  - v_proj
  - k_proj
  - o_proj
  - gate_proj
  - up_proj
  - down_proj

# Entrenamiento
sequence_len: 4096
sample_packing: true  # Empaqueta secuencias cortas para mayor eficiencia
pad_to_sequence_len: true
micro_batch_size: 2
gradient_accumulation_steps: 4
num_epochs: 3
learning_rate: 0.0002
optimizer: adamw_bnb_8bit
lr_scheduler: cosine

# Registro
logging_steps: 10
eval_steps: 100
save_steps: 100
output_dir: ./outputs/my-model

# wandb
wandb_project: my-fine-tune
wandb_run_id: run-001
```

```bash
# Instalar y ejecutar
pip install axolotl[flash-attn,deepspeed]
axolotl train axolotl_config.yml
```

**Mejor para**: Equipos que quieren ejecuciones de entrenamiento reproducibles y versionadas por configuración

***

## LLaMA-Factory: Análisis en profundidad

### Recorrido por la WebUI

```bash
# Instalar
pip install llamafactory

# Lanzar WebUI
llamafactory-cli webui
# Abrir http://localhost:7860
```

Pestañas de la WebUI:

1. **Entrenar** — configurar modelo base, dataset, método
2. **Evaluar** — ejecutar benchmarks MMLU, CMMLU
3. **Chat** — inferencia interactiva
4. **Exportar** — fusionar LoRA, cuantizar a GGUF

### Ejemplo de entrenamiento por CLI

```bash
# Ajuste fino supervisado
llamafactory-cli train \
  --stage sft \
  --model_name_or_path meta-llama/Meta-Llama-3-8B \
  --dataset alpaca_gpt4_en,glaive_toolcall_en \
  --template llama3 \
  --finetuning_type lora \
  --lora_rank 8 \
  --lora_alpha 16 \
  --lora_target all \
  --output_dir saves/llama3-lora \
  --num_train_epochs 3 \
  --per_device_train_batch_size 2 \
  --gradient_accumulation_steps 4 \
  --learning_rate 2e-4 \
  --quantization_bit 4 \
  --flash_attn fa2

# Entrenamiento DPO
llamafactory-cli train \
  --stage dpo \
  --model_name_or_path meta-llama/Meta-Llama-3-8B \
  --dataset dpo_mix_en \
  --template llama3 \
  --finetuning_type lora \
  --output_dir saves/llama3-dpo
```

**Mejor para**: Principiantes, equipos que desean WebUI, DPO/RLHF sin conocimiento profundo de investigación

***

## TRL: Análisis en profundidad

### Ejemplo de pipeline RLHF

TRL es la opción de referencia para entrenamiento de alineación:

```python
from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead
from trl import DPOTrainer, DPOConfig
from datasets import load_dataset

# DPO (Direct Preference Optimization) — método de alineación más común
model_name = "meta-llama/Meta-Llama-3-8B-Instruct"

dpo_config = DPOConfig(
    model_name_or_path=model_name,
    output_dir="dpo_outputs",
    num_train_epochs=1,
    per_device_train_batch_size=2,
    beta=0.1,             # coeficiente de penalización KL
    loss_type="sigmoid",  # o "hinge", "ipo", "kto_pair"
    learning_rate=5e-7,
)

# Cargar dataset de preferencias (prompt + elegido + rechazado)
dataset = load_dataset("Anthropic/hh-rlhf", split="train")

trainer = DPOTrainer(
    model=model_name,
    args=dpo_config,
    train_dataset=dataset,
)
trainer.train()
```

**Mejor para**: Investigación de alineación, RLHF, implementaciones de DPO, PPO, ORPO

***

## Elección de la herramienta adecuada

### Flujo de decisión

```
¿Necesitas velocidad máxima/VRAM mínima?
  → SÍ → Unsloth (2-5× más rápido, cabe en GPUs más pequeñas)

¿Necesitas entrenamiento de alineación (DPO/PPO/RLHF)?
  → SÍ → TRL o LLaMA-Factory
  → Investigación/personalizado → TRL
  → Producción/fácil → LLaMA-Factory

¿Necesitas reproducibilidad centrada en la configuración?
  → SÍ → Axolotl

¿Equipo no técnico o quieres WebUI?
  → SÍ → LLaMA-Factory

¿Solo quieres empezar rápidamente?
  → LLaMA-Factory o Unsloth
```

### Por tipo de equipo

| Equipo                  | Recomendación | Razón                                       |
| ----------------------- | ------------- | ------------------------------------------- |
| Investigador individual | Unsloth       | Velocidad + notebooks Jupyter               |
| Ingeniero de ML         | Axolotl       | Basado en configuración, reproducible       |
| Equipo de producto      | LLaMA-Factory | WebUI, amplio soporte de modelos            |
| Equipo de alineación    | TRL           | Primitivas RLHF nativas                     |
| Startup                 | Unsloth + TRL | Velocidad + alineación cuando sea necesario |

***

## Recomendaciones de GPU en Clore.ai

| Tarea             | GPU mínima      | Recomendado  | Herramienta     |
| ----------------- | --------------- | ------------ | --------------- |
| 7-8B LoRA (QLoRA) | RTX 3080 (10GB) | RTX 3090     | Unsloth         |
| 13B LoRA          | RTX 3090 (24GB) | A6000 (48GB) | Unsloth/Axolotl |
| 70B LoRA          | A100 (80GB)     | 2×A100       | Axolotl/TRL     |
| 8B FT completo    | A100 (40GB)     | A100 (80GB)  | Cualquiera      |
| DPO/PPO 7B        | RTX 4090 (24GB) | A6000 (48GB) | TRL             |

***

## Enlaces útiles

* [Unsloth GitHub](https://github.com/unslothai/unsloth) — 23K+ estrellas
* [Axolotl GitHub](https://github.com/axolotl-ai-cloud/axolotl) — 9K+ estrellas
* [LLaMA-Factory GitHub](https://github.com/hiyouga/LLaMA-Factory) — 37K+ estrellas
* [TRL GitHub](https://github.com/huggingface/trl) — 10K+ estrellas
* [Documentación HuggingFace PEFT](https://huggingface.co/docs/peft)

***

## Resumen

| Herramienta       | Mejor para                                         | Ventaja clave                          |
| ----------------- | -------------------------------------------------- | -------------------------------------- |
| **Unsloth**       | Entrenamiento crítico por velocidad, GPUs pequeñas | 2-5× más rápido, 70% menos VRAM        |
| **Axolotl**       | Ejecuciones reproducibles basadas en configuración | YAML primero, muchos formatos de datos |
| **LLaMA-Factory** | 100+ modelos, WebUI, ideal para principiantes      | Mayor soporte de modelos, GUI          |
| **TRL**           | RLHF, DPO, investigación de alineación             | Entrenamiento de alineación nativo     |

Para la mayoría de los casos de uso de Clore.ai: comienza con **Unsloth** (velocidad + eficiencia de memoria), añade **TRL** si necesitas entrenamiento de alineación DPO o PPO.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-es/comparaciones/finetuning-comparison.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
