# Inkling 2 Mini

[Inkling 2 Mini](https://huggingface.co/collections/thinkingmachines/inkling-2) は、[Thinking Machines Lab](https://huggingface.co/thinkingmachines) によるマルチモーダルモデルで、テキストと画像を入力として受け取り、テキストを出力します。[Inkling 2 Small](./inkling2) をベースにしていますが、48層ではなく24層のデコーダー層のみを備えています。層数の減少は、6層から17層までの層を3回実行するループ機構によって補われています。ループの各パス間で情報は、学習されたメッセージパッシング機構を介して共有され、前回のパスの残差が各ループ層の attention と mixture-of-experts の入力に混合されます。デコーダーの hidden size は 2304 であり、各トークンは 128 のエキスパートのうち 8 つにルーティングされます。画像エンコーダー、トークナイザー、プロセッサーは、Inkling 2 Small のものと同一です。

Inkling 2 Miniには、ループパスの回数を可変にできる追加の[research checkpoint](https://huggingface.co/thinkingmachines/TML-d24-varloop-research)が付属しています。アーキテクチャはInkling 2 Miniのメインモデルと同一です。ループパスの回数を調整することで、速度と品質のトレードオフを調整できます。パス数が少ないほど高速ですが、パス数が多いほど品質が向上します。

Both checkpointsには、Transformersがモデルの読み込み時にデクアンタイズするNVFP4およびMXFP8の量子化レイヤーが含まれています。

**チェックポイント**

- [Inkling 2 Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini)
- [Inkling 2 Mini varloop 研究](https://huggingface.co/thinkingmachines/TML-d24-varloop-research)

## リソース

- [Thinking Machines ブログ](https://thinkingmachines.ai/news/inkling-2-mini/)
- [Hugging Face ブログ](https://huggingface.co/blog/inkling2mini)

```python
import torch

from transformers import pipeline

pipe = pipeline(
    "image-text-to-text", model="thinkingmachines/Inkling-2-Mini", dtype=torch.bfloat16, device_map="auto"
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
            },
            {"type": "text", "text": "What animal is in this image, and where is it?"},
        ],
    },
]

output = pipe(messages, max_new_tokens=1024, return_full_text=False, skip_special_tokens=False)
print(output[0]["generated_text"])
# <|message_model|><|content_thinking|>The user is asking about an animal in an image. Let me
# analyze what I see: a small wild feline with thick, fluffy fur dusted with snow, short legs, a
# broad face, and black stripes/spots.
# ...
# <|end_message|><|message_model|><|content_text|>The animal appears to be a Pallas’s cat (manul) —
# a small, bear-like wild cat with thick speckled/striped fur. It’s standing on snow inside what
# looks like a zoo or wildlife enclosure, with snow-covered birch/log branches and a chain-link
# fence in the background.<|end_message|><|content_model_end_sampling|>
```

```python
import torch

from transformers import AutoModelForMultimodalLM, AutoProcessor

model_id = "thinkingmachines/Inkling-2-Mini"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, dtype=torch.bfloat16, device_map="auto")

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
            },
            {"type": "text", "text": "What animal is in this image, and where is it?"},
        ],
    },
]

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)
input_len = inputs["input_ids"].shape[-1]

outputs = model.generate(**inputs, max_new_tokens=1024)
print(processor.decode(outputs[0][input_len:], skip_special_tokens=False))
# <|message_model|><|content_thinking|>The user is asking what animal is in the image and where it
# is. Let me analyze the image.
# ...
# <|end_message|><|message_model|><|content_text|>The animal appears to be a Pallas’s cat (manul), a
# stocky small wild cat with thick, snow-dusted fur. It is standing on snow, likely inside a zoo or
# wildlife enclosure — you can see birch/aspen-like posts and chain-link fencing in the
# background.<|end_message|><|content_model_end_sampling|>
```

```python
import torch

from transformers import AutoModelForMultimodalLM, AutoProcessor

model_id = "thinkingmachines/TML-d24-varloop-research"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(
    model_id,
    dtype=torch.bfloat16,
    device_map="auto",
    text_config={"loop_num_passes": 3},  # number of loop passes, must be at least 1
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
            },
            {"type": "text", "text": "What animal is in this image, and where is it?"},
        ],
    },
]

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)
input_len = inputs["input_ids"].shape[-1]

outputs = model.generate(**inputs, max_new_tokens=1024)
print(processor.decode(outputs[0][input_len:], skip_special_tokens=False))
# <|message_model|><|content_thinking|>We need answer image question. Need identify animal and where
# is it.
# ...
# <|end_message|><|message_model|><|content_text|>The animal is a Pallas’s cat (a.k.a. Manul), a
# stocky, densely furred small wild cat. It’s in the snow outdoors in a cold setting—likely a winter
# enclosure/habitat—standing/walking on snow at the center of the
# image.<|end_message|><|content_model_end_sampling|>
```

## 注記

- Attentionがeagerモードでのみ実行されるのは、各レイヤーが相対位置バイアスとsinkを追加するためです。
- 短い畳み込みは、利用可能な場合は高速な GPU カーネルを使用します。`use_kernels=True` で読み込む場合は Hub カーネル、それ以外の場合はインストールされている [causal-conv1d](https://github.com/Dao-AILab/causal-conv1d) パッケージ（`pip install causal-conv1d`）を使用します。これらが利用できない場合、より低速な PyTorch 実装にフォールバックします。
- ループ層を1回通過するたびに、独自のキー、バリュー、および畳み込み状態が保持されるため、キャッシュにはレイヤー訪問ごとに1つのレイヤーが含まれます（公開されているチェックポイントでは48個です）。
- `output_hidden_states` と `output_attentions` は、レイヤーの訪問ごとに1つのエントリを返します。

## Inkling2LoopConfig[[transformers.Inkling2LoopConfig]]

#### transformers.Inkling2LoopConfig[[transformers.Inkling2LoopConfig]]

```python
transformers.Inkling2LoopConfig(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: transformers.models.inkling2_loop.configuration_inkling2_loop.Inkling2LoopTextConfig | dict | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_token_id: int = 200054)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/inkling2_loop/configuration_inkling2_loop.py#L181)

**パラメータ:**

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

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

image_token_id (`int`, *optional*, デフォルトは 200054) : 画像プレースホルダーのトークンインデックス。それぞれが1つの画像特徴量に置き換えられます。

This is the configuration class to store the configuration of a Inkling2LoopModel. It is used to instantiate a Inkling2 Loop model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini)

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

## Inkling2LoopTextConfig[[transformers.Inkling2LoopTextConfig]]

#### transformers.Inkling2LoopTextConfig[[transformers.Inkling2LoopTextConfig]]

```python
transformers.Inkling2LoopTextConfig(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 = 201024, unpadded_vocab_size: int = 200058, hidden_size: int = 2304, num_hidden_layers: int = 24, num_attention_heads: int = 24, num_key_value_heads: int = 8, head_dim: int = 128, swa_num_attention_heads: int = 24, swa_num_key_value_heads: int = 8, swa_head_dim: int = 128, sliding_window_size: int = 1024, d_rel: int = 16, rel_extent: int = 1024, log_scaling_n_floor: int = 8192, log_scaling_alpha: float = 0.1, layer_types: list[str] | None = None, max_position_embeddings: int = 1048576, rms_norm_eps: float = 1e-06, conv_kernel_size: int = 4, hidden_act: str = 'silu', moe_intermediate_size: int = 1152, n_routed_experts: int = 128, num_experts_per_tok: int = 8, route_scale: float = 8.0, attention_dropout: float = 0.0, initializer_range: float = 0.02, pad_token_id: int | None = None, bos_token_id: int | None = None, eos_token_id: int | None = 200006, qk_l2_clip_threshold: float = 22.627416997969522, rel_l2_clip_threshold: float = 8.0, n_layers_per_attn_res_block: int = 6, mlp_gate_softcap: float = 4.0, mlp_up_softcap: float = 25.0, final_logit_softcapping: float = 30.0, scoring_func: str = 'sigmoid', use_cache: bool = True, loop_layer_index_start: int = 6, loop_layer_index_end: int = 18, loop_num_passes: int = 3, loop_gate_rank: int = 64)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/inkling2_loop/configuration_inkling2_loop.py#L30)

**パラメータ:**

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

unpadded_vocab_size (`int`、*optional*、デフォルトは 200058) : 言語モデリングヘッドの出力サイズ。チェックポイントのアンエンベディングは`vocab_size`にパディングされ、読み込み時にパディングされた行は削除され、保存時にはゼロとして復元されます。

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

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

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

num_key_value_heads (`int`, *optional*, デフォルトは `8`) : 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` が使用されます。

head_dim (`int`、*任意*、デフォルトは`128`) : アテンションヘッドの次元です。None の場合、hidden_size // num_attention_heads がデフォルトとして使用されます。

swa_num_attention_heads (`int`、*optional*、デフォルトは 24) : スライディングウィンドウ層におけるアテンションヘッドの数。

swa_num_key_value_heads (`int`、*任意*、デフォルトは 8) : スライディングウィンドウ層におけるキー/バリューヘッドの数。

swa_head_dim (`int`、*optional*、デフォルトは 128) : スライディングウィンドウ層におけるクエリとキーのヘッドの次元数。

sliding_window_size (`int`、*任意*、デフォルトは 1024) : `layer_types` のエントリが `"hybrid_sliding"` であるレイヤーで使用されるスライディングアテンションウィンドウのサイズ。

d_rel (`int`、*optional*、デフォルトは 16) : 相対位置バイアスに混合される相対状態のヘッドごとの次元数。

rel_extent (`int`、*optional*、デフォルトは 1024) : フルアテンション層で相対位置バイアスが適用される、トークン単位のバックワード距離。

log_scaling_n_floor (`int`、*optional*、デフォルトは 8192) : フルアテンション層において、クエリと相対状態が対数的にスケーリングされる開始位置。

log_scaling_alpha (`float`、*任意*、デフォルト値は 0.1) : `log_scaling_n_floor` によって制御される対数スケーリングの強度。

layer_types (`list[str]`、*任意*) : 各レイヤーのインデックスとそのレイヤータイプを明示的にマッピングするリストです。指定しない場合、config の値に基づいて自動的に生成されます。

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

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

conv_kernel_size (`int`、*任意*、デフォルトは`4`) : 畳み込みカーネルのサイズ。

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

moe_intermediate_size (`int`, *optional*, デフォルトは `1152`) : ルーティングされたエキスパートのMLPの中間サイズ。

n_routed_experts (`int`、*任意*、デフォルトは`128`) : ルーティング対象のエクスパート数。

num_experts_per_tok (`int`、*任意*、デフォルトは`8`) : 各トークンをルーティングするエキスパートの数です。これは、トークン選択ルーティングにおける top-k の値です。

route_scale (`float`、*任意*、デフォルトは`8.0`) : スケーリング係数またはルーティングされたエキスパート。

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

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

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

bos_token_id (`int`, *任意*) : 語彙内でストリームの開始に使用されるトークン ID。

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

qk_l2_clip_threshold (`float`、*optional*、デフォルト値は 22.627416997969522) : 各クエリおよびキーのヘッドベクトルの最大 L2 ノルムです。このノルムを超える長いベクトルは、このノルムまでスケーリングされます。

rel_l2_clip_threshold (`float`、*optional*、デフォルトは 8.0) : 各相対状態ヘッドベクトルの最大 L2 ノルム。

n_layers_per_attn_res_block (`int`、*optional*、デフォルトは 6) : ブロックがアテンション残差のソースとなる前に、1 つのブロックに集約されるデコーダー層の数。

mlp_gate_softcap (`float`、*optional*、デフォルトは 4.0) : エキスパートのゲート投影の線形部分に適用されるソフトキャップ。

mlp_up_softcap (`float`、*任意*、デフォルトは 25.0) : エキスパートのアッププロジェクションに適用されるソフトキャップ。

final_logit_softcapping (`float`、*任意*、デフォルト値は 30.0) : 出力 logits に適用されるソフトキャップ。

scoring_func (`str`、*任意*、デフォルトは`"sigmoid"`) : ルーターのロジットをエキスパートスコアに変換するための活性化関数。

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

loop_layer_index_start (`int`、*任意*、デフォルトは 6) : 最初のループされたデコーダー層のインデックス。`n_layers_per_attn_res_block` の倍数である必要があります。

loop_layer_index_end (`int`、*任意*、デフォルトは 18) : 最後のループ対象デコーダー層のインデックス。`loop_layer_index_start` から `loop_layer_index_end - 1` までの層がループされます。`n_layers_per_attn_res_block` の倍数である必要があります。

loop_num_passes (`int`、*任意*、デフォルトは 3) : ループ回数。

loop_gate_rank (`int`, *optional*, デフォルトは 64) : 前回のパスの残差ブロックを現在のパスに混合するためのメッセージゲート投影のランクです。

This is the configuration class to store the configuration of a Inkling2LoopModel. It is used to instantiate a Inkling2 Loop model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini)

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

## Inkling2LoopPreTrainedModel[[transformers.Inkling2LoopPreTrainedModel]]

#### transformers.Inkling2LoopPreTrainedModel[[transformers.Inkling2LoopPreTrainedModel]]

```python
transformers.Inkling2LoopPreTrainedModel(config: PreTrainedConfig, *inputs, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1176)

**パラメータ:**

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

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

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

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

## Inkling2LoopTextModel[[transformers.Inkling2LoopTextModel]]

#### transformers.Inkling2LoopTextModel[[transformers.Inkling2LoopTextModel]]

```python
transformers.Inkling2LoopTextModel(config: Inkling2LoopTextConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1272)

**パラメータ:**

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

裸の Inkling2 Loop Text Modelは、上部に特定のヘッドを持たず、生の隠れ状態を出力します。

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

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

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1304)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/v5.24.1/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/v5.24.1/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/v5.24.1/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)

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

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

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

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

`MoeModelOutputWithPast`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（`None`）や入力に応じて、さまざまな要素で構成されます。

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

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

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

  自己注意ブロックおよび（`config.is_encoder_decoder=True` の場合、任意で）相互注意ブロックの事前計算済み隠れ状態（キーとバリュー）が含まれており、シーケンシャルデコーディングを高速化するために使用できます（`cache` 入力参照）。
- **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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **router_logits** (`tuple(torch.Tensor)`、*optional*、`output_router_probs=True` と `config.add_router_probs=True` が渡された場合、または `config.output_router_probs=True` の場合に返されます) -- 各層に対応する `torch.Tensor` のタプルで、形状は `(batch_size, sequence_length, num_experts)` です。

  MoE ルーターによって計算される生（raw）のルーター logits（softmax 後）であり、Mixture of Experts モデルの補助損失を計算するためにこれらの用語が使用されます。

## Inkling2LoopForCausalLM[[transformers.Inkling2LoopForCausalLM]]

#### transformers.Inkling2LoopForCausalLM[[transformers.Inkling2LoopForCausalLM]]

```python
transformers.Inkling2LoopForCausalLM(config: Inkling2LoopTextConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1465)

**パラメータ:**

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

因果言語モデリング用のInkling2 Loop Model。

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

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = 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.24.1/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1483)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/v5.24.1/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/v5.24.1/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/v5.24.1/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)

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

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

labels (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 因果言語モデリング損失を計算するためのラベル。インデックスは `[-100, 0, ..., config.vocab_size]` の範囲である必要があります（`input_ids` のドキュメント文字列を参照）。インデックスが `-100` に設定されたトークンは無視（マスク）され、損失は `[0, ..., config.vocab_size]` のラベルを持つトークンのみに対して計算されます。ラベルは内部で **シフト** されるため、`labels[..., 1:]` が `logits[..., :-1, :]` の予測に使用されます。`input_ids` と一致するシフトされていないラベルを渡してください（つまり `labels = input_ids`）。ラベルを渡す前に自分で **シフトしないでください**。ラベルがすでにシフトされている場合（シーケンス並列処理など）、`shift_labels` キーワード引数として渡してください。この場合、そのまま使用されます。損失を計算するには、`labels` を渡す必要があります。

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

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

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

`Inkling2LoopCausalLMOutputWithPast` または、`return_dict=False` が渡された場合、または `config.return_dict=False` の場合、`torch.Tensor` のタプル。設定（`None`）や入力に応じて、さまざまな要素で構成されます。

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

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

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 言語モデリングの損失(次のトークンの予測用)。
- **logits** (`torch.FloatTensor`、shape `(batch_size, sequence_length, config.vocab_size)`) -- 言語モデリングヘッドの予測スコア（SoftMax 適用前の各語彙トークンのスコア）。
- **cache** (`Cache`、*optional*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/v5.24.1/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。自己注意ブロック（および `config.is_encoder_decoder=True` の場合、クロスカレンス注意ブロック）の事前計算済み隠れ状態（キーとバリュー）を保持しており、これらはシーケンシャルデコーディングを高速化するために使用できます（`cache` 入力参照）。
- **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)` です。言語モデルのバックボーンにおける各層の出力時の隠れ状態と、任意の初期埋め込み出力です。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合、または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。アテンションの softmax 適用後の、言語モデルのバックボーンのアテンション重みです。
- **image_outputs** (`BaseModelOutputWithPooling`、*任意*) -- 画像エンコーダーの出力: `last_hidden_state`、`pooler_output`、`hidden_states` および `attentions`。画像が処理されなかった場合は `None`。
- **video_outputs** (`BaseModelOutputWithPooling`、*任意*) -- ビデオエンコーダーの出力: `last_hidden_state`、`pooler_output`、`hidden_states` および `attentions`。ビデオが処理されなかった場合は `None`。
- **audio_outputs** (`BaseModelOutputWithPooling`、*任意*) -- 音声エンコーダーの出力: `last_hidden_state`、`pooler_output`、`hidden_states` および `attentions`。音声が処理されなかった場合は `None`。
- **router_logits** (`tuple[torch.Tensor]`、*optional*、`output_router_logits=True` が渡された場合、または `config.add_router_probs=True` の場合に返されます) -- 各層に対応する `torch.Tensor` のタプルで、形状は `(batch_size, sequence_length, num_experts)` です。

  モデルのRouter logits。Mixture of Expertsモデルの補助損失を計算するのに役立ちます。

例:

```python
>>> import torch
>>> from transformers import AutoTokenizer, Inkling2LoopForCausalLM

>>> tokenizer = AutoTokenizer.from_pretrained("thinkingmachines/Inkling-2-Mini")
>>> model = Inkling2LoopForCausalLM.from_pretrained(
...     "thinkingmachines/Inkling-2-Mini", dtype=torch.bfloat16, device_map="auto"
... )

>>> messages = [{"role": "user", "content": "Explain in one sentence why the sky is usually blue."}]
>>> inputs = tokenizer.apply_chat_template(
...     messages,
...     tokenize=True,
...     add_generation_prompt=True,
...     return_dict=True,
...     return_tensors="pt",
... ).to(model.device)
>>> input_len = inputs["input_ids"].shape[-1]

>>> outputs = model.generate(**inputs, max_new_tokens=1024)
>>> print(tokenizer.decode(outputs[0][input_len:], skip_special_tokens=False))
```

## Inkling2LoopModel[[transformers.Inkling2LoopModel]]

#### transformers.Inkling2LoopModel[[transformers.Inkling2LoopModel]]

```python
transformers.Inkling2LoopModel(config: Inkling2LoopConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1570)

**パラメータ:**

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

言語モデリングヘッドを備えないビジョンバックボーンと言語モデルから構成されるベースのInkling2Loopモデル。

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

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1618)

**パラメータ:**

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

pixel_values (`torch.Tensor`、shape `(batch_size, num_channels, image_size, image_size)`、*optional*) : 入力画像に対応するテンソルです。ピクセル値は `image_processor_class` を使用して取得できます。詳細は `image_processor_class.__call__` を参照してください（`processor_class` は画像の処理に `image_processor_class` を使用します）。

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`、*任意*) : 各画像の時間軸、高さ、幅。言語モデルの画像トークン単位で数えます。

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)

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

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

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

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

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

`Inkling2LoopModelOutputWithPast`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（`None`）や入力に応じて、さまざまな要素で構成されます。

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

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- 言語モデルのバックボーンの最終層の出力における、隠れ状態のシーケンスです。`cache` が使用されている場合、shape `(batch_size, 1, hidden_size)` のシーケンスの最後の隠れ状態のみが出力されます。
- **cache** (`Cache`、*optional*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/v5.24.1/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。自己注意ブロック（および `config.is_encoder_decoder=True` の場合、クロスカレンス注意ブロック）の事前計算済み隠れ状態（キーとバリュー）を保持しており、これらはシーケンシャルデコーディングを高速化するために使用できます（`cache` 入力参照）。
- **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)` です。言語モデルのバックボーンにおける各層の出力時の隠れ状態と、任意の初期埋め込み出力です。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合、または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。アテンションの softmax 適用後の、言語モデルのバックボーンのアテンション重みです。
- **image_outputs** (`BaseModelOutputWithPooling`、*任意*) -- 画像エンコーダーの出力: `last_hidden_state`、`pooler_output`、`hidden_states` および `attentions`。画像が処理されなかった場合は `None`。
- **video_outputs** (`BaseModelOutputWithPooling`、*任意*) -- ビデオエンコーダーの出力: `last_hidden_state`、`pooler_output`、`hidden_states` および `attentions`。ビデオが処理されなかった場合は `None`。
- **audio_outputs** (`BaseModelOutputWithPooling`、*任意*) -- 音声エンコーダーの出力: `last_hidden_state`、`pooler_output`、`hidden_states` および `attentions`。音声が処理されなかった場合は `None`。
- **router_logits** (`tuple[torch.Tensor]`、*optional*、`output_router_logits=True` が渡された場合、または `config.add_router_probs=True` の場合に返されます) -- 各層に対応する `torch.Tensor` のタプルで、形状は `(batch_size, sequence_length, num_experts)` です。

  モデルのRouter logits。Mixture of Expertsモデルの補助損失を計算するのに役立ちます。

例:

```python
>>> import torch
>>> from transformers import AutoProcessor, Inkling2LoopModel

>>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Mini")
>>> model = Inkling2LoopModel.from_pretrained(
...     "thinkingmachines/Inkling-2-Mini", dtype=torch.bfloat16, device_map="auto"
... )

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {
...                 "type": "image",
...                 "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
...             },
...             {"type": "text", "text": "What animal is in this image, and where is it?"},
...         ],
...     },
... ]

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

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
```

## Inkling2LoopForConditionalGeneration[[transformers.Inkling2LoopForConditionalGeneration]]

#### transformers.Inkling2LoopForConditionalGeneration[[transformers.Inkling2LoopForConditionalGeneration]]

```python
transformers.Inkling2LoopForConditionalGeneration(config: Inkling2LoopConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1720)

**パラメータ:**

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

言語モデリングヘッドを備えないビジョンバックボーンと言語モデルから構成されるベースのInkling2Loopモデル。

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

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = 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/v5.24.1/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1742)

**パラメータ:**

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

pixel_values (`torch.Tensor`、shape `(batch_size, num_channels, image_size, image_size)`、*optional*) : 入力画像に対応するテンソルです。ピクセル値は `image_processor_class` を使用して取得できます。詳細は `image_processor_class.__call__` を参照してください（`processor_class` は画像の処理に `image_processor_class` を使用します）。

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`、*任意*) : 各画像の時間軸、高さ、幅。言語モデルの画像トークン単位で数えます。

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)

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

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

labels (`torch.LongTensor`、形状 `(batch_size, sequence_length)`、*任意*) : マスク言語モデリング損失を計算するためのラベル。インデックスは `[0, ..., config.vocab_size]` の範囲内であるか、-100 である必要があります（`input_ids` のドキュメント文字列を参照）。インデックスが `-100` に設定されたトークンは無視（マスク）され、損失は `[0, ..., config.vocab_size]` の範囲内のラベルを持つトークンに対してのみ計算されます。

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

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

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

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

`Inkling2LoopCausalLMOutputWithPast` または、`return_dict=False` が渡された場合、または `config.return_dict=False` の場合、`torch.Tensor` のタプル。設定（`None`）や入力に応じて、さまざまな要素で構成されます。

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

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

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 言語モデリングの損失(次のトークンの予測用)。
- **logits** (`torch.FloatTensor`、shape `(batch_size, sequence_length, config.vocab_size)`) -- 言語モデリングヘッドの予測スコア（SoftMax 適用前の各語彙トークンのスコア）。
- **cache** (`Cache`、*optional*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/v5.24.1/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。自己注意ブロック（および `config.is_encoder_decoder=True` の場合、クロスカレンス注意ブロック）の事前計算済み隠れ状態（キーとバリュー）を保持しており、これらはシーケンシャルデコーディングを高速化するために使用できます（`cache` 入力参照）。
- **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)` です。言語モデルのバックボーンにおける各層の出力時の隠れ状態と、任意の初期埋め込み出力です。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合、または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。アテンションの softmax 適用後の、言語モデルのバックボーンのアテンション重みです。
- **image_outputs** (`BaseModelOutputWithPooling`、*任意*) -- 画像エンコーダーの出力: `last_hidden_state`、`pooler_output`、`hidden_states` および `attentions`。画像が処理されなかった場合は `None`。
- **video_outputs** (`BaseModelOutputWithPooling`、*任意*) -- ビデオエンコーダーの出力: `last_hidden_state`、`pooler_output`、`hidden_states` および `attentions`。ビデオが処理されなかった場合は `None`。
- **audio_outputs** (`BaseModelOutputWithPooling`、*任意*) -- 音声エンコーダーの出力: `last_hidden_state`、`pooler_output`、`hidden_states` および `attentions`。音声が処理されなかった場合は `None`。
- **router_logits** (`tuple[torch.Tensor]`、*optional*、`output_router_logits=True` が渡された場合、または `config.add_router_probs=True` の場合に返されます) -- 各層に対応する `torch.Tensor` のタプルで、形状は `(batch_size, sequence_length, num_experts)` です。

  モデルのRouter logits。Mixture of Expertsモデルの補助損失を計算するのに役立ちます。

例:

```python
>>> import torch
>>> from transformers import AutoProcessor, Inkling2LoopForConditionalGeneration

>>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Mini")
>>> model = Inkling2LoopForConditionalGeneration.from_pretrained(
...     "thinkingmachines/Inkling-2-Mini", dtype=torch.bfloat16, device_map="auto"
... )

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {
...                 "type": "image",
...                 "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
...             },
...             {"type": "text", "text": "What animal is in this image, and where is it?"},
...         ],
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     add_generation_prompt=True,
...     return_dict=True,
...     return_tensors="pt",
... ).to(model.device)
>>> input_len = inputs["input_ids"].shape[-1]

>>> outputs = model.generate(**inputs, max_new_tokens=1024)
>>> print(processor.decode(outputs[0][input_len:], skip_special_tokens=False))
```

