> 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/shi-jue-mo-xing/llama-vision.md).

# Llama 3.2 Vision

在 Clore.ai 上运行 Meta 的 Llama 3.2 Vision 进行图像理解

在 CLORE.AI GPU 上运行 Meta 的多模态 Llama 3.2 Vision 模型进行图像理解。

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

## 为什么选择 Llama 3.2 Vision？

* **多模态** - 同时理解文本和图像
* **多种尺寸** - 11B 和 90B 参数版本
* **多用途** - OCR、视觉问答、图像描述、文档分析
* **开源权重** - Meta 完全开源
* **Llama 生态系统** - 兼容 Ollama、vLLM、transformers

## 模型变体

| 模型                            | 参数  | 显存（FP16） | 上下文  | 最适合        |
| ----------------------------- | --- | -------- | ---- | ---------- |
| Llama-3.2-11B-Vision          | 11B | 24GB     | 128K | 通用用途，单 GPU |
| Llama-3.2-90B-Vision          | 90B | 180GB    | 128K | 最高质量       |
| Llama-3.2-11B-Vision-Instruct | 11B | 24GB     | 128K | 聊天/助手      |
| Llama-3.2-90B-Vision-Instruct | 90B | 180GB    | 128K | 生产环境       |

## 在 CLORE.AI 上快速部署

**Docker 镜像：**

```
vllm/vllm-openai:latest
```

**端口：**

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

**命令：**

```bash
python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Llama-3.2-11B-Vision-Instruct \\
    --host 0.0.0.0 \\
    --port 8000 \\
    --max-model-len 8192
```

## 访问你的服务

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

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

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

## 硬件要求

{% hint style="warning" %}
**Clore.ai 市场上未列出多 GPU 的 80GB 级机型。** 目前列出的最大配置是 4× RTX PRO 6000 Blackwell（每张 96GB，共 380GB）以及 8–11× RTX 5090（每张 32GB）。A100 / H200 / B200 容量可按 [裸机](https://clore.ai/bare-metal) 需求提供。部署前请查看 [GPU 价格与可用性](/guides/guides_v2-zh/ru-men-zhi-nan/pricing.md) 。
{% endhint %}

| 模型      | 最低 GPU        | 推荐           | 最佳        |
| ------- | ------------- | ------------ | --------- |
| 11B 视觉版 | RTX 4090 24GB | A100 40GB    | A100 80GB |
| 90B 视觉版 | 4x A100 40GB  | 4x A100 80GB | 8x H100   |

## 安装

### 使用 Ollama（最简单）

```bash
# 拉取模型
ollama pull llama3.2-vision:11b

# 交互式运行
ollama run llama3.2-vision:11b
```

### 使用 vLLM

```bash
pip install vllm

python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Llama-3.2-11B-Vision-Instruct \\
    --host 0.0.0.0 \\
    --port 8000
```

### 使用 Transformers

```python
import torch
from transformers import MllamaForConditionalGeneration, AutoProcessor

model_id = "meta-llama/Llama-3.2-11B-Vision-Instruct"

model = MllamaForConditionalGeneration.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto"
)
processor = AutoProcessor.from_pretrained(model_id)
```

## 基础用法

### 图像理解

```python
import torch
from transformers import MllamaForConditionalGeneration, AutoProcessor
from PIL import Image
import requests

model_id = "meta-llama/Llama-3.2-11B-Vision-Instruct"

model = MllamaForConditionalGeneration.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto"
)
processor = AutoProcessor.from_pretrained(model_id)

# 加载图像
url = "https://example.com/image.jpg"
image = Image.open(requests.get(url, stream=True).raw)

# 创建提示
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "这张图片里有什么？请详细描述。"}
        ]
    }
]

input_text = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(image, input_text, return_tensors="pt").to(model.device)

output = model.generate(**inputs, max_new_tokens=500)
print(processor.decode(output[0], skip_special_tokens=True))
```

### 使用 Ollama

```bash
# 描述图片
ollama run llama3.2-vision:11b "描述这张图片：/path/to/image.jpg"

# 或使用 API
curl http://localhost:11434/api/generate -d '{
  "model": "llama3.2-vision:11b",
  "prompt": "这张图片里有什么？",
  "images": ["base64_encoded_image_here"]
}'
```

### 使用 vLLM API

```python
from openai import OpenAI
import base64

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="not-needed"
)

# 将图片编码为 base64
with open("image.jpg", "rb") as f:
    image_base64 = base64.b64encode(f.read()).decode()

response = client.chat.completions.create(
    model="meta-llama/Llama-3.2-11B-Vision-Instruct",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "这张图片里有什么？"},
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}
                }
            ]
        }
    ],
    max_tokens=500
)

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

## 应用场景

### OCR / 文本提取

```python
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "从这张图片中提取所有文本。请以 Markdown 格式输出。"}
        ]
    }
]
```

### 文档分析

```python
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "分析这份文档。总结要点。"}
        ]
    }
]
```

### 视觉问答

```python
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "这张照片里有多少人？他们在做什么？"}
        ]
    }
]
```

### 图像描述

```python
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "为这张图片写一段适合社交媒体的详细说明。"}
        ]
    }
]
```

### 截图代码

```python
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "将此 UI 截图转换为 HTML/CSS 代码。"}
        ]
    }
]
```

## 多张图片

```python
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "image"},
            {"type": "text", "text": "比较这两张图片。有什么不同？"}
        ]
    }
]

# 使用多张图片处理
inputs = processor(
    images=[image1, image2],
    text=input_text,
    return_tensors="pt"
).to(model.device)
```

## 批量处理

```python
import os
from PIL import Image

def process_images(image_paths, prompt):
    results = []

    for path in image_paths:
        image = Image.open(path)

        messages = [
            {
                "role": "user",
                "content": [
                    {"type": "image"},
                    {"type": "text", "text": prompt}
                ]
            }
        ]

        input_text = processor.apply_chat_template(messages, add_generation_prompt=True)
        inputs = processor(image, input_text, return_tensors="pt").to(model.device)

        output = model.generate(**inputs, max_new_tokens=300)
        result = processor.decode(output[0], skip_special_tokens=True)

        results.append({"file": path, "description": result})

        # 在图片之间清除缓存
        torch.cuda.empty_cache()

    return results

# 处理文件夹
images = [f"./images/{f}" for f in os.listdir("./images") if f.endswith(('.jpg', '.png'))]
results = process_images(images, "用一段话描述这张图片。")
```

## Gradio 界面

```python
import gradio as gr
import torch
from transformers import MllamaForConditionalGeneration, AutoProcessor
from PIL import Image

model_id = "meta-llama/Llama-3.2-11B-Vision-Instruct"
model = MllamaForConditionalGeneration.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto"
)
processor = AutoProcessor.from_pretrained(model_id)

def analyze_image(image, question):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "image"},
                {"type": "text", "text": question}
            ]
        }
    ]

    input_text = processor.apply_chat_template(messages, add_generation_prompt=True)
    inputs = processor(image, input_text, return_tensors="pt").to(model.device)

    output = model.generate(**inputs, max_new_tokens=500)
    return processor.decode(output[0], skip_special_tokens=True)

demo = gr.Interface(
    fn=analyze_image,
    inputs=[
        gr.Image(type="pil", label="上传图片"),
        gr.Textbox(label="问题", placeholder="这张图片里有什么？")
    ],
    outputs=gr.Textbox(label="响应"),
    title="Llama 3.2 Vision - 图像分析",
    description="上传图片并就其提问。运行于 CLORE.AI。"
)

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

## 性能

| 任务        | 模型  | GPU       | 时间     |
| --------- | --- | --------- | ------ |
| 单张图片描述    | 11B | RTX 4090  | \~3s   |
| 单张图片描述    | 11B | A100 40GB | \~2s   |
| OCR（1 页）  | 11B | RTX 4090  | 约 5 秒  |
| 文档分析      | 11B | A100 40GB | \~8s   |
| 批量（10张图片） | 11B | A100 40GB | \~25 秒 |

## 量化

### 使用 bitsandbytes 的 4 位量化

```python
from transformers import BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16
)

model = MllamaForConditionalGeneration.from_pretrained(
    model_id,
    quantization_config=quantization_config,
    device_map="auto"
)
```

### Ollama 的 GGUF 格式

```bash
# 4 位量化（适合 8GB VRAM）
ollama pull llama3.2-vision:11b-q4_K_M

# 8 位量化
ollama pull llama3.2-vision:11b-q8_0
```

## 成本估算

CLORE.AI 市场的典型费率：

| GPU           | 小时费率    | 最适合         |
| ------------- | ------- | ----------- |
| RTX 4090 24GB | \~$0.10 | 11B 模型      |
| A100 40GB     | \~$0.17 | 具有长上下文的 11B |
| A100 80GB     | \~$0.25 | 11B 最优      |
| 4x A100 80GB  | \~$1.00 | 90B 模型      |

*价格会有所不同。请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

**节省费用：**

* 使用 **竞价** 批处理顺序
* 使用 **CLORE** 代币支付
* 开发时使用量化模型（4 位）

## 故障排查

### 内存不足

```python
# 使用 4-bit 量化
model = MllamaForConditionalGeneration.from_pretrained(
    model_id,
    load_in_4bit=True,
    device_map="auto"
)

# 或减少 max_new_tokens
output = model.generate(**inputs, max_new_tokens=256)
```

### 生成缓慢

* 确保正在使用 GPU（检查 `nvidia-smi`)
* 使用 bfloat16 而不是 float32
* 在处理前降低图片分辨率
* 使用 vLLM 以获得更高吞吐量

### 图片未加载

```python
from PIL import Image
import requests
from io import BytesIO

# 从 URL
response = requests.get(url)
image = Image.open(BytesIO(response.content)).convert("RGB")

# 从文件
image = Image.open("path/to/image.jpg").convert("RGB")

# 如果太大则调整大小
max_size = 1024
if max(image.size) > max_size:
    image.thumbnail((max_size, max_size))
```

### 需要 HuggingFace 令牌

```bash
# 为受限模型设置令牌
export HUGGING_FACE_HUB_TOKEN=hf_xxxxx

# 或登录
huggingface-cli login
```

## Llama Vision 与其他模型对比

| 功能     | Llama 3.2 Vision | LLaVA 1.6  | GPT-4V |
| ------ | ---------------- | ---------- | ------ |
| 参数     | 11B / 90B        | 7B / 34B   | 未知     |
| 开源     | 是                | 是          | 否      |
| OCR 质量 | 优秀               | 好          | 优秀     |
| 上下文    | 128K             | 32K        | 128K   |
| 多图像    | 是                | 有限         | 是      |
| 许可证    | Llama 3.2        | Apache 2.0 | 专有     |

**在以下情况使用 Llama 3.2 Vision：**

* 需要开源多模态
* OCR 和文档分析
* 与 Llama 生态系统集成
* 长上下文理解

## 下一步

* [LLaVA](/guides/guides_v2-zh/shi-jue-mo-xing/llava-vision-language.md) - 替代视觉模型
* [Florence-2](/guides/guides_v2-zh/shi-jue-mo-xing/florence2.md) - 微软的视觉模型
* [Ollama](/guides/guides_v2-zh/yu-yan-mo-xing/ollama.md) - 易于部署
* [vLLM](/guides/guides_v2-zh/yu-yan-mo-xing/vllm.md) - 生产环境服务


---

# 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/shi-jue-mo-xing/llama-vision.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.
