# 如何在 Windows 上使用 Unsloth 对 LLM 进行微调（分步指南）

现在你可以直接在本地 Windows 设备上微调模型，而无需使用 WSL，方法是使用 [Unsloth](https://github.com/unslothai/unsloth)。本指南中有 3 种主要方法可供使用（[Conda](#method-1-windows-via-conda), [Docker](#method-2-docker) 和 [WSL](#method-3-wsl)）。\
如果你已经在 Windows 上安装了 PyTorch， `pip install unsloth` 应该可以工作。否则，请按照下面的指南：

<a href="/pages/bc3c53c3e0f87180567dda04ad25f8d2b13374ce#method-1-windows-via-conda" class="button secondary">Conda 教程</a><a href="/pages/bc3c53c3e0f87180567dda04ad25f8d2b13374ce#method-2-docker" class="button secondary">Docker 教程</a><a href="/pages/bc3c53c3e0f87180567dda04ad25f8d2b13374ce#method-3-wsl" class="button secondary">WSL 教程</a>

### Unsloth Studio

我们推出了一个新的 Web UI，名为 [Unsloth Studio](/docs/zh/xin/studio/install.md) ，开箱即用，支持 Windows：

```bash
irm https://unsloth.ai/install.ps1 | iex
```

使用相同命令进行更新，或者使用 `unsloth studio update`.

然后每次启动时使用：

```bash
unsloth studio -H 0.0.0.0 -p 8888
```

有关 Unsloth Studio 的详细安装说明和要求， [请查看我们的指南](/docs/zh/xin/studio/install.md).

下面是原始版本的安装说明 **Unsloth Core**:

### 方法 #1 - 通过 Conda 在 Windows 上安装：

{% stepper %}
{% step %}
**安装 Miniconda（或 Anaconda）**

在此处 [下载 Anaconda](https://www.anaconda.com/download)。我们的建议是使用 [Miniconda](https://www.anaconda.com/docs/getting-started/miniconda/install#quickstart-install-instructions)。要使用它，首先打开 Powershell——在开始菜单中搜索“Windows Powershell”：

<figure><img src="/files/6999e2add4dbd2ce667fc8da3092fe8447d6d53a" alt="" width="375"><figcaption></figcaption></figure>

然后它会打开 Powershell：

<figure><img src="/files/97d9b7a5ba1edf720b38516fe7be5e0f31980055" alt="" width="375"><figcaption></figcaption></figure>

接着复制粘贴下面的内容：CTRL+C，然后在 Powershell 中粘贴：CTRL+V：

{% code overflow="wrap" %}

```ps
Invoke-WebRequest -Uri "https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe" -OutFile ".\miniconda.exe"
Start-Process -FilePath ".\miniconda.exe" -ArgumentList "/S" -Wait
del .\miniconda.exe
```

{% endcode %}

接受警告并点击“仍然粘贴”，然后等待。

<figure><img src="/files/6dd9ad2855a6a280c2b7ebcd313eefd195306b65" alt="" width="375"><figcaption></figcaption></figure>

它会像下面这样下载安装程序：

<figure><img src="/files/8d55f3354a16bc8a67d6631e7fefe0be7e7e61c6" alt="" width="375"><figcaption></figcaption></figure>

安装完成后，打开 **Anaconda Powershell Prompt** ，通过开始菜单 -> 搜索它来使用 Miniconda：

<figure><img src="/files/08924705812a87ea009185fa8b4005e5fc9f2cb2" alt="" width="375"><figcaption></figcaption></figure>

然后你会看到：

<figure><img src="/files/6775678bbebfe2d0f7517b6fdaf7b671582f3684" alt="" width="375"><figcaption></figcaption></figure>
{% endstep %}

{% step %}
**创建 conda 环境**

```bash
conda create --name unsloth_env python==3.12 -y
conda activate unsloth_env
```

**你会看到：**

<figure><img src="/files/1f0e9edded798ac84f1ea4c842a734a8bffeb243" alt="" width="375"><figcaption></figcaption></figure>
{% endstep %}

{% step %}
**检查 `nvidia-smi` 以确认你有 GPU，并查看 CUDA 版本**

输入后 `nvidia-smi` 在 Powershell 中，你应该会看到如下内容。如果你没有 `nvidia-smi` ，或者下面内容没有弹出，你需要重新安装 [NVIDIA 驱动程序](https://www.nvidia.com/en-us/drivers/).

<figure><img src="/files/1cee74980dcd5b7c6a2732406623395cfdb053de" alt="" width="375"><figcaption></figcaption></figure>
{% endstep %}

{% step %}
**安装 PyTorch**

运行 `nvidia-smi` 时，你会在右上角看到：“CUDA Version: 13.0”。通过 PowerShell 安装 PyTorch。将 `130` 更改为你的 CUDA 版本——确保 [版本存在](https://pytorch.org/) 并且与你的 CUDA 驱动版本匹配。

{% code overflow="wrap" %}

```bash
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu130
```

{% endcode %}

你会看到：

<figure><img src="/files/710632806238679ee42506ee20ee819901063d06" alt="" width="563"><figcaption></figcaption></figure>

在 Python 中尝试运行这个命令，使用 `python` 在安装 PyTorch 后：

{% code overflow="wrap" %}

```python
import torch
print(torch.cuda.is_available())
A = torch.ones((10, 10), device = "cuda")
B = torch.ones((10, 10), device = "cuda")
A @ B
```

{% endcode %}

你应该会看到一个全为 10 的矩阵。并且第一个结果应为 True。

<figure><img src="/files/dfb01b809e83cbd8356351c25330c422d7225e9a" alt="" width="375"><figcaption></figcaption></figure>
{% endstep %}

{% step %}
**安装 Unsloth（仅当 PyTorch 正常工作时！）**

{% hint style="danger" %}
**确认 PyTorch 工作正常并能运行——如果不行，说明 PyTorch 有问题，这意味着你的 Windows 机器可能不幸需要重新安装 CUDA 驱动程序。**
{% endhint %}

在 Powershell 中（退出 Python 后使用 `exit()` ，执行并等待：

```bash
pip install unsloth
```

{% endstep %}

{% step %}
**验证 Unsloth 是否可用**

现在使用中的任何脚本 [Unsloth 笔记本](/docs/zh/kai-shi-shi-yong/unsloth-notebooks.md) （保存为 .py 文件），或者使用下面的基础脚本：

{% code expandable="true" %}

```python
from unsloth import FastLanguageModel, FastModel
import torch
from trl import SFTTrainer, SFTConfig
from datasets import load_dataset
max_seq_length = 512
url = "https://huggingface.co/datasets/laion/OIG/resolve/main/unified_chip2.jsonl"
dataset = load_dataset("json", data_files = {"train" : url}, split = "train")

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/gemma-3-270m-it",
    max_seq_length = max_seq_length, # 长上下文可任选！
    load_in_4bit = True,  # 4 位量化。False = 16 位 LoRA。
    load_in_8bit = False, # 8 位量化
    load_in_16bit = False, # 16 位 LoRA
    full_finetuning = False, # 用于全量微调。
    trust_remote_code = False, # 启用以支持新模型
    # token = "hf_...", # 如果使用受限模型，请使用一个
)

# 执行模型补丁并添加快速 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, # 支持任意值，但 = 0 已优化
    bias = "none",    # 支持任意值，但 = "none" 已优化
    # [NEW] "unsloth" 可减少 30% 显存占用，支持 2 倍更大的 batch size！
    use_gradient_checkpointing = "unsloth", # 对于超长上下文可用 True 或 "unsloth"
    random_state = 3407,
    max_seq_length = max_seq_length,
    use_rslora = False,  # 我们支持 rank stabilized LoRA
    loftq_config = None, # 以及 LoftQ
)

trainer = SFTTrainer(
    model = model,
    train_dataset = dataset,
    tokenizer = tokenizer,
    args = SFTConfig(
        max_seq_length = max_seq_length,
        per_device_train_batch_size = 2,
        gradient_accumulation_steps = 4,
        warmup_steps = 10,
        max_steps = 60,
        logging_steps = 1,
        output_dir = "outputs",
        optim = "adamw_8bit",
        seed = 3407,
        dataset_num_proc = 1,
    ),
)
trainer.train()
```

{% endcode %}

你应该会看到：

```bash
🦥 Unsloth：将为你的电脑打补丁，以支持快 2 倍的免费微调。
🦥 Unsloth Zoo 现在会打补丁以让训练更快！
==((====))==  Unsloth 2026.1.4：快速 Gemma3 打补丁。Transformers: 4.57.6.
   \\   /|    NVIDIA GeForce RTX 3060. GPU 数量 = 1. 最大显存：12.0 GB。平台：Windows.
O^O/ \_/ \    Torch: 2.10.0+cu130. CUDA: 8.6. CUDA Toolkit: 13.0. Triton: 3.6.0
\        /    Bfloat16 = TRUE. FA [Xformers = 0.0.34. FA2 = False]
 "-____-"     免费许可证：http://github.com/unslothai/unsloth
Unsloth：已启用快速下载——请忽略那些显示为红色的下载进度条！
Unsloth：Gemma3 不支持 SDPA——切换到 fast eager。
Unsloth：使 `model.base_model.model.model` 需要梯度
Unsloth：对 ["text"] 进行分词（num_proc=1）：   0%|                 | 0/210289 [00:00<?, ? examples/s]�  Unsloth：将为你的电脑打补丁，以支持快 2 倍的免费微调。
🦥 Unsloth：将为你的电脑打补丁，以支持快 2 倍的免费微调。
```

并且训练：

<figure><img src="/files/1f0049be7bc95268a879a8f020a877ce844c2928" alt="" width="375"><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### 方法 #2 - Docker：

对 Windows 用户来说，Docker 可能是开始使用 Unsloth 最简单的方式，因为无需额外设置，也没有依赖问题。 [**`unsloth/unsloth`**](https://hub.docker.com/r/unsloth/unsloth) 是 Unsloth 唯一的 Docker 镜像。对于 [Blackwell](/docs/zh/bo-ke/fine-tuning-llms-with-blackwell-rtx-50-series-and-unsloth.md) 和 50 系列 GPU，请使用同一个镜像——无需单独的镜像。

有关安装说明，请按照我们的 [Docker 指南](/docs/zh/bo-ke/how-to-fine-tune-llms-with-unsloth-and-docker.md)，否则这里是快速入门指南：

{% stepper %}
{% step %}
**安装 Docker 和 NVIDIA Container Toolkit。**

通过 [Linux](https://docs.docker.com/engine/install/) 或 [Desktop](https://docs.docker.com/desktop/) （其他）安装 Docker。然后安装 [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html#installation):

```bash
export NVIDIA_CONTAINER_TOOLKIT_VERSION=1.17.8-1
sudo apt-get update && sudo apt-get install -y \
  nvidia-container-toolkit=${NVIDIA_CONTAINER_TOOLKIT_VERSION} \
  nvidia-container-toolkit-base=${NVIDIA_CONTAINER_TOOLKIT_VERSION} \
  libnvidia-container-tools=${NVIDIA_CONTAINER_TOOLKIT_VERSION} \
  libnvidia-container1=${NVIDIA_CONTAINER_TOOLKIT_VERSION}
```

{% endstep %}

{% step %}
**运行容器。**

[**`unsloth/unsloth`**](https://hub.docker.com/r/unsloth/unsloth) 是 Unsloth 唯一的 Docker 镜像。

```bash
docker run -d -e JUPYTER_PASSWORD="mypassword" \
  -p 8888:8888 -p 2222:22 \
  -v $(pwd)/work:/workspace/work \
  --gpus all \
  unsloth/unsloth
```

{% endstep %}

{% step %}
**访问 Jupyter Lab**

前往 [http://localhost:8888](http://localhost:8888/) 并打开 Unsloth。访问 `unsloth-notebooks` 标签页以查看 Unsloth 笔记本。
{% endstep %}

{% step %}
**开始使用 Unsloth 训练**

如果你是新手，请按照我们的分步 [微调指南](/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide.md), [RL 指南](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md) 或者直接保存/复制我们预制的任意 [notebooks](/docs/zh/kai-shi-shi-yong/unsloth-notebooks.md).
{% endstep %}

{% step %}
**Docker 问题——没有检测到 GPU？**

尝试通过 WSL 进行 [#method-2-wsl](#method-2-wsl "mention")
{% endstep %}
{% endstepper %}

### 方法 #3 - WSL：

{% stepper %}
{% step %}
**安装 WSL**

打开命令提示符、终端，并安装 Ubuntu。如果系统提示，请设置密码。

```bash
wsl.exe --install Ubuntu-24.04
wsl.exe -d Ubuntu-24.04
```

{% endstep %}

{% step %} <mark style="color:$primary;background-color:orange;">**如果你没有执行 (1)，也就是你已经安装了 WSL**</mark>**，请在命令提示符中输入 `wsl` 并按回车进入 WSL**

```bash
wsl
```

{% endstep %}

{% step %}
**安装 Python**

{% code overflow="wrap" %}

```bash
sudo apt update
sudo apt install python3 python3-full python3-pip python3-venv -y
```

{% endcode %}
{% endstep %}

{% step %}
**安装 PyTorch**

{% code overflow="wrap" %}

```bash
pip install torch torchvision --force-reinstall --index-url https://download.pytorch.org/whl/cu130
```

{% endcode %}

如果遇到权限问题，请使用 `–break-system-packages` 因此 `pip install torch torchvision --force-reinstall --index-url https://download.pytorch.org/whl/cu130 –break-system-packages`
{% endstep %}

{% step %}
**安装 Unsloth 和 Jupyter Notebook**

{% code overflow="wrap" %}

```bash
pip install unsloth jupyter
```

{% endcode %}

如果遇到权限问题，请使用 `–-break-system-packages` 因此 `pip install unsloth jupyter –-break-system-packages`
{% endstep %}

{% step %}
**通过 Jupyter Notebook 启动 Unsloth**

{% code overflow="wrap" %}

```bash
jupyter notebook
```

{% endcode %}

然后在其中打开我们的 notebooks [Unsloth 笔记本](/docs/zh/kai-shi-shi-yong/unsloth-notebooks.md)并加载它们！你也可以前往 Colab notebooks，下载 > 下载 .ipynb，然后加载它们。

![](/files/f88ebc1b3aa24419dcd3a62b3e2a634c1c18aff5)
{% endstep %}
{% endstepper %}

{% hint style="warning" %}
如果你使用 GRPO 或计划使用 vLLM，目前 vLLM 不直接支持 Windows，只能通过 WSL 或 Linux 使用。
{% endhint %}

### **故障排查 /** 高级

对于 **高级安装说明** ，或者如果你在安装过程中看到奇怪的错误：

1. 安装 `torch` 和 `triton`。前往 <https://pytorch.org> 进行安装。例如 `pip install torch torchvision torchaudio triton`
2. 确认 CUDA 是否已正确安装。尝试 `nvcc`。如果失败，你需要安装 `cudatoolkit` 或 CUDA 驱动程序。
3. 如果使用 Intel GPU，你需要按照我们的 [Intel Windows 指南](/docs/zh/kai-shi-shi-yong/install/intel.md#windows-only-runtime-configurations)
4. 安装 `xformers` 手动安装。你可以尝试安装 `vllm` 并查看 `vllm` 是否成功。检查是否 `xformers` 已通过以下命令成功： `python -m xformers.info` 前往 <https://github.com/facebookresearch/xformers。另一个选项是安装> `flash-attn` 适用于 Ampere GPU。
5. 请再次确认你的 Python、CUDA、CUDNN、 `torch`, `triton`以及 `xformers` 的版本彼此兼容。 [PyTorch 兼容性矩阵](https://github.com/pytorch/pytorch/blob/main/RELEASE.md#release-compatibility-matrix) 可能会有帮助。
6. 最后，安装 `bitsandbytes` 并使用以下命令检查： `python -m bitsandbytes`
7. 如果 Unsloth 没有检测到或使用你的 GPU，并且你在 Windows 上使用我们的 Docker 容器，那么你的 CUDA toolkit 版本 `nvcc --version` 应该与主机上 nvidia-smi 显示的 CUDA 版本一致。Windows 上对 Docker 容器的 GPU 支持并不是自动的。 [你需要遵循 Docker 的指南](https://docs.docker.com/desktop/features/gpu/).

### 卸载 Unsloth Studio

要在 Windows 上卸载 Unsloth Studio，请按照以下 4 个步骤：

#### **1. 删除应用程序**

* WSL： `rm -rf ~/.unsloth/studio/unsloth_studio`
* Windows（PowerShell）： `Remove-Item -Recurse -Force "$HOME\.unsloth\studio\unsloth_studio"`&#x20;

这会删除应用程序，但会保留你的模型检查点、导出、历史记录、缓存和聊天内容。

#### **2. 删除快捷方式和符号链接**

**WSL / Windows（PowerShell）：**

```bash
Remove-Item -Force "$HOME\Desktop\Unsloth Studio.lnk"
Remove-Item -Force "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Unsloth Studio.lnk"
```

#### **3. 删除 CLI 命令**

**WSL：**

```bash
rm -f ~/.local/bin/unsloth
```

**Windows（PowerShell）：** 安装程序已将 venv 的 `Scripts` 目录添加到你的用户 PATH 中。要将其移除，请打开 设置 → 系统 → 关于 → 高级系统设置 → 环境变量，找到 `Path` （位于用户变量下），并删除指向 `.unsloth\studio\...\Scripts`.

#### **4. 删除全部内容（可选）**

如果还想删除历史记录、缓存、聊天内容、模型检查点和模型导出，请删除整个 Unsloth 文件夹：

* WSL, Linux： `rm -rf ~/.unsloth`
* Windows（PowerShell）： `Remove-Item -Recurse -Force "$HOME\.unsloth"`&#x20;

请注意，已下载的 HF 模型文件会单独存储在 Hugging Face 缓存中——以上步骤都不会删除它们。若你想释放那部分磁盘空间，请参阅下面的 **删除模型文件** 。


---

# 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://unsloth.ai/docs/zh/kai-shi-shi-yong/install/windows-installation.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.
