> 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

Google の PaliGemma 2 視覚言語モデルを Serverless Cloud API 経由で使用します

PaliGemma 2 は Google の vision-language モデルです。画像とテキストプロンプトを受け取り、テキスト応答を返します。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="https://1194881119-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fcmo9mhfIjYrvFFy1U7dk%2Fuploads%2Fgit-blob-347b3a4f648046dbc28be92bf99d3bd420e351bd%2Fpaligemma2-caption.webp?alt=media" alt=""><figcaption></figcaption></figure>

## PaliGemma 2 の推論速度

で測定したレイテンシ [Roboflow Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) を使い、1x NVIDIA L4、バッチサイズ1、固定プロンプトからグリーディーデコーディングでちょうど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` サーバーレス 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 で呼び出すことができます（ [バージョン、トレーニング、モデル](https://docs.roboflow.com/models/ja/versions-trainings-and-models.md)を参照）。 [追加のプロンプト形式と対応チェックポイントについては、](https://docs.roboflow.com/deployment/self-hosted/self-hosted) Inference のドキュメント

## カスタム重みをアップロード

Roboflow 外で学習した PaliGemma 2 モデルを実行するには、その重みを [Roboflow CLI](https://docs.roboflow.com/reference/platform/cli/install-and-set-up-the-cli):

```bash
roboflow upload_model -p my-project -v 1 -t paligemma2-3b-pt-224 -m ./paligemma2-finetuned
```

設定する `-t` を学習時の解像度に合わせます（例: `paligemma2-3b-pt-448`）。 `-peft` を LoRA 重みに追加します。 [カスタム重みをアップロード](https://docs.roboflow.com/models/ja/moderunomi/upload-custom-weights.md) Python SDK と学習版の要件については、

## 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####>` トークンとして出力し、JSON ではないため、可視化する前に応答を解析する必要があります。 `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/) アノテーターに渡して、ボックスを描画します。
