Moshi Guide: Real-Time Full-Duplex Speech-Text AI

Problem: The Cascaded Voice Pipeline Latency and Turn-Based Bottleneck
Conversational voice interaction is widely recognized as the most intuitive, natural interface between humans and intelligent systems. When operating high-throughput enterprise platforms—whether resolving real-time user inquiries from data pipelines established via real-time streaming data ingestion or deploying customer-facing conversational assistants informed by automated data extraction pipelines—voice provides unmatched immediacy.
Yet, despite massive advances in Large Language Models (LLMs), conversational voice agents in commercial deployment have historically suffered from an artificial, frustrating, and mechanical user experience. Users speak, wait in silence for multiple seconds, listen to a rigid monologue, and find themselves unable to interrupt, laugh, or offer simple conversational acknowledgments without derailing the system.
This fundamental breakdown stems from the ubiquitous architectural paradigm that has dominated voice engineering for over a decade: the cascaded turn-based pipeline.
+----------------------------------------------------------------------------------------------------+
| TRADITIONAL CASCADED VOICE PIPELINE (HALF-DUPLEX) |
+----------------------------------------------------------------------------------------------------+
| |
| [User Speaks] |
| │ |
| ▼ |
| +───────────+ Endpointing Delay + Audio Chunking (~300ms - 500ms) |
| │ ASR │ ──► Speech-to-Text Transcription (~200ms - 400ms) |
| +───────────+ Total ASR Stage: ~500ms - 900ms |
| │ |
| ▼ (Plain Text Only: ALL intonation, pitch, emotion, & hesitation stripped away) |
| +───────────+ Prompt Assembly + Network Transit (~100ms) |
| │ LLM │ ──► Prefill Processing + First Token Generation (~300ms - 800ms) |
| +───────────+ Total LLM Stage: ~400ms - 900ms |
| │ |
| ▼ (Generated Response Tokens) |
| +───────────+ Sentence/Clause Buffering (~200ms - 400ms) |
| │ TTS │ ──► Neural Vocoder Audio Synthesis (~300ms - 600ms) |
| +───────────+ Total TTS Stage: ~500ms - 1,000ms |
| │ |
| ▼ |
| [Agent Speaks] CUMULATIVE RESPONSE LATENCY: 1,400ms - 2,800ms (1.4s to 2.8s!) |
| |
+----------------------------------------------------------------------------------------------------+ The Compounding Latency Crisis
In human interpersonal communication, conversational turn-taking is remarkably fast. Psycholinguistic research across diverse languages demonstrates that the average gap between conversational turns in natural dialogue is approximately 230 milliseconds (Stivers et al., 2009). When a gap exceeds 500 milliseconds, human listeners subconsciously perceive awkwardness, hesitation, or cognitive disconnect.
Cascaded voice pipelines violate this physiological expectation by design. Because each module is decoupled, latency compounds additively across three independent stages:
- Automatic Speech Recognition (ASR) Delay: The system cannot begin transcribing audio accurately until Voice Activity Detection (VAD) confirms that the speaker has completed an utterance. This requires a silence threshold (typically 300ms to 700ms) to avoid cutting the speaker off mid-sentence. Once silence is detected, acoustic feature extraction and autoregressive token decoding add another 200ms to 400ms.
- Text LLM Processing Latency: The transcribed text must be wrapped in system instructions, context history, and tool schemas before being ingested by the LLM. Time-to-First-Token (TTFT) on a 70B parameter model typically consumes 200ms to 500ms, followed by token generation time.
- Text-to-Speech (TTS) Buffering Delay: Modern neural TTS engines (such as diffusion vocoders or autoregressive audio transformers) cannot synthesize natural prosody from single isolated words. They require complete phrases or punctuation-delimited clauses (4 to 8 words) before commencing audio synthesis, adding an unavoidable buffering delay of 300ms to 600ms before streaming audio begins.
When these independent latencies are combined, even an optimized enterprise cascade exhibits an end-to-end response time between 1.5 and 3.0 seconds. This delay shatters conversational flow, turning dialogue into a transactional walkie-talkie exchange.
The Turn-Based Half-Duplex Trap
Beyond latency, the cascaded approach enforces a rigid half-duplex turn-taking constraint:
- Discrete Speaker Ownership: The architecture assumes that a conversation is an alternating sequence of discrete, non-overlapping turns: Speaker A speaks while Speaker B listens, then Speaker B speaks while Speaker A listens.
- Barge-In Pathology: If the user speaks while the synthetic TTS voice is playing, the system must trigger a blunt “barge-in” mechanism that violently mutes the audio channel and flushes the LLM generation buffer. It cannot distinguish between a genuine interruption (“Stop, that’s incorrect!”) and a conversational affirmation (“Right, I agree”).
- Absence of Backchanneling: In natural human conversation, between 10% and 20% of spoken time consists of overlapping speech (Çetin and Shriberg, 2006). Attentive listeners continuously emit non-interruptive backchannels—such as “uh-huh,” “yeah,” “mm-hmm,” and slight head gestures—to communicate engagement without seizing the conversational floor. Cascaded systems are structurally incapable of backchanneling; any sound from the listener either halts the agent or is discarded as background noise.
The Paralinguistic Information Bottleneck
The most insidious limitation of the cascaded architecture is the textual bottleneck.
Speech carries vast amounts of communicative data that cannot be captured in a textual transcript:
- Emotional State & Tone: Sarcasm, urgency, frustration, confidence, and warmth are conveyed through pitch contours, vocal timbre, and speech rate. When an ASR system transcribes “Sure, that sounds great,” the LLM receives identical tokens whether the phrase was uttered with genuine enthusiasm or biting cynicism.
- Non-Verbal Vocalizations: Laughter, sighs, throat clearing, hesitations (“um,” “uh”), and breath patterns modulate the meaning of words. ASR pipelines either sanitize these vocalizations or misinterpret them as phonetic errors.
- Acoustic Environment: Reverberation, background voices, and ambient soundscapes contextualize the speaker’s environment, but are obliterated when converted to ASCII strings.
To resolve these structural bottlenecks, researchers at Kyutai—an open-science AI research lab in Paris—developed Moshi: a speech-text foundation model for real-time dialogue (arXiv:2410.00037). Moshi discards the cascaded pipeline entirely, unifying speech comprehension and speech synthesis into a single, end-to-end, multi-stream foundation model capable of full-duplex communication with sub-200ms latency.
Solution: End-to-End Multi-Stream Full-Duplex Speech Architecture
Moshi reconceptualizes conversational AI from first principles. Rather than converting audio to text, passing text to an LLM, and converting text back to audio, Moshi casts spoken dialogue as direct speech-to-speech autoregressive sequence modeling.
+----------------------------------------------------------------------------------------------------+
| MOSHI FULL-DUPLEX ARCHITECTURE |
+----------------------------------------------------------------------------------------------------+
| |
| USER INPUT STREAM MOSHI OUTPUT STREAM |
| (Continuous 24 kHz Audio) (Continuous 24 kHz Audio) |
| │ ▲ |
| ▼ │ |
| +─────────────────+ +─────────────────+ |
| │ Mimi Encoder │ │ Mimi Decoder │ |
| │ (12.5 Hz / 80ms)│ │ (12.5 Hz / 80ms)│ |
| +─────────────────+ +─────────────────+ |
| │ ▲ |
| ▼ │ |
| 8 RVQ Audio Tokens 8 RVQ Audio Tokens |
| [U_0, U_1, ..., U_7] [M_0, M_1, ..., M_7] |
| │ ▲ |
| │ │ |
| ▼ │ |
| +──────────────────────────────────────────────────────────────────────────────────────────+ |
| │ DUAL-TRANSFORMER HIERARCHICAL GENERATION ENGINE │ |
| │ │ |
| │ 1. Temporal Transformer (Helium 7B Backbone, 32 Layers, 4096 Hidden Dim, 4K Context) │ |
| │ Processes multi-stream history across time steps (t = 0, 1, 2, ..., T) │ |
| │ │ │ |
| │ ▼ │ |
| │ 2. Depth Transformer (6 Layers, 1024 Hidden Dim, Intra-Timestep Autoregressive) │ |
| │ Generates hierarchical token chain per 80ms frame: │ |
| │ │ |
| │ [Time-Aligned Text] ──► [Semantic Token] ──► [7 Fine Acoustic Tokens] │ |
| │ Inner Monologue Mimi RVQ 0 Mimi RVQ 1..7 │ |
| │ (Predicts Text Prefix) (Distilled WavLM) (Acoustic Audio Detail) │ |
| +──────────────────────────────────────────────────────────────────────────────────────────+ |
| |
| THEORETICAL LATENCY: 160ms | PRACTICAL DEPLOYMENT LATENCY: 200ms | FULL DUPLEX: ALWAYS ON |
| |
+----------------------------------------------------------------------------------------------------+ Core Tenets of the Moshi Paradigm
Moshi’s breakthrough rests upon four foundational architectural innovations:
1. Multi-Stream Token Representation: Instead of merging user and system utterances into a single serialized string of words, Moshi models two parallel audio streams continuously. At every 80ms time frame, the model ingests 8 discrete tokens representing user audio and generates 8 discrete tokens representing its own speech. Because both streams exist simultaneously, there are no speaker turns. The model naturally handles silence, single-speaker speech, overlapping interruptions, and conversational backchanneling.
2. The Mimi Neural Audio Codec: To enable autoregressive modeling over speech without exploding sequence length, Kyutai developed Mimi, an ultra-low-latency neural audio codec that operates at a remarkably low frame rate of 12.5 Hz (one frame every 80 milliseconds). Mimi employs a split Residual Vector Quantization (RVQ) scheme that distills semantic knowledge from WavLM into its first codebook while capturing fine acoustic detail across 7 subsequent codebooks, achieving pristine 24 kHz audio synthesis at a bandwidth of only 1.1 kbps.
3. Dual-Transformer Hierarchy: Rather than forcing a massive 7B parameter model to predict 16+ audio codebooks sequentially at every time step, Moshi splits compute between:
- A Temporal Transformer (the Helium 7B backbone) that attends across multi-minute conversational history along the time axis ($T$).
- A lightweight Depth Transformer (6 layers, 1024 hidden dimensions) that autoregressively predicts the hierarchical tokens (text, semantic audio, and fine acoustic codebooks) within each individual time step ($t$).
4. Inner Monologue Co-Speech Reasoning: Unconditioned speech language models often generate phonetic babble and hallucinate facts because audio tokens lack the abstract syntactic density of text. Moshi solves this by introducing Inner Monologue: before predicting the audio tokens for a given 80ms frame, the model predicts the corresponding time-aligned text token. The text token acts as an autoregressive prefix that guides semantic and acoustic generation, allowing Moshi to leverage the deep factual knowledge of its 7B text LLM backbone while outputting native speech.
Architecture: Helium Backbone, Mimi Codec, and Dual-Transformer Hierarchy
To understand how Moshi achieves streaming real-time performance, we must examine its three structural components: the Helium language model backbone, the Mimi neural audio codec, and the Dual-Transformer generation engine.
+----------------------------------------------------------------------------------------------------+
| MOSHI STRUCTURAL SPECIFICATIONS |
+------------------------------------+---------------------------------------------------------------+
| Component | Architectural Hyperparameters & Specifications |
+------------------------------------+---------------------------------------------------------------+
| Temporal Transformer (Helium) | 7 Billion parameters, 32 layers, hidden dimension 4,096 |
| | MLP dimension 11,264 (SwiGLU), 32 heads, RoPE embeddings |
| | Context length: 3,000 steps (~4 minutes of continuous audio) |
+------------------------------------+---------------------------------------------------------------+
| Depth Transformer | 6 layers, hidden dimension 1,024, MLP dimension 4,096 |
| | 16 attention heads, intra-frame cross-layer autoregression |
+------------------------------------+---------------------------------------------------------------+
| Mimi Neural Audio Codec | 24 kHz audio, 12.5 Hz frame rate (80ms frame stride) |
| | 8-level Split Residual Vector Quantization (RVQ) |
| | Codebook 0: Distilled semantic representation (from WavLM) |
| | Codebooks 1-7: High-fidelity acoustic detail reconstruction |
| | Bitrate: 1.1 kbps (12.5 frames/s * 8 codebooks * 11 bits) |
+------------------------------------+---------------------------------------------------------------+
| Latency Profile | Algorithmic latency: 80ms (Mimi codec frame stride) |
| | Lookahead buffer: 80ms (causal streaming convolution context) |
| | Total theoretical latency: 160ms (200ms in production WebRTC) |
+------------------------------------+---------------------------------------------------------------+ The Helium 7B Text LLM Backbone
The intellectual engine powering Moshi is Helium, a 7-billion-parameter text language model trained from scratch by Kyutai on 2.1 trillion tokens of curated English text.
Helium adheres to modern transformer best practices:
- Normalization: Root Mean Square Layer Normalization (RMSNorm) applied at the input of attention blocks, feed-forward networks, and output projection layers.
- Activation Functions: Gated Linear Units with Sigmoid Linear Units (SwiGLU) for enhanced expressiveness in MLP projections.
- Positional Encodings: Rotary Position Embeddings (RoPE) enabling smooth length extrapolation across extended sequence windows.
- Attention Mechanism: FlashAttention integration for memory-efficient computation.
- Tokenizer: Unigram SentencePiece vocabulary containing 32,000 tokens, with numbers split into single digits and byte-fallback encoding to prevent out-of-vocabulary serialization failures.
During conversational inference, Helium’s context window spans 3,000 temporal steps. Because each step represents an 80ms audio slice, the model maintains active temporal awareness across 4 minutes of continuous, unbroken dialogue.
The Mimi Neural Audio Codec: Semantic-Acoustic Split RVQ
Audio language modeling has historically faced an intractable dilemma:
- Semantic Tokens (e.g., w2v-BERT, HuBERT, WavLM): Carry rich linguistic information, making them easy for an LLM to predict, but discard speaker identity, pitch, emotion, and acoustic quality. They cannot reconstruct high-fidelity audio.
- Acoustic Codecs (e.g., EnCodec, SoundStream): Reconstruct pristine 24 kHz audio using Residual Vector Quantization (RVQ), but their codebooks are linguistically disorganized, causing LLMs to generate unintelligible garble.
Kyutai resolved this dilemma through Mimi, an innovative streaming codec featuring semantic distillation into a split RVQ:
+----------------------------------------------------------------------------------------------------+
| MIMI CODEC SPLIT RVQ ARCHITECTURE |
+----------------------------------------------------------------------------------------------------+
| |
| Input Waveform (24 kHz) |
| │ |
| ▼ |
| +───────────────────+ |
| │ Causal Conv1D Enc │ ──► Downsampling by 1920x (24,000 / 1920 = 12.5 Hz Frame Rate) |
| +───────────────────+ |
| │ |
| ▼ |
| +───────────────────+ |
| │ Transformer Block │ ──► Temporal Context Bottleneck |
| +───────────────────+ |
| │ |
| ▼ |
| +────────────────────────────────────────────────────────────────────────────────────────────+ |
| │ SPLIT RESIDUAL VECTOR QUANTIZATION (RVQ) │ |
| │ │ |
| │ Codebook 0 (Semantic): Distilled directly from frozen WavLM Layer 7 │ |
| │ ├── Captures phonemes, linguistic syntax, and speech intent │ |
| │ └── Cardinality: 2,048 entries (11 bits) │ |
| │ │ |
| │ Codebooks 1 to 7 (Acoustic Detail): Successive residual error quantization │ |
| │ ├── Codebook 1: Quantizes residual error e_1 = Latent - Q_0(Latent) │ |
| │ ├── Codebook 2: Quantizes residual error e_2 = e_1 - Q_1(e_1) │ |
| │ └── Codebooks 3-7: Reconstruct high-frequency harmonics, vocal timbre, & room acoustics │ |
| │ └── Total Codebooks: 8 | Cumulative Bitrate: 1.1 kbps │ |
| +────────────────────────────────────────────────────────────────────────────────────────────+ |
| │ |
| ▼ |
| +───────────────────+ |
| │ Causal Conv1D Dec │ ──► Synthesizes 24 kHz Audio Waveform (Lookahead Context: 80ms) |
| +───────────────────+ |
| |
+----------------------------------------------------------------------------------------------------+ By distilling WavLM features into the very first quantization layer ($Q_0$), Mimi ensures that token 0 represents pure semantic content. The subsequent 7 quantization layers ($Q_1$ through $Q_7$) model acoustic residuals. This allows Moshi to predict language structure and acoustic timbre in a unified, hierarchical framework.
Dual-Transformer Hierarchy: Conquering the Combinatorial Explosion
In a full-duplex setup modeling user audio, system audio, and text, each 80ms timestep contains:
- 1 User Text Token (optional)
- 8 User Audio Tokens ($U_0 \dots U_7$)
- 1 System Text Token (Inner Monologue)
- 8 System Audio Tokens ($M_0 \dots M_7$)
Predicting all 18 tokens sequentially inside a 7B parameter autoregressive model would increase sequence length by a factor of 18, crushing inference throughput.
To solve this, Moshi adopts a Dual-Transformer hierarchy:
- The Temporal Transformer (Helium 7B): Operates exclusively along the time axis ($t = 1 \dots T$). At each step $t$, it consumes the combined representation of the preceding frame’s tokens and outputs a rich contextual hidden state $H_t \in \mathbb{R}^{4096}$.
- The Depth Transformer (Small 6-Layer Transformer): Operates within the current timestep ($t$). Conditioned on $H_t$, it autoregressively predicts the text token, then semantic token $M_0$, then acoustic tokens $M_1 \dots M_7$.
This division of labor keeps the massive 7B model running at a relaxed 12.5 Hz clock speed while the tiny 6-layer model rapidly handles intra-frame token dependencies in parallel.
Implementation: Inner Monologue Alignment and Streaming Multi-Stream Inference
To understand how Moshi synchronizes text reasoning with raw acoustic generation, we must explore the mechanics of Inner Monologue and examine a functional PyTorch reference implementation.
+----------------------------------------------------------------------------------------------------+
| INNER MONOLOGUE INTRA-FRAME HIERARCHY |
+----------------------------------------------------------------------------------------------------+
| |
| Timestep t Hidden State from Temporal Transformer (H_t in R^4096) |
| │ |
| ▼ |
| +────────────────────────+ |
| │ Linear Projection Down │ ──► Projects 4096 dim to 1024 dim |
| +────────────────────────+ |
| │ |
| ▼ |
| [Depth Step 0] ──► Predicts System Text Token (Inner Monologue: "Hello", "How", <pad>) |
| │ ├── Forces model to establish semantic text plan BEFORE speaking |
| ▼ |
| [Depth Step 1] ──► Predicts Semantic Audio Token (Mimi RVQ Codebook 0) |
| │ ├── Conditioned on predicted text token + user audio history |
| ▼ |
| [Depth Step 2] ──► Predicts Acoustic Audio Token 1 (Mimi RVQ Codebook 1) |
| │ |
| ▼ |
| [Depth Step 3..8] Predicts Fine Acoustic Tokens 2 to 7 (Mimi RVQ Codebooks 2..7) |
| └── Reconstructs prosody, emotion, breath, and high-frequency timbre |
| |
+----------------------------------------------------------------------------------------------------+ Inner Monologue and Token Delay Dynamics
Human speakers do not formulate speech phoneme-by-phoneme in acoustic isolation; the brain plans semantic word concepts milliseconds before motor neurons engage the vocal cords.
Inner Monologue replicates this cognitive architecture:
- At timestep $t$, the Depth Transformer first emits a text token from Helium’s 32,000-token vocabulary.
- If a word spans multiple 80ms frames, subsequent frames emit a special padding token (
<pad>), maintaining strict time alignment with speech audio. - The emitted text token is projected into the Depth Transformer’s state, directly conditioning the emission of semantic token $M_0$ and acoustic tokens $M_1 \dots M_7$.
Furthermore, Kyutai introduced an Acoustic Delay ($\tau_{\text{audio}}$) and a Text Delay ($\tau_{\text{text}}$) during training. Setting an acoustic delay of 1 frame ($\tau_{\text{audio}} = 1$) ensures that the model observes user audio tokens at frame $t$ before finalizing its own acoustic response at frame $t + 1$. This subtle delay provides the transformer with causal foresight, drastically reducing phonemic stuttering and audio artifacts.
PyTorch Architecture Implementation
The following complete PyTorch module demonstrates the multi-stream conditioning loop, the Depth Transformer execution, and the Inner Monologue token generation pipeline:
# Moshi Spoken Dialogue Engine: Multi-Stream Full-Duplex Implementation
# Reference architecture demonstrating Helium Temporal Transformer conditioning,
# Inner Monologue text prefixing, and Depth Transformer RVQ decoding.
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Dict, List, Optional, Tuple
class MimiCodecEmbedding(nn.Module):
# Embeds multi-codebook RVQ audio tokens for both user and system streams.
# Compresses 8 codebooks per stream into a unified temporal dimension.
def __init__(self, num_codebooks: int = 8, codebook_size: int = 2048, embed_dim: int = 1024):
super().__init__()
self.num_codebooks = num_codebooks
self.embed_dim = embed_dim
# Independent embeddings for each RVQ level
self.embeddings = nn.ModuleList([
nn.Embedding(codebook_size, embed_dim) for _ in range(num_codebooks)
])
self.projection = nn.Linear(num_codebooks * embed_dim, embed_dim)
def forward(self, tokens: torch.Tensor) -> torch.Tensor:
# tokens: [batch_size, seq_len, num_codebooks]
batch_size, seq_len, _ = tokens.shape
embedded = []
for k in range(self.num_codebooks):
embedded.append(self.embeddings[k](tokens[:, :, k]))
# Concatenate along channel dimension and project
concat_emb = torch.cat(embedded, dim=-1)
return self.projection(concat_emb) # [batch_size, seq_len, embed_dim]
class DepthTransformer(nn.Module):
# Lightweight 6-layer Transformer modeling intra-timestep hierarchical token generation.
# Generates: Text Token -> Semantic RVQ 0 -> Acoustic RVQ 1..7.
def __init__(
self,
depth_dim: int = 1024,
num_layers: int = 6,
num_heads: int = 16,
mlp_dim: int = 4096,
text_vocab_size: int = 32000,
audio_codebook_size: int = 2048,
num_audio_codebooks: int = 8
):
super().__init__()
self.depth_dim = depth_dim
self.num_audio_codebooks = num_audio_codebooks
# Embeddings for intra-step autoregressive generation
self.text_embed = nn.Embedding(text_vocab_size, depth_dim)
self.audio_embeds = nn.ModuleList([
nn.Embedding(audio_codebook_size, depth_dim) for _ in range(num_audio_codebooks)
])
# Transformer Decoder Layers
decoder_layer = nn.TransformerEncoderLayer(
d_model=depth_dim,
nhead=num_heads,
dim_feedforward=mlp_dim,
activation="gelu",
batch_first=True,
norm_first=True
)
self.transformer = nn.TransformerEncoder(decoder_layer, num_layers=num_layers)
# Output prediction heads
self.text_head = nn.Linear(depth_dim, text_vocab_size, bias=False)
self.audio_heads = nn.ModuleList([
nn.Linear(depth_dim, audio_codebook_size, bias=False) for _ in range(num_audio_codebooks)
])
def forward(
self,
temporal_context: torch.Tensor,
prefix_text_tokens: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
# Executes intra-timestep autoregressive decoding.
# temporal_context: [batch_size, 1, depth_dim] - Hidden state from Helium 7B
# Returns:
# pred_text_logits: [batch_size, text_vocab_size]
# pred_audio_logits: [batch_size, num_codebooks, audio_codebook_size]
batch_size = temporal_context.shape[0]
device = temporal_context.device
# Step 1: Predict Inner Monologue Text Token
text_logits = self.text_head(temporal_context.squeeze(1)) # [batch_size, text_vocab]
pred_text_id = text_logits.argmax(dim=-1)
# Use ground truth prefix if provided (teacher forcing), else predicted token
active_text_id = prefix_text_tokens if prefix_text_tokens is not None else pred_text_id
text_representation = self.text_embed(active_text_id).unsqueeze(1)
# Step 2: Formulate sequence for Depth Transformer: [Temporal_Ctx, Text_Token]
current_sequence = torch.cat([temporal_context, text_representation], dim=1)
audio_logits_list = []
# Step 3: Autoregressively predict 8 RVQ Audio Codebooks
for k in range(self.num_audio_codebooks):
# Apply causal depth attention
transformed = self.transformer(current_sequence)
latest_hidden = transformed[:, -1, :] # Most recent position
# Predict kth codebook logits
kth_logits = self.audio_heads[k](latest_hidden)
audio_logits_list.append(kth_logits.unsqueeze(1))
# Sample token and append embedding for next depth step
kth_token = kth_logits.argmax(dim=-1)
kth_emb = self.audio_embeds[k](kth_token).unsqueeze(1)
current_sequence = torch.cat([current_sequence, kth_emb], dim=1)
audio_logits = torch.cat(audio_logits_list, dim=1) # [batch_size, 8, codebook_size]
return text_logits, audio_logits
class MoshiDialogueEngine(nn.Module):
# Top-Level Moshi Foundation Model Architecture.
# Coordinates Helium 7B Temporal Backbone and Depth Transformer across multi-stream inputs.
def __init__(
self,
temporal_dim: int = 4096,
depth_dim: int = 1024,
num_codebooks: int = 8,
codebook_size: int = 2048
):
super().__init__()
self.temporal_dim = temporal_dim
self.depth_dim = depth_dim
# Input token encoders for User Audio and Moshi Audio
self.user_audio_embed = MimiCodecEmbedding(num_codebooks, codebook_size, depth_dim)
self.moshi_audio_embed = MimiCodecEmbedding(num_codebooks, codebook_size, depth_dim)
# Temporal Stream Fusion Layer
self.fusion_projection = nn.Linear(depth_dim * 2, temporal_dim)
# Simulated Helium 7B Temporal Backbone (32 layers in production)
self.temporal_backbone_norm = nn.LayerNorm(temporal_dim)
self.temporal_to_depth = nn.Linear(temporal_dim, depth_dim)
# Depth Transformer for intra-step token generation
self.depth_engine = DepthTransformer(
depth_dim=depth_dim,
num_audio_codebooks=num_codebooks,
audio_codebook_size=codebook_size
)
def forward_step(
self,
user_audio_step: torch.Tensor,
prev_moshi_audio_step: torch.Tensor,
recurrent_temporal_state: torch.Tensor
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
# Executes single 80ms streaming step.
# user_audio_step: [batch_size, 1, 8] - Mimi RVQ tokens from microphone
# prev_moshi_audio_step: [batch_size, 1, 8] - Mimi RVQ tokens from Moshi output t-1
# recurrent_temporal_state: [batch_size, 1, 4096] - Context state
# 1. Embed incoming user and feedback audio streams
user_emb = self.user_audio_embed(user_audio_step) # [batch_size, 1, 1024]
moshi_emb = self.moshi_audio_embed(prev_moshi_audio_step) # [batch_size, 1, 1024]
# 2. Fuse multi-stream inputs into temporal space
multi_stream_concat = torch.cat([user_emb, moshi_emb], dim=-1)
step_input = self.fusion_projection(multi_stream_concat) # [batch_size, 1, 4096]
# 3. Update temporal hidden state (Helium backbone step)
updated_state = self.temporal_backbone_norm(step_input + recurrent_temporal_state)
# 4. Project down to Depth Transformer dimension
depth_context = self.temporal_to_depth(updated_state) # [batch_size, 1, 1024]
# 5. Execute Inner Monologue & Hierarchical Audio Generation
text_logits, audio_logits = self.depth_engine(depth_context)
return text_logits, audio_logits, updated_state
if __name__ == "__main__":
print("Initializing Moshi Spoken Dialogue Engine...")
model = MoshiDialogueEngine()
# Simulate a single 80ms streaming frame
batch_size = 1
dummy_user_tokens = torch.randint(0, 2048, (batch_size, 1, 8))
dummy_prev_moshi = torch.randint(0, 2048, (batch_size, 1, 8))
dummy_state = torch.zeros(batch_size, 1, 4096)
text_out, audio_out, next_state = model.forward_step(
dummy_user_tokens, dummy_prev_moshi, dummy_state
)
print("Step Execution Successful!")
print(f"Predicted Text Logits Shape: {text_out.shape} (Inner Monologue)")
print(f"Predicted Audio Logits Shape: {audio_out.shape} (8 RVQ Codebooks)")
print(f"Updated Temporal State Shape: {next_state.shape}") Comparison: Cascaded Pipelines vs. End-to-End Voice AI Benchmarks
To quantify the performance gains realized by Moshi’s end-to-end architecture, we contrast it against traditional cascaded systems, proprietary speech models (such as GPT-4o Voice and Gemini Live), and earlier open-source research prototypes (Mini-Omni, SpeechGPT, dGSLM).
+--------------------------------------------------------------------------------------------------------------------------------+
| COMPREHENSIVE CONVERSATIONAL VOICE AI BENCHMARK MATRIX |
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Evaluation Vector | Cascaded Pipeline | GPT-4o Voice Mode | Mini-Omni | dGSLM (2023) | Moshi (Kyutai) |
| | (Whisper+Llama+TTS)| (OpenAI Proprietary)| (SNU / OpenSource) | (Meta AI) | (Open Weights) |
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Architecture Paradigm | Cascaded 3-Stage | End-to-End Native | Audio Adapter over | Multi-Stream | Dual-Transformer |
| | (ASR -> LLM -> TTS)| Multimodal Model | Llama-3 8B | Unit Language M | (Helium 7B + Depth)|
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Response Latency (TTFT) | 1,400ms - 2,800ms | 240ms - 350ms | 350ms - 500ms | 1,200ms (Batch) | 160ms - 200ms |
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Duplex Capability | Half-Duplex Only | Full-Duplex Native | Half-Duplex Turn | Full-Duplex | Full-Duplex Native |
| | (VAD Turn Cutting) | (Interruption-Aware)| (VAD Based) | Proof-of-Concept| (Continuous Stream)|
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Overlapping Speech | Fails Completely | Supported | Fails (Triggers | Supported | Supported |
| Handling | (Barge-In Flush) | | Interruption Stop) | | Naturally |
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Spontaneous | Impossible | Supported | Impossible | Supported | Supported |
| Backchanneling | (Treats as Turn) | | (Treats as Turn) | (Non-Linguistic)| (Text & Acoustic) |
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Paralinguistic Input | Zero (All acoustic | High (Detects tone, | Moderate | Low | High (Processes raw|
| (Emotion, Sarcasm) | signals stripped) | laughter, pacing) | | | Mimi audio tokens) |
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Codec Frame Rate | N/A (WAV Buffer) | Proprietary | 25 Hz (SNAC) | 50 Hz (HuBERT) | 12.5 Hz (Mimi) |
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Total Audio Bandwidth | ~64 kbps (Opus) | Proprietary | ~2.4 kbps | ~3.2 kbps | 1.1 kbps |
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+
| Open Weights / Code | Open Weights | Closed Proprietary | Open Weights | Open Weights | Fully Open Weights |
| Availability | (Modular Pieces) | API Access Only | (Research Only) | (Unmaintained) | (Apache 2.0 / CC) |
+-------------------------+--------------------+---------------------+--------------------+-----------------+--------------------+ Empirical Benchmark Findings
In empirical evaluations conducted across spoken reasoning, speech intelligibility, and acoustic quality benchmarks, Moshi demonstrates remarkable capabilities:
1. Spoken Question Answering (Spoken SQuAD & CoQA):
- Evaluated on Spoken SQuAD, Moshi achieves an Exact Match (EM) score of 71.4% and an F1 score of 80.2%.
- Prior speech-to-speech models that lacked an Inner Monologue mechanism (such as Spectron and SpeechGPT) scored under 58% F1 due to phonetic divergence during multi-sentence generation.
- By prefixing audio generation with time-aligned text tokens, Moshi matches the factual question-answering accuracy of pure text LLMs while maintaining live speech delivery.
2. Speech Intelligibility & Word Error Rate (WER):
- When transcribing Moshi’s generated audio through an independent Whisper-Large-v3 ASR model, Moshi achieves a Word Error Rate of 4.2% on conversational English.
- Unconditioned audio language models (AudioLM, TWIST) exhibit WERs exceeding 18.5% due to phonetic drift over extended sequences. Moshi’s semantic WavLM distillation in Mimi Codebook 0 ensures crisp consonantal boundaries and natural vowel articulation.
3. Audio Reconstruction & Naturalness (UTMOS & PESQ):
- Mimi achieves a Perceptual Evaluation of Speech Quality (PESQ) score of 3.42 and a UTMOS naturalness score of 4.15 at just 1.1 kbps.
- In comparison, EnCodec requires 6.0 kbps to achieve a 3.38 PESQ score. Mimi’s adversarial training loss and causal transformer bottleneck deliver superior subjective audio fidelity at less than one-fifth the transmission bitrate.
Production: Deployment Strategies, Quantization, and Real-Time Serving
Deploying an end-to-end full-duplex conversational model in enterprise production introduces unique infrastructure considerations. Because Moshi continuously streams bidirectional audio at 12.5 Hz, standard HTTP request-response patterns are obsolete. Production deployments must leverage low-latency protocols, GPU kernel optimizations, and intelligent memory management.
+----------------------------------------------------------------------------------------------------+
| MOSHI PRODUCTION SERVING TOPOLOGY |
+----------------------------------------------------------------------------------------------------+
| |
| Client Browser / Mobile App |
| ├── Captures 24 kHz Microphone Audio via WebAudio API |
| └── Encodes PCM Frames into WebRTC Data Channel / Opus Stream |
| │ |
| ▼ (Sub-30ms Network Transit via UDP) |
| +──────────────────────────────────────────────────────────────────────────────────────────+ |
| │ RUST WEBRTC GATEWAY (MOSHI-SERVER / ACTIX-WEB) │ |
| │ ├── Terminates WebRTC PeerConnection & Jitter Buffering │ |
| │ ├── Decodes Opus to 24 kHz Float32 PCM Audio │ |
| │ └── Packages 80ms Chunks (1920 samples) into Cuda IPC Shared Memory Buffer │ |
| +──────────────────────────────────────────────────────────────────────────────────────────+ |
| │ |
| ▼ (Zero-Copy Shared Memory Pointer) |
| +──────────────────────────────────────────────────────────────────────────────────────────+ |
| │ TENSORRT-LLM / PYTORCH GPU INFERENCE WORKER │ |
| │ │ |
| │ 1. Mimi Causal Encoder: 1920 PCM samples ──► 8 RVQ Tokens (0.8ms GPU time) │ |
| │ 2. Helium 7B Temporal Step: PagedAttention KV Cache + FlashInfer (14.2ms GPU time) │ |
| │ 3. Depth Transformer Engine: 6 Layers Autoregressive Loop (5.4ms GPU time) │ |
| │ 4. Mimi Causal Decoder: 8 RVQ Tokens ──► 1920 PCM Audio Output (1.1ms GPU time) │ |
| │ │ |
| │ TOTAL COMPUTE TIME PER 80ms FRAME: ~21.5ms (3.7x Faster than Real-Time!) │ |
| +──────────────────────────────────────────────────────────────────────────────────────────+ |
| │ |
| ▼ |
| Moshi Audio Streamed Back over WebRTC with <200ms Glass-to-Glass Latency |
| |
+----------------------------------------------------------------------------------------------------+ Quantization and VRAM Budgeting
The standard FP16 checkpoint of Moshi Helium 7B requires approximately 15.5 GB of VRAM for weights alone, plus 2 to 4 GB for KV cache allocation across active sessions.
To maximize concurrency and enable deployment on cost-effective enterprise hardware (such as single Nvidia L4 or RTX 4090 GPUs), Moshi supports modern post-training quantization:
- INT4 Weight-Only Quantization (AWQ / Marlin): Compresses model weight footprint to 4.2 GB. Executes matrix-vector multiplications via optimized Marlin FP16xINT4 kernels, maintaining full 16-bit activation fidelity. Reduces VRAM consumption by 72% with less than 0.8% degradation in Spoken SQuAD accuracy.
- FP8 Quantization (Ada Lovelace & Hopper Architectures): Supported natively on Nvidia H100, L4, and RTX 4090. Fits the full model and a 16-session concurrent KV cache into 8.5 GB of VRAM. Eliminates dequantization overhead, accelerating temporal forward passes by up to 1.8x.
Managing Streaming Jitter and Buffer Underruns
In a full-duplex system operating at 80ms per frame, any network jitter or scheduling delay will cause audible clicks or dropouts in user audio:
- Jitter Buffer Configuration: The WebRTC gateway must maintain an adaptive 40ms to 80ms jitter buffer. Because Mimi’s causal lookahead requires one future frame for optimal vocoding, aligning the network buffer with the codec lookahead introduces zero net perceptual penalty.
- Silence Masking: When network packets are lost, the gateway injects Mimi padding tokens corresponding to neutral ambient silence rather than zeroing the waveform, preventing harsh acoustic pops.
Grounding and Knowledge Retrieval
While Moshi processes audio end-to-end, enterprise dialogue systems frequently require access to live external databases.
Developers can integrate live knowledge through a hybrid retrieval loop:
- As Moshi’s Inner Monologue emits text tokens in real time, a background daemon parses completed noun phrases and entities.
- The daemon queries indexed vector stores or enterprise data pipelines built on custom API integration endpoints.
- Relevant factual snippets are injected into Helium’s temporal context buffer as hidden prompting signals, dynamically updating Moshi’s factual grounding without interrupting ongoing vocal delivery. For organizations scaling multimodal agent infrastructure, consulting production infrastructure tiers and reviewing developer integration documentation ensures optimal hardware sizing and deployment reliability.
By merging the expressive power of neural audio codecs with the intellectual depth of 7B language backbones, Moshi establishes the blueprint for the next generation of conversational AI: real-time, emotionally aware, and truly full-duplex.