Transformers documentation
CohereAsr
This model was released on {release_date} and added to Hugging Face Transformers on 2026-03-26.
CohereAsr
Overview
Cohere ASR, released by Cohere on March 26th, 2026, is a 2B parameter Conformer-based encoder-decoder speech recognition model.
This model was contributed by Eustache Le Bihan.
Usage
Short-form transcription
from transformers import AutoProcessor, CohereAsrForConditionalGeneration
from transformers.audio_utils import load_audio
revision = "refs/pr/6"
processor = AutoProcessor.from_pretrained("CohereLabs/cohere-transcribe-03-2026", revision=revision)
model = CohereAsrForConditionalGeneration.from_pretrained("CohereLabs/cohere-transcribe-03-2026", device_map="auto", revision=revision)
audio = load_audio(
"https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3",
sampling_rate=16000,
)
inputs = processor(audio, sampling_rate=16000, return_tensors="pt", language="en")
inputs.to(model.device, dtype=model.dtype)
outputs = model.generate(**inputs, max_new_tokens=256)
text = processor.decode(outputs, skip_special_tokens=True)
print(text)Punctuation control
Pass punctuation=False to obtain lower-cased output without punctuation marks.
inputs_pnc = processor(audio, sampling_rate=16000, return_tensors="pt", language="en", punctuation=True)
inputs_nopnc = processor(audio, sampling_rate=16000, return_tensors="pt", language="en", punctuation=False)Long-form transcription
For audio longer than the feature extractor’s max_audio_clip_s, the feature extractor automatically splits the waveform into chunks.
The processor reassembles the per-chunk transcriptions using the returned audio_chunk_index.
audio_long = load_audio(
"https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3",
sampling_rate=16000,
)
inputs = processor(audio=audio_long, return_tensors="pt", language="en", sampling_rate=16000)
audio_chunk_index = inputs.get("audio_chunk_index")
inputs.to(model.device, dtype=model.dtype)
outputs = model.generate(**inputs, max_new_tokens=256)
text = processor.decode(outputs, skip_special_tokens=True, audio_chunk_index=audio_chunk_index, language="en")
print(text)Batched inference
Multiple audio files can be processed in a single call. When the batch mixes short-form and long-form audio, the processor handles chunking and reassembly.
audio_short = load_audio(
"https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3",
sampling_rate=16000,
)
audio_long = load_audio(
"https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3",
sampling_rate=16000,
)
inputs = processor([audio_short, audio_long], sampling_rate=16000, return_tensors="pt", language="en")
audio_chunk_index = inputs.get("audio_chunk_index")
inputs.to(model.device, dtype=model.dtype)
outputs = model.generate(**inputs, max_new_tokens=256)
text = processor.decode(
outputs, skip_special_tokens=True, audio_chunk_index=audio_chunk_index, language="en"
)
print(text)Non-English transcription
Specify the language code to transcribe in any of the 14 supported languages.
audio_es = load_audio(
"https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/fleur_es_sample.wav",
sampling_rate=16000,
)
inputs = processor(audio_es, sampling_rate=16000, return_tensors="pt", language="es", punctuation=True)
inputs.to(model.device, dtype=model.dtype)
outputs = model.generate(**inputs, max_new_tokens=256)
text = processor.decode(outputs, skip_special_tokens=True)
print(text)CohereAsrConfig
class transformers.CohereAsrConfig
< source >( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = True id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None vocab_size: int = 16384 hidden_size: int = 1024 num_hidden_layers: int = 8 num_attention_heads: int = 8 num_key_value_heads: int | None = None intermediate_size: int = 4096 hidden_act: str = 'relu' max_position_embeddings: int = 1024 pad_token_id: int | None = 2 eos_token_id: int | None = 3 bos_token_id: int | None = 4 initializer_range: float = 0.02 attention_dropout: float | int = 0.0 attention_bias: bool = True decoder_start_token_id: int | None = None tie_word_embeddings: bool = False head_dim: int | None = None )
Parameters
- is_encoder_decoder (
bool, optional, defaults toTrue) — Whether the model is used as an encoder/decoder or not. - encoder_config (
Union[dict, ~configuration_utils.PreTrainedConfig], optional) — The config object or dictionary of the encoder backbone. - vocab_size (
int, optional, defaults to16384) — Vocabulary size of the model. Defines the number of different tokens that can be represented by theinput_ids. - hidden_size (
int, optional, defaults to1024) — Dimension of the hidden representations. - num_hidden_layers (
int, optional, defaults to8) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to8) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional) — 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. - intermediate_size (
int, optional, defaults to4096) — Dimension of the MLP representations. - hidden_act (
str, optional, defaults torelu) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - max_position_embeddings (
int, optional, defaults to1024) — The maximum sequence length that this model might ever be used with. - pad_token_id (
int, optional, defaults to2) — Token id used for padding in the vocabulary. - eos_token_id (
int, optional, defaults to3) — Token id used for end-of-stream in the vocabulary. - bos_token_id (
int, optional, defaults to4) — Token id used for beginning-of-stream in the vocabulary. - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - attention_dropout (
Union[float, int], optional, defaults to0.0) — The dropout ratio for the attention probabilities. - attention_bias (
bool, optional, defaults toTrue) — Whether to use a bias in the query, key, value and output projection layers during self-attention. - decoder_start_token_id (
int, optional) — If an encoder-decoder model starts decoding with a different token thanbos, the id of that token. - tie_word_embeddings (
bool, optional, defaults toFalse) — Whether to tie weight embeddings according to model’stied_weights_keysmapping. - head_dim (
int, optional) — The attention head dimension. If None, it will default to hidden_size // num_attention_heads
This is the configuration class to store the configuration of a CohereAsrModel. It is used to instantiate a Cohere Asr 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 CohereLabs/cohere-transcribe-03-2026
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
CohereAsrFeatureExtractor
class transformers.CohereAsrFeatureExtractor
< source >( feature_size = 128 sampling_rate = 16000 hop_length = 160 n_fft = 512 win_length = 400 preemphasis = 0.97 padding_value = 0.0 dither = 1e-05 max_audio_clip_s = 35.0 overlap_chunk_second = 5.0 min_energy_window_samples = 1600 **kwargs )
Parameters
- feature_size (
int, optional, defaults to 128) — The feature dimension of the extracted features. - sampling_rate (
int, optional, defaults to 16000) — The sampling rate at which the audio files should be digitalized expressed in hertz (Hz). - hop_length (
int, optional, defaults to 160) — Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients. - n_fft (
int, optional, defaults to 512) — Size of the Fourier transform. - win_length (
int, optional, defaults to 400) — The window length for the STFT computation. - preemphasis (
float, optional, defaults to 0.97) — A preemphasis filter coefficient. 0.0 means no preemphasis filter. - padding_value (
float, optional, defaults to 0.0) — Padding value used to pad the audio. Should correspond to silences. - dither (
float, optional, defaults to 1e-05) — Amount of deterministic dither noise to add before feature extraction. Each sample is seeded by its valid waveform length so that dither is batch-composition invariant. Set to 0.0 to disable. - max_audio_clip_s (
float, optional, defaults to 35.0) — Maximum duration in seconds for a single audio chunk. Audio longer thanmax_audio_clip_s - overlap_chunk_secondis split at energy-based boundaries. - overlap_chunk_second (
float, optional, defaults to 5.0) — Size in seconds of the boundary search window used when splitting long audio. This is not actual overlap between chunks — it defines how far back from the chunk boundary to search for a quiet split point. - min_energy_window_samples (
int, optional, defaults to 1600) — Size in samples of the sliding window used to find the quietest point when splitting audio chunks.
Constructs a CohereAsr feature extractor.
This feature extractor inherits from SequenceFeatureExtractor which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
This class extracts mel-filter bank features from raw speech using a custom numpy implementation of the Short Time Fourier Transform which should match pytorch’s torch.stft equivalent.
__call__
< source >( raw_speech: numpy.ndarray | list[float] | list[numpy.ndarray] | list[list[float]] truncation: bool = False pad_to_multiple_of: int | None = None return_tensors: str | transformers.utils.generic.TensorType | None = None return_attention_mask: bool | None = None padding: str | None = 'longest' max_length: int | None = None sampling_rate: int | None = None do_normalize: bool | None = None device: str | None = 'cpu' return_token_timestamps: bool | None = None **kwargs )
Parameters
- raw_speech (
np.ndarray,list[float],list[np.ndarray],list[list[float]]) — The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not stereo, i.e. single float per timestep. - truncation (
bool, optional, default toTrue) — Activates truncation to cut input sequences longer than max_length to max_length. - pad_to_multiple_of (
int, optional, defaults to None) — If set will pad the sequence to a multiple of the provided value.This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
>= 7.5(Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. - return_attention_mask (
bool, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific feature_extractor’s default.For CohereAsr models,
attention_maskshould always be passed for batched inference, to avoid subtle bugs. - return_tensors (
stror TensorType, optional) — If set, will return tensors instead of list of python integers. Acceptable values are:'tf': Return TensorFlowtf.constantobjects.'pt': Return PyTorchtorch.Tensorobjects.'np': Return Numpynp.ndarrayobjects.
- sampling_rate (
int, optional) — The sampling rate at which theraw_speechinput was sampled. It is strongly recommended to passsampling_rateat the forward call to prevent silent errors and allow automatic speech recognition pipeline. - padding_value (
float, optional, defaults to 0.0) — The value that is used to fill the padding values / vectors. - do_normalize (
bool, optional, defaults toFalse) — Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly improve the performance of the model. - device (
str, optional, defaults to'cpu') — Specifies the device for computation of the log-mel spectrogram of audio signals in the_torch_extract_fbank_featuresmethod. (e.g., “cpu”, “cuda”) - return_token_timestamps (
bool, optional, defaults toNone) — Deprecated. Usereturn_attention_maskinstead from which the number of frames can be inferred.Whether or not to return the number of frames of the input raw_speech. These num_frames can be used by the model to compute word level timestamps.
Main method to featurize and prepare for the model one or several sequence(s). Implementation uses PyTorch for the STFT computation if available, otherwise a slower NumPy based one.
CohereAsrProcessor
class transformers.CohereAsrProcessor
< source >( feature_extractor tokenizer )
Constructs a CohereAsrProcessor which wraps a feature extractor and a tokenizer into a single processor.
CohereAsrProcessor offers all the functionalities of CohereAsrFeatureExtractor and TokenizersBackend. See the ~CohereAsrFeatureExtractor and ~TokenizersBackend for more information.
__call__
< source >( audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']] language: str text: str | list[str] | list[list[str]] | None = None punctuation: bool = True sampling_rate: int | None = None **kwargs: typing_extensions.Unpack[transformers.models.cohere_asr.processing_cohere_asr.CohereAsrProcessorKwargs] )
Parameters
- audio (
Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]) — The audio or batch of audios to be prepared. Each audio can be a NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels, and T is the sample length of the audio. - language (
str) — Language code (e.g."en","es","fr") used to build the decoder prompt. The processor constructs the full decoder prompt and returnsdecoder_input_idsalongside the audio features. - text (
Union[str, list[str], list[list[str]]], optional) — The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If you pass a pretokenized input, setis_split_into_words=Trueto avoid ambiguity with batched inputs. - punctuation (
bool, defaults toTrue) — Whether to enable punctuation in the decoder prompt. - sampling_rate (
int, optional) — The sampling rate of the input audio in Hz. This should match the sampling rate expected by the feature extractor (defaults to 16000 Hz). If provided, it will be validated against the processor’s expected sampling rate, and an error will be raised if they don’t match. If not provided, a warning will be issued and the default sampling rate will be assumed. - return_tensors (
stror TensorType, optional) — If set, will return tensors of a particular framework. Acceptable values are:'pt': Return PyTorchtorch.Tensorobjects.'np': Return NumPynp.ndarrayobjects.
- **kwargs (ProcessingKwargs, optional) — Additional processing options for each modality (text, images, videos, audio). Model-specific parameters are listed above; see the TypedDict class for the complete list of supported arguments.
CohereAsrPreTrainedModel
class transformers.CohereAsrPreTrainedModel
< source >( config: PreTrainedConfig *inputs **kwargs )
Parameters
- config (PreTrainedConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
Define the computation performed at every call.
Should be overridden by all subclasses.
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 registered hooks while the latter silently ignores them.
CohereAsrModel
class transformers.CohereAsrModel
< source >( config )
Parameters
- config (CohereAsrModel) — 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 Cohere Asr 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_features: torch.FloatTensor | None = None attention_mask: torch.LongTensor | None = None decoder_input_ids: torch.LongTensor | None = None decoder_attention_mask: torch.LongTensor | None = None encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None past_key_values: transformers.cache_utils.EncoderDecoderCache | None = None decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None decoder_position_ids: tuple[torch.LongTensor] | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → Seq2SeqModelOutput or tuple(torch.FloatTensor)
Parameters
- input_features (
torch.FloatTensorof shape(batch_size, audio_length)) — Float values of the raw speech waveform. Raw speech waveform can be obtained by loading a.flacor.wavaudio file into an array of typelist[float], anumpy.ndarrayor atorch.Tensor, e.g. via the torchcodec library (pip install torchcodec) or the soundfile library (pip install soundfile). To prepare the array intoinput_features, the AutoFeatureExtractor should be used for padding and conversion into a tensor of typetorch.FloatTensor. - attention_mask (
torch.LongTensorof 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.
- 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.LongTensorof 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. - encoder_outputs (
tuple[tuple[torch.FloatTensor]], 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). - decoder_inputs_embeds (
tuple[torch.FloatTensor]of 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. - decoder_position_ids (
torch.LongTensorof shape(batch_size, target_sequence_length)) — Indices of positions of each input sequence tokens in the position embeddings. Used to calculate the position embeddings up toconfig.decoder_config.max_position_embeddings - 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).
Returns
Seq2SeqModelOutput or tuple(torch.FloatTensor)
A 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 (CohereAsrConfig) and inputs.
The CohereAsrModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
last_hidden_state (
torch.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.
Example:
>>> import torch
>>> from transformers import AutoFeatureExtractor, CohereAsrModel
>>> from datasets import load_dataset
>>> model = CohereAsrModel.from_pretrained("UsefulSensors/cohere_asr-tiny")
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/cohere_asr-tiny")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_features = inputs.input_features
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
>>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
>>> list(last_hidden_state.shape)
[1, 2, 288]CohereAsrForConditionalGeneration
class transformers.CohereAsrForConditionalGeneration
< source >( config )
Parameters
- config (CohereAsrForConditionalGeneration) — 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 CohereAsr Model with a language modeling head. Can be used for automatic speech recognition.
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_features: torch.FloatTensor | None = None attention_mask: torch.LongTensor | None = None decoder_input_ids: torch.LongTensor | None = None decoder_attention_mask: torch.LongTensor | None = None encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None past_key_values: transformers.cache_utils.EncoderDecoderCache | None = None decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None decoder_position_ids: tuple[torch.LongTensor] | None = None use_cache: bool | None = None labels: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → Seq2SeqLMOutput or tuple(torch.FloatTensor)
Parameters
- input_features (
torch.FloatTensorof shape(batch_size, audio_length)) — Float values of the raw speech waveform. Raw speech waveform can be obtained by loading a.flacor.wavaudio file into an array of typelist[float], anumpy.ndarrayor atorch.Tensor, e.g. via the torchcodec library (pip install torchcodec) or the soundfile library (pip install soundfile). To prepare the array intoinput_features, the AutoFeatureExtractor should be used for padding and conversion into a tensor of typetorch.FloatTensor. - attention_mask (
torch.LongTensorof 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.
- 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.LongTensorof 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. - encoder_outputs (
tuple[tuple[torch.FloatTensor]], 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). - decoder_inputs_embeds (
tuple[torch.FloatTensor]of 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. - decoder_position_ids (
torch.LongTensorof shape(batch_size, target_sequence_length)) — Indices of positions of each input sequence tokens in the position embeddings. Used to calculate the position embeddings up toconfig.decoder_config.max_position_embeddings - 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). - 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].
Returns
Seq2SeqLMOutput or tuple(torch.FloatTensor)
A 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 (CohereAsrConfig) and inputs.
The CohereAsrForConditionalGeneration forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
loss (
torch.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.
Example:
>>> import torch
>>> from transformers import AutoProcessor, CohereAsrForConditionalGeneration
>>> from datasets import load_dataset
>>> processor = AutoProcessor.from_pretrained("UsefulSensors/cohere_asr-tiny")
>>> model = CohereAsrForConditionalGeneration.from_pretrained("UsefulSensors/cohere_asr-tiny")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_features = inputs.input_features
>>> generated_ids = model.generate(input_features, max_new_tokens=100)
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> transcription
'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'