> For the complete documentation index, see [llms.txt](https://docs.roboflow.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.roboflow.com/models/ja/supported-models/paligemma2.md).

# PaliGemma 2

PaliGemma 2 は Google の視覚言語モデルです。画像とテキストプロンプトを受け取り、テキスト応答を返します。PaliGemma 2 は当社の [サーバーレス Cloud API](https://docs.roboflow.com/deployment/roboflow-cloud/serverless-api), [専用デプロイ](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments)、および [セルフホスト型 Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted).

## PaliGemma 2 API

{% stepper %}
{% step %}

### API キーを取得する

Roboflow アカウントを作成し、キーは以下で確認してください [Roboflow API 設定ページ](https://app.roboflow.com/settings/api) そしてシェルで使えるようにします:

```bash
export ROBOFLOW_API_KEY="your-key-here"
```

{% endstep %}

{% step %}

### 依存関係をインストールする

以下をインストールします [Inference SDK](https://docs.roboflow.com/deployment/self-hosted/self-hosted):

```bash
pip install -U inference-sdk supervision
```

{% endstep %}

{% step %}

### モデルを実行する

このサンプルでは、事前学習済みの `paligemma2-3b-pt-224` チェックポイントをキャプションプロンプトで呼び出します。

```python
import os
import supervision as sv
from inference_sdk import InferenceHTTPClient, InferenceConfiguration

image = sv.load_image_from_url("https://media.roboflow.com/quickstart/dog.jpeg")

client = InferenceHTTPClient(
    api_url="https://serverless.roboflow.com",
    api_key=os.environ["ROBOFLOW_API_KEY"],
).configure(InferenceConfiguration(api_key_transport="header"))
result = client.infer_lmm(
    image,
    model_id="paligemma2-3b-pt-224",
    prompt="caption en",
    max_new_tokens=64,
)
print(result["response"] )
```

{% endstep %}
{% endstepper %}

上記のコードは、モデルの応答をターミナルに出力します：

```
ここでは男性の肩に犬が見えます
```

<figure><img src="/files/5a531760a2cde54096bf7b2827ce88b1ee6b3a7f" alt=""><figcaption></figcaption></figure>

## PaliGemma 2 の推論速度

レイテンシの測定条件： [Roboflow Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) 1 台の NVIDIA L4、バッチサイズ 1、固定プロンプトから greedy decoding でちょうど 128 トークンを生成した条件で測定。レイテンシは出力長に比例するため、他の長さの見積もりには tokens/sec を使用してください。

<table data-search="false"><thead><tr><th>別名</th><th>レイテンシ、128トークン（ms）</th><th>トークン/秒</th></tr></thead><tbody><tr><td><code>paligemma2-3b-pt-224</code></td><td>3986</td><td>32</td></tr></tbody></table>

{% hint style="info" %}
設定 `api_url` をデプロイ先に合わせて設定します:

* `https://serverless.roboflow.com` サーバーレス Cloud API 用。
* `http://localhost:9001` ローカルの [Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) サーバー。
* あなたの [専用デプロイ](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments) プライベートエンドポイントの URL。
  {% endhint %}

Roboflow で独自の PaliGemma 2 チェックポイントを学習し、モデルごとの `{workspace}/{model-slug}` IDに置き換えてください（ [バージョン、トレーニング、モデル](/models/ja/versions-trainings-and-models.md)）。詳細は [推論ドキュメント](https://docs.roboflow.com/deployment/self-hosted/self-hosted) で、追加のプロンプト形式と対応チェックポイントを確認してください。

## PaliGemma 1（旧版）

元の PaliGemma リリースは、今でも [`inference`](https://docs.roboflow.com/deployment/self-hosted/self-hosted) パッケージを自前のハードウェア上で使用できます。新規プロジェクトでは上記の PaliGemma 2 を使用してください。このセクションは既存の統合向けに残しています。

パッケージをインストールします：

```bash
pip install "inference[transformers]"
```

使用するには `inference-gpu[transformers]` GPU マシン上で。

### 視覚的質問応答

```python
from PIL import Image

from inference.models.paligemma.paligemma import PaliGemma

model = PaliGemma("paligemma-3b-mix-224", api_key="YOUR_API_KEY")

image = Image.open("image.jpeg")
result = model.predict(image, "How many dogs are in this image?")

print(result)
```

### 物体検出

PaliGemma は検出結果を次の形式で出力します： `<loc####>` トークンとして出力するため、可視化する前にレスポンスを解析する必要があります。次のようにプロンプトします： `detect <class>; <class>` そしてトークンをボックスにデコードします：

```python
import re
from typing import List, Optional, Tuple

import numpy as np
import supervision as sv

_DETECT_RE = re.compile(r"(.*?)" + r"<loc(\d{4})>" * 4 + r"\s*([^;<>]+)? ?(?:; )?")


def from_pali_gemma(
    response: str,
    resolution_wh: Tuple[int, int],
    class_list: Optional[List[str]] = None,
) -> sv.Detections:
    width, height = resolution_wh
    xyxy_list, class_name_list = [], []

    while response:
        match = _DETECT_RE.match(response)
        if not match:
            break

        groups = list(match.groups())
        before = groups.pop(0)
        name = groups.pop()
        y1, x1, y2, x2 = [int(value) / 1024 for value in groups[:4]]
        y1, x1, y2, x2 = map(round, (y1 * height, x1 * width, y2 * height, x2 * width))

        content = match.group()
        if before:
            response = response[len(before):]
            content = content[len(before):]

        xyxy_list.append([x1, y1, x2, y2])
        class_name_list.append(name.strip())
        response = response[len(content):]

    class_name = np.array(class_name_list)
    class_id = (
        np.array([class_list.index(name) for name in class_name])
        if class_list is not None
        else None
    )
    return sv.Detections(
        xyxy=np.array(xyxy_list),
        class_id=class_id,
        data={"class_name": class_name},
    )


classes = ["person", "car", "backpack"]
response = model.predict(image, "detect person; car; backpack")[0]
detections = from_pali_gemma(response, resolution_wh=image.size, class_list=classes)
```

結果として得られた `sv.Detections` を [supervision](https://supervision.roboflow.com/) アノテーターに渡して बॉックスを描画します。
