> 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/gemma2.md).

# Gemma 2

在 Clore.ai GPU 上高效运行 Google 的 Gemma 2 模型

{% hint style="info" %}
**有新版本可用！** Google 发布了 [**Gemma 3**](/guides/guides_v2-zh/yu-yan-mo-xing/gemma3.md) 于 2025 年 3 月发布——27B 模型超越 Llama 3.1 405B，并增加原生多模态支持。建议升级。
{% endhint %}

运行 Google 的 Gemma 2 模型以实现高效推理。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 在 CLORE.AI 上租用

1. 访问 [CLORE.AI 市场](https://clore.ai/marketplace)
2. 按 GPU 类型、VRAM 和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价）
4. 配置你的订单：
   * 选择 Docker 镜像
   * 设置端口（SSH 用 TCP，Web UI 用 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问你的服务器

* 在以下位置查找连接信息 **我的订单**
* Web 界面：使用 HTTP 端口 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 Gemma 2？

Google 的 Gemma 2 提供：

* 参数量从 2B 到 27B 的模型
* 更高参数效率的优异性能
* 出色的指令遵循能力
* 高效架构

## 模型变体

| 模型          | 参数  | 显存   | 上下文 |
| ----------- | --- | ---- | --- |
| Gemma-2-2B  | 2B  | 3GB  | 8K  |
| Gemma-2-9B  | 9B  | 12GB | 8K  |
| Gemma-2-27B | 27B | 32GB | 8K  |

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime
```

**端口：**

```
22/tcp
8000/http
```

**命令：**

```bash
pip install vllm && \\
vllm serve google/gemma-2-9b-it --port 8000
```

## 访问你的服务

部署后，找到你的 `http_pub` URL 在 **我的订单**:

1. 前往 **我的订单** 页面
2. 点击你的订单
3. 找到 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 替代 `localhost` 在下面的示例中。

## 使用 Ollama

```bash

# 运行 Gemma 2
ollama run gemma2

# 特定尺寸
ollama run gemma2:2b
ollama run gemma2:9b
ollama run gemma2:27b
```

## 安装

```bash
pip install transformers accelerate torch
```

## 基础用法

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

model_id = "google/gemma-2-9b-it"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto"
)

messages = [
    {"role": "user", "content": "解释神经网络如何学习。"}
]

inputs = tokenizer.apply_chat_template(
    messages,
    return_tensors="pt",
    add_generation_prompt=True
).to("cuda")

outputs = model.generate(
    inputs,
    max_new_tokens=512,
    temperature=0.7,
    do_sample=True
)

response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
打印(response)
```

## Gemma 2 2B（轻量版）

适用于边缘/移动端部署：

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

model_id = "google/gemma-2-2b-it"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

# 简单任务的快速推理
messages = [{"role": "user", "content": "用一句话总结：AI 正在改变各行各业。"}]
```

## Gemma 2 27B（最佳质量）

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

model_id = "google/gemma-2-27b-it"

# 使用 4 位量化以适配 24GB 显存
quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16
)

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    quantization_config=quantization_config,
    device_map="auto"
)
```

## vLLM 服务器

```bash
vllm serve google/gemma-2-9b-it \
    --port 8000 \\
    --dtype bfloat16 \\
    --max-model-len 8192
```

### OpenAI 兼容 API

```python
from openai import OpenAI

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

response = client.chat.completions.create(
    model="google/gemma-2-9b-it",
    messages=[
        {"role": "user", "content": "写一首关于编程的俳句"}
    ],
    temperature=0.8
)

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

## 流式输出

```python
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="google/gemma-2-9b-it",
    messages=[{"role": "user", "content": "给我讲个短故事"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

## Gradio 界面

```python
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "google/gemma-2-9b-it"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto"
)

def chat(message, history, temperature):
    messages = []
    for h in history:
        messages.append({"role": "user", "content": h[0]})
        messages.append({"role": "assistant", "content": h[1]})
    messages.append({"role": "user", "content": message})

    inputs = tokenizer.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True).to("cuda")
    outputs = model.generate(inputs, max_new_tokens=512, temperature=temperature, do_sample=True)

    return tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)

demo = gr.ChatInterface(
    fn=chat,
    additional_inputs=[gr.Slider(0.1, 1.5, value=0.7, label="温度")],
    title="Gemma 2 聊天"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## 批量处理

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

model_id = "google/gemma-2-9b-it"
tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side="left")
tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto"
)

prompts = [
    "用一句话解释重力。",
    "什么是光合作用？",
    "定义机器学习。",
    "光速是多少？"
]

messages_batch = [[{"role": "user", "content": p}] for p in prompts]

inputs = tokenizer.apply_chat_template(
    messages_batch,
    return_tensors="pt",
    padding=True,
    add_generation_prompt=True
).to("cuda")

outputs = model.generate(inputs, max_new_tokens=128, pad_token_id=tokenizer.pad_token_id)

for i, output in enumerate(outputs):
    response = tokenizer.decode(output, skip_special_tokens=True)
    print(f"问题：{prompts[i]}")
    print(f"回答：{response.split('<start_of_turn>model')[-1].strip()}\n")
```

## 性能

| 模型               | GPU      | 每秒 Token 数 |
| ---------------- | -------- | ---------- |
| Gemma-2-2B       | RTX 3060 | \~100      |
| Gemma-2-9B       | RTX 3090 | \~60       |
| Gemma-2-9B       | RTX 4090 | \~85       |
| Gemma-2-27B      | A100     | \~45       |
| Gemma-2-27B（4 位） | RTX 4090 | \~30       |

## 对比

| 模型           | MMLU  | 质量 | 速度 |
| ------------ | ----- | -- | -- |
| Gemma-2-9B   | 71.3% | 很高 | 快  |
| Llama-3.1-8B | 69.4% | 好  | 快  |
| Mistral-7B   | 62.5% | 好  | 快  |

## 故障排查

{% hint style="danger" %}
**CUDA 内存不足**
{% endhint %}

针对 27B - 使用 BitsAndBytesConfig 进行 4 位量化 - 减少 \`max\_new\_tokens\` - 清理 GPU 缓存：\`torch.cuda.empty\_cache()\`

### 生成缓慢

* 使用 vLLM 进行生产部署
* 启用 Flash Attention
* 尝试 9B 模型以获得更快的推理

### 输出质量问题

* 使用指令微调版本（`-it` 后缀）
* 调整 temperature（建议 0.7-0.9）
* 添加系统提示以提供上下文

### 分词器警告

* 将 transformers 更新到最新版本
* 使用 `padding_side="left"` 用于批量推理

## 成本估算

CLORE.AI 市场常见费率（截至 2024 年）：

| GPU       | 小时费率    | 日费率     | 4 小时会话  |
| --------- | ------- | ------- | ------- |
| RTX 3060  | \~$0.03 | \~$0.70 | \~$0.12 |
| RTX 3090  | \~$0.06 | \~$1.50 | \~$0.25 |
| RTX 4090  | \~$0.10 | \~$2.30 | \~$0.40 |
| A100 40GB | \~$0.17 | \~$4.00 | \~$0.70 |
| A100 80GB | \~$0.25 | \~$6.00 | \~$1.00 |

*价格因提供商和需求而异。请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

**节省费用：**

* 使用 **竞价** 可中断工作市场——约三分之一的服务器将现货价格定得低于按需价格（中位数约优惠 13%），其余则与按需价格持平
* 使用 **CLORE** 代币支付
* 比较不同提供商的价格

## 下一步

* Llama 3.2 - Meta 的模型
* Qwen2.5 - 阿里巴巴的模型
* vLLM 推理 - 生产环境服务


---

# 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/gemma2.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.
