Transformers documentation

Qwen3 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.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2026-01-29 在 HF papers 上发布,并于 2026-06-26 贡献至 Hugging Face Transformers。

Qwen3 ASR

FlashAttention SDPA

概述

Qwen3 ASR 是阿里巴巴 Qwen 团队推出的自动语音识别模型,它将 Whisper 风格的音频编码器与 Qwen3 语言模型解码器相结合,用于语音转文本。该模型支持自动语言检测和多语言转录。

该库还包含一个强制对齐器模型。它可以用于为提供的转录文本及其音频添加时间戳。该模型使用相同的音频编码器,并附加一个分类头来预测单词的长度。此模型可与任意 ASR 模型的转录文本配合使用(参见下方使用 Parakeet CTC 的示例)。

可用的检查点:

支持以下语言:

  • Qwen3-ASR-1.7B 和 Qwen3-ASR-0.6B:中文 (zh)、英语 (en)、粤语 (yue)、阿拉伯语 (ar)、德语 (de)、法语 (fr)、西班牙语 (es)、葡萄牙语 (pt)、印度尼西亚语 (id)、意大利语 (it)、韩语 (ko)、俄语 (ru)、泰语 (th)、越南语 (vi)、日语 (ja)、土耳其语 (tr)、印地语 (hi)、马来语 (ms)、荷兰语 (nl)、瑞典语 (sv)、丹麦语 (da)、芬兰语 (fi)、波兰语 (pl)、捷克语 (cs)、菲律宾语 (fil)、波斯语 (fa)、希腊语 (el)、匈牙利语 (hu)、马其顿语 (mk)、罗马尼亚语 (ro)。
  • Qwen3-ForcedAligner-0.6B:中文(zh)、英语(en)、粤语(yue)、法语(fr)、德语(de)、意大利语(it)、日语(ja)、韩语(ko)、葡萄牙语(pt)、俄语(ru)、西班牙语(es)。

有关更多详细信息,请参阅原始仓库 QwenLM/Qwen3-ASR 和 报告。

该模型由 Eric Bezzam 和 Muhammed Tariq 贡献。

用法

简单转录

最简单的音频转录方式是使用 apply_transcription_request,它会自动处理聊天模板的格式化,即它是 apply_chat_template 的便捷封装(参见下文 聊天模板)。

from transformers import AutoProcessor, AutoModelForMultimodalLM

model_id = "Qwen/Qwen3-ASR-1.7B-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, device_map="auto")
print(f"Model loaded on {model.device} with dtype {model.dtype}")

inputs = processor.apply_transcription_request(
    audio="https://huggingface.co/datasets/bezzam/audio_samples/resolve/main/librispeech_mr_quilter.wav",
).to(model.device, model.dtype)

output_ids = model.generate(**inputs, max_new_tokens=256)
generated_ids = output_ids[:, inputs["input_ids"].shape[1]:]

# Raw output includes language tag and <asr_text> marker
raw = processor.decode(generated_ids)[0]
print(f"Raw: {raw}")

# Parsed output: dict with "language" and "transcription"
parsed = processor.decode(generated_ids, return_format="parsed")[0]
print(f"Parsed: {parsed}")

# Extract only the transcription text
transcription = processor.decode(generated_ids, return_format="transcription_only")[0]
print(f"Transcription: {transcription}")

"""
Raw: language English<asr_text>Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.
Parsed: {'language': 'English', 'transcription': 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'}
Transcription: Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.
"""

强制指定语言

您可以按照以下所示强制指定转录语言。

from transformers import AutoProcessor, AutoModelForMultimodalLM

model_id = "Qwen/Qwen3-ASR-1.7B-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, device_map="auto")

# Without language hint (auto-detect)
inputs = processor.apply_transcription_request(
    audio="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mandarin_voxcpm_zh.wav",
).to(model.device, model.dtype)
output_ids = model.generate(**inputs, max_new_tokens=256)
generated_ids = output_ids[:, inputs["input_ids"].shape[1]:]
print(f"Auto-detect: {processor.decode(generated_ids, return_format='transcription_only')[0]}")

# With forced language
inputs = processor.apply_transcription_request(
    audio="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mandarin_voxcpm_zh.wav",
    language="Chinese",  # or language code "zh"
).to(model.device, model.dtype)
output_ids = model.generate(**inputs, max_new_tokens=256)
generated_ids = output_ids[:, inputs["input_ids"].shape[1]:]
print(f"Forced:      {processor.decode(generated_ids, return_format='transcription_only')[0]}")

上下文 / 热词

您可以通过 prompt 传入自由形式的上下文(例如特定领域的词汇、名称或背景信息),以引导转录结果。

from transformers import AutoProcessor, AutoModelForMultimodalLM

model_id = "Qwen/Qwen3-ASR-1.7B-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, device_map="auto")

inputs = processor.apply_transcription_request(
    audio="https://huggingface.co/datasets/bezzam/audio_samples/resolve/main/librispeech_mr_quilter.wav",
    prompt="Vocabulary: Quilter, apostle, gospel.",
    language="English",
).to(model.device, model.dtype)

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

批量推理

通过传入音频列表,以及(如果提供的话)语言列表和/或提示词列表,即可执行批量推理。

from transformers import AutoProcessor, AutoModelForMultimodalLM

model_id = "Qwen/Qwen3-ASR-1.7B-hf"
audio = [
    "https://huggingface.co/datasets/bezzam/audio_samples/resolve/main/librispeech_mr_quilter.wav",
    "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mandarin_voxcpm_zh.wav",
]

processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, device_map="auto")

inputs = processor.apply_transcription_request(
    audio,
    prompt=["Vocabulary: Quilter, apostle, gospel.", None],
    language=[None, "zh"],  # language codes ("zh") and full names ("Chinese") are both accepted
).to(model.device, model.dtype)

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

for i, text in enumerate(transcriptions):
    print(f"Audio {i + 1}: {text}")

聊天模板

Qwen3 ASR 也接受聊天模板输入。上述 用法 是 apply_transcription_request 的便捷封装,其底层调用的是 apply_chat_template。

可以通过在聊天模板中预填充助手轮次为 language <NAME><asr_text> 并传入 continue_final_message=True 来强制指定语言,apply_transcription_request 在底层正是这样实现的。请注意,如果强制指定语言,则必须为批次中的所有音频设置预填充(如下所示)。

from transformers import AutoProcessor, Qwen3ASRForConditionalGeneration

model_id = "Qwen/Qwen3-ASR-1.7B-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = Qwen3ASRForConditionalGeneration.from_pretrained(model_id, device_map="auto")

chat_template = [
    [
        # Context/hotwords as system message
        {"role": "system", "content": [{"type": "text", "text": "Vocabulary: Quilter, apostle, gospel."}]},
        {
            "role": "user",
            "content": [
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/bezzam/audio_samples/resolve/main/librispeech_mr_quilter.wav",
                },
            ],
        },
        # empty prefill since forcing language in the other sample
        {"role": "assistant", "content": [{"type": "text", "text": ""}]},
    ],
    [
        {
            "role": "user",
            "content": [
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mandarin_voxcpm_zh.wav",
                },
            ],
        },
        {"role": "assistant", "content": [{"type": "text", "text": "language Chinese<asr_text>"}]},
    ],
]

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

output_ids = model.generate(**inputs, max_new_tokens=256)
generated_ids = output_ids[:, inputs["input_ids"].shape[1]:]
transcriptions = processor.decode(generated_ids, return_format="transcription_only")
for text in transcriptions:
    print(text)

训练

将目标转录文本通过 transcription 传递给 apply_transcription_request,以获取用于计算损失的 labels。

from datasets import Audio, load_dataset
from transformers import AutoProcessor, Qwen3ASRForConditionalGeneration

model_id = "Qwen/Qwen3-ASR-1.7B-hf"
NUM_SAMPLES = 2

processor = AutoProcessor.from_pretrained(model_id)
model = Qwen3ASRForConditionalGeneration.from_pretrained(model_id, device_map="auto")
model.train()

ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el["array"] for el in ds["audio"][:NUM_SAMPLES]]
text_samples = ds["text"][:NUM_SAMPLES]

inputs = processor.apply_transcription_request(speech_samples, language="en", transcription=text_samples)
inputs.to(model.device, dtype=model.dtype)

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

强制对齐(词级时间戳)

使用 Qwen3ASRForTokenClassification 从转录文本中获取词级时间戳。首先使用 ASR 模型进行转录,然后使用强制对齐器进行对齐。

支持以下语言:中文(zh)、英语(en)、粤语(yue)、法语(fr)、德语(de)、意大利语(it)、日语(ja)、韩语(ko)、葡萄牙语(pt)、俄语(ru)、西班牙语(es)。

日语需要 nagisa 库,而韩语需要 soynlp 库:

pip install nagisa soynlp

使用 Qwen3 ASR

import torch
from transformers import AutoProcessor, AutoModelForMultimodalLM, AutoModelForTokenClassification

asr_model_id = "Qwen/Qwen3-ASR-0.6B-hf"
aligner_model_id = "Qwen/Qwen3-ForcedAligner-0.6B-hf"

asr_processor = AutoProcessor.from_pretrained(asr_model_id)
asr_model = AutoModelForMultimodalLM.from_pretrained(asr_model_id, device_map="auto")

aligner_processor = AutoProcessor.from_pretrained(aligner_model_id)
aligner_model = AutoModelForTokenClassification.from_pretrained(
    aligner_model_id, dtype=torch.bfloat16, device_map="auto"
)

audio_url = "https://huggingface.co/datasets/bezzam/audio_samples/resolve/main/librispeech_mr_quilter.wav"

# Step 1: Transcribe
inputs = asr_processor.apply_transcription_request(audio=audio_url)
inputs = inputs.to(asr_model.device, asr_model.dtype)
output_ids = asr_model.generate(**inputs, max_new_tokens=256)
generated_ids = output_ids[:, inputs["input_ids"].shape[1]:]
parsed = asr_processor.decode(generated_ids, return_format="parsed")[0]
transcript = parsed["transcription"]
language = parsed["language"] or "English"

# Step 2: Prepare alignment inputs
aligner_inputs, word_lists = aligner_processor.prepare_forced_aligner_inputs(
    audio=audio_url, transcript=transcript, language=language,
)
aligner_inputs = aligner_inputs.to(aligner_model.device, aligner_model.dtype)

# Step 3: Run forced aligner
with torch.inference_mode():
    outputs = aligner_model(**aligner_inputs)

# Step 4: Decode timestamps
timestamps = aligner_processor.decode_forced_alignment(
    logits=outputs.logits,
    input_ids=aligner_inputs["input_ids"],
    word_lists=word_lists,
    timestamp_token_id=aligner_model.config.timestamp_token_id,
)[0]

for item in timestamps:
    print(f"{item['text']:<20} {item['start_time']:>8.3f}s → {item['end_time']:>8.3f}s")

"""
Word                  Start (s)    End (s)
------------------------------------------
Mr                        0.560      0.800
Quilter                   0.800      1.280
is                        1.280      1.440
the                       1.440      1.520
apostle                   1.520      2.080
...
"""

使用另一个 ASR 模型

强制对齐器与模型无关,这意味着可以提供来自任何 ASR 系统的转录文本。下面是一个使用 NVIDIA Parakeet CTC 进行转录的批量推理示例。

import torch
from datasets import Audio, load_dataset
from transformers import AutoModelForCTC, AutoProcessor, AutoModelForTokenClassification

parakeet_processor = AutoProcessor.from_pretrained("nvidia/parakeet-ctc-1.1b")
parakeet_model = AutoModelForCTC.from_pretrained(
    "nvidia/parakeet-ctc-1.1b", dtype="auto", device_map="auto",
)

aligner_model_id = "Qwen/Qwen3-ForcedAligner-0.6B-hf"
aligner_processor = AutoProcessor.from_pretrained(aligner_model_id)
aligner_model = AutoModelForTokenClassification.from_pretrained(
    aligner_model_id, dtype=torch.bfloat16, device_map="auto",
)

ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=parakeet_processor.feature_extractor.sampling_rate))
audio_arrays = [ds[i]["audio"]["array"] for i in range(3)]
sr = ds[0]["audio"]["sampling_rate"]

# Batch transcribe with Parakeet
inputs = parakeet_processor(audio_arrays, sampling_rate=sr, return_tensors="pt", padding=True).to(
    parakeet_model.device, dtype=parakeet_model.dtype
)
with torch.inference_mode():
    outputs = parakeet_model.generate(**inputs)
transcripts = parakeet_processor.decode(outputs)

# Batch align with Qwen3 Forced Aligner
aligner_inputs, word_lists = aligner_processor.prepare_forced_aligner_inputs(
    audio=audio_arrays, transcript=transcripts, language="English",
)
aligner_inputs = aligner_inputs.to(aligner_model.device, aligner_model.dtype)

with torch.inference_mode():
    aligner_outputs = aligner_model(**aligner_inputs)

batch_timestamps = aligner_processor.decode_forced_alignment(
    logits=aligner_outputs.logits,
    input_ids=aligner_inputs["input_ids"],
    word_lists=word_lists,
    timestamp_token_id=aligner_model.config.timestamp_token_id,
)

for i, (transcript, timestamps) in enumerate(zip(transcripts, batch_timestamps)):
    print(f"\n[Sample {i}] {transcript}")
    for item in timestamps[:5]:
        print(f"  {item['text']:<20} {item['start_time']:>8.3f}s → {item['end_time']:>8.3f}s")
    if len(timestamps) > 5:
        print(f"  ... ({len(timestamps) - 5} more words)")

Torch 编译

ASR 模型和强制对齐模型均支持 torch.compile 以实现更快的推理。强制对齐模型尤其适合编译,因为它只执行一次前向传播(无需自回归解码)。这使其成为 批量音频时间戳标注 的理想选择:使用任意 ASR 模型进行转录,然后使用编译后的强制对齐模型进行批量对齐,以获得最大吞吐量。

强制对齐器

在 A100 上,当批处理大小为 4 时,我们观察到约 1.2 倍的加速效果(脚本)。

import torch
from transformers import AutoProcessor, AutoModelForTokenClassification

model_id = "Qwen/Qwen3-ForcedAligner-0.6B-hf"
num_warmup = 5
batch_size = 4

processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTokenClassification.from_pretrained(model_id, dtype=torch.bfloat16).to("cuda")

# Prepare a batch of 4 samples
audio_url = "https://huggingface.co/datasets/bezzam/audio_samples/resolve/main/librispeech_mr_quilter.wav"
transcript = "Mr. Quilter is the apostle of the middle classes."

aligner_inputs, word_lists = processor.prepare_forced_aligner_inputs(
    audio=[audio_url] * batch_size,
    transcript=[transcript] * batch_size,
    language=["English"] * batch_size,
)
aligner_inputs = aligner_inputs.to(model.device, torch.bfloat16)

# Warm-up and apply model
model = torch.compile(model)
with torch.no_grad():
    for _ in range(num_warmup):
        _ = model(**aligner_inputs)
with torch.no_grad():
    _ = model(**aligner_inputs)

ASR 模型(生成)

对于自回归转录,在 generate 设置中提供 CompileConfig 对象时,torch.compile 会加速其中每个 token 的前向传播。

在 A100 上,当批处理大小为 4 时,我们观察到约 3.8 倍的加速效果(脚本)。

import torch
from transformers import AutoProcessor, AutoModelForMultimodalLM, CompileConfig

model_id = "Qwen/Qwen3-ASR-1.7B-hf"
num_warmup = 3
max_new_tokens = 256

processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, dtype=torch.bfloat16).to("cuda").eval()

audio_url = "https://huggingface.co/datasets/bezzam/audio_samples/resolve/main/librispeech_mr_quilter.wav"
inputs = processor.apply_transcription_request(
    audio=[audio_url] * 4,  # batch of 4
).to(model.device, torch.bfloat16)

compile_config = CompileConfig()

# Warmup
with torch.inference_mode():
    for _ in range(num_warmup):
        _ = model.generate(
            **inputs, max_new_tokens=max_new_tokens, do_sample=False,
            cache_implementation="static", compile_config=compile_config,
        )
torch.cuda.synchronize()

# Apply model
with torch.inference_mode():
    output_ids = model.generate(
        **inputs, max_new_tokens=max_new_tokens, do_sample=False,
        cache_implementation="static", compile_config=compile_config,
    )
generated_ids = output_ids[:, inputs["input_ids"].shape[1] :]
text_compiled = processor.decode(generated_ids, return_format="transcription_only")[0]
print(f"Output:  {text_compiled}")

Pipeline 用法

from transformers import pipeline

model_id = "Qwen/Qwen3-ASR-1.7B-hf"
pipe = pipeline("any-to-any", model=model_id, device_map="auto")

chat_template = [
    {
        "role": "user",
        "content": [
            {
                "type": "audio",
                "path": "https://huggingface.co/datasets/bezzam/audio_samples/resolve/main/librispeech_mr_quilter.wav",
            },
        ],
    }
]
outputs = pipe(text=chat_template, return_full_text=False)
raw_text = outputs[0]["generated_text"]
print(f"Raw: {raw_text}")

# Use processor helper to extract transcription
transcription = pipe.processor.extract_transcription(raw_text)
print(f"Transcription: {transcription}")

Qwen3ASRConfig

类 transformers.Qwen3ASRConfig

< >

( 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 = 151676timestamp_token_id: int = 151705pad_token_id: int = 151645eos_token_id: list[int] | tuple[int, ...] | int = (151643, 151645)initializer_range: float = 0.02tie_word_embeddings: bool = Truetoken_classification_bias: bool = False )

参数

  • audio_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 音频骨干网络的配置对象或字典。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • audio_token_id (int,可选,默认为 151676) — 用于编码音频提示的音频 token id。
  • timestamp_token_id (int,可选,默认为 151705) — 分词器词表中 <timestamp> 标记的 Token ID。这些标记用于界定强制对齐输入序列中的单词边界。
  • pad_token_id (int,可选,默认为 151645) — 词表中用于填充的 token id。
  • eos_token_id (Union[list[int], tuple[int, …], int],可选,默认为 (151643, 151645)) — 词汇表中用于表示流结束(end-of-stream)的 Token id。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • tie_word_embeddings (bool,可选,默认为 True) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。
  • token_classification_bias (bool,可选,默认为 False) — 强制对齐的 token 分类头是否应包含偏置项。

这是用于存储 Qwen3ASRModel 配置的类。它根据指定的参数实例化 Qwen3 Asr 模型,并定义模型架构。使用默认值实例化配置,将得到与 Qwen/Qwen3-ASR-1.7B-hf 类似的配置。

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

示例:

>>> from transformers import Qwen3ASRForConditionalGeneration, Qwen3ASRConfig

>>> # Initializing a Qwen3ASR style configuration
>>> configuration = Qwen3ASRConfig()

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

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

Qwen3ASREncoderConfig

类 transformers.Qwen3ASREncoderConfig

< >

( 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 = 128encoder_layers: int = 24encoder_attention_heads: int = 16encoder_ffn_dim: int = 4096d_model: int = 1024dropout: float | int = 0.0attention_dropout: float | int = 0.0activation_function: str = 'gelu'activation_dropout: float | int = 0.0scale_embedding: bool = Falseinitializer_range: float = 0.02n_window: int = 50output_dim: int = 3584n_window_infer: int = 800downsample_hidden_size: int = 480max_position_embeddings: int = 13 )

参数

  • num_mel_bins (int,可选,默认为 128) — 每个输入帧使用的 mel 特征数量。应与 AutoFeatureExtractor 类中使用的值相对应。
  • encoder_layers (int,可选,默认为 24) — Transformer 编码器中的隐藏层数量。如果未设置,将使用与 num_layers 相同的值。
  • encoder_attention_heads (int,可选,默认为 16) — Transformer 编码器中每个注意力层的注意力头数量。
  • encoder_ffn_dim (int,可选,默认为 4096) — 编码器中“中间”(通常称为前馈)层的维度。
  • d_model(int,可选,默认为 1024)—— 编码器层和池化层的维度大小。
  • dropout (Union[float, int],可选,默认为 0.0) — 所有 dropout 层的比率。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • activation_function (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,“gelu”、 “relu”、“silu” 等。
  • activation_dropout (Union[float, int],可选,默认为 0.0) — 全连接层中激活值的 dropout 比率。
  • scale_embedding (bool,可选,默认为 False) — 是否通过将嵌入除以 sqrt(d_model) 来对嵌入进行缩放。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • n_window (int,可选,默认为 50) — 单个编码器块中梅尔帧数的一半。卷积堆栈处理的每个块包含 2 * n_window 个梅尔帧(16 kHz 采样率、10 ms 跳步下的 1 秒音频)。
  • output_dim (int,可选,默认为 3584) — 输出的维度。
  • n_window_infer (int,可选,默认为 800) — 每个注意力窗口所跨越的音频对应的 mel 帧数。必须是 n_window * 2 的倍数,以便注意力窗口与编码器块对齐。
  • downsample_hidden_size (int,可选,默认为 480) — 卷积下采样堆栈的隐藏层大小。
  • max_position_embeddings (int,可选,默认为 13) — 该模型可能使用的最大序列长度。

这是用于存储 Qwen3ASRModel 配置的类。它根据指定的参数实例化 Qwen3 Asr 模型,并定义模型架构。使用默认值实例化配置,将得到与 Qwen/Qwen3-ASR-1.7B-hf 类似的配置。

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

Qwen3ASRFeatureExtractor

类 transformers.Qwen3ASRFeatureExtractor

< >

( feature_size = 128sampling_rate = 16000hop_length = 160chunk_length = 30n_fft = 400padding_value = 0.0dither = 0.0return_attention_mask = Truen_window = 50min_length = 8000**kwargs )

参数

  • feature_size (int,可选,默认为 128) — 梅尔滤波器组的数量。
  • sampling_rate (int,可选,默认为 16000) — 音频采样率,单位为 Hz。
  • hop_length (int, optional, 默认值为 160) — 用于获取梅尔频率系数的 STFT 中重叠窗口的长度。
  • chunk_length (int,可选,默认为 30) — 当 padding="max_length" 时,用于裁剪/填充的最大音频长度(以秒为单位)。
  • n_fft (int,可选,默认为 400) — 傅里叶变换的大小。
  • padding_value (float,可选,默认为 0.0) — 用于填充原始音频的填充值。
  • dither (float, 可选,默认为 0.0) — 如果非零,则向每个 STFT 帧添加高斯噪声(std = dither)。
  • return_attention_mask (bool,可选,默认为 True) — 是否返回与填充后的 mel 帧对应的注意力掩码。
  • n_window (int,可选,默认为 50) — 用于填充的梅尔帧块大小的一半。对数梅尔时间轴会向右填充至 2 * n_window 的整数倍。
  • min_length (int,可选,默认值为 8000) — 每个音频片段的最小样本数。短于该长度的片段将进行零填充,以匹配原始 Qwen3-ASR 库的行为。

构建 Qwen3 ASR 特征提取器。

从原始语音中提取 128 维的 log-mel 特征,然后将 mel 时间轴右侧填充至 2 * n_window 的整数倍。

__call__

< >

( raw_speech: numpy.ndarray | list[float] | list[numpy.ndarray] | list[list[float]]truncation: bool = Falsepad_to_multiple_of: int | None = Nonereturn_tensors: str | None = 'pt'return_attention_mask: bool | None = Nonepadding: str | None = 'max_length'max_length: int | None = Nonesampling_rate: int | None = Nonen_window: int | None = Nonedevice: str | None = 'cpu'**kwargs )

参数

  • raw_speech (np.ndarray、list[float]、list[np.ndarray]、list[list[float]]) — 需要填充的序列或序列批次。仅支持单声道音频。
  • pad_to_multiple_of (int, optional) — 如果设置,则将原始音频填充为该值的整数倍(以采样点为单位)。这与 n_window 不同,后者应用于 mel 帧轴。
  • n_window (int, 可选) — 覆盖该实例在此调用中的 n_window。mel 轴会被填充为 2 * n_window 的整数倍。设置为 0 可完全跳过 mel 轴的填充。
  • device (str,可选,默认为 “cpu”) — 用于计算对数梅尔频谱的设备。

从一条或多条音频序列中准备 log-mel 特征。

Qwen3ASRProcessor

class transformers.Qwen3ASRProcessor

< >

( feature_extractor = Nonetokenizer = Nonechat_template = Nonetimestamp_segment_time: float = 80 )

参数

  • feature_extractor(Qwen3ASRFeatureExtractor)— 特征提取器是必需的输入。
  • tokenizer (Qwen2Tokenizer) — 分词器是必需的输入。
  • chat_template (str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
  • timestamp_segment_time (float,可选) — 每个时间戳类别对应的毫秒数。默认值为 80 ms。

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

Qwen3ASRProcessor 提供了 Qwen3ASRFeatureExtractor 和 Qwen2Tokenizer 的全部功能。有关更多信息,请参阅 ~Qwen3ASRFeatureExtractor 和 ~Qwen2Tokenizer。

__call__

< >

( text: str | list[str]audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']]output_labels: bool | None = False**kwargs: *<class 'transformers.models.qwen3_asr.processing_qwen3_asr.Qwen3ASRProcessorKwargs'> ) → 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_features、input_features_mask)的字典。

apply_transcription_request

< >

( audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], list[typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']]]]language: str | list[str] | None = Noneprompt: str | list[str] | None = Nonetranscription: str | list[str] | None = Nonetokenize: bool = True**kwargs: *<class 'transformers.models.qwen3_asr.processing_qwen3_asr.Qwen3ASRProcessorKwargs'> ) → [BatchFeature] or list[str]

参数

  • audio (AudioInput 或 list[AudioInput]) — 要转录的音频。可以是 URL 字符串、本地路径、numpy 数组,或这些类型的列表。
  • language (str 或 list[str],可选) — 用于强制指定转写语言。接受完整语言名称(例如 "English"、"Chinese")或 ISO 语言代码(例如 "en"、"zh")。 如果传入列表,其长度必须与音频批次相同。 遵循原始实现,通过在生成提示后附加 language <NAME><asr_text> 来强制指定语言,从而使模型仅生成转写文本。当 None 时,模型将执行自动语言检测,并自行输出 language <NAME><asr_text>...。
  • prompt (str 或 list[str],可选) — 作为系统提示词包含的上下文/热词,例如用于引导转录结果的领域特定词汇或短语。如果传入列表,其长度必须与音频批次相同。当值为 None 时,系统提示词保持为空。
  • transcription (str 或 list[str],可选) — 用于训练的目标转录文本,每个音频对应一个。提供时,每个转录文本将作为助手轮次写入,并返回 labels(参见 [~Qwen3ASRProcessor.call] 中的 output_labels)。 如果指定了 language,转录文本前会添加 language <NAME><asr_text> 前缀,以匹配模型的输出格式。如果未指定,则按原样写入,因此它本身应已处于该格式,以保持预训练行为。
  • tokenize (bool,可选,默认为 True) — 是否对提示词进行分词并处理音频。如果为 False,则不会加载音频,提示词将以字符串形式返回,其中包含未展开的音频占位符。将这些提示词与音频一起传递给处理器,即 processor(text=prompts, audio=audio),其输出结果与 tokenize=True 时相同。
  • **kwargs — 转发给 [~Qwen3ASRProcessor.apply_chat_template] 的额外关键字参数。 处理器关键字参数(例如 text_kwargs、audio_kwargs、……)应通过 processor_kwargs={…} 传递。

返回值

[BatchFeature] 或 list[str]

当 tokenize=False 时,每个音频对应一个提示;否则,处理器输出可直接传入 [Qwen3ASRForConditionalGeneration.generate] 的内容,或在给定 transcription 时传入 [Qwen3ASRForConditionalGeneration.forward] 以计算损失。

在无需手动编写聊天模板的情况下,为自动语音识别准备输入,用于推理,或在给定 transcription 时用于训练。

prepare_forced_aligner_inputs

< >

( audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']]transcript: str | list[str]language: str | list[str] | None = None**kwargs ) → tuple[BatchFeature, list[list[str]]]

参数

  • audio (AudioInput) — 音频输入。接受路径、URL、numpy 数组,或这些类型的列表。
  • transcript (str 或 list[str]) — 用于与音频进行对齐的转录文本。
  • language (str、list[str] 或 None,可选) — 语言提示。目前在分词过程中未使用,但为特定语言的分词器(例如日语、韩语)保留。
  • **kwargs — 转发给 [~Qwen3ASRProcessor.apply_chat_template] 的额外关键字参数。

返回值

tuple[BatchFeature, list[list[str]]]

  • inputs:一个 [BatchFeature],包含 input_ids、attention_mask、input_features 和 input_features_mask,可直接用于强制对齐模型。
  • word_lists:一个列表(每个样本对应一个),包含用于构建输入的单词级 token 列表。将这些列表传入 [~Qwen3ASRProcessor.decode_forced_alignment],以将时间戳与单词配对。

为强制对齐器模型准备输入。

decode_forced_alignment

< >

( logitsinput_idsword_lists: listtimestamp_token_id: inttimestamp_segment_time: float | None = None ) → list[list[dict]]

参数

  • logits(形状为 (batch_size, seq_len, num_labels) 的 torch.Tensor)— 来自 [Qwen3ASRForTokenClassification] 的分类 logits。
  • input_ids(形状为 (batch_size, seq_len) 的 torch.LongTensor)— 用于前向传播的输入 token ID。
  • word_lists (list[list[str]]) — 由 [~Qwen3ASRProcessor.prepare_forced_aligner_inputs] 返回的单词级 token 列表。
  • timestamp_token_id (int) — <timestamp> 标记的 Token ID(来自 model.config.timestamp_token_id)。
  • timestamp_segment_time (float,可选) — 每个时间戳类别对应的毫秒数。如果未提供,则使用 self.timestamp_segment_time。

返回值

list[list[dict]]

每个样本对应一个列表。每个内部列表包含字典,其键为 "text"(str)、"start_time"(float,单位:秒)和 "end_time"(float,单位:秒)。

将强制对齐器模型的输出解码为词级时间戳。

decode

< >

( *argsreturn_format = 'raw'**kwargs )

参数

  • return_format (str, 可选, 默认为 “raw”) — 选项:
    • "raw":从分词器返回原始解码后的字符串。
    • "parsed":返回一个字典(或字典列表),其中包含 "language" 和 "transcription" 键。
    • "transcription_only":仅提取转录文本(<asr_text> 之后的内容)。

    skip_special_tokens 在 "parsed" 和 "transcription_only" 模式下被硬性设置为 True。

将参数传递给分词器的 decode,并可选地解析 ASR 输出。

Qwen3 ASR 输出的转录格式为:language <LANG><asr_text>transcribed text

Qwen3ASREncoder

class transformers.Qwen3ASREncoder

< >

( config: Qwen3ASREncoderConfig )

参数

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

Qwen3 ASR 的音频模型,顶部未添加任何分类头或投影层。

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

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

forward

< >

( input_features: Tensorinput_features_mask: Tensor**kwargs ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

Qwen3ASREncoder 的 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 之后的权重,用于在自注意力头中计算加权平均值。

Qwen3ASRModel

class transformers.Qwen3ASRModel

< >

( config: Qwen3ASRConfig )

参数

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

Qwen3ASR 模型(经过微调的 Whisper 编码器、多模态投影器、Qwen2 语言模型), 不包含语言建模头。

该模型继承自 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] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Qwen3ASRModelOutputWithPast 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),可选) — 与输入音频特征对应的张量。可以使用 Qwen3ASRFeatureExtractor 获取音频特征。有关详细信息,请参阅 Qwen3ASRFeatureExtractor.call()(Qwen3ASRProcessor 使用 Qwen3ASRFeatureExtractor 来处理音频)。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 用于避免对填充特征索引执行注意力机制的掩码。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • 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(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回值

Qwen3ASRModelOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

get_audio_features

< >

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

参数

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

此方法用于从输入特征(对数梅尔频谱图)中获取音频嵌入。

  • 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 之后的权重,用于在自注意力头中计算加权平均值。

get_placeholder_mask

< >

( input_ids: LongTensorinputs_embeds: Tensoraudio_features: Tensor )

从 input_ids 或 inputs_embeds 中获取多模态占位符掩码,并检查占位符 token 的数量是否等于多模态特征的长度。如果长度不一致,则会引发错误。

Qwen3ASRForConditionalGeneration

类 transformers.Qwen3ASRForConditionalGeneration

< >

( config: Qwen3ASRConfig )

参数

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

由音频编码器和语言模型组成的 Qwen3ASR 模型。

该模型继承自 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] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Qwen3ASRCausalLMOutputWithPast 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),可选) — 与输入音频特征对应的张量。可以使用 Qwen3ASRFeatureExtractor 获取音频特征。有关详细信息,请参阅 Qwen3ASRFeatureExtractor.call()(Qwen3ASRProcessor 使用 Qwen3ASRFeatureExtractor 来处理音频)。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 用于避免对填充特征索引执行注意力机制的掩码。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • 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(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选)— 用于计算掩码语言建模损失的标签。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。

返回值

Qwen3ASRCausalLMOutputWithPast 或 tuple(torch.Tensor)

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

Qwen3ASRForConditionalGeneration 的 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 Qwen3ASRForConditionalGeneration, AutoProcessor

>>> model_id = "Qwen/Qwen3-ASR-1.7B-hf"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = Qwen3ASRForConditionalGeneration.from_pretrained(model_id, device_map="auto")

get_audio_features

< >

( input_featuresinput_features_mask**kwargs )

Qwen3ASRForTokenClassification

class transformers.Qwen3ASRForTokenClassification

< >

( config )

参数

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

带有用于时间戳预测(强制对齐)的 token 分类头的 Qwen3 ASR 模型。

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

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

forward

< >

( input_ids: torch.LongTensor | None = Noneattention_mask: torch.Tensor | None = Noneposition_ids: torch.LongTensor | None = Nonepast_key_values: Cache | None = Noneinputs_embeds: torch.Tensor | None = Nonelabels: torch.LongTensor | None = Noneuse_cache: bool | None = None**kwargs: Unpack[TransformersKwargs] ) → TokenClassifierOutput

参数

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

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

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (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(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选) — 用于计算 token 分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回值

TokenClassifierOutput

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

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

Update on GitHub