> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/llama4.md).

# Llama 4（Scout 与 Maverick）

在 Clore.ai GPU 上运行 Meta Llama 4 Scout 与 Maverick MoE 模型

Meta 的 Llama 4，于 2025 年 4 月发布，标志着向 **专家混合（MoE）** 架构。Llama 4 不再为每个 token 激活全部参数，而是将每个 token 路由到专门的“专家”子网络——以更低的计算成本实现前沿性能。提供两个开放权重模型： **Scout** （适合单 GPU）和 **Maverick** （多 GPU 强力机型）。

## 主要特性

* **MoE 架构**：每个 token 仅激活 17B 参数（总计 109B/400B）
* **超大上下文窗口**：Scout 支持 1000 万 token，Maverick 支持 100 万 token
* **原生多模态**：开箱即用，可同时理解文本和图像
* **两个模型**：Scout（16 个专家，适合单 GPU）和 Maverick（128 个专家，多 GPU）
* **具竞争力的性能**：Scout 可媲美 Gemma 3 27B；Maverick 可与 GPT-4o 级模型竞争
* **开放权重**：Llama 社区许可证（适用于大多数商业用途，免费）

## 模型变体

| 模型           | 总参数量 | 激活参数量 | 专家数 | 上下文   | 最低显存（Q4） | 最低显存（FP16） |
| ------------ | ---- | ----- | --- | ----- | -------- | ---------- |
| **Scout**    | 109B | 17B   | 16  | 1000万 | 12GB     | 80GB       |
| **Maverick** | 400B | 17B   | 128 | 100万  | 48GB（多卡） | 320GB（多卡）  |

## 需求

| 组件   | Scout（Q4）   | Scout（FP16） | Maverick（Q4） |
| ---- | ----------- | ----------- | ------------ |
| GPU  | 1× RTX 4090 | 1× H100     | 4× RTX 4090  |
| 显存   | 24GB        | 80GB        | 4×24GB       |
| 内存   | 32GB        | 64GB        | 128GB        |
| 磁盘   | 50GB        | 120GB       | 250GB        |
| CUDA | 12.8+       | 12.8+       | 12.8+        |

**推荐的 Clore.ai GPU**：RTX 4090 24GB（$0.14–0.42/小时）用于 Scout——性价比最高

## 使用 Ollama 快速开始

让 Llama 4 跑起来的最快方式：

```bash
# 安装 Ollama
curl -fsSL https://ollama.com/install.sh | sh

# 运行 Scout（量化后，约 12GB 显存）
ollama run llama4-scout

# 更长上下文（会占用更多显存）
ollama run llama4-scout --ctx-size 32768
```

### 将 Ollama 作为 API 服务器

```bash
# 在后台启动服务器
ollama serve &

# 拉取模型
ollama pull llama4-scout

# 通过兼容 OpenAI 的 API 查询
curl http://localhost:11434/v1/chat/completions \\
  -H "Content-Type: application/json" \\
  -d '{
    "model": "llama4-scout",
    "messages": [{"role": "user", "content": "用 3 句话解释 MoE 架构"}]
  }'
```

## vLLM 设置（生产环境）

对于需要更高吞吐量的生产负载：

```bash
# 安装 vLLM
pip install vllm

# 在单 GPU 上部署 Scout（量化）
vllm serve meta-llama/Llama-4-Scout-17B-16E-Instruct \\
  --max-model-len 32768 \\
  --gpu-memory-utilization 0.90

# 在 2 张 GPU 上部署 Scout（更长上下文）
vllm serve meta-llama/Llama-4-Scout-17B-16E-Instruct \\
  --tensor-parallel-size 2 \\
  --max-model-len 128000 \\
  --gpu-memory-utilization 0.90

# 在 4 张 GPU 上部署 Maverick
vllm serve meta-llama/Llama-4-Maverick-17B-128E-Instruct \\
  --tensor-parallel-size 4 \\
  --max-model-len 65536
```

### 查询 vLLM 服务器

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")

response = client.chat.completions.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "编写一个 Python 函数来计算斐波那契数列"}
    ],
    temperature=0.7,
    max_tokens=1024
)
print(response.choices[0].message.content)
```

## HuggingFace Transformers

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "meta-llama/Llama-4-Scout-17B-16E-Instruct"

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    load_in_4bit=True  # 适用于 24GB GPU 的 4 位量化
)

messages = [
    {"role": "system", "content": "你是一位乐于助人的编程助手。"},
    {"role": "user", "content": "编写一个使用 FastAPI 管理待办事项列表的 REST API"}
]

input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
output = model.generate(input_ids, max_new_tokens=2048, temperature=0.7, do_sample=True)
print(tokenizer.decode(output[0][input_ids.shape[-1]:], skip_special_tokens=True))
```

## Docker 快速开始

```bash
# 使用 vLLM Docker 镜像
docker run --gpus all -p 8000:8000 \\
  -v ~/.cache/huggingface:/root/.cache/huggingface \\
  vllm/vllm-openai:latest \
  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \\
  --max-model-len 32768
```

## MoE 为何在 Clore.ai 上重要

传统稠密模型（如 Llama 3.3 70B）需要巨大的显存，因为 70B 个参数全部都会激活。Llama 4 Scout 总计有 109B 参数，但每个 token 只激活 17B——这意味着：

* **与 70B+ 稠密模型相同的质量** 显存成本只需一小部分
* **可放进单张 RTX 4090** 在量化模式下
* **1000 万 token 上下文** ——可处理整个代码库、长文档、书籍
* **租用更便宜** ——一张 RTX 4090 仅需 $0.14–0.42/小时，而不是为 70B 模型租多 GPU 设备

## 给 Clore.ai 用户的建议

* **从 Scout Q4 开始**：RTX 4090 上性价比最高——$0.14–0.42/小时，覆盖 95% 的使用场景
* **使用 `--max-model-len` 明智地**：不要把上下文设得高于所需——这会预留显存。先从 8192 开始，按需提高
* **Maverick 的张量并行**：为 Maverick 租用 4× RTX 4090 机器；使用 `--tensor-parallel-size 4`
* **需要登录 HuggingFace**: `huggingface-cli login` ——你需要先在 HF 上接受 Llama 许可证
* **Ollama 用于快速测试，vLLM 用于生产**：Ollama 设置更快；vLLM 在 API 提供服务时吞吐量更高
* **监控 GPU 内存**: `watch nvidia-smi` ——MoE 模型在长序列上可能会使显存飙升

## 故障排查

| 问题                 | 解决方案                                                    |
| ------------------ | ------------------------------------------------------- |
| `OutOfMemoryError` | 减少 `--max-model-len`，使用 Q4 量化，或升级 GPU                   |
| 模型下载失败             | 运行 `huggingface-cli login` 并在 hf.co 接受 Llama 4 许可证      |
| 生成缓慢               | 确保正在使用 GPU（`nvidia-smi`）；检查 `--gpu-memory-utilization`  |
| vLLM 启动时崩溃         | 缩短上下文长度；确保已安装 CUDA 11.8+                                |
| Ollama 显示错误的模型     | 运行 `ollama list` 进行验证； `ollama rm` + `ollama pull` 重新下载 |

## 延伸阅读

* [Meta Llama 4 博客文章](https://llama.meta.com/)
* [HuggingFace 模型卡](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E-Instruct)
* [vLLM 文档](https://docs.vllm.ai/)
* [Ollama 模型库](https://ollama.com/library/llama4-scout)


---

# 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://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/llama4.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.
