Transformers documentation
T5Gemma 2
T5Gemma 2
T5Gemma 2 is a family of pretrained encoder-decoder large language models with strong multilingual, multimodal and long-context capability, available in 270M-270M, 1B-1B and 4B-4B parameters. Following T5Gemma, it is built via model adaptation (based on Gemma 3) using UL2. The architecture is similar to T5Gemma and Gemma 3, enhanced with tied word embeddings and merged self- and cross-attention to save model parameters.
Click on the T5Gemma 2 models in the right sidebar for more examples of how to apply T5Gemma 2 to different language tasks.
The example below demonstrates how to chat with the model with Pipeline or the AutoModel class, and from the command line.
import torch
from transformers import pipeline
generator = pipeline(
"image-text-to-text",
model="google/t5gemma-2-270m-270m",
dtype=torch.bfloat16,
device_map="auto",
)
generator(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",
text="<start_of_image> in this image, there is",
generate_kwargs={"do_sample": False, "max_new_tokens": 50},
)T5Gemma2Config
class transformers.T5Gemma2Config
< source >( encoder: typing.Union[transformers.models.t5gemma2.configuration_t5gemma2.T5Gemma2EncoderConfig, dict[str, typing.Any], NoneType] = None decoder: typing.Union[transformers.models.t5gemma2.configuration_t5gemma2.T5Gemma2DecoderConfig, dict[str, typing.Any], NoneType] = None is_encoder_decoder: bool = True dropout_rate: float = 0.0 attention_dropout: float = 0.0 classifier_dropout_rate: float = 0.0 initializer_range: float = 0.02 image_token_index: int = 256001 **kwargs )
Parameters
- encoder (
Union[T5Gemma2EncoderConfig, dict], optional, optional) — Configuration for the encoder. - decoder (
Union[T5Gemma2DecoderConfig, dict], optional, optional) — Configuration for the decoder. - is_encoder_decoder (bool, optional, optional, defaults to
True) — Whether the model is used as an encoder/decoder or not. - dropout_rate (
float, optional, defaults to 0.0) — The ratio for all dropout layers (following T5). - attention_dropout (
float, optional, defaults to 0.0) — The dropout ratio for attention. - classifier_dropout_rate (
float, optional, defaults to 0.0) — The dropout ratio for classifier (following T5). - initializer_range (
float, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - image_token_index (
int, optional, defaults to 256001) — The image token index to encode the image prompt. Defaults to 256001, which is right after the eoi_token_index. Note this is different from Gemma 3.
This is the configuration class to store the configuration of a T5Gemma2Model. It is used to instantiate an T5Gemma2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to a hypothetical balanced Gemma3 encoder-decoder model. e.g. google/t5gemma-2-270m-270m Configuration objects inherit from [PreTrainedConfig] and can be used to control the model outputs. Read the documentation from [PreTrainedConfig] for more information.
T5Gemma2TextConfig
class transformers.T5Gemma2TextConfig
< source >( vocab_size: typing.Optional[int] = 262208 hidden_size: typing.Optional[int] = 2304 intermediate_size: typing.Optional[int] = 9216 num_hidden_layers: typing.Optional[int] = 26 num_attention_heads: typing.Optional[int] = 8 num_key_value_heads: typing.Optional[int] = 4 head_dim: typing.Optional[int] = 256 hidden_activation: typing.Optional[str] = 'gelu_pytorch_tanh' max_position_embeddings: typing.Optional[int] = 131072 initializer_range: typing.Optional[float] = 0.02 rms_norm_eps: typing.Optional[int] = 1e-06 use_cache: typing.Optional[bool] = True pad_token_id: typing.Optional[int] = 0 eos_token_id: typing.Optional[int] = 1 bos_token_id: typing.Optional[int] = 2 tie_word_embeddings: typing.Optional[bool] = True attention_bias: typing.Optional[bool] = False attention_dropout: typing.Optional[float] = 0.0 query_pre_attn_scalar: typing.Optional[int] = 256 sliding_window: typing.Optional[int] = 4096 layer_types: typing.Optional[list[str]] = None final_logit_softcapping: typing.Optional[float] = None attn_logit_softcapping: typing.Optional[float] = None rope_parameters: typing.Union[transformers.modeling_rope_utils.RopeParameters, dict[str, transformers.modeling_rope_utils.RopeParameters], NoneType] = None use_bidirectional_attention: typing.Optional[bool] = False **kwargs )
Parameters
- vocab_size (
int, optional, defaults to 262208) — Vocabulary size of the T5Gemma2Text model. Defines the number of different tokens that can be represented by theinputs_idspassed when callingT5Gemma2TextModel - hidden_size (
int, optional, defaults to 2304) — Dimension of the hidden representations. - intermediate_size (
int, optional, defaults to 9216) — Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to 26) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to 8) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to 4) — 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 to 256) — The attention head dimension. - hidden_activation (
strorfunction, optional, defaults to"gelu_pytorch_tanh") — The non-linear activation function (function or string) in the decoder. Will default to"gelu_pytorch_tanh"if not specified."gelu_pytorch_tanh"uses an approximation of the"gelu"activation function. - max_position_embeddings (
int, optional, defaults to 131072) — The maximum sequence length that this model might ever be used with. - initializer_range (
float, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rms_norm_eps (
float, optional, defaults to 1e-06) — The epsilon used by the rms normalization layers. - 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=True. - pad_token_id (
int, optional, defaults to 0) — Padding token id. - eos_token_id (
int, optional, defaults to 1) — End of stream token id. - bos_token_id (
int, optional, defaults to 2) — Beginning of stream token id. - tie_word_embeddings (
bool, optional, defaults toTrue) — Whether to tie weight embeddings - attention_bias (
bool, defaults toFalse, optional, defaults toFalse) — Whether to use a bias in the query, key, value and output projection layers during self-attention. - attention_dropout (
float, optional, defaults to 0.0) — The dropout ratio for the attention probabilities. - query_pre_attn_scalar (
float, optional, defaults to 256) — Scaling factor used on the attention scores - sliding_window (
int, optional, defaults to 4096) — In T5Gemma2Text, every other layer uses sliding window attention. This is the size of the sliding window. - layer_types (
list, optional) — Attention pattern for each layer. - final_logit_softcapping (
float, optional) — Scaling factor when applying tanh softcapping on the logits. - attn_logit_softcapping (
float, optional) — Scaling factor when applying tanh softcapping on the attention scores. - rope_parameters (
RopeParameters, 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. - use_bidirectional_attention (
bool, optional, defaults toFalse) — If True, the model will attend to all text tokens instead of using a causal mask. This does not change behavior for vision tokens.
This is the configuration class to store the configuration of a T5Gemma2TextModel. It is used to instantiate an T5Gemma2Text
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 T5Gemma2Text-7B.
e.g. google/t5gemma2_text-7b
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the
documentation from PreTrainedConfig for more information.
>>> from transformers import T5Gemma2TextModel, T5Gemma2TextConfig
>>> # Initializing a T5Gemma2Text t5gemma2_text-7b style configuration
>>> configuration = T5Gemma2TextConfig()
>>> # Initializing a model from the t5gemma2_text-7b style configuration
>>> model = T5Gemma2TextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configT5Gemma2EncoderConfig
class transformers.T5Gemma2EncoderConfig
< source >( text_config: typing.Union[transformers.models.t5gemma2.configuration_t5gemma2.T5Gemma2TextConfig, dict[str, typing.Any], NoneType] = None vision_config: typing.Union[transformers.models.siglip.configuration_siglip.SiglipVisionConfig, dict[str, typing.Any], NoneType] = None mm_tokens_per_image: int = 256 boi_token_index: int = 255999 eoi_token_index: int = 256000 image_token_index: int = 262144 initializer_range: float = 0.02 **kwargs )
Parameters
- text_config (
Union[T5Gemma2EncoderTextConfig, dict], optional) — The config object of the text backbone. - vision_config (
Union[AutoConfig, dict], optional) — Custom vision config or dict. - mm_tokens_per_image (
int, optional, defaults to 256) — The number of tokens per image embedding. - boi_token_index (
int, optional, defaults to 255999) — The begin-of-image token index to wrap the image prompt. - eoi_token_index (
int, optional, defaults to 256000) — The end-of-image token index to wrap the image prompt. - image_token_index (
int, optional, defaults to 262144) — The image token index to encode the image prompt. - initializer_range (
float, optional, defaults to 0.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 T5Gemma2EncoderForConditionalGeneration. It is used to instantiate an
T5Gemma2EncoderForConditionalGeneration according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the PaliGemma-2B.
e.g. google/gemma-3-4b
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> from transformers import T5Gemma2EncoderForConditionalGeneration, T5Gemma2EncoderConfig, SiglipVisionConfig, T5Gemma2EncoderTextConfig
>>> # Initializing a Siglip-like vision config
>>> vision_config = SiglipVisionConfig()
>>> # Initializing a T5Gemma2Encoder Text config
>>> text_config = T5Gemma2EncoderTextConfig()
>>> # Initializing a T5Gemma2Encoder gemma-3-4b style configuration
>>> configuration = T5Gemma2EncoderConfig(vision_config, text_config)
>>> # Initializing a model from the gemma-3-4b style configuration
>>> model = T5Gemma2EncoderTextConfig(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configT5Gemma2DecoderConfig
class transformers.T5Gemma2DecoderConfig
< source >( vocab_size: typing.Optional[int] = 262208 hidden_size: typing.Optional[int] = 2304 intermediate_size: typing.Optional[int] = 9216 num_hidden_layers: typing.Optional[int] = 26 num_attention_heads: typing.Optional[int] = 8 num_key_value_heads: typing.Optional[int] = 4 head_dim: typing.Optional[int] = 256 hidden_activation: typing.Optional[str] = 'gelu_pytorch_tanh' max_position_embeddings: typing.Optional[int] = 131072 initializer_range: typing.Optional[float] = 0.02 rms_norm_eps: typing.Optional[int] = 1e-06 use_cache: typing.Optional[bool] = True pad_token_id: typing.Optional[int] = 0 eos_token_id: typing.Optional[int] = 1 bos_token_id: typing.Optional[int] = 2 tie_word_embeddings: typing.Optional[bool] = True attention_bias: typing.Optional[bool] = False attention_dropout: typing.Optional[float] = 0.0 query_pre_attn_scalar: typing.Optional[int] = 256 sliding_window: typing.Optional[int] = 4096 layer_types: typing.Optional[list[str]] = None final_logit_softcapping: typing.Optional[float] = None attn_logit_softcapping: typing.Optional[float] = None rope_parameters: typing.Union[transformers.modeling_rope_utils.RopeParameters, dict[str, transformers.modeling_rope_utils.RopeParameters], NoneType] = None use_bidirectional_attention: typing.Optional[bool] = False **kwargs )
Parameters
- vocab_size (
int, optional, defaults to 262208) — Vocabulary size of the T5Gemma2Decoder model. Defines the number of different tokens that can be represented by theinputs_idspassed when callingT5Gemma2DecoderModel - hidden_size (
int, optional, defaults to 2304) — Dimension of the hidden representations. - intermediate_size (
int, optional, defaults to 9216) — Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to 26) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to 8) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to 4) — 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 to 256) — The attention head dimension. - hidden_activation (
strorfunction, optional, defaults to"gelu_pytorch_tanh") — The non-linear activation function (function or string) in the decoder. Will default to"gelu_pytorch_tanh"if not specified."gelu_pytorch_tanh"uses an approximation of the"gelu"activation function. - max_position_embeddings (
int, optional, defaults to 131072) — The maximum sequence length that this model might ever be used with. - initializer_range (
float, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rms_norm_eps (
float, optional, defaults to 1e-06) — The epsilon used by the rms normalization layers. - 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=True. - pad_token_id (
int, optional, defaults to 0) — Padding token id. - eos_token_id (
int, optional, defaults to 1) — End of stream token id. - bos_token_id (
int, optional, defaults to 2) — Beginning of stream token id. - tie_word_embeddings (
bool, optional, defaults toTrue) — Whether to tie weight embeddings - attention_bias (
bool, defaults toFalse, optional, defaults toFalse) — Whether to use a bias in the query, key, value and output projection layers during self-attention. - attention_dropout (
float, optional, defaults to 0.0) — The dropout ratio for the attention probabilities. - query_pre_attn_scalar (
float, optional, defaults to 256) — Scaling factor used on the attention scores - sliding_window (
int, optional, defaults to 4096) — In T5Gemma2Decoder, every other layer uses sliding window attention. This is the size of the sliding window. - layer_types (
list, optional) — Attention pattern for each layer. - final_logit_softcapping (
float, optional) — Scaling factor when applying tanh softcapping on the logits. - attn_logit_softcapping (
float, optional) — Scaling factor when applying tanh softcapping on the attention scores. - rope_parameters (
RopeParameters, 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. - use_bidirectional_attention (
bool, optional, defaults toFalse) — If True, the model will attend to all text tokens instead of using a causal mask. This does not change behavior for vision tokens.
This is the configuration class to store the configuration of a T5Gemma2DecoderModel. It is used to instantiate an T5Gemma2Decoder
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 T5Gemma2Decoder-7B.
e.g. google/t5gemma2_text-7b
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the
documentation from PreTrainedConfig for more information.
>>> from transformers import T5Gemma2DecoderModel, T5Gemma2DecoderConfig
>>> # Initializing a T5Gemma2Decoder t5gemma2_text-7b style configuration
>>> configuration = T5Gemma2DecoderConfig()
>>> # Initializing a model from the t5gemma2_text-7b style configuration
>>> model = T5Gemma2DecoderModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configT5Gemma2Model
class transformers.T5Gemma2Model
< source >( config: T5Gemma2Config )
Parameters
- config (T5Gemma2Config) — 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 T5Gemma2 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] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None position_ids: typing.Optional[torch.LongTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None decoder_position_ids: typing.Optional[torch.LongTensor] = None encoder_outputs: typing.Optional[transformers.modeling_outputs.BaseModelOutput] = None past_key_values: typing.Optional[transformers.cache_utils.EncoderDecoderCache] = None inputs_embeds: typing.Optional[torch.Tensor] = None decoder_inputs_embeds: typing.Optional[torch.Tensor] = None use_cache: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.Seq2SeqModelOutput or tuple(torch.FloatTensor)
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.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using Gemma3ImageProcessor. See Gemma3ImageProcessor.call() for details (Gemma3Processor uses Gemma3ImageProcessor for processing images). - attention_mask (
torch.FloatTensorof 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]. - decoder_input_ids (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- decoder_attention_mask (
torch.BoolTensorof shape(batch_size, target_sequence_length), optional) — Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to make sure the model can only look at previous inputs in order to predict the future. - decoder_position_ids (
torch.LongTensorof shape(batch_size, decoder_sequence_length), optional) — Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range[0, config.decoder.n_positions - 1]. What are position IDs? - encoder_outputs (
~modeling_outputs.BaseModelOutput, optional) — Tuple consists of (last_hidden_state, optional:hidden_states, optional:attentions)last_hidden_stateof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. - past_key_values (
~cache_utils.EncoderDecoderCache, 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 thepast_key_valuesreturned 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
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare 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. - decoder_inputs_embeds (
torch.Tensorof shape(batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passingdecoder_input_idsyou can choose to directly pass an embedded representation. Ifpast_key_valuesis used, optionally only the lastdecoder_inputs_embedshave to be input (seepast_key_values). This is useful if you want more control over how to convertdecoder_input_idsindices into associated vectors than the model’s internal embedding lookup matrix.If
decoder_input_idsanddecoder_inputs_embedsare both unset,decoder_inputs_embedstakes the value ofinputs_embeds. - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - cache_position (
torch.LongTensorof shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
Returns
transformers.modeling_outputs.Seq2SeqModelOutput or tuple(torch.FloatTensor)
A transformers.modeling_outputs.Seq2SeqModelOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (T5Gemma2Config) and inputs.
-
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 decoder of the model.If
past_key_valuesis used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)is output. -
past_key_values (
EncoderDecoderCache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a EncoderDecoderCache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see
past_key_valuesinput) to speed up sequential decoding. -
decoder_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 decoder at the output of each layer plus the optional initial embedding outputs.
-
decoder_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).Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
-
cross_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).Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
-
encoder_last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. -
encoder_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 encoder at the output of each layer plus the optional initial embedding outputs.
-
encoder_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).Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
The T5Gemma2Model 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.
T5Gemma2ForConditionalGeneration
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None position_ids: typing.Optional[torch.LongTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None decoder_position_ids: typing.Optional[torch.LongTensor] = None encoder_outputs: typing.Optional[transformers.modeling_outputs.BaseModelOutput] = None past_key_values: typing.Optional[transformers.cache_utils.EncoderDecoderCache] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)
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.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using Gemma3ImageProcessor. See Gemma3ImageProcessor.call() for details (Gemma3Processor uses Gemma3ImageProcessor for processing images). - attention_mask (
torch.FloatTensorof 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]. - decoder_input_ids (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- decoder_attention_mask (
torch.BoolTensorof shape(batch_size, target_sequence_length), optional) — Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to make sure the model can only look at previous inputs in order to predict the future. - decoder_position_ids (
torch.LongTensorof shape(batch_size, decoder_sequence_length), optional) — Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range[0, config.decoder.n_positions - 1]. What are position IDs? - encoder_outputs (
~modeling_outputs.BaseModelOutput, optional) — Tuple consists of (last_hidden_state, optional:hidden_states, optional:attentions)last_hidden_stateof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. - past_key_values (
~cache_utils.EncoderDecoderCache, 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 thepast_key_valuesreturned 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
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare 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.FloatTensorof 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. - decoder_inputs_embeds (
torch.FloatTensorof shape(batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passingdecoder_input_idsyou can choose to directly pass an embedded representation. Ifpast_key_valuesis used, optionally only the lastdecoder_inputs_embedshave to be input (seepast_key_values). This is useful if you want more control over how to convertdecoder_input_idsindices into associated vectors than the model’s internal embedding lookup matrix.If
decoder_input_idsanddecoder_inputs_embedsare both unset,decoder_inputs_embedstakes the value ofinputs_embeds. - 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,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - cache_position (
torch.LongTensorof shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length. - logits_to_keep (
Union[int, torch.Tensor], 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
transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)
A transformers.modeling_outputs.Seq2SeqLMOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (T5Gemma2Config) and inputs.
-
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) — Language modeling loss. -
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). -
past_key_values (
EncoderDecoderCache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a EncoderDecoderCache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see
past_key_valuesinput) to speed up sequential decoding. -
decoder_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 decoder at the output of each layer plus the initial embedding outputs.
-
decoder_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).Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
-
cross_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).Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
-
encoder_last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. -
encoder_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 encoder at the output of each layer plus the initial embedding outputs.
-
encoder_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).Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
The T5Gemma2ForConditionalGeneration 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.
Example:
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, T5Gemma2ForConditionalGeneration
>>> model = T5Gemma2ForConditionalGeneration.from_pretrained("google/t5gemma-2-270m-270m")
>>> processor = AutoProcessor.from_pretrained("google/t5gemma-2-270m-270m")
>>> messages = [
... {
... "role": "user", "content": [
... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
... {"type": "text", "text": "Where is the cat standing?"},
... ]
... },
... ]
>>> inputs = processor.apply_chat_template(
... messages,
... tokenize=True,
... return_dict=True,
... return_tensors="pt",
... add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]T5Gemma2ForSequenceClassification
class transformers.T5Gemma2ForSequenceClassification
< source >( config: T5Gemma2Config )
Parameters
- config (T5Gemma2Config) — 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 T5Gemma2 Model with a sequence classification/regression head on top e.g. for GLUE tasks.
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] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.Tensor] = None decoder_position_ids: typing.Optional[torch.LongTensor] = None encoder_outputs: typing.Optional[transformers.modeling_outputs.BaseModelOutput] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)
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.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using Gemma3ImageProcessor. See Gemma3ImageProcessor.call() for details (Gemma3Processor uses Gemma3ImageProcessor for processing images). - 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]. - decoder_input_ids (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- decoder_attention_mask (
torch.Tensorof shape(batch_size, target_sequence_length), optional) — Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to make sure the model can only look at previous inputs in order to predict the future. - decoder_position_ids (
torch.LongTensorof shape(batch_size, decoder_sequence_length), optional) — Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range[0, config.decoder.n_positions - 1]. What are position IDs? - encoder_outputs (
~modeling_outputs.BaseModelOutput, optional) — Tuple consists of (last_hidden_state, optional:hidden_states, optional:attentions)last_hidden_stateof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. - inputs_embeds (
torch.FloatTensorof 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. - decoder_inputs_embeds (
torch.FloatTensorof shape(batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passingdecoder_input_idsyou can choose to directly pass an embedded representation. Ifpast_key_valuesis used, optionally only the lastdecoder_inputs_embedshave to be input (seepast_key_values). This is useful if you want more control over how to convertdecoder_input_idsindices into associated vectors than the model’s internal embedding lookup matrix.If
decoder_input_idsanddecoder_inputs_embedsare both unset,decoder_inputs_embedstakes the value ofinputs_embeds. - labels (
torch.LongTensorof shape(batch_size,), optional) — Labels for computing the sequence classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]. Ifconfig.num_labels == 1a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1a classification loss is computed (Cross-Entropy).
Returns
transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)
A transformers.modeling_outputs.SequenceClassifierOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (T5Gemma2Config) and inputs.
-
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) — Classification (or regression if config.num_labels==1) loss. -
logits (
torch.FloatTensorof shape(batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax). -
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 model 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).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The T5Gemma2ForSequenceClassification 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.
Example of single-label classification:
>>> import torch
>>> from transformers import AutoTokenizer, T5Gemma2ForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("google/t5gemma-2-270m-270m")
>>> model = T5Gemma2ForSequenceClassification.from_pretrained("google/t5gemma-2-270m-270m")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
...
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = T5Gemma2ForSequenceClassification.from_pretrained("google/t5gemma-2-270m-270m", num_labels=num_labels)
>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...Example of multi-label classification:
>>> import torch
>>> from transformers import AutoTokenizer, T5Gemma2ForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("google/t5gemma-2-270m-270m")
>>> model = T5Gemma2ForSequenceClassification.from_pretrained("google/t5gemma-2-270m-270m", problem_type="multi_label_classification")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = T5Gemma2ForSequenceClassification.from_pretrained(
... "google/t5gemma-2-270m-270m", num_labels=num_labels, problem_type="multi_label_classification"
... )
>>> labels = torch.sum(
... torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
... ).to(torch.float)
>>> loss = model(**inputs, labels=labels).lossT5Gemma2ForTokenClassification
class transformers.T5Gemma2ForTokenClassification
< source >( config: T5Gemma2Config )
Parameters
- config (T5Gemma2Config) — 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 T5Gemma2 transformer with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
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] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.Tensor] = None decoder_position_ids: typing.Optional[torch.LongTensor] = None encoder_outputs: typing.Optional[transformers.modeling_outputs.BaseModelOutput] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.TokenClassifierOutput or tuple(torch.FloatTensor)
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.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using Gemma3ImageProcessor. See Gemma3ImageProcessor.call() for details (Gemma3Processor uses Gemma3ImageProcessor for processing images). - 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]. - decoder_input_ids (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- decoder_attention_mask (
torch.Tensorof shape(batch_size, target_sequence_length), optional) — Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to make sure the model can only look at previous inputs in order to predict the future. - decoder_position_ids (
torch.LongTensorof shape(batch_size, decoder_sequence_length), optional) — Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range[0, config.decoder.n_positions - 1]. What are position IDs? - encoder_outputs (
~modeling_outputs.BaseModelOutput, optional) — Tuple consists of (last_hidden_state, optional:hidden_states, optional:attentions)last_hidden_stateof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. - inputs_embeds (
torch.FloatTensorof 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. - decoder_inputs_embeds (
torch.FloatTensorof shape(batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passingdecoder_input_idsyou can choose to directly pass an embedded representation. Ifpast_key_valuesis used, optionally only the lastdecoder_inputs_embedshave to be input (seepast_key_values). This is useful if you want more control over how to convertdecoder_input_idsindices into associated vectors than the model’s internal embedding lookup matrix.If
decoder_input_idsanddecoder_inputs_embedsare both unset,decoder_inputs_embedstakes the value ofinputs_embeds. - labels (
torch.LongTensorof shape(batch_size,), optional) — Labels for computing the sequence classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]. Ifconfig.num_labels == 1a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1a classification loss is computed (Cross-Entropy).
Returns
transformers.modeling_outputs.TokenClassifierOutput or tuple(torch.FloatTensor)
A transformers.modeling_outputs.TokenClassifierOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (T5Gemma2Config) and inputs.
-
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) — Classification loss. -
logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.num_labels)) — Classification scores (before SoftMax). -
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 model 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).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The T5Gemma2ForTokenClassification 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.
Example:
>>> from transformers import AutoTokenizer, T5Gemma2ForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google/t5gemma-2-270m-270m")
>>> model = T5Gemma2ForTokenClassification.from_pretrained("google/t5gemma-2-270m-270m")
>>> inputs = tokenizer(
... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_token_class_ids = logits.argmax(-1)
>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes
...
>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...