Transformers documentation
Inkling 2 Small
This model was contributed to Hugging Face Transformers on 2026-11-11.
Inkling 2 Small
Inkling 2 Small is a multimodal model from Thinking Machines Lab that accepts text and image inputs and generates text outputs. It is intended for use in English and other languages, and across multiple coding languages. It keeps the decoder of Inkling, with learned relative attention, short causal convolutions and mixture-of-experts layers, and adds block attention residuals, gated attention with a learned sink and dynamic key/value convolutions. The language backbone consists of 48 mixture-of-experts decoder layers, each routing tokens to 8 of 384 experts. The model has 594B total and 17B active parameters. Images are encoded by a vision transformer based on the Perception Encoder and projected into the language model embeddings, one embedding per 40x40 pixel patch.
The model is released with two checkpoints:
Both checkpoints contain quantized layers. Inkling-2-Small has both NVFP4 and MXFP8 quantized decoder layers. Inkling-2-Small-MXFP8 contains only MXFP8 quantized layers. Currently only the Inkling-2-Small-MXFP8 checkpoint is supported.
Resources
import torch
from transformers import pipeline
pipe = pipeline(
"image-text-to-text", model="thinkingmachines/Inkling-2-Small-MXFP8", 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 to identify the animal and location in the image. Need answer based on visible content. The animal looks like a Pallas's cat (Otocolobus manul), also called manul:
# ...
# <|end_message|><|message_model|><|content_text|>The animal is a **Pallas’s cat** (also called a **manul**). It’s walking through **snow** in front of birch logs, likely in a **zoo or enclosed habitat**. The exact geographic location can’t be determined from the image alone; in the wild they’re native to parts of **Central Asia**.<|end_message|><|content_model_end_sampling|>import torch
from transformers import AutoModelForMultimodalLM, AutoProcessor
model_id = "thinkingmachines/Inkling-2-Small-MXFP8"
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 to identify the animal and location in the image. Need answer based on visible content. The animal looks like a Pallas's cat (Otocolobus manul), also called manul:
# ...
# <|end_message|><|message_model|><|content_text|>The animal is a **Pallas’s cat** (also called a **manul**). It’s walking through **snow** in front of birch logs, likely in a **zoo or enclosed habitat**. The exact geographic location can’t be determined from the image alone; in the wild they’re native to parts of **Central Asia**.<|end_message|><|content_model_end_sampling|>Notes
- Attention runs in eager mode only, because every layer adds a relative position bias and a sink.
Inkling2Config
class transformers.Inkling2Config
< 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.configuration_inkling2.Inkling2TextConfig | dict | None = Nonevision_config: transformers.models.inkling2.configuration_inkling2.Inkling2VisionConfig | dict | None = Noneimage_token_id: int = 200054 )
Parameters
- text_config (
Union[~models.inkling2.configuration_inkling2.Inkling2TextConfig, dict], optional) — The config object or dictionary of the text backbone. - vision_config (
Union[~models.inkling2.configuration_inkling2.Inkling2VisionConfig, dict], 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 Inkling2Model. It is used to instantiate a Inkling2 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-Small-MXFP8
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Inkling2TextConfig
class transformers.Inkling2TextConfig
< 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 = 4608num_hidden_layers: int = 48num_attention_heads: int = 48num_key_value_heads: int = 8head_dim: int = 128swa_num_attention_heads: int = 48swa_num_key_value_heads: int = 8swa_head_dim: int = 128sliding_window_size: int = 1024d_rel: int = 16rel_extent: int = 1024log_scaling_n_floor: int = 128000log_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 = 2304n_routed_experts: int = 384num_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 = True )
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) — Number of rows of the unembedding matrix that hold real tokens. Logits beyond it are dropped. - hidden_size (
int, optional, defaults to4608) — Dimension of the hidden representations. - num_hidden_layers (
int, optional, defaults to48) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to48) — 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 48) — 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 128000) — 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 to2304) — Intermediate size of the routed expert MLPs. - n_routed_experts (
int, optional, defaults to384) — 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.
This is the configuration class to store the configuration of a Inkling2Model. It is used to instantiate a Inkling2 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-Small-MXFP8
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Inkling2VisionConfig
class transformers.Inkling2VisionConfig
< 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 = Nonehidden_size: int = 1024intermediate_size: int | None = Nonenum_hidden_layers: int = 23num_attention_heads: int = 16num_channels: int = 3patch_size: int = 20hidden_act: str = 'gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0mlp_ratio: float = 4.0layer_scale_init_value: float = 0.1rope_parameters: dict | None = Nonespatial_merge_size: int = 2posemb_grid_size: int = 32projection_hidden_dim: int = 4096projector_bias: bool = Falsetext_hidden_size: int = 4608initializer_range: float = 0.02 )
Parameters
- hidden_size (
int, optional, defaults to1024) — Dimension of the hidden representations. - intermediate_size (
int, optional) — Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to23) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to16) — Number of attention heads for each attention layer in the Transformer decoder. - num_channels (
int, optional, defaults to3) — The number of input channels. - patch_size (
int, optional, defaults to20) — The size (resolution) of each patch. - hidden_act (
str, optional, defaults togelu) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - layer_norm_eps (
float, optional, defaults to1e-05) — The epsilon used by the layer normalization layers. - attention_dropout (
Union[float, int], optional, defaults to0.0) — The dropout ratio for the attention probabilities. - mlp_ratio (
float, optional, defaults to4.0) — Ratio of the MLP hidden dim to the embedding dim. - layer_scale_init_value (
float, optional, defaults to0.1) — Scale to use in the self-attention layers. 0.1 for base, 1e-6 for large. Set 0 to disable layer scale. - rope_parameters (
dict, optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value forrope_thetaand optionally parameters used for scaling in case you want to use RoPE with longermax_position_embeddings. - spatial_merge_size (
int, optional, defaults to 2) — Side, in native patches, of the square of patch features concatenated into one language model token. - posemb_grid_size (
int, optional, defaults to 32) — Side of the learned position embedding grid, interpolated to each image’s native patch grid. - projection_hidden_dim (
int, optional, defaults to 4096) — Hidden size of the MLP projecting merged patch features to the language model. - projector_bias (
bool, optional, defaults toFalse) — Whether the projection MLP uses biases. - text_hidden_size (
int, optional, defaults to 4608) — Hidden size of the language model the image features are projected to. - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
This is the configuration class to store the configuration of a Inkling2Model. It is used to instantiate a Inkling2 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-Small-MXFP8
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Inkling2PreTrainedModel
class transformers.Inkling2PreTrainedModel
< 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.
Inkling2TextModel
class transformers.Inkling2TextModel
< source >( config: Inkling2TextConfig )
Parameters
- config (Inkling2TextConfig) — 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 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 Inkling2TextModel 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.
Inkling2ForCausalLM
class transformers.Inkling2ForCausalLM
< source >( config: Inkling2TextConfig )
Parameters
- config (Inkling2TextConfig) — 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 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'> ) → Inkling2CausalLMOutputWithPast 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
Inkling2CausalLMOutputWithPast or tuple(torch.Tensor)
A Inkling2CausalLMOutputWithPast 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 Inkling2ForCausalLM 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.Tensorof shape(1,), optional, returned whenlabelsis provided) — Language modeling loss (for next-token prediction).logits (
torch.Tensorof shape(batch_size, sequence_length, config.text_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) that can be used (see
cacheinput) 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.
image_hidden_states (
torch.Tensor, optional) — Atorch.Tensorof size(batch_size, num_images, sequence_length, hidden_size). image_hidden_states of the model produced by the vision encoder after projecting last hidden state.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, Inkling2ForCausalLM
>>> tokenizer = AutoTokenizer.from_pretrained("thinkingmachines/Inkling-2-Small-MXFP8")
>>> model = Inkling2ForCausalLM.from_pretrained(
... "thinkingmachines/Inkling-2-Small-MXFP8", 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))Inkling2VisionModel
class transformers.Inkling2VisionModel
< source >( config: Inkling2VisionConfig )
Parameters
- config (Inkling2VisionConfig) — 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 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 >( pixel_values: Tensorimage_grid_thw: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
Parameters
- pixel_values (
torch.Tensorof shape(num_image_tokens, patch_size * spatial_merge_size, patch_size * spatial_merge_size, num_channels)) — Image patches in[-1, 1], one per language model image token, in raster order within each image. - image_grid_thw (
torch.Tensorof shape(num_images, 3)) — Temporal, height and width of each image, counted in language model image tokens.
Returns
BaseModelOutputWithPooling or tuple(torch.Tensor)
A BaseModelOutputWithPooling 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 (Inkling2Config) and inputs.
The Inkling2VisionModel 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.pooler_output (
torch.Tensorof shape(batch_size, hidden_size)) — Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.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.
Inkling2Model
class transformers.Inkling2Model
< source >( config: Inkling2Config )
Parameters
- config (Inkling2Config) — 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 Inkling2 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'> ) → Inkling2ModelOutputWithPast 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
Inkling2ModelOutputWithPast or tuple(torch.Tensor)
A Inkling2ModelOutputWithPast 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 Inkling2Model 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.If
cacheis 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 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.
image_hidden_states (
torch.Tensor, optional) — Atorch.Tensorof size(batch_size, num_images, sequence_length, hidden_size). image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.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, Inkling2Model
>>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Small-MXFP8")
>>> model = Inkling2Model.from_pretrained(
... "thinkingmachines/Inkling-2-Small-MXFP8", 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_stateInkling2ForConditionalGeneration
class transformers.Inkling2ForConditionalGeneration
< source >( config: Inkling2Config )
Parameters
- config (Inkling2Config) — 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 Inkling2 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'> ) → Inkling2CausalLMOutputWithPast 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
Inkling2CausalLMOutputWithPast or tuple(torch.Tensor)
A Inkling2CausalLMOutputWithPast 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 Inkling2ForConditionalGeneration 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.Tensorof shape(1,), optional, returned whenlabelsis provided) — Language modeling loss (for next-token prediction).logits (
torch.Tensorof shape(batch_size, sequence_length, config.text_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) that can be used (see
cacheinput) 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.
image_hidden_states (
torch.Tensor, optional) — Atorch.Tensorof size(batch_size, num_images, sequence_length, hidden_size). image_hidden_states of the model produced by the vision encoder after projecting last hidden state.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, Inkling2ForConditionalGeneration
>>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Small-MXFP8")
>>> model = Inkling2ForConditionalGeneration.from_pretrained(
... "thinkingmachines/Inkling-2-Small-MXFP8", 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))Inkling2ImageProcessor
class transformers.Inkling2ImageProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )
Parameters
- do_convert_rgb (
bool, kwargs, optional, defaults toTrue) — Whether to convert the image to RGB. - do_resize (
bool, kwargs, optional) — Whether to resize the image. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to{'height' -- 40, 'width': 40}): Describes the maximum input dimensions to the model. - default_to_square (
bool, kwargs, optional, defaults toTrue) — Whether to default to a square image when resizing, if size is an int. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, kwargs, optional, defaults toTrue) — Whether to rescale the image. - rescale_factor (
float, kwargs, optional, defaults to0.00392156862745098) — Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, kwargs, optional, defaults toTrue) — Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.5, 0.5, 0.5]) — Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to[0.5, 0.5, 0.5]) — Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, kwargs, optional) — Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:"channels_first"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - disable_grouping (
bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. - Returns stacked tensors if set to
'pt', otherwise returns a list of tensors. —
Constructs an Inkling2 image processor.
disable_grouping (bool, kwargs, optional):
Whether to disable grouping of images by size to process them individually and not in batches.
If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on
empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 image_seq_length (int, kwargs, optional):
The number of image tokens to be used for each image in the input.
Added for backward compatibility but this should be set as a processor attribute in future models.
Inkling2Processor
class transformers.Inkling2Processor
< source >( image_processor = Nonetokenizer = Nonechat_template = Noneimage_token = '<|unused_200054|>' )
Parameters
- image_processor (
Inkling2ImageProcessor) — The image processor is a required input. - tokenizer (
tokenizer_class) — The tokenizer is a required input. - chat_template (
str) — A Jinja template to convert lists of messages in a chat into a tokenizable string. - image_token (
str, optional, defaults to"<|unused_200054|>") — Placeholder token for each image soft-token slot, replaced by image features.
Constructs a Inkling2Processor which wraps a image processor and a tokenizer into a single processor.
Inkling2Processor offers all the functionalities of Inkling2ImageProcessor and tokenizer_class. See the ~Inkling2ImageProcessor and ~tokenizer_class for more information.