> 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/ko/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="캡션 en",
    max_new_tokens=64,
)
print(result["response"])
```

{% endstep %}
{% endstepper %}

위의 코드는 모델 응답을 터미널에 출력합니다:

```
남자의 어깨 위에 개 한 마리가 보입니다
```

<figure><img src="/files/293c56dc9fa863eacb60e83ef70de117578a1cd7" alt=""><figcaption></figcaption></figure>

## 추론 속도

다음으로 측정한 지연 시간 [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` Serverless Hosted API용입니다.
* `http://localhost:9001` 로컬 [추론](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/ko/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####>` 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, "사람; 자동차; 백팩 탐지")[0]
detections = from_pali_gemma(response, resolution_wh=image.size, class_list=classes)
```

결과로 생성된 `sv.Detections` 을 [supervision](https://supervision.roboflow.com/) annotators에 전달해 박스를 그리세요.
