# GraniteDocling

[GraniteDocling](https://huggingface.co/papers/2408.09869)は、文書変換用のビジョン言語モデルです。ページ画像を入力すると、[DocLang](https://doclang.ai/)（`<doclang>`）を生成します。これは、読み取り順に並べられたレイアウト要素とそのバウンディングボックス、およびそれらが含むテキスト、表、数式、コードです。DocLangはマークアップであり、[Docling](https://github.com/docling-project/docling)（`docling-core`）は予測結果を解析し、Markdown、HTML、JSONなどの形式にエクスポート可能な文書に変換します。

ページは、アスペクト比に最もよく合うグリッド上に配置された512x512ピクセルのタイルに分割され、タイルが複数ある場合は、ページ全体のサムネイルも含まれます。ビジョンエンコーダーはすべてのタイルを埋め込み、ピクセルシャッフルコネクタはビジョンパッチをイメージトークンにマッピングします。ビジョンエンコーダーの中間状態も投影され、最初のデコーダー層の後にイメージトークンに追加されます。その後、DenseなGraniteスタイルのテキストデコーダーがDocLangを生成します。

GraniteDoclingは2つのモデルとしてリリースされています。500Mモデルは1タイルあたり64個の画像トークンを使用し、密集したページについては256個に切り替えることができます。この切り替えはページごとにルーターが選択します。2Bモデルはピクセルシャッフル比2を使用しており、これは1タイルあたり256個の画像トークンに相当し、500Mモデルのファインパスと同じ密度です。

[Doclingプロジェクト](https://huggingface.co/docling-project)がGraniteDoclingを作成しました。両方のモデルは[IBM Granite](https://huggingface.co/ibm-granite)組織によって公開されています。

GraniteDoclingは、[Idefics3](./idefics3)経由で読み込みを維持する[granite-docling-258M](https://huggingface.co/ibm-granite/granite-docling-258M)とは異なるアーキテクチャです。

> [!TIP]
> このモデルは[Doclingチーム](https://huggingface.co/docling-project)によって提供されました。
>
> GraniteDoclingを異なるドキュメント変換タスクに適用する方法のより多くの例については、右側のサイドバーにあるGraniteDoclingモデルをクリックしてください。

## 使用のコツ

- チャットテンプレートを通じてモデルにプロンプトを渡します。`<doclang>` はページ全体を変換します。要素のサブセットを要求するには、角括弧で囲んだリストを付加します。例えば `<doclang> [<ocr>]` や `<doclang> [<ocr>, <layout>, <picture>]` などです。
- 文字列を DocLang として解析する場合は、`skip_special_tokens=False` を指定してデコードしてください。そうしないと、専用のマークアップトークンは取り除かれます。
- 500Mモデルでは、密集したページ（小さな文字、長い表、複数カラムのテキスト）に対して`fine_route=True`を渡します。このパスでは画像トークンが4倍使用されるため、プロンプトが長くなり、推論が遅くなります。2Bモデルはすでにそのトークン密度を使用しており、別のパスが存在しないため、`fine_route=True`を指定するとエラーが発生します。
- 500Mモデルには密度ルーターが含まれており、これが判断を代行します。[predict_fine_route()](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingModel.predict_fine_route)は、バッチ内のどのページがファインパスを必要とするかを返します。

以下の例では、[Docling Technical Report](https://huggingface.co/papers/2408.09869)（`arXiv:2408.09869`）の1ページ目を変換しています。テキストプロンプトを変更するだけでタスクを切り替えることができ、モデルは要求された要素に絞り込まれたDocLangを返します。

| タスク | プロンプト |
|---|---|
| 全ページ | `<doclang>` |
| OCR | `<doclang> [<ocr>]` |
| レイアウト | `<doclang> [<layout>]` |
| テーブル | `<doclang> [<table>]` |
| 数式 | `<doclang> [<formula>]` |
| コード | `<doclang> [<code>]` |
| チャート | `<doclang> [<chart>]` |
| 画像 | `<doclang> [<picture>]` |
| 統合 | `<doclang> [<ocr>, <layout>, <picture>]` |

### 全ページ

`<doclang>` は、レイアウト、テキスト、表、数式、コード、チャート、画像を含むページ全体を変換します。

```python
from transformers import pipeline

pipe = pipeline(
    task="image-text-to-text",
    model="ibm-granite/granite-for-docling-500m",
)
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": "https://huggingface.co/ibm-granite/granite-for-docling-500m/resolve/main/docling_technical_report_p1.png"},
            {"type": "text", "text": "<doclang>"},
        ],
    }
]
pipe(text=messages, max_new_tokens=4096, return_full_text=False, skip_special_tokens=False)
```

```python
from transformers import AutoProcessor, AutoModelForImageTextToText

model_id = "ibm-granite/granite-for-docling-500m"

processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(model_id, device_map="auto")

conversation = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": "https://huggingface.co/ibm-granite/granite-for-docling-500m/resolve/main/docling_technical_report_p1.png"},
            {"type": "text", "text": "<doclang>"},
        ],
    },
]
inputs = processor.apply_chat_template(
    conversation,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)

output = model.generate(**inputs, max_new_tokens=4096)
# Keep the special tokens: they are the DocLang markup. Drop the end-of-text token that closes the generation.
doclang = processor.decode(output[0, inputs["input_ids"].shape[1] :], skip_special_tokens=False)
doclang = doclang.removesuffix(processor.tokenizer.eos_token).strip()
print(doclang)
```

一部の要素のみを変換する場合は、テキストプロンプトを上記の表のいずれかに変更します。例えば、`<doclang> [<ocr>, <layout>, <picture>]`のようにします。それ以外はすべて同じです。

### Dense pages: 細やかなパス

fine connector パスは、タイルあたりの画像トークン数を4倍にします。これにより、小さな文字、長い表、複数カラムのテキストの処理が向上します。呼び出しごとに`fine_route=True`を指定して選択できます。

```python
inputs = processor.apply_chat_template(
    conversation,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={"fine_route": True},
).to(model.device)
output = model.generate(**inputs, max_new_tokens=4096)
```

500Mモデル（`config.density_router_hidden_size`が設定されている）は、デフォルトの画像トークンから、どのページがファインパスを必要とするかを予測します：

```python
needs_fine = model.model.predict_fine_route(inputs["pixel_values"], inputs["pixel_attention_mask"])  # (batch_size,) bool
if needs_fine[0]:
    inputs = processor.apply_chat_template(
        conversation,
        add_generation_prompt=True,
        tokenize=True,
        return_dict=True,
        return_tensors="pt",
        processor_kwargs={"fine_route": True},
    ).to(model.device)
output = model.generate(**inputs, max_new_tokens=4096)
```

### バッチ推論

ページごとに異なるタイルグリッドが割り当てられるため、`pixel_values`はバッチ内の最大のタイル数に合わせてパディングされます。`pixel_attention_mask`は実際のタイルを示し、モデルはパディングを破棄します。

```python
pages = [
    "https://huggingface.co/ibm-granite/granite-for-docling-500m/resolve/main/docling_technical_report_p1.png",
    "https://huggingface.co/ibm-granite/granite-for-docling-500m/resolve/main/docling_technical_report_p1.png",
]
conversations = [
    [{"role": "user", "content": [{"type": "image", "url": url}, {"type": "text", "text": "<doclang>"}]}]
    for url in pages
]
inputs = processor.apply_chat_template(
    conversations,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={"padding": True},
).to(model.device)

output = model.generate(**inputs, max_new_tokens=4096)
for row in output:
    doclang = processor.decode(row[inputs["input_ids"].shape[1] :], skip_special_tokens=False)
    print(doclang.removesuffix(processor.tokenizer.eos_token).strip())
```

`processor_kwargs` に `"fine_route": True` を追加すると、バッチ全体が fine パスにルーティングされ、プロセッサは `tile_fine_mask` を返します。バッチは1つのパスのみを使用するため、ルーターが fine パスに送信するページを独自のバッチとして実行してください。

### DoclingでDocLangをエクスポート

`docling-core`は、AutoModelの例にある`doclang`文字列を`DoclingDocument`にパースし、必要に応じてシリアライズできます。

```python
from pathlib import Path
from docling_core.transforms.deserializer.doclang import DocLangDocDeserializer

document = DocLangDocDeserializer().deserialize_str(doclang)

print(document.export_to_markdown())
print(document.export_to_html())
print(document.export_to_dict())

document.save_as_markdown(Path("page.md"))
document.save_as_html(Path("page.html"))
document.save_as_json(Path("page.json"))
```

[DocLang](https://doclang.ai/)仕様と`doclang`ツールキット（validate / pack）は、[doclang-project/doclang](https://github.com/doclang-project/doclang)にあります。デシリアライザーと`DoclingDocument`エクスポート機能は、[`docling-core`](https://github.com/docling-project/docling-core)に含まれています。

## 注記

- 1ページ全体は長くなります。`max_new_tokens`は数千単位で設定してください。そうしないと、DocLangが静かに切り捨てられてしまいます。
- Tiles は 512x512 のサイズで、ページの縦横比に最もよく合うグリッド上に配置され、`max_patches`（デフォルト 32）および 1 辺あたり 16 タイルで上限が設定されています。1 つの Tile に収まるページにはサムネイルは生成されません。
- チェックポイントは、そのイメージプロセッサ設定にスプレッドルールを含めることができます。幅広のランドスケープページ（`dense_min_aspect` < 幅/高さ <= `dense_max_aspect`）に対して、`max_patches` グリッドが `dense_max_scale` 以下に縮小してしまう場合に、`max_patches` の代わりに `dense_max_patches` タイルを使用します。新聞のスプレッドが典型的なケースです。このルールはデフォルトで無効（`dense_max_patches=0`）であり、チェックポイントが学習された際の設定と一致させる必要があります。
- 500Mモデルでは、fineパスによりタイルあたりの画像トークン数が4倍になり、64から256に増加します。これは高密度なページでのみ使用するか、[predict_fine_route()](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingModel.predict_fine_route)でルーターに判断させることをお勧めします。2Bモデルでは、全体を通じてタイルあたり256の画像トークンを使用します（pixel-shuffle比率2）。

## GraniteDoclingConfig[[transformers.GraniteDoclingConfig]]

#### transformers.GraniteDoclingConfig[[transformers.GraniteDoclingConfig]]

```python
transformers.GraniteDoclingConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_token_id: int = 100337, tie_word_embeddings: bool = True, use_cache: bool = True, pad_token_id: int | None = 100256, density_router_hidden_size: int | None = None, density_router_threshold: float = 0.4, density_router_loss_weight: float = 0.1)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/configuration_granite_docling.py#L160)

**パラメータ:**

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *任意*) : テキストバックボーンの config オブジェクトまたは辞書。

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *任意*) : ビジョンバックボーンの config オブジェクトまたは辞書。

image_token_id (`int`、*任意*、デフォルトは`100337`) : 入力画像のプレースホルダーとして使用される画像トークンのインデックス。

tie_word_embeddings (`bool`、*任意*、デフォルトは`True`) : モデルの`tied_weights_keys`マッピングに従って重み埋め込みを共有するかどうか。

use_cache (`bool`、*任意*、デフォルトは `True`) : モデルが最後のキー/バリューアテンションを返すかどうか（すべてのモデルで利用されるわけではありません）。`config.is_decoder=True` の場合、またはモデルがデコーダー専用の生成モデルである場合にのみ関連します。

pad_token_id (`int`, *任意*, デフォルトは `100256`) : 語彙内でパディングに使用されるトークンID。

density_router_hidden_size (`int`, *optional*) : 密度ルーターの隠れ層サイズ。ビジョンエンコーダーの特徴量から、ページがファインコネクタパスを必要とするかどうかを予測します。`None`の場合、ルーターは構築されません。

density_router_threshold (`float`, *optional*, デフォルトは 0.4) : 密度ルーターがファインコネクタパスを選択する閾値となる確率。

density_router_loss_weight (`float`、*任意*、デフォルト値は 0.1) : `router_labels` が指定された場合の、density router loss の重み。

これはGraniteDoclingModelの設定を保存するための設定クラスです。指定された引数に基づいてGranite Doclingモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[ibm-granite/granite-for-docling-500m](https://huggingface.co/ibm-granite/granite-for-docling-500m)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/v5.23.0/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/v5.23.0/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

## GraniteDoclingTextConfig[[transformers.GraniteDoclingTextConfig]]

#### transformers.GraniteDoclingTextConfig[[transformers.GraniteDoclingTextConfig]]

```python
transformers.GraniteDoclingTextConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vocab_size: int = 133800, hidden_size: int = 1024, intermediate_size: int = 2048, num_hidden_layers: int = 28, num_attention_heads: int = 16, num_key_value_heads: int | None = 4, hidden_act: str = 'silu', max_position_embeddings: int = 32768, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = 100256, bos_token_id: int | None = 100257, eos_token_id: int | list[int] | None = 100257, tie_word_embeddings: bool = True, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool = False, attention_dropout: float | int = 0.0, mlp_bias: bool = False, embedding_multiplier: float | int = 12.0, logits_scaling: float | int = 4.0, residual_multiplier: float | int = 0.263, attention_multiplier: float | int = 0.015625)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/configuration_granite_docling.py#L92)

**パラメータ:**

vocab_size (`int`、*任意*、デフォルトは`133800`) : モデルの語彙サイズ。`input_ids`で表現できるトークンの種類数を定義します。

hidden_size (`int`、*任意*、デフォルトは`1024`) : 隠れ表現の次元数。

intermediate_size (`int`、*任意*、デフォルトは`2048`) : MLP 表現の次元数。

num_hidden_layers (`int`、*任意*、デフォルトは`28`) : Transformerデコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは`16`) : Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。

num_key_value_heads (`int`, *optional*, デフォルトは `4`) : Grouped Query Attention を実装するために使用する key_value ヘッドの数です。`num_key_value_heads=num_attention_heads` の場合、モデルは Multi Head Attention (MHA) を使用し、`num_key_value_heads=1` の場合は Multi Query Attention (MQA) を使用し、それ以外の場合は GQA が使用されます。マルチヘッドのチェックポイントを GQA チェックポイントに変換する際は、各グループの key ヘッドと value ヘッドは、そのグループ内の元のすべてのヘッドを平均プーリングして構築する必要があります。詳細については、[この論文](https://huggingface.co/papers/2305.13245)を参照してください。指定されない場合、デフォルトで `num_attention_heads` が使用されます。

hidden_act (`str`、*任意*、デフォルトは`silu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

max_position_embeddings (`int`、*任意*、デフォルトは`32768`) : このモデルが使用される可能性のある最大シーケンス長です。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

rms_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : rms 正規化レイヤーで使用する epsilon。

use_cache (`bool`、*任意*、デフォルトは `True`) : モデルが最後のキー/バリューアテンションを返すかどうか（すべてのモデルで利用されるわけではありません）。`config.is_decoder=True` の場合、またはモデルがデコーダー専用の生成モデルである場合にのみ関連します。

pad_token_id (`int`, *任意*, デフォルトは `100256`) : 語彙内でパディングに使用されるトークンID。

bos_token_id (`int`、*任意*、デフォルトは`100257`) : 語彙内でストリームの開始に使用されるトークン ID。

eos_token_id (`Union[int, list[int]]`、*任意*、デフォルトは `100257`) : 語彙内でストリームの終了に使用されるトークン ID。

tie_word_embeddings (`bool`、*任意*、デフォルトは`True`) : モデルの`tied_weights_keys`マッピングに従って重み埋め込みを共有するかどうか。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *optional*) : RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には `rope_theta` の値が含まれていなければならず、より長い `max_position_embeddings` で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。

attention_bias (`bool`、*任意*、デフォルトは`False`) : セルフアテンションにおけるクエリ、キー、バリュー、出力の投影層でバイアスを使用するかどうか。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

mlp_bias (`bool`, *任意*, デフォルトは `False`) : MLP 層の up_proj、down_proj、gate_proj 層でバイアスを使用するかどうか。

embedding_multiplier (`Union[float, int]`、*任意*、デフォルトは`12.0`) : ワードエンベディングに適用されるスケーリング係数。隠れサイズに対するエンベディングのスケーリングに使用されます。

logits_scaling (`Union[float, int]`、*任意*、デフォルトは`4.0`) : 確率分布を計算する前に、出力 logits に適用されるスケーリング係数。

residual_multiplier (`Union[float, int]`、*任意*、デフォルトは`0.263`) : 残差接続に適用されるスケーリング係数。

attention_multiplier (`Union[float, int]`、*任意*、デフォルトは`0.015625`) : 注意度重みに適用されるスケーリング係数。

これはGraniteDoclingModelの設定を保存するための設定クラスです。指定された引数に基づいてGranite Doclingモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[ibm-granite/granite-for-docling-500m](https://huggingface.co/ibm-granite/granite-for-docling-500m)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/v5.23.0/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/v5.23.0/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

```python
>>> from transformers import GraniteDoclingTextModel, GraniteDoclingTextConfig

>>> # Initializing a GraniteDoclingText granite_docling_text-3b style configuration
>>> configuration = GraniteDoclingTextConfig()

>>> # Initializing a model from the granite_docling_text-7b style configuration
>>> model = GraniteDoclingTextModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## GraniteDoclingVisionConfig[[transformers.GraniteDoclingVisionConfig]]

#### transformers.GraniteDoclingVisionConfig[[transformers.GraniteDoclingVisionConfig]]

```python
transformers.GraniteDoclingVisionConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 768, intermediate_size: int = 3072, num_hidden_layers: int = 12, num_attention_heads: int = 12, num_channels: int = 3, image_size: int | list[int] | tuple[int, int] = 512, patch_size: int | list[int] | tuple[int, int] = 16, hidden_act: str = 'gelu_pytorch_tanh', layer_norm_eps: float = 1e-06, attention_dropout: float | int = 0.0, initializer_range: float = 0.02, out_hidden_size: int = 1024, scale_factor: int = 4, deepstack_visual_indexes: list[int] | None = None, use_fine_route: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/configuration_granite_docling.py#L36)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`768`) : 隠れ表現の次元数。

intermediate_size (`int`、*任意*、デフォルトは `3072`) : MLP 表現の次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `12`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `12`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

num_channels (`int`、*任意*、デフォルトは`3`) : 入力チャネル数。

image_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`512`) : 各画像のサイズ（解像度）。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`16`) : 各パッチのサイズ（解像度）。

hidden_act (`str`、*任意*、デフォルトは `gelu_pytorch_tanh`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"` など。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

out_hidden_size (`int`、*optional*、デフォルトは 1024) : コネクタが射影するテキストデコーダーの隠れ層サイズ。

scale_factor (`int`, *任意*, デフォルトは 4) : コネクタのピクセルシャッフル係数。`(image_size // patch_size) ** 2` のビジョントークンからなる各タイルは、`scale_factor ** 2` によって削減されます。

deepstack_visual_indexes (`list[int]`、*optional*、デフォルトは`[3, 7, 10]`) : DeepStack マージャーによって射影されるビジョンエンコーダーの層のインデックス。インデックス 0 は最初の層の出力を指します。

use_fine_route (`bool`、*任意*、デフォルトは`True`) : `scale_factor`の半分だけピクセルをシャッフルし、タイルあたりの画像トークンを4倍に増やすファインコネクタパスを構築するかどうか。500Mのチェックポイントには含まれていますが、2Bのチェックポイントには含まれていません。

ページ内の各512x512タイルを埋め込むSigLIPスタイルのビジュアルエンコーダー、およびその出力をイメージトークンに変換するコネクタの構成です。

例:

```python
>>> from transformers import GraniteDoclingVisionConfig, GraniteDoclingVisionModel

>>> # Initializing a GraniteDoclingVisionConfig with ibm-granite/granite-for-docling-500m style configuration
>>> configuration = GraniteDoclingVisionConfig()

>>> # Initializing a GraniteDoclingVisionModel (with random weights) from the ibm-granite/granite-for-docling-500m style configuration
>>> model = GraniteDoclingVisionModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## GraniteDoclingImageProcessor[[transformers.GraniteDoclingImageProcessor]]

#### transformers.GraniteDoclingImageProcessor[[transformers.GraniteDoclingImageProcessor]]

```python
transformers.GraniteDoclingImageProcessor(**kwargs: *<class 'transformers.models.granite_docling.image_processing_granite_docling.GraniteDoclingImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/image_processing_granite_docling.py#L241)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は`{'height' : 512, 'width': 512}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *任意*、デフォルトは `True`) : size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルトは `3`) : 画像をリサイズする場合に使用するリサンプリングフィルター。`PILImageResampling` の列挙型のいずれかになります。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.48145466, 0.4578275, 0.40821073]`) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.26862954, 0.26130258, 0.27577711]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

crop_to_patches (`bool`, *kwargs*, *optional*, デフォルトは `True`) : ページを、アスペクト比に最もよく合うグリッド（1辺あたり最大16タイル）に配置された512x512のタイルに分割するかどうか。`preprocess` メソッドの `crop_to_patches` パラメータによって上書きできます。

min_patches (`int`, *kwargs*, *optional*, デフォルトは 1) : 1 ページあたりのタイルの最小数。`crop_to_patches` が `True` に設定されている場合のみ有効です。`preprocess` メソッドの `min_patches` パラメータによって上書きできます。

max_patches (`int`, *kwargs*, *optional*, デフォルトは 32) : 1 ページあたりのタイルの最大数。`crop_to_patches` が `True` に設定されている場合のみ有効です。`preprocess` メソッドの `max_patches` パラメータによって上書きできます。

fine_route (`bool`, *kwargs*, *任意*、デフォルトは`False`) : ページがファインコネクタパスを使用するかどうか。このパスを使用すると、タイルあたりのイメージトークン数が4倍になります。

dense_max_patches (`int`, *kwargs*, *optional*, デフォルト値は 0) : スプレッドルールが選択するページに対するタイルの最大数 (0 でルールを無効化します)。`max_patches` グリッドによって `dense_max_scale` 未満に縮小され、かつ幅と高さの比率が `dense_min_aspect` を超えている場合 (設定されている場合は `dense_max_aspect` 以下)、ページは `max_patches` ではなく最大 `dense_max_patches` 個のタイルでタイル化されます。チェックポイントは同じルールで訓練されていなければなりません。

dense_max_scale (`float`, *kwargs*, *任意*、デフォルト値は 0.0) : `max_patches` において、タイル化されたキャンバスの幅とページ幅の比率が、この値未満の場合にページが未解決とみなされる閾値です。0 を指定すると、このテストがスキップされます。

dense_min_aspect (`float`, *kwargs*, *任意*、デフォルト値は 0.0) : ページが `dense_max_patches` を取得するために超える必要がある幅/高さ比です。0 を指定すると、このテストがスキップされます。

dense_max_aspect (`float`, *kwargs*, *optional*, デフォルト値は 0.0) : `dense_max_patches` を取得するために、ページが超えてはならない幅/高さの比率です。これにより、単一の数式行などのストリップが `max_patches` に保持されます。0 は上限がないことを意味します。

ページをアスペクト比に最もよく合うグリッドで512x512のタイルに分割し（`crop_to_patches`、最大`max_patches`枚、1辺あたり16枚）、タイルが複数ある場合はページ全体のサムネイルを追加し、バッチ内のサンプルを同じタイル数にパディングします。`pixel_attention_mask`は実際のタイルを示します。`fine_route=True`は、ファインコネクタパス用のサンプルを示します（`tile_fine_mask`、サンプルごとに1つの値）。

#### preprocess[[transformers.GraniteDoclingImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], *args, image_like_kwargs: dict[str, typing.Any] | None = None, **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/image_processing_utils.py#L382)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 前処理対象の画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

image_like_kwargs (`dict[str, Any]`、*省略可*) : 追加の画像類似の入力も前処理対象にするための開発者向けフラグです。引数として kwarg を渡す方法が機能しない場合のみ使用してください。例えば、`preprocess(images, masks=masks)` が推奨される方法ですが、一部のモデルでは引数の優先順位の問題が発生します。そのような場合は、代わりに `preprocess(images, image_like_inputs={"masks": masks})` を使用できます。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

画像または画像のバッチを前処理します。

## GraniteDoclingImageProcessorPil[[transformers.GraniteDoclingImageProcessorPil]]

#### transformers.GraniteDoclingImageProcessorPil[[transformers.GraniteDoclingImageProcessorPil]]

```python
transformers.GraniteDoclingImageProcessorPil(**kwargs: *<class 'transformers.models.granite_docling.image_processing_pil_granite_docling.GraniteDoclingImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/image_processing_pil_granite_docling.py#L239)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は`{'height' : 512, 'width': 512}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *任意*、デフォルトは `True`) : size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルトは `3`) : 画像をリサイズする場合に使用するリサンプリングフィルター。`PILImageResampling` の列挙型のいずれかになります。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.48145466, 0.4578275, 0.40821073]`) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.26862954, 0.26130258, 0.27577711]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

crop_to_patches (`bool`, *kwargs*, *optional*, デフォルトは `True`) : ページを、アスペクト比に最もよく合うグリッド（1辺あたり最大16タイル）に配置された512x512のタイルに分割するかどうか。`preprocess` メソッドの `crop_to_patches` パラメータによって上書きできます。

min_patches (`int`, *kwargs*, *optional*, デフォルトは 1) : 1 ページあたりのタイルの最小数。`crop_to_patches` が `True` に設定されている場合のみ有効です。`preprocess` メソッドの `min_patches` パラメータによって上書きできます。

max_patches (`int`, *kwargs*, *optional*, デフォルトは 32) : 1 ページあたりのタイルの最大数。`crop_to_patches` が `True` に設定されている場合のみ有効です。`preprocess` メソッドの `max_patches` パラメータによって上書きできます。

fine_route (`bool`, *kwargs*, *任意*、デフォルトは`False`) : ページがファインコネクタパスを使用するかどうか。このパスを使用すると、タイルあたりのイメージトークン数が4倍になります。

dense_max_patches (`int`, *kwargs*, *optional*, デフォルト値は 0) : スプレッドルールが選択するページに対するタイルの最大数 (0 でルールを無効化します)。`max_patches` グリッドによって `dense_max_scale` 未満に縮小され、かつ幅と高さの比率が `dense_min_aspect` を超えている場合 (設定されている場合は `dense_max_aspect` 以下)、ページは `max_patches` ではなく最大 `dense_max_patches` 個のタイルでタイル化されます。チェックポイントは同じルールで訓練されていなければなりません。

dense_max_scale (`float`, *kwargs*, *任意*、デフォルト値は 0.0) : `max_patches` において、タイル化されたキャンバスの幅とページ幅の比率が、この値未満の場合にページが未解決とみなされる閾値です。0 を指定すると、このテストがスキップされます。

dense_min_aspect (`float`, *kwargs*, *任意*、デフォルト値は 0.0) : ページが `dense_max_patches` を取得するために超える必要がある幅/高さ比です。0 を指定すると、このテストがスキップされます。

dense_max_aspect (`float`, *kwargs*, *optional*, デフォルト値は 0.0) : `dense_max_patches` を取得するために、ページが超えてはならない幅/高さの比率です。これにより、単一の数式行などのストリップが `max_patches` に保持されます。0 は上限がないことを意味します。

[GraniteDoclingImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingImageProcessor)のPILバックエンド: 同じ512x512のタイル分割、サムネイル、およびタイルのパディング。

#### preprocess[[transformers.GraniteDoclingImageProcessorPil.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], *args, image_like_kwargs: dict[str, typing.Any] | None = None, **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/image_processing_utils.py#L382)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 前処理対象の画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

image_like_kwargs (`dict[str, Any]`、*省略可*) : 追加の画像類似の入力も前処理対象にするための開発者向けフラグです。引数として kwarg を渡す方法が機能しない場合のみ使用してください。例えば、`preprocess(images, masks=masks)` が推奨される方法ですが、一部のモデルでは引数の優先順位の問題が発生します。そのような場合は、代わりに `preprocess(images, image_like_inputs={"masks": masks})` を使用できます。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

画像または画像のバッチを前処理します。

## GraniteDoclingProcessor[[transformers.GraniteDoclingProcessor]]

#### transformers.GraniteDoclingProcessor[[transformers.GraniteDoclingProcessor]]

```python
transformers.GraniteDoclingProcessor(image_processor, tokenizer = None, image_seq_len: int = 64, chat_template: str | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/processing_granite_docling.py#L34)

**パラメータ:**

image_processor (`GraniteDoclingImageProcessor`) : 画像プロセッサは必須の入力です。

tokenizer (`tokenizer_class`) : トークナイザーは必須の入力です。

image_seq_len (`int`, *optional*, デフォルトは 64) : 粗いパスにおけるタイルごとの`<image>`トークンの数です。`image_seq_len = int(((image_size // patch_size) ** 2) / (scale_factor**2))`として計算されます。

chat_template (`str`, *任意*) : チャット内のメッセージのリストをトークン化可能な文字列に変換するための Jinja テンプレート。

GraniteDoclingProcessorを構築します。このクラスは、画像プロセッサとトークナイザーを単一のプロセッサとしてラップします。

[GraniteDoclingProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingProcessor) は、[GraniteDoclingImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingImageProcessor) と `tokenizer_class` のすべての機能を提供します。詳細については、[~GraniteDoclingImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingImageProcessor) および `~tokenizer_class` を参照してください。

#### __call__[[transformers.GraniteDoclingProcessor.__call__]]

```python
__call__(images = None, text = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/processing_granite_docling.py#L55)

**パラメータ:**

images (``) : Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.

text (``) : The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If you pass a pretokenized input, set `is_split_into_words=True` to avoid ambiguity with batched inputs.

return_tensors (`str` または [TensorType](/docs/transformers/v5.23.0/ja/internal/file_utils#transformers.TensorType)、*optional*) : 設定されている場合、特定のフレームワークのテンソルを返します。受け入れ可能な値は以下の通りです:  - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

**戻り値:** [BatchEncoding](/docs/transformers/v5.23.0/ja/main_classes/tokenizer#transformers.BatchEncoding)

`pixel_values` と `pixel_attention_mask` を含むトークン化されたプロンプト、および `fine_route=True` の場合の `tile_fine_mask`。タイルグリッドはプロンプトの構築にのみ使用され、返却されません。

## GraniteDoclingVisionModel[[transformers.GraniteDoclingVisionModel]]

#### transformers.GraniteDoclingVisionModel[[transformers.GraniteDoclingVisionModel]]

```python
transformers.GraniteDoclingVisionModel(config: GraniteDoclingVisionConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L955)

**パラメータ:**

config ([GraniteDoclingVisionConfig](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingVisionConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

GraniteDoclingのビジュアルエンコーダーと、その上に配置されたコネクタ: ページのタイルを埋め込み、すべてのタイルの画像トークンと射影されたDeepStack特徴量を返します。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.GraniteDoclingVisionModel.forward]]

```python
forward(pixel_values: FloatTensor, fine: bool = False, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L981)

**パラメータ:**

pixel_values (`torch.FloatTensor`、形状 `(num_tiles, num_channels, image_size, image_size)`) : パディングタイルを含まず、バッチ全体でフラット化されたタイル。

fine (`bool`、*任意*、デフォルトは`False`) : タイルがファインコネクタパスを使用するかどうか。このパスを使用すると、タイルあたりのイメージトークン数が4倍になります。

**戻り値:**

タイル順のすべてのタイルの画像トークン（`pooler_output`）と、タップされた各ビジョンレイヤーごとに1つの射影されたDeepStack特徴量（`deepstack_features`）で、同じタイル順です。

[GraniteDoclingVisionModel](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingVisionModel)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

## GraniteDoclingModel[[transformers.GraniteDoclingModel]]

#### transformers.GraniteDoclingModel[[transformers.GraniteDoclingModel]]

```python
transformers.GraniteDoclingModel(config: GraniteDoclingConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L1025)

**パラメータ:**

config ([GraniteDoclingConfig](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

ビジョンエンコーダー、コネクタ、テキストデコーダーで構成されるGraniteDoclingモデル。特定のヘッドを上に置かず、生の隠れ状態を出力します。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.GraniteDoclingModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, pixel_values: typing.Optional[torch.FloatTensor] = None, tile_fine_mask: typing.Optional[torch.BoolTensor] = None, pixel_attention_mask: typing.Optional[torch.BoolTensor] = None, mm_encoder_outputs: dict | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L1091)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

pixel_values (`torch.FloatTensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [GraniteDoclingImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingImageProcessor) を使用して取得できます。詳細については [GraniteDoclingImageProcessor.__call__()](/docs/transformers/v5.23.0/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（[GraniteDoclingProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingProcessor) は画像の処理に [GraniteDoclingImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingImageProcessor) を使用します）。

tile_fine_mask (`torch.BoolTensor`、shape `(batch_size,)`、*optional*) : `fine_route=True` でプロセッサが呼び出された場合、すべて True になります。このとき、バッチはファインコネクタのパスを通り、タイルあたりの画像トークン数が4倍になります。

pixel_attention_mask (`torch.BoolTensor`、形状 `(batch_size, num_tiles)`、*任意*) : プロセッサが返す実際のタイルです。パディングのタイルは false です。`pixel_values` と併せて指定する必要があります。

mm_encoder_outputs (`dict`, *任意*) : キーがサポートされているモダリティ、値がそのモダリティのエンコード済み出力である辞書。各エンコード済み出力は、(`pooler_output`、*任意*: `last_hidden_states`、*任意*: `hidden_states`、*任意*: `attentions`) というタプルで構成されます。`pooler_output` は形状 `(batch_size, sequence_length, hidden_size)`、*任意*) を持ち、エンコーダーのマルチモーダル特徴がテキスト埋め込みにマージされたシーケンスです。

**戻り値:** `GraniteDoclingBaseModelOutputWithPast` または `tuple(torch.Tensor)`

`GraniteDoclingBaseModelOutputWithPast`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[GraniteDoclingConfig](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingConfig)）や入力に応じて、さまざまな要素で構成されます。

モデルに与えられる入力には、任意の数の画像が含まれる場合があります。これに対応するため、モデルに与えられる pixel_values には画像パディングが適用され、形状は (batch_size, max_num_tiles, 3, image_size, image_size) となります。ここで max_num_tiles は、バッチ内の batch_size 個のサンプルの中で最大のタイル数です。パディングされたタイルは `pixel_attention_mask` で False となり、ビジョンエンコーダーに渡される前に破棄されます。

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **past_key_values** (`~cache_utils.Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.Cache) インスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  自己アテンションブロック（および `config.is_encoder_decoder=True` の場合、クロスカレンションブロック）の事前計算済みヒドゥンステート（キーとバリュー）を保持します。これらは逐次デコーディングを高速化するために使用できます（`past_key_values` 入力参照）。
- **hidden_states** (`tuple[torch.Tensor]`、*optional*、`output_hidden_states=True` が渡された場合、または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple[torch.Tensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **image_hidden_states** (`tuple[torch.Tensor]`、形状 `(batch_size, num_images, sequence_length, hidden_size)`、*任意*) -- ビジョンエンコーダーによって生成され、最後の隠れ状態を投影した後のモデルの画像隠れ状態です。
- **router_logits** (`torch.FloatTensor`、shape `(batch_size,)`、*任意*) -- 密度ルーターのロジット。サンプルごとに1つ返されます。モデルにルーターがあり、`pixel_values` が指定された場合に返されます。

#### get_image_features[[transformers.GraniteDoclingModel.get_image_features]]

```python
get_image_features(pixel_values: FloatTensor, pixel_attention_mask: BoolTensor, tile_fine_mask: typing.Optional[torch.BoolTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L1052)

**パラメータ:**

pixel_values (`torch.FloatTensor`、形状 `(batch_size, num_tiles, num_channels, image_size, image_size)`) : 入力画像タイルに対応するテンソル。

pixel_attention_mask (`torch.BoolTensor`、形状 `(batch_size, num_tiles)`) : プロセッサが返す実際のタイルです。パディングタイルは false です。

tile_fine_mask (`torch.BoolTensor`、shape `(batch_size,)`、*任意*) : `fine_route=True` を指定して呼び出されたプロセッサが必要です: バッチはファインコネクタパスを使用し、タイルあたりの画像トークン数が4倍になります。

**戻り値:** `GraniteDoclingImageFeaturesOutput` または `tuple(torch.Tensor)`

`GraniteDoclingImageFeaturesOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[GraniteDoclingConfig](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingConfig)）と入力に応じて、さまざまな要素で構成されます。

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`tuple[torch.FloatTensor]`、長さ `batch_size`) -- 各サンプルの画像トークンをタイル順に並べ、テキストの隠れ層サイズに射影したものです。各テンソルの形状は `(num_image_tokens, hidden_size)` です。1タイルから得られるトークン数は、粗いコネクタパスでは `image_seq_len` 個、細いパスではその4倍です。生成時には、これらのサンプルごとのテンソルがビーム全体にわたって繰り返し使用されます。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **deepstack_features** (`list[tuple[torch.FloatTensor]]`, *optional*) -- `config.deepstack_visual_indexes` の各エントリに対応する、1つの射影された中間ビジョンエンコーダーの隠れ状態。各エントリはサンプルごとに分割されており、レイアウトは `pooler_output` と同じです。
- **router_logits** (`torch.FloatTensor`、形状 `(batch_size,)`、*任意*) -- 密度ルーターのロジット。サンプルごとに1つ返されます。モデルにルーターがある場合に返されます。

#### predict_fine_route[[transformers.GraniteDoclingModel.predict_fine_route]]

```python
predict_fine_route(pixel_values: FloatTensor, pixel_attention_mask: BoolTensor)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L1198)

**パラメータ:**

pixel_values (`torch.FloatTensor`、形状 `(batch_size, num_tiles, num_channels, image_size, image_size)`) : 入力画像タイルに対応するテンソル。

pixel_attention_mask (`torch.BoolTensor`、形状 `(batch_size, num_tiles)`) : プロセッサによって返される実際のタイル。

**戻り値:** `torch.BoolTensor`、形状は`(batch_size,)`

`True`は、ファインコネクタパスを必要とするサンプルを示します。

密度ルーターを使用して、ファインコネクタパスを必要とするサンプルを予測します。`fine_route=True` を指定してプロセッサを再度呼び出すことで、それらをルーティングします。

## GraniteDoclingTextModel[[transformers.GraniteDoclingTextModel]]

#### transformers.GraniteDoclingTextModel[[transformers.GraniteDoclingTextModel]]

```python
transformers.GraniteDoclingTextModel(config: GraniteDoclingTextConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L423)

**パラメータ:**

config ([GraniteDoclingTextConfig](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingTextConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

特定のヘッドを上に付加せずに、生の隠れ状態を出力する、素のGranite Docling Text Model。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.GraniteDoclingTextModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, use_cache: bool | None = None, visual_pos_masks: typing.Optional[torch.BoolTensor] = None, deepstack_visual_embeds: list[torch.Tensor] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L441)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

visual_pos_masks (`torch.BoolTensor`、形状 `(batch_size, sequence_length)`、*任意*) : DeepStack 特徴を受け取る画像トークンの位置。

deepstack_visual_embeds (`list[torch.Tensor]`、*任意*) : DeepStack 特徴量。各要素の形状は `(num_image_tokens, hidden_size)` です。`i` 番目の要素は、デコーダー層 `i` の後に `visual_pos_masks` における隠れ状態に追加されます。

**戻り値:** [BaseModelOutputWithPast](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) または `tuple(torch.Tensor)`

`torch.Tensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）または [BaseModelOutputWithPast](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast)。設定（[GraniteDoclingConfig](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingConfig)）と入力に応じて、さまざまな要素で構成されます。

[GraniteDoclingTextModel](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingTextModel)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。

  `past_key_values`が使用されている場合、出力されるのは、形状`(batch_size, 1, hidden_size)`のシーケンスの最後の隠れ状態のみです。
- **past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  自己アテンションブロック（および `config.is_encoder_decoder=True` の場合、クロスカレンションブロック）の事前計算済みヒドゥンステート（キーとバリュー）を保持します。これらは逐次デコーディングを高速化するために使用できます（`past_key_values` 入力参照）。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

## GraniteDoclingForConditionalGeneration[[transformers.GraniteDoclingForConditionalGeneration]]

#### transformers.GraniteDoclingForConditionalGeneration[[transformers.GraniteDoclingForConditionalGeneration]]

```python
transformers.GraniteDoclingForConditionalGeneration(config: GraniteDoclingConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L1231)

**パラメータ:**

config ([GraniteDoclingConfig](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

言語モデリングヘッドを備えたGraniteDoclingモデルです。ビジュアルエンコーダー、コネクタ、テキストデコーダーで構成され、その上に言語モデリングヘッドが配置されています。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.GraniteDoclingForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, pixel_values: typing.Optional[torch.FloatTensor] = None, tile_fine_mask: typing.Optional[torch.BoolTensor] = None, pixel_attention_mask: typing.Optional[torch.BoolTensor] = None, mm_encoder_outputs: dict | None = None, labels: typing.Optional[torch.LongTensor] = None, router_labels: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L1269)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

pixel_values (`torch.FloatTensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [GraniteDoclingImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingImageProcessor) を使用して取得できます。詳細については [GraniteDoclingImageProcessor.__call__()](/docs/transformers/v5.23.0/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（[GraniteDoclingProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingProcessor) は画像の処理に [GraniteDoclingImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingImageProcessor) を使用します）。

tile_fine_mask (`torch.BoolTensor`、shape `(batch_size,)`、*optional*) : `fine_route=True` でプロセッサが呼び出された場合、すべて True になります。このとき、バッチはファインコネクタのパスを通り、タイルあたりの画像トークン数が4倍になります。

pixel_attention_mask (`torch.BoolTensor`、形状 `(batch_size, num_tiles)`、*任意*) : プロセッサが返す実際のタイルです。パディングのタイルは false です。`pixel_values` と併せて指定する必要があります。

mm_encoder_outputs (`dict`, *任意*) : キーがサポートされているモダリティ、値がそのモダリティのエンコード済み出力である辞書。各エンコード済み出力は、(`pooler_output`、*任意*: `last_hidden_states`、*任意*: `hidden_states`、*任意*: `attentions`) というタプルで構成されます。`pooler_output` は形状 `(batch_size, sequence_length, hidden_size)`、*任意*) を持ち、エンコーダーのマルチモーダル特徴がテキスト埋め込みにマージされたシーケンスです。

labels (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : マスクド言語モデリング損失を計算するためのラベル。インデックスは `[0, ..., config.vocab_size]` または `model.image_token_id`（ここで `model` は `GraniteDoclingForConditionalGeneration` のインスタンス）のいずれかである必要があります。インデックスが `model.image_token_id` に設定されているトークンは無視（マスク）され、損失は `[0, ..., config.vocab_size]` にラベルを持つトークンのみに対して計算されます。

router_labels (`torch.Tensor`、shape `(batch_size,)`、*optional*) : density router のターゲット。fine connector パスが必要なサンプルは `1`（または `True`）、それ以外は `0` です。float、bool、または int で指定します。router の損失は、logits に対する binary cross-entropy です。

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

logits_to_keep (`Union[int, torch.Tensor]`、*任意*、デフォルトは `0`) : `int` の場合、最後の `logits_to_keep` トークンについて logits を計算します。`0` の場合、すべての `input_ids` について logits を計算します（特殊ケース）。生成には最後のトークンの logits だけで十分であり、そのトークンのみについて計算することでメモリを節約できます。これは、長いシーケンスや大規模な語彙サイズの場合に特に顕著な効果があります。`torch.Tensor` の場合、シーケンス長次元で保持するインデックスに対応する 1 次元である必要があります。これは、パックされたテンソル形式（バッチとシーケンス長を単一の次元にまとめる形式）を使用する場合に有用です。

**戻り値:** `GraniteDoclingCausalLMOutputWithPast` または `tuple(torch.Tensor)`

`GraniteDoclingCausalLMOutputWithPast`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[GraniteDoclingConfig](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingConfig)）や入力に応じて、さまざまな要素で構成されます。

[GraniteDoclingForConditionalGeneration](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingForConditionalGeneration)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 言語モデリングの損失(次のトークンの予測用)。
- **logits** (`torch.FloatTensor`、shape `(batch_size, sequence_length, config.vocab_size)`) -- 言語モデリングヘッドの予測スコア（SoftMax 適用前の各語彙トークンのスコア）。
- **past_key_values** (`~cache_utils.Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/v5.23.0/ja/internal/generation_utils#transformers.Cache) インスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  自己アテンションブロック（および `config.is_encoder_decoder=True` の場合、クロスカレンションブロック）の事前計算済みヒドゥンステート（キーとバリュー）を保持します。これらは逐次デコーディングを高速化するために使用できます（`past_key_values` 入力参照）。
- **hidden_states** (`tuple[torch.Tensor]`、*optional*、`output_hidden_states=True` が渡された場合、または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple[torch.Tensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **image_hidden_states** (`tuple[torch.Tensor]`、形状 `(batch_size, num_images, sequence_length, hidden_size)`、*任意*) -- ビジョンエンコーダーによって生成され、最後の隠れ状態を投影した後のモデルの画像隠れ状態です。
- **router_logits** (`torch.FloatTensor`、shape `(batch_size,)`、*任意*) -- 密度ルーターのロジット。サンプルごとに1つ返されます。モデルにルーターがあり、`pixel_values` が指定された場合に返されます。

例:

```python
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> from transformers.image_utils import load_image

>>> image = load_image("https://huggingface.co/ibm-granite/granite-for-docling-500m/resolve/main/docling_technical_report_p1.png")

>>> processor = AutoProcessor.from_pretrained("ibm-granite/granite-for-docling-500m")
>>> model = AutoModelForImageTextToText.from_pretrained("ibm-granite/granite-for-docling-500m", device_map="auto")

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {"type": "image"},
...             {"type": "text", "text": "<doclang>"},
...         ],
...     }
... ]
>>> prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
>>> inputs = processor(text=prompt, images=image, return_tensors="pt").to(model.device)

>>> generated_ids = model.generate(**inputs, max_new_tokens=4096)
>>> print(processor.decode(generated_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=False))
```

#### get_image_features[[transformers.GraniteDoclingForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: Tensor, pixel_attention_mask: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/granite_docling/modeling_granite_docling.py#L1252)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソル。

pixel_attention_mask (`torch.LongTensor`, *任意*) : 画像内のパディング領域を示すアテンションマスク。

**戻り値:** [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) または `tuple(torch.Tensor)`

`torch.Tensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）または [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling)。設定（[GraniteDoclingConfig](/docs/transformers/v5.23.0/ja/model_doc/granite_docling#transformers.GraniteDoclingConfig)）と入力に応じて、さまざまな要素で構成されます。

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.Tensor`、形状 `(batch_size, hidden_size)`) -- 補助的な事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT系のモデルでは、線形層とtanh活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次の文予測（分類）目的から学習されます。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, GraniteDoclingForConditionalGeneration

>>> model = GraniteDoclingForConditionalGeneration.from_pretrained("ibm-granite/granite-for-docling-500m")
>>> processor = AutoProcessor.from_pretrained("ibm-granite/granite-for-docling-500m")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

