> 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 は当社の [サーバーレスホスト型 API](https://docs.roboflow.com/deployment/roboflow-cloud/serverless-api), [専用デプロイ](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments)、および [セルフホスト型推論](https://docs.roboflow.com/deployment/self-hosted/self-hosted).

## コードサンプル

{% 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

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"],
)
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>

## 推論速度

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

<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` Serverless Hosted 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}` の [Versions, Trainings, and Models](/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, "この画像には犬が何匹いますか？")

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/) 注釈器に渡してボックスを描画します。
