AI Wiki中文/EN

Whisper:结构、任务token与解码边界

Whisper

连接弱监督与编码器—解码器设计,核对固定前端、任务格式及长音频失败控制。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

它写得很像一句话,就一定有人说过吗?

一段背景噪声之后,识别器输出了一句语法完整的文字。流畅性不能证明这句话存在于声音中:编码器—解码器同时利用声学证据和已生成的文本,弱声学证据下仍可能生成合理但错误的续写。Whisper模型卡承认未说出文字和重复输出等失败模式,并将部分原因作为作者假设,而不是已被证明的唯一机制。模型卡的限制

Whisper是一组以大规模弱监督音频—文本对训练的编码器—解码器模型。原论文报告约680,000小时的多语、多任务监督,研究在不为每个评价数据集单独微调时的迁移能力。这个“zero-shot”评价设置不自动保证任意语言、设备和场景同样可靠,也不应被理解为对所有训练数据重叠问题的证明。训练与评价范围

本篇解释模型、任务token、前端数值和长音频解码,再用小程序检查其中几条容易混淆的契约。程序没有Whisper权重,不从声音识别文字;它接受已有Mel功率和合成解码诊断,帮助读者理解真实系统为何需要这些条件。

给定Mel功率揭示地板与尺度约定;时间几何和供给诊断用于解释边界,不运行语音模型。重置仅在尝试选中且片段保留后适用。
给定Mel功率揭示地板与尺度约定;时间几何和供给诊断用于解释边界,不运行语音模型。重置仅在尝试选中且片段保留后适用。

一段音频,多种条件化输出

原版将音频按30秒窗口处理。16kHz声音使用25ms窗、10ms步长构造80带Mel输入;先经过两层宽度3、带GELU的卷积,其中第二层以步长2减少时间位置,再进入Transformer编码器。解码器通过交叉注意力读取编码器,并按已有输出自回归预测下一token。原论文还区分编码器的正弦位置与解码器的学习位置表示。结构图及前端

目标序列不仅含文字,也含语言、任务和时间戳等特殊token。模型可条件于前一窗口的文本;论文说明此前文部分不计训练损失,其余目标参与预测。用II表示参与损失的位置,可把这一思想写成:

L=−∑i∈Ilog⁡Pθ(yi∣X,y<i),I={positions outside supplied previous context}.\mathcal L=-\sum_{i\in I}\log P_\theta(y_i\mid X,y_{<i}),\qquad I=\{\text{positions outside supplied previous context}\}.

此处表达的是遮掉前文损失的条件化目标,不声称给出训练代码全部归一化和任务权重。它不同于CTC按帧独立输出再折叠,也不同于RNN-T的二维blank网格;Whisper按文字/特殊token序列预测。时间戳是输出格式的一部分,不是由该公式自动获得精确对齐。

多语转写的前缀可包含startoftranscript、输入语言、transcribe;translate表示翻译到英语,不是把语言token改成任意目标语。省略时间戳时追加notimestamps。固定tokenizer实现将这些符号转换为实际词表ID,本例只展示符号名称与en/zh/es教学子集,不是完整BPE或全部支持语言。前缀构造

前端也有版本和尺度。论文使用log-magnitude措辞,所查固定audio.py实际先计算STFT模平方,再乘保存的Mel滤组:

Pb,t=∑kBb,k∣Xk,t∣2.P_{b,t}=\sum_k B_{b,k}|X_{k,t}|^2.

这是原始FFT功率路径,不能直接换成另一篇教学程序中除以FFT长度、将内部单边频点翻倍的能量。仓库允许80或128带滤组,必须与所加载模型的输入配置相匹配;这不意味着原论文的所有模型都用128带。固定前端实现

设输入Mel功率为PP,固定代码的后处理依次为绝对地板、全矩阵峰值下8个十进制数量级的地板,以及仿射变换:

q=log⁡10max⁡(P,10−10),r=max⁡(q,max⁡(q)−8),F=(r+4)/4.q=\log_{10}\max(P,10^{-10}),\qquad r=\max(q,\max(q)-8),\qquad F=(r+4)/4.

所有max除峰值外均逐元素计算。功率[10⁻¹²,10⁻⁴,1,100]得到[−0.5,0,1,1.5],全静音得到−1.5;因此论文所述大致−1至1的尺度不是代码硬裁剪。峰值还会耦合同一处理矩阵中的帧:功率10⁻⁸单独处理为−1,与功率100的一帧共同处理则变成−0.5。地板与缩放

时间几何可以直接核算。固定30秒、16kHz窗口与160样本步长对应以下数量,第二卷积再将时间位置减半:

N=30×16000=480000,TMel=N/160=3000,Tenc=1500,Δt=320/16000=0.02 s.N=30\times16000=480000,\qquad T_{\mathrm{Mel}}=N/160=3000,\qquad T_{\mathrm{enc}}=1500,\qquad \Delta t=320/16000=0.02\ \mathrm{s}.

20ms是时间戳网格精度,不是识别边界误差上界。原论文按模型预测时间戳移动长音频窗口,而不是把任何音频按任意固定长度切开后拼接。错误前文可能影响后面的输出。时间格式与长音频

长音频实现使用多项启发式。令ℓ\ell为平均log概率,ss为no-speech概率,cc为压缩比,固定默认阈值下的重试条件为:

R=(ℓ<−1 ∨ c>2.4) ∧ ¬(s>0.6 ∧ ℓ<−1).R=(\ell<-1\ \lor\ c>2.4)\ \land\ \neg(s>0.6\ \land\ \ell<-1).

低log概率或重复性高会触发重试,但明显无语音且log概率低时取消重试。跳过片段则是另一条条件;固定实现只有严格高于−1的log概率才解除no-speech跳过,所以等号处不能混用:

S=(s>0.6)∧(ℓ≤−1),reset=(¬S)∧(¬usePrevious ∨ τ>0.5).S=(s>0.6)\land(\ell\le-1),\qquad \mathrm{reset}=(\neg S)\land(\neg\mathrm{usePrevious}\ \lor\ \tau>0.5).

τ\tau是本次温度。skip分支先继续下一窗口,不执行后面的前文重置;未跳过片段才检查温度与配置。论文用低于0.5描述前文条件,固定代码在大于0.5时重置,正文按具体实现保留这个等号区别。这些阈值是解码策略,不是“这句话必然正确”的概率证明。重试、跳过与前文状态

运行可核验的契约,不冒充模型推理

完整Python/NumPy程序计算给定80/128带、1—64帧Mel功率的后处理;生成有限语言子集的符号前缀;将给定时间量化到20ms网格;对供给的解码诊断选择尝试。时间平分点取最近偶数是本例量化约定,不是声学模型的预测。压缩比和log概率都是合成输入,没有实际压缩文本或执行解码器。

"""Whisper numerical input and decoding-policy contracts, without model weights.

Given Mel power and synthetic decoder diagnostics. Not waveform inference, BPE,
a Transformer implementation, or a measurement of transcription quality.
"""
import json
import numpy as np


def normalize_mel(power):
    raw=np.asarray(power)
    if np.iscomplexobj(raw):raise ValueError('Real Mel power required')
    x=np.asarray(raw,float)
    if x.ndim!=2 or x.shape[0] not in (80,128) or not 1<=x.shape[1]<=64 or not np.isfinite(x).all() or (x<0).any() or (x>1e12).any():raise ValueError('Use80 or128 bands,1–64 frames, finite powers0–1e12')
    logs=np.log10(np.maximum(x,1e-10));peak=float(logs.max());floored=np.maximum(logs,peak-8)
    return dict(features=((floored+4)/4).tolist(),log_peak=peak,dynamic_floor=peak-8)


def prefix(language='en',task='transcribe',timestamps=False):
    if language not in ('en','zh','es') or task not in ('transcribe','translate') or type(timestamps) is not bool:raise ValueError('Teaching subset: en/zh/es; transcribe/translate; boolean timestamps')
    result=['<|startoftranscript|>',f'<|{language}|>',f'<|{task}|>']
    if not timestamps:result.append('<|notimestamps|>')
    return result


def timestamp_grid(seconds):
    raw=np.asarray(seconds)
    if np.iscomplexobj(raw):raise ValueError('Real times required')
    x=np.asarray(raw,float)
    if x.ndim!=1 or not 1<=len(x)<=32 or not np.isfinite(x).all() or (x<0).any() or (x>30).any():raise ValueError('Use1–32 segment-relative times within0–30seconds')
    ticks=np.rint(x/.02).astype(int);values=ticks*.02
    return dict(ticks=ticks.tolist(),seconds=values.tolist(),error=(values-x).tolist(),rounding='nearest, midpoint ties to even; a teaching quantizer, not model predictions')


def decision(avg_logprob,no_speech_prob,compression_ratio,temperature=0.,condition_on_previous=True):
    values=[avg_logprob,no_speech_prob,compression_ratio,temperature]
    if any(isinstance(v,bool) or not isinstance(v,(int,float)) for v in values) or not np.isfinite(values).all() or not -100<=avg_logprob<=0 or not 0<=no_speech_prob<=1 or not 0<=compression_ratio<=100 or not 0<=temperature<=1 or type(condition_on_previous) is not bool:raise ValueError('Invalid bounded decoder diagnostics')
    low=avg_logprob< -1.;silent=no_speech_prob>.6;repetitive=compression_ratio>2.4
    retry=(low or repetitive) and not (silent and low)
    # Pinned implementation uses > to cancel skipping, so equality at -1 matters.
    skip=silent and not (avg_logprob> -1.)
    return dict(retry=retry,skip=skip,reset_prompt=(not skip) and ((not condition_on_previous) or temperature>.5),low_logprob=low,high_no_speech=silent,repetitive=repetitive)


def select_attempt(attempts,condition_on_previous=True):
    if not isinstance(attempts,(list,tuple)) or not 1<=len(attempts)<=6:raise ValueError('Supply1–6 synthetic attempt records')
    trace=[]
    for i,row in enumerate(attempts):
        if not isinstance(row,dict) or set(row)!={'avg_logprob','no_speech_prob','compression_ratio'}:raise ValueError('Three named decoder diagnostics required')
        temperature=i*.2;state=decision(**row,temperature=temperature,condition_on_previous=condition_on_previous);trace.append(dict(attempt=i,temperature=temperature,**state))
        if not state['retry']:break
    # A short supplied schedule is an explicit teaching configuration.
    return dict(selected=len(trace)-1,trace=trace,exhausted=bool(trace[-1]['retry']),skip=trace[-1]['skip'],reset_prompt=trace[-1]['reset_prompt'])


def demo():
    power=np.tile([1e-12,1e-4,1.,100.],(80,1));normal=normalize_mel(power);quiet=np.full((80,1),1e-8);loud=np.full((80,1),100.)
    attempts=[dict(avg_logprob=-2.,no_speech_prob=.2,compression_ratio=3.),dict(avg_logprob=-.5,no_speech_prob=.2,compression_ratio=1.2)]
    return dict(input_power_first_band=power[0].tolist(),normalized_first_band=normal['features'][0],log_peak=normal['log_peak'],dynamic_floor=normal['dynamic_floor'],silence_first_band=normalize_mel(np.zeros((80,2)))['features'][0],
                context=dict(quiet_alone=normalize_mel(quiet)['features'][0],quiet_with_loud=normalize_mel(np.hstack([quiet,loud]))['features'][0]),
                prefixes=dict(transcribe=prefix('zh'),translate=prefix('zh','translate'),timestamped=prefix('en',timestamps=True)),timestamps=timestamp_grid([0,.031,1.009,29.999,30]),
                geometry=dict(sample_rate=16000,window_samples=480000,mel_hop=160,mel_frames=3000,encoder_stride=2,encoder_frames=1500,timestamp_seconds=.02),
                attempts=select_attempt(attempts),silent=decision(-2.,.9,3.),confident=decision(-.2,.9,1.),threshold=decision(-1.,.9,1.),exhausted=select_attempt([attempts[0]]*6),prompt_boundary=[decision(-.2,.1,1.,temperature=t) for t in [.5,.6]])


if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))

select_attempt按0、0.2等温度依次检查,遇到无需重试的记录就停止;最多6次,也允许明确给定较短的教学尝试表。若尝试耗尽仍需重试,exhausted=True保留失败状态,不宣称最后一次已成功。no-speech概率高但log概率也高时不跳过;恰在log概率−1时,跳过与重试的判断可能不同。

该后处理的时间和返回存储为O(MT)O(MT),MM为频带数;前缀为常数规模,时间网格O(K)O(K),诊断选择O(A)O(A)。这些不是完整Whisper推理复杂度或速度。真实使用还需要匹配模型、采样率、滤组、tokenizer、解码参数和硬件预算,并用有代表性的音频检验失败条件。

后续型号不能沿用所有原版数字

模型卡按月列出原版2022年9月、large-v2于2022年12月、large-v3于2023年11月、turbo于2024年9月。后续型号并非只改文件名;不能把原论文的数据规模、模型规格和实验结果无条件套到所有版本。所查卡片开头仍写“9 models”,表中却已加入turbo;正文不采用这个过时总数。版本与模型卡

同样,模型卡与论文的部分语言数、翻译小时数不同,本篇只使用明确归属原论文的总体规模,不拼接成伪精确的统一统计。模型卡报告的幻觉、低资源语言及口音差异应作为评测动机;它对成因的解释是作者假设,不能说本例已经验证。

温度回退、beam搜索、no-speech阈值与前文条件可缓解某些问题,但原论文表5的改善并非每个数据集都单调一致。流畅度、平均log概率或重复度都不能代替声音核对。Whisper也不是自动得到可靠说话人身份或任意音频分类的通用保证;本程序没有验证那些用途。

从边界值看清实现

  1. 基本理解。 多语前缀中zh加translate,是翻译成中文吗?

    答案:不是。zh指定输入语言,translate任务表示翻译到英语;输入语言与目标任务是不同槽位。本例只展示符号格式,不执行翻译。

  2. 手算。 固定后处理遇到全零Mel功率,为什么输出−1.5而不是−1?

    答案:绝对地板给出log10值−10,峰值下8的地板更低而不起作用;仿射得到(−10+4)/4=−1.5(−10+4)/4=-1.5。这不是硬限制在[−1,1]。

  3. 边界。 no-speech为0.9、平均log概率恰为−1、压缩比1,是否重试、是否跳过?

    答案:不重试,但跳过。重试检查严格小于−1,取消skip则要求严格大于−1;等号不是同一个分支。

  4. 迁移。 最后一次温度尝试仍重复,能否因为流程结束就认定转写正确?

    答案:不能。尝试耗尽只是策略终止,本例保留exhausted;真实项目需要检查声音、错误样本和回退办法。局部阈值不会证明文字确实被说过。

按版本保留证据,不把局部复算当全模型

ICML2023论文提供结构、任务和长音频脉络;固定2026-08-31提交的audio.py、transcribe.py、tokenizer.py和模型卡支持具体实现与版本说明。未运行上游代码或下载权重。原型采用原创数学与有限诊断,不能证明官方模型兼容、识别准确率、速度或真实时间戳质量。

先判断,再看解释

温度回退尝试耗尽能证明什么?

选择一个答案

学习目标

  • 解释编码器—解码器及多任务目标格式。
  • 区分原论文、后续版本与代码约定。
  • 计算log-Mel地板与时间几何。
  • 检查重试、跳过和前文重置边界,不夸大准确率。

先修与延伸

查看知识关联图 →

参考文献

  1. Robust Speech Recognition via Large-Scale Weak Supervision
    Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever · 2023
  2. Whisper audio preprocessing at commit86098128
    OpenAI Whisper contributors
  3. Whisper transcription fallback and context at commit86098128
    OpenAI Whisper contributors
  4. Whisper task-prefix construction at commit86098128
    OpenAI Whisper contributors
  5. Whisper model card at commit86098128
    OpenAI Whisper contributors

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-13 · Single AI author checked scoped ICML2023 architecture, weak supervision, multitask prefixes and long-form policies alongside pinned2026-08-31 audio.py/transcribe.py/tokenizer.py/model-card sections. Distinguished paper scale wording, actual log-Mel floors, version/month and conflicting card statistics, strict retry/skip equality and conditional prompt reset. Six paired equations and four explained exercises. Original supplied-Mel and diagnostic calculations, not STFT, BPE, model weights, corpus accuracy or latency replication.

  • 检查给定功率特征[-0.5,0,1,1.5]、静音−1.5、前缀语义、帧/时间几何、恰在−1的skip/retry差异、跳过不重置及回退耗尽。
  • 四张计算SVG绑定真实双语程序;本组十一项数值/编码检查、30组语言/宽度及四字体检查通过,AI作者实际查看十张截图。冻结前检查普通正文AST;完整文章页面验收另记,不称人工同行审校。
  • 渲染复核后补英文参考引用前缺失空格,验证严格仅空白变化、公式/程序不变,保留冻结正文与测试;见editorial/corrections/011h-citation-spacing。

核对的来源位置:

  • Robust Speech Recognition via Large-Scale Weak Supervision · Read introduction scope, sections2.2/2.3 and3.2, appendixA.1. Visually inspected pages3 and14 including Table5; no benchmark numbers replicated. Pin the ICML2023 version and distinguish paper wording from repository preprocessing/threshold details.
  • Whisper audio preprocessing at commit86098128 · Read constants, pad/trim excerpt,80/128 filter-bank support and lines133–157 STFT magnitude squared and log/floor/affine processing. Our program starts with supplied Mel power, not waveform/official filter-bank inference. Snapshot2026-08-31; no upstream code execution.
  • Whisper transcription fallback and context at commit86098128 · Read lines196–227 retry,293–310 skip and498–507 context reset. Strict threshold equalities and skip-before-reset preserved. Synthetic diagnostics only; compression and neural decoding not run. Snapshot2026-08-31; no upstream code execution.
  • Whisper task-prefix construction at commit86098128 · Read lines142–159 SOT/language/task sequence and238–240 notimestamps append. Symbolic teaching subset en/zh/es only; no BPE/vocabulary-ID compatibility claim. Snapshot2026-08-31; no upstream code execution.
  • Whisper model card at commit86098128 · Read lines10–34 versions/dates,51 data and56–64 limitations. The nine-model prose is stale relative to the added turbo row; some language/hour statistics differ from the paper. Scope dates by month; causal explanations remain author hypotheses. Snapshot2026-08-31; no upstream code execution.

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。