跳至主要内容

如何在本地运行 Qwen3-Next

学习如何在本地运行 Qwen3-Next,使用 transformers serve 提供服务,并通过 cURL 和 OpenAI SDK 进行交互,为您的应用集成做好准备。
· 6分钟 阅读

使用 AI 探索

开源 AI 正以惊人的速度发展;几乎每天都有新模型出现,在性能上超越旧版,同时变得更快、更易训练,也更“适配智能体”。 

在这篇动手教程中,我们将深入了解 Qwen3‑Next,在本地运行它,启动一个简易本地服务器,并完成后续可集成到您应用中的基础设置。最棒的是,我们将全程只使用 Hugging Face Transformers 框架,既用于推理也用于服务化。

完成后,您将能够:

  • 了解 Qwen3‑Next 的新特性
  • 使用 Transformers 在本地运行 Qwen3‑Next
  • 使用 4 位 bitsandbytes(bnb)变体降低内存占用
  • 使用 transformers serve 通过 HTTP 提供 Qwen3‑Next 服务
  • 通过 cURL 和 Python 与服务器交互

Qwen3-Next 简介

Qwen3-Next 是一套面向可扩展性的全新架构,兼顾上下文长度与总参数规模。其 800 亿参数的基础模型在推理时仅激活约 30 亿参数,同时实现与 Dense Qwen3-32B 模型相当或略优的性能,训练成本却低于 10%。对于超过 32,000 个 token 的上下文长度,吞吐量提升超过 10 倍。 

在后训练变体方面,Instruct 模型可与 2350 亿参数旗舰模型竞争,并支持最多 256,000 个 token 的上下文长度。此外,Thinking 变体的表现优于 Qwen3-30B-A3B、Qwen3-32B 以及 Gemini-2.5-Flash-Thinking,接近 2350 亿参数 Thinking 模型的水平。

来源: Qwen

Qwen3-Next 的新特性:

  • 混合注意力(Gated DeltaNet + Gated Attention,3:1):将用于长输入的高速、低内存注意力与标准注意力相结合,以实现精确回忆。输出门控、更大的注意力头(256)以及部分 RoPE(25%)使其在超长序列上兼具高精度与高效率。
  • 超稀疏 MoE(512 专家;10 路由 + 1 共享;~3B/80B 激活):每个 token 仅有模型的一小部分参与运行,降低算力与内存开销,同时保持高质量。全局负载均衡将任务分配到各专家,带来稳定且不浪费的性能提升。
  • 稳定性优先的训练:输出门控注意力防止激活失控;带权重衰减的零中心 RMSNorm 保持归一化权重稳定;归一化的 MoE 路由器初始化避免早期训练混乱。总体效果:更少训练波动,更顺滑的扩展。
  • 原生多 Token 预测(MTP):允许模型一次自信地提出多个后续 token,提升解码速度。多步训练与推理时的使用方式一致,提高了推测解码的接受率而不牺牲质量。
  • 强化学习稳定性修复:在混合注意力和高稀疏 MoE 配置上,强化学习微调更快且更不易崩溃——因此能更快达到更优的最终性能。

您可以在 Hugging Face 和 ModelScope 获取 Qwen3‑Next 以供本地下载使用,或使用 vLLM、SGLang、Transformers Serve 等框架将其部署为服务器。 

本地运行 Qwen3-Next

要在本地运行 Qwen3-Next,我们将从主仓库安装 transformers 库,并安装 accelerate、bitsandbytes、flash-linear-attention 和 causal-conv1d 以获得更快的后端。 

安装完成后,请重启 Jupyter 笔记本内核。 

%%capture

!pip install git+https://github.com/huggingface/transformers.git@main
!pip install accelerate bitsandbytes

!pip install git+https://github.com/fla-org/flash-linear-attention.git
!pip install git+https://github.com/Dao-AILab/causal-conv1d.git

接下来,使用合适的数据类型与设备映射下载并加载分词器与模型。 

我们将加载一个 4 位量化模型,可将内存占用减少至四分之一。这意味着加载并运行推理所需的存储空间和显存更少。 

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_name = "unsloth/Qwen3-Next-80B-A3B-Instruct-bnb-4bit"

# --- Load tokenizer ---
tokenizer = AutoTokenizer.from_pretrained(model_name)

# --- Load model ---
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    device_map="auto", 
    dtype="auto", 
)

随后,我们将创建一个提示词,组织消息,并通过聊天模板处理,确保其具备 Qwen3-Next 识别的必要格式。 

# prepare the model input
prompt = "Write a short introduction to large language models, highlighting how learners can explore them through DataCamp's interactive courses and hands-on projects."
messages = [
    {"role": "user", "content": prompt},
]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
)

之后,我们将把文本进行分词,传入模型,并仅提取输出的 token。最后进行解码并展示最终响应。 

model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

# conduct text completion
generated_ids = model.generate(
    **model_inputs,
    max_new_tokens=512,
)
output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist() 

content = tokenizer.decode(output_ids, skip_special_tokens=True)

print("content:", content)

输出效果很理想:

content: Large language models (LLMs) are advanced AI systems trained on vast amounts of text data to understand, generate, and reason with human language. 
From answering questions and writing code to summarizing documents and engaging in conversation, LLMs are transforming how we interact with technology--and how we learn. 
At DataCamp, learners can explore the power of LLMs through interactive courses and hands-on projects that bridge theory with real-world application. 
Whether you're building your first chatbot, fine-tuning a model with Hugging Face, or evaluating AI-generated text, DataCamp's guided, code-based learning environment lets you experiment safely and effectively--no prior AI expertise required. 
Start your journey into the future of language AI today.

有几点需要注意: 

  1. 4 位大小:4 位量化的 Qwen3-Next 模型仅权重就约 60 GB;考虑开销/kv-cache,通常需要 约 60–80 GB 显存 才能流畅生成。纯 CPU 也可运行,但非常慢。
  2. 加载时间:在较慢的磁盘(如 HDD/网络盘)上,初次加载可能较久。SSD/NVMe 会大幅改善。
  3. 保持显存驻留:一旦加载,模型会留在 GPU 内存中,除非您手动释放或重启内核,因此后续推理会快很多。
  4. 确保使用 GPU:如果 torch.cuda.is_available() 为 False,说明正在使用 CPU。请仔细检查您的 CUDA/驱动配置。

提供 Qwen3-Next 服务

您可以使用 SGLang 或 vLLM 在本地提供 Qwen3-Next 服务,具体见 Qwen 的模型页面。不过在本教程中,我们将学习一项新技能:使用 Transformers 的 CLI 来提供模型服务,并通过 Transformers 提供的聊天界面进行访问,类似于 Ollama。

首先,安装具备服务能力的 Transformers 库:

pip install transformers[serving]

接着,从终端启动 Transformers 服务器。这是一个通用服务器,类似 Ollama。 

transformers serve

如您所见,服务器将开放在 8000 端口:

INFO:     Started server process [3502]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://localhost:8000 (Press CTRL+C to quit)

与服务器交互的最简方式是使用 Transformers 的 chat CLI。它能连接到服务器,并在终端中提供类似聊天的界面。

打开一个新的终端窗口并安装 Rich 库:

pip install rich

然后运行以下命令,以模型路径启动聊天界面:

transformers chat localhost:8000 \
  --model-name-or-path unsloth/Qwen3-Next-80B-A3B-Instruct-bnb-4bit

Transformers chat 会自动选择并加载已下载的模型。初次加载可能需要一些时间,随后您就可以开始对话了。

如图所示,我们正通过聊天界面在本地与 Qwen3-Next 模型交互。

与 Qwen3-Next 服务器交互

我们有多种方式与服务器交互。您可以使用 Hugging Face Hub 的 AsyncInferenceClient,发起 CURL 命令,使用 Python 的 requests 库,或通过 OpenAI API 访问服务器。 

该服务器兼容 OpenAI,因此您可以将其集成到 VSCode、Agentic 工作流中,或将其用作MCP 服务器。

首先,我们在新终端中运行一个简单的 CURL 命令,查看服务器上有多少可用模型:

curl -s http://localhost:8000/v1/models

随后,我们将使用 responses API。我们会提供模型、提示词,并将流式传输设为 false:

curl -s http://localhost:8000/v1/responses \
  -H "Content-Type: application/json" \
  -d '{
    "model": "unsloth/Qwen3-Next-80B-A3B-Instruct-bnb-4bit",
    "input": "One line: what is Qwen3-Next?",
    "stream": false
  }'

结果将生成包含 Qwen3-Next 模型信息的响应。 

{"response":{"id":"resp_req_0","created_at":1758494863.6661901,"model":"unsloth/Qwen3-Next-80B-A3B-Instruct-bnb-4bit@main","object":"response","output":[{"id":"msg_req_0","content":[{"annotations":[],"text":"Qwen3-Next is the next-generation large language model in Alibaba's Qwen series, featuring enhanced performance, broader knowledge, and improved reasoning capabilities.","type":"output_text"}],"role":"assistant","status":"completed","type":"message","annotations":[]}],"parallel_tool_calls":false,"tool_choice":"auto","tools":[],"status":"completed","text":{"format":{"type":"text"}}},"sequence_number":40,"type":"response.completed"}

同样,您也可以新建一个 Python 文件,加入以下代码并运行。 

代码会使用本地服务器 URL 初始化 OpenAI 客户端。我们提供模型名称与输入,并以流的方式生成响应。 

from openai import OpenAI

# Connect to your local server
client = OpenAI(
    base_url="http://localhost:8000/v1",  # transformers serve endpoint
    api_key="not-needed"                  # required by SDK, but can be dummy
)

# Create a streaming response request
response = client.responses.create(
    model="unsloth/Qwen3-Next-80B-A3B-Instruct-bnb-4bit",  # use your loaded model
    instructions="You are a helpful assistant.",
    input="What is love?",
    stream=True,                      # enable SSE streaming
    metadata={"source": "local-test"} # optional metadata
)

# Iterate over server-sent events
for event in response:
    if event.type == "response.output_text.delta":
        # This event contains the incremental text
        print(event.delta, end="", flush=True)
    elif event.type == "response.completed":
        print("\n--- done ---")

我们以流式响应的形式得到了正确结果。非常棒。

Love is one of the most profound, complex, and universal human experiences -- a powerful emotion that defies simple definition but shapes our lives in countless ways.

At its core, **love** is a deep affection, care, and connection toward another person -- or even a thing, idea, or cause. It can manifest in many forms:

### Types of Love (from ancient Greek philosophy):
- **Eros**: Passionate, romantic, or sexual love.
- **Philia**: Deep friendship and platonic affection.
- **Storge**: Familial love -- the natural affection between parents and children.
- **Agape**: Selfless, unconditional love -- often spiritual or altruistic.
- **Ludus**: Playful, flirtatious love.
- **Pragma**: Long-lasting, committed love built on patience and compromise.
- **Philautia**: Self-love -- healthy self-regard that enables us to love others.

### What Love Feels Like:
- **Emotionally**: Warmth, safety, joy, vulnerability, longing, and sometimes pain.
- **Behaviorally**: Acts of kindness, sacrifice, patience, listening, and presence.
- **Biologically**: Involves neurotransmitters like oxytocin, dopamine, and serotonin -- chemicals that bond us and create attachment.

### Love Is Also a Choice:
Beyond feelings, love is often a decision -- to show up, to forgive, to stay even when it's hard. It's not just a rush of butterflies; it's the quiet commitment to care for someone day after day.

### In Essence:
> **Love is seeing someone's soul -- and choosing to hold it gently.**

It's the reason people write poetry, compose music, risk everything for another, and find meaning in life. Love connects us -- to others, to ourselves, and to something greater than just our individual existence.

So what is love?  
It's complicated. It's messy. It's beautiful.  
And above all -- it's human. ❤️
--- done ---

结语

撰写本文时,Qwen3-Next 的 GGUF 版本尚未发布,这意味着无法借助 Ollama 或 Llama.cpp 在本地运行。完整模型要高效运行需要四张 A100 GPU,因此我们选择了量化版本,使其可以在一张 80GB 显存的 A100 上运行。尽管下载与配置花费了一些时间,但我们已成功学习了如何进行推理。

在本教程中,我们探索了 Qwen3-Next 模型。尽管规模更小,但其在速度与准确性上可与其他领先的专有模型竞争。

在本地运行模型后,我们通过 curl 命令和 OpenAI Python SDK 访问了它。接下来的步骤是针对您的特定机器优化该模型。我们可能会探索更小的版本,例如 1.2 位模型,以在低端 GPU 上进一步提升推理速度。

或者,您也可以考虑租用 GPU 服务器来搭建自己的私有 LLM 服务器,Runpod 是一个值得考虑的选择。

Abid Ali Awan

作者

Abid Ali Awan

作为一名持证的数据科学家,我热衷于利用前沿技术打造创新的机器学习应用。凭借在语音识别、数据分析与报告、MLOps、对话式人工智能以及自然语言处理方面的扎实背景,我不断打磨构建智能系统的能力,力求带来切实影响。除技术专长外,我也擅长沟通,能够将复杂概念提炼为清晰、简明的表述。因此,我成为数据科学领域备受关注的博主,与不断壮大的数据专业人士社区分享洞见与实践经验。目前,我专注于内容创作与编辑,借助大语言模型打造有力且吸引人的内容,帮助企业与个人更好地发挥数据价值。

主题