# GLM-4.7-Flash

> GLM-4.7-Flash 是一个 **300 亿参数的专家混合（Mixture-of-Experts）模型** 由智谱AI开发，每个标记仅激活 30 亿参数。在代码和推理任务上表现出色，在 SWE-bench 上达到 59.2%，而进行 FP16 推理仅需约 10-12GB 显存。根据 **MIT 许可证**发布，是希望以单卡可承受成本获得前沿模型质量的开发者的理想选择。

## 概览

* **模型规模**: 总计 30B / 每次激活 3B 参数（MoE）
* **许可证**: MIT（完全商业可用）
* **上下文**: 128K 令牌
* **性能**: 59.2% SWE-bench，75.4% HumanEval
* **显存**: 约 10-12GB FP16，约 6GB INT8
* **速度**: 在 RTX 4090 上约 45-60 标记/秒

## 为什么选择 GLM-4.7-Flash？

**高效性能**: GLM-4.7-Flash 的表现超出其级别。尽管每次仅使用 3B 激活参数，它在代码基准上优于许多 70B+ 的密集模型。MoE 架构以 7B 模型推理成本提供接近 30B 的模型质量。

**单卡友好**: 与需要多卡配置的大型模型不同，GLM-4.7-Flash 可在单张 RTX 4090 或 A100 40GB 上轻松运行。非常适合开发、微调和具有成本效益的生产部署。

**代码专项**: GLM-4.7-Flash 在软件工程任务方面表现优异（SWE-bench 59.2%）——代码生成、调试、重构和技术文档。它理解 20+ 编程语言并具备深层上下文感知。

**MIT 许可**: 无使用限制。可商业部署、微调或修改，无需担心许可问题。完整权重和训练配方可自由获取。

## GPU 建议

| GPU          | 显存   | 性能         | 每日成本\*  |
| ------------ | ---- | ---------- | ------- |
| **RTX 4090** | 24GB | \~50 标记/秒  | \~$2.10 |
| **RTX 3090** | 24GB | \~35 标记/秒  | \~$1.10 |
| A100 40GB    | 40GB | \~80 标记/秒  | \~$3.50 |
| A100 80GB    | 80GB | \~90 标记/秒  | \~$4.00 |
| H100         | 80GB | \~120 标记/秒 | \~$6.00 |

**最佳性价比**: RTX 4090 在性能与成本之间为 GLM-4.7-Flash 提供了最佳平衡。

\*估算自 Clore.ai 市场价格

## 使用 vLLM 部署

### 安装 vLLM

```bash
pip install vllm>=0.6.0
# 或 最新版本
pip install git+https://github.com/vllm-project/vllm.git
```

### 单卡设置

```bash
vllm serve THUDM/glm-4-flash \
  --model THUDM/glm-4-flash \
  --tensor-parallel-size 1 \
  --dtype float16 \
  --max-model-len 32768 \
  --served-model-name glm-4.7-flash \
  --trust-remote-code
```

### 查询服务器

```python
from openai import OpenAI

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

response = client.chat.completions.create(
    model="glm-4.7-flash",
    messages=[
        {"role": "system", "content": "你是一名资深 Python 开发者。"},
        {"role": "user", "content": "编写一个使用异步 SQLAlchemy 和 JWT 认证的 FastAPI 应用"}
    ],
    max_tokens=2048,
    temperature=0.7
)

print(response.choices[0].message.content)
```

## 使用 SGLang 部署

SGLang 往往为 MoE 模型提供更好的吞吐量：

```bash
pip install "sglang[all]>=0.3.0"

# 启动服务器
python -m sglang.launch_server \
  --model-path THUDM/glm-4-flash \
  --port 30000 \
  --host 0.0.0.0 \
  --dtype float16 \
  --tp-size 1 \
  --context-length 32768
```

## 使用 Ollama 部署

本地开发的简单设置：

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

# 拉取模型（将下载约 18GB）
ollama pull glm4:7b-chat

# 交互运行
ollama run glm4:7b-chat

# API 模式
ollama serve
```

然后通过 REST API 查询：

```python
import requests

response = requests.post('http://localhost:11434/api/generate',
    json={
        'model': 'glm4:7b-chat',
        'prompt': '解释 GLM-4.7-Flash 中的 MoE 架构',
        'stream': False
    }
)

print(response.json()['response'])
```

## Docker 模板

```dockerfile
FROM nvidia/cuda:12.1-devel-ubuntu22.04

# 安装 Python 3.10
RUN apt-get update && apt-get install -y python3.10 python3-pip curl

# 安装 vLLM
RUN pip install vllm>=0.6.0 transformers

# 预下载模型（可选）
# RUN python3 -c "from transformers import AutoModel; AutoModel.from_pretrained('THUDM/glm-4-flash', trust_remote_code=True)"

EXPOSE 8000

CMD ["vllm", "serve", "THUDM/glm-4-flash", \
     "--host", "0.0.0.0", \
     "--port", "8000", \
     "--tensor-parallel-size", "1", \
     "--dtype", "float16", \
     "--trust-remote-code"]
```

构建并运行：

```bash
docker build -t glm-4.7-flash .
docker run --gpus all -p 8000:8000 glm-4.7-flash
```

## 代码生成示例

GLM-4.7-Flash 擅长复杂代码生成：

```python
from openai import OpenAI

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

response = client.chat.completions.create(
    model="glm-4.7-flash",
    messages=[
        {"role": "user", 
         "content": """为速率限制器创建一个 Python 类，要求：
- 令牌桶算法
- 支持 async/await  
- Redis 后端
- 用于函数速率限制的装饰器
- 适当的错误处理"""}
    ],
    max_tokens=2048,
    temperature=0.3
)

print(response.choices[0].message.content)
```

## Clore.ai 用户提示

* **内存优化**: 使用 `--dtype float16` 以减少显存使用。对于 16GB GPU，请添加 `--max-model-len 16384` 以限制上下文长度。
* **批处理**: 增加 `--max-num-seqs` 以在服务多个请求时获得更高吞吐量。
* **量化**: 对于 RTX 3060/4060（12GB），使用 AWQ 或 GPTQ 量化版本可将显存降至约 6GB。
* **抢占**: GLM-4.7-Flash 能够优雅地处理中断——适合可抢占的 Clore.ai 实例。
* **上下文长度**: 默认 128K 上下文可能过大。设置 `--max-model-len 32768` 适用于大多数应用。

## 故障排查

| 问题       | 解决方案                                                |
| -------- | --------------------------------------------------- |
| `内存不足错误` | 减少 `--max-model-len` 或使用 `--dtype float16`          |
| 模型加载缓慢   | 预缓存，使用 `huggingface-cli download THUDM/glm-4-flash` |
| 导入错误     | 更新 transformers： `pip install transformers>=4.40.0` |
| 性能差      | 启用 Flash Attention： `pip install flash-attn`        |
| 连接被拒绝    | 检查防火墙： `ufw allow 8000`                             |

## 替代模型

如果 GLM-4.7-Flash 不适合你的需求：

* **Qwen2.5-Coder-7B**: 更好的纯代码性能，体积更小
* **CodeQwen1.5-7B**: 中文+英文的代码专项模型
* **GLM-4-9B**: 更大的同系模型，推理与推理能力更强
* **DeepSeek-V3**: 671B 的 MoE，用于终极性能（多 GPU）

## 资源

* [Hugging Face 上的 GLM-4-Flash](https://huggingface.co/THUDM/glm-4-flash)
* [GLM-4 技术报告](https://arxiv.org/abs/2406.12793)
* [vLLM 文档](https://docs.vllm.ai/)
* [SGLang GitHub](https://github.com/sgl-project/sglang)
* [智谱 AI 平台](https://open.bigmodel.cn/)


---

# 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/glm-47-flash.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.
