Transformers documentation

MOSS-Transcribe-Diarize

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-10-14 贡献至 Hugging Face Transformers。

MOSS-Transcribe-Diarize

概述

MOSS-Transcribe-Diarize 0.9B 是一款面向长音频多说话人转写、说话人分离和时间戳标注的端到端音频理解模型。它集成了 Whisper 风格的编码器、4× 帧合并步骤、多模态投影器以及 Qwen3 语言模型。

模型检查点可在以下位置获取:itazap/MOSS-Transcribe-Diarize-HF

主要功能包括:

  • 在单次处理中完成联合转录与说话人分离,片段格式为 [start][S01]text[end]。
  • 通过处理器上游的 Whisper-window 分块处理长音频;模型会按样本重新组装这些分块。
  • 通过 apply_transcription_request 或聊天模板实现可提示转录。
  • 支持 50 多种语言的多语言支持。

该模型由 Hugging Face 团队的 Ita Zaporozhets 贡献。有关更多详细信息,请参阅 模型卡片 和 OpenMOSS 仓库。

用法

以下大多数示例使用了 apply_transcription_request,这是一个为您构建聊天模板的便捷函数。有关等效的 apply_chat_template 调用,请参阅 使用聊天模板的高级用法。

基础转录与说话人分离

每个说话人轮次都被解码为 [start][S0N]text[end] 片段。processor.decode 可以返回原始解码字符串、以字典列表形式表示的解析后片段(return_format="parsed"),或仅返回拼接后的转录文本(return_format="transcription_only")。

from transformers import AutoProcessor, AutoModelForCausalLM

model_id = "itazap/MOSS-Transcribe-Diarize-HF"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")

audio_url = "https://huggingface.co/datasets/itazap/audio_samples/resolve/main/podcast_sample.wav"
inputs = processor.apply_transcription_request(audio_url)
inputs = inputs.to(model.device, dtype=model.dtype)

outputs = model.generate(**inputs, do_sample=False, max_new_tokens=512)
generated_ids = outputs[:, inputs.input_ids.shape[1] :]

decoded = processor.decode(generated_ids, skip_special_tokens=True)
print("RAW OUTPUT:", decoded)

parsed = processor.decode(generated_ids, return_format="parsed")[0]
print("\nPARSED (list of dicts):")
for segment in parsed:
    print(segment)

transcription = processor.decode(generated_ids, return_format="transcription_only")
print("\nTRANSCRIPTION ONLY:", transcription[0])

"""
RAW OUTPUT: ["[0.48][S01] Hey everyone, welcome back to the show.[2.43][2.46][S01] Today, we're talking about the best way to learn a new skill.[5.22][5.43][S01] I'm here with Jordan to dig into it.[7.14][8.40][S02] Thanks for having me.[9.42][9.63][S02] My take is that consistency beats intensity every single time.[12.87][13.14][S01] That makes sense.[13.92][13.92][S01] Even 20 minutes a day adds up over a few months.[16.17][16.32][S02] Exactly, and writing down small wins keeps you motivated along the way.[19.62]"]

PARSED (list of dicts):
{'Start': 0.48, 'End': 2.43, 'Speaker': 1, 'Content': 'Hey everyone, welcome back to the show.'}
{'Start': 2.46, 'End': 5.22, 'Speaker': 1, 'Content': "Today, we're talking about the best way to learn a new skill."}
{'Start': 5.43, 'End': 7.14, 'Speaker': 1, 'Content': "I'm here with Jordan to dig into it."}
{'Start': 8.4, 'End': 9.42, 'Speaker': 2, 'Content': 'Thanks for having me.'}
{'Start': 9.63, 'End': 12.87, 'Speaker': 2, 'Content': 'My take is that consistency beats intensity every single time.'}
{'Start': 13.14, 'End': 13.92, 'Speaker': 1, 'Content': 'That makes sense.'}
{'Start': 13.92, 'End': 16.17, 'Speaker': 1, 'Content': 'Even 20 minutes a day adds up over a few months.'}
{'Start': 16.32, 'End': 19.62, 'Speaker': 2, 'Content': 'Exactly, and writing down small wins keeps you motivated along the way.'}

TRANSCRIPTION ONLY: Hey everyone, welcome back to the show. Today, we're talking about the best way to learn a new skill. I'm here with Jordan to dig into it. Thanks for having me. My take is that consistency beats intensity every single time. That makes sense. Even 20 minutes a day adds up over a few months. Exactly, and writing down small wins keeps you motivated along the way.
"""

自定义提示词和热词

apply_transcription_request 接受 keywords 参数,用于将转录结果偏向特定术语(例如专有名词或领域特定词汇),这些术语在聊天模板中呈现为热词列表:(“hotword list”)。还可以同时传入自定义的 prompt 以提供额外的上下文。

下方,我们转录了一段提及“Yorùbá”的音频片段,并对比了传入该关键词与未传入该关键词时的结果。

from transformers import AutoProcessor, AutoModelForCausalLM

model_id = "itazap/MOSS-Transcribe-Diarize-HF"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")

audio_url = "https://huggingface.co/datasets/itazap/audio_samples/resolve/main/languages_sample.wav"

# Without keywords
inputs = processor.apply_transcription_request(audio_url)
inputs = inputs.to(model.device, dtype=model.dtype)
outputs = model.generate(**inputs, do_sample=False, max_new_tokens=128)
transcription = processor.decode(outputs[:, inputs.input_ids.shape[1] :], return_format="transcription_only")
print(f"WITHOUT keywords: {transcription[0]}")

# With keywords
inputs = processor.apply_transcription_request(audio_url, keywords=["Mandarin", "Yorùbá"])
inputs = inputs.to(model.device, dtype=model.dtype)
outputs = model.generate(**inputs, do_sample=False, max_new_tokens=128)
transcription = processor.decode(outputs[:, inputs.input_ids.shape[1] :], return_format="transcription_only")
print(f"WITH keywords   : {transcription[0]}")

"""
WITHOUT keywords: Let's talk about the most spoken languages in the world. Mandarin Chinese has the most native speakers, followed by Spanish, English, and Hindi. In West Africa, one of the most widely spoken languages is Yoruba, with over 50 million speakers.
WITH keywords   : Let's talk about the most spoken languages in the world. Mandarin Chinese has the most native speakers, followed by Spanish, English, and Hindi. In West Africa, one of the most widely spoken languages is Yorùbá, with over 50 million speakers.
"""

使用聊天模板的高级用法

apply_transcription_request 等效于一个仅包含音频的用户轮次的聊天模板:

from transformers import AutoProcessor, AutoModelForCausalLM

model_id = "itazap/MOSS-Transcribe-Diarize-HF"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")

audio_url = "https://huggingface.co/datasets/itazap/audio_samples/resolve/main/intro_sample.wav"
conversation = [
    {
        "role": "user",
        "content": [
            {"type": "audio", "url": audio_url},
        ],
    },
]

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

outputs = model.generate(**inputs, do_sample=False, max_new_tokens=128)
decoded = processor.decode(
    outputs[:, inputs.input_ids.shape[1] :],
    skip_special_tokens=True,
)
print(decoded)

批量推理

传入一个音频列表,并可选地传入与之匹配的提示词和/或关键词列表,以便在一次调用中批量转录。 将某个条目设置为 None 即可在对应样本中跳过该条目。

from transformers import AutoProcessor, AutoModelForCausalLM

model_id = "itazap/MOSS-Transcribe-Diarize-HF"
processor = AutoProcessor.from_pretrained(model_id)
# `from_pretrained` is used here for convenience, the model can also be built from a config directly.
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")

audio = [
    "https://huggingface.co/datasets/itazap/audio_samples/resolve/main/intro_sample.wav",
    "https://huggingface.co/datasets/itazap/audio_samples/resolve/main/languages_sample.wav",
]
keywords = [None, ["Mandarin", "Yorùbá"]]

inputs = processor.apply_transcription_request(audio, keywords=keywords)
inputs = inputs.to(model.device, dtype=model.dtype)
outputs = model.generate(**inputs, do_sample=False, max_new_tokens=128)
transcription = processor.decode(outputs[:, inputs.input_ids.shape[1] :], return_format="transcription_only")
print(transcription)

训练

将目标转录文本以模型带时间戳和说话人标签的输出格式,通过 transcription 传递给 apply_transcription_request。返回的 labels 用于计算损失。

from transformers import AutoModelForCausalLM, AutoProcessor

model_id = "itazap/MOSS-Transcribe-Diarize-HF"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
model.train()

audio_url = "https://huggingface.co/datasets/itazap/audio_samples/resolve/main/intro_sample.wav"
transcription = (
    "[0.00][S01] Welcome to this demonstration of automatic speech recognition and speaker diarization using an "
    "end-to-end transformer model.[7.47]"
)

inputs = processor.apply_transcription_request(audio_url, transcription=transcription)
inputs.to(model.device, dtype=model.dtype)

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

Torch 编译

该模型可以编译以加快推理/训练速度。device_map="auto" 会使用 accelerate 钩子包装前向传播,从而导致反复重新编译,因此建议直接将模型加载到单个设备上。

在 B200 上,我们观察到当批处理大小为 4 时,速度提升了约 2.1 倍。

import time

import torch

from transformers import AutoProcessor, AutoModelForCausalLM


model_id = "itazap/MOSS-Transcribe-Diarize-HF"

num_warmup = 5
num_runs = 20

# Load processor + model
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id).to("cuda")

# Prepare static inputs
audio_url = "https://huggingface.co/datasets/itazap/audio_samples/resolve/main/intro_sample.wav"
inputs = processor.apply_transcription_request([audio_url] * 4).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")

对于自回归转录,torch.compile 通过提供一个 CompileConfig 对象,而不是直接编译 model.forward,来加速 generate 内部逐 token 的前向传播。

import torch
from transformers import AutoProcessor, AutoModelForCausalLM, CompileConfig

model_id = "itazap/MOSS-Transcribe-Diarize-HF"
num_warmup = 3

processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id).to("cuda")

audio_url = "https://huggingface.co/datasets/itazap/audio_samples/resolve/main/intro_sample.wav"
inputs = processor.apply_transcription_request([audio_url] * 4).to(model.device, torch.bfloat16)

compile_config = CompileConfig()

# Warmup
for _ in range(num_warmup):
    _ = model.generate(**inputs, max_new_tokens=128, cache_implementation="static", compile_config=compile_config)

# Apply model
generated_ids = model.generate(
    **inputs, max_new_tokens=128, cache_implementation="static", compile_config=compile_config
)
transcription = processor.decode(generated_ids[:, inputs.input_ids.shape[1] :], return_format="transcription_only")
print(transcription)

MossTranscribeDiarizeConfig

class transformers.MossTranscribeDiarizeConfig

< >

( 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: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneaudio_token_id: int = 151671projector_hidden_act: str = 'silu'projector_bias: bool = Trueaudio_merge_size: int = 4audio_chunk_size: int = 480000tie_word_embeddings: bool = True )

参数

  • audio_config (Union[dict, ~configuration_utils.PreTrainedConfig], 可选) — 音频骨干网络的配置对象或字典。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • audio_token_id (int,可选,默认为 151671) — 用作输入音频占位符的音频 token 索引。
  • projector_hidden_act (str, 可选,默认为 silu) — 多模态投影器所使用的激活函数。
  • projector_bias (bool,可选,默认为 True) — 是否在多模态投影器中使用偏置。
  • audio_merge_size (int,可选,默认为 4) — 在多模态投影器之前拼接的连续 Whisper 编码器帧数。
  • audio_chunk_size (int, 可选,默认为 480000) — Whisper 编码器的窗口大小(以原始音频采样点计),与 padding_mask 配合使用以恢复 audio_chunk_mapping。
  • tie_word_embeddings (bool,可选,默认为 True) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 MossTranscribeDiarizeModel 配置的类。它根据指定的参数实例化 Moss Transcribe Diarize 模型,并定义模型架构。使用默认值实例化配置,将得到与 hf-audio/MOSS-Transcribe-Diarize-HF 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import MossTranscribeDiarizeForConditionalGeneration, MossTranscribeDiarizeConfig

>>> # Initializing a MossTranscribeDiarize configuration
>>> configuration = MossTranscribeDiarizeConfig()

>>> # Initializing a model from the configuration
>>> model = MossTranscribeDiarizeForConditionalGeneration(configuration)

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

MossTranscribeDiarizeAudioConfig

类 transformers.MossTranscribeDiarizeAudioConfig

< >

( 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 = Nonenum_mel_bins: int = 80num_hidden_layers: int = 24num_attention_heads: int = 16intermediate_size: int = 4096activation_function: str = 'gelu'hidden_size: int = 1024dropout: float | int = 0.0attention_dropout: float | int = 0.0activation_dropout: float | int = 0.0initializer_range: float = 0.02max_source_positions: int = 1500 )

参数

  • num_mel_bins (int,可选,默认为 80) — 每个输入帧使用的 mel 特征数量。应与 AutoFeatureExtractor 类中使用的值相对应。
  • num_hidden_layers (int,可选,默认为 24) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • intermediate_size (int,可选,默认为 4096) — MLP 表示的维度。
  • activation_function (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu" 等。
  • hidden_size (int,可选,默认为 1024) — 隐藏表示的维度。
  • dropout (Union[float, int],可选,默认为 0.0) — 所有 dropout 层的比率。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • activation_dropout (Union[float, int],可选,默认为 0.0) — 全连接层中激活值的 dropout 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • max_source_positions (int,可选,默认值为 1500) — 该模型可能使用的 log-mel 滤波器组特征的最大序列长度。

这是用于存储 MossTranscribeDiarizeModel 配置的类。它根据指定的参数实例化 Moss Transcribe Diarize 模型,并定义模型架构。使用默认值实例化配置,将得到与 hf-audio/MOSS-Transcribe-Diarize-HF 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import MossTranscribeDiarizeAudioConfig, MossTranscribeDiarizeAudioModel

>>> # Initializing a MossTranscribeDiarizeAudioConfig
>>> configuration = MossTranscribeDiarizeAudioConfig()

>>> # Initializing a MossTranscribeDiarizeAudioModel (with random weights)
>>> model = MossTranscribeDiarizeAudioModel(configuration)

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

MossTranscribeDiarizeAudioModel

class transformers.MossTranscribeDiarizeAudioModel

< >

( config: MossTranscribeDiarizeAudioConfig )

参数

  • config (MossTranscribeDiarizeAudioConfig) — 模型的配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

MOSS-Transcribe-Diarize 音频模型,它是一个 Whisper 编码器。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_featuresattention_mask = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • input_features (torch.Tensor,形状为 (batch_size, feature_size, sequence_length)) — 从原始语音波形中提取的对数梅尔特征,每个 30 秒的 Whisper 窗口对应一行。参见 call()。
  • attention_mask (torch.Tensor, 可选) — MossTranscribeDiarize 不支持对 input_features 进行掩码处理,此参数仅为保持兼容性而保留,实际不会被使用。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MossTranscribeDiarizeConfig)和输入。

MossTranscribeDiarizeAudioModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

MossTranscribeDiarizeFeatureExtractor

class transformers.MossTranscribeDiarizeFeatureExtractor

< >

( feature_size = 80sampling_rate = 16000hop_length = 160chunk_length = 30n_fft = 400padding_value = 0.0dither = 0.0return_attention_mask = False**kwargs )

构建 MOSS-Transcribe-Diarize 特征提取器。

这是一个 WhisperFeatureExtractor,它会在提取对数梅尔特征之前,将时长超过 chunk_length 秒的音频分割为连续的 Whisper 窗口块,并通过 padding_mask 报告每个样本的原始原始音频长度(而 input_features_mask 则标记每个块中的有效帧)。

__call__

< >

( raw_speech: numpy.ndarray | list[float] | list[numpy.ndarray] | list[list[float]]truncation: bool = Truepad_to_multiple_of: int | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonesampling_rate: int | None = Nonedevice: str | None = 'cpu'**kwargs ) → BatchFeature

参数

  • raw_speech(np.ndarray、list[float]、list[np.ndarray]、list[list[float]])— 要处理的序列或序列批次。仅支持单声道音频。
  • truncation(bool,可选,默认为 True)— 启用截断,将每个长度为 n_samples 的块截断为 n_samples。
  • pad_to_multiple_of (int, 可选) — 如果设置,会将每个分块的原始音频填充为该值的整数倍。
  • device (str,可选,默认为 "cpu") — 用于计算对数梅尔频谱的设备。

返回值

BatchFeature

其中 input_features(对数梅尔特征,每个块一行)、input_features_mask(每个块的有效帧掩码)以及 padding_mask(有效原始采样掩码,每个输入样本一行)。

将每个音频样本拆分为连续的、长度为 n_samples 的片段,为每个片段提取对数梅尔特征,并通过 padding_mask 报告每个样本的原始原始音频长度。

MossTranscribeDiarizeProcessor

class transformers.MossTranscribeDiarizeProcessor

< >

( feature_extractor = Nonetokenizer = Nonechat_template: str | None = Noneaudio_token: str = '<|audio_pad|>'audio_bos_token: str = '<|audio_start|>'audio_eos_token: str = '<|audio_end|>'audio_tokens_per_second: float = 12.5audio_merge_size: int = 4time_marker_every_seconds: int = 2 )

参数

  • feature_extractor(MossTranscribeDiarizeFeatureExtractor)— 特征提取器是必需的输入。
  • tokenizer (Qwen2Tokenizer) — 分词器是必需的输入。
  • chat_template (str, 可选) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
  • audio_token (str, 可选,默认为 "<|audio_pad|>") — 在聊天模板中用于表示音频输入的特殊标记。
  • audio_bos_token (str,可选,默认为 "<|audio_start|>") — 用于标记聊天模板中音频片段起始位置的特殊标记。
  • audio_eos_token (str,可选,默认为 "<|audio_end|>") — 用于标记聊天模板中音频片段结束的特殊标记。
  • audio_tokens_per_second (float,可选,默认为 12.5) — 每秒输入音频中预期的音频占位符 token 数量。
  • audio_merge_size (int,可选,默认为 4) — 在计算音频 token 数量时使用的 Whisper 帧合并因子。
  • time_marker_every_seconds (int,可选,默认为 2) — 在音频片段中每隔 N 秒插入一个数字时间标记 token。将其设置为 0 可禁用时间标记,改为输出一个普通的音频占位符片段。

构建一个 MossTranscribeDiarizeProcessor,它将特征提取器和分词器封装为单个处理器。

MossTranscribeDiarizeProcessor 提供了 MossTranscribeDiarizeFeatureExtractor 和 Qwen2Tokenizer 的所有功能。有关更多信息,请参阅 ~MossTranscribeDiarizeFeatureExtractor 和 ~Qwen2Tokenizer。

__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.moss_transcribe_diarize.processing_moss_transcribe_diarize.MossTranscribeDiarizeProcessorKwargs'> ) → 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 张量,每个音频的形状应为 (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_chat_template

< >

( conversation: list[dict[str, str]] | list[list[dict[str, str]]]chat_template: str | None = Nonetools: list[dict] | None = Nonedocuments: list[dict[str, str]] | None = Noneadd_generation_prompt: bool = Falsecontinue_final_message: bool | str = Falsereturn_assistant_tokens_mask: bool = Falsetokenize: bool = Falsereturn_tensors: str | transformers.utils.generic.TensorType | None = 'auto'return_dict: bool = Falseload_audio_from_video: bool = Falseprocessor_kwargs: dict | None = None**kwargs )

参数

  • conversation (Union[list[Dict, [str, str]], list[list[dict[str, str]]]]) — 要格式化的对话。
  • chat_template (Optional[str],可选) — 用于格式化对话的 Jinja 模板。如果未提供,则使用分词器的聊天模板。

与分词器上的 apply_chat_template 方法类似,该方法将 Jinja 模板应用于输入对话,将其转换为单个可分词的字符串。

输入应遵循以下格式,其中每条消息的内容是一个列表,包含文本以及可选的图像或视频输入。也可以提供图像、视频、URL 或本地路径,当 return_dict=True 时,这些内容将用于构建 pixel_values。如果未提供,则只会获得格式化后的文本,以及可选的标记化文本。

conversation = [ { “role”: “user”, “content”: [ {“type”: “image”, “url”: “https://www.ilankelman.org/stopsigns/australia.jpg”}, {“type”: “text”, “text”: “Please describe this image in detail.”}, ], }, ]

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 = Nonekeywords: str | list[str] | list[list[str]] | None = Nonetranscription: str | list[str] | None = Nonetokenize: bool = True**kwargs: *<class 'transformers.models.moss_transcribe_diarize.processing_moss_transcribe_diarize.MossTranscribeDiarizeProcessorKwargs'> )

参数

  • audio (str, list[str], np.ndarray, torch.Tensor, list[np.ndarray], list[torch.Tensor]) — 要转录的音频。字符串会被解释为本地路径或 URL,并由聊天模板加载器自动加载;NumPy 数组和 PyTorch 张量会被直接传递。
  • prompt (str 或 list[str],可选) — 包含在用户轮次中的自定义提示词。如果传入列表,其长度必须与批次大小相同。当值为 None 时,聊天模板将提供默认的带时间戳的说话人分离提示词。
  • keywords (str、list[str] 或 list[list[str]],可选) — 热词/领域术语(例如专有名词),用于将转录结果偏向正确的拼写。字符串或扁平的字符串列表在整个批次中共享;嵌套列表则为每个音频样本提供各自的热词。
  • transcription (str 或 list[str],可选) — 用于训练的目标转录文本,每个音频对应一个,格式需符合模型的输出格式(例如 "[0.00][S01] Hello world.[1.20]")。提供时,每个转录文本将作为助手轮次写入,并返回 labels(参见 call() 中的 output_labels)。
  • tokenize (bool,可选,默认为 True) — 是否对提示词进行分词并处理音频。如果为 False,则不会加载音频,提示词将以字符串形式返回,其中包含未展开的音频占位符。将这些提示词与音频一起传递给处理器,即 processor(text=prompts, audio=audio),其输出与 tokenize=True 时相同。
  • **kwargs — 转发给 apply_chat_template() 的额外关键字参数。 处理器关键字参数(例如 text_kwargs、audio_kwargs、……)应通过 processor_kwargs={...} 传递。

在无需手动编写聊天模板的情况下,为转录/说话人分离准备输入,用于推理,或在提供 transcription 时用于训练。

MossTranscribeDiarizeModel

类 transformers.MossTranscribeDiarizeModel

< >

( config: MossTranscribeDiarizeConfig )

参数

  • config (MossTranscribeDiarizeConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

MOSS-Transcribe-Diarize 模型:Whisper 编码器、4 倍时间合并、多模态投影器以及 Qwen3 语言模型。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneinput_features: typing.Optional[torch.Tensor] = Noneinput_features_mask: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepadding_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MossTranscribeDiarizeModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim),可选) — 与输入音频特征对应的张量。可以使用 MossTranscribeDiarizeFeatureExtractor 获取音频特征。有关详细信息,请参阅 MossTranscribeDiarizeFeatureExtractor.call()(MossTranscribeDiarizeProcessor 使用 MossTranscribeDiarizeFeatureExtractor 来处理音频)。
  • input_features_mask (torch.Tensor,形状为 (num_chunks, feature_sequence_length),可选) — 掩码,用于标记有效的(非填充的)特征索引,input_features 中每个分块的 log-mel 特征行对应一行。用于计算每个分块的有效编码器输出长度。
  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length),可选) — 用于避免在填充(padding)标记索引上执行注意力的掩码。该掩码会原样传递给语言模型。
  • inputs_embeds (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 预计算的嵌入,用于替代传入 input_ids。如果同时提供了 input_features, 仍然需要 input_ids,以便定位 inputs_embeds 中的音频占位符位置,并用音频嵌入进行填充。
  • padding_mask (torch.Tensor,形状为 (batch_size, max_audio_length),可选) — 用于标记每个音频样本有效原始音频长度的掩码。与 config.audio_chunk_size 配合使用,以恢复 audio_chunk_mapping。

返回值

MossTranscribeDiarizeModelOutputWithPast 或 tuple(torch.Tensor)

MossTranscribeDiarizeModelOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),包含根据配置(MossTranscribeDiarizeConfig)和输入而定的各种元素。

MossTranscribeDiarizeModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • audio_hidden_states (torch.Tensor,可选) — 投影后的音频隐藏状态。

get_audio_features

< >

( input_features: Tensorinput_features_mask: Tensorpadding_mask: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim)) — 与输入音频特征对应的张量。可以使用 MossTranscribeDiarizeFeatureExtractor 获取音频特征。有关详细信息,请参阅 MossTranscribeDiarizeFeatureExtractor.call()(MossTranscribeDiarizeProcessor 使用 MossTranscribeDiarizeFeatureExtractor 处理音频)。
  • input_features_mask(形状为 (num_chunks, feature_sequence_length) 的 torch.Tensor)— 掩码,用于标记有效的(非填充的)特征索引,input_features 中每个分块的 log-mel 特征行对应一行。用于计算每个分块的有效编码器输出长度。
  • padding_mask(形状为 (batch_size, max_audio_length) 的 torch.Tensor)— 掩码,用于标记每个音频样本的有效原始音频长度,每个样本对应一行。与 config.audio_chunk_size 配合使用,以恢复 audio_chunk_mapping。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MossTranscribeDiarizeConfig)和输入。

从对数梅尔特征中提取 MOSS 音频嵌入,并按样本重新组装多块音频。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

MossTranscribeDiarizeForConditionalGeneration

class transformers.MossTranscribeDiarizeForConditionalGeneration

< >

( config: MossTranscribeDiarizeConfig )

参数

  • config (MossTranscribeDiarizeConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

用于条件生成的 MOSS-Transcribe-Diarize 模型,支持转录和说话人分离。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneinput_features: typing.Optional[torch.Tensor] = Noneinput_features_mask: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0padding_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MossTranscribeDiarizeCausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim),可选) — 与输入音频特征对应的张量。可以使用 MossTranscribeDiarizeFeatureExtractor 获取音频特征。有关详细信息,请参阅 MossTranscribeDiarizeFeatureExtractor.call()(MossTranscribeDiarizeProcessor 使用 MossTranscribeDiarizeFeatureExtractor 来处理音频)。
  • input_features_mask (torch.Tensor,形状为 (num_chunks, feature_sequence_length),可选) — 掩码,用于标记有效的(非填充的)特征索引,input_features 中每个分块的 log-mel 特征行对应一行。用于计算每个分块的有效编码器输出长度。
  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length),可选) — 用于避免在填充(padding)标记索引上执行注意力的掩码。该掩码会原样传递给语言模型。
  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 预计算的嵌入,用于替代传入 input_ids。如果同时提供了 input_features, 仍然需要 input_ids,以便定位 inputs_embeds 中的音频占位符位置,并用音频嵌入进行填充。
  • labels(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选)— 用于计算掩码语言建模损失的标签。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。
  • padding_mask (torch.Tensor,形状为 (batch_size, max_audio_length),可选) — 用于标记每个音频样本有效原始音频长度的掩码。与 config.audio_chunk_size 配合使用,以恢复 audio_chunk_mapping。

返回值

MossTranscribeDiarizeCausalLMOutputWithPast 或 tuple(torch.Tensor)

MossTranscribeDiarizeCausalLMOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(MossTranscribeDiarizeConfig)和输入。

MossTranscribeDiarizeForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数。

  • 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 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • audio_hidden_states (torch.Tensor,可选) — 音频编码器投影后的隐藏状态。

示例:

>>> from transformers import MossTranscribeDiarizeForConditionalGeneration, AutoProcessor

>>> model_id = "hf-audio/MOSS-Transcribe-Diarize-HF"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = MossTranscribeDiarizeForConditionalGeneration.from_pretrained(model_id, device_map="auto")
>>> inputs = processor.apply_transcription_request("https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3")
>>> inputs = inputs.to(model.device, dtype=model.dtype)
>>> outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500)
>>> processor.batch_decode(outputs[:, inputs.input_ids.shape[1] :], skip_special_tokens=True)

get_audio_features

< >

( input_featuresinput_features_mask**kwargs )

Update on GitHub