Phase 03/Alternative engines/Serving multimodal, speech and diffusion models
PHASE 03 · Alternative engines

Serving multimodal, speech and diffusion models

0%
10 h6 subtopics3 lessons · 2 required
In plain English

Not every AI model writes text one word at a time. A vision-language model first turns a picture into hundreds of "image words" before it can answer a question about it, so the hard part is reading the picture, not writing the reply. A speech recognizer like Whisper listens to audio in chunks and must keep up with a person talking live. A text-to-speech model has to start playing sound within a fraction of a second and never fall behind. An image generator runs the same big calculation dozens of times to refine a picture. Think of a restaurant kitchen that also runs a bakery and a juice bar. The ovens, timings and bottlenecks are different for each station, and a manager who only knows how to run the grill will make bad decisions. This topic teaches what changes when the model is not a text chatbot, using small models that run on a laptop or a free GPU.

Why it matters

Inference teams at Fireworks, Perplexity, ElevenLabs and Baseten serve vision-language, audio, embedding and diffusion models next to text LLMs, and the compute shape of each is different. Image prefill is heavy and bursty, streaming audio has hard real-time deadlines, and diffusion is compute-bound with no KV cache at all. Knowing where each workload's bottleneck sits tells you which text-LLM tricks transfer and which do not.

Hiring signal

Fireworks' performance optimization role names LLMs, vision-language models and next-generation video models as the workloads to maximize, and ElevenLabs hires research engineers to build serving systems for real-time streaming audio "where every millisecond matters"; Perplexity asks for bringing up retrieval, text-generation and multimodal models from weight loading through KV-cache management.

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Explain how a vision encoder turns an image into tokens and compute the prefill cost an image adds for a given VLM.
  • Measure the real-time factor of Whisper-class speech recognition and implement chunked, overlapping streaming transcription.
  • Describe the latency budget of streaming text-to-speech and why first-audio latency and underruns, not throughput, are the primary metrics.
  • Explain why diffusion models batch differently from LLMs and measure images per second versus batch size on a small model.
  • Classify each workload as prefill-heavy, decode-heavy, real-time or compute-bound and name the serving optimizations that apply to each.

Key concepts

Vision encoder and projector
A ViT-style encoder turns image patches into embeddings and a projector maps them into the language model's token space; the result is hundreds of image tokens per image.
Image tokens
Placeholder positions in the prompt that are replaced by projected image embeddings; they dominate prefill length for VLMs (for example 64 per 512x512 tile in SmolVLM-256M, 576 for LLaVA-1.5).
Dynamic resolution and tiling
Splitting a large image into tiles each encoded separately, so token count and prefill cost grow with image resolution.
Encoder-decoder ASR
Whisper encodes a 30-second log-mel spectrogram once, then decodes text tokens autoregressively; the encoder is a fixed-cost prefill, the decoder is a short decode.
Real-time factor (RTF)
Processing time divided by audio duration; below 1.0 means the system keeps up with live speech.
Streaming ASR and TTS
Processing audio in overlapping chunks with a small look-ahead so partial results appear with bounded delay; TTS must emit audio frames faster than they are played back.
First-audio latency and buffer underrun
Time from request to the first playable audio chunk, and the failure where the player runs out of audio because generation fell behind real time.
Diffusion denoising loop
A UNet or DiT run 20-50 times over a latent with no cache between steps; cost per image is steps times one compute-bound forward pass.
Classifier-free guidance
Running conditional and unconditional passes each step (often as a doubled batch), doubling diffusion compute.
Embedding and retrieval models
Encoder-only models whose entire cost is one prefill-like pass; throughput is bounded by compute at large batch and by launch overhead at small batch.

Subtopics

  1. 1. Vision-language prefill

    Image preprocessing, encoder forward, projection, token insertion; why TTFT is dominated by the encoder plus a long prefill; encoder caching and batching encoder calls separately from the LLM step.

  2. 2. Multimodal inputs in engines

    How vLLM and SGLang accept images and audio in the OpenAI chat format, placeholder-token expansion, multimodal prefix caching, and the memory profile of encoder activations.

  3. 3. Speech recognition with Whisper

    Log-mel features, the 30-second encoder window, decoder with timestamps, chunked long-form transcription, faster-whisper and batched decoding; RTF as the metric.

  4. 4. Streaming audio pipelines

    Chunk size versus latency versus accuracy, overlap and look-ahead, voice activity detection, and emitting partial hypotheses; TTS frame-level streaming and the real-time deadline.

  5. 5. Diffusion model serving

    Denoising steps, classifier-free guidance doubling, compute-bound batching, step distillation (SD-Turbo, LCM), and why KV-cache and continuous batching ideas do not apply directly.

  6. 6. What transfers from text LLM serving

    Batching, quantization, CUDA Graphs and torch.compile transfer; paged KV, prefix caching and speculative decoding apply only where there is an autoregressive decoder; a decision table per workload.

Resources

paper
repo
article

Hands-on lessons

L1

Streaming speech recognition with whisper-tiny on CPU

CPU · your Macscript120 minrequired

Goal · A chunked streaming transcriber built on whisper-tiny that reports real-time factor, latency to first partial transcript, and the accuracy cost of smaller chunks.

  1. 1pip install torch transformers datasets librosa jiwer; load openai/whisper-tiny with the transformers automatic-speech-recognition pipeline; build a 60-second English clip by concatenating LibriSpeech test-clean utterances from the datasets library (or use any 60-second English recording).
  2. 2Transcribe the full clip with the pipeline using chunk_length_s=30 and record wall time; compute RTF as wall time divided by 60 seconds. Keep this transcript as the reference.
  3. 3Write stream_transcribe(audio, chunk_s, overlap_s) that feeds consecutive chunks of chunk_s seconds with overlap_s seconds of overlap, runs the model on each, and merges text by dropping the overlapped prefix.
  4. 4Simulate live arrival by sleeping until each chunk would have been recorded; record the latency from chunk end to transcript emission for every chunk, and the time to the first partial transcript.
  5. 5Run chunk_s in 2, 5, 10 with overlap_s 0.5 and compute word error rate against the reference transcript with jiwer.
  6. 6Repeat the full-clip transcription with batch_size 8 over eight copies of the clip and compute audio seconds processed per wall second to see encoder batching.
  7. 7Write a short table of chunk size, RTF, first-partial latency and WER, and one paragraph on which setting you would ship for live captions.
Deliverable
stream_transcribe.py plus the results table and paragraph.
Check
RTF for the full clip is below 1.0 on your CPU; first-partial latency with chunk_s 2 is under 3 seconds; WER against the 30-second-chunk reference falls as chunk_s grows.
L2

Count and time image tokens in a small VLM

CPU · your Macnotebook90 minrequired

Goal · Measurements of how many tokens an image adds to the prompt of SmolVLM-256M-Instruct and how prefill time scales with image resolution and number of images.

  1. 1pip install torch transformers pillow; load HuggingFaceTB/SmolVLM-256M-Instruct with AutoProcessor and AutoModelForVision2Seq in float32 on CPU.
  2. 2Build the same question with and without an image using processor.apply_chat_template, run the processor, and compare input_ids length; count occurrences of the image placeholder token id.
  3. 3Time a single forward pass (prefill only, no generation) for the text-only prompt and for the prompt with one 512x512 image; repeat 5 times and take the median.
  4. 4Resize the image to 256, 512, 1024 and 1536 pixels on the long side; record image token count and prefill time for each (the processor tiles larger images).
  5. 5Add a second image to the prompt and record token count and prefill time again.
  6. 6Register a forward hook on the vision encoder and time it separately from the language model prefill; report the split.
  7. 7Plot prefill time against total image tokens and fit a line; write two sentences on what this means for TTFT and for batching VLM requests.
Deliverable
A notebook with the token-count table, the encoder-versus-LM timing split and the prefill-versus-tokens plot.
Check
One 512x512 image adds at least 64 tokens to input_ids; prefill time with the image is at least 1.5x the text-only prefill; token count and prefill time both increase monotonically with image resolution.
L3

Diffusion batching on a T4

Colab T4 · freeexperiment75 minoptional

Goal · A plot of images per second and peak memory versus batch size for a small Stable Diffusion model, showing where diffusion saturates the GPU and why its curve differs from LLM decode.

  1. 1pip install diffusers transformers accelerate; load stabilityai/sd-turbo (or segmind/tiny-sd) in float16 on the Colab T4 and generate one warm-up image.
  2. 2Generate images at batch sizes 1, 2, 4, 8 with a fixed prompt, 4 denoising steps for sd-turbo (20 for tiny-sd), fixed seed; time each run with torch.cuda.synchronize and record torch.cuda.max_memory_allocated.
  3. 3Compute images per second and peak memory per batch size; plot both.
  4. 4Rerun batch size 4 with guidance_scale 0 versus a value above 1 and note the time difference, which is the classifier-free guidance doubling.
  5. 5Rerun batch size 4 with 4, 10 and 20 steps and confirm time scales linearly with steps.
  6. 6Write a paragraph contrasting this curve with the decode batch-size knee you measured in p3-batching-l2.
Deliverable
A notebook with the two plots, the guidance and step-count measurements and the paragraph.
Check
Images per second at batch 4 is at least 1.5x batch 1 and gains flatten by batch 8; time per batch grows approximately linearly with step count (within 20 percent of proportional).
Fallback
Run segmind/tiny-sd on CPU at 256x256 with batch sizes 1 and 2 and 5 steps; the ratio of images per second is the only number you can measure, but the step-scaling and guidance experiments still work.

Build your own

Build your own streaming ASR server

PythonCPU · your Mac~7 h

whisper-tiny behind a websocket, fed chunked 16 kHz audio, emitting partial and committed transcripts with a local-agreement policy, batched across clients and measured by real-time factor.

The real thing: github.com/ufal/whisper_streaming ↗

How you know a stage passes

Write tests/test_asr.py first using 10 LibriSpeech test-clean utterances and their reference transcripts committed to the repo, with jiwer for WER. A pytest fixture starts the websocket server as a subprocess; a client helper streams a WAV at real time (or faster with a flag for tests) and collects the messages. Each stage asserts WER ranges, latency numbers or message invariants. Run `pytest -q`.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01offline transcription with a WER check
    A transcribe(wav_path) function on whisper-tiny (transformers or faster-whisper) and a wer.py that scores it against reference text.
    test · WER over the 10 LibriSpeech utterances is at most 15 percent and the number is printed; the test fails above 20 percent.
  2. 02a chunked sliding-window pipeline
    Audio arrives as 1 second PCM frames into a buffer; after each frame the last 30 seconds are transcribed and a partial transcript is produced.
    test · Streaming a 30 second file yields at least 25 partial transcripts and a final transcript whose WER is within 5 points of the offline WER on the same file.
  3. 03the websocket server
    A FastAPI websocket endpoint accepts binary PCM frames and sends JSON messages with text, is_final and a timestamp; a client script streams a file at real time.
    test · The client receives at least one partial every 2 seconds, the last message has is_final true, and the server handles a disconnect mid-stream without a traceback.
  4. 04local agreement commits
    Text is committed as final only when two consecutive windows agree on a prefix; committed text is removed from the buffer so the window slides.
    test · Concatenated committed text is never retracted (every committed message extends the previous one), latency to first partial is under 2 seconds, and final WER stays within 5 points of offline.
  5. 05batching across clients
    Frames from N clients are queued and the model runs on a batch of windows per tick instead of one forward per client.
    test · 4 concurrent real-time clients keep real-time factor below 1.0 on your CPU, with per-client first-partial latency reported, and the single-client WER is unchanged.
  6. 06measure chunk size trade-offs
    A bench script sweeps chunk sizes 0.5, 1 and 2 seconds and reports real-time factor, first-partial latency and WER for each.
    test · A table and plot are in README; WER is non-increasing as chunk size grows (or the exception is explained), and first-partial latency grows with chunk size.

Knowledge check

QWhy is time to first token for a vision-language model usually much worse than for a text model with the same number of parameters?

Each image adds hundreds of tokens to prefill plus a vision-encoder forward pass, so the prompt is effectively far longer and the encoder work comes before the first LLM step.

QWhat does a real-time factor of 0.3 mean for a speech recognizer, and why does it not guarantee low latency?

It processes audio 3.3x faster than it is spoken; but latency depends on chunk size and look-ahead, so a system with RTF 0.3 that waits for 10-second chunks still shows 10 seconds of delay.

QWhy does continuous batching not apply to diffusion models the way it does to LLM decode?

Diffusion has no per-request autoregressive state to join or leave mid-sequence; every image runs the same fixed number of compute-bound steps, so batching is a plain dense batch and saturates compute quickly.

QWhich text-LLM optimizations transfer to a Whisper decoder, and which do not?

KV cache, batching and quantization transfer because the decoder is autoregressive; prefix caching rarely helps because the encoder output is unique per audio clip.

QWhat is the primary failure metric for streaming TTS, and what causes it?

Buffer underrun, when audio generation falls behind playback; caused by generation throughput below the audio frame rate or by latency spikes from batching with other requests.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All subtopics marked completed.
  • Lessons l1 and l2 deliverables saved and both checks pass.
  • Can fill in a table of VLM, ASR, TTS, diffusion and embedding workloads with their bottleneck and the serving optimizations that apply.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →