Transformers documentation

Nemotron 3 화자 분리

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

and get access to the augmented documentation experience

to get started

이 모델은 2026-09-23에 Hugging Face Transformers에 기여되었습니다.

Nemotron 3 화자 분리

개요

Nemotron 3 Diarization은 실제 오디오에서 “누가 언제 말했는지”를 판별하도록 설계된 오픈 웨이트 스트리밍 화자 분리 모델입니다. 스트리밍 및 오프라인 추론을 모두 지원하며, 최대 8명의 화자를 처리하고 입력 오디오에서 각 화자가 처음 등장한 순서대로 화자 출력을 정렬합니다.

모델은 Streaming Sortformer 1, 2에 도입된 Arrival-Order Speaker Cache(AOSC) 1와 FIFO 큐를 사용합니다. 단일 체크포인트는 80 ms 입력 버퍼부터 30.4 s 오프라인 스타일 버퍼까지 다양한 지연 시간 프로필을 지원하며, 10 ms의 배수로 출력 프레임 해상도를 설정할 수 있습니다. 청크 기반 추론을 사용하면 최대 오디오 길이에 제한이 없습니다.

사용

오프라인

import torch
from transformers import AutoModelForAudioFrameClassification, AutoProcessor
from transformers.audio_utils import load_audio

model_id = "nvidia/Nemotron-3-Diarization"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForAudioFrameClassification.from_pretrained(model_id, device_map="auto")

sampling_rate = processor.feature_extractor.sampling_rate
audio = load_audio(
    "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/diarization_example.mp3",
    sampling_rate=sampling_rate,
)
inputs = processor(audio, sampling_rate=sampling_rate).to(model.device, dtype=model.dtype)

with torch.inference_mode():
    logits = model(**inputs).logits  # (1, num_frames, 8), one frame every 10 ms

segments = processor.extract_speaker_dict(logits, inputs.attention_mask)[0]
for segment in segments:
    print(f"speaker_{segment['Speaker']}: {segment['Start']:.2f}s - {segment['End']:.2f}s")

스트리밍

Audio는 청크 단위로 도착하며, 각 forward는 하나의 청크를 처리합니다. 프로세서가 streaming_mode에 따라 청크를 잘라내고, 다음 청크를 여는 역할을 하므로 점수화되지 않는 후방 look-ahead 프레임 수인 num_lookahead_frames을 추가합니다. forward는 다음 호출에 전달하기 위해 speaker_cache를 반환합니다. 세션의 마지막 청크는 is_last_audio_chunk=True로 추출됩니다. look-ahead가 없으므로 나머지 모든 프레임이 점수화됩니다.

streaming_mode지연 시간¹
"low_latency" (기본값)1.04 s
"very_low_latency"0.64 s
"ultra_low_latency"0.32 s

¹ 모델이 청크를 실행하기 전에 대기해야 하는 오디오: 계산 시간을 제외한 청크와 그 look-ahead.

import torch
from transformers import AutoModelForAudioFrameClassification, AutoProcessor
from transformers.audio_utils import load_audio

model_id = "nvidia/Nemotron-3-Diarization"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForAudioFrameClassification.from_pretrained(model_id, device_map="auto")
processor.set_streaming_mode("low_latency")  # the default, can also be "very_low_latency" and "ultra_low_latency"
print(f"Streaming latency: {processor.streaming_latency_ms} ms")

sampling_rate = processor.feature_extractor.sampling_rate
audio = load_audio(
    "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/diarization_example.mp3",
    sampling_rate=sampling_rate,
)


def inputs_generator():
    """Yields the processor outputs of each chunk."""
    yield processor(
        audio[: processor.num_samples_first_audio_chunk],
        sampling_rate=sampling_rate,
        is_streaming=True,
        is_first_audio_chunk=True,
    )

    mel_frame_idx = processor.num_mel_frames_per_step
    start_idx = processor.audio_chunk_start(mel_frame_idx)
    while (end_idx := start_idx + processor.num_samples_per_audio_chunk) <= audio.shape[0]:
        yield processor(
            audio[start_idx:end_idx],
            sampling_rate=sampling_rate,
            is_streaming=True,
            is_first_audio_chunk=False,
        )
        mel_frame_idx += processor.num_mel_frames_per_step
        start_idx = processor.audio_chunk_start(mel_frame_idx)

    # the audio ended: the frames left in the buffer are the last ones of the session
    yield processor(
        audio[start_idx:],
        sampling_rate=sampling_rate,
        is_streaming=True,
        is_first_audio_chunk=False,
        is_last_audio_chunk=True,
    )


speaker_cache, logits = None, []
with torch.inference_mode():
    for inputs in inputs_generator():
        inputs = inputs.to(model.device, dtype=model.dtype)
        # `inputs` carries `num_lookahead_frames` for every chunk but the last, `speaker_cache` links the chunks
        outputs = model(**inputs, speaker_cache=speaker_cache)
        logits.append(outputs.logits)  # the chunk's frames, without its look-ahead
        speaker_cache = outputs.speaker_cache

logits = torch.cat(logits, dim=1)  # (1, num_frames, 8), one frame every 10 ms
segments = processor.extract_speaker_dict(logits)[0]  # [{"Start": 0.0, "End": 15.43, "Speaker": 0}, ...]

성능 극대화

스트리밍 단계의 인코더 입력은 [speaker cache | FIFO | chunk]이며, 캐시와 FIFO가 채워지고 줄어드는 동안 길이가 변합니다: torch.compile은 세션당 약 100회 정도 재컴파일됩니다. 모든 단계에서 해당 모드의 최대 윈도우로 패딩하면 형태가 고정됩니다. 각 청크마다 위치가 0으로 재시작되므로, 오른쪽 패딩은 유효한 프레임에 영향을 주지 않습니다:

import torch.nn.functional as F

chunk_length, chunk_right_context = processor.streaming_modes[processor.streaming_mode]
max_window = (
    model.config.streaming_config.speaker_cache_length
    + model.config.streaming_config.fifo_length
    + chunk_length
    + chunk_right_context
)
encoder = model.model
compiled_forward = torch.compile(encoder.forward, mode="reduce-overhead", fullgraph=True, dynamic=False)


def padded_forward(inputs_embeds, attention_mask=None, position_ids=None, **kwargs):
    batch_size, num_frames, _ = inputs_embeds.shape
    if attention_mask is None:
        attention_mask = inputs_embeds.new_ones(batch_size, num_frames, dtype=torch.bool)
    padding = max_window - num_frames
    hidden_states = compiled_forward(
        inputs_embeds=F.pad(inputs_embeds, (0, 0, 0, padding)),
        attention_mask=F.pad(attention_mask.bool(), (0, padding), value=False),
        position_ids=torch.arange(max_window, device=inputs_embeds.device)[None, :],
        **kwargs,
    )
    return hidden_states[:, :num_frames].clone()  # CUDA graphs reuse the output buffer


encoder.forward = padded_forward

# warm up before the session: compiles, then records the CUDA graph, so the first real chunk runs at full speed
with torch.inference_mode():
    for _ in range(3):
        hidden_size = model.config.audio_config.hidden_size
        padded_forward(torch.zeros(1, max_window, hidden_size, device=model.device, dtype=model.dtype))

위의 스트리밍 루프는 한 번만 컴파일됩니다. 오프라인 forward도 동일한 방식으로 청크를 나누므로, max_window에 config.fifo_length, config.chunk_left_context, config.chunk_length, config.chunk_right_context를 사용하여 동일한 래퍼를 적용할 수 있습니다.

Eager 대비 속도 향상 (A100, 배치 크기 1)float32bfloat16
스트리밍, 단계별1.2x4.4x
오프라인, 488초 녹음1.3x2.8x

Nemotron3DiarizationConfig

class transformers.Nemotron3DiarizationConfig

< >

( 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 = Noneaudio_config: transformers.models.nemotron3_diarization.configuration_nemotron3_diarization.Nemotron3DiarizationAudioConfig | dict | None = Nonehead_config: transformers.models.nemotron3_diarization.configuration_nemotron3_diarization.Nemotron3DiarizationHeadConfig | dict | None = Nonestreaming_config: transformers.models.nemotron3_diarization.configuration_nemotron3_diarization.Nemotron3DiarizationStreamingConfig | dict | None = Nonechunk_length: int = 340chunk_right_context: int = 40chunk_left_context: int = 0fifo_length: int = 40speaker_cache_update_period: int = 300initializer_range: float = 0.02 )

매개변수

  • audio_config (Nemotron3DiarizationAudioConfig 또는 dict, 선택) — transformer 오디오 인코더의 설정입니다. 기본값은 Nemotron3DiarizationAudioConfig()입니다.
  • head_config (Nemotron3DiarizationHeadConfig 또는 dict, 선택) — 스피커 헤드 구성입니다. 기본값은 Nemotron3DiarizationHeadConfig()입니다.
  • streaming_config (Nemotron3DiarizationStreamingConfig 또는 dict, 선택) — 스피커 캐시 정책 및 스트리밍 모드의 FIFO 크기입니다. 기본값은 Nemotron3DiarizationStreamingConfig()입니다.
  • chunk_length (int, 선택 사항, 기본값 340) — 오프라인 모드: 전체 녹음 파일을 한 번의 forward로 화자 분리할 때 chunk당 인코더 프레임 수입니다. 스트리밍 모드에서는 chunk가 각 forward의 입력이 됩니다.
  • chunk_right_context (int, 선택 사항, 기본값 40) — 오프라인 모드: 각 청크가 후속 청크에서 가져오는 look-ahead 인코더 프레임 수. 스트리밍 모드에서는 look-ahead가 각 forward의 num_lookahead_frames입니다.
  • chunk_left_context (int, 선택 사항, 기본값 0) — 오프라인 모드: 각 청크가 이전 청크들로부터 다시 가져오는 look-back 인코더 프레임 수입니다. 이 프레임들은 캐시된 프레임과 청크 사이에 삽입됩니다. look-ahead와 마찬가지로 attention 대상이 되지만 점수를 매기지도 FIFO 큐에 push하지도 않습니다. 스트리밍 모드에서는 look-back은 각 forward의 num_lookback_frames입니다.
  • fifo_length (int, 선택 사항, 기본값 40) — 오프라인 모드: 최근 인코더 프레임의 FIFO 큐 용량. 스트리밍 모드에서는 streaming_config.fifo_length를 사용합니다.
  • speaker_cache_update_period (int, 선택 사항, 기본값 300) — 오프라인 모드: 큐가 오버플로될 때 FIFO 큐에서 스피커 캐시로 이동되는 인코더 프레임 수. 스트리밍 모드에서는 streaming_config.speaker_cache_update_period를 사용합니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

이것은 Nemotron3DiarizationModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Nemotron3 Diarization 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 nvidia/Nemotron-3-Diarization의 설정과 유사한 설정이 생성됩니다.

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

Nemotron3DiarizationAudioConfig

클래스 transformers.Nemotron3DiarizationAudioConfig

< >

( 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 = Nonehidden_size: int = 512intermediate_size: int = 2048num_hidden_layers: int = 31num_attention_heads: int = 8num_key_value_heads: int | None = Nonehidden_act: str = 'gelu'max_position_embeddings: int = 5000initializer_range: float = 0.02rope_parameters: dict | None = Noneattention_dropout: float | int = 0.0num_mel_bins: int = 128subsampling_factor: int = 8 )

매개변수

  • hidden_size (int, 선택 사항, 기본값 512) — 숨겨진 표현의 차원입니다.
  • intermediate_size (int, 선택 사항, 기본값 2048) — MLP 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 31) — Transformer decoder의 숨겨진 레이어 수입니다.
  • num_attention_heads (int, 선택 사항, 기본값 8) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • num_key_value_heads (int, 선택 사항) — 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, 선택 사항, 기본값 gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • max_position_embeddings (int, 선택 사항, 기본값 5000) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • rope_parameters (dict, 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는 rope_theta 값이 포함되어야 하며, 더 긴 max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • num_mel_bins (int, 선택 사항, 기본값 128) — 입력 프레임당 사용되는 mel 특징의 수입니다. AutoFeatureExtractor 클래스에서 사용된 값과 일치해야 합니다.
  • subsampling_factor (int, 선택 사항, 기본값 8) — 하나의 encoder frame에 스택되는 연속 spectrogram frame의 수입니다. 분류기는 동일한 배율로 출력을 업샘플링하므로, 화자 활동은 spectrogram frame rate에서 예측됩니다.

이것은 Nemotron3DiarizationModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Nemotron3 Diarization 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 nvidia/Nemotron-3-Diarization의 설정과 유사한 설정이 생성됩니다.

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

Nemotron3DiarizationHeadConfig

클래스 transformers.Nemotron3DiarizationHeadConfig

< >

( 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 = Nonehidden_size: int = 192num_speakers: int = 8audio_hidden_size: int = 512subsampling_factor: int = 8 )

매개변수

  • hidden_size (int, 선택 사항, 기본값 192) — 스피커 헤드의 hidden size입니다. 인코더 출력이 이 크기로 투영되며, 업샘플러와 분류기가 이 크기를 유지합니다.
  • num_speakers (int, 선택 사항, 기본값 8) — 최대 화자 수, 즉 프레임별 활동 출력의 수입니다. 화자는 오디오에서 처음 등장한 순서대로 정렬됩니다.
  • audio_hidden_size (int, 선택 사항, 기본값 512) — 헤드가 투영하는 인코더 출력의 hidden size입니다. Nemotron3DiarizationAudioConfig.hidden_size와 일치해야 합니다.
  • subsampling_factor (int, 선택 사항, 기본값 8) — 헤드의 업샘플링 계수로, 스펙트로그램 프레임 레이트로 되돌리는 데 사용됩니다. Nemotron3DiarizationAudioConfig.subsampling_factor와 일치해야 합니다.

이것은 Nemotron3DiarizationModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Nemotron3 Diarization 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 nvidia/Nemotron-3-Diarization의 설정과 유사한 설정이 생성됩니다.

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

Nemotron3DiarizationStreamingConfig

class transformers.Nemotron3DiarizationStreamingConfig

< >

( 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 = Nonefifo_length: int = 264speaker_cache_update_period: int = 222speaker_cache_length: int = 264speaker_cache_silence_frames_per_speaker: int = 1prediction_score_threshold: float = 0.25latest_frames_score_boost: float = 0.05strong_boost_rate: float = 0.75weak_boost_rate: float = 1.5min_positive_scores_rate: float = 0.5num_speakers: int = 8subsampling_factor: int = 8 )

매개변수

  • fifo_length (int, 선택, 기본값 264) — 스트리밍 모드에서 최근 인코더 프레임의 FIFO 큐 용량입니다(오프라인 모드에서는 Nemotron3DiarizationConfig.fifo_length를 사용합니다).
  • speaker_cache_update_period (int, 선택 사항, 기본값 222) — 스트리밍 모드에서 큐가 오버플로우될 때 FIFO 큐에서 스피커 캐시로 이동되는 인코더 프레임 수입니다(오프라인 모드에서는 Nemotron3DiarizationConfig.speaker_cache_update_period를 사용합니다).
  • speaker_cache_length (int, 선택 사항, 기본값 264) — Arrival-Order Speaker Cache의 용량입니다. 반드시 (1 + speaker_cache_silence_frames_per_speaker) * num_speakers 이상이어야 합니다.
  • speaker_cache_silence_frames_per_speaker (int, 선택 사항, 기본값 1) — 캐시가 압축될 때 학습된 무음 임베딩을 위해 스피커당 예약되는 스피커 캐시 슬롯 수입니다.
  • prediction_score_threshold (float, 선택 사항, 기본값 0.25) — speaker-cache 프레임 점수에서 로그를 취하기 전에 화자 확률에 적용되는 하한 값입니다.
  • latest_frames_score_boost (float, 선택, 기본값 0.05) — 스피커 캐시가 압축될 때 새로 추가된 프레임에 부여되는 점수 보너스입니다.
  • strong_boost_rate (float, 선택, 기본값 0.75) — 화자별 캐시 예산 중 최상위 프레임에 강한 점수 보상을 적용하는 비율입니다. 이를 통해 모든 화자가 캐시에 해당 비율만큼의 프레임을 최소한으로 유지하도록 합니다.
  • weak_boost_rate (float, 선택 사항, 기본값 1.5) — 화자별 캐시 예산 중 최상위 프레임에 약한 점수 보강을 적용하는 비율입니다. 이를 통해 특정 화자가 캐시를 독점하는 것을 방지합니다.
  • min_positive_scores_rate (float, 선택, 기본값 0.5) — 스피커별 캐시 예산의 비율: 해당 비율 이상의 양의 점수를 받은 프레임을 가진 스피커의 경우, 양의 점수를 받지 않은(중첩된 음성) 프레임은 캐시에서 제외됩니다.
  • num_speakers (int, 선택 사항, 기본값 8) — 스피커 캐시가 추적하는 스피커 수입니다. Nemotron3DiarizationHeadConfig.num_speakers와 일치해야 합니다.
  • subsampling_factor (int, 선택 사항, 기본값 8) — 인코더 프레임당 화자 확률 프레임 수입니다. Nemotron3DiarizationAudioConfig.subsampling_factor와 일치해야 합니다.

이것은 Nemotron3DiarizationModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Nemotron3 Diarization 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 nvidia/Nemotron-3-Diarization의 설정과 유사한 설정이 생성됩니다.

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

Nemotron3DiarizationAudioModel

class transformers.Nemotron3DiarizationAudioModel

< >

( config: Nemotron3DiarizationAudioConfig )

매개변수

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

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 기본 Nemotron3 Diarization Model

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

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

forward

< >

( input_features: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutput or tuple(torch.Tensor)

매개변수

  • input_features (torch.Tensor, shape (batch_size, sequence_length, feature_dim), 선택 사항) — 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 NemotronAsrStreamingFeatureExtractor를 사용하여 얻을 수 있습니다. 자세한 내용은 NemotronAsrStreamingFeatureExtractor.__call__()를 참조하세요 (Nemotron3DiarizationProcessor는 오디오 처리에 NemotronAsrStreamingFeatureExtractor를 사용합니다).
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

BaseModelOutput 또는 tuple(torch.Tensor)

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

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

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

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

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

Nemotron3DiarizationModel

class transformers.Nemotron3DiarizationModel

< >

( config: Nemotron3DiarizationConfig )

매개변수

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

스피커 분류기가 없는 Nemotron3Diarization 모델: 하나의 청크(캐시된 프레임 포함)를 인코딩한 후, 인코더 프레임을 스펙트로그램 프레임 레이트로 업샘플링합니다. 스트리밍 상태를 유지하지 않으며, 청크 단위 포워드 관련 내용은 Nemotron3DiarizationForAudioFrameClassification를 참조하세요.

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

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

forward

< >

( input_features: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutput or tuple(torch.Tensor)

매개변수

  • input_features (torch.Tensor, shape (batch_size, sequence_length, feature_dim), 선택 사항) — 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 NemotronAsrStreamingFeatureExtractor를 사용하여 얻을 수 있습니다. 자세한 내용은 NemotronAsrStreamingFeatureExtractor.__call__()를 참조하세요 (Nemotron3DiarizationProcessor는 오디오 처리에 NemotronAsrStreamingFeatureExtractor를 사용합니다).
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

BaseModelOutput 또는 tuple(torch.Tensor)

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

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

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

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

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

Nemotron3DiarizationProcessor

class transformers.Nemotron3DiarizationProcessor

< >

( feature_extractorsubsampling_factor = 8streaming_modes = Nonestreaming_mode = 'low_latency' )

매개변수

  • feature_extractor (NemotronAsrStreamingFeatureExtractor) — 피처 추출기는 필수 입력입니다.
  • subsampling_factor (int, 선택 사항, 기본값 8) — Nemotron3DiarizationAudioConfig.subsampling_factor와 동일하게, 인코더 프레임당 mel 프레임 수를 나타냅니다.
  • streaming_modes (dict[str, tuple[int, int]], 선택) — 체크포인트가 지원하는 스트리밍 모드로, 인코더 프레임 기준 이름별 (chunk_length, chunk_right_context)입니다. 이 집합의 단일 진실 공급원(single source of truth)은 프로세서이며, set_streaming_mode()가 이를 기준으로 검증합니다. 기본값은 모델 카드의 모드인 "low_latency" (9, 4), "very_low_latency" (6, 2), "ultra_low_latency" (3, 1)입니다.
  • streaming_mode (str, 선택 사항, 기본값 "low_latency") — 세션의 스트리밍 모드로, streaming_modes 중 하나입니다. set_streaming_mode()로 변경할 수 있습니다. 오프라인 사용 시에는 무시됩니다.

Nemotron3DiarizationProcessor를 생성하여 feature extractor를 단일 processor로 래핑합니다.

Nemotron3DiarizationProcessor는 NemotronAsrStreamingFeatureExtractor의 모든 기능을 제공합니다. 자세한 내용은 ~NemotronAsrStreamingFeatureExtractor를 참고하세요.

__call__

< >

( audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']]sampling_rate: int | None = Noneis_streaming: bool = Falseis_first_audio_chunk: bool = Trueis_last_audio_chunk: bool = False**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> ) → BatchFeature

매개변수

  • 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는 오디오의 샘플 길이입니다.
  • sampling_rate (int, 선택 사항) — 입력 오디오의 Hz 단위 샘플링 레이트입니다. 값이 제공되면 feature extractor가 기대하는 샘플링 레이트(16000 Hz)와 대조하여 검증됩니다.
  • is_streaming (bool, 선택 사항, 기본값 False) — 오디오가 스트리밍 세션의 한 청크인지 여부입니다. is_first_audio_chunk와 is_last_audio_chunk를 통해 첫 번째 청크와 마지막 청크를 나머지 청크와 구분합니다. 청크 크기는 streaming_mode의 값이며, set_streaming_mode()로 변경할 수 있습니다. 마지막 청크를 제외한 모든 청크는 첫 번째 청크의 경우 정확히 num_samples_first_audio_chunk개의 오디오 샘플을, 이후 청크의 경우 num_samples_per_audio_chunk개의 오디오 샘플을 포함해야 합니다.
  • is_first_audio_chunk (bool, 선택 사항, 기본값 True) — 스트리밍 세션의 첫 번째 청크인지 여부입니다. 피처 추출기는 첫 번째 청크와 오프라인 사용 시 분석 윈도우를 중앙 정렬(center=True)하고, 이후 청크에는 중앙 정렬하지 않습니다(center=False). 이를 통해 청크별 스펙트로그램이 프레임 단위로 단일 전체 발화 패스와 동일하게 재현됩니다. is_streaming=False인 경우 True여야 합니다.
  • is_last_audio_chunk (bool, 선택, 기본값 False) — 이 청크가 스트리밍 세션을 종료하는지 여부입니다. 세션의 청크는 chunk_right_context만큼의 look-ahead 인코더 프레임으로 끝나며, 이 프레임은 다음 단계에서만 모델이 점수를 매기고, 다음 청크가 이 프레임으로 시작합니다. 마지막 청크에는 다음 단계가 없으므로 프레임 개수와 무관하게 모든 프레임에 점수가 매겨지며, 전체 발화 패스가 오디오 끝을 패딩하는 방식과 동일하게 끝이 0으로 패딩되어 발화의 마지막 프레임이 생성됩니다. is_streaming=False인 경우 False여야 합니다.
  • return_mm_token_type_ids (bool, kwargs) — 멀티모달 플레이스홀더 토큰의 위치를 나타내는 멀티모달 토큰 타입 ID를 반환할지 여부입니다.
  • return_text_replacement_offsets (bool, kwargs) — 각 멀티모달 플레이스홀더와 그 대체 문자열의 문자 오프셋을 반환할지 여부입니다.
  • return_tensors (str 또는 TensorType, 선택 사항) — 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:
    • 'pt': PyTorch torch.Tensor 객체를 반환합니다.
    • 'np': NumPy np.ndarray 객체를 반환합니다.
  • **kwargs (ProcessingKwargs, 선택) — 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인수의 전체 목록은 TypedDict 클래스를 참조하세요.

반환값

BatchFeature

feature extractor의 출력인 input_features와 attention_mask입니다. 스트리밍 모드에서는 마지막 청이 아닌 청의 분석 윈도우가 그 청을 넘어가는 경우, 해당 청의 뒤쪽 프레임이 제거되므로 input_features에는 해당 청의 프레임만 정확히 포함됩니다. 따라서 이를 그대로 모델에 전달할 수 있습니다. 또한 마지막 청을 제외한 모든 청에는 num_lookahead_frames가 포함되며, 이는 해당 청의 뒤쪽 look-ahead 인코더 프레임 수를 나타내며 모델이 스트리밍 모드로 동작하도록 합니다.

Nemotron3DiarizationSpeakerCache

class transformers.Nemotron3DiarizationSpeakerCache

< >

( config: Nemotron3DiarizationStreamingConfigfifo_length: int | None = Nonespeaker_cache_update_period: int | None = None )

매개변수

  • config (Nemotron3DiarizationStreamingConfig) — 스피커 캐시 정책 및 스트리밍 모드의 FIFO 크기입니다.
  • fifo_length (int, 선택 사항) — 최근 인코더 프레임의 FIFO 큐 용량입니다. 기본값은 config.fifo_length입니다.
  • speaker_cache_update_period (int, 선택 사항) — 큐가 오버플로될 때 FIFO 큐에서 스피커 캐시로 이동되는 인코더 프레임 수입니다. 기본값은 config.speaker_cache_update_period입니다.

Nemotron3DiarizationForAudioFrameClassification의 스트리밍 상태: 도착 순서 스피커 캐시(Arrival-Order Speaker Cache)와 각 청크가 주의를 기울이는 가장 최근 인코더 프레임의 FIFO 큐입니다.

업데이트

< >

( chunk_input_embeds: Tensorchunk_logits: Tensorsilence_embeds: Tensornum_chunk_frames: intmask: typing.Optional[torch.Tensor] = Nonenum_lookback_frames: int = 0 )

매개변수

  • chunk_input_embeds (torch.Tensor, shape (batch_size, num_input_frames, hidden_size)) — 해당 단계의 인코더 입력: get_embeds가 반환한 캐시된 프레임, look-back 프레임, 해당 chunk 및 그 look-ahead입니다.
  • chunk_logits (torch.Tensor, shape (batch_size, num_input_frames * subsampling_factor, num_speakers)) — 스피커 캐시가 압축될 때 프레임을 점수화하는 데 사용되는 해당 스텝의 스피커 logits입니다.
  • silence_embeds (torch.Tensor, shape (hidden_size,)) — 압축된 캐시의 예약된 silence 슬롯을 채우는 학습된 silence 임베딩입니다.
  • num_chunk_frames (int) — chunk_input_embeds에서 캐시된 프레임과 look-back 프레임 뒤에 오는 chunk 프레임의 수입니다. FIFO 큐에 추가되는 것은 이 프레임들뿐이며, 그 뒤에 있는 look-ahead 프레임은 다음 단계에서 다시 입력됩니다.
  • mask (torch.Tensor, shape (batch_size, num_input_frames), 선택 사항) — chunk_input_embeds의 유효 프레임을 나타내며, 패딩 프레임에는 0의 화자 확률이 부여됩니다.
  • num_lookback_frames (int, 선택 사항, 기본값 0) — chunk_input_embeds의 캐시된 프레임과 청크 사이의 look-back 프레임 수: 이전 청크의 프레임이 다시 공급되며, 이미 함께 push된 상태입니다.

FIFO 큐에 처리된 청크를 푸시하며, 큐가 오버플로우되면 가장 오래된 프레임을 스피커 캐시로 이동합니다.

Nemotron3DiarizationOutput

class transformers.Nemotron3DiarizationOutput

< >

( logits: typing.Optional[torch.Tensor] = Nonehidden_states: tuple[torch.Tensor, ...] | None = Noneattentions: tuple[torch.Tensor, ...] | None = Nonespeaker_cache: transformers.models.nemotron3_diarization.modeling_nemotron3_diarization.Nemotron3DiarizationSpeakerCache | None = None )

매개변수

  • logits (torch.Tensor, shape (batch_size, num_frames, config.head_config.num_speakers)) — 스펙트로그램 프레임 단위의 화자 활동 logits입니다. logits.sigmoid()을 적용하면 각 프레임에서 각 화자가 활동할 확률을 얻을 수 있으며, 화자는 오디오에서 처음 등장한 순서대로 정렬됩니다.
  • hidden_states (tuple[torch.Tensor, ...], 선택 사항, output_hidden_states=True일 때 반환됨) — 각 청크의 인코더 hidden states를 청크 순서대로 포함합니다. 인코더는 청크마다 한 번씩 실행되므로, 이 tuple에는 청크당 config.audio_config.num_hidden_layers + 1개의 텐서가 포함됩니다. 시퀀스 길이는 해당 청크의 길이이며, cache 와 look-ahead 프레임을 포함합니다.
  • attentions (tuple[torch.Tensor, ...], 선택 사항, output_attentions=True일 때 반환됨) — 각 청크의 인코더 어텐션 가중치입니다. 청크 순서대로, 청크당 config.audio_config.num_hidden_layers개의 텐서로 구성됩니다.
  • speaker_cache (Nemotron3DiarizationSpeakerCache, 선택, 스트리밍 모드에서 반환됨) — 같은 스트림의 다음 오디오 청크의 forward에 전달할 업데이트된 스트리밍 상태입니다.

Nemotron3DiarizationForAudioFrameClassification의 출력입니다.

Nemotron3DiarizationForAudioFrameClassification

class transformers.Nemotron3DiarizationForAudioFrameClassification

< >

( config: Nemotron3DiarizationConfig )

매개변수

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

Streaming Sortformer 화자 분리 모델: 각 스펙트로그램 프레임에 대해 최초 도착 순서로 정렬된 최대 config.head_config.num_speakers명의 화자 활동을 예측합니다. 오디오는 청크 단위로 처리되며, 각 청크는 일부 look-ahead 프레임과 Nemotron3DiarizationSpeakerCache에 유지되는 Arrival-Order Speaker Cache 및 FIFO 큐에 주의를 기울입니다. 전체 녹음은 forward 자체에 의해 청크로 분할됩니다(오프라인 모드). 스트림은 forward당 하나의 청크가 공급됩니다(스트리밍 모드).

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

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

forward

< >

( input_features: Tensorattention_mask: typing.Optional[torch.Tensor] = Nonespeaker_cache: transformers.models.nemotron3_diarization.modeling_nemotron3_diarization.Nemotron3DiarizationSpeakerCache | None = Nonenum_lookahead_frames: int | None = Nonenum_lookback_frames: int | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Nemotron3DiarizationOutput or tuple(torch.Tensor)

매개변수

  • input_features (torch.Tensor, shape (batch_size, sequence_length, feature_dim)) — 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 NemotronAsrStreamingFeatureExtractor를 사용하여 얻을 수 있습니다. 자세한 내용은 NemotronAsrStreamingFeatureExtractor.__call__()를 참조하세요 (Nemotron3DiarizationProcessor는 오디오 처리에 NemotronAsrStreamingFeatureExtractor를 사용합니다).
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • speaker_cache (Nemotron3DiarizationSpeakerCache, 선택 사항) — 같은 오디오 스트림의 이전 청크 forward에서 반환된 스트리밍 상태입니다.
  • num_lookahead_frames (int, 선택 사항) — 스트리밍 모드: 입력의 후행 인코더 프레임 중 lookahead 전용으로 사용되는 프레임 수입니다. 이 프레임들은 attention 대상이 되지만, 해당 logits는 반환되지 않으며 다음 chunk를 열기 때문에 FIFO 큐에 추가되지 않습니다. Nemotron3DiarizationProcessor 세션의 마지막 chunk를 제외한 모든 chunk에 대해 이 값을 설정합니다.

    이러한 인자와 num_lookback_frames이 모드를 선택합니다. 스트리밍 모드, 포워드당 1개 청크: num_lookahead_frames 또는 num_lookback_frames가 지정된 경우(첫 번째 청크가 speaker_cache를 생성하고, 이후 청크는 이를 수신) 또는 speaker_cache만 지정된 경우(세션의 마지막 청크, 룩어헤드 없음). 입력에서 룩백 및 룩어헤드 프레임을 제외한 부분이 하나의 청크가 되며, 길이에 관계없이 config.streaming_config로 크기가 지정된 FIFO 큐에 전체로 푸시됩니다. 오프라인 모드, 둘 다 지정되지 않은 경우: 입력은 전체 녹음 파일이며, 포워드가 config.chunk_length 인코더 프레임의 청크로 분할합니다. 각 청크는 이전 청크에서 최대 config.chunk_left_context 룩백 프레임과 이후 청크에서 최대 config.chunk_right_context 룩어헤드 프레임을 사용하며, config.fifo_length로 크기가 지정된 FIFO 큐를 사용합니다. 캐시는 반환되지 않습니다.

  • num_lookback_frames (int, 선택) — 스트리밍 모드: 입력의 앞부분 인코더 프레임 중, speaker_cache의 프레임 위에 이 청크의 앞에 다시 공급되는 이전 청크의 끝 부분으로만 사용되는 룩백 프레임의 수입니다. 이 프레임들은 어텐션 대상이 되지만, 그 로짓은 반환되지 않고 FIFO 큐에도 다시 추가되지 않습니다. 기본값은 0입니다.

반환값

Nemotron3DiarizationOutput 또는 tuple(torch.Tensor)

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

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

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

  • logits (torch.Tensor, shape (batch_size, num_frames, config.head_config.num_speakers)) — 스펙트로그램 프레임 단위의 화자 활동 logits입니다. logits.sigmoid()을 적용하면 각 프레임에서 각 화자가 활동할 확률을 얻을 수 있으며, 화자는 오디오에서 처음 등장한 순서대로 정렬됩니다.
  • hidden_states (tuple[torch.Tensor, ...], 선택 사항, output_hidden_states=True일 때 반환됨) — chunk 순서대로 각 chunk의 Encoder hidden states입니다. Encoder는 chunk별로 한 번씩 실행되므로, 이 tuple에는 chunk당 config.audio_config.num_hidden_layers + 1개의 tensor가 포함됩니다. 시퀀스 길이는 cache 및 look-ahead 프레임을 포함한 해당 chunk의 길이입니다.
  • attentions (tuple[torch.Tensor, ...], 선택 사항, output_attentions=True일 때 반환됨) — config.audio_config.num_hidden_layers개의 텐서가 포함된 각 청크의 인코더 어텐션 가중치. 청크 순서대로 배치됩니다.
  • speaker_cache (Nemotron3DiarizationSpeakerCache, 선택, 스트리밍 모드에서 반환됨) — 동일한 스트림의 다음 오디오 청크의 forward에 전달할 업데이트된 스트리밍 상태입니다.

예:

>>> from transformers import AutoModelForAudioFrameClassification, AutoProcessor
>>> from transformers.audio_utils import load_audio

>>> model_id = "nvidia/Nemotron-3-Diarization"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = AutoModelForAudioFrameClassification.from_pretrained(model_id, device_map="auto")

>>> sampling_rate = processor.feature_extractor.sampling_rate
>>> audio = load_audio(
...     "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/en-Alice_woman.wav",
...     sampling_rate=sampling_rate,
... )
>>> inputs = processor(audio, sampling_rate=sampling_rate).to(model.device, dtype=model.dtype)
>>> probabilities = model(**inputs).logits.sigmoid()  # (1, num_frames, 8), one frame every 10 ms
Update on GitHub