Buckets:
Gemma2 [[gemma2]]
개요 [[overview]]
Gemma2 모델은 Google의 Gemma2 팀이 작성한 Gemma2: Open Models Based on Gemini Technology and Research에서 제안되었습니다. 파라미터 크기가 각각 90억(9B)과 270억(27B)인 두 가지 Gemma2 모델이 출시되었습니다.
블로그 게시물의 초록은 다음과 같습니다:
이제 우리는 전 세계의 연구자와 개발자들에게 Gemma 2를 공식적으로 출시합니다. 90억(9B)과 270억(27B) 파라미터 크기로 제공되는 Gemma 2는 1세대보다 더 높은 성능과 추론 효율성을 제공하며, 상당한 안전성 향상을 포함하고 있습니다. 사실 270억 규모의 모델은 크기가 두 배 이상인 모델과 비교해도 경쟁력 있는 대안을 제공하며, 이는 작년 12월까지만 해도 독점 모델에서만 가능했던 성능을 제공합니다.
팁:
- 원본 체크포인트는 변환 스크립트
src/transformers/models/Gemma2/convert_Gemma2_weights_to_hf.py를 사용하여 변환할 수 있습니다.
이 모델은 Arthur Zucker, Pedro Cuenca, Tom Arsen이 기여했습니다.
Gemma2Config [[transformers.Gemma2Config]][[transformers.Gemma2Config]]
transformers.Gemma2Config[[transformers.Gemma2Config]]
This is the configuration class to store the configuration of a Gemma2Model. It is used to instantiate a Gemma2 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 google/gemma2-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 Gemma2Model, Gemma2Config
>>> # Initializing a Gemma2 gemma2-7b style configuration
>>> configuration = Gemma2Config()
>>> # Initializing a model from the gemma2-7b style configuration
>>> model = Gemma2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
Parameters:
vocab_size (int, optional, defaults to 256000) : Vocabulary size of the model. Defines the number of different tokens that can be represented by the input_ids.
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. If num_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), if num_key_value_heads=1 the 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 to num_attention_heads.
head_dim (int, optional, defaults to 256) : The attention head dimension. If None, it will default to hidden_size // num_attention_heads
hidden_activation (str, optional, defaults to gelu_pytorch_tanh) : The non-linear activation function (function or string) in the decoder. For example, "gelu", "relu", "silu", etc.
max_position_embeddings (int, optional, defaults to 8192) : 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 to True) : Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if config.is_decoder=True or when the model is a decoder-only generative model.
pad_token_id (int, optional, defaults to 0) : Token id used for padding in the vocabulary.
eos_token_id (Union[int, list[int]], optional, defaults to 1) : Token id used for end-of-stream in the vocabulary.
bos_token_id (int, optional, defaults to 2) : Token id used for beginning-of-stream in the vocabulary.
tie_word_embeddings (bool, optional, defaults to True) : Whether to tie weight embeddings according to model's tied_weights_keys mapping.
rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], optional) : Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for rope_theta and optionally parameters used for scaling in case you want to use RoPE with longer max_position_embeddings.
attention_bias (bool, optional, defaults to False) : Whether to use a bias in the query, key, value and output projection layers during self-attention.
attention_dropout (Union[int, 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) : Sliding window attention window size. If None, no sliding window is applied.
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.
final_logit_softcapping (float, optional, defaults to 30.0) : scaling factor when applying tanh softcapping on the logits.
attn_logit_softcapping (float, optional, defaults to 50.0) : scaling factor when applying tanh softcapping on the attention scores.
use_bidirectional_attention (bool, optional) : If True, the model will attend to all text tokens instead of using a causal mask.
Gemma2Model [[transformers.Gemma2Model]][[transformers.Gemma2Model]]
transformers.Gemma2Model[[transformers.Gemma2Model]]
The bare Gemma2 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.
forwardtransformers.Gemma2Model.forwardhttps://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma2/modeling_gemma2.py#L411[{"name": "input_ids", "val": ": torch.LongTensor | None = None"}, {"name": "attention_mask", "val": ": torch.Tensor | None = None"}, {"name": "position_ids", "val": ": torch.LongTensor | None = None"}, {"name": "past_key_values", "val": ": transformers.cache_utils.Cache | None = None"}, {"name": "inputs_embeds", "val": ": torch.FloatTensor | None = None"}, {"name": "use_cache", "val": ": bool | None = None"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs]"}]- input_ids (torch.LongTensor of 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].past_key_values (
~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 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.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).0BaseModelOutputWithPast ortuple(torch.FloatTensor)A BaseModelOutputWithPast or a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (Gemma2Config) and inputs. The Gemma2Model forward method, overrides the__call__special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) -- Sequence of hidden-states at the output of the last layer of the 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 (
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 (seepast_key_valuesinput) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the 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.
Parameters:
config (Gemma2Config) : 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.
Returns:
[BaseModelOutputWithPast](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) or tuple(torch.FloatTensor)``
A BaseModelOutputWithPast 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 (Gemma2Config) and inputs.
Gemma2ForCausalLM [[transformers.Gemma2ForCausalLM]][[transformers.Gemma2ForCausalLM]]
transformers.Gemma2ForCausalLM[[transformers.Gemma2ForCausalLM]]
The Gemma2 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.
forwardtransformers.Gemma2ForCausalLM.forwardhttps://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma2/modeling_gemma2.py#L491[{"name": "input_ids", "val": ": torch.LongTensor | None = None"}, {"name": "attention_mask", "val": ": torch.Tensor | None = None"}, {"name": "position_ids", "val": ": torch.LongTensor | None = None"}, {"name": "past_key_values", "val": ": transformers.cache_utils.Cache | None = None"}, {"name": "inputs_embeds", "val": ": torch.FloatTensor | None = None"}, {"name": "labels", "val": ": torch.LongTensor | None = None"}, {"name": "use_cache", "val": ": bool | None = None"}, {"name": "logits_to_keep", "val": ": int | torch.Tensor = 0"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs]"}]- input_ids (torch.LongTensor of 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].past_key_values (
~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 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.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).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).0CausalLMOutputWithPast ortuple(torch.FloatTensor)A CausalLMOutputWithPast or a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (Gemma2Config) and inputs. The Gemma2ForCausalLM forward method, overrides the__call__special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) -- Language modeling loss (for next-token prediction).logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.vocab_size)) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).past_key_values (
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
past_key_valuesinput) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the 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.
Example:
>>> from transformers import AutoTokenizer, Gemma2ForCausalLM
>>> model = Gemma2ForCausalLM.from_pretrained("google/gemma-2-9b")
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
>>> prompt = "What is your favorite condiment?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"What is your favorite condiment?"
Parameters:
config (Gemma2ForCausalLM) : 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.
Returns:
[CausalLMOutputWithPast](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) or tuple(torch.FloatTensor)``
A CausalLMOutputWithPast 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 (Gemma2Config) and inputs.
Gemma2ForSequenceClassification [[transformers.Gemma2ForSequenceClassification]][[transformers.Gemma2ForSequenceClassification]]
transformers.Gemma2ForSequenceClassification[[transformers.Gemma2ForSequenceClassification]]
forwardtransformers.Gemma2ForSequenceClassification.forwardhttps://github.com/huggingface/transformers/blob/main/src/transformers/modeling_layers.py#L110[{"name": "input_ids", "val": ": torch.LongTensor | None = None"}, {"name": "attention_mask", "val": ": torch.Tensor | None = None"}, {"name": "position_ids", "val": ": torch.LongTensor | None = None"}, {"name": "past_key_values", "val": ": transformers.cache_utils.Cache | None = None"}, {"name": "inputs_embeds", "val": ": torch.FloatTensor | None = None"}, {"name": "labels", "val": ": torch.LongTensor | None = None"}, {"name": "use_cache", "val": ": bool | None = None"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs]"}]- input_ids (torch.LongTensor of 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].past_key_values (
~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 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.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).0SequenceClassifierOutputWithPastortuple(torch.FloatTensor)ASequenceClassifierOutputWithPastor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (None) and inputs. TheGenericForSequenceClassificationforward method, overrides the__call__special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) -- 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).past_key_values (
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
past_key_valuesinput) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the 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.
Parameters:
input_ids (torch.LongTensor of 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. What are input IDs?
attention_mask (torch.Tensor of 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. What are attention masks?
position_ids (torch.LongTensor of 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]. What are position IDs?
past_key_values (~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 the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True. Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default. The model will output the same cache format that is fed as input. If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don't have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).
inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) : Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model's internal embedding lookup matrix.
labels (torch.LongTensor of 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 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].
use_cache (bool, optional) : If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).
Returns:
SequenceClassifierOutputWithPast` or `tuple(torch.FloatTensor)
A SequenceClassifierOutputWithPast 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 (None) and inputs.
Gemma2ForTokenClassification [[transformers.Gemma2ForTokenClassification]][[transformers.Gemma2ForTokenClassification]]
transformers.Gemma2ForTokenClassification[[transformers.Gemma2ForTokenClassification]]
forwardtransformers.Gemma2ForTokenClassification.forwardhttps://github.com/huggingface/transformers/blob/main/src/transformers/modeling_layers.py#L253[{"name": "input_ids", "val": ": torch.LongTensor | None = None"}, {"name": "attention_mask", "val": ": torch.Tensor | None = None"}, {"name": "position_ids", "val": ": torch.LongTensor | None = None"}, {"name": "past_key_values", "val": ": transformers.cache_utils.Cache | None = None"}, {"name": "inputs_embeds", "val": ": torch.FloatTensor | None = None"}, {"name": "labels", "val": ": torch.LongTensor | None = None"}, {"name": "use_cache", "val": ": bool | None = None"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs]"}]- input_ids (torch.LongTensor of 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].past_key_values (
~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 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.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).0TokenClassifierOutput ortuple(torch.FloatTensor)A TokenClassifierOutput or a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (None) and inputs. TheGenericForTokenClassificationforward method, overrides the__call__special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) -- 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.
Parameters:
input_ids (torch.LongTensor of 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. What are input IDs?
attention_mask (torch.Tensor of 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. What are attention masks?
position_ids (torch.LongTensor of 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]. What are position IDs?
past_key_values (~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 the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True. Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default. The model will output the same cache format that is fed as input. If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don't have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).
inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) : Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model's internal embedding lookup matrix.
labels (torch.LongTensor of 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 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].
use_cache (bool, optional) : If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).
Returns:
[TokenClassifierOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.TokenClassifierOutput) or tuple(torch.FloatTensor)``
A 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 (None) and inputs.
Xet Storage Details
- Size:
- 44.8 kB
- Xet hash:
- 0ac9799c53f09c04ba678965b93f1ea2df25145a7150001687bde109cb7cfe15
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.