Transformers documentation

RecurrentGemma

You are viewing v4.43.4 version. A newer version v4.46.2 is available.
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

RecurrentGemma

Overview

The Recurrent Gemma model was proposed in RecurrentGemma: Moving Past Transformers for Efficient Open Language Models by the Griffin, RLHF and Gemma Teams of Google.

The abstract from the paper is the following:

We introduce RecurrentGemma, an open language model which uses Google’s novel Griffin architecture. Griffin combines linear recurrences with local attention to achieve excellent performance on language. It has a fixed-sized state, which reduces memory use and enables efficient inference on long sequences. We provide a pre-trained model with 2B non-embedding parameters, and an instruction tuned variant. Both models achieve comparable performance to Gemma-2B despite being trained on fewer tokens.

Tips:

This model was contributed by Arthur Zucker. The original code can be found here.

RecurrentGemmaConfig

class transformers.RecurrentGemmaConfig

< >

( num_hidden_layers = 26 vocab_size = 256000 hidden_size = 2560 intermediate_size = 7680 num_attention_heads = 10 lru_width = None attention_window_size = 2048 conv1d_width = 4 logits_soft_cap = 30.0 rms_norm_eps = 1e-06 use_cache = True pad_token_id = 0 eos_token_id = 1 bos_token_id = 2 hidden_activation = 'gelu_pytorch_tanh' partial_rotary_factor = 0.5 rope_theta = 10000.0 block_types = ('recurrent', 'recurrent', 'attention') attention_dropout = 0.0 num_key_value_heads = None attention_bias = False w_init_variance_scale = 0.01 **kwargs )

Parameters

  • num_hidden_layers (int, optional, defaults to 26) — The number of hidden layers in the model.
  • vocab_size (int, optional, defaults to 256000) — Vocabulary size of the RecurrentGemma model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling RecurrentGemmaModel
  • hidden_size (int, optional, defaults to 2560) — Dimension of the hidden representations.
  • intermediate_size (int, optional, defaults to 7680) — Dimension of the MLP representations.
  • num_attention_heads (int, optional, defaults to 10) — The number of heads for the attention block and the number of heads/blocks for the block-diagonal layers used in the RG-LRU gates. This number must divide hidden_size and lru_width.
  • lru_width (int or None, optional) — Dimension of the hidden representations of the RG-LRU. If None this will be set to hidden_size. Whether to scale the output of the embeddings by sqrt(hidden_size).
  • attention_window_size (int, optional, defaults to 2048) — The size of the attention window used in the attention block.
  • conv1d_width (int, optional, defaults to 4) — The kernel size of conv1d layers used in the recurrent blocks.
  • logits_soft_cap (float, optional, defaults to 30.0) — The value at which the logits should be soft-capped to after the transformer and LM-head computation in the Causal LM architecture.
  • 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 the model should return the last key/values attentions (not used by all models). Only relevant if config.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.
  • hidden_activation (str` or `function, optional, defaults to "gelu_pytorch_tanh") — The hidden activation used in the recurrent block as well as the MLP layer of the decoder layers.
  • partial_rotary_factor (float, optional, defaults to 0.5) — The partial rotary factor used in the initialization of the rotary embeddings.
  • rope_theta (float, optional, defaults to 10000.0) — The base period of the RoPE embeddings.
  • block_types (List[str], optional, defaults to ('recurrent', 'recurrent', 'attention')) — List of aleternating blocks that will be repeated to initialize the temporal_block layer.
  • attention_dropout (float, optional, defaults to 0.0) — dropout value to use after the attention softmax.
  • num_key_value_heads (16, optional, defaults to 16) — Number of key value heads to use GQA.
  • attention_bias (bool, optional, defaults to False) — whether or not the linear q,k,v of the Attention layer should have bias
  • w_init_variance_scale (float, optional, defaults to 0.01) — weight initialization variance.

This is the configuration class to store the configuration of a RecurrentGemmaModel. It is used to instantiate a RecurrentGemma 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 RecurrentGemma-7B.

e.g. google/recurrentgemma-2b

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 RecurrentGemmaModel, RecurrentGemmaConfig

>>> # Initializing a RecurrentGemma recurrentgemma-2b style configuration
>>> configuration = RecurrentGemmaConfig()

>>> # Initializing a model from the recurrentgemma-2b style configuration
>>> model = RecurrentGemmaModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

RecurrentGemmaModel

class transformers.RecurrentGemmaModel

< >

( config: RecurrentGemmaConfig )

Parameters

  • config (RecurrentGemmaConfig) — 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. config — RecurrentGemmaConfig

The bare RecurrentGemma 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.

Transformer decoder consisting of config.num_hidden_layers layers. Each layer is a RecurrentGemmaDecoderLayer

forward

< >

( input_ids: LongTensor = None position_ids: Optional = None attention_mask: Optional = None cache_position: Optional = None inputs_embeds: Optional = None use_cache: Optional = None output_hidden_states: Optional = None return_dict: Optional = None )

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

    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?

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

  • 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?

  • 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.
  • 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).
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_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.

The RecurrentGemmaModel 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.

RecurrentGemmaForCausalLM

class transformers.RecurrentGemmaForCausalLM

< >

( config )

forward

< >

( input_ids: Optional = None cache_position: Optional = None attention_mask: Optional = None inputs_embeds: Optional = None labels: Optional = None output_hidden_states: Optional = None return_dict: Optional = None use_cache: Optional = None ) transformers.modeling_outputs.CausalLMOutput or tuple(torch.FloatTensor)

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

    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?

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

  • 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?

  • 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.
  • 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).
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_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.

    Args — 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].

Returns

transformers.modeling_outputs.CausalLMOutput or tuple(torch.FloatTensor)

A transformers.modeling_outputs.CausalLMOutput 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 (RecurrentGemmaConfig) and inputs.

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss (for next-token prediction).

  • logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.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 when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.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 RecurrentGemmaForCausalLM 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.

Example:

>>> from transformers import AutoTokenizer, RecurrentGemmaForCausalLM

>>> model = RecurrentGemmaForCausalLM.from_pretrained("google/recurrentgemma-2b")
>>> tokenizer = AutoTokenizer.from_pretrained("google/recurrentgemma-2b")

>>> 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?"
< > Update on GitHub