Transformers documentation

VibeVoice

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2025-08-26 在 HF papers 上发布,并于 2026-08-27 贡献至 Hugging Face Transformers。

VibeVoice

FlashAttention SDPA

概述

VibeVoice 是一个新颖的框架,通过在大型语言模型(LLM)结构中采用下一 token 扩散方法,来合成高保真、长篇幅的多说话人语音。它旨在捕捉真实对话的“氛围”,尤其适合生成播客和多参与者有声读物等音频内容。

两个模型检查点可在以下位置获取:

该模型由 Eric Bezzam 贡献。

架构

VibeVoice 框架集成了三个关键组件:

  1. 连续语音分词器:专用的声学和语义分词器,其中声学分词器使用 $\sigma$-VAE 实现超低压缩率(7.5 tokens/sec,3200x),以兼顾可扩展性与保真度;语义分词器则使用 ASR 代理任务进行以内容为中心的特征提取。
  2. 大语言模型(LLM):使用 Qwen2.5(1.5B 和 7B 版本)作为其核心序列模型。
  3. Token 级扩散头:以 LLM 的隐藏状态为条件,负责以流式方式预测连续的 VAE 特征。

原始的 VibeVoice-1.5B 检查点在 Hugging Face 的 Microsoft 组织下可用。

主要功能

  • 长文本合成:可合成长达 90 分钟的多说话人对话语音。
  • 多说话人对话:能够合成最多包含 4 位说话人的音频。
  • 业界领先的质量:在主观和客观指标上均优于基线模型。
  • 高压缩率:通过一种以超低 7.5 Hz 帧率运行的新型声学分词器实现。
  • 可扩展的 LLM:将核心 LLM 从 1.5B 扩展到 7B,可显著提升感知质量。

用法

设置

音频生成依赖于扩散过程,因此需要一个噪声调度器。最简单的方法(也是模型开发者所采用的方式)是使用 diffusers 库中的噪声调度器。默认情况下,模型会在内部使用 diffusers 创建一个噪声调度器。

pip install diffusers
pip install soundfile   # for saving audio

加载模型

from transformers import AutoProcessor, AutoModelForTextToWaveform

model_id = "vibevoice/VibeVoice-1.5B-hf"  # "vibevoice/VibeVoice-7B-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTextToWaveform.from_pretrained(model_id)

文本转语音(TTS)

import os
from transformers import AutoProcessor, AutoModelForTextToWaveform

model_id = "vibevoice/VibeVoice-1.5B-hf"   # "vibevoice/VibeVoice-7B-hf"
text = "Hello, nice to meet you. How are you?"

# Load model
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTextToWaveform.from_pretrained(model_id, device_map="auto")

# Prepare input
conversation = [{"role": "0", "content": [{"type": "text", "text": text}]}]
inputs = processor.apply_chat_template(
    conversation, return_dict=True, tokenize=True, add_generation_prompt=True,
).to(model.device, model.dtype)

# Generate!
audio = model.generate(**inputs)

# Save to file
file_name = f"{os.path.basename(model_id)}_tts.wav"
processor.save_audio(audio, file_name)
print(f"Saved output to {file_name}")

TTS 语音克隆

可以通过在聊天模板字典中同时提供参考音频和文本,来克隆语音。

import os
from transformers import AutoProcessor, AutoModelForTextToWaveform, set_seed

model_id = "vibevoice/VibeVoice-1.5B-hf"   # "vibevoice/VibeVoice-7B-hf"
text = "Hello, nice to meet you. How are you?"
set_seed(42)  # for deterministic results

# Load model
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTextToWaveform.from_pretrained(model_id, device_map="auto")
sampling_rate = processor.feature_extractor.sampling_rate

# Prepare input
conversation = [
    {
        "role": "0",
        "content": [
            {"type": "text", "text": text},
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Alice_woman.wav",
            },
        ],
    }
]
inputs = processor.apply_chat_template(
    conversation, return_dict=True, tokenize=True, add_generation_prompt=True,
).to(model.device, model.dtype)

# Generate!
audio = model.generate(**inputs)

# Save to file
fn = f"{os.path.basename(model_id)}_tts_clone.wav"
processor.save_audio(audio, fn)
print(f"Saved output to {fn}")

根据脚本生成播客

以下是一个示例,用于生成两位说话者之间的对话。通过为聊天模板中的每个唯一角色 ID 提供参考音频,即可克隆其声音。

下面的示例还使用了 monitor_progress 选项来跟踪生成进度。

import os
import time
from transformers import AutoProcessor, AutoModelForTextToWaveform

model_id = "vibevoice/VibeVoice-1.5B-hf"   # "vibevoice/VibeVoice-7B-hf"
max_new_tokens = 400  # `None` to ensure full generation

# create conversation with an audio for the first time a speaker appears to clone that particular voice
conversation = [
    {
        "role": "0",
        "content": [
            {
                "type": "text", "text": "Hello everyone, and welcome to the VibeVoice podcast. I'm your host, Linda, and today we're getting into one of the biggest debates in all of sports: who's the greatest basketball player of all time? I'm so excited to have Thomas here to talk about it with me.",
            },
            {
                "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Alice_woman.wav",
            },
        ],
    },
    {
        "role": "1",
        "content": [
            {
                "type": "text", "text": "Thanks so much for having me, Linda. You're absolutely right—this question always brings out some seriously strong feelings.",
            },
            {
                "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Frank_man.wav",
            },
        ],
    },
    {
        "role": "0",
        "content": [
            {
                "type": "text", "text": "Okay, so let's get right into it. For me, it has to be Michael Jordan. Six trips to the Finals, six championships. That kind of perfection is just incredible.",
            },
        ],
    },
    {
        "role": "1",
        "content": [
            {
                "type": "text", "text": "Oh man, the first thing that always pops into my head is that shot against the Cleveland Cavaliers back in '89. Jordan just rises, hangs in the air forever, and just sinks it",
            },
        ],
    },
]

# Load model
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTextToWaveform.from_pretrained(model_id, device_map="auto")

# prepare inputs
inputs = processor.apply_chat_template(
    conversation, return_dict=True, tokenize=True, add_generation_prompt=True,
).to(model.device, model.dtype)

# Generate audio with a progress bar to track generation
model.generation_config.max_new_tokens = max_new_tokens
start_time = time.time()
audio = model.generate(**inputs, monitor_progress=True)
generation_time = time.time() - start_time
print(f"Generation time: {generation_time:.2f} seconds")

# Save audio
fn = f"{os.path.basename(model_id)}_script.wav"
processor.save_audio(audio, fn)
print(f"Saved output to {fn}")

批量推理

对于批量处理,可以将对话列表传递给 processor.apply_chat_template:

import os
import time
from transformers import AutoProcessor, AutoModelForTextToWaveform

model_id = "vibevoice/VibeVoice-1.5B-hf"   # "vibevoice/VibeVoice-7B-hf"
max_new_tokens = 400  # `None` to ensure full generation

conversation = [
    [
        {
            "role": "0",
            "content": [
                {
                    "type": "text", "text": "Hello everyone, and welcome to the VibeVoice podcast. I'm your host, Linda, and today we're getting into one of the biggest debates in all of sports: who's the greatest basketball player of all time? I'm so excited to have Thomas here to talk about it with me.",
                },
                {
                    "type": "audio",
                    "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Alice_woman.wav",
                },
            ],
        },
        {
            "role": "1",
            "content": [
                {
                    "type": "text", "text": "Thanks so much for having me, Linda.",
                },
                {
                    "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Frank_man.wav",
                },
            ],
        },
    ],
    [
        {
            "role": "0",
            "content": [
                {
                    "type": "text", "text": "Hello and welcome to Planet in Peril. I'm your host, Alice. We're here today to discuss a really sobering new report that looks back at the last ten years of climate change. I'm joined by our expert panel. Welcome Carter, Frank, and Maya.",
                },
                {
                    "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Alice_woman.wav",
                },
            ],
        },
        {
            "role": "1",
            "content": [
                {"type": "text", "text": "Hi Alice, it's great to be here. I'm Carter."},
                {
                    "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Carter_man.wav",
                },
            ],
        },
        {
            "role": "2",
            "content": [
                {"type": "text", "text": "Hello, uh, I'm Frank. Good to be on."},
                {
                    "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Frank_man.wav",
                },
            ],
        },
        {
            "role": "3",
            "content": [
                {"type": "text", "text": "And I'm Maya. Thanks for having me."},
                {
                    "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Maya_woman.wav",
                },
            ],
        },
    ],
]

# Load model
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTextToWaveform.from_pretrained(model_id, device_map="auto")

# prepare inputs
inputs = processor.apply_chat_template(
    conversation, return_dict=True, tokenize=True, add_generation_prompt=True,
).to(model.device, model.dtype)

# Generate audio with a progress bar to track generation
model.generation_config.max_new_tokens = max_new_tokens
start_time = time.time()
audio = model.generate(**inputs, monitor_progress=True)
generation_time = time.time() - start_time
print(f"Generation time: {generation_time:.2f} seconds")

# Save audio
output_dir = f"{os.path.basename(model_id)}_batch"
processor.save_audio(audio, output_dir)
print(f"Saved output to {output_dir}")

Pipeline 用法

VibeVoice 也可以作为 pipeline 加载。下面还展示了如何调整扩散参数。

import os
import soundfile as sf
from transformers import pipeline

model_id = "vibevoice/VibeVoice-1.5B-hf"   # "vibevoice/VibeVoice-7B-hf"
text = "Hello, nice to meet you. How are you?"
pipe = pipeline("text-to-speech", model=model_id)

# Generate!
conversation = [
    {
        "role": "0",
        "content": [
            {"type": "text", "text": text},
            {
                "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/voices/en-Alice_woman.wav",
            },
        ],
    }
]
# optional kwargs for generation
generate_kwargs = {"guidance_scale": 1.3, "num_diffusion_steps": 10}
output = pipe(conversation, generate_kwargs=generate_kwargs)

# Save to file
fn = f"{os.path.basename(model_id)}_pipeline.wav"
sf.write(fn, output["audio"], output["sampling_rate"])
print(f"Saved output to {fn}")

训练

VibeVoice 可以使用模型输出的损失进行训练。

from transformers import AutoProcessor, AutoModelForTextToWaveform


model_id = "vibevoice/VibeVoice-1.5B-hf"   # "vibevoice/VibeVoice-7B-hf"

# Load model and processor
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTextToWaveform.from_pretrained(
    model_id,
    diffusion_loss_weight=0.75,  # by default, equal weighting (0.5) of language modeling loss (CE) and diffusion loss is applied
    device_map="auto"
)
model.train()

# Prepare batch of 2
conversation = [
    [
        {
            "role": "0",
            "content": [
                {
                    "type": "text", "text": "VibeVoice is this novel framework designed for generating expressive, long-form, multi-speaker, conversational audio.",
                },
                {
                    "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
                },
            ],
        }
    ],
    # NOTE: multiple speakers not supported yet
    [
        {
            "role": "0",
            "content": [
                {
                    "type": "text", "text": "Hello everyone and welcome to the VibeVoice podcast. I'm your host, Alex, and today we're getting into one of the biggest debates in all of sports: who's the greatest basketball player of all time? I'm so excited to have Sam here to talk about it with me. Thanks so much for having me, Alex. And you're absolutely right. This question always brings out some seriously strong feelings. Okay, so let's get right into it. For me, it has to be Michael Jordan. Six trips to the finals, six championships. That kind of perfection is just incredible. Oh man, the first thing that always pops into my head is that shot against the Cleveland Cavaliers back in '89. Jordan just rises, hangs in the air forever, and just sinks it.",
                },
                {
                    "type": "audio",
                    "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/example_output/VibeVoice-1.5B_output.wav",
                },
            ],
        }
    ],
]

# Process with apply_chat_template and output_labels=True for training
inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    return_dict=True,
    processor_kwargs={"output_labels": True},
).to(model.device, model.dtype)

# Forward pass
outputs = model(**inputs, ddpm_batch_multiplier=2, num_diffusion_steps=2)
print(f"Total loss: {outputs.loss.item():.4f}")

# Backward pass
outputs.loss.backward()

Torch 编译

该模型可以使用 torch.compile 进行编译,以加快推理速度。在编译后的模型达到全速之前,需要进行几次预热运行。

在 A100 上,当 batch size 为 4 时,我们观察到编译后的推理相比未编译的推理有约 1.5 倍的加速效果,详见 此脚本。

import os
import time
import torch
from transformers import AutoModelForTextToWaveform, AutoProcessor, CompileConfig


model_id = "vibevoice/VibeVoice-1.5B-hf"   # "vibevoice/VibeVoice-7B-hf"
num_warmup = 5
max_new_tokens = 128

torch.set_float32_matmul_precision("high")

# Load processor + model
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTextToWaveform.from_pretrained(model_id, dtype=torch.bfloat16, device_map="auto").eval()

# Prepare inputs
conversation = [
    [
        {
            "role": "0",
            "content": [
                {"type": "text", "text": "VibeVoice is a novel framework for generating expressive audio."},
                {
                    "type": "audio", "url": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
                },
            ],
        }
    ],
] * 4  # batch size 4
inputs = processor.apply_chat_template(
    conversation, tokenize=True, return_dict=True, add_generation_prompt=True,
).to(model.device, model.dtype)

compile_config = CompileConfig(mode="default", dynamic=False)

generate_kwargs = dict(
    **inputs,
    max_new_tokens=max_new_tokens,
    cache_implementation="static",
    compile_config=compile_config,
)

# Warmup
print("Warming up...")
warmup_start = time.time()
with torch.inference_mode():
    for _ in range(num_warmup):
        torch.compiler.cudagraph_mark_step_begin()
        _ = model.generate(**generate_kwargs)
torch.cuda.synchronize()
print(f"Warmup complete in {time.time() - warmup_start:.2f}s. Ready!")

# Apply model
with torch.inference_mode():
    torch.compiler.cudagraph_mark_step_begin()
    audio = model.generate(**generate_kwargs)
output_folder = f"{os.path.basename(model_id)}_compiled_output"
processor.save_audio(audio, output_folder)
print(f"Saved output to {output_folder}")

VibeVoiceConfig

class transformers.VibeVoiceConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneaudio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonesemantic_model_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonediffusion_head_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepad_token_id: int = 151643eos_token_id: int = 151643audio_bos_token_id: int = 151652audio_eos_token_id: int = 151653audio_token_id: int = 151654diffusion_loss_weight: float = 0.5 )

参数

  • audio_config (Union[dict, ~configuration_utils.PreTrainedConfig], 可选) — 音频骨干网络的配置对象或字典。
  • semantic_model_config (Union[AutoConfig, dict],可选) — 语义分词器编码器的配置对象或字典。该分词器用于从音频中提取语义特征。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • diffusion_head_config (Union[VibeVoiceDiffusionHeadConfig, dict], 可选) — 用于合成声学潜变量的扩散头配置对象或字典。
  • pad_token_id (int,可选,默认为 151643) — 词表中用于填充的 token id。
  • eos_token_id (int,可选,默认为 151643) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • audio_bos_token_id (int,可选,默认为 151652) — 表示音频 token 起始位置的 token ID。
  • audio_eos_token_id (int,可选,默认为 151653) — 表示音频 token 结束位置的 token ID。
  • audio_token_id (int,可选,默认为 151654) — 用作输入音频占位符的音频 token 索引。
  • diffusion_loss_weight (float,可选,默认为 0.5) — 扩散损失在整体损失计算中的权重。语言建模头的交叉熵损失权重为 (1 - diffusion_loss_weight)。

这是用于存储 VibeVoiceForConditionalGeneration 配置的类。它根据指定的参数实例化 Vibevoice 模型,并定义模型架构。使用默认值实例化配置,将得到与 vibevoice/VibeVoice-1.5B-hf 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

>>> from transformers import VibeVoiceForConditionalGeneration, VibeVoiceConfig

>>> # Initializing a VibeVoice configuration
>>> configuration = VibeVoiceConfig()

>>> # Initializing a 1.5B model with random weights
>>> model = VibeVoiceForConditionalGeneration(configuration)

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

VibeVoiceDiffusionHeadConfig

class transformers.VibeVoiceDiffusionHeadConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1536latent_size: int = 64num_hidden_layers: int = 4intermediate_size: int = 4608rms_norm_eps: float = 1e-05hidden_act: str = 'silu'frequency_embedding_size: int = 256diffusion_max_period: int = 10000mlp_bias: bool = False )

参数

  • hidden_size (int,可选,默认为 1536) — 隐藏表示的维度。
  • latent_size (int,可选,默认为 64) — 头部进行去噪的声学潜变量的维度。
  • num_hidden_layers (int, 可选,默认为 4) — Transformer 解码器中的隐藏层数量。
  • intermediate_size (int,可选,默认为 4608) — MLP 表示的维度。
  • rms_norm_eps (float,可选,默认为 1e-05) — RMS 归一化层使用的 epsilon 值。
  • hidden_act (str,可选,默认为 silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • frequency_embedding_size (int, 可选,默认为 256) — 扩散头中用于时间步编码的正弦频率嵌入的维度大小。
  • diffusion_max_period (int,可选,默认值为 10000) — 扩散头中正弦频率嵌入的最大周期。
  • mlp_bias (bool,可选,默认为 False) — 是否在 MLP 层的 up_proj、down_proj 和 gate_proj 层中使用偏置。

这是用于存储 VibeVoiceForConditionalGeneration 配置的类。它根据指定的参数实例化 Vibevoice 模型,并定义模型架构。使用默认值实例化配置,将得到与 vibevoice/VibeVoice-1.5B-hf 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

VibeVoiceProcessor

class transformers.VibeVoiceProcessor

< >

( feature_extractortokenizerchat_template = Noneaudio_bos_token = '<|vision_start|>'audio_eos_token = '<|vision_end|>'audio_token = '<|vision_pad|>' )

参数

  • feature_extractor(VibeVoiceAcousticTokenizerFeatureExtractor)—— 特征提取器是必需的输入。
  • tokenizer (Qwen2TokenizerFast) — tokenizer 是必需的输入。
  • chat_template (str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
  • audio_bos_token (str,可选,默认为 "<|vision_start|>") — 用于指示音频生成开始的标记。
  • audio_eos_token (str,可选,默认为 "<|vision_end|>") — 用于指示音频生成结束标记的 token。
  • audio_token (str,可选,默认为 "<|vision_pad|>") — 用于指示继续生成音频的 token。

构建一个 VibeVoiceProcessor,它将特征提取器和分词器封装为单个处理器。

VibeVoiceProcessor 提供了 VibeVoiceAcousticTokenizerFeatureExtractor 和 Qwen2TokenizerFast 的全部功能。有关更多信息,请参阅 ~VibeVoiceAcousticTokenizerFeatureExtractor 和 ~Qwen2TokenizerFast。

__call__

< >

( text: str | list[str] | list[list[str]]audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = Noneoutput_labels: bool | None = False**kwargs: *<class 'transformers.models.vibevoice.processing_vibevoice.VibeVoiceProcessorKwargs'> ) → BatchFeature

参数

  • text (str, List[str]) — 要处理的输入文本,通常由 apply_chat_template 准备,并包含音频 token 占位符。
  • audio (List[Union[str, np.ndarray]], 可选) — 用于说话人声音克隆的音频样本。其数量应与文本中的音频 token 占位符数量一致。
  • output_labels (bool,可选,默认值=False) — 是否返回用于训练的标签。
  • **kwargs — 传递给分词器和特征提取器的额外关键字参数。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

返回值

BatchFeature

一个包含以下字段的 BatchFeature:

  • input_ids — 输入模型的 token id 列表。
  • attention_mask — 索引列表,指定模型应关注哪些 token(当 return_attention_mask=True 时)。
  • input_values — 要输入模型的音频值列表。当 audio 不为 None 时返回。
  • padding_mask — 索引列表,指定模型应关注哪些音频帧。 当 audio 不为 None 时返回。
  • labels — 用于语言模型训练的标签。填充和音频扩散 token 会被 -100 屏蔽(因为音频扩散 token 的嵌入会被音频特征替换,所以它们的 token 身份不是有意义的目标)。音频 bos/eos 和文本 eos token 会保留为目标,以便语言模型学习何时开始和停止生成音频。当 output_labels=True 时返回。
  • acoustic_loss_mask — 用于指示在哪些位置计算扩散损失的布尔掩码。在音频扩散 token 位置处为 True。当 output_labels=True 时返回。

VibeVoiceForConditionalGeneration

class transformers.VibeVoiceForConditionalGeneration

< >

( config: VibeVoiceConfig )

参数

  • config (VibeVoiceConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

VibeVoice 模型由语言模型、音频分词器、连接器和扩散头组成。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: LongTensor = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Nonelogits_to_keep: int | slice = 0input_values: typing.Optional[torch.Tensor] = Nonepadding_mask: typing.Optional[torch.BoolTensor] = Noneacoustic_loss_mask: typing.Optional[torch.BoolTensor] = Nonenoise_scheduler: object | None = Noneddpm_batch_multiplier: int = 4num_diffusion_steps: int = 10sample: bool = True**kwargs ) → VibeVoiceCausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • logits_to_keep (Union[int, slice], 可选,默认为 0) — 如果为 int,则仅计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当可观。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。
  • input_values (torch.Tensor, 可选) — 用于声音克隆的预处理音频波形。
  • padding_mask (torch.BoolTensor, 可选) — 指示有效输入帧的掩码。
  • acoustic_loss_mask (torch.BoolTensor, 可选) — 用于仅在特定的声学 token 上计算扩散损失的掩码。
  • noise_scheduler (object,可选) — 训练时需要用于计算扩散损失的噪声目标。默认情况下,使用模型 generation_config 中指定的噪声调度器配置。
  • ddpm_batch_multiplier (int,可选,默认为 4) — 在训练过程中,用于计算扩散损失时,每个音频 token 生成的噪声样本数量,有助于稳定训练。
  • num_diffusion_steps (int, 可选,默认为 10) — 用于训练时,指定要使用的扩散步数。如果未提供,则默认为 10。
  • sample (bool,可选,默认为 True) — 是否向声学潜变量添加高斯噪声,与原始模型一致(σ-VAE:噪声尺度按批次中的每个样本从 N(0, vae_std) 中采样)。如果为 False,则直接使用编码器输出,因此输出是确定性的。

返回值

VibeVoiceCausalLMOutputWithPast 或 tuple(torch.Tensor)

VibeVoiceCausalLMOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(VibeVoiceConfig)和输入。

VibeVoiceForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • audio_features(形状为 (batch_size, sequence_length, feature_size) 的 torch.Tensor,可选)— 提取的音频特征,可用于对语言模型进行条件化。

示例:

>>> from transformers import AutoProcessor, VibeVoiceForConditionalGeneration

>>> model = VibeVoiceForConditionalGeneration.from_pretrained("vibevoice/VibeVoice-1.5B-hf")

>>> processor = AutoProcessor.from_pretrained("vibevoice/VibeVoice-1.5B-hf")
>>> inputs = processor(text="Hello, my dog is cute", return_tensors="pt")

>>> # generate speech
>>> speech = model(inputs["input_ids"])

generate

< >

( inputs: typing.Optional[torch.Tensor] = Nonegeneration_config: transformers.generation.configuration_utils.GenerationConfig | None = Nonelogits_processor: transformers.generation.logits_process.LogitsProcessorList | None = Nonestopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = Noneprefix_allowed_tokens_fn: collections.abc.Callable[[int, torch.Tensor], list[int]] | None = Nonesynced_gpus: bool | None = Noneassistant_model: typing.Optional[ForwardRef('PreTrainedModel')] = Nonestreamer: typing.Optional[ForwardRef('BaseStreamer')] = Nonenegative_prompt_ids: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonecustom_generate: str | collections.abc.Callable | None = None**kwargs ) → ModelOutput or torch.LongTensor

参数

  • inputs(形状因模态而异的 torch.Tensor,可选)— 用作生成提示的序列,或作为编码器的模型输入。如果为 None,该方法将使用 bos_token_id 和批大小 1 对其进行初始化。对于仅解码器模型,inputs 应采用 input_ids 的格式。对于编码器-解码器模型,inputs 可以是 input_ids、input_values、input_features 或 pixel_values 中的任意一种。
  • generation_config (GenerationConfig, 可选) — 用作生成调用基础参数化的生成配置。传递给 generate 且与 generation_config 属性匹配的 **kwargs 将覆盖这些属性。如果未提供 generation_config,则使用默认值,其加载优先级如下:1) 如果存在 generation_config.json 模型文件,则从中加载;2) 从模型配置中加载。请注意,未指定的参数将继承 GenerationConfig 的默认值,应查阅其文档以参数化生成。
  • logits_processor (LogitsProcessorList, 可选) — 自定义的 logits 处理器,用于补充由参数和生成配置构建的默认 logits 处理器。如果传入的 logit 处理器已经由参数或生成配置创建,则会抛出错误。此功能面向高级用户。
  • stopping_criteria (StoppingCriteriaList,可选) — 自定义停止条件,用于补充由参数和生成配置构建的默认停止条件。如果传入的停止条件已经由参数或生成配置创建,则会抛出错误。如果你的停止条件依赖于 scores 输入,请确保向 generate 传入 return_dict_in_generate=True, output_scores=True。此功能面向高级用户。
  • prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], list[int]], 可选) — 如果提供,此函数会在每一步将束搜索限制为仅使用允许的 token。如果未提供,则不施加任何约束。此函数接受 2 个参数:批次 ID batch_id 和 input_ids。它必须返回一个列表,其中包含根据批次 ID batch_id 和之前生成的 token inputs_ids 条件化后,用于下一步生成的允许 token。此参数对于基于前缀的约束生成非常有用,如 Autoregressive Entity Retrieval 中所述。
  • synced_gpus (bool, 可选) — 是否继续执行 while 循环直到达到 max_length。除非被覆盖,否则在使用 FullyShardedDataParallel 或 DeepSpeed ZeRO Stage 3 且涉及多 GPU 时,此标志将设置为 True,以避免某个 GPU 在其他 GPU 之前完成生成时发生死锁。否则,默认为 False。
  • assistant_model (PreTrainedModel, 可选) — 可用于加速生成的辅助模型。辅助模型必须使用完全相同的 tokenizer。当使用辅助模型预测候选 token 的速度远快于从你调用 generate 的模型运行生成时,即可实现加速。因此,辅助模型应小得多。
  • streamer (BaseStreamer,可选) — 用于流式传输生成序列的 Streamer 对象。生成的 token 会通过 streamer.put(token_ids) 传入,由 streamer 负责后续处理。
  • negative_prompt_ids(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选) — 某些处理器(例如 CFG)所需的负面提示。批处理大小必须与输入批处理大小相匹配。这是一个实验性功能,未来版本中可能会发生破坏性的 API 变更。
  • negative_prompt_attention_mask(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选)— negative_prompt_ids 的 attention_mask。
  • custom_generate (str 或 Callable, 可选) — 以下之一:
    • str(Hugging Face Hub 仓库名称):运行该仓库中 custom_generate/generate.py 定义的自定义 generate 函数,而不是标准的 generate 方法。该仓库会完全替换生成逻辑,且返回类型可能有所不同。
    • str(本地仓库路径):与上述相同,但来自本地路径。本地目录也需要 trust_remote_code=True,因为会执行本地的 custom_generate/generate.py。
    • Callable:generate 将执行常规的输入准备步骤,然后调用提供的可调用对象来运行解码循环。 有关更多信息,请参阅 文档。
  • kwargs (dict[str, Any], 可选) — generation_config 的临时参数设置,和/或将被转发给模型 forward 函数的额外模型特定 kwargs。如果模型是编码器-解码器模型,编码器特定的 kwargs 不应添加前缀,而解码器特定的 kwargs 应以 decoder_ 作为前缀。

返回值

ModelOutput 或 torch.LongTensor

ModelOutput(当 return_dict_in_generate=True 或 config.return_dict_in_generate=True 时)或 torch.LongTensor。

如果模型不是编码器-解码器模型(model.config.is_encoder_decoder=False),可能的 ModelOutput 类型为:

如果模型是编码器-解码器模型(model.config.is_encoder_decoder=True),则可能的 ModelOutput 类型为:

为具有语言建模头的模型生成 token id 序列。

大多数生成控制参数都在 generation_config 中设置,如果未传入该参数,则会使用模型的默认生成配置。你可以通过向 generate() 传入相应参数来覆盖 generation_config 中的任意设置,例如 .generate(inputs, num_beams=4, do_sample=True)。

有关生成策略和代码示例的概述,请参阅以下指南。

VibeVoiceModel

class transformers.VibeVoiceModel

< >

( config: VibeVoiceConfig )

参数

  • config (VibeVoiceConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

VibeVoice 模型由音频分词器和 LLM 骨干网络组成,不包含语言建模头。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: LongTensor = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneinput_values: typing.Optional[torch.Tensor] = Nonepadding_mask: typing.Optional[torch.BoolTensor] = Nonesample: bool = True**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • input_values (torch.Tensor,形状为 (batch_size, sequence_length),可选) — 输入原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取这些值,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组准备为 input_values,应使用 AutoProcessor 进行填充并转换为 torch.Tensor 类型的张量。详情请参见 VibeVoiceProcessor.call()。
  • padding_mask (torch.Tensor,形状为 (batch_size, padded_audio_length)) — 用于移除音频中填充部分的掩码。
  • sample (bool,可选,默认为 True) — 是否向声学潜变量添加高斯噪声,与原始模型一致(σ-VAE:噪声尺度按批次中的每个样本从 N(0, vae_std) 中采样)。如果为 False,则直接使用编码器输出,因此输出是确定性的。

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(VibeVoiceConfig)和输入。

VibeVoiceModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

get_audio_features

< >

( input_values: Tensorpadding_mask: Tensorsample: bool = True**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • input_values (torch.Tensor) — (归一化)音频波形的浮点值。
  • padding_mask (torch.Tensor,形状为 (batch_size, padded_audio_length)) — 用于移除音频中填充部分的掩码。
  • sample (bool,可选,默认为 True) — 是否向声学潜变量添加高斯噪声,与原始模型一致(σ-VAE:噪声尺度按批次中的每个样本从 N(0, vae_std) 中采样)。如果为 False,则直接使用编码器输出,因此输出是确定性的。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(VibeVoiceConfig)和输入。

此方法用于从输入音频波形中获取音频嵌入(用于替换输入序列中的占位符音频标记)和声学特征(用作扩散目标)。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

get_placeholder_mask

< >

( input_ids: LongTensorinputs_embeds: Tensoraudio_features: Tensor )

从 input_ids 或 inputs_embeds 中获取多模态占位符掩码,并检查占位符 token 的数量是否等于多模态特征的长度。如果长度不一致,则会引发错误。

Update on GitHub