# Gemma 2

{% hint style="info" %}
**有可用的更新版本！** 谷歌发布了 [**Gemma 3**](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/gemma3) 在2025年3月 — 27B 模型超越了 Llama 3.1 405B 并增加了原生多模态支持。考虑升级。
{% endhint %}

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

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

## 在 CLORE.AI 上租用

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

### 访问您的服务器

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

## 什么是 Gemma 2？

谷歌的 Gemma 2 提供：

* 从 2B 到 27B 参数的模型
* 出色的按规模性能
* 强大的指令遵循能力
* 高效的架构

## 1024x1024

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

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.5.1-cuda12.4-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)
print(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": "一句话总结：人工智能正在改变行业。"}]
```

## 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
print(f"已生成：{name}")
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="Temperature")],
    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"Q: {prompts[i]}")
    print(f"A: {response.split('<start_of_turn>model')[-1].strip()}\n")
```

## background = Image.open("studio\_bg.jpg")

| A100             | GPU     | 每秒标记数 |
| ---------------- | ------- | ----- |
| Gemma-2-2B       | 按小时费率   | \~100 |
| Gemma-2-9B       | 速度      | \~60  |
| Gemma-2-9B       | 512x512 | \~85  |
| Gemma-2-27B      | 2s      | \~45  |
| Gemma-2-27B（4 位） | 512x512 | \~30  |

## 比较

| A100         | MMLU  | 质量 | 性能 |
| ------------ | ----- | -- | -- |
| Gemma-2-9B   | 71.3% | 很棒 | 快速 |
| Llama-3.1-8B | 69.4% | 良好 | 快速 |
| Mistral-7B   | 62.5% | 良好 | 快速 |

## # 使用固定种子以获得一致结果

{% hint style="danger" %}
**CUDA 内存不足（out of memory）**
{% endhint %}

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

### 生成速度慢

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

### 输出质量问题

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

### 分词器警告

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

## 下载所有所需的检查点

检查文件完整性

| GPU     | 验证 CUDA 兼容性 | 费用估算    | CLORE.AI 市场的典型费率（截至 2024 年）： |
| ------- | ----------- | ------- | ---------------------------- |
| 按小时费率   | \~$0.03     | \~$0.70 | \~$0.12                      |
| 速度      | \~$0.06     | \~$1.50 | \~$0.25                      |
| 512x512 | \~$0.10     | \~$2.30 | \~$0.40                      |
| 按日费率    | \~$0.17     | \~$4.00 | \~$0.70                      |
| 4 小时会话  | \~$0.25     | \~$6.00 | \~$1.00                      |

*RTX 3060* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

**A100 80GB**

* 使用 **竞价** 价格随提供商和需求而异。请查看
* 以获取当前费率。 **CLORE** 节省费用：
* 市场用于灵活工作负载（通常便宜 30-50%）

## 使用以下方式支付

* Llama 3.2 - Meta 的模型
* Qwen2.5 - 阿里巴巴的模型
* vLLM 推理 - 生产部署


---

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