# Llama 4（Scout 与 Maverick）

Meta 的 Llama 4，于 2025 年 4 月发布，标志着向 **专家混合（Mixture of Experts，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 社区许可（对大多数商业用途免费）

## 1024x1024

| A100         | 总参数  | 激活参数 | 专家数 | 上下文 | 最小显存（Q4） | 最小显存（FP16） |
| ------------ | ---- | ---- | --- | --- | -------- | ---------- |
| **Scout**    | 109B | 17B  | 16  | 10M | 12GB     | 80GB       |
| **Maverick** | 400B | 17B  | 128 | 1M  | 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 | 11.8+       | 12.0+       | 12.0+        |

**推荐的 Clore.ai GPU**：RTX 4090 24GB（约 $0.5–2/天）用于 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": "用三句话解释 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-bit 量化
)

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 的上下文** — 可处理整个代码库、长文档、书籍
* **租用成本更低** — $0.5–2/天，而不是 70B 模型的 $6–12/天

## 给 Clore.ai 用户的提示

* **从 Scout Q4 开始**：在 RTX 4090 上性价比最高 — $0.5–2/天，覆盖 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: 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://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/llama4.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.
