Transformers documentation

VibeVoice ASR

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

and get access to the augmented documentation experience

to get started

이 모델은 2026-01-26에 HF papers에 게시되었으며, 2026-03-02에 Hugging Face Transformers에 기여되었습니다.

VibeVoice ASR

FlashAttention SDPA

개요

VibeVoice ASR는 Microsoft에서 개발한 자동 음성 인식 모델로, 음향 및 의미론적 오디오 토크나이저를 인과적 언어 모델과 결합하여 견고한 음성-텍스트 변환을 수행합니다. 이 모델은 24kHz로 오디오를 처리하는 VibeVoice의 음향 및 의미론적 토크나이저와 전사 내용을 생성하기 위한 Qwen2 기반 언어 디코더를 함께 사용합니다. 자세한 내용은 기술 보고서를 참고하세요.

모델 체크포인트는 microsoft/VibeVoice-ASR-HF에서 사용할 수 있습니다.

주요 내용:

  • 🕒 60분 단일 패스 처리: 단순히 오디오를 짧은 청크로 잘라서 처리하는 기존 ASR 모델(전체 맥락을 잃기 쉬움)과 달리, VibeVoice ASR은 64K 토큰 길이 내에서 최대 60분의 연속 오디오 입력을 처리할 수 있습니다. 이를 통해 1시간 전체에 걸쳐 일관된 화자 추적과 의미적 응집력을 보장합니다.

  • 👤 사용자 지정 핫워드: 사용자는 인식 과정을 안내하기 위해 사용자 지정 핫워드(예: 특정 이름, 기술 용어, 배경 정보)를 제공할 수 있으며, 이를 통해 도메인별 콘텐츠의 정확도를 크게 향상시킬 수 있습니다.

  • 📝 풍부한 전사(누가, 언제, 무엇을): 모델은 ASR, 화자 분리, 타임스탬핑을 동시에 수행하여 누가 무엇을 언제 말했는지를 나타내는 구조화된 출력을 생성합니다.

  • 🌍 다국어 및 코드 스위칭 지원: 50개 이상의 언어를 지원하며, 명시적인 언어 설정이 필요 없고, 발화 내 및 발화 간 코드 스위칭을 기본적으로 처리합니다.

이 모델은 Eric Bezzam이 기여했습니다.

사용

모델은 다양한 자동 음성 인식 기능을 지원합니다.

화자별 타임스탬프가 포함된 전사

VibeVoice ASR의 주목할 만한 기능은 다중 화자 내용을 전사하면서 누가 언제 말했는지를 표시할 수 있다는 점입니다.

from transformers import AutoProcessor, VibeVoiceAsrForConditionalGeneration


model_id = "microsoft/VibeVoice-ASR-HF"
processor = AutoProcessor.from_pretrained(model_id)
model = VibeVoiceAsrForConditionalGeneration.from_pretrained(model_id, device_map="auto")
print(f"Model loaded on {model.device} with dtype {model.dtype}")

# Prepare inputs using `apply_transcription_request`
inputs = processor.apply_transcription_request(
    audio="https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/example_output/VibeVoice-1.5B_output.wav",
).to(model.device, model.dtype)

# Apply model
output_ids = model.generate(**inputs)
generated_ids = output_ids[:, inputs["input_ids"].shape[1] :]
transcription = processor.decode(generated_ids)[0]
print("\n" + "=" * 60)
print("RAW OUTPUT")
print("=" * 60)
print(transcription)

transcription = processor.decode(generated_ids, return_format="parsed")[0]
print("\n" + "=" * 60)
print("TRANSCRIPTION (list of dicts)")
print("=" * 60)
for speaker_transcription in transcription:
    print(speaker_transcription)

# Remove speaker labels, only get raw transcription
transcription = processor.decode(generated_ids, return_format="transcription_only")[0]
print("\n" + "=" * 60)
print("TRANSCRIPTION ONLY")
print("=" * 60)
print(transcription)

"""
============================================================
RAW OUTPUT
============================================================
<|im_start|>assistant
[{"Start":0,"End":15.43,"Speaker":0,"Content":"Hello everyone and welcome to the Vibe Voice 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."},{"Start":15.43,"End":21.05,"Speaker":1,"Content":"Thanks so much for having me, Alex. And you're absolutely right. This question always brings out some seriously strong feelings."},{"Start":21.05,"End":31.66,"Speaker":0,"Content":"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."},{"Start":31.66,"End":40.93,"Speaker":1,"Content":"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."}]<|im_end|>
<|endoftext|>

============================================================
TRANSCRIPTION (list of dicts)
============================================================
{'Start': 0, 'End': 15.43, 'Speaker': 0, 'Content': "Hello everyone and welcome to the Vibe Voice 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."}
{'Start': 15.43, 'End': 21.05, 'Speaker': 1, 'Content': "Thanks so much for having me, Alex. And you're absolutely right. This question always brings out some seriously strong feelings."}
{'Start': 21.05, 'End': 31.66, 'Speaker': 0, 'Content': "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."}
{'Start': 31.66, 'End': 40.93, 'Speaker': 1, 'Content': "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."}

============================================================
TRANSCRIPTION ONLY
============================================================
Hello everyone and welcome to the Vibe Voice 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.
"""

VibeVoice ASR 모델은 JSON 구조와 유사한 문자열을 생성하도록 학습됩니다. return_format="parsed" 플래그는 생성된 출력을 dict 목록으로 반환하려고 하며, return_format="transcription_only" 플래그는 전사된 오디오만 추출하려고 합니다. 이 과정이 실패하면 생성된 출력이 있는 그대로 반환됩니다.

컨텍스트 제공

컨텍스트를 제공하는 것도 가능합니다. 고유명사처럼 올바르게 전사되지 않을 수 있는 특정 단어가 있는 경우 유용합니다.

아래에서는 화자(독일어 억양)가 VibeVoice에 대해 이야기하는 오디오를 전사한 것입니다. 이때 “About VibeVoice”라는 컨텍스트가 있는 경우와 없는 경우를 비교합니다.

from transformers import AutoProcessor, VibeVoiceAsrForConditionalGeneration


model_id = "microsoft/VibeVoice-ASR-HF"
processor = AutoProcessor.from_pretrained(model_id)
model = VibeVoiceAsrForConditionalGeneration.from_pretrained(model_id, device_map="auto")
print(f"Model loaded on {model.device} with dtype {model.dtype}")

# Without context
inputs = processor.apply_transcription_request(
    audio="https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
).to(model.device, model.dtype)
output_ids = model.generate(**inputs)
generated_ids = output_ids[:, inputs["input_ids"].shape[1] :]
transcription = processor.decode(generated_ids, return_format="transcription_only")[0]
print(f"WITHOUT CONTEXT: {transcription}")

# With context
inputs = processor.apply_transcription_request(
    audio="https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
    prompt="About VibeVoice",
).to(model.device, model.dtype)
output_ids = model.generate(**inputs)
generated_ids = output_ids[:, inputs["input_ids"].shape[1] :]
transcription = processor.decode(generated_ids, return_format="transcription_only")[0]
print(f"WITH CONTEXT   : {transcription}")

"""
WITHOUT CONTEXT: Revevoices is a novel framework designed for generating expressive, long-form, multi-speaker conversational audio.
WITH CONTEXT   : VibeVoice is this novel framework designed for generating expressive, long-form, multi-speaker, conversational audio.
"""

배치 추론

오디오 목록을 전달하고, 제공된 경우 프롬프트 목록을 전달하여 배치 추론이 가능합니다. 오디오 입력과 프롬프트의 수는 일치해야 합니다(해당 오디오에 프롬프트가 필요 없는 경우 항목을 None으로 설정할 수 있습니다).

from transformers import AutoProcessor, VibeVoiceAsrForConditionalGeneration


model_id = "microsoft/VibeVoice-ASR-HF"
audio = [
    "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
    "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/example_output/VibeVoice-1.5B_output.wav"
]
prompts = ["About VibeVoice", None]

processor = AutoProcessor.from_pretrained(model_id)
model = VibeVoiceAsrForConditionalGeneration.from_pretrained(model_id, device_map="auto")
print(f"Model loaded on {model.device} with dtype {model.dtype}")

inputs = processor.apply_transcription_request(audio, prompt=prompts).to(model.device, model.dtype)
output_ids = model.generate(**inputs)
generated_ids = output_ids[:, inputs["input_ids"].shape[1] :]
transcription = processor.decode(generated_ids, return_format="transcription_only")

print(transcription)

토크나이저 청크 조정(예: 메모리 부족 시)

VibeVoice ASR의 핵심 기능 중 하나는 최대 60분까지의 연속 오디오를 전사할 수 있다는 점입니다. 이를 위해 오디오를 60초 단위의 세그먼트(24kHz 기준 1440000 샘플)로 분할하고, 각 세그먼트 사이에 컨볼루션 상태를 캐싱하는 방식으로 처리됩니다.

다만, 60초 분량의 청크가 사용자의 기기에 너무 크다면, generate에 전달되는 acoustic_tokenizer_chunk_size 인수를 조정할 수 있습니다. hop length(원본 acoustic tokenizer의 경우 3200)의 배수여야 한다는 점에 유의하세요.

from transformers import AutoProcessor, VibeVoiceAsrForConditionalGeneration


acoustic_tokenizer_chunk_size = 64000    # default is 1440000 (60s @ 24kHz)
model_id = "microsoft/VibeVoice-ASR-HF"
audio = [
    "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
    "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/example_output/VibeVoice-1.5B_output.wav"
]
prompts = ["About VibeVoice", None]

processor = AutoProcessor.from_pretrained(model_id)
model = VibeVoiceAsrForConditionalGeneration.from_pretrained(model_id, device_map="auto")
print(f"Model loaded on {model.device} with dtype {model.dtype}")

inputs = processor.apply_transcription_request(audio, prompt=prompts).to(model.device, model.dtype)
output_ids = model.generate(**inputs, acoustic_tokenizer_chunk_size=acoustic_tokenizer_chunk_size)
generated_ids = output_ids[:, inputs["input_ids"].shape[1] :]
transcription = processor.decode(generated_ids, return_format="transcription_only")
print(transcription)

채팅 템플릿

VibeVoice ASR는 채팅 템플릿 입력도 허용합니다(apply_transcription_request는 편의를 위해 apply_chat_template의 래퍼입니다):

from transformers import AutoProcessor, VibeVoiceAsrForConditionalGeneration


model_id = "microsoft/VibeVoice-ASR-HF"
processor = AutoProcessor.from_pretrained(model_id)
model = VibeVoiceAsrForConditionalGeneration.from_pretrained(model_id, device_map="auto")

chat_template = [
    [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "About VibeVoice"},
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
                },
            ],
        }
    ],
    [
        {
            "role": "user",
            "content": [
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/example_output/VibeVoice-1.5B_output.wav",
                },
            ],
        }
    ],
]

inputs = processor.apply_chat_template(
    chat_template,
    tokenize=True,
    return_dict=True,
).to(model.device, model.dtype)

output_ids = model.generate(**inputs)
generated_ids = output_ids[:, inputs["input_ids"].shape[1] :]
transcription = processor.decode(generated_ids, return_format="transcription_only")
print(transcription)

학습

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

from transformers import AutoProcessor, VibeVoiceAsrForConditionalGeneration


model_id = "microsoft/VibeVoice-ASR-HF"
processor = AutoProcessor.from_pretrained(model_id)
model = VibeVoiceAsrForConditionalGeneration.from_pretrained(model_id, device_map="auto")
model.train()

# Prepare batch of 2
# -- NOTE: the original model is trained to output transcription, speaker ID, and timestamps in JSON-like format. Below we are only using the transcription text as the label
chat_template = [
    [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "VibeVoice is this novel framework designed for generating expressive, long-form, multi-speaker, conversational audio."},
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
                },
            ],
        }
    ],
    [
        {
            "role": "user",
            "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",
                    "path": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/example_output/VibeVoice-1.5B_output.wav",
                },
            ],
        }
    ],
]
inputs = processor.apply_chat_template(
    chat_template,
    tokenize=True,
    return_dict=True,
    output_labels=True,
).to(model.device, model.dtype)

loss = model(**inputs).loss
print("Loss:", loss.item())
loss.backward()

Torch compile

모델은 더 빠른 추론/트레이닝을 위해 컴파일할 수 있습니다.

import time

import torch

from transformers import AutoProcessor, VibeVoiceAsrForConditionalGeneration


model_id = "microsoft/VibeVoice-ASR-HF"

num_warmup = 5
num_runs = 20

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

# Prepare static inputs
chat_template = [
    [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "VibeVoice is this novel framework designed for generating expressive, long-form, multi-speaker, conversational audio.",
                },
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
                },
            ],
        }
    ],
] * 4  # batch size 4
inputs = processor.apply_chat_template(
    chat_template,
    tokenize=True,
    return_dict=True,
).to(model.device, torch.bfloat16)

# Benchmark without compile
print("Warming up without compile...")
with torch.no_grad():
    for _ in range(num_warmup):
        _ = model(**inputs)

torch.accelerator.synchronize()

print("\nBenchmarking without torch.compile...")
torch.accelerator.synchronize()
start = time.time()
with torch.no_grad():
    for _ in range(num_runs):
        _ = model(**inputs)
torch.accelerator.synchronize()
no_compile_time = (time.time() - start) / num_runs
print(f"Average time without compile: {no_compile_time:.4f}s")

# Benchmark with compile
print("\nCompiling model...")
model = torch.compile(model)

print("Warming up with compile (includes graph capture)...")
with torch.no_grad():
    for _ in range(num_warmup):
        _ = model(**inputs)

torch.accelerator.synchronize()

print("\nBenchmarking with torch.compile...")
torch.accelerator.synchronize()
start = time.time()
with torch.no_grad():
    for _ in range(num_runs):
        _ = model(**inputs)
torch.accelerator.synchronize()
compile_time = (time.time() - start) / num_runs
print(f"Average time with compile: {compile_time:.4f}s")

speedup = no_compile_time / compile_time
print(f"\nSpeedup: {speedup:.2f}x")

Pipeline 사용

model은 파이프라인으로 사용할 수 있지만, 원시 출력을 파싱하는 메서드는 직접 정의해야 합니다.

from transformers import pipeline


model_id = "microsoft/VibeVoice-ASR-HF"
pipe = pipeline("any-to-any", model=model_id, device_map="auto")
chat_template = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "About VibeVoice"},
            {
                "type": "audio",
                "path": "https://huggingface.co/datasets/bezzam/vibevoice_samples/resolve/main/realtime_model/vibevoice_tts_german.wav",
            },
        ],
    }
]
outputs = pipe(text=chat_template, return_full_text=False)

print("\n" + "=" * 60)
print("RAW PIPELINE OUTPUT")
print("=" * 60)
print(outputs[0]["generated_text"])

print("\n" + "=" * 60)
print("DICT OUTPUT")
print("=" * 60)
dict_output = pipe.processor.extract_speaker_dict(outputs[0]["generated_text"])
print(dict_output)

print("\n" + "=" * 60)
print("TRANSCRIPT OUTPUT")
print("=" * 60)
transcription = pipe.processor.extract_transcription(outputs[0]["generated_text"])
print(transcription)

VibeVoiceAsrConfig

클래스 transformers.VibeVoiceAsrConfig

< >

( 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 = Noneacoustic_tokenizer_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonesemantic_tokenizer_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneaudio_token_id: int = 151648audio_bos_token_id: int = 151646audio_eos_token_id: int = 151647acoustic_tokenizer_chunk_size: int = 1440000 )

매개변수

  • acoustic_tokenizer_encoder_config (Union[VibeVoiceAcousticTokenizerConfig, dict], 선택) — 음성 토크나이저의 config 객체 또는 사전입니다. 이 토크나이저는 오디오에서 음향 특성을 추출합니다.
  • semantic_tokenizer_encoder_config (Union[VibeVoiceAcousticTokenizerConfig, dict], 선택) — semantic tokenizer의 config 객체 또는 사전입니다. 이 tokenizer는 오디오에서 의미론적 특징을 추출합니다.
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — 텍스트 백본의 config 객체 또는 사전입니다.
  • audio_token_id (int, 선택 사항, 기본값 151648) — 입력 오디오를 위한 플레이스홀더로 사용되는 오디오 토큰 인덱스입니다.
  • audio_bos_token_id (int, 선택 사항, 기본값 151646) — 오디오 시퀀스 시작 토큰 인덱스입니다.
  • audio_eos_token_id (int, 선택 사항, 기본값 151647) — 오디오 시퀀스 종료 토큰 인덱스입니다.
  • acoustic_tokenizer_chunk_size (int, 선택 사항, 기본값 1440000) — 오디오 입력을 토크나이징할 때 사용할 청크 크기(샘플 수). 기본값은 24kHz에서 60초에 해당합니다.

이것은 VibeVoiceAsrModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Vibevoice Asr 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 microsoft/VibeVoice-ASR-HF와 유사한 구성이 생성됩니다.

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> from transformers import VibeVoiceAsrForConditionalGeneration, VibeVoiceAsrConfig, VibeVoiceAcousticTokenizerEncoderConfig, Qwen2Config

>>> # Initializing VibeVoice acoustic and semantic encoder configs
>>> acoustic_config = VibeVoiceAcousticTokenizerEncoderConfig()
>>> semantic_config = VibeVoiceAcousticTokenizerEncoderConfig(hidden_size=128)

>>> # Initializing a Qwen2 config
>>> text_config = Qwen2Config()

>>> # Initializing a VibeVoice ASR configuration
>>> configuration = VibeVoiceAsrConfig(acoustic_config, semantic_config, text_config)

>>> # Initializing a model from the vibevoice_asr style configuration
>>> model = VibeVoiceAsrForConditionalGeneration(configuration)

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

VibeVoiceAsrProcessor

클래스 transformers.VibeVoiceAsrProcessor

< >

( feature_extractortokenizerchat_template = Noneaudio_token = '<|box_start|>'audio_bos_token = '<|object_ref_start|>'audio_eos_token = '<|object_ref_end|>'audio_duration_token = '<|AUDIO_DURATION|>' )

매개변수

  • feature_extractor (VibeVoiceAcousticTokenizerFeatureExtractor) — 오디오 처리를 위한 feature extractor입니다.
  • tokenizer (Qwen2TokenizerFast) — 텍스트 처리에 사용되는 토크나이저입니다.
  • chat_template (str, 선택 사항) — 채팅의 메시지 목록을 토큰화 가능한 문자열로 변환하는 데 사용되는 Jinja 템플릿입니다.
  • audio_token (str, 선택 사항, 기본값 "<|box_start|>") — 채팅 템플릿에서 사용할 오디오 토큰 플레이스홀더입니다.
  • audio_bos_token (str, 선택 사항, 기본값 "<|object_ref_start|>") — 채팅 템플릿에서 사용할 오디오 시퀀스 시작 토큰 플레이스홀더입니다.
  • audio_eos_token (str, 선택 사항, 기본값 "<|object_ref_end|>") — 채팅 템플릿에서 사용할 오디오 시퀀스 종료 토큰 플레이스홀더입니다.
  • audio_duration_token (str, 선택 사항, 기본값 "<|AUDIO_DURATION|>") — 채팅 템플릿에서 사용할 오디오 길이 토큰 플레이스홀더입니다.

VibeVoiceAcousticTokenizerFeatureExtractor와 Qwen2TokenizerFast를 단일 프로세서로 감싸서 오디오 특징 추출과 토크나이저 기능을 모두 상속하는 VibeVoice ASR 프로세서를 생성합니다.

자세한 내용은 call()을 참조하세요.

__call__

< >

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

매개변수

  • text (Union[str, list[str]]) — 인코딩할 시퀀스 또는 시퀀스 배치입니다. 각 시퀀스는 문자열 또는 문자열 목록(사전 토큰화된 문자열)일 수 있습니다. 사전 토큰화된 입력을 전달하는 경우, 배치 입력과의 모호성을 피하기 위해 is_split_into_words=True를 설정하세요.
  • audio (Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 선택 사항) — 준비할 오디오 또는 오디오 배치입니다. 각 오디오는 NumPy 배열 또는 PyTorch 텐서일 수 있습니다. NumPy 배열/PyTorch 텐서의 경우, 각 오디오의 shape은 (C, T)여야 하며, 여기서 C는 채널 수, T는 오디오의 샘플 길이입니다.
  • output_labels (bool, 선택, 기본값=False) — 학습용 라벨을 반환할지 여부.
  • return_tensors (str 또는 TensorType, 선택 사항) — 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:
    • 'pt': PyTorch torch.Tensor 객체를 반환합니다.
    • 'np': NumPy np.ndarray 객체를 반환합니다.
  • **kwargs (ProcessingKwargs, 선택) — 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인수의 전체 목록은 TypedDict 클래스를 참조하세요.

반환값

BatchFeature

토큰화된 텍스트(input_ids, attention_mask)와 오디오 특징(input_values, padding_mask)을 포함하는 사전입니다.

apply_transcription_request

< >

( audio: typing.Union[str, list[str], numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']]prompt: str | list[str] | None = Nonetokenize: bool = True**kwargs: *<class 'transformers.models.vibevoice_asr.processing_vibevoice_asr.VibeVoiceAsrProcessorKwargs'> ) → BatchFeature or list[str]

매개변수

  • audio (str, list[str], np.ndarray, torch.Tensor, list[np.ndarray], list[torch.Tensor]) — 전사할 오디오입니다. 문자열은 로컬 경로 또는 URL로 해석되며 chat template loader에 의해 자동으로 로드됩니다. NumPy 배열과 PyTorch 텐서는 그대로 전달됩니다.
  • prompt (str 또는 list[str], 선택 사항) — 사용자 턴에 추가 컨텍스트로 포함할 사용자 지정 프롬프트입니다. 리스트의 길이는 배치와 동일해야 합니다. None인 경우 추가 컨텍스트가 제공되지 않습니다.
  • tokenize (bool, 선택 사항, 기본값 True) — 프롬프트를 토큰화하고 오디오를 처리할지 여부입니다. False인 경우 오디오가 로드되지 않고, 오디오 플레이스홀더가 확장되지 않은 문자열로 프롬프트가 반환됩니다. 이 프롬프트를 오디오와 함께 프로세서에 전달하면 processor(text=prompts, audio=audio), tokenize=True일 때와 동일한 출력을 얻습니다.
  • **kwargs — text_kwargs, audio_kwargs 등) apply_chat_template()로 전달되는 추가 키워드 인자.

반환값

BatchFeature 또는 list[str]

tokenize=False인 경우 오디오 하나당 프롬프트가 하나씩 생성되며, 그렇지 않으면 VibeVoiceAsrForConditionalGeneration.generate()에 바로 전달할 수 있는 형태로 프로세서가 출력을 생성합니다.

수동으로 채팅 템플릿을 작성하지 않고도 자동 음성 인식(ASR)을 위한 입력을 준비합니다.

decode

< >

( *argsreturn_format = 'raw'**kwargs )

매개변수

  • return_format (str, 선택 사항, 기본값은 "raw") — 옵션은 다음과 같습니다: "raw": 파싱 없이 토크나이저에서 디코딩된 원시 문자열 목록을 반환합니다. "parsed": 각 화자의 발화에 대해 타임스탬프가 포함된 파싱된 딕셔너리 객체의 목록을 반환합니다. "transcription_only": 추출된 전사 문자열 목록을 반환합니다. "parsed"와 "transcription_only"의 경우 skip_special_tokens는 자동으로 True로 설정됩니다.
    • "raw": 파싱 없이 토크나이저에서 생성된 원시 디코딩 문자열 목록을 반환합니다.
    • "parsed": 각 화자의 발화에 대해 타임스탬프가 포함된 파싱된 딕셔너리 객체의 리스트로 된 리스트를 반환합니다.
    • "transcription_only": 추출된 전사 문자열 목록을 반환합니다.

    skip_special_tokens는 "parsed"와 "transcription_only"의 경우 자동으로 True로 고정됩니다.

인수를 decode()로 전달하고, 필요에 따라 dict 형식의 출력을 파싱합니다.

VibeVoice ASR는 사전과 유사한 형식으로 전사 결과를 출력합니다. 예:

[
    'assistant
":0.0,"End":7.56,"Speaker":0,"Content":"text"}]

    'assistant
":0,"End":5.20,"Speaker":0,"Content":"text"}]

]

VibeVoiceAsrModel

class transformers.VibeVoiceAsrModel

< >

( config: VibeVoiceAsrConfig )

매개변수

  • config (VibeVoiceAsrConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

VibeVoice ASR 모델(음성 토크나이저 + 의미 토크나이저 + 멀티모달 프로젝터 + 언어 모델)로, 언어 모델링 헤드가 없습니다.

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

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

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

매개변수

  • input_ids (torch.LongTensor 형상이 (batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • 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 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • 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를 사용해야 합니다. 자세한 내용은 VibeVoiceAsrProcessor.call()를 참조하세요.
  • padding_mask (torch.BoolTensor, shape (batch_size, sequence_length), 선택 사항) — 패딩된 feature 인덱스에 대한 연산을 수행하지 않도록 하는 마스크입니다.
  • sample (bool, 선택 사항, 기본값 True) — 원본 모델과 동일하게 음향 latents에 가우시안 노이즈를 추가할지 여부입니다 (σ-VAE: 노이즈 스케일은 배치 항목별로 N(0, vae_std)에서 추출됩니다). False인 경우 인코더 출력을 그대로 사용하므로 출력이 결정론적입니다.

반환값

VibeVoiceAsrModelOutputWithPast 또는 tuple(torch.Tensor)

VibeVoiceAsrModelOutputWithPast 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(VibeVoiceAsrConfig)과 입력에 따라 다양한 요소를 포함합니다.

VibeVoiceAsrModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 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 인스턴스입니다.

  • 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 가중치.

  • audio_hidden_states (torch.Tensor, 선택 사항) — 투영된 오디오 히든 상태입니다.

VibeVoiceAsrForConditionalGeneration

클래스 transformers.VibeVoiceAsrForConditionalGeneration

< >

( config: VibeVoiceAsrConfig )

매개변수

  • config (VibeVoiceAsrConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

사전 학습된 음향 토크나이저와 언어 모델을 갖춘 VibeVoice ASR 모델.

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

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneinput_values: typing.Optional[torch.Tensor] = Nonepadding_mask: typing.Optional[torch.BoolTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0sample: bool = True**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → VibeVoiceAsrCausalLMOutputWithPast or tuple(torch.Tensor)

매개변수

  • input_ids (torch.LongTensor 형상이 (batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • 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 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • 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를 사용해야 합니다. 자세한 내용은 VibeVoiceAsrProcessor.call()를 참조하세요.
  • padding_mask (torch.BoolTensor, shape (batch_size, sequence_length), 선택 사항) — 패딩된 feature 인덱스에 대한 연산을 수행하지 않도록 하는 마스크입니다.
  • labels (torch.LongTensor, shape (batch_size, sequence_length), 선택 사항) — 마스크 언어 모델링 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., config.vocab_size] 범위 내의 값이거나 -100이어야 합니다(input_ids docstring 참조). 인덱스가 -100으로 설정된 토큰은 무시(마스크)되며, 손실은 [0, ..., config.vocab_size] 범위의 라벨을 가진 토큰에 대해서만 계산됩니다.
  • logits_to_keep (Union[int, torch.Tensor], 선택 사항, 기본값 0) — int인 경우, 마지막 logits_to_keep 토큰에 대한 logits를 계산합니다. 0인 경우, 모든 input_ids에 대한 logits를 계산합니다(특수한 경우). 생성에는 마지막 토큰의 logits만 필요하며, 해당 토큰에 대해서만 계산하면 메모리를 절약할 수 있습니다. 이는 긴 시퀀스나 큰 어휘 크기의 경우 상당한 이점을 제공합니다. torch.Tensor인 경우, 시퀀스 길이 차원에서 유지할 인덱스에 해당하는 1차원 텐서여야 합니다. 이는 패킹된 텐서 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.
  • sample (bool, 선택 사항, 기본값 True) — 원본 모델과 동일하게 음향 latents에 가우시안 노이즈를 추가할지 여부입니다 (σ-VAE: 노이즈 스케일은 배치 항목별로 N(0, vae_std)에서 추출됩니다). False인 경우 인코더 출력을 그대로 사용하므로 출력이 결정론적입니다.

반환값

VibeVoiceAsrCausalLMOutputWithPast 또는 tuple(torch.Tensor)

VibeVoiceAsrCausalLMOutputWithPast 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(VibeVoiceAsrConfig)과 입력에 따라 다양한 요소를 포함합니다.

VibeVoiceAsrForConditionalGeneration의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.Tensor, shape (1,), 선택 사항, labels이 제공될 때 반환됨) — 언어 모델링 손실.

  • logits (torch.Tensor, shape (batch_size, sequence_length, config.vocab_size)) — 예측 점수.

  • past_key_values (Cache, 선택 사항) — Cache 인스턴스.

  • 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 가중치.

  • audio_hidden_states (torch.Tensor, 선택 사항) — 투영된 오디오 히든 상태입니다.

예:

>>> from transformers import VibeVoiceAsrForConditionalGeneration, AutoProcessor

>>> model_id = "microsoft/VibeVoice-ASR-HF"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = VibeVoiceAsrForConditionalGeneration.from_pretrained(model_id, dtype="auto", device_map="auto")

get_audio_features

< >

( *args**kwargs )

Update on GitHub