# VibeVoice

## 개요

[VibeVoice](https://huggingface.co/papers/2508.19205)는 Large Language Model(LLM) 구조 내에서 next-token diffusion 방식을 활용하여 다수의 화자가 포함된 고해상도 장문 음성 합성을 위한 새로운 프레임워크입니다. 자연스러운 대화의 'vibe'를 포착하도록 설계되었으며, 팟캐스트나 다수의 참여자가 있는 오디오북과 같은 오디오 콘텐츠 생성에 특히 적합합니다.

두 개의 모델 체크포인트는 다음 위치에 있습니다:
- [vibevoice/VibeVoice-1.5B-hf](https://huggingface.co/vibevoice/VibeVoice-1.5B-hf)
- [vibevoice/VibeVoice-7B-hf](https://huggingface.co/vibevoice/VibeVoice-7B-hf)

이 모델은 [Eric Bezzam](https://huggingface.co/bezzam)이 기여했습니다.

## 아키텍처

    

VibeVoice 프레임워크는 세 가지 핵심 구성 요소를 통합합니다:
1. **연속 음성 토크나이저:** [음향](./vibevoice_acoustic_tokenizer) 및 의미론적 토크나이저로, 음향 토크나이저는 $\sigma$-VAE를 사용하여 초저 압축(7.5 토크/초, 3200배)을 달성하여 확장성과 충실도를 확보하고, 의미론적 토크나이저는 ASR 프록시 작업을 통해 콘텐츠 중심의 특징 추출을 수행합니다.
2. **대형 언어 모델(LLM):** 핵심 시퀀스 모델로 Qwen2.5(1.5B 및 7B 버전)를 사용합니다.
3. **토큰 레벨 디퓨전 헤드:** LLM의 히든 상태에 조건부이며, 스트리밍 방식으로 연속적인 VAE 특징을 예측하는 역할을 합니다.

원본 VibeVoice-1.5B 체크포인트는 Hugging Face의 [Microsoft](https://huggingface.co/microsoft/VibeVoice-1.5B) 조직에서 사용할 수 있습니다.

## 주요 기능

- **장문 합성**: 최대 90분 분량의 다중 화자 대화 음성 합성이 가능합니다.
- **다중 화자 대화**: 최대 4명의 화자가 포함된 오디오를 합성할 수 있습니다.
- **최고 수준의 품질**: 주관적 및 객관적 지표 모두에서 베이스라인을 능가합니다.
- **높은 압축률**: 초저속 7.5 Hz 프레임 레이트로 동작하는 새로운 음향 토크나이저를 통해 달성됩니다.
- **확장 가능한 LLM**: 핵심 LLM을 1.5B에서 7B로 확장하면 지각 품질이 크게 향상됩니다.

## 사용

### 설정 

오디오 생성은 diffusion process에 의존하므로 noise scheduler가 필요합니다. 가장 간단한 방법(모델 개발자가 사용한 방식)은 `diffusers` 라이브러리의 noise scheduler를 사용하는 것입니다. 기본적으로 모델은 내부적으로 `diffusers`를 사용하여 noise scheduler를 생성합니다.
```
pip install diffusers
pip install soundfile   # for saving audio
```

### 모델 로드

```python
from transformers import AutoProcessor, AutoModelForTextToWaveform

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

### 텍스트-음성 변환(TTS)

```python
import os
from transformers import AutoProcessor, AutoModelForTextToWaveform

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

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

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

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

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

### TTS 음성 클로닝

채팅 템플릿 사전에 텍스트와 함께 참조 오디오를 제공하면 목소리를 복제할 수 있습니다.

```python
import os
from transformers import AutoProcessor, AutoModelForTextToWaveform, set_seed

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

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

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

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

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

### 스크립트에서 팟캐스트 생성

…는 각 고유한 역할 ID에 대해 참조 오디오를 제공하여 목소리를 복제하는 두 화자 간의 대화를 생성하는 예시입니다.

아래 예제에서는 생성 진행 상황을 추적하기 위해 `monitor_progress` 옵션도 사용했습니다.

```python
import os
import time
from transformers import AutoProcessor, AutoModelForTextToWaveform

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

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

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

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

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

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

### 배치 추론

배치 처리를 위해 대화 목록을 `processor.apply_chat_template`에 전달할 수 있습니다:

```python
import os
import time
from transformers import AutoProcessor, AutoModelForTextToWaveform

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

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

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

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

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

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

### Pipeline 사용

VibeVoice는 pipeline로도 로드할 수 있습니다. 아래에서는 diffusion 파라미터를 조정하는 방법도 함께 보여 드립니다.

```python
import os
import soundfile as sf
from transformers import pipeline

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

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

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

### 학습

VibeVoice는 모델이 출력하는 손실로 학습할 수 있습니다.

```python
from transformers import AutoProcessor, AutoModelForTextToWaveform

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

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

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

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

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

# Backward pass
outputs.loss.backward()
```

### Torch compile

모델은 `torch.compile`로 컴파일하여 추론 속도를 높일 수 있습니다. 컴파일된 모델이 최대 속도에 도달하려면 몇 번의 워밍업 실행이 필요합니다.

A100에서 배치 크기 4로 실행할 때, 컴파일된 추론과 컴파일되지 않은 추론 사이에 약 1.5배의 속도 향상을 관찰했으며, [이 스크립트](https://gist.github.com/ebezzam/c45b9fdee65f3029e17d566e30c59399)를 참고하세요.

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

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

torch.set_float32_matmul_precision("high")

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

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

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

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

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

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

## VibeVoiceConfig[[transformers.VibeVoiceConfig]]

#### transformers.VibeVoiceConfig[[transformers.VibeVoiceConfig]]

```python
transformers.VibeVoiceConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, audio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, semantic_model_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, diffusion_head_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, pad_token_id: int = 151643, eos_token_id: int = 151643, audio_bos_token_id: int = 151652, audio_eos_token_id: int = 151653, audio_token_id: int = 151654, diffusion_loss_weight: float = 0.5)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/configuration_vibevoice.py#L49)

**매개변수:**

audio_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *선택*) : 오디오 백본의 config 객체 또는 사전입니다.

semantic_model_config (`Union[AutoConfig, dict]`, *선택 사항*) : 시맨틱 토크나이저 인코더의 config 객체 또는 사전입니다. 이 토크나이저는 오디오에서 시맨틱 특징을 추출합니다.

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *선택*) : 텍스트 백본의 config 객체 또는 사전입니다.

diffusion_head_config (`Union[VibeVoiceDiffusionHeadConfig, dict]`, *선택 사항*) : 음향 잠재 변수를 합성하는 데 사용되는 diffusion head의 config 객체 또는 사전입니다.

pad_token_id (`int`, *선택 사항*, 기본값 `151643`) : 어휘에서 패딩에 사용되는 토큰 ID입니다.

eos_token_id (`int`, *선택 사항*, 기본값 `151643`) : 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.

audio_bos_token_id (`int`, *선택 사항*, 기본값 151652) : 오디오 토큰의 시작을 나타내는 토큰 ID입니다.

audio_eos_token_id (`int`, *선택 사항*, 기본값 151653) : 오디오 토큰의 끝을 나타내는 토큰 ID입니다.

audio_token_id (`int`, *선택 사항*, 기본값 `151654`) : 입력 오디오의 자리표시자로 사용되는 오디오 토큰 인덱스입니다.

diffusion_loss_weight (`float`, *선택 사항*, 기본값 0.5) : 전체 손실 계산에서 diffusion loss의 가중치입니다. 언어 모델링 헤드의 cross entropy loss는 `(1 - diffusion_loss_weight)`로 가중됩니다.

이것은 VibeVoiceForConditionalGeneration의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Vibevoice 모델을 초기화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 초기화하면 [vibevoice/VibeVoice-1.5B-hf](https://huggingface.co/vibevoice/VibeVoice-1.5B-hf)와 유사한 설정이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/v5.23.0/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/v5.23.0/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

```python
>>> from transformers import VibeVoiceForConditionalGeneration, VibeVoiceConfig

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

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

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

## VibeVoiceDiffusionHeadConfig[[transformers.VibeVoiceDiffusionHeadConfig]]

#### transformers.VibeVoiceDiffusionHeadConfig[[transformers.VibeVoiceDiffusionHeadConfig]]

```python
transformers.VibeVoiceDiffusionHeadConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 1536, latent_size: int = 64, num_hidden_layers: int = 4, intermediate_size: int = 4608, rms_norm_eps: float = 1e-05, hidden_act: str = 'silu', frequency_embedding_size: int = 256, diffusion_max_period: int = 10000, mlp_bias: bool = False)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/configuration_vibevoice.py#L24)

**매개변수:**

hidden_size (`int`, *선택 사항*, 기본값 `1536`) : 숨겨진 표현의 차원.

latent_size (`int`, *선택 사항*, 기본값 64) : 헤드(denoising)가 노이즈를 제거하는 음향 잠재 변수(acoustic latents)의 차원.

num_hidden_layers (`int`, *선택 사항*, 기본값 `4`) : Transformer 디코더의 숨겨진 레이어 수.

intermediate_size (`int`, *선택 사항*, 기본값 `4608`) : MLP 표현의 차원.

rms_norm_eps (`float`, *선택 사항*, 기본값 `1e-05`) : rms normalization 레이어에서 사용되는 epsilon 값입니다.

hidden_act (`str`, *선택 사항*, 기본값 `silu`) : 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열). 예를 들어, `"gelu"`, `"relu"`, `"silu"` 등이 있습니다.

frequency_embedding_size (`int`, *선택 사항*, 기본값 256) : diffusion head에서 timestep 인코딩을 위한 sinusoidal frequency embedding의 크기입니다.

diffusion_max_period (`int`, *선택 사항*, 기본값 10000) : diffusion head의 사인 주파수 임베딩에 사용되는 최대 주기입니다.

mlp_bias (`bool`, *선택 사항*, 기본값 `False`) : MLP 레이어의 up_proj, down_proj, gate_proj 레이어에 bias를 사용할지 여부.

이것은 VibeVoiceForConditionalGeneration의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Vibevoice 모델을 초기화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 초기화하면 [vibevoice/VibeVoice-1.5B-hf](https://huggingface.co/vibevoice/VibeVoice-1.5B-hf)와 유사한 설정이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/v5.23.0/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/v5.23.0/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

## VibeVoiceProcessor[[transformers.VibeVoiceProcessor]]

#### transformers.VibeVoiceProcessor[[transformers.VibeVoiceProcessor]]

```python
transformers.VibeVoiceProcessor(feature_extractor, tokenizer, chat_template = None, audio_bos_token = '<|vision_start|>', audio_eos_token = '<|vision_end|>', audio_token = '<|vision_pad|>')
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/processing_vibevoice.py#L38)

**매개변수:**

feature_extractor (`VibeVoiceAcousticTokenizerFeatureExtractor`) : feature extractor는 필수 입력입니다.

tokenizer (`Qwen2TokenizerFast`) : 토크나이저는 필수 입력입니다.

chat_template (`str`) : 채팅의 메시지 목록을 토큰화 가능한 문자열로 변환하는 Jinja 템플릿입니다.

audio_bos_token (`str`, *선택 사항*, 기본값 `"<|vision_start|>"`) : 오디오 생성의 시작을 나타내는 데 사용되는 토큰입니다.

audio_eos_token (`str`, *선택 사항*, 기본값 `"<|vision_end|>"`) : 오디오 생성의 끝을 나타내는 데 사용되는 토큰입니다.

audio_token (`str`, *선택 사항*, 기본값 `"<|vision_pad|>"`) : 오디오 생성을 계속하도록 나타내는 데 사용되는 토큰입니다.

VibeVoiceProcessor를 생성하며, feature extractor와 tokenizer를 단일 processor로 래핑합니다.

[VibeVoiceProcessor](/docs/transformers/v5.23.0/ko/model_doc/vibevoice#transformers.VibeVoiceProcessor)는 [VibeVoiceAcousticTokenizerFeatureExtractor](/docs/transformers/v5.23.0/ko/model_doc/vibevoice_acoustic_tokenizer#transformers.VibeVoiceAcousticTokenizerFeatureExtractor)와 [Qwen2TokenizerFast](/docs/transformers/v5.23.0/ko/model_doc/qwen2#transformers.Qwen2Tokenizer)의 모든 기능을 제공합니다. 자세한 내용은 [~VibeVoiceAcousticTokenizerFeatureExtractor](/docs/transformers/v5.23.0/ko/model_doc/vibevoice_acoustic_tokenizer#transformers.VibeVoiceAcousticTokenizerFeatureExtractor)와 [~Qwen2TokenizerFast](/docs/transformers/v5.23.0/ko/model_doc/qwen2#transformers.Qwen2Tokenizer)를 참고하세요.

#### __call__[[transformers.VibeVoiceProcessor.__call__]]

```python
__call__(text: str | list[str] | list[list[str]], audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, output_labels: bool | None = False, **kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/processing_vibevoice.py#L92)

**매개변수:**

text (`str`, `List[str]`) : 처리할 입력 텍스트로, 일반적으로 오디오 토큰 플레이스홀더를 포함하여 apply_chat_template로 준비됩니다.

audio (`List[Union[str, np.ndarray]]`, *선택 사항*) : 화자 음성 클로닝을 위한 오디오 샘플. 텍스트의 오디오 토큰 플레이스홀더 수와 일치해야 합니다.

output_labels (`bool`, *선택*, 기본값=False) : 학습용 라벨을 반환할지 여부.

- ****kwargs** : 토크나이저와 feature extractor에 전달되는 추가 키워드 인자.

return_mm_token_type_ids (`bool`, *kwargs*) : 멀티모달 플레이스홀더 토큰의 위치를 나타내는 멀티모달 토큰 타입 ID를 반환할지 여부.

return_text_replacement_offsets (`bool`, *kwargs*) : 각 멀티모달 플레이스홀더 및 그 대체 문자열의 문자 오프셋을 반환할지 여부.

return_tensors (`str` 또는 [TensorType](/docs/transformers/v5.23.0/ko/internal/file_utils#transformers.TensorType), *optional*) : 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:  - `'pt'`: PyTorch `torch.Tensor` 객체를 반환합니다. - `'np'`: NumPy `np.ndarray` 객체를 반환합니다.

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.23.0/ko/main_classes/processors#transformers.ProcessingKwargs), *optional*) : 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인수의 전체 목록은 TypedDict 클래스를 참조하세요.

**반환값:** [BatchFeature](/docs/transformers/v5.23.0/ko/main_classes/feature_extractor#transformers.BatchFeature)

다음 필드를 가진 [BatchFeature](/docs/transformers/v5.23.0/ko/main_classes/feature_extractor#transformers.BatchFeature):
- **input_ids** -- 모델에 입력할 토큰 ID 목록.
- **attention_mask** -- 모델이 어떤 토큰에 주의를 기울여야 하는지 지정하는 인덱스 목록(`return_attention_mask=True`인 경우).
- **input_values** -- 모델에 입력할 오디오 값 목록. `audio`가 `None`이 아닌 경우 반환됩니다.
- **padding_mask** -- 모델이 주의해야 할 오디오 프레임을 지정하는 인덱스 목록. `audio`가 `None`이 아닌 경우 반환됩니다.
- **labels** -- 언어 모델 학습용 라벨입니다. 패딩 및 오디오 디퓨전 토큰은 -100으로 마스킹됩니다(오디오 디퓨전 토큰 임베딩은 오디오 특징으로 대체되므로, 해당 토큰의 정체성은 의미 있는 학습 대상이 아닙니다). 오디오 bos/eos 및 텍스트 eos 토큰은 학습 대상으로 유지되어, LM이 오디오 생성을 시작하고 종료할 시점을 학습할 수 있도록 합니다. `output_labels=True`일 때 반환됩니다.
- **acoustic_loss_mask** -- diffusion loss가 계산되는 위치를 위한 Boolean mask입니다. 오디오 diffusion 토큰 위치에서 True입니다. `output_labels=True`일 때 반환됩니다.

## VibeVoiceForConditionalGeneration[[transformers.VibeVoiceForConditionalGeneration]]

#### transformers.VibeVoiceForConditionalGeneration[[transformers.VibeVoiceForConditionalGeneration]]

```python
transformers.VibeVoiceForConditionalGeneration(config: VibeVoiceConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/modeling_vibevoice.py#L367)

**매개변수:**

config ([VibeVoiceConfig](/docs/transformers/v5.23.0/ko/model_doc/vibevoice#transformers.VibeVoiceConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

언어 모델, 오디오 토크나이저, 커넥터, diffusion head로 구성된 VibeVoice 모델.

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.VibeVoiceForConditionalGeneration.forward]]

```python
forward(input_ids: LongTensor = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, logits_to_keep: int | slice = 0, input_values: typing.Optional[torch.Tensor] = None, padding_mask: typing.Optional[torch.BoolTensor] = None, acoustic_loss_mask: typing.Optional[torch.BoolTensor] = None, noise_scheduler: object | None = None, ddpm_batch_multiplier: int = 4, num_diffusion_steps: int = 10, sample: bool = True, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/modeling_vibevoice.py#L422)

**매개변수:**

input_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 어휘(input sequence tokens)의 인덱스입니다. 기본적으로 패딩은 무시됩니다. [AutoTokenizer](/docs/transformers/v5.23.0/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [입력 ID란 무엇인가요?](../glossary#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)`, *선택 사항*) : masked language modeling loss를 계산하기 위한 라벨. 인덱스는 `[0, ..., config.vocab_size]` 범위 내이거나 -100이어야 합니다(`input_ids` docstring 참조). 인덱스가 `-100`으로 설정된 토큰은 무시(마스크)되며, loss는 `[0, ..., config.vocab_size]` 범위의 라벨을 가진 토큰에 대해서만 계산됩니다.

logits_to_keep (`Union[int, slice]`, *선택 사항*, 기본값 `0`) : `int`인 경우, 마지막 `logits_to_keep` 토큰에 대한 logits를 계산합니다. `0`인 경우, 모든 `input_ids`에 대한 logits를 계산합니다(특수한 경우). 생성에는 마지막 토큰의 logits만 필요하며, 해당 토큰에 대해서만 계산하면 메모리를 절약할 수 있습니다. 이는 긴 시퀀스나 큰 어휘 크기의 경우 상당한 이점을 제공합니다. `torch.Tensor`인 경우, 시퀀스 길이 차원에서 유지할 인덱스에 해당하는 1차원이어야 합니다. 이는 패킹된 텐서 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.

input_values (`torch.Tensor`, *선택 사항*) : 음성 클로닝을 위한 전처리된 오디오 웨이브폼.

padding_mask (`torch.BoolTensor`, *선택 사항*) : 유효한 입력 프레임을 나타내는 마스크.

acoustic_loss_mask (`torch.BoolTensor`, *선택 사항*) : 특정 음향 토큰에서만 확산 손실을 계산하기 위한 마스크입니다.

noise_scheduler (`object`, *선택 사항*) : diffusion loss의 noise targets를 계산하기 위해 학습에 필요합니다. 기본적으로 모델의 `generation_config`에 지정된 noise scheduler 구성을 사용합니다.

ddpm_batch_multiplier (`int`, *선택 사항*, 기본값 4) : 학습 시, 확산 손실(diffusion loss) 계산에 사용할 오디오 토큰당 노이즈 샘플 수입니다. 학습 안정화에 도움이 될 수 있습니다.

num_diffusion_steps (`int`, *선택 사항*, 기본값 10) : 학습에 사용할 diffusion step 수입니다. 제공되지 않으면 기본값으로 10이 사용됩니다.

sample (`bool`, *선택 사항*, 기본값 `True`) : 원본 모델과 동일하게 음향 latents에 가우시안 노이즈를 추가할지 여부입니다 (σ-VAE: 노이즈 스케일은 배치 항목별로 N(0, `vae_std`)에서 추출됩니다). False인 경우 인코더 출력을 그대로 사용하므로 출력은 결정론적입니다.

**반환값:** `VibeVoiceCausalLMOutputWithPast` 또는 `tuple(torch.Tensor)`

`VibeVoiceCausalLMOutputWithPast` 또는 `return_dict=False`가 전달되거나 `config.return_dict=False`인 경우 `torch.Tensor`의 튜플로, [VibeVoiceConfig](/docs/transformers/v5.23.0/ko/model_doc/vibevoice#transformers.VibeVoiceConfig) 및 입력에 따라 다양한 요소를 포함합니다.

[VibeVoiceForConditionalGeneration](/docs/transformers/v5.23.0/ko/model_doc/vibevoice#transformers.VibeVoiceForConditionalGeneration)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  `past_key_values`가 사용되면, `(batch_size, 1, hidden_size)` 형태의 시퀀스의 마지막 hidden-state만 출력됩니다.
- **past_key_values** (`Cache`, *선택 사항*, `use_cache=True`가 전달되었거나 `config.use_cache=True`인 경우 반환됨) -- [Cache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.Cache) 인스턴스입니다. 자세한 내용은 [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요.

  순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록의 key와 value, 그리고 `config.is_encoder_decoder=True`인 경우 크로스 어텐션 블록의 key와 value)를 포함합니다(입력 `past_key_values` 참조).
- **hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 형태는 `(batch_size, sequence_length, hidden_size)`입니다.

  각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
- **attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환됨) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, 모양은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.
- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*, `labels`가 제공될 때 반환됨) -- 언어 모델링 손실(다음 토큰 예측용).
- **logits** (`torch.Tensor`, shape `(batch_size, sequence_length, config.vocab_size)`) -- 언어 모델링 헤드에서 생성된 예측 점수(SoftMax 적용 전 각 어휘 토큰에 대한 점수).
- **audio_features** (`torch.Tensor`, shape `(batch_size, sequence_length, feature_size)`, *선택 사항*) -- 언어 모델을 조건화하는 데 사용할 수 있는 추출된 오디오 특징입니다.

예:

```python
>>> from transformers import AutoProcessor, VibeVoiceForConditionalGeneration

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

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

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

#### generate[[transformers.VibeVoiceForConditionalGeneration.generate]]

```python
generate(inputs: typing.Optional[torch.Tensor] = None, generation_config: transformers.generation.configuration_utils.GenerationConfig | None = None, logits_processor: transformers.generation.logits_process.LogitsProcessorList | None = None, stopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = None, prefix_allowed_tokens_fn: collections.abc.Callable[[int, torch.Tensor], list[int]] | None = None, synced_gpus: bool | None = None, assistant_model: typing.Optional[ForwardRef('PreTrainedModel')] = None, streamer: typing.Optional[ForwardRef('BaseStreamer')] = None, negative_prompt_ids: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, custom_generate: str | collections.abc.Callable | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/generation/utils.py#L2581)

**매개변수:**

inputs (`torch.Tensor`, 모달리티에 따라 형태가 다양하며, *선택 사항*) : 생성을 위한 프롬프트로 사용되거나 인코더의 모델 입력으로 사용되는 시퀀스입니다. `None`인 경우 `bos_token_id`와 배치 크기 1로 초기화됩니다. 디코더 전용 모델의 경우 `inputs`는 `input_ids` 형식이어야 합니다. 인코더-디코더 모델의 경우 *inputs*는 `input_ids`, `input_values`, `input_features`, `pixel_values` 중 어느 하나를 나타낼 수 있습니다.

generation_config ([GenerationConfig](/docs/transformers/v5.23.0/ko/main_classes/text_generation#transformers.GenerationConfig), *선택*) : 생성 호출의 기본 파라미터화로 사용할 생성 구성입니다. `**kwargs`로 전달되며 `generation_config`의 속성과 일치하는 값은 해당 속성을 덮어씁니다. `generation_config`가 제공되지 않으면 기본값이 사용되며, 이때 로딩 우선순위는 다음과 같습니다: 1) `generation_config.json` 모델 파일이 존재하는 경우 해당 파일에서; 2) 모델 구성에서. 명시되지 않은 파라미터는 [GenerationConfig](/docs/transformers/v5.23.0/ko/main_classes/text_generation#transformers.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를 허용된 토큰으로만 제한합니다. 지정되지 않으면 제약이 적용되지 않습니다. 이 함수는 2개의 인수를 받습니다: 배치 ID `batch_id`와 `input_ids`. 배치 ID `batch_id`와 이전에 생성된 토큰 `inputs_ids`에 조건부인 다음 생성 단계에 허용되는 토큰의 리스트를 반환해야 합니다. 이 인수는 [Autoregressive Entity Retrieval](https://huggingface.co/papers/2010.00904)에 설명된 바와 같이 접두사에 조건부인 제약 생성에 유용합니다.

synced_gpus (`bool`, *선택 사항*) : max_length까지 while 루프를 계속 실행할지 여부. `FullyShardedDataParallel` 또는 DeepSpeed ZeRO Stage 3을 여러 GPU로 사용하는 경우, 한 GPU가 다른 GPU보다 먼저 생성을 완료할 때 데드락을 방지하기 위해 이 플래그가 `True`로 설정됩니다. 이 경우를 제외하면 기본값은 `False`입니다.

assistant_model (`PreTrainedModel`, *선택 사항*) : 생성을 가속화하는 데 사용할 수 있는 어시스턴트 모델입니다. 어시스턴트 모델은 정확히 동일한 토크나이저를 가져야 합니다. 어시스턴트 모델로 후보 토큰을 예측하는 것이 generate를 호출하는 모델로 생성을 실행하는 것보다 훨씬 빠를 때 가속화가 이루어집니다. 따라서 어시스턴트 모델은 훨씬 작아야 합니다.

streamer (`BaseStreamer`, *선택 사항*) : 생성된 시퀀스를 스트리밍하는 데 사용되는 Streamer 객체입니다. 생성된 토큰은 `streamer.put(token_ids)`를 통해 전달되며, 스트리머는 추가 처리를 담당합니다.

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을 호출하여 디코딩 루프를 실행합니다. 자세한 내용은 [문서](../../generation_strategies#custom-generation-methods)를 참조하세요.

kwargs (`dict[str, Any]`, *선택*) : `generation_config`의 즉석 파라미터화 및/또는 모델의 `forward` 함수로 전달될 추가적인 모델 전용 kwargs입니다. 모델이 encoder-decoder 모델인 경우, encoder 전용 kwargs에는 접두사를 붙이지 않고 decoder 전용 kwargs에는 *decoder_* 접두사를 붙여야 합니다.

**반환값:** [ModelOutput](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.utils.ModelOutput) 또는 `torch.LongTensor`

`return_dict_in_generate=True`인 경우 또는 `config.return_dict_in_generate=True`인 경우 [ModelOutput](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.utils.ModelOutput), 아니면 `torch.LongTensor`.

모델이 인코더-디코더 모델이 *아니면* (`model.config.is_encoder_decoder=False`), 가능한 [ModelOutput](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.utils.ModelOutput) 유형은 다음과 같습니다:

- [GenerateDecoderOnlyOutput](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.generation.GenerateDecoderOnlyOutput),
- [GenerateBeamDecoderOnlyOutput](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.generation.GenerateBeamDecoderOnlyOutput)

모델이 인코더-디코더 모델(`model.config.is_encoder_decoder=True`)인 경우, 가능한 [ModelOutput](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.utils.ModelOutput) 유형은 다음과 같습니다:

- [GenerateEncoderDecoderOutput](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.generation.GenerateEncoderDecoderOutput),
- [GenerateBeamEncoderDecoderOutput](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.generation.GenerateBeamEncoderDecoderOutput)

language modeling 헤드가 있는 모델에 대해 토큰 ID 시퀀스를 생성합니다.

대부분의 생성 제어 매개변수는 `generation_config`에 설정되며, 전달되지 않으면 모델의 기본 생성 구성으로 설정됩니다. `generation_config`의 항목은 generate()에 해당 매개변수를 전달하여 오버라이드할 수 있습니다. 예를 들어 `.generate(inputs, num_beams=4, do_sample=True)`와 같이 사용할 수 있습니다.

생성 전략 개요와 코드 예제는 [다음 가이드](../generation_strategies)를 참고하세요.

## VibeVoiceModel[[transformers.VibeVoiceModel]]

#### transformers.VibeVoiceModel[[transformers.VibeVoiceModel]]

```python
transformers.VibeVoiceModel(config: VibeVoiceConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/modeling_vibevoice.py#L241)

**매개변수:**

config ([VibeVoiceConfig](/docs/transformers/v5.23.0/ko/model_doc/vibevoice#transformers.VibeVoiceConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

언어 모델링 헤드가 없는 오디오 토크나이저와 LLM 백본으로 구성된 VibeVoice 모델

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.VibeVoiceModel.forward]]

```python
forward(input_ids: LongTensor = None, inputs_embeds: typing.Optional[torch.Tensor] = None, input_values: typing.Optional[torch.Tensor] = None, padding_mask: typing.Optional[torch.BoolTensor] = None, sample: bool = True, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/modeling_vibevoice.py#L324)

**매개변수:**

input_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 어휘(input sequence tokens)의 인덱스입니다. 기본적으로 패딩은 무시됩니다. [AutoTokenizer](/docs/transformers/v5.23.0/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [입력 ID란 무엇인가요?](../glossary#input-ids)

inputs_embeds (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`, *선택 사항*) : `input_ids`를 전달하는 대신 임베디드 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다 `input_ids` 인덱스를 관련 벡터로 변환하는 방식에 대해 더 많은 제어가 필요한 경우 유용합니다.

input_values (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 입력 원시 음성 파형의 부동 소수점 값. `.flac` 또는 `.wav` 오디오 파일을 `list[float]`, `numpy.ndarray` 또는 `torch.Tensor` 타입의 배열로 로드하여 값을 얻을 수 있습니다. *예를 들어* torchcodec 라이브러리(`pip install torchcodec`) 또는 soundfile 라이브러리(`pip install soundfile`)를 사용할 수 있습니다. `input_values` 배열을 준비하려면 패딩 및 `torch.Tensor` 타입의 텐서 변환을 위해 [AutoProcessor](/docs/transformers/v5.23.0/ko/model_doc/auto#transformers.AutoProcessor)를 사용해야 합니다. 자세한 내용은 [VibeVoiceProcessor.__call__()](/docs/transformers/v5.23.0/ko/model_doc/vibevoice#transformers.VibeVoiceProcessor.__call__)를 참조하세요.

padding_mask (`torch.Tensor`, shape `(batch_size, padded_audio_length)`) : 오디오의 패딩된 부분을 제거하기 위한 패딩 마스크.

sample (`bool`, *선택 사항*, 기본값 `True`) : 원본 모델과 동일하게 음향 latents에 가우시안 노이즈를 추가할지 여부입니다 (σ-VAE: 노이즈 스케일은 배치 항목별로 N(0, `vae_std`)에서 추출됩니다). False인 경우 인코더 출력을 그대로 사용하므로 출력은 결정론적입니다.

**반환값:** [BaseModelOutputWithPast](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 또는 `tuple(torch.Tensor)`

구성([VibeVoiceConfig](/docs/transformers/v5.23.0/ko/model_doc/vibevoice#transformers.VibeVoiceConfig))과 입력에 따라 다양한 요소를 포함하는 [BaseModelOutputWithPast](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[VibeVoiceModel](/docs/transformers/v5.23.0/ko/model_doc/vibevoice#transformers.VibeVoiceModel)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  `past_key_values`가 사용되면, `(batch_size, 1, hidden_size)` 형태의 시퀀스의 마지막 hidden-state만 출력됩니다.
- **past_key_values** (`Cache`, *선택 사항*, `use_cache=True`가 전달되었거나 `config.use_cache=True`인 경우 반환됨) -- [Cache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.Cache) 인스턴스입니다. 자세한 내용은 [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요.

  순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록의 key와 value, 그리고 `config.is_encoder_decoder=True`인 경우 크로스 어텐션 블록의 key와 value)를 포함합니다(입력 `past_key_values` 참조).
- **hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 형태는 `(batch_size, sequence_length, hidden_size)`입니다.

  각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
- **attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환됨) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, 모양은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.

#### get_audio_features[[transformers.VibeVoiceModel.get_audio_features]]

```python
get_audio_features(input_values: Tensor, padding_mask: Tensor, sample: bool = True, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/modeling_vibevoice.py#L258)

**매개변수:**

input_values (`torch.Tensor`) : (정규화된) 오디오 웨이브폼의 Float 값.

padding_mask (`torch.Tensor`, shape `(batch_size, padded_audio_length)`) : 오디오의 패딩된 부분을 제거하기 위한 패딩 마스크.

sample (`bool`, *선택 사항*, 기본값 `True`) : 원본 모델과 동일하게 음향 latents에 가우시안 노이즈를 추가할지 여부입니다 (σ-VAE: 노이즈 스케일은 배치 항목별로 N(0, `vae_std`)에서 추출됩니다). False인 경우 인코더 출력을 그대로 사용하므로 출력은 결정론적입니다.

**반환값:** [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 또는 `tuple(torch.Tensor)`

구성([VibeVoiceConfig](/docs/transformers/v5.23.0/ko/model_doc/vibevoice#transformers.VibeVoiceConfig))과 입력에 따라 다양한 요소를 포함하는 [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

이 메서드는 입력 오디오 웨이브폼에서 오디오 임베딩(입력 시퀀스의 플레이스홀더 오디오 토큰을 대체하는 값)과 음향 특징(확산 타겟으로 사용됨)을 가져오는 데 사용됩니다.

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.
- **pooler_output** (`torch.Tensor`, shape `(batch_size, hidden_size)`) -- 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 보조 사전학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 값입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전학습 단계에서 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.
- **hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 형태는 `(batch_size, sequence_length, hidden_size)`입니다.

  각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
- **attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환됨) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, 모양은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.

#### get_placeholder_mask[[transformers.VibeVoiceModel.get_placeholder_mask]]

```python
get_placeholder_mask(input_ids: LongTensor, inputs_embeds: Tensor, audio_features: Tensor)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/vibevoice/modeling_vibevoice.py#L300)

`input_ids` 또는 `inputs_embeds`에서 멀티모달 플레이스홀더 마스크를 가져오고, 플레이스홀더 토큰 수가 멀티모달 특징의 길이와 같은지 확인합니다. 길이가 다르면 오류가 발생합니다.

