> 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/zh/mo-xing/qwen3-coder-next.md).

# Qwen3-Coder-Next：如何在本地运行

Qwen 发布了 Qwen3-Coder-Next，一款 80B MoE 模型（30 亿活跃参数），具有 **256K 上下文** 适用于快速的代理式编程和本地使用。其性能可与活跃参数多 10–20 倍的模型相媲美。

它可运行于 **46GB RAM**/VRAM/统一内存（8 位需 85GB），不进行推理，因此可实现超快代码响应。该模型擅长长程推理、复杂工具使用以及从执行失败中恢复。

{% hint style="success" %}
**2 月 19 日更新**：在 llama.cpp 修复解析后，工具调用现在应该会更好。

**新！** 参见 [量化基准测试](#gguf-quantization-benchmarks) 适用于我们的动态 GGUF！

**2 月 4 日：** `llama.cpp` 修复了一个用于纠正以下计算的错误： `向量化 key_gdiff。` 这修复了之前的循环和输出问题。我们已更新 GGUF，请 **重新下载** 和 **更新** `llama.cpp` 以获得更好的输出。
{% endhint %}

你还将学习如何在 Codex 和 Claude Code 上运行该模型。对于 **微调**，Qwen3-Next-Coder 可在 Unsloth 中用于 bf16 LoRA，并适配单张 B200 GPU。

Qwen3-Coder-Next Unsloth [动态 GGUF](/docs/zh/ji-chu/unsloth-dynamic-2.0-ggufs.md) 运行： [unsloth/Qwen3-Coder-Next-GGUF](https://huggingface.co/unsloth/Qwen3-Coder-Next-GGUF)

<a href="/pages/07558781d1c2c35e14fcaa4821ee92be27a005a8#run-qwen3-coder-next" class="button primary">运行 GGUF 教程</a><a href="https://unsloth.ai/docs/models/qwen3-coder-next#claude-codex" class="button secondary">Codex 和 Claude Code</a><a href="/pages/07558781d1c2c35e14fcaa4821ee92be27a005a8#fp8-qwen3-coder-next-in-vllm" class="button secondary">FP8 vLLM 教程</a>

### ⚙️ 使用指南

没有 46GB RAM 或统一内存？没关系，你可以运行我们更小的量化版本，例如 3-bit。最好让模型大小 = 你的可用资源总和（ **`磁盘空间 + RAM + VRAM ≥ 量化大小）。`** 如果你的量化版本完全适配你的设备，预计可达到 20+ tokens/s。若不完全适配，仍可通过卸载运行，但会更慢。

为获得最佳性能，Qwen 推荐以下设置：

* <mark style="background-color:blue;">`Temperature = 1.0`</mark>
* `Top_P = 0.95`
* `Top_K = 40`
* `Min_P = 0.01` (llama.cpp 的默认值是 0.05)
* `重复惩罚` = 禁用或 1.0

支持最多 `262,144` 的上下文长度，但你可以将其设置为 `32,768` 个 token，以减少内存使用。

### 🖥️ 运行 Qwen3-Coder-Next

根据你的使用场景，你需要使用不同的设置。由于本指南使用 4-bit，你大约需要 46GB RAM/统一内存。我们建议至少使用 3-bit 精度以获得最佳性能。

#### 🦥 Unsloth Studio 指南

Qwen3-Coder-Next 可以在以下环境中运行和微调： [Unsloth Studio](/docs/zh/xin/studio.md)，这是我们用于本地 AI 的全新开源 Web UI。借助 Unsloth Studio，你可以在本地运行模型于 **MacOS、Windows**、Linux，以及：

{% columns %}
{% column %}

* 搜索、下载， [运行 GGUF](/docs/zh/xin/studio.md#run-models-locally) 以及 safetensor 模型
* [**自修复** 工具调用](/docs/zh/xin/studio.md#execute-code--heal-tool-calling) + **网页搜索**
* [**代码执行**](/docs/zh/xin/studio.md#run-models-locally) （Python、Bash）
* [自动推理](/docs/zh/xin/studio.md#model-arena) 参数调优（temp、top-p 等）
* 通过 llama.cpp 实现快速 CPU + GPU 推理
* [训练 LLM](/docs/zh/xin/studio.md#no-code-training) 速度提升 2 倍，VRAM 减少 70%
  {% endcolumn %}

{% column %}

<div data-with-frame="true"><figure><img src="/files/5af4df407c8134f1ff75a4d7535569361c049e51" alt=""><figcaption></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

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

在终端中运行：

MacOS、Linux、WSL：

```bash
curl -fsSL https://unsloth.ai/install.sh | sh
```

Windows PowerShell：

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

{% hint style="success" %}
**安装会很快，大约需要 1-2 分钟。**
{% endhint %}
{% endstep %}

{% step %}
**启动 Unsloth**

MacOS、Linux、WSL 和 Windows：

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

然后打开 `http://localhost:8888` 在你的浏览器中。
{% endstep %}

{% step %}
**搜索并下载 Qwen3-Coder-Next**

首次启动时，你需要创建一个密码来保护你的账户，并在之后重新登录。然后你会看到一个简短的引导向导，用于选择模型、数据集和基本设置。你可以随时跳过它，直接进入聊天。

然后前往 [Unsloth Chat](/docs/zh/xin/studio/chat.md) 选项卡并搜索 **Qwen3-Coder-Next** 在搜索栏中输入，并下载你想要的模型和量化版本。

<div data-with-frame="true"><figure><img src="/files/2e64f48d0ed4a75fef9e4aa1a208b7839d80d1d5" alt="" width="563"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}
**运行 Qwen3-Coder-Next**

使用 Unsloth Studio 时，推理参数应会自动设置，不过你仍然可以手动更改。你也可以编辑上下文长度、聊天模板和其他设置。

更多信息，你可以查看我们的 [Unsloth Studio 推理指南](/docs/zh/xin/studio/chat.md).

<div data-with-frame="true"><figure><img src="/files/6273055e6bbde016134838582519f00de2201635" alt="" width="563"><figcaption></figcaption></figure></div>
{% endstep %}
{% endstepper %}

#### Llama.cpp 教程（GGUF）：

在 llama.cpp 中运行的说明（注意，我们将使用 4-bit 以适配大多数设备）：

{% stepper %}
{% step %}
获取最新的 `llama.cpp` 在 [GitHub 这里](https://github.com/ggml-org/llama.cpp)。你也可以按照下面的构建说明进行操作。将 `-DGGML_CUDA=ON` 更改为 `-DGGML_CUDA=OFF` 如果你没有 GPU，或者只想进行 CPU 推理。 **对于 Apple Mac / Metal 设备**，设置 `-DGGML_CUDA=OFF` 然后像往常一样继续——Metal 支持默认开启。

{% code overflow="wrap" %}

```bash
apt-get update
apt-get install pciutils build-essential cmake curl libcurl4-openssl-dev -y
git clone https://github.com/ggml-org/llama.cpp
cmake llama.cpp -B llama.cpp/build \\
    -DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-cli llama-mtmd-cli llama-server llama-gguf-split
cp llama.cpp/build/bin/llama-* llama.cpp
```

{% endcode %}
{% endstep %}

{% step %}
你可以直接从 Hugging Face 拉取。如果你的 RAM/VRAM 足够，可以将上下文增加到 256K。使用 `--fit on` 也会自动确定上下文长度。

你可以使用推荐参数： `temperature=1.0`, `top_p=0.95`, `top_k=40`

```bash
./llama.cpp/llama-cli \\
    -hf unsloth/Qwen3-Coder-Next-GGUF:UD-Q4_K_XL \\
    --ctx-size 16384 \\
    --temp 1.0 --top-p 0.95 --min-p 0.01 --top-k 40
```

{% endstep %}

{% step %}
通过以下方式下载模型（在安装 `pip install huggingface_hub`之后）。你可以选择 `UD-Q4_K_XL` 或其他量化版本。如果下载卡住，请参见 [Hugging Face Hub、XET 调试](/docs/zh/ji-chu/troubleshooting-and-faqs/hugging-face-hub-xet-debugging.md)

{% code overflow="wrap" %}

```bash
pip install -U huggingface_hub
hf download unsloth/Qwen3-Coder-Next-GGUF \\
    --local-dir unsloth/Qwen3-Coder-Next-GGUF \\
    --include "*UD-Q4_K_XL*"
```

{% endcode %}
{% endstep %}

{% step %}
然后以对话模式运行模型：

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-cli \\
    --model unsloth/Qwen3-Coder-Next-GGUF/Qwen3-Coder-Next-UD-Q4_K_XL.gguf \\
    --seed 3407 \\
    --temp 1.0 \\
    --top-p 0.95 \
    --min-p 0.01 \
    --top-k 40
```

{% endcode %}

同时，还要调整 **上下文窗口** 按需，最多到 `262,144`

{% hint style="info" %}
注意：此模型仅支持非思考模式，不会生成 `<think></think>` 块在其输出中。因此指定 `enable_thinking=False` 已不再需要。
{% endhint %}
{% endstep %}
{% endstepper %}

### 🦙Llama-server 服务与部署

要将 Qwen3-Coder-Next 部署到生产环境，我们使用 `llama-server` 在新的终端中，例如通过 tmux。然后，通过以下方式部署模型：

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-server \
    --model unsloth/Qwen3-Coder-Next-GGUF/Qwen3-Coder-Next-UD-Q4_K_XL.gguf \\
    --alias "unsloth/Qwen3-Coder-Next" \\
    --seed 3407 \\
    --temp 1.0 \\
    --top-p 0.95 \
    --min-p 0.01 \
    --top-k 40 \\
    --port 8001
```

{% endcode %}

然后在新的终端中，在执行 `pip install openai`，我们可以运行该模型：

{% code overflow="wrap" %}

```python
from openai import OpenAI
import json
openai_client = OpenAI(
    base_url = "http://127.0.0.1:8001/v1",
    api_key = "sk-no-key-required",
)
completion = openai_client.chat.completions.create(
    model = "unsloth/Qwen3-Coder-Next",
    messages = [{"role": "user", "content": "在 HTML 中创建一个 Flappy Bird 游戏"},],
)
print(completion.choices[0].message.content)
```

{% endcode %}

将会输出：

{% columns %}
{% column width="66.66666666666666%" %}
{% code overflow="wrap" expandable="true" %}

````markdown
这是一个完整可运行的 Flappy Bird 游戏，包含在单个文件中。

我使用 **HTML5 Canvas** 来绘制图形，并使用 **JavaScript** 实现物理效果（重力、碰撞检测和计分）。无需外部图片或下载；游戏通过代码绘制小鸟和管道。

### 如何运行：
1.  复制下面的代码块。
2.  在你的电脑上创建一个名为 `game.html` 的新文件。
3.  将代码粘贴到该文件中并保存它。
4.  双击 `game.html` 以在浏览器中打开它。

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单的 Flappy Bird</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #333;
            font-family: 'Courier New', Courier, monospace;
            color: white;
        }

        h1 {
            margin-bottom: 10px;
        }

        #game-container {
            position: relative;
            box-shadow: 0 0 20px rgba(0,0,0,0.5);
        }

        canvas {
            display: block;
            background-color: #70c5ce; /* 天蓝色 */
            border: 4px solid #000;
        }

        #ui-layer {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none; /* 让点击穿透到 canvas */
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
        }

        .message {
            background: rgba(255, 255, 255, 0.8);
            padding: 20px;
            border-radius: 10px;
            color: #333;
        }

        #score-board {
            position: absolute;
            top: 20px;
            width: 100%;
            text-align: center;
            font-size: 40px;
            font-weight: bold;
            color: white;
            text-shadow: 2px 2px 0 #000;
            z-index: 10;
        }
    </style>
</head>
<body>

    <h1>Flappy Bird 克隆版</h1>
    
    <div id="game-container">
        <div id="score-board">0</div>
        <canvas id="birdCanvas" width="320" height="480"></canvas>
        
        <div id="ui-layer">
            <div id="start-screen" class="message">
                <h2>准备起飞了吗？</h2>
                <p>按 <strong>Space</strong> 或 <strong>单击</strong> 来跳跃</p>
                <p>按 Space 开始</p>
            </div>
            <div id="game-over-screen" class="message" style="display: none;">
                <h2>游戏结束</h2>
                <p>得分：<span id="final-score">0</span></p>
                <p>最佳：<span id="best-score">0</span></p>
                <p>按 <strong>Space</strong> 重新开始</p>
            </div>
        </div>
    </div>

    <script>
        // --- 配置 ---
        const canvas = document.getElementById('birdCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score-board');
        const startScreen = document.getElementById('start-screen');
        const gameOverScreen = document.getElementById('game-over-screen');
        const finalScoreSpan = document.getElementById('final-score');
        const bestScoreSpan = document.getElementById('best-score');

        // 游戏变量
        let frames = 0;
        let score = 0;
        let highScore = localStorage.getItem('flappyHighScore') || 0;
        let gameState = 'START'; // START, PLAYING, GAMEOVER
        const gravity = 0.25;
        const speed = 2; // 管道向左移动的速度

        // --- 小鸟对象 ---
        const bird = {
            x: 50,
            y: 150,
            width: 30,
            height: 30,
            velocity: 0,
            jumpStrength: 4.5,
            radius: 15,
            draw: function() {
                ctx.fillStyle = "#FFD700"; // 金色
                ctx.beginPath();
                ctx.arc(this.x + this.radius, this.y + this.radius, this.radius, 0, Math.PI * 2);
                ctx.fill();
                ctx.lineWidth = 2;
                ctx.stroke();

                // 眼睛
                ctx.fillStyle = "white";
                ctx.beginPath();
                ctx.arc(this.x + this.radius + 5, this.y + this.radius - 5, 5, 0, Math.PI * 2);
                ctx.fill();
                ctx.fillStyle = "black";
                ctx.beginPath();
                ctx.arc(this.x + this.radius + 7, this.y + this.radius - 5, 2, 0, Math.PI * 2);
                ctx.fill();
                
                // 喙
                ctx.fillStyle = "orange";
                ctx.beginPath();
                ctx.moveTo(this.x + this.radius + 10, this.y + this.radius);
                ctx.lineTo(this.x + this.radius + 20, this.y + this.radius + 5);
                ctx.lineTo(this.x + this.radius + 10, this.y + this.radius + 10);
                ctx.fill();
                ctx.stroke();
            },
            update: function() {
                this.velocity += gravity;
                this.y += this.velocity;

                // 地面碰撞
                if (this.y + this.height >= canvas.height) {
                    this.y = canvas.height - this.height;
                    gameOver();
                }
                
                // 天花板碰撞（可选：防止飞到管道上方）
                if (this.y < 0) {
                    this.y = 0;
                    this.velocity = 0;
                }
            },
            jump: function() {
                this.velocity = -this.jumpStrength;
            },
            reset: function() {
                this.y = 150;
                this.velocity = 0;
            }
        };

        // --- 管道数组 ---
        const pipes = {
            position: [],
            width: 50,
            gap: 120, // 上下管道之间的间隙
            dx: 2, // 移动速度

            draw: function() {
                for (let i = 0; i < this.position.length; i++) {
                    let p = this.position[i];
                    let topY = p.y;
                    let bottomY = p.y + this.gap;

                    ctx.fillStyle = "#228B22"; // 森林绿

                    // 上管道
                    ctx.fillRect(p.x, 0, this.width, topY);
                    ctx.strokeRect(p.x, 0, this.width, topY);

                    // 下管道
                    ctx.fillRect(p.x, bottomY, this.width, canvas.height - bottomY);
                    ctx.strokeRect(p.x, bottomY, this.width, canvas.height - bottomY);
                }
            },

            update: function() {
                // 每 120 帧添加一个新管道（约 2 秒）
                if (frames % 120 === 0) {
                    // 上管道随机高度
                    // 最小高度 50，最大高度为 canvas - gap - 50
                    let maxY = canvas.height - this.gap - 50;
                    let randomY = Math.floor(Math.random() * (maxY - 50 + 1) + 50);
                    
                    this.position.push({
                        x: canvas.width,
                        y: randomY
                    });
                }

                for (let i = 0; i < this.position.length; i++) {
                    let p = this.position[i];
                    p.x -= this.dx;

                    // 碰撞检测
                    // 逻辑：检查小鸟的 X 是否在管道 X 范围内
                    if (bird.x + bird.width > p.x && bird.x < p.x + this.width) {
                        // 逻辑：检查小鸟的 Y 是否撞到上管道或下管道
                        if (bird.y < p.y || bird.y + bird.height > p.y + this.gap) {
                            gameOver();
                        }
                    }

                    // 得分更新（当小鸟通过管道时）
                    if (p.x + this.width < bird.x && !p.passed) {
                        score++;
                        scoreElement.innerText = score;
                        p.passed = true;
                    }

                    // 移除已移出屏幕的管道
                    if (p.x + this.width <= 0) {
                        this.position.shift();
                        // 由于数组长度变化，i 减 1
                        i--; 
                    }
                }
            },
            
            reset: function() {
                this.position = [];
            }
        };

        // --- 背景（云/草地）---
        const background = {
            draw: function() {
                // 绘制草地
                ctx.fillStyle = "#7cfc00"; // 草坪绿
                ctx.fillRect(0, canvas.height - 20, canvas.width, 20);
                ctx.beginPath();
                ctx.moveTo(0, canvas.height - 20);
                ctx.lineTo(canvas.width, canvas.height - 20);
                ctx.stroke();
            }
        };

        // --- 游戏控制函数 ---

        function loop() {
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // 绘制背景
            background.draw();

            if (gameState === 'START') {
                bird.draw();
                // 绘制地面线
                ctx.fillStyle = "#ded895";
                ctx.fillRect(0, canvas.height - 10, canvas.width, 10);
            } 
            else if (gameState === 'PLAYING') {
                bird.update();
                bird.draw();
                pipes.update();
                pipes.draw();
                frames++;
            } 
            else if (gameState === 'GAMEOVER') {
                pipes.draw();
                bird.draw();
                // 不更新帧数或位置，直接冻结
            }

            requestAnimationFrame(loop);
        }

        function startGame() {
            gameState = 'PLAYING';
            startScreen.style.display = 'none';
            gameOverScreen.style.display = 'none';
            score = 0;
            frames = 0;
            scoreElement.innerText = score;
            bird.reset();
            pipes.reset();
        }

        function gameOver() {
            gameState = 'GAMEOVER';
            
            // 更新最高分
            if (score > highScore) {
                highScore = score;
                localStorage.setItem('flappyHighScore', highScore);
            }

            finalScoreSpan.innerText = score;
            bestScoreSpan.innerText = highScore;
            gameOverScreen.style.display = 'block';
        }

        // --- 输入处理 ---

        function handleInput(e) {
            // 阻止 Space 的默认滚动行为
            if (e.type === 'keydown' && e.code === 'Space') {
                e.preventDefault();
            }

            if (e.code === 'Space' || e.type === 'mousedown' || e.type === 'touchstart') {
                switch (gameState) {
                    case 'START':
                        startGame();
                        bird.jump();
                        break;
                    case 'PLAYING':
                        bird.jump();
                        break;
                    case 'GAMEOVER':
                        startGame();
                        bird.jump();
                        break;
                }
            }
        }

        window.addEventListener('keydown', handleInput);
        canvas.addEventListener('mousedown', handleInput);
        canvas.addEventListener('touchstart', handleInput);

        // 初始化
        loop();

    </script>
</body>
</html>
```

### 此版本的功能：
1.  **物理效果：** 真实的重力和跳跃机制。
2.  **碰撞检测：** 如果你撞到管道、地面或天花板，游戏就会结束。
3.  **计分系统：** 每通过一个管道可得 1 分。
4.  **最高分：** 使用浏览器的 LocalStorage 记录你的最佳分数，即使刷新页面也会保留。
5.  **响应式控制：** 支持 **空格键**、**鼠标点击** 或 **触摸**（适用于移动设备）。
6.  **图形：** 小鸟由代码绘制（包括眼睛和喙），管道带有边框，因此不会出现图片链接失效的问题。
````

{% endcode %}

我们提取了 HTML 并运行了它，它生成的 Flappy Bird 示例游戏运行得很好！
{% endcolumn %}

{% column width="33.33333333333334%" %}

<figure><img src="/files/6709c4bbafc7e69a4eb5d97a8d1f29f6b3b4f4d6" alt=""><figcaption></figcaption></figure>
{% endcolumn %}
{% endcolumns %}

### 👾 OpenAI Codex 和 Claude Code <a href="#claude-codex" id="claude-codex"></a>

若要通过本地编程代理工作负载运行该模型，你可以参考我们的指南。使用 `llama-server` 我们刚刚设置的内容，并将模型名设置为它在 `GET /v1/models` （ `--alias` 上面的值， `unsloth/Qwen3-Coder-Next`）。请遵循正确的 Qwen3-Coder-Next 参数和使用说明。

{% columns %}
{% column %}
{% content-ref url="/pages/1a707991086189a8e5cd8374f3ce1b81915bc159" %}
[Claude Code](/docs/zh/ji-chu/claude-code.md)
{% endcontent-ref %}
{% endcolumn %}

{% column %}
{% content-ref url="/pages/b71ddea7924324c058a771e5e831c3cb6fc75b18" %}
[OpenAI Codex](/docs/zh/ji-chu/codex.md)
{% endcontent-ref %}
{% endcolumn %}
{% endcolumns %}

例如，在按照 Claude Code 的说明后，你会看到：

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

然后我们可以输入 `创建一个国际象棋的 Python 游戏` :

<div><figure><img src="/files/f550af4f99be6b79fd3b5a400e30ad58218fa7e3" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="/files/fdd9c81b9b972c00c10cb5f7f81465750b5ffb9f" alt="" width="563"><figcaption></figcaption></figure> <figure><img src="/files/578a400d2f1235e4bf41d8620874e1c714fa38e6" alt="" width="563"><figcaption></figcaption></figure></div>

如果你看到 `API 错误：400 {"error":{"code":400,"message":"请求（16582 个 token）超过了可用上下文大小（16384 个 token），请尝试增加它","type":"exceed_context_size_error","n_prompt_tokens":16582,"n_ctx":16384}}` 这意味着你需要增加上下文长度，或者查看 [#how-to-fit-long-context-256k-to-1m](#how-to-fit-long-context-256k-to-1m "mention")

<figure><img src="/files/74382468c8a8bbf787b4c29d07149d3f7f38a6a2" alt=""><figcaption></figcaption></figure>

### 🎱 vLLM 中的 FP8 Qwen3-Coder-Next

你现在可以使用我们新的 [FP8 动态量化版本](https://huggingface.co/unsloth/Qwen3-Coder-Next-FP8-Dynamic) 用于高质量且快速的推理。首先从 nightly 版本安装 vLLM。将 `--extra-index-url https://wheels.vllm.ai/nightly/cu130` 改为与你的 CUDA 版本相匹配，该版本可通过以下方式查找： `nvidia-smi` - 仅 `cu129` 和 `cu130` 目前受支持。

{% hint style="success" %}
如果使用 vLLM / SGLang，请尝试使用我们的 FP8-Dynamic 量化版本，其吞吐量可提升 25% 或更多！请参见 [#fp8-qwen3-coder-next-in-vllm](#fp8-qwen3-coder-next-in-vllm "mention")
{% endhint %}

{% code overflow="wrap" %}

```bash
# 如果你没有安装 uv，请先安装以便更快地安装环境
curl -LsSf https://astral.sh/uv/install.sh | sh

# 创建一个新的 Python 环境——如果你想修改整个系统，则不需要
uv venv unsloth_fp8 --python 3.12 --seed
source unsloth_fp8/bin/activate

uv pip install --upgrade --force-reinstall vllm --torch-backend=auto --extra-index-url https://wheels.vllm.ai/nightly/cu130
uv pip install --upgrade --force-reinstall git+https://github.com/huggingface/transformers.git
uv pip install --force-reinstall numba
```

{% endcode %}

然后启动服务 [Unsloth 的动态 FP8 版本](https://huggingface.co/unsloth/Qwen3-Coder-Next-FP8-Dynamic) 的模型。你还可以通过添加以下参数启用 FP8，将 KV 缓存内存占用减少 50% `--kv-cache-dtype fp8` 我们在 4 张 GPU 上进行了部署，但如果你只有 1 张 GPU，请使用 `CUDA_VISIBLE_DEVICES='0'` 并设置 `--tensor-parallel-size 1` 或者移除此参数。使用 `tmux` 在新终端中启动下面的命令，然后按 CTRL+B+D —— 使用 `tmux attach-session -t0` 返回到该会话。

```bash
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False
CUDA_VISIBLE_DEVICES='0,1,2,3' vllm serve unsloth/Qwen3-Coder-Next-FP8-Dynamic \\
    --served-model-name unsloth/Qwen3-Coder-Next \\
    --tensor-parallel-size 4 \\
    --tool-call-parser qwen3_coder \\
    --enable-auto-tool-choice \\
    --dtype bfloat16 \\
    --seed 3407 \\
    --max-model-len 200000 \\
    --gpu-memory-utilization 0.93 \\
    --port 8001
```

你应该会看到如下内容。请参见 [#tool-calling-with-qwen3-coder-next](#tool-calling-with-qwen3-coder-next "mention") 了解如何使用 OpenAI API 和工具调用来实际使用 Qwen3-Coder-Next——这适用于 vLLM 和 llama-server。

<figure><img src="/files/515ccb4201b70e73df8fff2e1d837f67d8f4ddf6" alt=""><figcaption></figcaption></figure>

### :wrench:使用 Qwen3-Coder-Next 的工具调用

在新的终端中，我们创建一些工具，例如将 2 个数字相加、执行 Python 代码、执行 Linux 函数等等：

{% code expandable="true" %}

```python
import json, subprocess, random
from typing import Any
def add_number(a: float | str, b: float | str) -> float:
    return float(a) + float(b)
def multiply_number(a: float | str, b: float | str) -> float:
    return float(a) * float(b)
def subtract_number(a: float | str, b: float | str) -> float:
    return float(a) - float(b)
def write_a_story() -> str:
    return random.choice([
        "很久很久以前，在一个遥远的星系里……",
        "有两个朋友热爱树懒和代码……",
        "世界正在终结，因为每只树懒都进化出了超人般的智慧……",
        "其中一位朋友不知道，另一位不小心编写了一个让树懒进化的程序……",
    ])
def terminal(command: str) -> str:
    if "rm" in command or "sudo" in command or "dd" in command or "chmod" in command:
        msg = "由于这些命令很危险，无法执行 'rm, sudo, dd, chmod' 命令"
        print(msg); return msg
    print(f"正在执行终端命令 `{command}`")
    try:
        return str(subprocess.run(command, capture_output = True, text = True, shell = True, check = True).stdout)
    except subprocess.CalledProcessError as e:
        return f"命令失败：{e.stderr}"
def python(code: str) -> str:
    data = {}
    exec(code, data)
    del data["__builtins__"]
    return str(data)
MAP_FN = {
    "add_number": add_number,
    "multiply_number": multiply_number,
    "subtract_number": subtract_number,
    "write_a_story": write_a_story,
    "terminal": terminal,
    "python": python,
}
tools = [
    {
        "type": "function",
        "function": {
            "name": "add_number",
            "description": "将两个数字相加。",
            "参数": {
                "类型": "object",
                "属性": {
                    "a": {
                        "类型": "string",
                        "描述": "第一个数字。",
                    },
                    "b": {
                        "类型": "string",
                        "描述": "第二个数字。",
                    },
                },
                "必需": ["a", "b"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "名称": "multiply_number",
            "描述": "将两个数字相乘。",
            "参数": {
                "类型": "object",
                "属性": {
                    "a": {
                        "类型": "string",
                        "描述": "第一个数字。",
                    },
                    "b": {
                        "类型": "string",
                        "描述": "第二个数字。",
                    },
                },
                "必需": ["a", "b"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "名称": "subtract_number",
            "描述": "将两个数字相减。",
            "参数": {
                "类型": "object",
                "属性": {
                    "a": {
                        "类型": "string",
                        "描述": "第一个数字。",
                    },
                    "b": {
                        "类型": "string",
                        "描述": "第二个数字。",
                    },
                },
                "必需": ["a", "b"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "名称": "write_a_story",
            "描述": "编写一个随机故事。",
            "参数": {
                "类型": "object",
                "属性": {},
                "必需": [],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "名称": "terminal",
            "描述": "在终端中执行操作。",
            "参数": {
                "类型": "object",
                "属性": {
                    "command": {
                        "类型": "string",
                        "描述": "你希望执行的命令，例如 `ls`、`rm` 等。",
                    },
                },
                "必需": ["command"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "名称": "python",
            "描述": "调用一个 Python 解释器来运行一些 Python 代码。",
            "参数": {
                "类型": "object",
                "属性": {
                    "code": {
                        "类型": "string",
                        "描述": "要运行的 Python 代码",
                    },
                },
                "必需": ["code"],
            },
        },
    },
]
```

{% endcode %}

然后我们使用下面的函数（复制、粘贴并执行），它们会自动解析函数调用，并为任何模型调用 OpenAI 端点：

{% code overflow="wrap" expandable="true" %}

```python
from openai import OpenAI
def unsloth_inference(
    messages,
    temperature = 1.0,
    top_p = 0.95,
    top_k = 40,
    min_p = 0.01,
    repetition_penalty = 1.0,
):
    messages = messages.copy()
    openai_client = OpenAI(
        base_url = "http://127.0.0.1:8001/v1",
        api_key = "sk-no-key-required",
    )
    model_name = next(iter(openai_client.models.list())).id
    print(f"使用的模型 = {model_name}")
    has_tool_calls = True
    original_messages_len = len(messages)
    while has_tool_calls:
        print(f"当前消息 = {messages}")
        response = openai_client.chat.completions.create(
            model = model_name,
            messages = messages,
            temperature = temperature,
            top_p = top_p,
            tools = tools if tools else None,
            tool_choice = "auto" if tools else None,
            extra_body = {"top_k": top_k, "min_p": min_p, "repetition_penalty" :repetition_penalty,}
        )
        tool_calls = response.choices[0].message.tool_calls or []
        content = response.choices[0].message.content or ""
        tool_calls_dict = [tc.to_dict() for tc in tool_calls] if tool_calls else tool_calls
        messages.append({"role": "assistant", "tool_calls": tool_calls_dict, "content": content,})
        for tool_call in tool_calls:
            fx, args, _id = tool_call.function.name, tool_call.function.arguments, tool_call.id
            out = MAP_FN[fx](**json.loads(args))
            messages.append({"role": "tool", "tool_call_id": _id, "name": fx, "content": str(out),})
        else:
            has_tool_calls = False
    return messages
```

{% endcode %}

现在我们将在下面展示多种适用于许多不同用例的工具调用方法：

#### 执行生成的 Python 代码

{% code overflow="wrap" %}

```python
messages = [{
    "role": "user",
    "content": [{"type": "text", "text": "在 Python 中创建一个斐波那契函数并求 fib(20)。"}],
}]
unsloth_inference(messages, temperature = 1.0, top_p = 0.95, top_k = 40, min_p = 0.00)
```

{% endcode %}

<figure><img src="/files/5410fcd3e79df9fb13bea8bfb3eb04b55f5ae9f0" alt=""><figcaption></figcaption></figure>

#### 执行任意终端函数

{% code overflow="wrap" %}

```python
messages = [{
    "role": "user",
    "content": [{"type": "text", "text": "把 'I'm a happy Sloth' 写入文件，然后把它打印回来给我。"}],
}]
messages = unsloth_inference(messages, temperature = 1.0, top_p = 1.0, top_k = 40, min_p = 0.00)
```

{% endcode %}

我们确认文件已创建，而且确实创建了！

<figure><img src="/files/43a1a50b1a9c0a638d25283d3d0ef75aa4e6053f" alt=""><figcaption></figcaption></figure>

参见 [Tool Calling Guide](/docs/zh/ji-chu/tool-calling-guide-for-local-llms.md) 查看更多工具调用示例。

## :triangular\_ruler:基准测试

### GGUF 量化基准测试

这里是由第三方评测者进行的一些量化基准测试。

<div><figure><img src="/files/83eaba98aad122507f5764cfdb1675596460ada9" alt="" width="563"><figcaption><p>Aider Polyglot 基准测试</p></figcaption></figure> <figure><img src="/files/d10b056c649759de5b958a5a1e40f69826e1883c" alt="" width="450"><figcaption><p>Benjamine Marie 基准测试（<a href="https://x.com/bnjmn_marie/status/2019809651387514947/photo/1">来源</a>)</p></figcaption></figure></div>

{% columns %}
{% column %}
基准测试由 Aider Polyglot 服务器上的第三方贡献者运行，将 Unsloth GGUF 量化在 Aider Polyglot 基准测试（得分 vs. VRAM）上进行比较。值得注意的是，3-bit **`UD-IQ3_XXS`** 量化几乎接近 **BF16** 性能，使得 **3-bit 成为一个合理的最低** 适用于大多数用例。

**NVFP4** 略微优于 BF16 参考值，这可能是由于运行次数有限导致的采样噪声；不过，整体模式： **1-bit → 2-bit → 3-bit → 6-bit** 稳步提升，表明该基准测试正在捕捉 Unsloth GGUF 之间有意义的质量差异。 **非 Unsloth** FP8 的表现似乎比两者都差 **`UD-IQ3_XXS`** 和 **`UD-Q6_K_XL`**，这可能反映了量化流程中的差异，或者同样是采样不足。
{% endcolumn %}

{% column %}
[Benjamin Marie（第三方）进行了基准测试](https://x.com/bnjmn_marie/status/2019809651387514947/photo/1) **Qwen3-Coder-Next** 使用 Unsloth 和 Qwen GGUF 在一个 **750 个提示的混合套件** （LiveCodeBench v6、MMLU Pro、GPQA、Math500），并报告了 **总体准确率** 和 **相对错误增加** （量化模型相较于原始模型出错的频率增加了多少）。

图表清楚显示，Unsloth 的 Q4\_K\_M 量化效果优于标准 Q4\_K\_M。Q3\_K\_M 如预期在 Live Code Bench v6 上表现较差，但令人惊讶的是，它在 HumanEval 上明显优于标准 Q4\_K\_M。\
\
它似乎以最高效率运行，因此建议至少使用 Q4\_K\_M。
{% endcolumn %}
{% endcolumns %}

### Qwen3-Coder-Next 基准测试

Qwen3-Coder-Next 是其规模下表现最佳的模型，其性能可与活跃参数数量多出 10–20 倍的模型相媲美。

<table data-full-width="true"><thead><tr><th>基准</th><th align="right">Qwen3-Coder-Next（80B）</th><th align="right">DeepSeek-V3.2（671B）</th><th align="right">GLM-4.7（358B）</th><th align="right">MiniMax M2.1（229B）</th></tr></thead><tbody><tr><td>SWE-Bench Verified（使用 SWE-Agent）</td><td align="right">70.6</td><td align="right">70.2</td><td align="right">74.2</td><td align="right">74.8</td></tr><tr><td>SWE-Bench Multilingual（使用 SWE-Agent）</td><td align="right">62.8</td><td align="right">62.3</td><td align="right">63.7</td><td align="right">66.2</td></tr><tr><td>SWE-Bench Pro（使用 SWE-Agent）</td><td align="right">44.3</td><td align="right">40.9</td><td align="right">40.6</td><td align="right">34.6</td></tr><tr><td>Terminal-Bench 2.0（使用 Terminus-2 json）</td><td align="right">36.2</td><td align="right">39.3</td><td align="right">37.1</td><td align="right">32.6</td></tr><tr><td>Aider</td><td align="right">66.2</td><td align="right">69.9</td><td align="right">52.1</td><td align="right">61.0</td></tr></tbody></table>

<figure><img src="/files/595922005983ec659098be99550189c8ecad02c7" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/20d8f285588c989aa5b92ab1af95963501e0a68d" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="/files/b39543d5542ac626e76bd679aa1d511c2abdb88c" alt=""><figcaption></figcaption></figure>


---

# 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 dynamically by asking a question.

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

```
GET https://unsloth.ai/docs/zh/mo-xing/qwen3-coder-next.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
