A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://huggingface.co/docs/transformers/v4.51.3/en/model_doc/moshi below:

Website Navigation


Moshi

Moshi Overview

The Moshi model was proposed in Moshi: a speech-text foundation model for real-time dialogue by Alexandre Défossez, Laurent Mazaré, Manu Orsini, Amélie Royer, Patrick Pérez, Hervé Jégou, Edouard Grave and Neil Zeghidour.

Moshi is a speech-text foundation model that casts spoken dialogue as speech-to-speech generation. Starting from a text language model backbone, Moshi generates speech as tokens from the residual quantizer of a neural audio codec, while modeling separately its own speech and that of the user into parallel streams. This allows for the removal of explicit speaker turns, and the modeling of arbitrary conversational dynamics. Moshi also predicts time-aligned text tokens as a prefix to audio tokens. This “Inner Monologue” method significantly improves the linguistic quality of generated speech and provides streaming speech recognition and text-to-speech. As a result, Moshi is the first real-time full-duplex spoken large language model, with a theoretical latency of 160ms, 200ms in practice.

The abstract from the paper is the following:

We introduce Moshi, a speech-text foundation model and full-duplex spoken dialogue framework. Current systems for spoken dialogue rely on pipelines of independent components, namely voice activity detection, speech recognition, textual dialogue and text-to-speech. Such frameworks cannot emulate the experience of real conversations. First, their complexity induces a latency of several seconds between interactions. Second, text being the intermediate modality for dialogue, non-linguistic information that modifies meaning— such as emotion or non-speech sounds— is lost in the interaction. Finally, they rely on a segmentation into speaker turns, which does not take into account overlapping speech, interruptions and interjections. Moshi solves these independent issues altogether by casting spoken dialogue as speech-to-speech generation. Starting from a text language model backbone, Moshi generates speech as tokens from the residual quantizer of a neural audio codec, while modeling separately its own speech and that of the user into parallel streams. This allows for the removal of explicit speaker turns, and the modeling of arbitrary conversational dynamics. We moreover extend the hierarchical semantic-to-acoustic token generation of previous work to first predict time-aligned text tokens as a prefix to audio tokens. Not only this “Inner Monologue” method significantly improves the linguistic quality of generated speech, but we also illustrate how it can provide streaming speech recognition and text-to-speech. Our resulting model is the first real-time full-duplex spoken large language model, with a theoretical latency of 160ms, 200ms in practice, and is available at github.com/kyutai-labs/moshi.

Moshi deals with 3 streams of information:

  1. The user’s audio
  2. Moshi’s audio
  3. Moshi’s textual output

Similarly to ~MusicgenModel, audio is represented with audio codebooks, which can be interpreted like tokens. The main difference between text tokens and audio codebooks is that audio codebooks introduce an additional dimension of information. Text tokens are typically of dim (batch_size, sequence_length) but audio tokens are of dim (batch_size, num_codebooks, sequence_length).

Moshi’s made of 3 components:

1. The main decoder (Helium in the paper)

It corresponds to MoshiForCausalLM. It is strictly a classic text LLM, that uses an architecture similar to ~GemmaForCausalLM. In other words, it takes text tokens, embeds them, pass them through the decoder and a language head, to get text logits.

2. The depth decoder

On its own, it’s also a classic LLM, but this time, instead of generating over the time dimension, it generates over the codebook dimension.

It also means that its context length is num_codebooks, thus it can’t generate more than num_codebooks.

Note that each timestamp - i.e each codebook - gets its own set of Linear Layers and Embeddings.

3. MimiModel

It’s the audio encoder from Kyutai, that has recently been integrated to transformers, which is used to “tokenize” audio. It has the same use that ~EncodecModel has in ~MusicgenModel.

Tips:

The original checkpoints can be converted using the conversion script src/transformers/models/moshi/convert_moshi_transformers.py

How to use the model:

This implementation has two main aims:

  1. quickly test model generation by simplifying the original API
  2. simplify training. A training guide will come soon, but user contributions are welcomed!

It is designed for intermediate use. We strongly recommend using the original implementation to infer the model in real-time streaming.

1. Model generation

Moshi is a streaming auto-regressive model with two streams of audio. To put it differently, one audio stream corresponds to what the model said/will say and the other audio stream corresponds to what the user said/will say.

MoshiForConditionalGeneration.generate() thus needs 3 inputs:

  1. input_ids - corresponding to the text token history
  2. moshi_input_values or moshi_audio_codes- corresponding to the model audio history
  3. user_input_values or user_audio_codes - corresponding to the user audio history

These three inputs must be synchronized. Meaning that their lengths must correspond to the same number of tokens.

You can dynamically use the 3 inputs depending on what you want to test:

  1. Simply check the model response to an user prompt - in that case, input_ids can be filled with pad tokens and user_input_values can be a zero tensor of the same shape than the user prompt.
  2. Test more complex behaviour - in that case, you must be careful about how the input tokens are synchronized with the audios.

The original model is synchronized text with audio by padding the text in between each token enunciation.

To follow the example of the following image, "Hello, I'm Moshi" could be transformed to "Hello,<pad><unk>I'm Moshi".

MoshiForConditionalGeneration.generate() then auto-regressively feeds to itself its own audio stream, but since it doesn’t have access to the user input stream while using transformers, it will thus assume that the user is producing blank audio.

>>> from datasets import load_dataset, Audio
>>> import torch, math
>>> from transformers import MoshiForConditionalGeneration, AutoFeatureExtractor, AutoTokenizer


>>> librispeech_dummy = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("kyutai/moshiko-pytorch-bf16")
>>> tokenizer = AutoTokenizer.from_pretrained("kyutai/moshiko-pytorch-bf16")
>>> device = "cuda"
>>> dtype = torch.bfloat16

>>> 
>>> librispeech_dummy = librispeech_dummy.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
>>> audio_sample = librispeech_dummy[-1]["audio"]["array"]
>>> user_input_values = feature_extractor(raw_audio=audio_sample, sampling_rate=feature_extractor.sampling_rate, return_tensors="pt").to(device=device, dtype=dtype)

>>> 
>>> moshi_input_values = torch.zeros_like(user_input_values.input_values)

>>> 
>>> num_tokens = math.ceil(moshi_input_values.shape[-1] * waveform_to_token_ratio)
>>> input_ids = torch.ones((1, num_tokens), device=device, dtype=torch.int64) * tokenizer.encode("<pad>")[0]

>>> 
>>> output = model.generate(input_ids=input_ids, user_input_values=user_input_values.input_values, moshi_input_values=moshi_input_values, max_new_tokens=25)

>>> text_tokens = output.sequences
>>> audio_waveforms = output.audio_sequences

2. Model training

Most of the work has to be done during data creation/pre-processing, because of the need to align/synchronize streams.

Once it’s done, you can simply forward text_labels and audio_labels to MoshiForConditionalGeneration.forward(), alongside the usual inputs, to get the model loss.

A training guide will come soon, but user contributions are welcomed!

How does the model forward the inputs / generate:
  1. The input streams are embedded and combined into inputs_embeds.

  2. inputs_embeds is passed through the main decoder, which processes it like a normal LLM would.

  3. The main decoder outputs text logits but also its last hidden state which is called temporal context in the paper.

  4. The depth decoder switches the dimension on which we forward / generate (codebooks instead of time). It uses the token generated from text logits and the temporal context to auto-regressively generate audio codebooks.

This model was contributed by Yoach Lacombe (ylacombe).

The original code can be found here.

MoshiConfig class transformers.MoshiConfig < source >

( vocab_size = 32000 hidden_size = 4096 num_hidden_layers = 32 num_attention_heads = 32 num_key_value_heads = None audio_vocab_size = None max_position_embeddings = 3000 rope_theta = 10000.0 hidden_act = 'silu' head_dim = None initializer_range = 0.02 use_cache = True sliding_window = 3000 attention_dropout = 0.0 ffn_dim = 22528 rms_norm_eps = 1e-08 num_codebooks = 8 tie_word_embeddings = False **kwargs )

Parameters

This is the configuration class to store the configuration of a MoshiModel. It is used to instantiate a Moshi model according to the specified arguments, defining the audio encoder, Moshi depth decoder and Moshi decoder configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the Moshiko model, e.g. kmhf/hf-moshiko

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 (
...     MoshiConfig,
...     MoshiForConditionalGeneration,
... )

>>> configuration = MoshiConfig()

>>> 
>>> model = MoshiForConditionalGeneration(configuration)

>>> 
>>> configuration = model.config

>>> 
>>> model.save_pretrained("kmhf/hf-moshiko")

>>> 
>>> moshi_config = MoshiConfig.from_pretrained("kmhf/hf-moshiko")
>>> model = MoshiForConditionalGeneration.from_pretrained("kmhf/hf-moshiko", config=moshi_config)
from_audio_encoder_config < source >

( audio_encoder_config: PretrainedConfig **kwargs ) MoshiConfig

An instance of a configuration object

Instantiate a MoshiConfig (or a derived class) from an audio encoder configuration.

MoshiDepthConfig class transformers.MoshiDepthConfig < source >

( vocab_size = 32000 hidden_size = 1024 input_size = 4096 num_hidden_layers = 6 num_attention_heads = 16 num_key_value_heads = None audio_vocab_size = 2048 max_position_embeddings = 9 hidden_act = 'silu' head_dim = None initializer_range = 0.02 use_cache = True sliding_window = 8 attention_dropout = 0.0 ffn_dim = 5632 rms_norm_eps = 1e-08 num_codebooks = 8 tie_word_embeddings = False **kwargs )

Parameters

This is the configuration class to store the configuration of a MoshiDepthDecoder. It is used to instantiate a Moshi depth decoder model according to the specified arguments, defining the Moshi depth decoder config.

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 (
...     MoshiDepthConfig,
...     MoshiDepthDecoder,
... )

>>> configuration = MoshiDepthConfig()

>>> 
>>> model = MoshiDepthDecoder(configuration)

>>> 
>>> configuration = model.config
MoshiModel class transformers.MoshiModel < source >

( config: MoshiConfig )

Parameters

The bare Moshi 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 MoshiDecoderLayer

forward < source >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Union[transformers.cache_utils.Cache, typing.List[torch.FloatTensor], NoneType] = None inputs_embeds: typing.Optional[torch.FloatTensor] = 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 )

Parameters

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

MoshiForCausalLM class transformers.MoshiForCausalLM < source >

( config )

Parameters

The Moshi decoder model with a text language modelling head on top. Only usable for text. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward < source >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Union[transformers.cache_utils.Cache, typing.List[torch.FloatTensor], NoneType] = None inputs_embeds: typing.Optional[torch.FloatTensor] = 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 labels: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs ) transformers.models.moshi.modeling_moshi.MoshiCausalLMOutputWithPast or tuple(torch.FloatTensor)

Parameters

Returns

transformers.models.moshi.modeling_moshi.MoshiCausalLMOutputWithPast or tuple(torch.FloatTensor)

A transformers.models.moshi.modeling_moshi.MoshiCausalLMOutputWithPast 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 (MoshiConfig) and inputs.

The MoshiForCausalLM 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, MoshiForCausalLM

>>> model = MoshiForCausalLM.from_pretrained("kmhf/hf-moshiko")
>>> tokenizer = AutoTokenizer.from_pretrained("kmhf/hf-moshiko")

>>> prompt = "What is your favorite condiment?"
>>> inputs = tokenizer(prompt, return_tensors="pt")

>>> 
>>> 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?"
MoshiForConditionalGeneration class transformers.MoshiForConditionalGeneration < source >

( config: MoshiConfig )

Parameters

The original Moshi model with an audio encoder, a Moshi depth decoder and a Moshi decoder, for speech-to-speech. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward < source >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.BoolTensor] = None user_input_values: typing.Optional[torch.FloatTensor] = None user_audio_codes: typing.Optional[torch.Tensor] = None moshi_input_values: typing.Optional[torch.FloatTensor] = None moshi_audio_codes: typing.Optional[torch.Tensor] = None past_key_values: typing.Tuple[typing.Tuple[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None text_labels: typing.Optional[torch.LongTensor] = None audio_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 **kwargs ) transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)

Parameters

A transformers.modeling_outputs.Seq2SeqLMOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (MoshiConfig) and inputs.

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

Examples:

>>> from transformers import MoshiForConditionalGeneration
>>> import torch

>>> model = MoshiForConditionalGeneration.from_pretrained("kmhf/hf-moshiko")
>>> inputs = moshi.get_unconditional_inputs()

>>> logits = model(**inputs, ).logits
>>> logits.shape  
torch.Size([1, 1, 32000])
generate < source >

( input_ids: typing.Optional[torch.LongTensor] = None user_input_values: typing.Optional[torch.FloatTensor] = None user_audio_codes: typing.Optional[torch.Tensor] = None moshi_input_values: typing.Optional[torch.FloatTensor] = None moshi_audio_codes: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None return_audio_waveforms: typing.Optional[bool] = True return_audio_codes: typing.Optional[bool] = None concat_unconditional_inputs: typing.Optional[bool] = True **kwargs )

Parameters

Generates sequences of text token ids and audio tokens ids.

get_unconditional_inputs < source >

( num_samples = 1 )

Parameters

Helper function to get null inputs for unconditional generation, enabling the model to be used without the feature extractor or tokenizer.

Example:

>>> from transformers import MoshiForConditionalGeneration

>>> model = MoshiForConditionalGeneration.from_pretrained("kmhf/hf-moshiko-pytorch-bf16")

>>> 
>>> unconditional_inputs = model.get_unconditional_inputs(num_samples=1)
>>> audio_samples = model.generate(**unconditional_inputs, max_new_tokens=256)
< > Update on GitHub

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.3