> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/models/inkling-2-mini/fine-tuning.md). Agents can also search and read this documentation through its [MCP server](https://unsloth.ai/docs/~gitbook/mcp).

# Fine-tuning Inkling 2 Mini Guide

Learn how to fine-tune Thinking Machines Lab's Inkling 2 Mini with Unsloth.

You can now fine-tune Thinking Machines Lab's [Inkling 2 Mini](https://unsloth.ai/docs/models/inkling-2-mini.md) (26.4B MoE, looped transformer) with [Unsloth](https://github.com/unslothai/unsloth). Unsloth is **1.8 to 3.1x faster** than Hugging Face TRL on RTX PRO 6000 and A100 80GB and uses **50% less VRAM** with all optimizations turned on - all with **no accuracy loss**!

Local training with Unsloth works on **22GB VRAM**. We also provide a free Kaggle training notebook.

* Unsloth trains Inkling 2 Mini 1.81x faster while using 50% less VRAM on an A100 80GB (29.4 vs 58.3 GiB peak at 2,048 tokens) compared with transformers + PEFT + TRL. On an RTX PRO 6000 it trains **3.10x faster** (25.7 vs 55.4 GiB at 1,024 tokens).

{% columns %}
{% column %}
[**Conversational** free Kaggle Notebook](https://www.kaggle.com/notebooks/welcome?src=https://github.com/unslothai/notebooks/blob/main/nb/Kaggle-Inkling_2_Mini_%2826B%29-Conversational.ipynb\&accelerator=nvidiaTeslaT4)

{% embed url="<https://www.kaggle.com/notebooks/welcome?src=https://github.com/unslothai/notebooks/blob/main/nb/Kaggle-Inkling_2_Mini_(26B)-Conversational.ipynb&accelerator=nvidiaTeslaT4>" %}
{% endcolumn %}

{% column %}
[**Conversational** (Colab A100)](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Inkling_2_Mini_%2826B%29-Conversational.ipynb)

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Inkling_2_Mini_(26B)-Conversational.ipynb>" %}
{% endcolumn %}
{% endcolumns %}

* The 4-bit weights are about 14.4 GB, so one T4 is not enough - 2xT4 Kaggle fits! On 24GB cards, **Unsloth uses 21.1GB peak memory** - TRL needs more than 40GB. We quantize Inkling's 128 routed experts per layer to 4-bit (**optional** - you can do FFT or LoRA with Unsloth), so QLoRA can fit a tuned single-24GB run or the two-T4 Kaggle setup.
* We also allow you to export the fine-tune to GGUF and merged 16bit at the end!

### Benchmarks

We trained and benchmarked Inkling 2 Mini with QLoRA in all setups on the same tokens and used FineTome data, a batch size of 1 x gradient accumulation 4, LoRA r = 16 on attention and the routed experts and adamw\_8bit. Below times are the median step of steps 6-25 over 2-3 runs per setup.

| GPU                    | Context | Unsloth step | Unsloth peak VRAM | transformers + TRL step | transformers + TRL peak VRAM | Speedup   |
| ---------------------- | ------- | ------------ | ----------------- | ----------------------- | ---------------------------- | --------- |
| A100 80GB              | 2048    | 9.09 s       | 29.4 GiB          | 16.49 s                 | 58.3 GiB                     | **1.81x** |
| RTX PRO 6000 Blackwell | 1024    | 2.94 s       | 25.7 GiB          | 9.09 s                  | 55.4 GiB                     | **3.10x** |

![Inkling 2 Mini QLoRA step time and peak VRAM: Unsloth vs transformers + PEFT + TRL on A100 80GB and RTX PRO 6000](https://3215535692-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F5HICgfWx3ha64hQ4mpVo%2Finkling-2-mini-vs-trl-v2.png?alt=media)

* **40GB cards:** transformers + bitsandbytes only quantizes `nn.Linear` layers. Inkling's experts are 3D parameters, so the experts stayed in BF16 in our comparison. The model alone used 47.8 GiB and did not load with memory capped to an A100 40GB's capacity. Under the same cap Unsloth trains in 27.9 GiB at 2048 tokens and 25.7 GiB at 1024.
* **Correct loss:** with plain transformers 4-bit, the looped layers' message gates are quantized too and the first losses are 3.4-3.9 instead of 0.4-1.2. Keeping `message_gate.down_proj` out of 4-bit fixes the loss and Unsloth does this automatically.

### Optimizations

We optimized Inkling 2 Mini training with the below items:

* **4-bit experts:** Unsloth quantizes the routed experts while loading, so the model takes 14.5 GiB after load instead of 47.8 GiB.
* **16-bit message gates:** the loop message gates stay out of 4-bit so training loss and generations stay correct.
* **FlexAttention** is used for the sliding window and attention sinks on Ampere and newer GPUs: 15% faster steps on an L4 (5.89 to 5.01 s per step). T4s use eager attention, which is faster there.
* **Gradient checkpointing for the looped layers:** layers 6-17 run three times per forward, and their message residual is now recomputed in the backward pass. This saves about 1 GB on an A100 and is bitwise deterministic across runs on a 2 GPU split.
* **Fused cross entropy with the final logit softcap:** removes 2.29 GB of fp32 logits on the second card.
* **Bounded expert dequantization scratch:** 1.27 GB down to 0.18 GB per card.

In the 1,024-token notebook workload (batch 1 \* 4), peak allocated memory on Kaggle's two T4s fell from 11.3 and 12.5 GB to 10.0 and 9.9 GB. The layer-split path also fit 2,048 tokens on 2x T4 in separate source testing

![Inkling 2 Mini memory before and after the optimizations](https://3215535692-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FjkEfZeGyKX9p29KdS0Uz%2Finkling-2-mini-memory-optimizations-v2.png?alt=media)

### Multi-GPU support

* **2x T4 (Kaggle):** the notebook splits the layers over both GPUs. Do not pass `device_map as` Unsloth fills one card, then the next. On Kaggle the notebook runs at about 27 s per step.
* **DDP with offloaded layers:** DDP keeps a full copy of the model on each GPU. In the two-T4 test, it fit with offloaded layers: `offload_layers = 20` kept 20 of the 24 layers in CPU RAM and streamed them async in as needed.

To use Unsloth, simply do:

{% code collapsedlinecount="10" %}

```python
model, tokenizer = FastModel.from_pretrained(
    model_name     = "unsloth/Inkling-2-Mini",
    max_seq_length = 1024,
    load_in_4bit   = True,
    offload_layers = 20,
)
```

{% endcode %}

For DDP:

{% code collapsedlinecount="10" %}

```bash
UNSLOTH_MOE_DEQUANT_MAX_MB=64 UNSLOTH_PARALLEL="dp=2" torchrun --nproc_per_node 2 train.py
```

{% endcode %}

In a short two-T4 FP16 QLoRA benchmark (rank 8, 2 \* 512 tokens per step), DDP with block swap took 16.4 s per step and peaked at 13.2 GB on the busiest GPU. The layer-split baseline took 9.0 s per step and peaked at 10.8 GB. The layer split keeps a portion of the model and its activations on each GPU. With DDP, each GPU runs the whole 24-layer model on its own batch.

Four layers, the embeddings, the vision tower and `lm_head` stay on each GPU (5.26 GiB after loading). Each step adds about 8 GiB for activations, streamed layers, expert dequantization scratch, logits, LoRA gradients, DDP's FP32 gradient buckets (about 0.75 GiB), and optimizer state.

<img src="https://3215535692-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F9baJMfZbWNHLA9eIAtlM%2Finkling-2-mini-multi-gpu-2xt4-v2.png?alt=media" alt="Inkling 2 Mini on 2x T4: step time and peak VRAM per GPU for the layer split and DDP with block swap" width="563">

### Quick Start

Unsloth picks the precision for your GPU (float16 on T4), so do not pass `dtype` or set `fp16` / `bf16` on the trainer.

{% code expandable="true" collapsedlinecount="10" %}

```python
from unsloth import FastModel

max_seq_length = 1024

model, tokenizer = FastModel.from_pretrained(
    model_name      = "unsloth/Inkling-2-Mini",
    max_seq_length  = max_seq_length,
    load_in_4bit    = True,
    full_finetuning = False,
)

model = FastModel.get_peft_model(
    model,
    finetune_vision_layers     = False, # Turn off for just text!
    finetune_language_layers   = True,
    finetune_attention_modules = True,  # q, k, v, o and the output gate
    finetune_mlp_modules       = True,  # The routed experts

    r = 8,
    lora_alpha = 8,
    lora_dropout = 0,
    bias = "none",
    use_gradient_checkpointing = "unsloth",
    random_state = 3407,
)
```

{% endcode %}

Format your data with Inkling's own chat template, then train on the assistant turns only:

{% code expandable="true" collapsedlinecount="10" %}

```python
from datasets import load_dataset
from unsloth.chat_templates import standardize_sharegpt, train_on_responses_only
from trl import SFTTrainer, SFTConfig

dataset = load_dataset("mlabonne/FineTome-100k", split = "train[:3000]")
dataset = standardize_sharegpt(dataset)

def formatting_prompts_func(examples):
    texts = [
        tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False)
        for convo in examples["conversations"]
    ]
    return { "text" : texts, }

dataset = dataset.map(formatting_prompts_func, batched = True)

trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = dataset,
    args = SFTConfig(
        dataset_text_field = "text",
        max_length = max_seq_length,
        per_device_train_batch_size = 1,
        gradient_accumulation_steps = 4,
        warmup_steps = 5,
        max_steps = 30,
        learning_rate = 2e-4,
        logging_steps = 1,
        optim = "adamw_8bit",
        weight_decay = 0.001,
        lr_scheduler_type = "linear",
        seed = 3407,
        output_dir = "outputs",
        report_to = "none",
    ),
)

trainer = train_on_responses_only(
    trainer,
    instruction_part = "<|message_user|>",
    response_part = "<|message_model|>",
)

trainer_stats = trainer.train()
```

{% endcode %}

* Keep `per_device_train_batch_size = 1` and raise `gradient_accumulation_steps` instead: the 200K vocabulary makes the logits the largest allocation in a step.
* Pass `reasoning_effort` (`"none"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"`, or 0 to 0.99) to `apply_chat_template` to control thinking. The template default is 0.9.
* If you are close to the memory limit, lower `max_seq_length` or set `finetune_mlp_modules = False`.

#### Saving / export fine-tuned model

To save the LoRA adapters:

{% code collapsedlinecount="10" %}

```python
model.save_pretrained("inkling_2_mini_lora")
tokenizer.save_pretrained("inkling_2_mini_lora")
# model.push_to_hub("HF_ACCOUNT/inkling_2_mini_lora")
# tokenizer.push_to_hub("HF_ACCOUNT/inkling_2_mini_lora")
```

{% endcode %}

Also to save to 16bit and or GGUF:

{% code collapsedlinecount="10" %}

```python
model.save_pretrained_merged("inkling_finetune_16bit", tokenizer, save_method = "merged_16bit")
model.save_pretrained_gguf("inkling_finetune", tokenizer, quantization_method = "q4_k_m")
```

{% endcode %}

* A merged 16-bit Inkling 2 Mini is about 53 GB on disk.
* GGUF export writes the 53 GB merge and a 53 GB 16-bit GGUF first, so it needs about **150 GB of free disk**. Kaggle runs out of disk. On a Colab A100 the `q4_k_m` export produced a 17.48 GB GGUF in about 21 minutes, and it runs in llama.cpp. See the [run guide](https://unsloth.ai/docs/models/inkling-2-mini.md#run-inkling-2-mini-in-llama-cpp) for running it.

#### Limits and further experiments:

* Text QLoRA is the tested path on free GPUs. On a 96 GB GPU we also tested:
  * **16-bit LoRA:** peak 59 GB and 2.54 s per step, against 25 GB and 3.05 s per step for QLoRA on the same GPU, with losses within 0.05 of QLoRA.
  * **Full fine-tuning with the experts frozen** (1.6B trainable weights, `adamw_8bit`): peak 62 GB.
  * **Full fine-tuning of all 26B weights** fits only with `optim = "lomo"` (peak 59 GB). With `adamw_8bit` it runs out of memory, because the bf16 weights and gradients alone need about 98 GB.
* One T4 is not enough: the 4-bit weights are about 14.4 GB.
* [Inkling 2 Small](https://unsloth.ai/docs/models/inkling-2-small.md) needs about 310 GB for its 4-bit weights alone, so it does not fit free tiers or a single GPU.
* vLLM fast inference is not supported for Inkling 2 training yet.

### Free Notebooks for Inkling fine-tuning and training:

{% columns %}
{% column %}
[**Conversational** free Kaggle Notebook](https://www.kaggle.com/notebooks/welcome?src=https://github.com/unslothai/notebooks/blob/main/nb/Kaggle-Inkling_2_Mini_%2826B%29-Conversational.ipynb\&accelerator=nvidiaTeslaT4)

{% embed url="<https://www.kaggle.com/notebooks/welcome?src=https://github.com/unslothai/notebooks/blob/main/nb/Kaggle-Inkling_2_Mini_(26B)-Conversational.ipynb&accelerator=nvidiaTeslaT4>" %}
{% endcolumn %}

{% column %}
[**Conversational** (Colab A100)](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Inkling_2_Mini_%2826B%29-Conversational.ipynb)

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Inkling_2_Mini_(26B)-Conversational.ipynb>" %}
{% endcolumn %}
{% endcolumns %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/models/inkling-2-mini/fine-tuning.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
