# GlmImage

## 概要

GLM-Image は、ハイブリッドな自己回帰 + 拡散デコーダーアーキテクチャを採用した画像生成モデルであり、視覚的忠実度と細部表現の上限を効果的に押し上げています。一般的な画像生成の品質については、業界標準の LDM ベースのアプローチと同等の水準にあり、知識集約型の画像生成シナリオでは顕著な優位性を示しています。

モデルアーキテクチャ: オートレグレッシブと拡散デコーダーのハイブリッド設計、

+ 自己回帰型ジェネレーター: [GLM-4-9B-0414](https://huggingface.co/zai-org/GLM-4-9B-0414)から初期化された9Bパラメータのモデルで、視覚トークンを組み込むために語彙が拡張されています。モデルはまず約256トークンのコンパクトなエンコーディングを生成し、その後1K〜4Kトークンに展開します。これにより、1K〜2Kの高解像度画像出力に対応します。
+ Diffusion Decoder: 潜在空間での画像デコードに特化した、単一ストリームのDiTアーキテクチャに基づく7Bパラメータのデコーダーです。Glyph Encoderテキストモジュールを備えており、画像内のテキストの正確なレンダリングを大幅に向上させます。

デカップルされた強化学習によるポストトレーニング：このモデルは、GRPOアルゴリズムを用いた細粒度かつモジュール化されたフィードバック戦略を導入し、セマンティック理解と視覚的詳細の品質を大幅に向上させます。

+ 自己回帰モジュール: 美観と意味の整合性に焦点を当てた低周波数のフィードバック信号を提供し、指示の追従性や芸術的表現力を向上させます。
+ Decoder モジュール: 詳細の忠実度とテキストの正確さを対象とした高周波フィードバックを提供し、非常にリアルなテクスチャ、ライティング、色再現、およびより正確なテキストレンダリングを実現します。

GLM-Imageは、単一のモデル内でテキストから画像への生成と画像から画像への生成の両方をサポートしています

+ テキストから画像へ: テキストの説明から高詳細な画像を生成し、情報密度の高いシナリオで特に優れたパフォーマンスを発揮します。
+ Image-to-image: 画像編集、スタイル転写、複数被写体の整合性、人物やオブジェクトのアイデンティティを保持した生成など、幅広いタスクに対応しています。

+ `GlmImageForConditionalGeneration` は GLM-Image モデルの AR 部分であり、完全な画像生成パイプラインについては、[こちら](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/glm_image)を参照してください。

このモデルは、[Raushan Turganbay](https://huggingface.co/RaushanTurganbay)氏と[Yuxuan Zhang](https://huggingface.co/ZHANGYUXUAN-zR)氏によって提供されました。

## 使用例

画像入力をGLM-Imageに与え、DITで使用するビジョントークンを生成します。

```python

import torch

from transformers import AutoProcessor, GlmImageForConditionalGeneration

model = GlmImageForConditionalGeneration.from_pretrained(
    pretrained_model_name_or_path="zai-org/GLM-Image/vision_language_encoder",
    device_map=torch.accelerator.current_accelerator()
)
processor = AutoProcessor.from_pretrained(
    pretrained_model_name_or_path="zai-org/GLM-Image/processor",
    use_fast=True
)

# Case1 T2I
prompt = "现代美食杂志风格的甜点制作教程图，主题为覆盆子慕斯蛋糕。整体布局干净明亮，分为四个主要区域：顶部左侧是黑色粗体标题“覆盆子慕斯蛋糕制作指南”，右侧搭配光线柔和的成品蛋糕特写照片，蛋糕呈淡粉色，表面点缀新鲜覆盆子与薄荷叶；左下方为配料清单区域，标题“配料”使用简洁字体，下方列有“面粉 150g”“鸡蛋 3个”“细砂糖 120g”“覆盆子果泥 200g”“明胶片 10g”“淡奶油 300ml”“新鲜覆盆子”等配料，每种配料旁配有简约线图标（如面粉袋、鸡蛋、糖罐等）；右下方是四个等大的步骤方框，每个方框内含高清微距实拍图及对应操作说明，从上到下依次为：步骤1展示打蛋器打发白色泡沫（对应说明“打发蛋白至干性发泡”），步骤2展示红白相间的混合物被刮刀翻拌（对应说明“轻柔翻拌果泥与面糊”），步骤3展示粉色液体被倒入圆形模具（对应说明“倒入模具并冷藏4小时”），步骤4展示成品蛋糕表面装饰覆盆子与薄荷叶（对应说明“用覆盆子和薄荷装饰”）；底部边缘设浅棕色信息条，左侧图标分别代表“准备时间：30分钟”“烹饪时间：20分钟”“份量：8人份”。整体色调以奶油白、淡粉色为主，背景带轻微纸质纹理，图文排版紧凑有序，信息层级分明。"
target_h, target_w = 1152, 768
use_reference_images = False
reference_image_paths = None

# ## Case2
# prompt = "Replace the background of the snow forest with an underground station featuring an automatic escalator."
# cond_0 = "cond.jpg"
# target_h, target_w = 1152, 768
# use_reference_images = True
# reference_image_paths = [cond_0]

## Case3
# prompt = "Make the man in the first figure and the child from the second image bow at the same time in a respectful KTV."
# cond_0 = "cond_0.jpg"
# cond_1 = "cond_1.jpg"
# target_h, target_w = 1152, 768
# use_reference_images = True
# reference_image_paths = [cond_0, cond_1]

def build_messages(prompt, use_reference_images, reference_image_paths):
    content = []
    if use_reference_images:
        for img_path in reference_image_paths:
            content.append({"type": "image", "url": img_path})
    content.append({"type": "text", "text": prompt})
    return [{"role": "user", "content": content}]

def compute_generation_params(image_grid_thw, use_reference_images):
    grid_sizes = []
    for i in range(image_grid_thw.shape[0]):
        t, h, w = image_grid_thw[i].tolist()
        grid_sizes.append(int(h * w))

    target_output_length = grid_sizes[0]

    if use_reference_images:
        max_new_tokens = grid_sizes[-1] + 1
        output_start_offset = 0
        output_length = grid_sizes[-1]
    else:
        total_tokens = sum(grid_sizes)
        max_new_tokens = total_tokens + 1
        output_start_offset = sum(grid_sizes[1:])
        output_length = target_output_length

    return max_new_tokens, output_start_offset, output_length

messages = build_messages(prompt, use_reference_images, reference_image_paths if use_reference_images else None)

inputs = processor.apply_chat_template(
    messages,
    target_h=target_h,
    target_w=target_w,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)

image_grid_thw = inputs.get('image_grid_thw')
print(f"image_grid_thw: {image_grid_thw}")

max_new_tokens, output_start_offset, output_length = compute_generation_params(
    image_grid_thw, use_reference_images
)

print(f"use_reference_images: {use_reference_images}")
print(f"max_new_tokens: {max_new_tokens}")
print(f"output_start_offset: {output_start_offset}")
print(f"output_length: {output_length}")

outputs = model.generate(
    **inputs,
    max_new_tokens=max_new_tokens,
    do_sample=True
)

input_length = inputs["input_ids"].shape[-1]
output_tokens = outputs[0][input_length:][output_start_offset:output_start_offset + output_length]
print(f"Input length: {input_length}")
print(f"Total generated tokens: {outputs[0].shape[-1] - input_length}")
print(f"Extracted output tokens shape: {output_tokens.shape}")
print(f"Output tokens: {output_tokens}")
```

## GlmImageConfig[[transformers.GlmImageConfig]]

#### transformers.GlmImageConfig[[transformers.GlmImageConfig]]

```python
transformers.GlmImageConfig(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, vq_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_token_id: int = 167855, image_start_token_id: int = 16384, image_end_token_id: int = 16385, tie_word_embeddings: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/configuration_glm_image.py#L149)

**パラメータ:**

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

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

vq_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *任意*) : ベクトル量子化モジュールの設定辞書。

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

image_start_token_id (`int`, *optional*, デフォルトは 16384) : 画像の開始をエンコードするための画像開始トークンのインデックスです。

image_end_token_id (`int`、*optional*、デフォルトは 16385) : 画像の終了をエンコードするための画像終了トークンのインデックス。

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

これは GlmImageModel の設定を保存するための設定クラスです。指定された引数に基づいて Glm Image モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[zai-org/GLM-Image](https://huggingface.co/zai-org/GLM-Image) と同様の設定が得られます。

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

```python
>>> from transformers import Glm4vForConditionalGeneration, Glm4vConfig

>>> # Initializing a GLM-Image style configuration
>>> configuration = Glm4vConfig()

>>> # Initializing a model from the GLM-Image style configuration
>>> model = Glm4vForConditionalGeneration(configuration)

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

## GlmImageVisionConfig[[transformers.GlmImageVisionConfig]]

#### transformers.GlmImageVisionConfig[[transformers.GlmImageVisionConfig]]

```python
transformers.GlmImageVisionConfig(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, depth: int = 40, hidden_size: int = 1536, hidden_act: str = 'gelu', attention_bias: bool = True, attention_dropout: float | int = 0.0, num_heads: int = 16, in_channels: int = 3, image_size: int | list[int] | tuple[int, int] = 2048, patch_size: int | list[int] | tuple[int, int] = 16, spatial_merge_size: int = 1, intermediate_size: int = 6144, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/configuration_glm_image.py#L43)

**パラメータ:**

depth (`int`、*任意*、デフォルトは `40`) : ビジョンエンコーダーの Transformer レイヤー数。

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

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

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

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

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

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

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

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

spatial_merge_size (`int`、*optional*、デフォルトは`1`) : 近接するパッチをマージしてビジュアルトークンの数を削減するために使用される、空間マージウィンドウのサイズです。

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

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

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

これは GlmImageModel の設定を保存するための設定クラスです。指定された引数に基づいて Glm Image モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[zai-org/GLM-Image](https://huggingface.co/zai-org/GLM-Image) と同様の設定が得られます。

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

例:

```python
>>> from transformers import GlmImageVisionConfig, GlmImageVisionModel

>>> # Initializing a GlmImageVisionConfig GLM-Image style configuration
>>> configuration = GlmImageVisionConfig()

>>> # Initializing a model (with random weights) from the GLM-Image configuration
>>> model = GlmImageVisionModel(configuration)

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

## GlmImageTextConfig[[transformers.GlmImageTextConfig]]

#### transformers.GlmImageTextConfig[[transformers.GlmImageTextConfig]]

```python
transformers.GlmImageTextConfig(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 = 168064, hidden_size: int = 4096, intermediate_size: int = 13696, num_hidden_layers: int = 40, num_attention_heads: int = 32, num_key_value_heads: int | None = 2, hidden_act: str = 'silu', max_position_embeddings: int = 131072, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, attention_dropout: float | int = 0.0, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, pad_token_id: int = 167841, vision_vocab_size: int = 16512, attention_bias: bool = True, eos_token_id: int | list[int] | None = 16385)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/configuration_glm_image.py#L82)

**パラメータ:**

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

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

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

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

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

num_key_value_heads (`int`、*任意*、デフォルトは `2`) : 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`、*任意*、デフォルトは `131072`) : このモデルが使用される可能性のある最大シーケンス長です。

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

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

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

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

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

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

vision_vocab_size (`int`、*任意*、デフォルトは 16512) : GlmImage モデルのビジョン語彙サイズ。[GlmImageVisionModel](/docs/transformers/main/ja/model_doc/glm_image#transformers.GlmImageVisionModel) を呼び出す際に渡す `inputs_ids` で表現できるトークンの種類数を定義します。

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

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

これは GlmImageModel の設定を保存するための設定クラスです。指定された引数に基づいて Glm Image モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[zai-org/GLM-Image](https://huggingface.co/zai-org/GLM-Image) と同様の設定が得られます。

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

例:

```python
>>> from transformers import GlmImageTextModel, GlmImageConfig

>>> # Initializing a GlmImageConfig style configuration
>>> configuration = GlmImageConfig()

>>> # Initializing a model from the GlmImageConfig style configuration
>>> model = GlmImageTextModel(configuration)

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

## GlmImageVQVAEConfig[[transformers.GlmImageVQVAEConfig]]

#### transformers.GlmImageVQVAEConfig[[transformers.GlmImageVQVAEConfig]]

```python
transformers.GlmImageVQVAEConfig(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, embed_dim: int = 2048, num_embeddings: int = 16384, latent_channels: int = 1536, in_channels: int = 3, initializer_range: float = 0.02)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/configuration_glm_image.py#L30)

**パラメータ:**

embed_dim (`int`、*任意*、デフォルトは`2048`) : 埋め込みおよび隠れ状態の次元数。

num_embeddings (`int`、*任意*、デフォルトは`16384`) : コードブック埋め込みの数。

latent_channels (`int`、*任意*、デフォルトは `1536`) : 潜在空間のチャネル数。

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

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

これは GlmImageModel の設定を保存するための設定クラスです。指定された引数に基づいて Glm Image モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[zai-org/GLM-Image](https://huggingface.co/zai-org/GLM-Image) と同様の設定が得られます。

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

## GlmImageImageProcessor[[transformers.GlmImageImageProcessor]]

#### transformers.GlmImageImageProcessor[[transformers.GlmImageImageProcessor]]

```python
transformers.GlmImageImageProcessor(**kwargs: *<class 'transformers.models.glm_image.image_processing_glm_image.GlmImageImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/image_processing_glm_image.py#L99)

**パラメータ:**

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*、デフォルト値は `{'shortest_edge' : 3136, 'longest_edge': 1003520}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*, デフォルトは `False`) : 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*、デフォルトは `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*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

min_pixels (`int`, *kwargs*, *optional*, デフォルトは `56 * 56`) : 画像をリサイズする際の最小ピクセル数。

max_pixels (`int`, *kwargs*, *optional*, デフォルトは `28 * 28 * 1280`) : 画像をリサイズする際の最大ピクセル数。

patch_size (`int`, *kwargs*, *optional*, デフォルトは 14) : ビジョンエンコーダーの空間パッチサイズです。

temporal_patch_size (`int`, *kwargs*, *任意*, デフォルトは 2) : ビジョンエンコーダーの時間方向のパッチサイズです。

merge_size (`int`, *kwargs*, *optional*, デフォルトは 2) : vision encoder から llm encoder へのマージサイズです。

GlmImageImageProcessorの画像プロセッサを構築します。

#### preprocess[[transformers.GlmImageImageProcessor.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']], **kwargs: *<class 'transformers.models.glm_image.image_processing_glm_image.GlmImageImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/image_processing_glm_image.py#L149)

**パラメータ:**

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` を設定してください。

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

min_pixels (`int`, *kwargs*, *optional*, デフォルトは `56 * 56`) : 画像をリサイズする際の最小ピクセル数。

max_pixels (`int`, *kwargs*, *optional*, デフォルトは `28 * 28 * 1280`) : 画像をリサイズする際の最大ピクセル数。

patch_size (`int`, *kwargs*, *optional*, デフォルトは 14) : ビジョンエンコーダーの空間パッチサイズです。

temporal_patch_size (`int`, *kwargs*, *任意*, デフォルトは 2) : ビジョンエンコーダーの時間方向のパッチサイズです。

merge_size (`int`, *kwargs*, *optional*, デフォルトは 2) : vision encoder から llm encoder へのマージサイズです。

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

- **data** (`dict`, *任意*) -- __call__/pad メソッドによって返されるリスト/配列/テンソルの辞書（'input_values'、'attention_mask' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。
- **skip_tensor_conversion** (`list[str]` または `set[str]`、*任意*) -- `tensor_type` が指定されている場合でも、テンソルに変換すべきでないキーのリストまたはセット。

## GlmImageImageProcessorPil[[transformers.GlmImageImageProcessorPil]]

#### transformers.GlmImageImageProcessorPil[[transformers.GlmImageImageProcessorPil]]

```python
transformers.GlmImageImageProcessorPil(**kwargs: *<class 'transformers.models.glm_image.image_processing_pil_glm_image.GlmImageImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/image_processing_pil_glm_image.py#L97)

**パラメータ:**

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*、デフォルト値は `{'shortest_edge' : 3136, 'longest_edge': 1003520}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*, デフォルトは `False`) : 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*、デフォルトは `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*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

min_pixels (`int`, *kwargs*, *optional*, デフォルトは `56 * 56`) : 画像をリサイズする際の最小ピクセル数。

max_pixels (`int`, *kwargs*, *optional*, デフォルトは `28 * 28 * 1280`) : 画像をリサイズする際の最大ピクセル数。

patch_size (`int`, *kwargs*, *optional*, デフォルトは 14) : ビジョンエンコーダーの空間パッチサイズです。

temporal_patch_size (`int`, *kwargs*, *任意*, デフォルトは 2) : ビジョンエンコーダーの時間方向のパッチサイズです。

merge_size (`int`, *kwargs*, *optional*, デフォルトは 2) : vision encoder から llm encoder へのマージサイズです。

GlmImageImageProcessorの画像プロセッサを構築します。

#### preprocess[[transformers.GlmImageImageProcessorPil.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']], **kwargs: *<class 'transformers.models.glm_image.image_processing_pil_glm_image.GlmImageImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/image_processing_pil_glm_image.py#L210)

**パラメータ:**

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` を設定してください。

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

min_pixels (`int`, *kwargs*, *optional*, デフォルトは `56 * 56`) : 画像をリサイズする際の最小ピクセル数。

max_pixels (`int`, *kwargs*, *optional*, デフォルトは `28 * 28 * 1280`) : 画像をリサイズする際の最大ピクセル数。

patch_size (`int`, *kwargs*, *optional*, デフォルトは 14) : ビジョンエンコーダーの空間パッチサイズです。

temporal_patch_size (`int`, *kwargs*, *任意*, デフォルトは 2) : ビジョンエンコーダーの時間方向のパッチサイズです。

merge_size (`int`, *kwargs*, *optional*, デフォルトは 2) : vision encoder から llm encoder へのマージサイズです。

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

- **data** (`dict`, *任意*) -- __call__/pad メソッドによって返されるリスト/配列/テンソルの辞書（'input_values'、'attention_mask' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。
- **skip_tensor_conversion** (`list[str]` または `set[str]`、*任意*) -- `tensor_type` が指定されている場合でも、テンソルに変換すべきでないキーのリストまたはセット。

## GlmImageProcessor[[transformers.GlmImageProcessor]]

#### transformers.GlmImageProcessor[[transformers.GlmImageProcessor]]

```python
transformers.GlmImageProcessor(image_processor = None, tokenizer = None, chat_template = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/processing_glm_image.py#L59)

**パラメータ:**

image_processor ([GlmImageProcessor](/docs/transformers/main/ja/model_doc/glm_image#transformers.GlmImageProcessor)、*任意*) : 画像プロセッサは必須の入力です。

tokenizer ([PreTrainedTokenizerFast](/docs/transformers/main/ja/main_classes/tokenizer#transformers.TokenizersBackend)、*任意*) : トークナイザーは必須の入力です。

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

GLM-Image の画像プロセッサと GLM-Image のトークナイザーを単一のプロセッサにラップする GLM-Image プロセッサを構築します。詳細は [__call__()](/docs/transformers/main/ja/model_doc/glm_image#transformers.GlmImageProcessor.__call__) および [decode()](/docs/transformers/main/ja/model_doc/wav2vec2#transformers.Wav2Vec2Processor.decode) を参照してください。

#### __call__[[transformers.GlmImageProcessor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: str | list[str] | list[list[str]] = None, **kwargs: *<class 'transformers.models.glm_image.processing_glm_image.GlmImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/processing_glm_image.py#L83)

**パラメータ:**

images (`PIL.Image.Image`、`np.ndarray`、`torch.Tensor`、`List[PIL.Image.Image]`、`List[np.ndarray]`、`List[torch.Tensor]`) : 準備対象の画像または画像のバッチです。各画像は、PIL 画像、NumPy 配列、または PyTorch テンソルのいずれかです。channels-first 形式と channels-last 形式の両方をサポートしています。

text (`str`、`List[str]`、`List[List[str]]`) : エンコード対象のシーケンスまたはシーケンスのバッチです。各シーケンスは、文字列または文字列のリスト（プレトークナイズ済み文字列）であることができます。シーケンスが文字列のリスト（プレトークナイズ済み）として提供される場合、`is_split_into_words=True` を設定する必要があります（シーケンスのバッチとの曖昧さを解消するため）。

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

**戻り値:** [BatchFeature](/docs/transformers/main/ja/main_classes/feature_extractor#transformers.BatchFeature)

以下のフィールドを持つ[BatchFeature](/docs/transformers/main/ja/main_classes/feature_extractor#transformers.BatchFeature):

- **input_ids** -- モデルに与えるトークンIDのリスト。`text`が`None`でない場合に返されます。
- **attention_mask** -- モデルが注意すべきトークンを指定するインデックスのリスト（`return_attention_mask=True`の場合、または`self.model_input_names`に*"attention_mask"*が含まれており`text`が`None`でない場合）。
- **pixel_values** -- モデルに渡すピクセル値。`images` が `None` でない場合に返されます。
- **image_grid_thw** -- LLMにおける画像の3次元グリッドのリスト。`images`が`None`でない場合に返されます。

モデルに対して1つまたは複数のシーケンスおよび画像を準備するための主要なメソッドです。`text`が`None`でない場合、テキストをエンコードするために、`text`および`kwargs`引数をPreTrainedTokenizerFastの[__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)に転送します。

## GlmImageVisionModel[[transformers.GlmImageVisionModel]]

#### transformers.GlmImageVisionModel[[transformers.GlmImageVisionModel]]

```python
transformers.GlmImageVisionModel(config: GlmImageVisionConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L615)

#### forward[[transformers.GlmImageVisionModel.forward]]

```python
forward(pixel_values: Tensor, grid_thw: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L641)

**パラメータ:**

pixel_values (`torch.Tensor`、shape `(total_patches, num_channels * patch_size * patch_size)`) : パックされたピクセル値。

grid_thw (`torch.Tensor`、shape `(num_images, 3)`) : 各画像の feature shape の時間軸、高さ、幅。

**戻り値:** `torch.Tensor`、形状は `(total_patches, hidden_size)`

隠れ状態。

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

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

## GlmImageTextModel[[transformers.GlmImageTextModel]]

#### transformers.GlmImageTextModel[[transformers.GlmImageTextModel]]

```python
transformers.GlmImageTextModel(config: GlmImageTextConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L770)

**パラメータ:**

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

特定のヘッドを上に持たず、生のhidden-statesを出力する素のGlm Image Text Model。

このモデルは [PreTrainedModel](/docs/transformers/main/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.GlmImageTextModel.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, **kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L794)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/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/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/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`を参照）。

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

`None` や入力に応じて、さまざまな要素で構成される [BaseModelOutputWithPast](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) または `torch.FloatTensor` のタプル(`return_dict=False` が渡された場合、または `config.return_dict=False` の場合)。

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

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(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/main/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.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

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

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

## GlmImageVQVAE[[transformers.GlmImageVQVAE]]

#### transformers.GlmImageVQVAE[[transformers.GlmImageVQVAE]]

```python
transformers.GlmImageVQVAE(config: GlmImageVQVAEConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L587)

**パラメータ:**

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

GlmImageで画像を離散トークンへエンコード/デコードするために使用されるVQ-VAEモデルです。このモデルは、[Oran Gafni、Adam Polyak、Oron Ashual、Shelly Sheynin、Devi Parikh、Yaniv Taigman](https://huggingface.co/papers/2203.13131)による論文「Make-a-scene: Scene-based text-to-image generation with human priors」に従っています。

このモデルは [PreTrainedModel](/docs/transformers/main/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.GlmImageVQVAE.forward]]

```python
forward(*args, **kwargs)
```

ドット区切りパス（例: `torch.float32`）に対するモック値: 属性アクセスのチェーン、呼び出しはパススルーデコレータとして動作し、`repr` はドット区切りパスを返し、ベースクラスとして使用するとプレーンな `type` ベースに置き換えられます（PEP 560 の `__mro_entries__`）。これにより、実際のサブクラスは通常のメタクラスを保持し、`inspect.signature` はモックのものではなく実際の `__init__` を読み取ります。

## GlmImageModel[[transformers.GlmImageModel]]

#### transformers.GlmImageModel[[transformers.GlmImageModel]]

```python
transformers.GlmImageModel(config: GlmImageConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L874)

**パラメータ:**

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

裸の Glm Image Modelは、上部に特定のヘッドを持たず、生の hidden-states を出力します。

このモデルは [PreTrainedModel](/docs/transformers/main/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.GlmImageModel.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.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, images_per_sample: typing.Optional[torch.LongTensor] = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L1224)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/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/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/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.Tensor`、shape `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [GlmImageImageProcessor](/docs/transformers/main/ja/model_doc/glm_image#transformers.GlmImageImageProcessor) を使用して取得できます。詳細については [GlmImageImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（[GlmImageProcessor](/docs/transformers/main/ja/model_doc/glm_image#transformers.GlmImageProcessor) は画像の処理に [GlmImageImageProcessor](/docs/transformers/main/ja/model_doc/glm_image#transformers.GlmImageImageProcessor) を使用します）。

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`、*任意*) : LLM における各画像のフィーチャー形状の時間軸、高さ、幅。

images_per_sample (`torch.LongTensor`、shape `(batch_size,)`、*任意*) : バッチ内の各サンプルにおける画像の数（ターゲットグリッドを含む）。

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

**戻り値:** `GlmImageModelOutputWithPast` または `tuple(torch.FloatTensor)`

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

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

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(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/main/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.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

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

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **rope_deltas** (`torch.LongTensor`、形状 `(batch_size, )`、*任意*) -- シーケンス長とマルチモーダル rope の間の rope インデックスの差です。この属性は非推奨であり、v5.20 で削除される予定です。代わりに `model.base_model.rope_deltas` を使用してください。

#### get_image_features[[transformers.GlmImageModel.get_image_features]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L1116)

**パラメータ:**

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

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`、*任意*) : LLM における各画像のフィーチャー形状の時間軸、高さ、幅。

images_per_sample (`torch.LongTensor`、shape `(batch_size,)`、*任意*) : バッチ内の各サンプルあたりの画像入力数。

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

config（[GlmImageConfig](/docs/transformers/main/ja/model_doc/glm_image#transformers.GlmImageConfig)）や入力に応じて、さまざまな要素で構成される [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling)、または `torch.FloatTensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。

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

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

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

## GlmImageForConditionalGeneration[[transformers.GlmImageForConditionalGeneration]]

#### transformers.GlmImageForConditionalGeneration[[transformers.GlmImageForConditionalGeneration]]

```python
transformers.GlmImageForConditionalGeneration(config: GlmImageConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L1345)

#### forward[[transformers.GlmImageForConditionalGeneration.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, labels: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, images_per_sample: typing.Optional[torch.LongTensor] = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L1378)

images_per_sample (`torch.LongTensor`、shape `(batch_size,)`、*任意*): バッチ内の各サンプルにおける画像の数（ターゲットグリッドを含む）。

例:

```python
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, GlmImageForConditionalGeneration

>>> model = GlmImageForConditionalGeneration.from_pretrained("zai-org/GLM-Image")
>>> processor = AutoProcessor.from_pretrained("zai-org/GLM-Image")

>>> messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "Add a truck of this photo.<sop>28 40<eop>"},
        ],
    },
]
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])

>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
```

#### get_image_features[[transformers.GlmImageForConditionalGeneration.get_image_features]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm_image/modeling_glm_image.py#L1361)

**パラメータ:**

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

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`、*任意*) : LLM における各画像のフィーチャー形状の時間軸、高さ、幅。

images_per_sample (`torch.LongTensor`、shape `(batch_size,)`、*任意*) : バッチ内の各サンプルにおける画像の数（ターゲットグリッドを含む）。

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

config（[GlmImageConfig](/docs/transformers/main/ja/model_doc/glm_image#transformers.GlmImageConfig)）や入力に応じて、さまざまな要素で構成される [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling)、または `torch.FloatTensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。

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

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

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

