[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6PZVGSQ5X5YPPHSKGGVAWET":3,"skill-same:01M6PZVGSQ5X5YPPHSKGGVAWET":77},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":27,"commitSha":58,"skillDirectory":59,"forksCount":13,"repositoryHtmlUrl":60,"repositoryHomepageUrl":6,"ownerHtmlUrl":61,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":62,"install":63,"resources":76},"01M6PZVGSQ5X5YPPHSKGGVAWET","unsloth-finetuning",null,"Fine-tune and post-train LLMs with Unsloth Core on a single consumer GPU: VRAM sizing, LoRA\u002FQLoRA, GRPO\u002FDPO, chat-template correctness, and GGUF export.","duc-duy-1612\u002FOnline-Delivery-Systems-Web","duc-duy-1612","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F192231384?v=4","01M6NSDKQQDKVTHZ8DZMZ1VYY6","01M6NSDKW8DDVTQHBT1HBDDJPT",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Funsloth-finetuning\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"finetuning","unsloth finetuning","Unsloth","template","single","vram","correctness","GGUF","critical","main","community","export","gemini","tuning","LoRA","Fine-Tuning","license","core","ml","llms","2026-11-10 10:12:30",false,"---\nname: unsloth-finetuning\ndescription: \"Fine-tune and post-train LLMs with Unsloth Core on a single consumer GPU: VRAM sizing, LoRA\u002FQLoRA, GRPO\u002FDPO, chat-template correctness, and GGUF export.\"\ncategory: ai-ml\nrisk: critical\nsource: community\nsource_repo: unslothai\u002Funsloth\nsource_type: community\ndate_added: \"2026-08-27\"\nauthor: A-ryanVAT-S\ntags: [unsloth, fine-tuning, lora, qlora, grpo, gguf, vram]\ntools: [claude, cursor, gemini]\nlicense: \"Apache-2.0\"\nlicense_source: \"https:\u002F\u002Fgithub.com\u002Funslothai\u002Funsloth\u002Fblob\u002Fmain\u002FLICENSE\"\n---\n\n# Unsloth Fine-Tuning\n\n## Overview\n\nUnsloth trains LLMs with custom kernels that cut VRAM use and step time without changing the\nmath, which makes single-GPU fine-tuning practical on hardware that would otherwise OOM.\nThis skill covers **Unsloth Core** — the Python API — because that is what an agent can drive\nprogrammatically; the Desktop app and Studio web UI are interactive and out of scope.\n\nThe hard parts of an Unsloth run are not the training call. They are sizing the job against\navailable VRAM, getting the chat template and loss masking right, and choosing an export\nformat the target runtime can actually load. This skill covers those three.\n\n## When to Use This Skill\n\n- Use when fine-tuning an LLM on one GPU and VRAM is the binding constraint.\n- Use when a training run OOMs and needs to be resized rather than rewritten.\n- Use when doing preference or RL post-training (GRPO, DPO) on consumer hardware.\n- Use when a fine-tuned model must be exported to GGUF, vLLM, or merged 16-bit weights.\n- Use when a fine-tune \"ran fine\" but the model's output format is wrong — usually a chat\n  template or loss-masking bug, not a hyperparameter one.\n\n### Do not use this skill when\n\n- The training is multi-node or large-scale multi-GPU. Use plain TRL with Accelerate\u002FDeepSpeed.\n- The architecture is unsupported by Unsloth. Fall back to TRL; do not force it.\n- The user wants managed cloud training. That is Hugging Face Jobs, not local Unsloth.\n- The user wants the Desktop or Studio GUI. Point them at the installer, not this skill.\n\n## How It Works\n\n### Step 1: Size the run before writing code\n\nVRAM is the constraint that decides everything else. Estimate weights first, then leave room\nfor activations and optimizer state:\n\n| Load mode | Weight cost | 8B model | Use when |\n| :--- | :--- | :--- | :--- |\n| `load_in_4bit` (QLoRA) | ~0.55 GB per 1B params | ~4.5 GB | Default. Under 16 GB VRAM. |\n| `load_in_8bit` | ~1.1 GB per 1B params | ~9 GB | Quality-sensitive, 16-24 GB. |\n| `load_in_16bit` | ~2 GB per 1B params | ~16 GB | LoRA at full precision, 24 GB+. |\n| `full_finetuning=True` | ~2 GB weights + ~12 GB optimizer | ~112 GB | Rarely justified. Prefer LoRA. |\n\nAdd roughly 2-6 GB for activations, scaling with `max_seq_length` and batch size. Treat these\nas planning figures and confirm against `nvidia-smi` on the first run — they vary by\narchitecture, attention implementation and vocabulary size.\n\nIf the estimate does not fit, reduce in this order: `max_seq_length`, then batch size (raising\n`gradient_accumulation_steps` to hold the effective batch constant), then LoRA rank, then model\nsize. Cutting rank before sequence length usually costs more quality than it saves memory.\n\n### Step 2: Load the model\n\n`import unsloth` must come **before** `transformers`, `trl` or `peft`. Unsloth patches those\nlibraries at import time; importing them first silently disables the optimizations.\n\n```python\nimport unsloth  # must be first\nimport os\nimport re\nfrom unsloth import FastLanguageModel\n\ndef reviewed_revision(variable):\n    revision = os.environ.get(variable, \"\")\n    if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) is None:\n        raise RuntimeError(f\"{variable} must be a reviewed full 40-character Hub commit SHA\")\n    return revision.lower()\n\nmodel_revision = reviewed_revision(\"UNSLOTH_MODEL_REVISION\")\nmodel, tokenizer = FastLanguageModel.from_pretrained(\n    model_name = \"unsloth\u002FQwen3-8B\",\n    revision = model_revision,\n    max_seq_length = 2048,\n    load_in_4bit = True,\n    dtype = None,  # auto-detects bf16 where supported\n)\n```\n\nPick the loader that matches the modality: `FastLanguageModel` for text-only causal LMs,\n`FastVisionModel` for vision-language models, `FastModel` when the modality is decided at runtime.\n\nThe `unsloth\u002F` Hub namespace holds pre-quantized copies that download faster and skip a local\nquantization pass. Upstream repos such as `Qwen\u002F` or `meta-llama\u002F` work identically.\nBefore setting `UNSLOTH_MODEL_REVISION`, inspect that exact Hub commit and obtain approval for the\ndownload. Record the repository and full revision with the run; never substitute a branch, tag,\nrange, or moving default.\n\n### Step 3: Fix the chat template before training\n\nThis is the most common silent failure. A run with the wrong template converges cleanly and\nproduces a model that ignores its stop tokens or emits prompt scaffolding at inference.\n\n```python\nfrom unsloth.chat_templates import (\n    get_chat_template,\n    standardize_data_formats,\n    train_on_responses_only,\n)\n\ntokenizer = get_chat_template(tokenizer, chat_template = \"qwen3\")\ndataset = standardize_data_formats(dataset)  # normalizes ShareGPT\u002FOpenAI column names\n```\n\nThen mask the prompt so loss is computed on assistant turns only. Without this, the model is\nalso trained to generate user messages:\n\n```python\ntrainer = train_on_responses_only(\n    trainer,\n    instruction_part = \"\u003C|im_start|>user\\n\",\n    response_part = \"\u003C|im_start|>assistant\\n\",\n)\n```\n\nThe two part strings must match the template's actual delimiters. Verify by decoding one batch\nand confirming the masked region covers exactly the prompt.\n\n### Step 4: Attach LoRA adapters\n\n```python\nmodel = FastLanguageModel.get_peft_model(\n    model,\n    r = 16,\n    lora_alpha = 16,\n    lora_dropout = 0.0,\n    target_modules = [\n        \"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n        \"gate_proj\", \"up_proj\", \"down_proj\",\n    ],\n    use_gradient_checkpointing = \"unsloth\",  # Unsloth's variant, lower VRAM than True\n    random_state = 3407,\n)\n```\n\nRank guidance: `r=8-16` for style and format adaptation, `r=32-64` when teaching genuinely new\ncapability. Setting `lora_alpha` to 1-2x `r` is a safe default. Keep `lora_dropout = 0.0` —\nUnsloth's fast path is only taken when dropout is zero.\n\nTrain all seven projection modules unless VRAM forces otherwise; attention-only LoRA\nunderperforms noticeably on instruction data. For MoE models, expert layers are `nn.Parameter`\nrather than `nn.Linear` and need `target_parameters` instead of `target_modules`.\n\n### Step 5: Train\n\nUnsloth returns standard PEFT-wrapped models, so TRL's trainers work unmodified.\n\n```python\nfrom trl import SFTTrainer, SFTConfig\n\ntrainer = SFTTrainer(\n    model = model,\n    tokenizer = tokenizer,\n    train_dataset = dataset,\n    args = SFTConfig(\n        per_device_train_batch_size = 2,\n        gradient_accumulation_steps = 8,  # effective batch 16\n        warmup_steps = 5,\n        num_train_epochs = 1,\n        learning_rate = 2e-4,\n        optim = \"adamw_8bit\",\n        output_dir = \"outputs\",\n    ),\n)\ntrainer.train()\n```\n\n`2e-4` suits LoRA; full fine-tuning needs roughly 10x lower. One to three epochs is typical —\nLoRA overfits small datasets quickly, so watch eval loss rather than trusting an epoch count.\n\n### Step 6: Export to the target runtime\n\nThe right format depends entirely on where the model will run:\n\n| Target | Call | Notes |\n| :--- | :--- | :--- |\n| llama.cpp \u002F Ollama \u002F LM Studio | `model.save_pretrained_gguf(dir, tokenizer, quantization_method=\"q4_k_m\")` | Builds llama.cpp on first use. |\n| vLLM \u002F TGI \u002F Transformers | `model.save_pretrained_merged(dir, tokenizer, save_method=\"merged_16bit\")` | Full-size weights. |\n| Adapter only (swapped at runtime) | `model.save_pretrained_merged(dir, tokenizer, save_method=\"lora\")` | Megabytes, not gigabytes. |\n| Hugging Face Hub | `model.push_to_hub_gguf(...)` \u002F `model.push_to_hub_merged(...)` | Needs a write token. |\n\n`quantization_method` accepts a list, so several GGUF quants can be produced in one conversion\npass: `[\"q4_k_m\", \"q5_k_m\", \"q8_0\"]`. `q4_k_m` is the usual quality\u002Fsize compromise. The `iq*`\nimportance-matrix quants additionally require `imatrix_file=`.\n\nAvoid `save_method=\"merged_4bit\"` for anything redistributed — it bakes in the quantization and\ncannot be cleanly re-quantized afterwards.\n\n## Examples\n\n### Example 1: QLoRA SFT on a 16 GB GPU\n\n```python\nimport unsloth\nimport os\nimport re\nfrom unsloth import FastLanguageModel\nfrom unsloth.chat_templates import get_chat_template, train_on_responses_only\nfrom datasets import load_dataset\nfrom trl import SFTTrainer, SFTConfig\n\ndef reviewed_revision(variable):\n    revision = os.environ.get(variable, \"\")\n    if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) is None:\n        raise RuntimeError(f\"{variable} must be a reviewed full 40-character Hub commit SHA\")\n    return revision.lower()\n\nmodel_revision = reviewed_revision(\"UNSLOTH_MODEL_REVISION\")\ndataset_revision = reviewed_revision(\"UNSLOTH_DATASET_REVISION\")\nmodel, tokenizer = FastLanguageModel.from_pretrained(\n    model_name = \"unsloth\u002FQwen3-8B\",\n    revision = model_revision,\n    max_seq_length = 2048,\n    load_in_4bit = True,\n)\nmodel = FastLanguageModel.get_peft_model(model, r = 16, lora_alpha = 16)\n\ntokenizer = get_chat_template(tokenizer, chat_template = \"qwen3\")\ndataset = load_dataset(\n    \"mlabonne\u002FFineTome-100k\",\n    revision = dataset_revision,\n    split = \"train[:5000]\",\n)\n\ntrainer = SFTTrainer(\n    model = model,\n    tokenizer = tokenizer,\n    train_dataset = dataset,\n    args = SFTConfig(\n        per_device_train_batch_size = 2,\n        gradient_accumulation_steps = 8,\n        num_train_epochs = 1,\n        learning_rate = 2e-4,\n        optim = \"adamw_8bit\",\n        output_dir = \"outputs\",\n    ),\n)\ntrainer = train_on_responses_only(\n    trainer,\n    instruction_part = \"\u003C|im_start|>user\\n\",\n    response_part = \"\u003C|im_start|>assistant\\n\",\n)\ntrainer.train()\n\nmodel.save_pretrained_gguf(\"qwen3-tuned\", tokenizer, quantization_method = \"q4_k_m\")\n```\n\n### Example 2: GRPO with vLLM-backed generation\n\nGRPO samples several completions per prompt at every step, so generation dominates step time.\nLoad with `fast_inference=True` to route sampling through vLLM in the same process.\n\n```python\nimport unsloth\nimport os\nimport re\nfrom unsloth import FastLanguageModel\nfrom trl import GRPOTrainer, GRPOConfig\n\ndef reviewed_revision(variable):\n    revision = os.environ.get(variable, \"\")\n    if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) is None:\n        raise RuntimeError(f\"{variable} must be a reviewed full 40-character Hub commit SHA\")\n    return revision.lower()\n\nmodel_revision = reviewed_revision(\"UNSLOTH_MODEL_REVISION\")\nmodel, tokenizer = FastLanguageModel.from_pretrained(\n    model_name = \"unsloth\u002FQwen3-4B\",\n    revision = model_revision,\n    max_seq_length = 1024,\n    load_in_4bit = True,\n    fast_inference = True,       # vLLM sampling backend\n    max_lora_rank = 32,          # must be >= the r used below\n    gpu_memory_utilization = 0.6,\n)\nmodel = FastLanguageModel.get_peft_model(model, r = 32, lora_alpha = 32)\n\ndef reward_length(completions, **kwargs):\n    \"\"\"Placeholder. Replace with a task-specific verifier.\"\"\"\n    return [min(len(c) \u002F 200.0, 1.0) for c in completions]\n\ntrainer = GRPOTrainer(\n    model = model,\n    processing_class = tokenizer,\n    reward_funcs = [reward_length],\n    train_dataset = dataset,\n    args = GRPOConfig(\n        num_generations = 8,\n        max_prompt_length = 256,\n        max_completion_length = 512,\n        learning_rate = 5e-6,\n        output_dir = \"grpo-outputs\",\n    ),\n)\ntrainer.train()\n```\n\n`gpu_memory_utilization` splits VRAM between vLLM's KV cache and training. Raise it if\ngeneration is the bottleneck, lower it if training OOMs. `max_lora_rank` is fixed at load time\nand must be at least the `r` passed later, or adapter loading fails.\n\nGRPO learning rates sit roughly two orders of magnitude below SFT. Reward functions receive\n`completions` plus any dataset columns as keyword arguments, and return one float per completion.\n\n## Best Practices\n\n- ✅ Set `random_state` so a promising run can be reproduced.\n- ✅ Log peak VRAM on the first run and reuse it to size later jobs on the same hardware.\n- ✅ Evaluate the exported artifact, not just the adapter — quantization shifts behaviour.\n- ❌ Don't change `max_seq_length` between training and export; the GGUF inherits it.\n- ❌ Don't tune hyperparameters before the loss mask has been verified once.\n\n## Limitations\n\n- The VRAM figures above are planning heuristics, not benchmarks. Confirm on target hardware.\n- Architecture support changes between releases. Check upstream before assuming a model works.\n- Unsloth's speed and memory claims are the project's own published figures, measured on their\n  own benchmarks; they are not independently verified here.\n- This skill does not replace environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if the GPU, model, dataset format or export target is unknown —\n  every step above depends on those four.\n\n## Security & Safety Notes\n\n- Training commands are long-running and hold the GPU exclusively. Confirm before launching on\n  a shared or remote machine.\n- `push_to_hub_gguf` and `push_to_hub_merged` publish weights to a public Hub repo by default.\n  Confirm intent and pass `private=True` when the model is not meant to be public.\n- Read Hugging Face tokens from the environment (`HF_TOKEN`), never inline in a script. A\n  committed token grants write access to every model the account owns.\n- Fine-tuning reproduces the training data's content and biases in the weights. Confirm the\n  dataset is licensed for training and free of secrets before starting.\n- Pin every Hub model and dataset to a reviewed full commit SHA, obtain approval before changing\n  either revision, and record both values with the training artifact. Prefer the verified local\n  cache for repeat runs instead of re-resolving network defaults.\n- GGUF export builds llama.cpp from source on first use, compiling third-party code and\n  requiring network access. Before the first export, identify and review the exact llama.cpp\n  revision that will be built; do not permit an unattended moving-revision fetch. Prefer a\n  user-approved, full-commit-pinned local toolchain and cache.\n- Unsloth is dual-licensed: the core package is Apache-2.0, while optional components such as\n  the Studio UI are AGPL-3.0. Check a component's license before redistributing it.\n\n## Common Pitfalls\n\n- **Problem:** Trained model ignores stop tokens or echoes the prompt format.\n  **Solution:** Wrong chat template, or `train_on_responses_only` was never applied. Verify the\n  mask on a decoded batch before blaming hyperparameters.\n\n- **Problem:** CUDA OOM partway through the first epoch rather than at step 0.\n  **Solution:** A long sample exceeded the activation budget. Lower `max_seq_length` or filter\n  outliers — peak memory tracks the longest sequence, not the mean.\n\n- **Problem:** Training runs, but at ordinary unaccelerated speed.\n  **Solution:** `transformers` or `trl` was imported before `unsloth`, so the patches never\n  applied. Move `import unsloth` to the top of the file.\n\n- **Problem:** `save_pretrained_gguf` appears to hang on first call.\n  **Solution:** It is building llama.cpp. Ensure a compiler and network access are available, or\n  export `merged_16bit` and convert separately.\n\n- **Problem:** GRPO fails with a LoRA rank mismatch.\n  **Solution:** `max_lora_rank` at `from_pretrained` is below the `r` given to `get_peft_model`.\n  Raise it to match.\n\n- **Problem:** Loss collapses to near zero within a few hundred steps.\n  **Solution:** Overfitting a small dataset, or the loss mask is leaking the answer into the\n  prompt. Check dataset size against epoch count, then re-verify masking.\n\n## Related Skills\n\n- `@trl-training` - Use for the TRL CLI, multi-GPU runs, or architectures Unsloth lacks.\n- `@hugging-face-model-trainer` - Use for managed training on Hugging Face Jobs instead of local hardware.\n- `@local-llm-expert` - Use to serve the exported GGUF via Ollama, llama.cpp or vLLM.\n\n## Additional Resources\n\n- [Unsloth documentation](https:\u002F\u002Funsloth.ai\u002Fdocs)\n- [Reinforcement learning guide (GRPO, DPO)](https:\u002F\u002Funsloth.ai\u002Fdocs\u002Fget-started\u002Freinforcement-learning-rl-guide)\n- [Saving to GGUF](https:\u002F\u002Funsloth.ai\u002Fdocs\u002Fbasics\u002Finference-and-deployment\u002Fsaving-to-gguf)\n- [unslothai\u002Funsloth on GitHub](https:\u002F\u002Fgithub.com\u002Funslothai\u002Funsloth)\n","# Unsloth Fine-Tuning\n\n## Overview\n\nUnsloth trains LLMs with custom kernels that cut VRAM use and step time without changing the\nmath, which makes single-GPU fine-tuning practical on hardware that would otherwise OOM.\nThis skill covers **Unsloth Core** — the Python API — because that is what an agent can drive\nprogrammatically; the Desktop app and Studio web UI are interactive and out of scope.\n\nThe hard parts of an Unsloth run are not the training call. They are sizing the job against\navailable VRAM, getting the chat template and loss masking right, and choosing an export\nformat the target runtime can actually load. This skill covers those three.\n\n## When to Use This Skill\n\n- Use when fine-tuning an LLM on one GPU and VRAM is the binding constraint.\n- Use when a training run OOMs and needs to be resized rather than rewritten.\n- Use when doing preference or RL post-training (GRPO, DPO) on consumer hardware.\n- Use when a fine-tuned model must be exported to GGUF, vLLM, or merged 16-bit weights.\n- Use when a fine-tune \"ran fine\" but the model's output format is wrong — usually a chat\n  template or loss-masking bug, not a hyperparameter one.\n\n### Do not use this skill when\n\n- The training is multi-node or large-scale multi-GPU. Use plain TRL with Accelerate\u002FDeepSpeed.\n- The architecture is unsupported by Unsloth. Fall back to TRL; do not force it.\n- The user wants managed cloud training. That is Hugging Face Jobs, not local Unsloth.\n- The user wants the Desktop or Studio GUI. Point them at the installer, not this skill.\n\n## How It Works\n\n### Step 1: Size the run before writing code\n\nVRAM is the constraint that decides everything else. Estimate weights first, then leave room\nfor activations and optimizer state:\n\n| Load mode | Weight cost | 8B model | Use when |\n| :--- | :--- | :--- | :--- |\n| `load_in_4bit` (QLoRA) | ~0.55 GB per 1B params | ~4.5 GB | Default. Under 16 GB VRAM. |\n| `load_in_8bit` | ~1.1 GB per 1B params | ~9 GB | Quality-sensitive, 16-24 GB. |\n| `load_in_16bit` | ~2 GB per 1B params | ~16 GB | LoRA at full precision, 24 GB+. |\n| `full_finetuning=True` | ~2 GB weights + ~12 GB optimizer | ~112 GB | Rarely justified. Prefer LoRA. |\n\nAdd roughly 2-6 GB for activations, scaling with `max_seq_length` and batch size. Treat these\nas planning figures and confirm against `nvidia-smi` on the first run — they vary by\narchitecture, attention implementation and vocabulary size.\n\nIf the estimate does not fit, reduce in this order: `max_seq_length`, then batch size (raising\n`gradient_accumulation_steps` to hold the effective batch constant), then LoRA rank, then model\nsize. Cutting rank before sequence length usually costs more quality than it saves memory.\n\n### Step 2: Load the model\n\n`import unsloth` must come **before** `transformers`, `trl` or `peft`. Unsloth patches those\nlibraries at import time; importing them first silently disables the optimizations.\n\n```python\nimport unsloth  # must be first\nimport os\nimport re\nfrom unsloth import FastLanguageModel\n\ndef reviewed_revision(variable):\n    revision = os.environ.get(variable, \"\")\n    if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) is None:\n        raise RuntimeError(f\"{variable} must be a reviewed full 40-character Hub commit SHA\")\n    return revision.lower()\n\nmodel_revision = reviewed_revision(\"UNSLOTH_MODEL_REVISION\")\nmodel, tokenizer = FastLanguageModel.from_pretrained(\n    model_name = \"unsloth\u002FQwen3-8B\",\n    revision = model_revision,\n    max_seq_length = 2048,\n    load_in_4bit = True,\n    dtype = None,  # auto-detects bf16 where supported\n)\n```\n\nPick the loader that matches the modality: `FastLanguageModel` for text-only causal LMs,\n`FastVisionModel` for vision-language models, `FastModel` when the modality is decided at runtime.\n\nThe `unsloth\u002F` Hub namespace holds pre-quantized copies that download faster and skip a local\nquantization pass. Upstream repos such as `Qwen\u002F` or `meta-llama\u002F` work identically.\nBefore setting `UNSLOTH_MODEL_REVISION`, inspect that exact Hub commit and obtain approval for the\ndownload. Record the repository and full revision with the run; never substitute a branch, tag,\nrange, or moving default.\n\n### Step 3: Fix the chat template before training\n\nThis is the most common silent failure. A run with the wrong template converges cleanly and\nproduces a model that ignores its stop tokens or emits prompt scaffolding at inference.\n\n```python\nfrom unsloth.chat_templates import (\n    get_chat_template,\n    standardize_data_formats,\n    train_on_responses_only,\n)\n\ntokenizer = get_chat_template(tokenizer, chat_template = \"qwen3\")\ndataset = standardize_data_formats(dataset)  # normalizes ShareGPT\u002FOpenAI column names\n```\n\nThen mask the prompt so loss is computed on assistant turns only. Without this, the model is\nalso trained to generate user messages:\n\n```python\ntrainer = train_on_responses_only(\n    trainer,\n    instruction_part = \"\u003C|im_start|>user\\n\",\n    response_part = \"\u003C|im_start|>assistant\\n\",\n)\n```\n\nThe two part strings must match the template's actual delimiters. Verify by decoding one batch\nand confirming the masked region covers exactly the prompt.\n\n### Step 4: Attach LoRA adapters\n\n```python\nmodel = FastLanguageModel.get_peft_model(\n    model,\n    r = 16,\n    lora_alpha = 16,\n    lora_dropout = 0.0,\n    target_modules = [\n        \"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n        \"gate_proj\", \"up_proj\", \"down_proj\",\n    ],\n    use_gradient_checkpointing = \"unsloth\",  # Unsloth's variant, lower VRAM than True\n    random_state = 3407,\n)\n```\n\nRank guidance: `r=8-16` for style and format adaptation, `r=32-64` when teaching genuinely new\ncapability. Setting `lora_alpha` to 1-2x `r` is a safe default. Keep `lora_dropout = 0.0` —\nUnsloth's fast path is only taken when dropout is zero.\n\nTrain all seven projection modules unless VRAM forces otherwise; attention-only LoRA\nunderperforms noticeably on instruction data. For MoE models, expert layers are `nn.Parameter`\nrather than `nn.Linear` and need `target_parameters` instead of `target_modules`.\n\n### Step 5: Train\n\nUnsloth returns standard PEFT-wrapped models, so TRL's trainers work unmodified.\n\n```python\nfrom trl import SFTTrainer, SFTConfig\n\ntrainer = SFTTrainer(\n    model = model,\n    tokenizer = tokenizer,\n    train_dataset = dataset,\n    args = SFTConfig(\n        per_device_train_batch_size = 2,\n        gradient_accumulation_steps = 8,  # effective batch 16\n        warmup_steps = 5,\n        num_train_epochs = 1,\n        learning_rate = 2e-4,\n        optim = \"adamw_8bit\",\n        output_dir = \"outputs\",\n    ),\n)\ntrainer.train()\n```\n\n`2e-4` suits LoRA; full fine-tuning needs roughly 10x lower. One to three epochs is typical —\nLoRA overfits small datasets quickly, so watch eval loss rather than trusting an epoch count.\n\n### Step 6: Export to the target runtime\n\nThe right format depends entirely on where the model will run:\n\n| Target | Call | Notes |\n| :--- | :--- | :--- |\n| llama.cpp \u002F Ollama \u002F LM Studio | `model.save_pretrained_gguf(dir, tokenizer, quantization_method=\"q4_k_m\")` | Builds llama.cpp on first use. |\n| vLLM \u002F TGI \u002F Transformers | `model.save_pretrained_merged(dir, tokenizer, save_method=\"merged_16bit\")` | Full-size weights. |\n| Adapter only (swapped at runtime) | `model.save_pretrained_merged(dir, tokenizer, save_method=\"lora\")` | Megabytes, not gigabytes. |\n| Hugging Face Hub | `model.push_to_hub_gguf(...)` \u002F `model.push_to_hub_merged(...)` | Needs a write token. |\n\n`quantization_method` accepts a list, so several GGUF quants can be produced in one conversion\npass: `[\"q4_k_m\", \"q5_k_m\", \"q8_0\"]`. `q4_k_m` is the usual quality\u002Fsize compromise. The `iq*`\nimportance-matrix quants additionally require `imatrix_file=`.\n\nAvoid `save_method=\"merged_4bit\"` for anything redistributed — it bakes in the quantization and\ncannot be cleanly re-quantized afterwards.\n\n## Examples\n\n### Example 1: QLoRA SFT on a 16 GB GPU\n\n```python\nimport unsloth\nimport os\nimport re\nfrom unsloth import FastLanguageModel\nfrom unsloth.chat_templates import get_chat_template, train_on_responses_only\nfrom datasets import load_dataset\nfrom trl import SFTTrainer, SFTConfig\n\ndef reviewed_revision(variable):\n    revision = os.environ.get(variable, \"\")\n    if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) is None:\n        raise RuntimeError(f\"{variable} must be a reviewed full 40-character Hub commit SHA\")\n    return revision.lower()\n\nmodel_revision = reviewed_revision(\"UNSLOTH_MODEL_REVISION\")\ndataset_revision = reviewed_revision(\"UNSLOTH_DATASET_REVISION\")\nmodel, tokenizer = FastLanguageModel.from_pretrained(\n    model_name = \"unsloth\u002FQwen3-8B\",\n    revision = model_revision,\n    max_seq_length = 2048,\n    load_in_4bit = True,\n)\nmodel = FastLanguageModel.get_peft_model(model, r = 16, lora_alpha = 16)\n\ntokenizer = get_chat_template(tokenizer, chat_template = \"qwen3\")\ndataset = load_dataset(\n    \"mlabonne\u002FFineTome-100k\",\n    revision = dataset_revision,\n    split = \"train[:5000]\",\n)\n\ntrainer = SFTTrainer(\n    model = model,\n    tokenizer = tokenizer,\n    train_dataset = dataset,\n    args = SFTConfig(\n        per_device_train_batch_size = 2,\n        gradient_accumulation_steps = 8,\n        num_train_epochs = 1,\n        learning_rate = 2e-4,\n        optim = \"adamw_8bit\",\n        output_dir = \"outputs\",\n    ),\n)\ntrainer = train_on_responses_only(\n    trainer,\n    instruction_part = \"\u003C|im_start|>user\\n\",\n    response_part = \"\u003C|im_start|>assistant\\n\",\n)\ntrainer.train()\n\nmodel.save_pretrained_gguf(\"qwen3-tuned\", tokenizer, quantization_method = \"q4_k_m\")\n```\n\n### Example 2: GRPO with vLLM-backed generation\n\nGRPO samples several completions per prompt at every step, so generation dominates step time.\nLoad with `fast_inference=True` to route sampling through vLLM in the same process.\n\n```python\nimport unsloth\nimport os\nimport re\nfrom unsloth import FastLanguageModel\nfrom trl import GRPOTrainer, GRPOConfig\n\ndef reviewed_revision(variable):\n    revision = os.environ.get(variable, \"\")\n    if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) is None:\n        raise RuntimeError(f\"{variable} must be a reviewed full 40-character Hub commit SHA\")\n    return revision.lower()\n\nmodel_revision = reviewed_revision(\"UNSLOTH_MODEL_REVISION\")\nmodel, tokenizer = FastLanguageModel.from_pretrained(\n    model_name = \"unsloth\u002FQwen3-4B\",\n    revision = model_revision,\n    max_seq_length = 1024,\n    load_in_4bit = True,\n    fast_inference = True,       # vLLM sampling backend\n    max_lora_rank = 32,          # must be >= the r used below\n    gpu_memory_utilization = 0.6,\n)\nmodel = FastLanguageModel.get_peft_model(model, r = 32, lora_alpha = 32)\n\ndef reward_length(completions, **kwargs):\n    \"\"\"Placeholder. Replace with a task-specific verifier.\"\"\"\n    return [min(len(c) \u002F 200.0, 1.0) for c in completions]\n\ntrainer = GRPOTrainer(\n    model = model,\n    processing_class = tokenizer,\n    reward_funcs = [reward_length],\n    train_dataset = dataset,\n    args = GRPOConfig(\n        num_generations = 8,\n        max_prompt_length = 256,\n        max_completion_length = 512,\n        learning_rate = 5e-6,\n        output_dir = \"grpo-outputs\",\n    ),\n)\ntrainer.train()\n```\n\n`gpu_memory_utilization` splits VRAM between vLLM's KV cache and training. Raise it if\ngeneration is the bottleneck, lower it if training OOMs. `max_lora_rank` is fixed at load time\nand must be at least the `r` passed later, or adapter loading fails.\n\nGRPO learning rates sit roughly two orders of magnitude below SFT. Reward functions receive\n`completions` plus any dataset columns as keyword arguments, and return one float per completion.\n\n## Best Practices\n\n- ✅ Set `random_state` so a promising run can be reproduced.\n- ✅ Log peak VRAM on the first run and reuse it to size later jobs on the same hardware.\n- ✅ Evaluate the exported artifact, not just the adapter — quantization shifts behaviour.\n- ❌ Don't change `max_seq_length` between training and export; the GGUF inherits it.\n- ❌ Don't tune hyperparameters before the loss mask has been verified once.\n\n## Limitations\n\n- The VRAM figures above are planning heuristics, not benchmarks. Confirm on target hardware.\n- Architecture support changes between releases. Check upstream before assuming a model works.\n- Unsloth's speed and memory claims are the project's own published figures, measured on their\n  own benchmarks; they are not independently verified here.\n- This skill does not replace environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if the GPU, model, dataset format or export target is unknown —\n  every step above depends on those four.\n\n## Security & Safety Notes\n\n- Training commands are long-running and hold the GPU exclusively. Confirm before launching on\n  a shared or remote machine.\n- `push_to_hub_gguf` and `push_to_hub_merged` publish weights to a public Hub repo by default.\n  Confirm intent and pass `private=True` when the model is not meant to be public.\n- Read Hugging Face tokens from the environment (`HF_TOKEN`), never inline in a script. A\n  committed token grants write access to every model the account owns.\n- Fine-tuning reproduces the training data's content and biases in the weights. Confirm the\n  dataset is licensed for training and free of secrets before starting.\n- Pin every Hub model and dataset to a reviewed full commit SHA, obtain approval before changing\n  either revision, and record both values with the training artifact. Prefer the verified local\n  cache for repeat runs instead of re-resolving network defaults.\n- GGUF export builds llama.cpp from source on first use, compiling third-party code and\n  requiring network access. Before the first export, identify and review the exact llama.cpp\n  revision that will be built; do not permit an unattended moving-revision fetch. Prefer a\n  user-approved, full-commit-pinned local toolchain and cache.\n- Unsloth is dual-licensed: the core package is Apache-2.0, while optional components such as\n  the Studio UI are AGPL-3.0. Check a component's license before redistributing it.\n\n## Common Pitfalls\n\n- **Problem:** Trained model ignores stop tokens or echoes the prompt format.\n  **Solution:** Wrong chat template, or `train_on_responses_only` was never applied. Verify the\n  mask on a decoded batch before blaming hyperparameters.\n\n- **Problem:** CUDA OOM partway through the first epoch rather than at step 0.\n  **Solution:** A long sample exceeded the activation budget. Lower `max_seq_length` or filter\n  outliers — peak memory tracks the longest sequence, not the mean.\n\n- **Problem:** Training runs, but at ordinary unaccelerated speed.\n  **Solution:** `transformers` or `trl` was imported before `unsloth`, so the patches never\n  applied. Move `import unsloth` to the top of the file.\n\n- **Problem:** `save_pretrained_gguf` appears to hang on first call.\n  **Solution:** It is building llama.cpp. Ensure a compiler and network access are available, or\n  export `merged_16bit` and convert separately.\n\n- **Problem:** GRPO fails with a LoRA rank mismatch.\n  **Solution:** `max_lora_rank` at `from_pretrained` is below the `r` given to `get_peft_model`.\n  Raise it to match.\n\n- **Problem:** Loss collapses to near zero within a few hundred steps.\n  **Solution:** Overfitting a small dataset, or the loss mask is leaking the answer into the\n  prompt. Check dataset size against epoch count, then re-verify masking.\n\n## Related Skills\n\n- `@trl-training` - Use for the TRL CLI, multi-GPU runs, or architectures Unsloth lacks.\n- `@hugging-face-model-trainer` - Use for managed training on Hugging Face Jobs instead of local hardware.\n- `@local-llm-expert` - Use to serve the exported GGUF via Ollama, llama.cpp or vLLM.\n\n## Additional Resources\n\n- [Unsloth documentation](https:\u002F\u002Funsloth.ai\u002Fdocs)\n- [Reinforcement learning guide (GRPO, DPO)](https:\u002F\u002Funsloth.ai\u002Fdocs\u002Fget-started\u002Freinforcement-learning-rl-guide)\n- [Saving to GGUF](https:\u002F\u002Funsloth.ai\u002Fdocs\u002Fbasics\u002Finference-and-deployment\u002Fsaving-to-gguf)\n- [unslothai\u002Funsloth on GitHub](https:\u002F\u002Fgithub.com\u002Funslothai\u002Funsloth)\n",{"name":5,"risk":26,"tags":43,"tools":50,"author":53,"source":28,"license":14,"category":54,"date_added":55,"description":7,"source_repo":56,"source_type":28,"license_source":57},[44,45,46,47,48,49,23],"unsloth","fine-tuning","lora","qlora","grpo","gguf",[51,52,30],"claude","cursor","A-ryanVAT-S","ai-ml","2026-08-27","unslothai\u002Funsloth","https:\u002F\u002Fgithub.com\u002Funslothai\u002Funsloth\u002Fblob\u002Fmain\u002FLICENSE","f3312ba749561b6159f477dbfc9313c875d40a56",".agents\u002Fskills_archive\u002Funsloth-finetuning","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612","2026-10-25 23:50:58",{"source":8,"skillName":5,"commands":64,"prompt":74,"zipAvailable":75},[65,68,71],{"tool":66,"command":67},"npx","npx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill unsloth-finetuning",{"tool":69,"command":70},"bunx","bunx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill unsloth-finetuning",{"tool":72,"command":73},"pnpm","pnpm dlx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill unsloth-finetuning","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Funsloth-finetuning\u002FSKILL.md",true,[],[78,107,131,155,182,206],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":90,"publishedAt":38},"01M6Q0FA5FZ410Z33Z3TFQ4DBA","zero-trust","Implement zero-trust network architecture. Configure identity-based access, micro-segmentation, and continuous verification. Use when implementing modern security architectures.","MIT","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fzero-trust\u002FSKILL.md",[85],{"categoryNo":86,"categoryName":87,"taxonomyType":88,"taxonomyTypeDesc":89},"01JBSEEDCAT000000000000011","运维与部署","SCENARIO","使用场景",[91,92,93,94,95,96,80,97,98,99,100,101,28,27,102,26,103,104,105,106],"ZeRO","trust","zero trust","architecture","assessment","verification","segmentation","devops-security","access","configure","only","active","scope","scripts","relevant","implementing",{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":38},"01M6Q0F1YZJW3KX5FBKEVZ8CV4","zcode-delegate","Delegate coding tasks to the Z.AI ZCode CLI only when the user explicitly requests it, while the orchestrator retains review and landing responsibility.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fzcode-delegate\u002FSKILL.md",[],[114,115,116,117,118,119,120,121,122,123,124,125,126,101,127,28,128,129,26,130],"delegate","zcode","zcode delegate","review","cli","orchestration","tasks","run","Bash","model","node","read","orchestrator","files","desktop app","app","agent-orchestration",{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":137,"publishedAt":38},"01M6Q0ETK41VGNMYEXW0T00AJN","youtube-transcript","Fetch YouTube transcripts through DeepAPI or local fallback tooling and save clean text output.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-transcript\u002FSKILL.md",[],[138,139,140,141,142,143,144,34,145,146,147,148,149,28,27,150,151,152,153,154],"transcript","youtube transcript","youtube","safe","github","codex","research","https","text","fetch","tooling","clean","local","output","deepapi","youtube transcripts","blob",{"skillNo":156,"name":157,"nameZh":6,"description":158,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":159,"categories":160,"keywords":172,"publishedAt":38},"01M6Q0EPPH2PVMDW40017F8WX0","youtube-transcript-skills","Fetch YouTube video transcripts, search videos\u002Fchannels, browse channels, and extract playlists via the getyoutubetranscript.com API - free tier, no card required.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-transcript-skills\u002FSKILL.md",[161,164,167],{"categoryNo":162,"categoryName":163,"taxonomyType":88,"taxonomyTypeDesc":89},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":165,"categoryName":166,"taxonomyType":88,"taxonomyTypeDesc":89},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":168,"categoryName":169,"taxonomyType":170,"taxonomyTypeDesc":171},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[138,139,140,173,141,30,142,143,34,174,175,176,177,147,178,28,27,179,180,181],"youtube transcript skills","search","api","Video","browse","api-integration","free","card","channels",{"skillNo":183,"name":184,"nameZh":6,"description":185,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":186,"categories":187,"keywords":192,"publishedAt":38},"01M6Q0EAB96PX83W5PTE8A0R8D","youtube-notetaker","Turn YouTube talks into local study notes with slides, transcripts, editable annotations, and a markdown-backed viewer.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-notetaker\u002FSKILL.md",[188,191],{"categoryNo":189,"categoryName":190,"taxonomyType":88,"taxonomyTypeDesc":89},"01JBSEEDCAT000000000000003","演示文稿",{"categoryNo":165,"categoryName":166,"taxonomyType":88,"taxonomyTypeDesc":89},[140,193,194,118,141,195,196,197,198,34,176,199,200,201,202,27,203,150,204,205],"youtube notetaker","notetaker","workflow","official","notes","code","markdown","slides","annotations","README","study","dair-academy","viewer",{"skillNo":207,"name":208,"nameZh":6,"description":209,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":210,"categories":211,"keywords":213,"publishedAt":38},"01M6Q0E55F0GW5MX48V8HXS8B5","youtube-full","Fetch YouTube transcripts, search videos, browse channels, and extract playlists via TranscriptAPI — no yt-dlp, no Google API key, works from any cloud server.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-full\u002FSKILL.md",[212],{"categoryNo":162,"categoryName":163,"taxonomyType":88,"taxonomyTypeDesc":89},[214,140,215,216,141,30,174,217,218,175,176,177,147,219,178,28,27,179,220,153],"youtube full","full","google","server","dlp","credits","automatic"]