# Inkling 2 Mini

[Inkling 2 Mini](https://huggingface.co/collections/thinkingmachines/inkling-2) 是 [Thinking Machines Lab](https://huggingface.co/thinkingmachines) 推出的多模态模型，支持文本和图像输入，并生成文本输出。该模型基于 [Inkling 2 Small](./inkling2)，但解码器层数仅为 24 层，而非 48 层。层数的减少通过一种循环机制得到补偿，其中第 6 至 17 层会运行三次。各循环轮次之间通过一种学习到的消息传递机制共享信息，该机制将上一轮次的残差混合到每个循环层的注意力和混合专家（mixture-of-experts）输入中。解码器的隐藏层大小为 2304，并将每个 token 路由到 128 个专家中的 8 个。其图像编码器、分词器和处理器与 Inkling 2 Small 完全相同。

Inkling 2 Mini 附带一个额外的 [research checkpoint](https://huggingface.co/thinkingmachines/TML-d24-varloop-research)，支持可变数量的循环遍历次数。其架构与主 Inkling 2 Mini 模型完全相同。循环遍历次数可以调整，以在速度和质量之间进行权衡。遍历次数越少，速度越快；遍历次数越多，质量越高。

这两个检查点均包含 NVFP4 和 MXFP8 量化层，Transformers 在加载模型时会对其进行反量化。

**检查点**

- [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 实现。
- 每次循环通过循环层时都会保留各自的键、值和卷积状态，因此缓存中每次访问层都会对应一个层（发布的检查点为 48 个）。
- `output_hidden_states` 和 `output_attentions` 会为每次访问层返回一个条目。

## 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/main/src/transformers/models/inkling2_loop/configuration_inkling2_loop.py#L181)

**参数：**

text_config (`Union[~models.inkling2_loop.configuration_inkling2_loop.Inkling2LoopTextConfig, dict]`, *可选*) : 文本骨干网络的配置对象或字典。

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：视觉骨干网络的配置对象或字典。

image_token_id (`int`, *可选*，默认为 200054)：图像占位符的 Token 索引，每个占位符将被替换为一个图像特征。

这是用于存储 Inkling2LoopModel 配置的类。它根据指定的参数实例化 Inkling2 Loop 模型，并定义模型架构。使用默认值实例化配置，将得到与 [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/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/main/src/transformers/models/inkling2_loop/configuration_inkling2_loop.py#L30)

**参数：**

vocab_size (`int`，*可选*，默认值为 `201024`)：模型的词汇表大小。定义了 `input_ids` 可以表示的不同 token 的数量。

unpadded_vocab_size (`int`, *可选*，默认为 200058) : 语言建模头的输出大小。检查点中的反嵌入会被填充至 `vocab_size`，加载时会丢弃填充的行，保存时则恢复为零。

hidden_size (`int`，*可选*，默认为 `2304`)：隐藏表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `24`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `24`)：Transformer 解码器中每个注意力层的注意力头数量。

num_key_value_heads (`int`, *可选*，默认为 `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`，*可选*，默认为 24)：滑动窗口层中的注意力头数量。

swa_num_key_value_heads (`int`，*可选*，默认为 8)：滑动窗口层中键/值头的数量。

swa_head_dim (`int`，*可选*，默认为 128)：滑动窗口层中查询和键头的维度。

sliding_window_size (`int`，*可选*，默认值为 1024)：`layer_types` 条目为 `"hybrid_sliding"` 的层所使用的滑动注意力窗口大小。

d_rel (`int`，*可选*，默认为 16)：混合到相对位置偏置中的相对状态的每头维度。

rel_extent (`int`，*可选*，默认为 1024)：在全注意力层中应用相对位置偏置的向后距离（以 token 为单位）。

log_scaling_n_floor (`int`，*可选*，默认值为 8192)：在全注意力层中，查询和相对状态从此位置开始进行对数缩放。

log_scaling_alpha (`float`, *可选*, 默认值为 0.1) : 由 `log_scaling_n_floor` 控制的对数缩放强度。

layer_types (`list[str]`，*可选*)：一个列表，用于显式地将每个层索引与其层类型进行映射。如果未提供，将根据配置值自动生成。

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`，*可选*，默认为 `1152`)：路由专家 MLP 的中间层大小。

n_routed_experts (`int`，*可选*，默认为 `128`)：路由专家的数量。

num_experts_per_tok (`int`，*可选*，默认为 `8`)：每个 token 路由到的专家数量。这是 token 选择路由的 top-k 值。

route_scale (`float`，*可选*，默认值为 `8.0`)：缩放因子或路由专家。

attention_dropout (`float`, *可选*, 默认为 `0.0`) : 注意力概率的 dropout 比率。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

pad_token_id (`int`, *可选*) : 词表中用于填充的 Token id。

bos_token_id (`int`, *可选*) : 词表中用于表示流开始的 Token id。

eos_token_id (`int`，*可选*，默认为 `200006`)：词汇表中用于表示流结束（end-of-stream）的 Token ID。

qk_l2_clip_threshold (`float`, *可选*，默认为 22.627416997969522) : 每个查询和键头向量的最大 L2 范数。较长的向量会被缩放至该范数。

rel_l2_clip_threshold (`float`，*可选*，默认值为 8.0)：每个相对状态头向量的最大 L2 范数。

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) : 应用于输出 logits 的软上限。

scoring_func (`str`，*可选*，默认为 `"sigmoid"`)：用于将路由器的 logits 转换为专家分数的激活函数。

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`, *可选*，默认为 64)：消息门控投影的秩，用于将上一轮传递中的残差块混合到当前轮中。

这是用于存储 Inkling2LoopModel 配置的类。它根据指定的参数实例化 Inkling2 Loop 模型，并定义模型架构。使用默认值实例化配置，将得到与 [thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/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/main/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1176)

**参数：**

config ([PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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/main/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1272)

**参数：**

config ([Inkling2LoopTextConfig](/docs/transformers/main/zh/model_doc/inkling2_loop#transformers.Inkling2LoopTextConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

未添加任何特定头部的裸 Inkling2 Loop Text Model，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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/main/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1304)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(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/main/zh/model_doc/inkling2_loop#transformers.Inkling2LoopTextModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **cache**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [Cache](/docs/transformers/main/zh/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)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，当传入 `output_router_probs=True` 且 `config.add_router_probs=True`，或当 `config.output_router_probs=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, sequence_length, num_experts)`。

  由 MoE 路由器计算的原始路由器 logits（softmax 之后），这些术语用于计算混合专家模型的辅助损失。

## Inkling2LoopForCausalLM[[transformers.Inkling2LoopForCausalLM]]

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

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1465)

**参数：**

config ([Inkling2LoopTextConfig](/docs/transformers/main/zh/model_doc/inkling2_loop#transformers.Inkling2LoopTextConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

用于因果语言建模的 Inkling2 Loop 模型。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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/main/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1483)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*) : 用于计算因果语言建模损失的标签。索引应在 `[-100, 0, ..., config.vocab_size]` 范围内（参见 `input_ids` 的文档字符串）。索引设置为 `-100` 的 token 将被忽略（被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。 标签会在**内部进行移位**，因此使用 `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` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

**返回：** `Inkling2LoopCausalLMOutputWithPast` 或 `tuple(torch.Tensor)`

`Inkling2LoopCausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[Inkling2LoopForCausalLM](/docs/transformers/main/zh/model_doc/inkling2_loop#transformers.Inkling2LoopForCausalLM) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.FloatTensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.FloatTensor`）—— 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/main/zh/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)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(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]`，*可选*，在传入 `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/main/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1570)

**参数：**

config ([Inkling2LoopConfig](/docs/transformers/main/zh/model_doc/inkling2_loop#transformers.Inkling2LoopConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

由视觉骨干网络和语言模型组成的 Base Inkling2Loop 模型，不包含语言建模头。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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/main/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1618)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

image_grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`，*可选*)：每张图片的时间、高度和宽度，以语言模型图像 token 为单位计数。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(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/main/zh/model_doc/inkling2_loop#transformers.Inkling2LoopModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.FloatTensor`）-- 语言模型主干最后一层输出的隐藏状态序列。如果使用 `cache`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列最后一个隐藏状态。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/main/zh/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)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(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]`，*可选*，在传入 `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/main/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1720)

**参数：**

config ([Inkling2LoopConfig](/docs/transformers/main/zh/model_doc/inkling2_loop#transformers.Inkling2LoopConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

由视觉骨干网络和语言模型组成的 Base Inkling2Loop 模型，不包含语言建模头。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/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/main/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py#L1742)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

image_grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`，*可选*)：每张图片的时间、高度和宽度，以语言模型图像 token 为单位计数。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(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` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

use_cache (`bool`, *可选*) : 如果设置为 `True`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

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` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[Inkling2LoopForConditionalGeneration](/docs/transformers/main/zh/model_doc/inkling2_loop#transformers.Inkling2LoopForConditionalGeneration) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.FloatTensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.FloatTensor`）—— 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/main/zh/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)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(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]`，*可选*，在传入 `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))
```

