Transformers documentation
Higgs Audio V2
该模型于 2026-02-19 贡献至 Hugging Face Transformers。
Higgs Audio V2
概述
Higgs Audio V2 是由 Boson AI 开发的一款强大的音频基础模型。 该模型在超过 1000 万小时的音频数据以及多样化的文本数据上进行了预训练。 尽管没有经过后训练或微调,Higgs Audio v2 凭借其深入的语言和声学理解能力,在富有表现力的音频生成方面表现出色。
模型架构:

- 我们开发了一条自动化标注流水线,该流水线利用了多个 ASR 模型、声音事件分类模型以及我们自研的音频理解模型。借助这条流水线,我们对 1000 万小时的音频数据进行了清洗和标注,并将其命名为 AudioVerse。该自研理解模型是在 Higgs Audio v1 Understanding 的基础上进行微调的,它采用了架构图中所示的“理解变体”。
- 从头训练了一个统一的音频分词器,能够同时捕捉语义特征和声学特征。
- 所提出的 DualFFN 架构,能够在极低的计算开销下增强 LLM 对声学 token 的建模能力。
用法
以下所有代码片段均与 test_higgs_audio.py 中的集成测试保持一致,确保文档与官方支持的工作流程同步。
单说话人智能语音
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
conversation = [
{
"role": "system",
"content": [
{
"type": "text",
"text": "Generate audio following instruction."
}
],
},
{
"role": "scene",
"content": [
{
"type": "text",
"text": "Audio is recorded from a quiet room."
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
}
]
}
]
inputs = processor.apply_chat_template(
conversation,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
sampling_rate=24000,
return_tensors="pt"
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=1000, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, "output_single_speaker_smart_voice.wav")多说话人智能语音
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
system_message = """You are an AI assistant designed to convert text into speech.
If the user's message includes a [SPEAKER*] tag, do not read out the tag and generate speech for the following text, using the specified voice.
If no speaker tag is present, select a suitable voice on your own."""
user_message = """[SPEAKER0] I can't believe you did that without even asking me first!
[SPEAKER1] Oh, come on! It wasn't a big deal, and I knew you would overreact like this.
[SPEAKER0] Overreact? You made a decision that affects both of us without even considering my opinion!
[SPEAKER1] Because I didn't have time to sit around waiting for you to make up your mind! Someone had to act."""
conversation = [
{
"role": "system",
"content": [
{
"type": "text",
"text": system_message
}
]
},
{
"role": "scene",
"content": [
{
"type": "text",
"text": "Audio is recorded from a quiet room."
},
{
"type": "text",
"text": "SPEAKER0: feminine"
},
{
"type": "text",
"text": "SPEAKER1: masculine"
},
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": user_message
}
]
}
]
inputs = processor.apply_chat_template(
conversation,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
sampling_rate=24000,
return_tensors="pt"
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=50, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, "output_multi_speaker_smart_voice.wav")零样本语音克隆
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
conversation = [
{
"role": "system",
"content": [
{
"type": "text",
"text": "Generate audio following instruction."
}
]
},
{
"role": "scene",
"content": [
{
"type": "text",
"text": "Audio is recorded from a quiet room."
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
}
]
},
{
"role": "assistant",
"content": [
{
"type": "audio",
"url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
}
]
}
]
inputs = processor.apply_chat_template(
conversation,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
sampling_rate=24000,
return_tensors="pt"
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=1000, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, "output_zero_shot_voice_cloning.wav")多说话人语音克隆
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
user_message = """[SPEAKER0] I can't believe you did that without even asking me first!
[SPEAKER1] Oh, come on! It wasn't a big deal, and I knew you would overreact like this.
[SPEAKER0] Overreact? You made a decision that affects both of us without even considering my opinion!
[SPEAKER1] Because I didn't have time to sit around waiting for you to make up your mind! Someone had to act."""
conversation = [
{
"role": "system",
"content": [
{
"type": "text",
"text": "Generate audio following instruction."
}
]
},
{
"role": "scene",
"content": [
{
"type": "text",
"text": "Audio is recorded from a quiet room."
},
{
"type": "text",
"text": "SPEAKER0:"
},
{
"type": "audio",
"url": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/audio/voice_sample.wav"
},
{
"type": "text",
"text": "SPEAKER1:"
},
{
"type": "audio",
"url": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/audio/mr_quiller.flac"
},
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": user_message
}
]
},
]
inputs = processor.apply_chat_template(
conversation,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
sampling_rate=24000,
return_tensors="pt"
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=1000, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, "output_multi_speaker_voice_cloning.wav")批量推理
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
conversation1 = [
{
"role": "system",
"content": [
{
"type": "text",
"text": "Generate audio following instruction."
}
]
},
{
"role": "scene",
"content": [
{
"type": "text",
"text": "Audio is recorded from a quiet room."
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
}
]
},
{
"role": "assistant",
"content": [
{
"type": "audio",
"url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
}
]
}
]
conversation2 = [
{
"role": "system",
"content": [
{
"type": "text",
"text": "Generate audio following instruction."
}
]
},
{
"role": "scene",
"content": [
{
"type": "text",
"text": "Audio is recorded from a quiet room."
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": " It's super important to assess fairly the fact that our former model is over. And this is not a question of adjustment. This is not the same world, 2024, 2025. And on top of that, we are making the same mistakes, on top of the key elements I mentioned. We are over-regulating and under-investing. So just if, in the two to three years to come, if we follow our classical agenda, we will be out of the market. I have no doubts."
}
]
},
{
"role": "assistant",
"content": [
{
"type": "audio",
"url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/macron.wav"
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Hey, here is a clone from the given voice."
}
]
}
]
inputs = processor.apply_chat_template(
[conversation1, conversation2],
add_generation_prompt=True,
tokenize=True,
return_dict=True,
sampling_rate=24000,
return_tensors="pt"
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=1000, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, ["output_batched_1.wav", "output_batched_2.wav"])训练
默认情况下,模型不会加载文本语言建模头以节省内存(约减少 1.5GiB),因为生成过程并不需要它。 但在训练模型时,你需要文本头来计算文本 token 的损失。要启用它,请在实例化模型时设置
use_text_head=True(参见下方示例)。
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto", use_text_head=True)
conversation1 = [
{
"role": "system",
"content": [
{
"type": "text",
"text": "Generate audio following instruction."
}
]
},
{
"role": "scene",
"content": [
{
"type": "text",
"text": "Audio is recorded from a quiet room."
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
}
]
},
{
"role": "assistant",
"content": [
{
"type": "audio",
"url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
}
]
}
]
conversation2 = [
{
"role": "system",
"content": [
{
"type": "text",
"text": "Generate audio following instruction."
}
]
},
{
"role": "scene",
"content": [
{
"type": "text",
"text": "Audio is recorded from a quiet room."
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": " I would imagine so. A wand with a dragon heartstring core is capable of dazzling magic, and the bond between you and your wand should only grow stronger. Do not be surprised at your new wand's ability to perceive your intentions, particularly in a moment of need"
}
]
},
{
"role": "assistant",
"content": [
{
"type": "audio",
"url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/broom_salesman.wav"
}
]
}
]
inputs = processor.apply_chat_template(
[conversation1, conversation2],
tokenize=True,
return_dict=True,
sampling_rate=24000,
return_tensors="pt",
output_labels=True,
).to(model.device)
outputs = model(**inputs)
outputs.loss.backward()该模型由 Shuai Zheng 和 Eustache Le Bihan 贡献。原始代码可在此处找到。
HiggsAudioV2Config
class transformers.HiggsAudioV2Config
< source >( 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 = Nonevocab_size: int = 128256hidden_size: int = 3072intermediate_size: int = 8192num_hidden_layers: int = 28num_attention_heads: int = 24num_key_value_heads: int = 8hidden_act: str = 'silu'max_position_embeddings: int = 2048initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Truepad_token_id: int | None = 128001bos_token_id: int | None = 1eos_token_id: int | list[int] | None = 128009pretraining_tp: int | None = 1tie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falseattention_dropout: int | float | None = 0.0mlp_bias: bool = Falsehead_dim: int | None = 128num_codebooks: int = 8codebook_size: int = 1024audio_token_id: int = 128016audio_bos_token_id: int = 128013audio_delay_token_id: int = 128014audio_stream_bos_id: int = 1024audio_stream_eos_id: int = 1025 )
参数
- vocab_size (
int,可选,默认为128256) — 模型的词汇表大小。定义了input_ids可以表示的不同 token 数量。 - hidden_size (
int,可选,默认为3072) — 隐藏表示的维度。 - intermediate_size (
int,可选,默认为8192) — MLP 表示的维度。 - num_hidden_layers (
int,可选,默认为28) — Transformer 解码器中的隐藏层数量。 - num_attention_heads(
int,可选,默认值为24)— Transformer 解码器中每个注意力层的注意力头数量。 - num_key_value_heads (
int, 可选,默认为8) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为num_attention_heads。 - hidden_act (
str,可选,默认为silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - max_position_embeddings (
int,可选,默认为2048) — 该模型可能使用的最大序列长度。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - rms_norm_eps (
float,可选,默认为1e-05) — RMS 归一化层使用的 epsilon 值。 - use_cache (
bool,可选,默认为True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当config.is_decoder=True或模型为仅解码器生成式模型时相关。 - pad_token_id (
int,可选,默认为128001) — 词表中用于填充的 token id。 - bos_token_id (
int,可选,默认为1) — 词汇表中用于表示流起始的 token id。 - eos_token_id (
Union[int, list[int]],可选,默认为128009) — 词汇表中用于表示流结束(end-of-stream)的 token id。 - pretraining_tp (
int,可选,默认为1) — 实验性功能。预训练期间使用的张量并行 rank。请参阅此文档以了解更多相关信息。此值对于确保预训练结果的精确可复现性是必需的。请参阅此 issue。 - tie_word_embeddings (
bool,可选,默认为False) — 是否根据模型的tied_weights_keys映射来绑定权重嵌入。 - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,并且如果希望使用 RoPE 处理更长的max_position_embeddings,则可选地包含用于缩放的参数。 - attention_bias (
bool,可选,默认为False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。 - attention_dropout (
Union[int, float],可选,默认为0.0) — 注意力概率的 dropout 比率。 - mlp_bias (
bool,可选,默认为False) — 是否在 MLP 层的 up_proj、down_proj 和 gate_proj 层中使用偏置。 - head_dim (
int,可选,默认为128) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads - num_codebooks (
int,可选,默认为8) — 模型使用的并行码本数量。 - codebook_size (
int,可选,默认为1024) — 模型使用的并行码本数量。 - audio_token_id (
int,可选,默认为128016) — 用作输入音频占位符的音频 token 索引。 - audio_bos_token_id (
int,可选,默认为 128013) — 音频输出的序列起始 token 的 ID。 - audio_delay_token_id (
int,可选,默认为 128014) — 在多码本生成中用于音频延迟模式的 token ID。 - audio_stream_bos_id (
int,可选,默认为 1024) — 音频序列中流开始(beginning-of-stream)令牌的 ID。 - audio_stream_eos_id (
int,可选,默认为 1025) — 音频序列中流结束令牌的 ID。
这是用于存储 HiggsAudioV2ForConditionalGeneration 配置的类。它根据指定的参数实例化 Higgs Audio V2 模型,并定义模型架构。使用默认值实例化配置将得到与 bosonai/higgs-audio-v2-generation-3B-base 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import HiggsAudioV2Model, HiggsAudioV2Config
>>> # Initializing a HiggsAudioV2 style configuration
>>> configuration = HiggsAudioV2Config()
>>> # Initializing a model from the configuration
>>> model = HiggsAudioV2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configHiggsAudioV2Processor
class transformers.HiggsAudioV2Processor
< source >( feature_extractortokenizeraudio_tokenizerchat_template = Noneaudio_token = '<|AUDIO_OUT|>'audio_bos_token = '<|audio_out_bos|>'audio_eos_token = '<|audio_eos|>'audio_delay_token = '<|reserved_special_token_6|>'audio_stream_bos_id = 1024audio_stream_eos_id = 1025 )
参数
- feature_extractor (
DacFeatureExtractor) — DacFeatureExtractor 的实例。特征提取器是必需的输入。 - tokenizer(
AutoTokenizer)—— AutoTokenizer 的实例。分词器是必需的输入。 - audio_tokenizer (
HiggsAudioV2TokenizerModel) — HiggsAudioV2TokenizerModel 的实例。音频分词器是必需的输入。 - chat_template (
str, 可选) — 用于组合文本和音频交互时的聊天格式化模板字符串。 - audio_token (
str, 可选,默认为"<|AUDIO_OUT|>") — 用于在文本序列中表示音频输出的标记。 - audio_bos_token (
str,可选,默认为"<|audio_out_bos|>") — 音频输出的序列起始标记。 - audio_eos_token (
str,可选,默认为"<|audio_eos|>") — 音频输出的序列结束标记。 - audio_delay_token (
str,可选,默认为"<|reserved_special_token_6|>") — 在多码本生成中用于音频延迟模式的标记。 - audio_stream_bos_id (
int,可选,默认为 1024) — 音频序列中流开始(beginning-of-stream)令牌的 ID。 - audio_stream_eos_id (
int,可选,默认为 1025) — 音频序列中流结束令牌的 ID。
构建一个 Higgs Audio 处理器,它将 DacFeatureExtractor、AutoTokenizer 和 HiggsAudioV2TokenizerModel 封装为单一处理器。它继承了音频特征提取、分词器以及音频编码/解码功能。 有关更多信息,请参阅 call() 和 decode()。
__call__
< source >( text: str | list[str] | list[list[str]] | None = Noneaudio: 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.higgs_audio_v2.processing_higgs_audio_v2.HiggsAudioV2ProcessorKwargs'> )
HiggsAudioV2Model
class transformers.HiggsAudioV2Model
< source >( config: HiggsAudioV2Config )
参数
- config (HiggsAudioV2Config) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Higgs Audio V2 模型,输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneaudio_input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Noneaudio_input_ids_mask: typing.Optional[torch.BoolTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ~models.modeling_outputs.BaseModelOutputWithPast
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- audio_input_ids (
torch.LongTensor形状为(batch_size, num_audio_frames, num_codebooks), 可选) — 音频码本令牌的索引。可以使用 HiggsAudioV2TokenizerModel.encode() 获取索引。
- attention_mask (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充(padding)标记索引执行注意力机制的掩码。掩码值取自 [0, 1]:1 表示未屏蔽的标记,0 表示被屏蔽的标记。什么是注意力掩码?[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- audio_input_ids_mask(形状为
(batch_size, num_audio_frames)的torch.BoolTensor,可选) — 指示audio_input_ids中哪些音频帧是有效的。 - position_ids (
torch.LongTensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由past_key_values在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
past_key_values,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用了
past_key_values,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的全部input_ids。 - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - use_cache (
bool,可选) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。
返回值
~models.modeling_outputs.BaseModelOutputWithPast
通常的解码器输出,其中占位符位置已被其对应的音频嵌入替换。
HiggsAudioV2Model 的 forward 方法会重写 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
示例:
>>> from transformers import AutoProcessor, HiggsAudioV2Model
>>> import torch
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> processor = AutoProcessor.from_pretrained("eustlb/higgs-audio-v2-generation-3B-base", device_map=device)
>>> model = HiggsAudioV2Model.from_pretrained("eustlb/higgs-audio-v2-generation-3B-base", device_map=device)
>>> conversation = [
... {
... "role": "system",
... "content": [
... {
... "type": "text",
... "text": "Generate audio following instruction."
... }
... ]
... },
... {
... "role": "scene",
... "content": [
... {
... "type": "text",
... "text": "Audio is recorded from a quiet room."
... }
... ]
... },
... {
... "role": "user",
... "content": [
... {
... "type": "text",
... "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
... }
... ]
... },
... {
... "role": "assistant",
... "content": [
... {
... "type": "audio",
... "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
... }
... ]
... },
... {
... "role": "user",
... "content": [
... {
... "type": "text",
... "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
... }
... ]
... }
... ]
>>> inputs = processor.apply_chat_template(conversation, return_dict=True, tokenize=True, sampling_rate=24000, return_tensors="pt")
>>> inputs = inputs.to(model.device)
>>> outputs = model(**inputs)HiggsAudioV2ForConditionalGeneration
class transformers.HiggsAudioV2ForConditionalGeneration
< source >( config: HiggsAudioV2Configuse_text_head: bool = False )
参数
- config (HiggsAudioV2Config) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
- use_text_head (
bool,可选,默认为 False) — 是否使用文本语言模型头。生成过程不需要该头,但在训练时可用于计算文本损失。
Higgs Audio 模型,一种具有双 FFN 的类 Llama 自回归 Transformer 模型。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.BoolTensor] = Noneaudio_input_ids: typing.Optional[torch.LongTensor] = Noneaudio_input_ids_mask: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneaudio_labels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ~models.modeling_outputs.CausalLMOutputWithPast
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.BoolTensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- audio_input_ids (
torch.LongTensor形状为(batch_size, num_audio_frames, num_codebooks), 可选) — 音频码本令牌的索引。可以使用 HiggsAudioV2TokenizerModel.encode() 获取索引。
- audio_input_ids_mask(形状为
(batch_size, num_audio_frames)的torch.BoolTensor,可选) — 指示audio_input_ids中哪些音频帧是有效的。 - position_ids (
torch.LongTensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由past_key_values在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
past_key_values,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用了
past_key_values,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的全部input_ids。 - 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 进行计算。 - audio_labels (
torch.LongTensorof shape(batch_size, num_audio_frames, num_codebooks), optional) — 用于计算掩码语言建模损失的音频码本 token 标签。索引应在[0, ..., config.codebook_size]. Token with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, …, config.codebook_size]. Can be obtained usingoutput_labels=True` when calling HiggsAudioV2Processor. - use_cache (
bool,可选) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。 - logits_to_keep (
Union[int, torch.Tensor], 可选,默认为0) — 如果为int,则计算最后logits_to_keep个 token 的 logits。如果为0,则计算所有input_ids的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。
返回值
~models.modeling_outputs.CausalLMOutputWithPast
一个 ~models.modeling_outputs.CausalLMOutputWithPast,包含 logits、loss(如果提供了 labels)以及模型的其他输出。
HiggsAudioV2ForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
示例:
>>> from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
>>> model_id = "eustlb/higgs-audio-v2-generation-3B-base"
>>> processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
>>> model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
>>> conversation = [
... {
... "role": "system",
... "content": [
... {
... "type": "text",
... "text": "Generate audio following instruction."
... }
... ]
... },
... {
... "role": "scene",
... "content": [
... {
... "type": "text",
... "text": "Audio is recorded from a quiet room."
... }
... ]
... },
... {
... "role": "user",
... "content": [
... {
... "type": "text",
... "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
... }
... ]
... },
... {
... "role": "assistant",
... "content": [
... {
... "type": "audio",
... "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
... }
... ]
... },
... {
... "role": "user",
... "content": [
... {
... "type": "text",
... "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
... }
... ]
... }
... ]
>>> inputs = processor.apply_chat_template(conversation, return_dict=True, tokenize=True, sampling_rate=24000, return_tensors="pt")
>>> inputs = inputs.to(model.device)
>>> outputs = model(**inputs)generate
< source >( 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 个参数:批次 IDbatch_id和input_ids。它必须返回一个列表,其中包含根据批次 IDbatch_id和之前生成的 tokeninputs_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)。有关生成策略和代码示例的概述,请参阅以下指南。