asr
asr is Whisper, OpenAI's speech-to-text model, written in Agentica for inference. It turns audio into text, with timed segments. Audio over 30 seconds is read in windows of 30 seconds.
Example #
Transcribe one clip in Spanish. The folder whisper-tiny holds model.safetensors, config.json and tokenizer.json, from a Hugging Face Whisper checkpoint. The samples are a List[Float32] of 16 kHz mono floats: one channel, 16 000 samples per second. You can read them with Whisper.load from the whisper package, which uses Wav.load from its wav module.
import Asr from "pkg/asr/asr"
import Tensor from "pkg/tensor/tensor"
import Tokenizer from "pkg/asr/tokenizer"
def transcribe_file(pcm: List[Float32]) -> Result[Void]
backend = Tensor.Backend.Reference
model = try Asr.open("whisper-tiny/model.safetensors", backend)
tok = try Tokenizer.open("whisper-tiny/tokenizer.json")
options = Asr.Options(language: some("es"), timestamps: true)
t = try Asr.transcribe(model, tok, pcm, options)
puts(t.text)
puts(t.language)
for s in t.segments
puts("#{s.start} #{s.stop} #{s.text}")
end
ok()
end
def main() -> Void
transcribe_file([0.0]).unwrap!
endMain API #
Asr.open(path, backend, weights)loads a.safetensorsfile, or the.index.jsonof a sharded one, with theconfig.jsonin its folder. Withweights: Dtype.F16the big dense matrices and the token table (also the tied output head) are kept as half weights on ggml, which halves the weights' memory; whisper-tiny gains little (see the hub page and the benchmarks).F32is the default and the exact path, and Vulkan multiplies in fp16 by default (Tensor.vulkan_fp16), which breaks token-exactness against Hugging Face withF32weights too:Tensor.vulkan_fp16(false)before the first ggml call makes it exact, as the checks of this package do.Asr.close_model(model)frees the weights and the log-mel plan now, as a server does when it replaces a model. Using the model afterwards is an error, and a second call changes nothing.Asr.config(path)reads theconfig.jsonof a checkpoint as aConfig: the sizes, head counts and position limits the forward needs, and the suppressed token lists.Asr.load(checkpoint, config, backend, weights)makes the model from a checkpoint fromHub.openand aConfig.opendoes both.Asr.transcribe(model, tok, pcm, options)runs the whole pipeline on one clip and gives aResultofTranscript.Asr.features(model, pcm, frames)gives the log-mel ofpcmas a[1, num_mel_bins, frames]F32tensor on the model's backend. The caller closes it.Tokenizer.open(path)reads atokenizer.json. The tokenizer decodes ids to text; it does not encode text.Tokenizer.decode(tok, ids)gives the text of the ids. Special and timestamp tokens give no text, and a character split across tokens joins back.Tokenizer.prompt(tok, language, job, timestamps)gives the ids that start the decoder.languageisnoneor a code, andjobisTokenizer.Job.TranscribeorTokenizer.Job.Translate.Tokenizer.language_id(tok, code)gives the id of a language, andTokenizer.seconds(tok, id)the time of a timestamp token in seconds, or none for another id.Tokenizer.parse(text)reads the text of atokenizer.jsoninstead of a path.
Asr.encode(model, mel)andAsr.decode(model, tokens, audio)are the model's forward passes (one run of the network), for callers who want the parts.Asr.listen,Asr.step,Asr.step_pickand theCachethey use decode one token at a time. The cache is a KV cache: it keeps the past keys and values, so earlier tokens are not computed again, and itslengthcounts the tokens so far.Asr.stepgives aStepped, with the logits of the last token and the new cache;Asr.step_pick(model, cache, ids, mask)addsmaskto them (0 for an id that may be emitted, a very negative number for one that may not) and gives the first largest id and its log-probability as aPicked; withstamps, anAsr.Stamps(rules, state), it applies Whisper's timestamp rules in the graph too:rulesare theGreedy.Rules, andstateisGreedy.state(rules, emitted)as an F32 tensor of 4 on the model's backend, made for each step and closed by the caller.
Asr.Options has these fields:
language, anOptional[String]such assome("es").none, the default, detects the language.translate, defaultfalse: translate to English instead of transcribing.timestamps, defaulttrue: timestamp tokens, which give the segments. On ggml the next token is chosen on the device, with or without the timestamp rules, and only its id and log-probability come back.max_tokens, anOptional[Int].none, the default, decodes up to the model'smax_target_positions. For audio over 30 s it applies to each window.max_windows, anOptional[Int], for audio over 30 s: at most that many windows.none, the default, is2 * ceil(frames / window) + 2, which audio that seeks normally never reaches, so a model that hallucinates and never advances is stopped.
Asr.Transcript has these fields:
text, the text.languageandlanguage_probability, the language and its probability.tokens, the ids after the prompt, without the end-of-text token.segments, a list ofGreedy.Segment, each withstartandstopin seconds,text,tokensandavg_logprob.avg_logprobandno_speech_prob, as OpenAI's Whisper reports them.truncated,falseunlessmax_windowsran out before the end of the audio.
Greedy rules #
pkg/asr/greedy has the rules of greedy decoding over plain lists. Use it for a loop of your own over step_pick:
Greedy.rules(tok, suppress, begin_suppress, timestamps)makes theRulesfor a tokenizer.suppressandbegin_suppressare the config's lists, ornonefor the defaults.timestamps: falseturns the timestamp rules off.Greedy.mask(rules, size, first)gives aList[Float]of the scores of astep_pickmask: 0 for an id that may come,Greedy.FORBIDDENfor one that may not. Turn it into the F32[vocab_size]tensor thatAsr.step_picktakes, withTensor.from_list.Greedy.state(rules, emitted)gives the four numbers thatAsr.Stampstakes.Greedy.allowed(rules, logits, emitted)applies the rules to a list of logits, andGreedy.pick(logits)gives the first largest id.Greedy.segments(tok, emitted, duration, avg_logprob)makes theSegments of emitted ids.Greedy.window(tok, emitted, frames, avg_logprob)also gives the ids to keep and how many 10 ms frames the next window advances.Greedy.probability(logits, i)andGreedy.log_probability(logits, i)score one id of a list of logits.
Frontend #
pkg/asr/mel is the log-mel frontend:
Mel.log_mel(samples, mels, frames)takes aList[Float32]and gives the log-mel as a flatList[Float32], row-major[mels, frames], computed with an exact FFT in doubles and rounded toFloat32once at the end.framesdefaults to 3000, which is 30 s. Non-finite samples are errors.Mel.spectrogram(samples, mels, frames, backend)is the same computation as one traced graph on any backend. In F32 it is about 1e-5 fromlog_mel.Mel.featurespicks between them:Referencegetslog_mel, and every other backend the graph.Asr.featurescalls it.
Limits #
- Audio over one window (30 s of 16 kHz audio for Whisper's checkpoints; a window is the chunk the model takes in one pass) needs
timestamps: true, the default. It is read as OpenAI'stranscribeand Hugging Face's long-formgenerate(withtruncation=Falsefeatures) do: each window starts where the last timestamp of the one before said its segments end, with no previous text in the prompt, and the language is the first window's. For such audio:- the segments' times count from the start of the audio, and a segment with no text is left out;
tokensare the ids of the segments of every window, each window with its own timestamps;language_probabilityandno_speech_probare the first window's, andavg_logprobcovers all the windows;max_tokensapplies to each window;- a window whose timestamps would seek by zero is done instead, so it always advances;
- at most
max_windowswindows are decoded (seeOptions), andtruncatedsays when that stopped the transcript short.
- Decoding is greedy: at each step it takes the most likely token (temperature 0). It follows OpenAI's rules for suppressed tokens and timestamps. There is no beam search (a search that keeps several candidate outputs).
- The samples must be mono 16 kHz floats. The frontend, the part that turns audio into the model's input, does not resample (change the sample rate).
Tokenizer.vocab_sizemust equal the model'svocab_size, ortranscribeis an error.
How it works #
asr loads a Hugging Face checkpoint. Then it runs the log-mel frontend (it turns audio into log-mel features, the model's input; on ggml and libtorch it is one graph of tensor ops), the encoder and greedy decoding. It depends on tensor, nn and hub.
asr runs on the reference backend, on libtorch and on ggml (CPU and Vulkan). See the tensor page for the backends.
A window is 2 * max_source_positions frames of 160 samples. For Whisper's checkpoints that is 30 seconds of 16 kHz audio.
tools/transcribe_check.agc compares the cases of test/fixtures/transcribe_golden.json with a real whisper-tiny checkpoint. It is run by hand, not by the tests. Against Hugging Face's generate on whisper-tiny, the token ids match.
Speed #
The benchmarks folder times whisper-tiny against whisper.cpp on one machine, with the same weights, clips and threads. On the CPU the encoder is on par. The gap is in the decoder step and the load.
- Design asr — design