Transformers documentation
Higgs Audio V2
이 모델은 2026-02-19에 Hugging Face Transformers에 기여되었습니다.
Higgs Audio V2
개요
Higgs Audio V2는 Boson AI에서 개발한 강력한 오디오 파운데이션 모델입니다. 이 모델은 1,000만 시간 이상의 오디오 데이터와 다양한 텍스트 데이터로 사전 학습되었습니다. 사후 학습이나 파인튜닝이 없음에도 불구하고, Higgs Audio v2는 심층적인 언어 및 음향 이해력을 바탕으로 표현력 있는 오디오 생성에서 뛰어난 성능을 발휘합니다.
모델 아키텍처:

- 여러 ASR 모델, 사운드 이벤트 분류 모델, 그리고 자체 개발한 오디오 이해 모델을 활용하는 자동화 어노테이션 파이프라인을 개발했습니다. 이 파이프라인을 사용하여 1,000만 시간 분량의 오디오 데이터를 정제하고 어노테이션했으며, 이를 AudioVerse라고 부릅니다. 자체 개발한 이해 모델은 아키텍처 도면에 표시된 “understanding variant”를 채택한 Higgs Audio v1 Understanding을 기반으로 파인튜닝되었습니다.
- 의미적 특징과 음향적 특징을 모두 포착하도록 처음부터 통합 오디오 토크나이저를 학습했습니다.
- 최소 계산 오버헤드로 LLM의 음향 토큰 모델링 능력을 향상시키는 제안된 DualFFN 아키텍처.
사용
아래의 모든 스니펫은 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 감소). 그러나 모델을 학습할 때는 텍스트 토큰에 대한 손실을 계산하기 위해 텍스트 헤드가 필요합니다. 이를 활성화하려면 모델을 인스턴스화할 때
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로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다. - hidden_size (
int, 선택 사항, 기본값3072) — 숨겨진 표현의 차원입니다. - intermediate_size (
int, 선택 사항, 기본값8192) — MLP 표현의 차원입니다. - num_hidden_layers (
int, 선택 사항, 기본값28) — Transformer decoder의 숨겨진 레이어 수. - num_attention_heads (
int, 선택 사항, 기본값24) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다. - 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) — 모델이 마지막 key/values attention을 반환할지 여부입니다(모든 모델에서 사용되지 않음).config.is_decoder=True인 경우 또는 모델이 decoder-only 생성 모델인 경우에만 관련이 있습니다. - pad_token_id (
int, 선택 사항, 기본값128001) — 어휘에서 패딩에 사용되는 토큰 ID입니다. - bos_token_id (
int, 선택 사항, 기본값1) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다. - eos_token_id (
Union[int, list[int]], 선택 사항, 기본값128009) — 어휘에서 스트림 종료에 사용되는 토큰 id입니다. - pretraining_tp (
int, 선택 사항, 기본값1) — 실험적 기능입니다. 사전 학습(pretraining) 동안 사용된 Tensor parallelism rank입니다. 자세한 내용은 이 문서를 참고하세요. 이 값은 사전 학습 결과를 정확히 재현하기 위해 필요합니다. 이 이슈를 참고하세요. - tie_word_embeddings (
bool, 선택, 기본값False) — 모델의tied_weights_keys매핑에 따라 가중치 임베딩을 묶을지 여부. - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는rope_theta값이 포함되어야 하며, 더 긴max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다. - attention_bias (
bool, 선택 사항, 기본값False) — 자기 주의(self-attention) 시 query, key, value 및 출력 투영 계층에 bias를 사용할지 여부입니다. - attention_dropout (
Union[int, float], 선택 사항, 기본값0.0) — Attention 확률에 적용할 dropout 비율입니다. - mlp_bias (
bool, 선택 사항, 기본값False) — MLP 레이어의 up_proj, down_proj, gate_proj 레이어에 bias를 사용할지 여부. - head_dim (
int, 선택 사항, 기본값128) — Attention head의 차원입니다. None인 경우 hidden_size // num_attention_heads 값이 기본값으로 사용됩니다. - num_codebooks (
int, 선택 사항, 기본값8) — 모델이 사용하는 병렬 코드북의 수입니다. - codebook_size (
int, 선택 사항, 기본값1024) — 모델이 사용하는 병렬 코드북의 수입니다. - audio_token_id (
int, 선택 사항, 기본값128016) — 입력 오디오를 위한 플레이스홀더로 사용되는 오디오 토큰 인덱스입니다. - audio_bos_token_id (
int, 선택 사항, 기본값 128013) — 오디오 출력의 시퀀스 시작 토큰에 대한 토큰 ID입니다. - audio_delay_token_id (
int, 선택 사항, 기본값 128014) — 멀티 코드북 생성에서 오디오 지연 패턴에 사용되는 토큰 ID입니다. - audio_stream_bos_id (
int, 선택 사항, 기본값 1024) — 오디오 시퀀스에서 스트림 시작 토큰의 ID입니다. - audio_stream_eos_id (
int, 선택 사항, 기본값 1025) — 오디오 시퀀스에서 스트림 종료 토큰의 ID입니다.
이것은 bosonai/higgs-audio-v2-generation-3B-base의 구성과 유사한 구성을 생성하는 HiggsAudioV2ForConditionalGeneration의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Higgs Audio V2 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다.
Configuration 객체는 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의 인스턴스입니다. feature extractor는 필수 입력값입니다. - 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) — 오디오 시퀀스에서 스트림 시작 토큰의 ID입니다. - audio_stream_eos_id (
int, 선택 사항, 기본값 1025) — 오디오 시퀀스에서 스트림 종료 토큰의 ID입니다.
DacFeatureExtractor, AutoTokenizer, HiggsAudioV2TokenizerModel를 단일 프로세서로 감싸는 Higgs Audio 프로세서를 생성합니다. 오디오 특징 추출, 토크나이저, 오디오 인코딩/디코딩 기능을 상속합니다. 자세한 내용은 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() 메서드를 확인하세요.
특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 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), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.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), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- audio_input_ids_mask (
torch.BoolTensor, shape(batch_size, num_audio_frames), 선택 사항) —audio_input_ids에서 유효한 오디오 프레임을 나타냅니다. - position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(self-attention 블록과 cross-attention 블록의 key 및 value). 일반적으로 이는past_key_values디코딩의 이전 단계에서 모델이 반환한use_cache=True또는config.use_cache=True.입력으로 Cache 인스턴스만 허용되며, kv cache 가이드를 참고하세요.
past_key_values가 전달되지 않으면 기본적으로 DynamicCache가 초기화됩니다.모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다.
past_key_values를 사용하는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은input_ids만 입력해야 하며, 이때의 shape은(batch_size, unprocessed_length)입니다. shape이(batch_size, sequence_length)인 전체input_ids를 입력하지 않습니다. - inputs_embeds (
torch.Tensor, shape(batch_size, sequence_length, hidden_size), 선택) —input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다input_ids인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다. - use_cache (
bool, 선택 사항) —True로 설정하면past_key_values키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다(past_key_values참조).
반환값
~models.modeling_outputs.BaseModelOutputWithPast
자리 이미 해당 오디오 임베딩으로 대체된 일반적인 decoder 출력입니다.
HiggsAudioV2Model의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
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 계열의 오토레그레시브 트랜스포머 모델입니다.
이 모델은 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), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- attention_mask (
torch.BoolTensor다음 형태의(batch_size, sequence_length), , 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇일까요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- audio_input_ids (
torch.LongTensor다음 형태의(batch_size, num_audio_frames, num_codebooks), 선택 사항) — 오디오 코드북 토큰의 인덱스입니다.HiggsAudioV2TokenizerModel.encode()를 사용하여 인덱스를 얻을 수 있습니다.
- audio_input_ids_mask (
torch.BoolTensor, shape(batch_size, num_audio_frames), 선택 사항) —audio_input_ids에서 유효한 오디오 프레임을 나타냅니다. - position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(self-attention 블록과 cross-attention 블록의 key 및 value). 일반적으로 이는past_key_values디코딩의 이전 단계에서 모델이 반환한use_cache=True또는config.use_cache=True.입력으로 Cache 인스턴스만 허용되며, kv cache 가이드를 참고하세요.
past_key_values가 전달되지 않으면 기본적으로 DynamicCache가 초기화됩니다.모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다.
past_key_values를 사용하는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은input_ids만 입력해야 하며, 이때의 shape은(batch_size, unprocessed_length)입니다. shape이(batch_size, sequence_length)인 전체input_ids를 입력하지 않습니다. - inputs_embeds (
torch.Tensor, shape(batch_size, sequence_length, hidden_size), 선택) —input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다input_ids인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다. - labels (
torch.LongTensor, shape(batch_size, sequence_length), 선택 사항) — 마스크 언어 모델링 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., config.vocab_size]범위 내의 값이거나 -100이어야 합니다(input_idsdocstring 참조). 인덱스가-100으로 설정된 토큰은 무시(마스크)되며, 손실은[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, 선택 사항) —True로 설정하면past_key_values키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다(past_key_values참조). - logits_to_keep (
Union[int, torch.Tensor], 선택 사항, 기본값0) —int인 경우, 마지막logits_to_keep토큰에 대한 logits를 계산합니다.0인 경우, 모든input_ids에 대한 logits를 계산합니다(특수한 경우). 생성에는 마지막 토큰의 logits만 필요하며, 해당 토큰에 대해서만 계산하면 메모리를 절약할 수 있습니다. 이는 긴 시퀀스나 큰 어휘 크기의 경우 상당한 이점을 제공합니다.torch.Tensor인 경우, 시퀀스 길이 차원에서 유지할 인덱스에 해당하는 1차원 텐서여야 합니다. 이는 패킹된 텐서 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.
반환값
~models.modeling_outputs.CausalLMOutputWithPast
~models.modeling_outputs.CausalLMOutputWithPast 객체로, logits, loss(레이블이 제공된 경우), 그리고 모델의 기타 출력값을 포함합니다.
HiggsAudioV2ForConditionalGeneration의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
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, 선택) —
생성 호출의 기본 파라미터화로 사용할 생성 설정입니다.
**kwargs를 통해 generate에 전달되며generation_config의 속성과 일치하는 값은 해당 속성을 덮어씁니다.generation_config가 제공되지 않으면 기본값이 사용되며, 이 기본값은 다음 로딩 우선순위를 따릅니다: 1)generation_config.json모델 파일이 존재하는 경우 해당 파일에서; 2) 모델 구성에서. 명시되지 않은 파라미터는 GenerationConfig의 기본값을 상속받으므로, 생성을 파라미터화하려면 해당 문서에서 기본값을 확인해야 합니다. - logits_processor (
LogitsProcessorList, 선택) — 인자와 generation config에서 기본으로 생성되는 logits processor를 보완하는 사용자 정의 logits processor입니다. 인자나 generation config로 이미 생성된 logit processor를 전달하면 오류가 발생합니다. 이 기능은 고급 사용자를 위해 제공됩니다. - stopping_criteria (
StoppingCriteriaList, 선택) — 인자와 generation config에서 기본으로 생성되는 stopping criteria를 보완하는 사용자 정의 stopping criteria입니다. 인자 또는 generation config로 이미 생성된 stopping criteria를 전달하면 오류가 발생합니다. stopping criteria가scores입력에 의존하는 경우,generate에return_dict_in_generate=True, output_scores=True를 전달하도록 하십시오. 이 기능은 고급 사용자를 위한 것입니다. - prefix_allowed_tokens_fn (
Callable[[int, torch.Tensor], list[int]], 선택) — 지정된 경우, 이 함수는 각 단계에서 beam search를 허용된 토큰으로만 제한합니다. 지정되지 않으면 제약이 적용되지 않습니다. 이 함수는 두 개의 인수를 받습니다: 배치 IDbatch_id와input_ids. 배치 IDbatch_id와 이전에 생성된 토큰inputs_ids에 조건부인 다음 생성 단계에 허용되는 토큰의 목록을 반환해야 합니다. 이 인수는 Autoregressive Entity Retrieval에 설명된 바와 같이 접두사에 조건부인 제약 생성에 유용합니다. - synced_gpus (
bool, 선택) — max_length까지 while 루프를 계속 실행할지 여부.FullyShardedDataParallel또는 DeepSpeed ZeRO Stage 3을 여러 GPU에서 사용하는 경우, 한 GPU가 다른 GPU보다 먼저 생성을 완료할 때 데드락을 방지하기 위해 이 플래그는 기본적으로True로 설정됩니다. 이 경우를 제외하면 기본값은False입니다. - assistant_model (
PreTrainedModel, 선택) — 생성을 가속하는 데 사용할 수 있는 어시스턴트 모델입니다. 어시스턴트 모델은 정확히 동일한 tokenizer를 가져야 합니다. 어시스턴트 모델로 후보 토큰을 예측하는 것이 generate를 호출하는 모델로 생성을 실행하는 것보다 훨씬 빠를 때 가속이 이루어집니다. 따라서 어시스턴트 모델은 훨씬 작아야 합니다. - streamer (
BaseStreamer, 선택 사항) — 생성된 시퀀스를 스트리밍하는 데 사용되는 Streamer 객체입니다. 생성된 토큰은streamer.put(token_ids)를 통해 전달되며, streamer는 추가적인 처리를 담당합니다. - negative_prompt_ids (
torch.LongTensor, shape(batch_size, sequence_length), 선택) — CFG와 같은 일부 프로세서에 필요한 negative prompt입니다. 배치 크기는 입력 배치 크기와 일치해야 합니다. 이는 실험적 기능이며, 향후 버전에서 API가 변경될 수 있습니다. - negative_prompt_attention_mask (
torch.LongTensor, shape(batch_size, sequence_length), 선택 사항) —negative_prompt_ids에 대한 attention_mask입니다. - custom_generate (
str또는Callable, 선택 사항) — 다음 중 하나입니다:str(Hugging Face Hub 저장소 이름): 표준generate메서드 대신 해당 저장소의custom_generate/generate.py에 정의된 사용자 정의generate함수를 실행합니다. 이 저장소는 생성 로직을 완전히 대체하며, 반환 타입이 다를 수 있습니다.str(로컬 저장소 경로): 위와 동일하지만 로컬 경로에서 가져옵니다. 로컬 디렉터리도 로컬custom_generate/generate.py가 실행되므로trust_remote_code=True가 필요합니다.Callable:generate는 일반적인 입력 준비 단계를 수행한 후, 제공된 callable을 호출하여 디코딩 루프를 실행합니다. 자세한 내용은 문서를 참조하세요.
- kwargs (
dict[str, Any], 선택) —generation_config의 즉석 파라미터화 및/또는 모델의forward함수로 전달되는 모델 특정 추가 kwargs입니다. 모델이 인코더-디코더 모델인 경우, 인코더 특정 kwargs에는 접두사를 붙이지 않고 디코더 특정 kwargs에는 decoder_ 접두사를 붙여야 합니다.
반환값
ModelOutput 또는 torch.LongTensor
return_dict_in_generate=True인 경우 또는 config.return_dict_in_generate=True인 경우 ModelOutput, 아니면 torch.LongTensor입니다.
모델이 인코더-디코더 모델이 아니면 (model.config.is_encoder_decoder=False), 가능한 ModelOutput 유형은 다음과 같습니다:
모델이 인코더-디코더 모델(model.config.is_encoder_decoder=True)인 경우, 가능한 ModelOutput 유형은 다음과 같습니다:
language modeling 헤드가 있는 모델에 대해 토큰 ID 시퀀스를 생성합니다.
대부분의 생성 제어 매개변수는
generation_config에 설정되며, 전달되지 않으면 모델의 기본 생성 구성으로 설정됩니다.generation_config의 항목은 generate()에 해당 매개변수를 전달하여 오버라이드할 수 있습니다. 예를 들어.generate(inputs, num_beams=4, do_sample=True)와 같이 사용할 수 있습니다.생성 전략 개요와 코드 예제는 다음 가이드를 참고하세요.