> 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，这是一款 800 亿参数的 MoE 模型（30 亿活跃参数），具备 **256K 上下文** 用于快速的智能体式编码和本地使用。其性能可与活跃参数多 10–20 倍的模型相媲美。

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

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

**全新！** 请参阅 [量化基准测试](#gguf-quantization-benchmarks) 适用于我们的 Dynamic GGUF！

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

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

Qwen3-Coder-Next 的 Unsloth 版 [动态 GGUF](/docs/zh/ji-chu-zhi-shi/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="/pages/07558781d1c2c35e14fcaa4821ee92be27a005a8#improving-generation-speed" 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 位量化，你大约需要 46GB RAM/统一内存。为了获得最佳性能，我们建议至少使用 3 位精度。

#### 🦥 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**

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

然后进入 [Studio 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 位以适配大多数设备）：

{% 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-zhi-shi/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": "Create a Flappy Bird game in HTML"},],
)
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="zh">
<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; /* 让点击穿透到画布 */
            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>Click</strong> 跳跃</p>
                <p>按空格开始</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 减一
                        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) {
            // 阻止空格键的默认滚动行为
            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` 我们刚刚设置好的，并将模型名称设置为它在以下位置报告的精确 id `GET /v1/models` （上面的 `--alias` 值， `unsloth/Qwen3-Coder-Next`）。请遵循正确的 Qwen3-Coder-Next 参数和使用说明。

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

{% column %}
{% content-ref url="/pages/b71ddea7924324c058a771e5e831c3cb6fc75b18" %}
[OpenAI Codex](/docs/zh/ji-chu-zhi-shi/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 的工具调用

在新终端中，我们创建一些工具，比如对两个数字求和、执行 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": "将两个数字相加。",
            "parameters": {
                "type": "object",
                "properties": {
                    "a": {
                        "type": "string",
                        "description": "第一个数字。",
                    },
                    "b": {
                        "type": "string",
                        "description": "第二个数字。",
                    },
                },
                "required": ["a", "b"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "multiply_number",
            "description": "将两个数字相乘。",
            "parameters": {
                "type": "object",
                "properties": {
                    "a": {
                        "type": "string",
                        "description": "第一个数字。",
                    },
                    "b": {
                        "type": "string",
                        "description": "第二个数字。",
                    },
                },
                "required": ["a", "b"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "subtract_number",
            "description": "将两个数字相减。",
            "parameters": {
                "type": "object",
                "properties": {
                    "a": {
                        "type": "string",
                        "description": "第一个数字。",
                    },
                    "b": {
                        "type": "string",
                        "description": "第二个数字。",
                    },
                },
                "required": ["a", "b"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "write_a_story",
            "description": "写一个随机故事。",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": [],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "terminal",
            "description": "从终端执行操作。",
            "parameters": {
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "你想要执行的命令，例如 `ls`、`rm` 等。",
                    },
                },
                "required": ["command"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "python",
            "description": "调用一个 Python 解释器来运行一些 Python 代码。",
            "parameters": {
                "type": "object",
                "properties": {
                    "code": {
                        "type": "string",
                        "description": "要运行的 Python 代码",
                    },
                },
                "required": ["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": "将‘我是一个快乐的树懒’写入文件，然后再把它打印给我。"}],
}]
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-zhi-shi/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 位 **`UD-IQ3_XXS`** 量化结果接近 **BF16** 性能，使得 **3 位成为一个合理的最低值** 适用于大多数用例。

**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.
