FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
fix(speech): bound Whisper model metadata allocations (#2866)
Earl Coda691ce78ab1
diff --git a/crates/speech/src/whisper/mod.rs b/crates/speech/src/whisper/mod.rsindex 6a602bce1..b84c82e9c 100644--- a/crates/speech/src/whisper/mod.rs+++ b/crates/speech/src/whisper/mod.rs@@ -43,6 +43,8 @@ const N_FRAMES: usize = 3000;const FRAMES_PER_TS: usize = 2;const SAMPLES_PER_FRAME: usize = crate::mel::HOP;const MAX_TOKENS: usize = 224;+/// More than the total alignment heads in any published Whisper architecture.+const MAX_ALIGNMENT_HEADS: usize = 4_096;fn merr(e: candle_core::Error) -> SpeechError {SpeechError::Model(e.to_string())@@ -66,11 +68,7 @@ impl Whisper {let gen_cfg: serde_json::Value = serde_json::from_slice(&read("generation_config.json")?).unwrap_or_default();let tok = Tokenizer::from_json(&String::from_utf8_lossy(&read("tokenizer.json")?))?;let weights = read("model.safetensors")?;- let alignment_heads = gen_cfg["alignment_heads"]- .as_array()- .map(|a| a.iter().filter_map(|p| Some((p[0].as_u64()? as usize, p[1].as_u64()? as usize))).collect::<Vec<_>>())- .filter(|v| !v.is_empty())- .unwrap_or_else(|| (cfg.decoder_layers / 2..cfg.decoder_layers).flat_map(|l| (0..cfg.decoder_attention_heads).map(move |h| (l, h))).collect());+ let alignment_heads = alignment_heads(&cfg, &gen_cfg)?;let mut suppress: Vec<u32> =gen_cfg["suppress_tokens"].as_array().map(|a| a.iter().filter_map(|x| x.as_u64().map(|v| v as u32)).collect()).unwrap_or_default();suppress.extend(tok.non_text_specials());@@ -193,6 +191,34 @@ impl Whisper {}}+fn alignment_heads(cfg: &Config, generation: &serde_json::Value) -> Result<Vec<(usize, usize)>, SpeechError> {+ let bad = |message: &str| SpeechError::Model(format!("generation_config.json: {message}"));+ if let Some(values) = generation["alignment_heads"].as_array().filter(|values| !values.is_empty()) {+ if values.len() > MAX_ALIGNMENT_HEADS {+ return Err(bad("too many alignment heads"));+ }+ return values+ .iter()+ .map(|pair| {+ let layer =+ pair.get(0).and_then(serde_json::Value::as_u64).and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("invalid alignment head"))?;+ let head =+ pair.get(1).and_then(serde_json::Value::as_u64).and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("invalid alignment head"))?;+ if layer >= cfg.decoder_layers || head >= cfg.decoder_attention_heads {+ return Err(bad("alignment head is outside the decoder architecture"));+ }+ Ok((layer, head))+ })+ .collect();+ }+ let first_layer = cfg.decoder_layers / 2;+ let count = cfg.decoder_layers.saturating_sub(first_layer).checked_mul(cfg.decoder_attention_heads).ok_or_else(|| bad("alignment-head count overflow"))?;+ if count > MAX_ALIGNMENT_HEADS {+ return Err(bad("alignment-head fallback is too large"));+ }+ Ok((first_layer..cfg.decoder_layers).flat_map(|layer| (0..cfg.decoder_attention_heads).map(move |head| (layer, head))).collect())+}+fn softmax_at(x: &[f32], i: usize) -> f32 {let m = x.iter().copied().fold(f32::NEG_INFINITY, f32::max);let s: f32 = x.iter().map(|v| (v - m).exp()).sum();@@ -335,6 +361,27 @@ impl Transcriber for Whisper {mod tests {use super::*;+ fn config(layers: usize, heads: usize) -> Config {+ Config {+ num_mel_bins: 80,+ d_model: 384,+ encoder_layers: 4,+ encoder_attention_heads: 6,+ decoder_layers: layers,+ decoder_attention_heads: heads,+ max_source_positions: 1_500,+ max_target_positions: 448,+ vocab_size: 51_865,+ }+ }++ #[test]+ fn fallback_alignment_heads_are_bounded_before_collection() {+ let error = alignment_heads(&config(usize::MAX, usize::MAX), &serde_json::Value::Null).unwrap_err();+ assert!(error.to_string().contains("alignment-head"));+ assert_eq!(alignment_heads(&config(4, 6), &serde_json::Value::Null).unwrap().len(), 12);+ }+#[test]fn repetition_guard() {let tb = 1000;diff --git a/crates/speech/src/whisper/tokenizer.rs b/crates/speech/src/whisper/tokenizer.rsindex 2fa024b22..aaaa93b9c 100644--- a/crates/speech/src/whisper/tokenizer.rs+++ b/crates/speech/src/whisper/tokenizer.rs@@ -9,6 +9,9 @@ use std::collections::HashMap;use crate::SpeechError;+/// Generous ceiling above every published Whisper vocabulary, before allocating a dense id table.+const MAX_VOCAB_ID: u64 = 1_000_000;+pub struct Tokenizer {/// Bytes of each regular token, by id.bytes: Vec<Vec<u8>>,@@ -48,7 +51,11 @@ impl Tokenizer {let v: serde_json::Value = serde_json::from_str(json).map_err(|e| bad(&e.to_string()))?;let vocab = v["model"]["vocab"].as_object().ok_or_else(|| bad("no model.vocab"))?;let table = unicode_to_byte();- let max = vocab.values().filter_map(|x| x.as_u64()).max().unwrap_or(0) as usize;+ let max = vocab.values().filter_map(|x| x.as_u64()).max().unwrap_or(0);+ if max > MAX_VOCAB_ID {+ return Err(bad("vocab id is too large"));+ }+ let max = usize::try_from(max).map_err(|_| bad("vocab id is too large"))?;let mut bytes = vec![Vec::new(); max + 1];for (tok, id) in vocab {let id = id.as_u64().ok_or_else(|| bad("vocab id"))? as usize;@@ -118,6 +125,21 @@ impl Tokenizer {}}+#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn sparse_huge_vocab_id_is_rejected_before_allocation() {+ let json = format!(r#"{{"model":{{"vocab":{{"x":{}}}}},"added_tokens":[]}}"#, MAX_VOCAB_ID + 1);+ let error = match Tokenizer::from_json(&json) {+ Err(error) => error,+ Ok(_) => panic!("huge sparse vocabulary was accepted"),+ };+ assert!(error.to_string().contains("vocab id is too large"));+ }+}+/// Group text tokens into words: a token whose text starts with a space starts a new word;/// punctuation-only tokens join the word before them (opening quotes/brackets the word after)./// Returns (word text, token index range).