Transformers documentation
Granite Speech
Granite Speech
Overview
The Granite Speech model is a multimodal language model, consisting of a speech encoder, speech projector, large language model, and LoRA adapter(s). More details regarding each component for the current (Granite 3.2 Speech) model architecture may be found below.
Speech Encoder: A Conformer encoder trained with Connectionist Temporal Classification (CTC) on character-level targets on ASR corpora. The encoder uses block-attention and self-conditioned CTC from the middle layer.
Speech Projector: A query transformer (q-former) operating on the outputs of the last encoder block. The encoder and projector temporally downsample the audio features to be merged into the multimodal embeddings to be processed by the llm.
Large Language Model: The Granite Speech model leverages Granite LLMs, which were originally proposed in this paper.
LoRA adapter(s): The Granite Speech model contains a modality specific LoRA, which will be enabled when audio features are provided, and disabled otherwise.
Note that most of the aforementioned components are implemented generically to enable compatability and potential integration with other model architectures in transformers.
This model was contributed by Alexander Brooks, Avihu Dekel, and George Saon.
Usage tips
- This model bundles its own LoRA adapter, which will be automatically loaded and enabled/disabled as needed during inference calls. Be sure to install PEFT to ensure the LoRA is correctly applied!
GraniteSpeechConfig
class transformers.GraniteSpeechConfig
< source >( text_config = None encoder_config = None projector_config = None audio_token_index = 49155 initializer_range = 0.02 has_lora_adapter = True downsample_rate = 5 window_size = 15 **kwargs )
Parameters
- text_config (
Union[AutoConfig, dict]
, optional, defaults toGraniteConfig
) — The config object or dictionary of the text backbone. - encoder_config (
GraniteSpeechEncoderConfig
, optional) — The config object or dictionary of the Granite Speech CTC Encoder. - projector_config (
Union[AutoConfig, dict]
, optional, defaults toBlip2QFormerConfig
) — The config object or dictionary of the audio projector. - audio_token_index (
int
, optional, defaults to 49155) — The audio token index to encode the audio prompt. - initializer_range (
float
, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - has_lora_adapter (
bool
, optional, defaults toTrue
) — Indicates whether or not the model has a lora adapter that should only be activate when processing audio inputs. - downsample_rate (
int
, optional, defaults to 5) — Downsample rate for the audio feature extractor. - window_size (
int
, optional, defaults to 15) — Window size for the audio feature projector.
This is the configuration class to store the configuration of a GraniteSpeechForConditionalGeneration. It is used to instantiate an Granite Speech model according to the specified arguments, defining the model architecture.
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 GraniteSpeechConfig, GraniteSpeechForConditionalGeneration
>>> # Initializing a GraniteSpeechConfig
>>> configuration = GraniteSpeechConfig()
>>> # Initializing a GraniteSpeechForConditionalGeneration (with random weights)
>>> model = GraniteSpeechForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
GraniteSpeechEncoderConfig
class transformers.GraniteSpeechEncoderConfig
< source >( input_dim = 160 num_layers = 10 hidden_dim = 1024 feedforward_mult = 4 num_heads = 8 dim_head = 128 output_dim = 42 context_size = 200 max_pos_emb = 512 dropout = 0.1 conv_kernel_size = 15 conv_expansion_factor = 2 **kwargs )
Parameters
- input_dim (
int
, optional, defaults to 160) — Dimension of the first hidden layer of the encoder. - num_layers (
int
, optional, defaults to 10) — Number of encoder blocks. - hidden_dim (
int
, optional, defaults to 1024) — The size of the intermediate layers in the conformer encoder. - feedforward_mult (
int
, optional, defaults to 4) — Multiplier for the up/down projections in the encoder’s feedforward layers; The projections will have intermediate dim of sizehidden_dim * feedforward_mult
. - num_heads (
int
, optional, defaults to 8) — Number of attention heads for each attention layer in the Transformer encoder. - dim_head (
int
, optional, defaults to 128) — Dimension of attention heads for each attention layer in the Transformer encoder. - output_dim (
int
, optional, defaults to 42) — Intermediate dimension of the feedforward projections in the conformer to be added to every other encoder block’s output. - context_size (
int
, optional, defaults to 200) — Context size to be used in conformer attention. - max_pos_emb (
int
, optional, defaults to 512) — Max pos embeds to be used in attention (shaw’s relative positional encoding). - dropout (
float
, optional, defaults to 0.1) — The dropout probability for fully connected layers in the encoder. - conv_kernel_size (
int
, optional, defaults to 15) — Kernel size to be used for 1D convolution in each conformer block. - conv_expansion_factor (
int
, optional, defaults to 2) — Intermediate dimension to be used in conformer convolutions.
This is the configuration class to store the configuration of a GraniteSpeechCTCEncoder
. It is used to instantiate
a Granite Speech audio encoder according to the specified arguments, defining the model architecture. Instantiating a
configuration with the dfefaults will yield a similar configuration to that of the audio encoder of the Granite Speech
architecture.
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 GraniteSpeechEncoderConfig, GraniteSpeechCTCEncoder
>>> # Initializing a GraniteSpeechEncoderConfig
>>> configuration = GraniteSpeechEncoderConfig()
>>> # Initializing a GraniteSpeechCTCEncoder (with random weights)
>>> model = GraniteSpeechCTCEncoder(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
GraniteSpeechProcessor
class transformers.GraniteSpeechProcessor
< source >( audio_processor tokenizer audio_token = '<|audio|>' chat_template = None )
GraniteSpeechFeatureExtractor
class transformers.GraniteSpeechFeatureExtractor
< source >( sampling_rate: int = 16000 n_fft: int = 512 win_length: int = 400 hop_length: int = 160 n_mels: int = 80 projector_window_size: int = 15 projector_downsample_rate: int = 5 **kwargs )
GraniteSpeechForConditionalGeneration
class transformers.GraniteSpeechForConditionalGeneration
< source >( config: GraniteSpeechConfig )
Parameters
- config (
GraniteSpeechConfig
) — 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 Granite Speech model, which consists of an audio encoder, projector, and language model. 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: LongTensor = None input_features: FloatTensor = None input_features_mask: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **lm_kwargs ) → transformers.models.granite_speech.modeling_granite_speech.GraniteSpeechCausalLMOutputWithPast
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.
- input_features (
torch.FloatTensor
of shape(batch_size, audio seq len, mel feat dim)) -- The tensors corresponding to the input audios. input features can be obtained using [AutoFeatureExtractor](/docs/transformers/main/en/model_doc/auto#transformers.AutoFeatureExtractor). See
GraniteSpeechFeatureExtractor.call()` for details. GraniteSpeechProcessor uses GraniteSpeechFeatureExtractor for processing audio. - input_mask (
torch.Tensor
, optional) — Mask for extracted audio features that should should be ignored when creating the merged multimodal representation (i.e., due to padding). - 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.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
If
past_key_values
is used, optionally only the lastdecoder_input_ids
have to be input (seepast_key_values
).If you want to change padding behavior, you should read
modeling_opt._prepare_decoder_attention_mask
and modify to your needs. See diagram 1 in the paper for more information on the default strategy.- 1 indicates the head is not masked,
- 0 indicates the head is masked.
- 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 (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.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_values
input) to speed up sequential decoding.If
past_key_values
are used, the user can optionally input only the lastdecoder_input_ids
(those that don’t have their past key value states given to this model) of shape(batch_size, 1)
instead of alldecoder_input_ids
of shape(batch_size, sequence_length)
. - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids
indices into associated vectors than the model’s internal embedding lookup matrix. - use_cache (
bool
, optional) — If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
). - output_attentions (
bool
, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail. - output_hidden_states (
bool
, optional) — Whether or not to return the hidden states of all layers. Seehidden_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 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. - 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 (seeinput_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]
. - logits_to_keep (
int
ortorch.Tensor
, optional) — If anint
, compute logits for the lastlogits_to_keep
tokens. 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.models.granite_speech.modeling_granite_speech.GraniteSpeechCausalLMOutputWithPast
or tuple(torch.FloatTensor)
A transformers.models.granite_speech.modeling_granite_speech.GraniteSpeechCausalLMOutputWithPast
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 (GraniteSpeechConfig) and inputs.
-
loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
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). -
past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
)Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
past_key_values
input) to speed up sequential decoding. -
hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is 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=True
is 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 GraniteSpeechForConditionalGeneration 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.