Transformers documentation
Higgs Audio V2
Mô hình này đã được đóng góp cho Hugging Face Transformers vào ngày 2026-02-19.
Higgs Audio V2
Tổng quan
Higgs Audio V2 là một mô hình nền tảng âm thanh mạnh mẽ do Boson AI phát triển. Mô hình này được tiền huấn luyện trên hơn 10 triệu giờ dữ liệu âm thanh và một tập dữ liệu văn bản đa dạng. Mặc dù không có huấn luyện hậu kỳ hay tinh chỉnh, Higgs Audio v2 vẫn vượt trội trong việc tạo ra âm thanh biểu cảm, nhờ vào khả năng hiểu sâu về ngôn ngữ và âm học.
Kiến trúc mô hình:

- Chúng tôi đã phát triển một pipeline chú thích tự động, tận dụng nhiều mô hình ASR, các mô hình phân loại sự kiện âm thanh và mô hình hiểu âm thanh nội bộ của chúng tôi. Sử dụng pipeline này, chúng tôi đã làm sạch và chú thích 10 triệu giờ dữ liệu âm thanh, được gọi là AudioVerse. Mô hình hiểu nội bộ được finetune dựa trên Higgs Audio v1 Understanding, vốn áp dụng “biến thể understanding” được thể hiện trong hình kiến trúc.
- Đã huấn luyện một bộ mã hóa âm thanh thống nhất từ đầu, nắm bắt cả các đặc trưng ngữ nghĩa và âm học.
- Kiến trúc DualFFN được đề xuất, giúp tăng cường khả năng mô hình hóa các token âm thanh của LLM với chi phí tính toán tối thiểu.
Cách sử dụng
Tất cả các đoạn mã dưới đây phản ánh các bài kiểm thử tích hợp trong test_higgs_audio.py, đảm bảo tài liệu luôn đồng bộ với các quy trình được hỗ trợ chính thức.
Giọng nói thông minh một người nói
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")Giọng nói thông minh đa người nói
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")Nhân bản giọng nói không cần mẫu
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")Nhân bản giọng nói đa người
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")Suy luận theo lô
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"])Huấn luyện
Mặc định, mô hình không nạp đầu mô hình hóa ngôn ngữ văn bản để tiết kiệm bộ nhớ (giảm khoảng 1.5GiB), vì nó không cần thiết cho quá trình sinh. Tuy nhiên, khi huấn luyện mô hình, bạn cần đầu văn bản để tính loss trên các token văn bản. Để bật tính năng này, hãy đặt
use_text_head=Truekhi khởi tạo mô hình (xem ví dụ bên dưới).
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()Mô hình này được đóng góp bởi Shuai Zheng và Eustache Le Bihan. Mã gốc có thể được tìm thấy tại đây.
HiggsAudioV2Config
lớp 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 )
Tham số
- vocab_size (
int, tuỳ chọn, mặc định là128256) — Kích thước từ vựng của mô hình. Xác định số lượng token khác nhau có thể được biểu diễn bởiinput_ids. - hidden_size (
int, tùy chọn, mặc định là3072) — Kích thước của các biểu diễn ẩn. - intermediate_size (
int, tùy chọn, mặc định là8192) — Kích thước của các biểu diễn MLP. - num_hidden_layers (
int, tùy chọn, mặc định là28) — Số lượng lớp ẩn trong bộ giải mã Transformer. - num_attention_heads (
int, tùy chọn, mặc định là24) — Số lượng đầu attention cho mỗi lớp attention trong bộ giải mã Transformer. - num_key_value_heads (
int, tùy chọn, mặc định là8) — Đây là số lượng key_value heads cần được sử dụng để triển khai Grouped Query Attention. Nếunum_key_value_heads=num_attention_heads, mô hình sẽ sử dụng Multi Head Attention (MHA), nếunum_key_value_heads=1mô hình sẽ sử dụng Multi Query Attention (MQA), ngược lại sẽ sử dụng GQA. Khi chuyển đổi checkpoint multi-head sang checkpoint GQA, mỗi nhóm key và value head nên được xây dựng bằng cách meanpooling tất cả các head gốc trong nhóm đó. Để biết thêm chi tiết, hãy xem bài báo này. Nếu không được chỉ định, giá trị mặc định sẽ lànum_attention_heads. - hidden_act (
str, tùy chọn, mặc định làsilu) — Hàm kích hoạt phi tuyến (hàm hoặc chuỗi) trong bộ giải mã. Ví dụ,"gelu","relu","silu", v.v. - max_position_embeddings (
int, tùy chọn, mặc định là2048) — Chiều dài chuỗi tối đa mà mô hình này có thể được sử dụng. - initializer_range (
float, tùy chọn, mặc định là0.02) — Độ lệch chuẩn của truncated_normal_initializer để khởi tạo tất cả các ma trận trọng số. - rms_norm_eps (
float, tùy chọn, mặc định là1e-05) — Giá trị epsilon được sử dụng bởi các lớp chuẩn hóa rms. - use_cache (
bool, tùy chọn, mặc định làTrue) — Xác định xem mô hình có nên trả về các chú ý key/values cuối cùng hay không (không được sử dụng bởi tất cả các mô hình). Chỉ liên quan nếuconfig.is_decoder=Truehoặc khi mô hình là mô hình sinh chỉ có decoder. - pad_token_id (
int, tùy chọn, mặc định là128001) — Token id được sử dụng để đệm (padding) trong từ vựng. - bos_token_id (
int, tùy chọn, mặc định là1) — Token id được sử dụng cho beginning-of-stream trong bảng từ vựng. - eos_token_id (
Union[int, list[int]], tùy chọn, mặc định là128009) — Token id được sử dụng cho end-of-stream trong bảng từ vựng. - pretraining_tp (
int, tùy chọn, mặc định là1) — Tính năng thử nghiệm. Bậc song song tensor (tensor parallelism rank) được sử dụng trong quá trình tiền huấn luyện. Vui lòng tham khảo tài liệu này để hiểu thêm về nó. Giá trị này là cần thiết để đảm bảo khả năng tái lập chính xác các kết quả tiền huấn luyện. Vui lòng tham khảo vấn đề này. - tie_word_embeddings (
bool, tùy chọn, mặc định làFalse) — Có nên gắn kết các trọng số nhúng theo ánh xạtied_weights_keyscủa mô hình hay không. - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], tùy chọn) — Từ điển chứa các tham số cấu hình cho các embedding RoPE. Từ điển phải chứa một giá trị chorope_thetavà tùy chọn các tham số được sử dụng để mở rộng trong trường hợp bạn muốn sử dụng RoPE vớimax_position_embeddingsdài hơn. - attention_bias (
bool, tùy chọn, mặc định làFalse) — Có sử dụng bias trong các lớp chiếu query, key, value và output trong quá trình tự chú ý hay không. - attention_dropout (
Union[int, float], tùy chọn, mặc định là0.0) — Tỷ lệ dropout cho các xác suất chú ý. - mlp_bias (
bool, tùy chọn, mặc định làFalse) — Có sử dụng bias trong các lớp up_proj, down_proj và gate_proj của các lớp MLP hay không. - head_dim (
int, tùy chọn, mặc định là128) — Kích thước chiều của đầu chú ý. Nếu là None, giá trị mặc định sẽ là hidden_size // num_attention_heads - num_codebooks (
int, tùy chọn, mặc định là8) — Số lượng codebook song song được mô hình sử dụng. - codebook_size (
int, tùy chọn, mặc định là1024) — Số lượng codebook song song được mô hình sử dụng. - audio_token_id (
int, tùy chọn, mặc định là128016) — Chỉ số token âm thanh được dùng làm ký tự thay thế cho âm thanh đầu vào. - audio_bos_token_id (
int, tùy chọn, mặc định là 128013) — ID của token bắt đầu chuỗi cho đầu ra âm thanh. - audio_delay_token_id (
int, tùy chọn, mặc định là 128014) — ID của token được sử dụng cho mẫu độ trễ âm thanh trong quá trình tạo đa codebook. - audio_stream_bos_id (
int, tuỳ chọn, mặc định là 1024) — ID của token bắt đầu luồng trong các chuỗi âm thanh. - audio_stream_eos_id (
int, tuỳ chọn, mặc định là 1025) — ID của token kết thúc luồng trong các chuỗi âm thanh.
Đây là lớp cấu hình để lưu trữ cấu hình của một HiggsAudioV2ForConditionalGeneration. Nó được sử dụng để khởi tạo một mô hình Higgs Audio V2 theo các đối số được chỉ định, xác định kiến trúc mô hình. Khởi tạo một cấu hình với các giá trị mặc định sẽ tạo ra một cấu hình tương tự như của bosonai/higgs-audio-v2-generation-3B-base
Các đối tượng cấu hình kế thừa từ PreTrainedConfig và có thể được sử dụng để kiểm soát đầu ra của mô hình. Đọc tài liệu từ PreTrainedConfig để biết thêm thông tin.
Ví dụ:
>>> 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
lớp 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 )
Tham số
- feature_extractor (
DacFeatureExtractor) — Một instance của DacFeatureExtractor. Feature extractor là một đầu vào bắt buộc. - tokenizer (
AutoTokenizer) — Một instance của AutoTokenizer. Tokenizer là một đầu vào bắt buộc. - audio_tokenizer (
HiggsAudioV2TokenizerModel) — Một instance của HiggsAudioV2TokenizerModel. Audio tokenizer là một đầu vào bắt buộc. - chat_template (
str, tùy chọn) — Chuỗi mẫu để định dạng chat khi kết hợp tương tác văn bản và âm thanh. - audio_token (
str, tùy chọn, mặc định là"<|AUDIO_OUT|>") — Token được sử dụng để đại diện cho đầu ra âm thanh trong chuỗi văn bản. - audio_bos_token (
str, tùy chọn, mặc định là"<|audio_out_bos|>") — Token bắt đầu chuỗi cho đầu ra âm thanh. - audio_eos_token (
str, tùy chọn, mặc định là"<|audio_eos|>") — Token kết thúc chuỗi cho đầu ra âm thanh. - audio_delay_token (
str, tùy chọn, mặc định là"<|reserved_special_token_6|>") — Token được sử dụng cho mẫu độ trễ âm thanh trong quá trình tạo đa codebook. - audio_stream_bos_id (
int, tuỳ chọn, mặc định là 1024) — ID của token bắt đầu luồng trong các chuỗi âm thanh. - audio_stream_eos_id (
int, tuỳ chọn, mặc định là 1025) — ID của token kết thúc luồng trong các chuỗi âm thanh.
Tạo một bộ xử lý Higgs Audio, bao bọc DacFeatureExtractor, một AutoTokenizer và một HiggsAudioV2TokenizerModel thành một bộ xử lý duy nhất. Nó kế thừa các chức năng trích xuất đặc trưng âm thanh, tokenizer và mã hóa/giải mã âm thanh. Xem call() và decode() để biết thêm thông tin.
__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
lớp transformers.HiggsAudioV2Model
< source >( config: HiggsAudioV2Config )
Tham số
- config (HiggsAudioV2Config) — Lớp cấu hình mô hình chứa tất cả các tham số của mô hình. Khởi tạo bằng tệp cấu hình không tải trọng số liên quan đến mô hình, chỉ tải cấu hình. Xem phương thức from_pretrained() để tải trọng số mô hình.
Mô hình Higgs Audio V2 cơ bản, xuất ra các hidden-states thô mà không có bất kỳ head cụ thể nào ở phía trên.
Mô hình này kế thừa từ PreTrainedModel. Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các mô hình của nó (chẳng hạn như tải xuống hoặc lưu trữ, thay đổi kích thước các nhúng đầu vào, cắt tỉa các đầu, v.v.)
Mô hình này cũng là một lớp con của torch.nn.Module trong PyTorch. Hãy sử dụng nó như một Module PyTorch thông thường và tham khảo tài liệu PyTorch cho mọi vấn đề liên quan đến cách sử dụng và hành vi chung.
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
Tham số
- input_ids (
torch.LongTensorcó dạng(batch_size, sequence_length), tùy chọn) — Chỉ số của các token trong chuỗi đầu vào theo từ điển. Mặc định, padding sẽ bị bỏ qua.Các chỉ số có thể được lấy bằng cách sử dụng AutoTokenizer. Xem PreTrainedTokenizer.encode() và PreTrainedTokenizer.call() để biết thêm chi tiết.
- audio_input_ids (
torch.LongTensorcó dạng(batch_size, num_audio_frames, num_codebooks), tùy chọn) — Chỉ số của các token codebook âm thanh.Các chỉ số có thể được lấy bằng cách sử dụng HiggsAudioV2TokenizerModel.encode().
- attention_mask (
torch.LongTensorcó hình dạng(batch_size, sequence_length), tùy chọn) — Mặt nạ để tránh thực hiện attention trên các chỉ số token padding. Các giá trị mặt nạ được chọn trong[0, 1]:- 1 cho các token không bị che,
- 0 cho các token bị che.
- audio_input_ids_mask (
torch.BoolTensorcó hình dạng(batch_size, num_audio_frames), tùy chọn) — Chỉ ra các khung âm thanh nào trongaudio_input_idslà hợp lệ. - position_ids (
torch.LongTensorcó hình dạng(batch_size, sequence_length), tùy chọn) — Chỉ số vị trí của các token trong mỗi chuỗi đầu vào trong các position embeddings. Được chọn trong khoảng[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, tuỳ chọn) — Các hidden-state đã tính trước (key và value trong các khối self-attention và cross-attention) có thể được sử dụng để tăng tốc giải mã tuần tự. Điều này thường bao gồmpast_key_valuesđược trả về bởi mô hình ở một giai đoạn giải mã trước đó, khiuse_cache=Truehoặcconfig.use_cache=True.Chỉ cho phép Cache instance làm đầu vào, xem hướng dẫn kv cache của chúng tôi. Nếu không truyền
past_key_values, DynamicCache sẽ được khởi tạo theo mặc định.Mô hình sẽ xuất ra cùng định dạng cache được đưa vào làm đầu vào.
Nếu
past_key_valuesđược sử dụng, người dùng được kỳ vọng chỉ nhậpinput_idschưa được xử lý (những phần chưa có trạng thái key value quá khứ được cung cấp cho mô hình này) có hình dạng(batch_size, unprocessed_length)thay vì toàn bộinput_idscó hình dạng(batch_size, sequence_length). - inputs_embeds (
torch.Tensorcó hình dạng(batch_size, sequence_length, hidden_size), tùy chọn) — Tùy chọn, thay vì truyềninput_ids, bạn có thể chọn truyền trực tiếp một biểu diễn nhúng. Điều này hữu ích nếu bạn muốn kiểm soát nhiều hơn cách chuyển đổi các chỉ sốinput_idsthành các vector liên quan so với ma trận tra cứu nhúng nội bộ của mô hình. - use_cache (
bool, tùy chọn) — Nếu đặt thànhTrue, các trạng thái key value củapast_key_valuessẽ được trả về và có thể được sử dụng để tăng tốc quá trình giải mã (xempast_key_values).
Trả về
~models.modeling_outputs.BaseModelOutputWithPast
Đầu ra thông thường của bộ giải mã với các vị trí placeholder đã được thay thế bằng các audio embeddings tương ứng.
Phương thức forward của HiggsAudioV2Model ghi đè lên phương thức đặc biệt __call__.
Mặc dù công thức cho bước truyền tiến cần được định nghĩa bên trong hàm này, người dùng nên gọi instance của
Modulesau đó thay vì gọi hàm này, vì instanceModulesẽ đảm nhận việc thực hiện các bước tiền xử lý và hậu xử lý, trong khi hàm này sẽ lặng lẽ bỏ qua chúng.
Ví dụ:
>>> 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
lớp transformers.HiggsAudioV2ForConditionalGeneration
< source >( config: HiggsAudioV2Configuse_text_head: bool = False )
Tham số
- config (HiggsAudioV2Config) — Lớp cấu hình mô hình chứa tất cả các tham số của mô hình. Khởi tạo bằng tệp cấu hình không tải trọng số liên quan đến mô hình, chỉ tải cấu hình. Xem phương thức from_pretrained() để tải trọng số mô hình.
- use_text_head (
bool, tuỳ chọn, mặc định là False) — Có sử dụng đầu mô hình ngôn ngữ văn bản hay không. Đầu này không bắt buộc cho việc tạo ra, nhưng có thể được dùng để tính toán tổn thất văn bản khi huấn luyện.
Mô hình Higgs Audio, một mô hình transformer tự hồi quy kiểu llama với dual-FFN.
Mô hình này kế thừa từ PreTrainedModel. Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các mô hình của nó (chẳng hạn như tải xuống hoặc lưu trữ, thay đổi kích thước các nhúng đầu vào, cắt tỉa các đầu, v.v.)
Mô hình này cũng là một lớp con của torch.nn.Module trong PyTorch. Hãy sử dụng nó như một Module PyTorch thông thường và tham khảo tài liệu PyTorch cho mọi vấn đề liên quan đến cách sử dụng và hành vi chung.
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
Tham số
- input_ids (
torch.LongTensorcó dạng(batch_size, sequence_length), tùy chọn) — Chỉ số của các token trong chuỗi đầu vào theo từ điển. Mặc định, padding sẽ bị bỏ qua.Các chỉ số có thể được lấy bằng cách sử dụng AutoTokenizer. Xem PreTrainedTokenizer.encode() và PreTrainedTokenizer.call() để biết thêm chi tiết.
- attention_mask (
torch.BoolTensorcó hình dạng(batch_size, sequence_length), tùy chọn) — Mặt nạ để tránh thực hiện attention trên các chỉ số token padding. Các giá trị mặt nạ được chọn trong[0, 1]:- 1 cho các token không bị che,
- 0 cho các token bị che.
- audio_input_ids (
torch.LongTensorcó dạng(batch_size, num_audio_frames, num_codebooks), tùy chọn) — Chỉ số của các token codebook âm thanh.Các chỉ số có thể được lấy bằng cách sử dụng HiggsAudioV2TokenizerModel.encode().
- audio_input_ids_mask (
torch.BoolTensorcó hình dạng(batch_size, num_audio_frames), tùy chọn) — Chỉ ra các khung âm thanh nào trongaudio_input_idslà hợp lệ. - position_ids (
torch.LongTensorcó hình dạng(batch_size, sequence_length), tùy chọn) — Chỉ số vị trí của các token trong mỗi chuỗi đầu vào trong các position embeddings. Được chọn trong khoảng[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, tuỳ chọn) — Các hidden-state đã tính trước (key và value trong các khối self-attention và cross-attention) có thể được sử dụng để tăng tốc giải mã tuần tự. Điều này thường bao gồmpast_key_valuesđược trả về bởi mô hình ở một giai đoạn giải mã trước đó, khiuse_cache=Truehoặcconfig.use_cache=True.Chỉ cho phép Cache instance làm đầu vào, xem hướng dẫn kv cache của chúng tôi. Nếu không truyền
past_key_values, DynamicCache sẽ được khởi tạo theo mặc định.Mô hình sẽ xuất ra cùng định dạng cache được đưa vào làm đầu vào.
Nếu
past_key_valuesđược sử dụng, người dùng được kỳ vọng chỉ nhậpinput_idschưa được xử lý (những phần chưa có trạng thái key value quá khứ được cung cấp cho mô hình này) có hình dạng(batch_size, unprocessed_length)thay vì toàn bộinput_idscó hình dạng(batch_size, sequence_length). - inputs_embeds (
torch.Tensorcó hình dạng(batch_size, sequence_length, hidden_size), tùy chọn) — Tùy chọn, thay vì truyềninput_ids, bạn có thể chọn truyền trực tiếp một biểu diễn nhúng. Điều này hữu ích nếu bạn muốn kiểm soát nhiều hơn cách chuyển đổi các chỉ sốinput_idsthành các vector liên quan so với ma trận tra cứu nhúng nội bộ của mô hình. - labels (
torch.LongTensorcó shape(batch_size, sequence_length), tùy chọn) — Nhãn để tính toán tổn thất mô hình hóa ngôn ngữ có che (masked language modeling loss). Chỉ số phải nằm trong[0, ..., config.vocab_size]hoặc -100 (xem docstring củainput_ids). Các token có chỉ số được đặt thành-100sẽ bị bỏ qua (che), tổn thất chỉ được tính cho các token có nhãn nằm trong[0, ..., config.vocab_size]. - audio_labels (
torch.LongTensorof shape(batch_size, num_audio_frames, num_codebooks), optional) — Labels for the audio codebook tokens for computing the masked language modeling loss. Indices should either be in[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, tùy chọn) — Nếu đặt thànhTrue, các trạng thái key value củapast_key_valuessẽ được trả về và có thể được sử dụng để tăng tốc quá trình giải mã (xempast_key_values). - logits_to_keep (
Union[int, torch.Tensor], tùy chọn, mặc định là0) — Nếu làint, tính logits chologits_to_keeptoken cuối. Nếu là0, tính logits cho tất cảinput_ids(trường hợp đặc biệt). Chỉ cần logits của token cuối cho quá trình sinh, và việc chỉ tính cho token đó có thể tiết kiệm bộ nhớ, điều này trở nên khá đáng kể với các chuỗi dài hoặc kích thước từ vựng lớn. Nếu làtorch.Tensor, phải là 1 chiều tương ứng với các chỉ số cần giữ trong chiều độ dài chuỗi. Điều này hữu ích khi sử dụng định dạng tensor đóng gói (một chiều duy nhất cho batch và độ dài chuỗi).
Trả về
~models.modeling_outputs.CausalLMOutputWithPast
Một ~models.modeling_outputs.CausalLMOutputWithPast chứa logits, loss (nếu có labels được cung cấp),
và các đầu ra khác từ mô hình.
Phương thức forward của HiggsAudioV2ForConditionalGeneration ghi đè lên phương thức đặc biệt __call__.
Mặc dù công thức cho bước truyền tiến cần được định nghĩa bên trong hàm này, người dùng nên gọi instance của
Modulesau đó thay vì gọi hàm này, vì instanceModulesẽ đảm nhận việc thực hiện các bước tiền xử lý và hậu xử lý, trong khi hàm này sẽ lặng lẽ bỏ qua chúng.
Ví dụ:
>>> 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
Tham số
- inputs (
torch.Tensorcó hình dạng thay đổi tùy theo chế độ, không bắt buộc) — Chuỗi được dùng làm prompt cho quá trình sinh hoặc làm đầu vào mô hình cho bộ mã hóa. NếuNone, phương thức sẽ khởi tạo nó vớibos_token_idvà kích thước batch là 1. Đối với các mô hình chỉ có bộ giải mã,inputsphải ở định dạnginput_ids. Đối với các mô hình mã hóa-giải mã, inputs có thể đại diện cho bất kỳinput_ids,input_values,input_features, hoặcpixel_values. - generation_config (GenerationConfig, optional) —
Cấu hình sinh được sử dụng làm tham số cơ sở cho lệnh gọi sinh.
**kwargsđược truyền vào generate và khớp với các thuộc tính củageneration_configsẽ ghi đè lên chúng. Nếugeneration_configkhông được cung cấp, giá trị mặc định sẽ được sử dụng, với thứ tự ưu tiên nạp như sau: 1) từ tệp mô hìnhgeneration_config.json, nếu tệp này tồn tại; 2) từ cấu hình mô hình. Vui lòng lưu ý rằng các tham số không được chỉ định sẽ kế thừa các giá trị mặc định của GenerationConfig, và tài liệu của chúng nên được kiểm tra để tham số hóa quá trình sinh. - logits_processor (
LogitsProcessorList, tùy chọn) — Các logits processor tùy chỉnh bổ sung cho các logits processor mặc định được tạo từ các đối số và cấu hình sinh. Nếu một logit processor được truyền vào mà đã được tạo từ các đối số hoặc một cấu hình sinh, một lỗi sẽ được ném ra. Tính năng này dành cho người dùng nâng cao. - stopping_criteria (
StoppingCriteriaList, tùy chọn) — Tiêu chí dừng tùy chỉnh bổ sung cho tiêu chí dừng mặc định được xây dựng từ các đối số và cấu hình sinh. Nếu một tiêu chí dừng được truyền vào mà đã được tạo từ các đối số hoặc cấu hình sinh, một lỗi sẽ được ném ra. Nếu tiêu chí dừng của bạn phụ thuộc vào đầu vàoscores, hãy đảm bảo bạn truyềnreturn_dict_in_generate=True, output_scores=Truevàogenerate. Tính năng này dành cho người dùng nâng cao. - prefix_allowed_tokens_fn (
Callable[[int, torch.Tensor], list[int]], tùy chọn) — Nếu được cung cấp, hàm này sẽ ràng buộc beam search chỉ sử dụng các token được phép ở mỗi bước. Nếu không được cung cấp, sẽ không áp dụng ràng buộc nào. Hàm này nhận 2 đối số: ID của batchbatch_idvàinput_ids. Nó phải trả về một danh sách chứa các token được phép cho bước sinh tiếp theo, dựa trên ID của batchbatch_idvà các token đã được sinh trước đóinputs_ids. Đối số này hữu ích cho việc sinh có ràng buộc dựa trên tiền tố, như được mô tả trong Autoregressive Entity Retrieval. - synced_gpus (
bool, tùy chọn) — Có tiếp tục chạy vòng lặp while cho đến max_length hay không. Trừ khi được ghi đè, cờ này sẽ được đặt thànhTruenếu sử dụngFullyShardedDataParallelhoặc DeepSpeed ZeRO Stage 3 với nhiều GPU để tránh tình trạng deadlock nếu một GPU hoàn thành việc tạo ra trước các GPU khác. Ngược lại, mặc định làFalse. - assistant_model (
PreTrainedModel, tùy chọn) — Một mô hình trợ lý có thể được sử dụng để tăng tốc quá trình sinh. Mô hình trợ lý phải có cùng bộ phân từ (tokenizer) chính xác. Việc tăng tốc đạt được khi dự đoán các token ứng viên bằng mô hình trợ lý nhanh hơn nhiều so với việc chạy sinh bằng mô hình mà bạn đang gọi generate từ. Do đó, mô hình trợ lý nên nhỏ hơn nhiều. - streamer (
BaseStreamer, tuỳ chọn) — Đối tượng Streamer sẽ được dùng để stream các chuỗi được tạo ra. Các token được tạo sẽ được truyền quastreamer.put(token_ids)và streamer chịu trách nhiệm cho mọi xử lý tiếp theo. - negative_prompt_ids (
torch.LongTensorcó shape(batch_size, sequence_length), tùy chọn) — Prompt âm cần thiết cho một số bộ xử lý như CFG. Kích thước batch phải khớp với kích thước batch đầu vào. Đây là tính năng thử nghiệm, có thể bị thay đổi API gây lỗi trong các phiên bản tương lai. - negative_prompt_attention_mask (
torch.LongTensorcó hình dạng(batch_size, sequence_length), tùy chọn) — Attention_mask chonegative_prompt_ids. - custom_generate (
strhoặcCallable, tùy chọn) — Một trong các lựa chọn sau:str(tên kho Hugging Face Hub): chạy hàmgeneratetùy chỉnh được định nghĩa tạicustom_generate/generate.pytrong kho đó thay vì phương thứcgeneratetiêu chuẩn. Kho này thay thế hoàn toàn logic tạo ra, và kiểu trả về có thể khác.str(đường dẫn kho cục bộ): giống như trên nhưng từ một đường dẫn cục bộ. Các thư mục cục bộ cũng yêu cầutrust_remote_code=Truevìcustom_generate/generate.pycục bộ sẽ được thực thi.Callable:generatesẽ thực hiện các bước chuẩn bị đầu vào thông thường, sau đó gọi callable được cung cấp để chạy vòng lặp giải mã. Để biết thêm thông tin, xem tài liệu.
- kwargs (
dict[str, Any], tùy chọn) — Tham số hóa ad hoc chogeneration_configvà/hoặc các kwargs cụ thể của model bổ sung sẽ được chuyển tiếp đến hàmforwardcủa model. Nếu model là model encoder-decoder, các kwargs cụ thể của encoder không nên có tiền tố và các kwargs cụ thể của decoder nên có tiền tố decoder_.
Trả về
ModelOutput hoặc torch.LongTensor
Một ModelOutput (nếu return_dict_in_generate=True
hoặc khi config.return_dict_in_generate=True) hoặc một torch.LongTensor.
Nếu mô hình không phải là mô hình encoder-decoder (model.config.is_encoder_decoder=False), các kiểu
ModelOutput có thể là:
Nếu mô hình là mô hình encoder-decoder (model.config.is_encoder_decoder=True), các kiểu
ModelOutput có thể là:
Tạo ra các chuỗi id token cho các mô hình có đầu mô hình hóa ngôn ngữ.
Hầu hết các tham số kiểm soát quá trình sinh được đặt trong
generation_config, nếu không được truyền vào, sẽ được đặt thành cấu hình sinh mặc định của mô hình. Bạn có thể ghi đè bất kỳgeneration_confignào bằng cách truyền các tham số tương ứng vào generate(), ví dụ.generate(inputs, num_beams=4, do_sample=True).Để xem tổng quan về các chiến lược sinh và ví dụ mã, hãy xem hướng dẫn sau.