Transformers documentation
Inkling 2 Mini
This model was contributed to Hugging Face Transformers on 2026-11-21.
Inkling 2 Mini
Inkling 2 Mini is a multimodal model from Thinking Machines Lab that accepts text and image inputs and generates text outputs. It is based on Inkling 2 Small but has only 24 decoder layers instead of 48. The lower layer count is compensated for by a looping mechanism in which layers 6 to 17 run three times. Information is shared between loop passes through a learned message-passing mechanism that mixes the residuals of the previous pass into the attention and mixture-of-experts inputs of each loop layer. The decoder has a hidden size of 2304 and routes each token to 8 of 128 experts. The image encoder, tokenizer and processor are identical to those of Inkling 2 Small.
Inkling 2 Mini comes with an additional research checkpoint that supports a variable number of loop passes. The architecture is identical to the main Inkling 2 Mini model. The number of loop passes can be adjusted to trade off speed against quality. Fewer passes are faster, while more passes improve quality.
Both checkpoints contain NVFP4 and MXFP8 quantized layers that Transformers dequantizes when loading the model.
Checkpoints
Resources
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|>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|>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|>Notes
- Attention runs in eager mode only because every layer adds a relative position bias and a sink.
- The short convolutions use fast GPU kernels when available: Hub kernels when loading with
use_kernels=True, otherwise the causal-conv1d package if installed (pip install causal-conv1d). Without them, they fall back to a slower PyTorch implementation. - Every pass through the loop layers keeps its own keys, values and convolution states, so the cache has one layer per layer visit (48 for the released checkpoint).
output_hidden_statesandoutput_attentionsreturn one entry per layer visit.
Inkling2LoopConfig
class transformers.Inkling2LoopConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonetext_config: transformers.models.inkling2_loop.configuration_inkling2_loop.Inkling2LoopTextConfig | dict | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneimage_token_id: int = 200054 )
Parameters
- text_config (
Union[~models.inkling2_loop.configuration_inkling2_loop.Inkling2LoopTextConfig, dict], optional) — The config object or dictionary of the text backbone. - vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig], optional) — The config object or dictionary of the vision backbone. - image_token_id (
int, optional, defaults to 200054) — Token index of the image placeholders, each replaced by one image feature.
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
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Inkling2LoopTextConfig
class transformers.Inkling2LoopTextConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 201024unpadded_vocab_size: int = 200058hidden_size: int = 2304num_hidden_layers: int = 24num_attention_heads: int = 24num_key_value_heads: int = 8head_dim: int = 128swa_num_attention_heads: int = 24swa_num_key_value_heads: int = 8swa_head_dim: int = 128sliding_window_size: int = 1024d_rel: int = 16rel_extent: int = 1024log_scaling_n_floor: int = 8192log_scaling_alpha: float = 0.1layer_types: list[str] | None = Nonemax_position_embeddings: int = 1048576rms_norm_eps: float = 1e-06conv_kernel_size: int = 4hidden_act: str = 'silu'moe_intermediate_size: int = 1152n_routed_experts: int = 128num_experts_per_tok: int = 8route_scale: float = 8.0attention_dropout: float = 0.0initializer_range: float = 0.02pad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | None = 200006qk_l2_clip_threshold: float = 22.627416997969522rel_l2_clip_threshold: float = 8.0n_layers_per_attn_res_block: int = 6mlp_gate_softcap: float = 4.0mlp_up_softcap: float = 25.0final_logit_softcapping: float = 30.0scoring_func: str = 'sigmoid'use_cache: bool = Trueloop_layer_index_start: int = 6loop_layer_index_end: int = 18loop_num_passes: int = 3loop_gate_rank: int = 64 )
Parameters
- vocab_size (
int, optional, defaults to201024) — Vocabulary size of the model. Defines the number of different tokens that can be represented by theinput_ids. - unpadded_vocab_size (
int, optional, defaults to 200058) — Output size of the language modeling head. The checkpoint unembedding is padded tovocab_size, the padded rows are dropped on load and restored as zeros on save. - hidden_size (
int, optional, defaults to2304) — Dimension of the hidden representations. - num_hidden_layers (
int, optional, defaults to24) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to24) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to8) — This is the number of key_value heads that should be used to implement Grouped Query Attention. Ifnum_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), ifnum_key_value_heads=1the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out this paper. If it is not specified, will default tonum_attention_heads. - head_dim (
int, optional, defaults to128) — The attention head dimension. If None, it will default to hidden_size // num_attention_heads - swa_num_attention_heads (
int, optional, defaults to 24) — Number of attention heads in the sliding-window layers. - swa_num_key_value_heads (
int, optional, defaults to 8) — Number of key/value heads in the sliding-window layers. - swa_head_dim (
int, optional, defaults to 128) — Dimension of query and key heads in the sliding-window layers. - sliding_window_size (
int, optional, defaults to 1024) — Size of the sliding attention window used by layers whoselayer_typesentry is"hybrid_sliding". - d_rel (
int, optional, defaults to 16) — Per-head dimension of the relative states that are mixed into the relative position bias. - rel_extent (
int, optional, defaults to 1024) — Backward distance, in tokens, over which the relative position bias is applied in the full-attention layers. - log_scaling_n_floor (
int, optional, defaults to 8192) — Position from which queries and relative states are scaled up logarithmically in the full-attention layers. - log_scaling_alpha (
float, optional, defaults to 0.1) — Strength of the logarithmic scaling controlled bylog_scaling_n_floor. - layer_types (
list[str], optional) — A list that explicitly maps each layer index with its layer type. If not provided, it will be automatically generated based on config values. - max_position_embeddings (
int, optional, defaults to1048576) — The maximum sequence length that this model might ever be used with. - rms_norm_eps (
float, optional, defaults to1e-06) — The epsilon used by the rms normalization layers. - conv_kernel_size (
int, optional, defaults to4) — The size of the convolutional kernel. - hidden_act (
str, optional, defaults tosilu) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - moe_intermediate_size (
int, optional, defaults to1152) — Intermediate size of the routed expert MLPs. - n_routed_experts (
int, optional, defaults to128) — Number of routed experts. - num_experts_per_tok (
int, optional, defaults to8) — Number of experts to route each token to. This is the top-k value for the token-choice routing. - route_scale (
float, optional, defaults to8.0) — Scaling factor or routed experts. - attention_dropout (
float, optional, defaults to0.0) — The dropout ratio for the attention probabilities. - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - pad_token_id (
int, optional) — Token id used for padding in the vocabulary. - bos_token_id (
int, optional) — Token id used for beginning-of-stream in the vocabulary. - eos_token_id (
int, optional, defaults to200006) — Token id used for end-of-stream in the vocabulary. - qk_l2_clip_threshold (
float, optional, defaults to 22.627416997969522) — Maximum L2 norm of each query and key head vector. Longer vectors are scaled down to this norm. - rel_l2_clip_threshold (
float, optional, defaults to 8.0) — Maximum L2 norm of each relative-state head vector. - n_layers_per_attn_res_block (
int, optional, defaults to 6) — Number of decoder layers summed into one block before the block becomes a source of the attention residuals. - mlp_gate_softcap (
float, optional, defaults to 4.0) — Softcap applied to the linear part of the experts’ gate projection. - mlp_up_softcap (
float, optional, defaults to 25.0) — Softcap applied to the experts’ up projection. - final_logit_softcapping (
float, optional, defaults to 30.0) — Softcap applied to the output logits. - scoring_func (
str, optional, defaults to"sigmoid") — Activation turning the router logits into expert scores. - use_cache (
bool, optional, defaults toTrue) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant ifconfig.is_decoder=Trueor when the model is a decoder-only generative model. - loop_layer_index_start (
int, optional, defaults to 6) — Index of the first looped decoder layer. Must be a multiple ofn_layers_per_attn_res_block. - loop_layer_index_end (
int, optional, defaults to 18) — Index after the last looped decoder layer. Layersloop_layer_index_starttoloop_layer_index_end - 1are looped. Must be a multiple ofn_layers_per_attn_res_block. - loop_num_passes (
int, optional, defaults to 3) — Number of loops. - loop_gate_rank (
int, optional, defaults to 64) — Rank of the message gate projections that mix the residual blocks of the previous pass into the current one.
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
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Inkling2LoopPreTrainedModel
class transformers.Inkling2LoopPreTrainedModel
< source >( config: PreTrainedConfig*inputs**kwargs )
Parameters
- config (PreTrainedConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
A mock value for a dotted path (e.g. torch.float32): attribute access chains,
calls behave as pass-through decorators, repr is the dotted path, and using it
as a base class substitutes a plain-type base (PEP 560 __mro_entries__), so
real subclasses keep a normal metaclass and inspect.signature reads their real __init__ instead of a mock’s.
Inkling2LoopTextModel
class transformers.Inkling2LoopTextModel
< source >( config: Inkling2LoopTextConfig )
Parameters
- config (Inkling2LoopTextConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The bare Inkling2 Loop Text Model outputting raw hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeModelOutputWithPast or tuple(torch.Tensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - use_cache (
bool, optional) — If set toTrue,cachekey value states are returned and can be used to speed up decoding (seecache).
Returns
MoeModelOutputWithPast or tuple(torch.Tensor)
A MoeModelOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Inkling2LoopTextModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
last_hidden_state (
torch.Tensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
config.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seecacheinput) to speed up sequential decoding.hidden_states (
tuple(torch.Tensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.Tensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple(torch.Tensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
router_logits (
tuple(torch.Tensor), optional, returned whenoutput_router_probs=Trueandconfig.add_router_probs=Trueis passed or whenconfig.output_router_probs=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, sequence_length, num_experts).Raw router logits (post-softmax) that are computed by MoE routers, these terms are used to compute the auxiliary loss for Mixture of Experts models.
Inkling2LoopForCausalLM
class transformers.Inkling2LoopForCausalLM
< source >( config: Inkling2LoopTextConfig )
Parameters
- config (Inkling2LoopTextConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The Inkling2 Loop Model for causal language modeling.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Inkling2LoopCausalLMOutputWithPast or tuple(torch.Tensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Labels for computing the causal language modeling loss. Indices should be in[-100, 0, ..., config.vocab_size](seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size].The labels are shifted internally so that
labels[..., 1:]are used to predictlogits[..., :-1, :]. Pass unshifted labels matchinginput_ids(i.e.labels = input_ids). Do not shift the labels yourself before passing them.If the labels are already shifted (for example with sequence parallelism), pass them as the
shift_labelskeyword argument and they are used as is.labelsmust still be passed for the loss to be computed. - use_cache (
bool, optional) — If set toTrue,cachekey value states are returned and can be used to speed up decoding (seecache). - logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) — If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_ids(special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If atorch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).
Returns
Inkling2LoopCausalLMOutputWithPast or tuple(torch.Tensor)
A Inkling2LoopCausalLMOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Inkling2LoopForCausalLM forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) — Language modeling loss (for next-token prediction).logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide. Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally ifconfig.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seecacheinput) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size). Hidden-states of the language model backbone at the output of each layer plus the optional initial embedding outputs.attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length). Attention weights of the language model backbone, after the attention softmax.image_outputs (
BaseModelOutputWithPooling, optional) — Output of the image encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no images were processed.video_outputs (
BaseModelOutputWithPooling, optional) — Output of the video encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no videos were processed.audio_outputs (
BaseModelOutputWithPooling, optional) — Output of the audio encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no audio was processed.router_logits (
tuple[torch.Tensor], optional, returned whenoutput_router_logits=Trueis passed or whenconfig.add_router_probs=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, sequence_length, num_experts).Router logits of the model, useful to compute the auxiliary loss for Mixture of Experts models.
Example:
>>> 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
class transformers.Inkling2LoopModel
< source >( config: Inkling2LoopConfig )
Parameters
- config (Inkling2LoopConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The Base Inkling2Loop model which consists of a vision backbone and a language model without language modeling head.,
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Inkling2LoopModelOutputWithPast or tuple(torch.Tensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- pixel_values (
torch.Tensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained usingimage_processor_class. Seeimage_processor_class.__call__for details (processor_classusesimage_processor_classfor processing images). - image_grid_thw (
torch.LongTensorof shape(num_images, 3), optional) — Temporal, height and width of each image, counted in language model image tokens. - attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - use_cache (
bool, optional) — If set toTrue,cachekey value states are returned and can be used to speed up decoding (seecache). - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], optional) — Dict where keys are supported modalities and values are encoded outputs for that modality. Each encoded output is a tuple that consists of (pooler_output, optional:last_hidden_states, optional:hidden_states, optional:attentions)pooler_outputof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of multimmodal features of the encoder merged into text embeddings.
Returns
Inkling2LoopModelOutputWithPast or tuple(torch.Tensor)
A Inkling2LoopModelOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Inkling2LoopModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the language model backbone. Ifcacheis used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)is output.cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide. Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally ifconfig.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seecacheinput) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size). Hidden-states of the language model backbone at the output of each layer plus the optional initial embedding outputs.attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length). Attention weights of the language model backbone, after the attention softmax.image_outputs (
BaseModelOutputWithPooling, optional) — Output of the image encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no images were processed.video_outputs (
BaseModelOutputWithPooling, optional) — Output of the video encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no videos were processed.audio_outputs (
BaseModelOutputWithPooling, optional) — Output of the audio encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no audio was processed.router_logits (
tuple[torch.Tensor], optional, returned whenoutput_router_logits=Trueis passed or whenconfig.add_router_probs=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, sequence_length, num_experts).Router logits of the model, useful to compute the auxiliary loss for Mixture of Experts models.
Example:
>>> 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_stateInkling2LoopForConditionalGeneration
class transformers.Inkling2LoopForConditionalGeneration
< source >( config: Inkling2LoopConfig )
Parameters
- config (Inkling2LoopConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The Base Inkling2Loop model which consists of a vision backbone and a language model without language modeling head.,
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Inkling2LoopCausalLMOutputWithPast or tuple(torch.Tensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- pixel_values (
torch.Tensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained usingimage_processor_class. Seeimage_processor_class.__call__for details (processor_classusesimage_processor_classfor processing images). - image_grid_thw (
torch.LongTensorof shape(num_images, 3), optional) — Temporal, height and width of each image, counted in language model image tokens. - attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]. - use_cache (
bool, optional) — If set toTrue,cachekey value states are returned and can be used to speed up decoding (seecache). - logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) — If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_ids(special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If atorch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length). - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], optional) — Dict where keys are supported modalities and values are encoded outputs for that modality. Each encoded output is a tuple that consists of (pooler_output, optional:last_hidden_states, optional:hidden_states, optional:attentions)pooler_outputof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of multimmodal features of the encoder merged into text embeddings.
Returns
Inkling2LoopCausalLMOutputWithPast or tuple(torch.Tensor)
A Inkling2LoopCausalLMOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Inkling2LoopForConditionalGeneration forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) — Language modeling loss (for next-token prediction).logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide. Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally ifconfig.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seecacheinput) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size). Hidden-states of the language model backbone at the output of each layer plus the optional initial embedding outputs.attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length). Attention weights of the language model backbone, after the attention softmax.image_outputs (
BaseModelOutputWithPooling, optional) — Output of the image encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no images were processed.video_outputs (
BaseModelOutputWithPooling, optional) — Output of the video encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no videos were processed.audio_outputs (
BaseModelOutputWithPooling, optional) — Output of the audio encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no audio was processed.router_logits (
tuple[torch.Tensor], optional, returned whenoutput_router_logits=Trueis passed or whenconfig.add_router_probs=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, sequence_length, num_experts).Router logits of the model, useful to compute the auxiliary loss for Mixture of Experts models.
Example:
>>> 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))