Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 20 — Bumblebee: Pre-trained Models

Bumblebee runs Hugging Face models directly in Elixir — zero Python, zero conversion. Models download on first run (~6MB–2GB) and cache locally.

20.1 Setup & Backend Rule

Mix.install([
  {:bumblebee, "~> 0.7"},
  {:axon, "~> 0.8"},
  {:nx, "~> 0.13"},
  {:exla, "~> 0.13"},
  {:stb_image, "~> 0.6"},
  {:req, "~> 0.7"}
])

# EXLA, always (see the compatibility note below)
Nx.global_default_backend(EXLA.Backend)

Compatibility, verified 2026-08 against nx 0.13.1 / emlx 0.4.1 / bumblebee 0.7.1 — re-check before trusting it. emlx 0.4.x was incompatible with Bumblebee on Nx 0.13: running a serving raised ** (ArgumentError) ... batch_keys, because Bumblebee passes a batch_keys option EMLX did not support. Diagnosis: an error naming batch_keys, under EMLX only. Fallback: EXLA.Backend, which works on macOS CPU by default. Plain Nx/defn on Apple Silicon → EMLX is fine; this restriction is about Bumblebee’s serving path only.

Use global_default_backend/1 here, not Nx.default_backend/1: Bumblebee loads and runs models in processes it starts itself, and a process-local setting would not reach them (Ch 18 §18.3 spells out the four scopes).

What happens under the hood for every recipe below:

flowchart TD
    HF["Hugging Face Hub"] --> LOAD["Bumblebee.load_model/1<br/>downloads config + weights (.safetensors)"]
    LOAD --> PRE["Preprocessing<br/>tokenizer / featurizer"]
    PRE --> JIT["Nx.Defn compilation (EXLA)<br/>→ optimized kernel"]
    JIT --> FWD["Model forward pass"]
    FWD --> POST["Postprocessing<br/>softmax / normalize / labels"]
    POST --> OUT["plain Elixir data structures"]

The Load Triple

Every task below assembles the same three pieces — learn it once, read any recipe forever:

PieceLoaderRole
ModelBumblebee.load_model/2weights + config, the compiled network
Tokenizer / Featurizerload_tokenizer/2, load_featurizer/2raw input → ids/pixels/spectrograms
Task bindingBumblebee.Text.*, .Vision.*, .Audio.*model + pre/post → Nx.Serving

Boundaries are explicit, in the Erlang tradition: strings never enter the network. They become token ids whose vocabulary, casing, and special tokens must match those the weights were trained against — mismatched pairs degrade silently, no exception raised.

Downloads cache under the OS user-cache directory (~/.cache/bumblebee on Linux; override with BUMBLEBEE_CACHE_DIR). First load fetches and verifies; later loads reuse. Deployments point the cache at a mounted volume and pre-warm it during image build so nodes start inference-ready.

Budget the disk. Realistic cache sizes, so you size a volume instead of discovering it at deploy time: bart-large-mnli 1.6GB, a ViT 330MB, whisper-small 466MB, Stable Diffusion 4GB+. Mount, don’t layer.

Gated models (Llama, Mistral and friends) need a token:

{:ok, info} = Bumblebee.load_model({:hf, "meta-llama/Llama-3.2-1B",
                                    auth_token: System.fetch_env!("HF_TOKEN")})

Pass it explicitly, as above — Bumblebee does not read a token from the environment itself. Without one you get a 401 with no useful map — that is the tell.

Two load options worth knowing before you hit VRAM limits:

{:ok, info} = Bumblebee.load_model({:hf, repo}, type: :bf16)          # halve memory
{:ok, info} = Bumblebee.load_model({:hf, repo}, backend: EXLA.Backend)

type: :bf16 trades a little precision for roughly half the weights in memory — usually the right move for a single-GPU box.

What Bumblebee does not do: no text-to-speech, and no training (that is Ch 19/Axon). It is an inference library with a very wide model zoo.

20.2 Text Classification (BERT)

{:ok, model_info} =
  Bumblebee.load_model({:hf, "distilbert-base-uncased-finetuned-sst-2-english"})

# The fine-tuned repo lacks a Rust-compatible tokenizer.json;
# load the tokenizer from the base model (same tokenizer architecture).
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "distilbert-base-uncased"})

serving = Bumblebee.Text.text_classification(model_info, tokenizer)

Nx.Serving.run(serving, "This movie was absolutely amazing!")
#=> %{predictions: [%{label: "POSITIVE", score: 0.999}]}

Tokenizer gotcha repeats across repos (NER, QA): when a fine-tuned repo has no tokenizer.json, pull the tokenizer from its base model. How to detect it: Bumblebee.load_tokenizer/1 on the fine-tuned repo raises while loading the tokenizer (or you see an empty/garbled vocabulary). The base repo ships the same WordPiece/SentencePiece architecture, so swapping the repo id fixes it. Check the repo’s file listing on the HF Hub first — it is one page load versus a confusing runtime error.

Mechanically, text_classification/3 compiles tokenize → DistilBERT forward pass → softmax over the sentiment head. Treat scores as confidence, not truth: argmax decides, but route sub-threshold scores to human review — guard clauses for uncertainty. Lists batch naturally, Nx.Serving.run(serving, [text1, text2]); handy in notebooks, while traffic at scale belongs behind a supervised serving process (Ch 21).

20.3 Zero-Shot Classification

Classify into arbitrary labels without task-specific training (NLI-based: premise vs “This text is about {label}”, entailment scoring):

{:ok, model_info} = Bumblebee.load_model({:hf, "facebook/bart-large-mnli"})
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "facebook/bart-large-mnli"})

labels = ["New booking", "Update booking", "Cancel booking", "Refund", "Complaint", "delay"]

serving = Bumblebee.Text.zero_shot_classification(model_info, tokenizer, labels)

Nx.Serving.run(serving, "I need a room with two beds for tomorrow")
#=> %{predictions: [%{label: "New booking", score: ...}, ...]}

The NLI framing costs one forward pass per label but makes labels data rather than weights: revise the taxonomy by editing the list, no retraining. Expect softer score distributions than from fine-tuned classifiers — calibrate thresholds on your own texts before trusting absolute numbers.

20.4 Text Generation (GPT-2)

{:ok, model_info} = Bumblebee.load_model({:hf, "openai-community/gpt2"})
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai-community/gpt2"})
{:ok, gen_config} = Bumblebee.load_generation_config({:hf, "openai-community/gpt2"})

# Generation controls live on the generation config, not serving opts
gen_config =
  Bumblebee.configure(gen_config,
    max_new_tokens: 100,
    temperature: 0.7,
    strategy: %{type: :multinomial_sampling, top_k: 50}
  )

serving =
  Bumblebee.Text.generation(model_info, tokenizer, gen_config,
    defn_options: [compiler: EXLA]
  )

Nx.Serving.run(serving, "The future of Elixir and the BEAM is")
ParameterDefaultMeaning
max_new_tokens20Generation length
temperaturenilSampling temperature (sampling only)
strategy%{type: :greedy_search}Decoding method
no_repeat_ngram_lengthnilBan repeated n-grams

Why config-not-opts: decoding strategy is part of the compiled autoregressive loop (for step in 1..max_new_tokens: logits → filter → sample → append).

Strategies live in the strategy map:

  • Greedy (%{type: :greedy_search}, the default): argmax per step — deterministic, loop-prone; no_repeat_ngram_length breaks the loops.
  • Sampling (%{type: :multinomial_sampling, top_k: ..., top_p: ...}): temperature sharpens or flattens the distribution; top_k truncates to the k likeliest tokens; top_p keeps the smallest prefix set whose probabilities sum past p. Temperature 0.7 + top_p 0.9 is a common baseline.
  • Contrastive search (%{type: :contrastive_search, top_k: 4, alpha: 0.6}): deterministic and higher quality at a few times the compute. Bumblebee has no beam-search strategy.

In interactive settings perceived latency dominates user judgment, which is why streaming (next) usually matters more than decoding refinements.

Streaming for LiveView

serving =
  Bumblebee.Text.generation(model_info, tokenizer, gen_config,
    stream: true,
    # client: is EXLA's device selector (Ch 18 §18.3) — :cuda on a GPU box.
    # Same knob as Nx.Defn.default_options(client: ...)
    defn_options: [compiler: EXLA, client: :host]
  )

# run/2 now returns a lazy Stream — one chunk per token/step,
# each carrying the cumulative text so far:
stream_result = Nx.Serving.run(serving, prompt)

# look at ONE chunk before wiring anything to a browser — this confirms
# whether you receive cumulative text or deltas, and the exact key set:
IO.inspect(hd(Enum.take(stream_result, 1)))

Enum.each(stream_result, fn chunk ->
  [%{text: partial}] = chunk.results
  IO.write(partial)
end)

Consume chunks in handle_info and push deltas to the browser.

Chunks carry cumulative text, so the client renders the latest chunk as-is — no assembly logic. Pipe deltas through PubSub: serving → broadcast → LiveView → browser, while the serving process keeps admitting other requests the whole time.

20.5 Vision: Image Classification & Embeddings

# Classification with ViT (~86M params, ImageNet)
{:ok, model_info} = Bumblebee.load_model({:hf, "google/vit-base-patch16-224"})
{:ok, featurizer} = Bumblebee.load_featurizer({:hf, "google/vit-base-patch16-224"})

serving =
  Bumblebee.Vision.image_classification(model_info, featurizer,
    top_k: 5,
    compile: [batch_size: 1],
    defn_options: [compiler: EXLA, client: :host]
  )

image_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png"
{:ok, %Req.Response{body: image_data}} = Req.get(image_url)
image = StbImage.read_binary!(image_data)

Nx.Serving.run(serving, image)
#=> %{predictions: [%{label: "beignet", score: 0.98}, ...]}

Featurizer pipeline: resize to 224×224 → normalize → patchify into 16×16 patches.

# CLIP image embeddings — note the explicit vision module selector
{:ok, clip_info} =
  Bumblebee.load_model({:hf, "openai/clip-vit-base-patch32"},
    module: Bumblebee.Vision.ClipVision   # repo has both encoders!
  )
{:ok, featurizer} = Bumblebee.load_featurizer({:hf, "openai/clip-vit-base-patch32"})

serving =
  Bumblebee.Vision.image_embedding(clip_info, featurizer,
    compile: [batch_size: 1],
    defn_options: [compiler: EXLA, client: :host]
  )

%{embedding: emb} = Nx.Serving.run(serving, image)   # L2-normalized vector

Use embeddings for similarity search (dot product ≈ cosine), clustering, zero-shot classification against text embeddings.

Sizing intuition: ViT-base is ~86M params ≈ 330MB in f32 (halved in bf16); CLIP ships two towers, so load only the encoder you call. Compiled executables pin shapes — compile: [batch_size: 1] trades batching flexibility for steady single-request latency, the right trade until volume proves otherwise.

20.6 NER and Question Answering

# Named Entity Recognition
{:ok, ner_info} = Bumblebee.load_model({:hf, "dslim/bert-base-NER"})
{:ok, ner_tok} = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-cased"})

serving = Bumblebee.Text.token_classification(ner_info, ner_tok, aggregation: :same)

Nx.Serving.run(serving, "Apple Inc. is based in Cupertino, California.")
#=> %{entities: [%{label: "ORG", phrase: "Apple Inc.", score: 0.99}, ...
#                 %{label: "LOC", phrase: "Cupertino"}, ...]}

Aggregation strategies: nil (per-token), :same (merge consecutive same-label subwords — the usual NER choice), plus :word_first, :word_average, :word_max.

Why aggregation exists: WordPiece splits “Cupertino” into subword tokens, each scored independently. :same stitches consecutive same-label subwords back into phrases — the difference between a bag of token scores and the clean entity list shown above.

# Extractive QA
{:ok, qa_info} = Bumblebee.load_model({:hf, "deepset/roberta-base-squad2"})
{:ok, qa_tok} = Bumblebee.load_tokenizer({:hf, "FacebookAI/roberta-base"})

serving = Bumblebee.Text.question_answering(qa_info, qa_tok)

Nx.Serving.run(serving, %{
  question: "What does Elixir run on?",
  context: "Elixir runs on the BEAM VM, which provides massive concurrency."
})
#=> %{results: [%{text: "the BEAM VM", score: 0.95, start: 11, end: 20}]}
{:ok, model_info} =
  Bumblebee.load_model({:hf, "sentence-transformers/all-MiniLM-L6-v2"})
{:ok, tokenizer} =
  Bumblebee.load_tokenizer({:hf, "sentence-transformers/all-MiniLM-L6-v2"})

serving =
  Bumblebee.Text.text_embedding(model_info, tokenizer,
    output_attribute: :hidden_state,   # select token-level output...
    output_pool: :mean_pooling,        # ...then pool tokens...
    embedding_processor: :l2_norm       # ...then normalize
  )

texts = [
  "Elixir is a functional programming language",
  "The BEAM provides massive concurrency",
  "Phoenix is a web framework for Elixir"
]

results = Nx.Serving.run(serving, texts)             # 384-dim each
embeddings = Nx.stack(Enum.map(results, & &1.embedding))   # {3, 384}

[%{embedding: query_emb}] = Nx.Serving.run(serving, ["How does Elixir handle concurrency?"])
scores = Nx.dot(embeddings, query_emb) |> Nx.to_flat_list()   #=> {3}
# pick argmax — L2-normalized so dot product == cosine similarity

Note the shape on that dot: embeddings is {3, 384} and query_emb is {384}, so Nx.dot/2 contracts the last axis against the first and yields {3} — one score per document. Nx.transpose/1 on a rank-1 tensor is the identity, so wrapping query_emb in it would look meaningful and change nothing.

(output_attribute: :hidden_state is needed because the default pooled state is already rank-2; you must pool from rank-3 token states.)

A ranking helper, boring on purpose:

defmodule SemanticSearch do
  def top_k(query_embedding, doc_embeddings, k \\ 3) do
    doc_embeddings
    |> Nx.dot(query_embedding)   # {n, dim} · {dim} → {n}
    |> Nx.to_flat_list()
    |> Enum.with_index()
    |> Enum.sort(:desc)
    |> Enum.take(k)
  end
end

L2-normalized vectors make dot product equal cosine similarity, bounded in [-1, 1]. Brute-force ranking stays snappy into the tens of thousands of documents; graduate to pgvector/HNSW only when measurement says so. Calibrate “similar” thresholds per model and corpus — 0.3+ often relates for MiniLM-class encoders, but trust your data over folklore.

Multi-component load; bfloat16 halves memory (~4GB VRAM for SD 1.5):

# NOTE: the original "runwayml/stable-diffusion-v1-5" repo was taken down;
# the community mirror lives under the stable-diffusion-v1-5 org:
repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
opts = [type: :bf16]

{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai/clip-vit-large-patch14"})
{:ok, text_encoder} = Bumblebee.load_model({:hf, repo_id, subdir: "text_encoder"}, opts)
{:ok, unet} = Bumblebee.load_model({:hf, repo_id, subdir: "unet"}, opts)
{:ok, vae} = Bumblebee.load_model({:hf, repo_id, subdir: "vae"}, [architecture: :decoder] ++ opts)
{:ok, scheduler} = Bumblebee.load_scheduler({:hf, repo_id, subdir: "scheduler"})
{:ok, safety_checker} = Bumblebee.load_model({:hf, repo_id, subdir: "safety_checker"}, opts)
{:ok, featurizer} = Bumblebee.load_featurizer({:hf, repo_id, subdir: "feature_extractor"})

serving =
  Bumblebee.Diffusion.StableDiffusion.text_to_image(
    text_encoder, unet, vae, tokenizer, scheduler,
    num_steps: 20,
    guidance_scale: 7.5,
    num_images_per_prompt: 2,
    safety_checker: safety_checker,
    safety_checker_featurizer: featurizer,
    compile: [batch_size: 1, sequence_length: 77],
    defn_options: [compiler: EXLA]
  )

Kino.start_child({Nx.Serving, name: :stable_diffusion, serving: serving})

output =
  Nx.Serving.batched_run(:stable_diffusion, %{
    prompt: "A futuristic Elixir logo, glowing purple, cyberpunk style",
    negative_prompt: "blurry, low quality"
  })

Tuning: num_steps 20–50 (quality vs speed), guidance_scale ~7.5 (prompt adherence), bf16 on Ampere+/Apple Silicon.

The negative prompt is guidance, not filtering: classifier-free guidance computes a conditional and an unconditional direction each step and pushes away from the latter — substituting your negative prompt’s embeddings for the unconditional branch steers composition. Keep num_images_per_prompt consistent with compile: [batch_size: ...], or shape specialization will recompile per mismatch.

20.9 Model Selection Cheat Sheet

TaskModelSize
Sentimentdistilbert-base-uncased-finetuned-sst-2-english250MB
Zero-shotfacebook/bart-large-mnli1.6GB
Generationopenai-community/gpt2-medium1.5GB
Chat generationa small instruct model your provider serves (HF_TOKEN + {:hf, repo, auth_token: ...})varies
Image classmicrosoft/resnet-50100MB
Image classgoogle/vit-base-patch16-224330MB
Image embedopenai/clip-vit-base-patch32330MB
Image embedgoogle/siglip-base-patch16-224330MB
Speech→textopenai/whisper-tiny → -base → -small39/142/466MB
Text embedsentence-transformers/all-MiniLM-L6-v290MB
Text embedsentence-transformers/all-mpnet-base-v2420MB
Text embed (retrieval-tuned)intfloat/e5-small-v2, Qwen/Qwen3-Embedding-0.6B130MB+
Text-to-imagestable-diffusion-v1-5/stable-diffusion-v1-54GB+

Browse more: https://huggingface.co/models?library=bumblebee

Selection heuristics: pick the smallest model clearing your quality bar — download size, RAM footprint, and latency scale together, and a tiny variant serving today beats a large variant arriving next sprint. Latency-sensitive paths want distilled checkpoints (DistilBERT, MiniLM); offline quality-maximal jobs can afford bart-large. Read each model card’s license before shipping.

20.10 Speech-to-Text With Whisper

Same triple, audio edition: the featurizer turns PCM samples into log-mel spectrograms; the decoder emits text tokens autoregressively.

{:ok, model_info} = Bumblebee.load_model({:hf, "openai/whisper-tiny"})
{:ok, featurizer} = Bumblebee.load_featurizer({:hf, "openai/whisper-tiny"})
{:ok, tokenizer}  = Bumblebee.load_tokenizer({:hf, "openai/whisper-tiny"})
{:ok, generation_config} = Bumblebee.load_generation_config({:hf, "openai/whisper-tiny"})

generation_config =
  Bumblebee.configure(generation_config, max_new_tokens: 100)

serving =
  Bumblebee.Audio.speech_to_text_whisper(model_info, featurizer, tokenizer, generation_config,
    # `compile:` accepts only `:batch_size` for Whisper. The featurizer sizes
    # each chunk to 30s of audio (`encoder_max_positions` is 1500, doubled by
    # Whisper's 2× conv frontend), and longer input is chunked internally.
    # There is no per-chunk `sequence_length` knob to raise.
    compile: [batch_size: 1]
  )

Input is a map of raw PCM data plus its sample rate — decode and resample to 16kHz yourself (FFmpeg, or Kino.Input.audio/1 in Livebook):

Nx.Serving.run(serving, %{"data" => pcm_binary, "sampling_rate" => 16000})
#=> %{chunks: [%{text: "transcribed speech appears here", ...}]}

Practice notes:

  • Start with whisper-tiny (39MB) and upgrade on evidence — -base, -small buy accuracy with download size and latency.
  • Long recordings are chunked internally; tiny/base transcribe near real-time on laptop CPUs.
  • Multilingual out of the box; language and task (transcribe vs translate) come from the model config.

Explore More

  • Bumblebee docs — every supported architecture and task, with runnable examples per task module
  • Bumblebee examples folder — Livebooks for SD, Whisper speech-to-text, and more
  • Hugging Face Hub — filter by bumblebee library tag; model cards list required featurizer/tokenizer companions
  • Exercise idea: build a tiny semantic search over your own notes using §20.7’s embedding serving plus a brute-force dot-product ranking — then swap in pgvector once it works
  • Practice Labs: Lab 6 — Semantic Search and Lab 5 — Character-Level LSTM — new E5/cross-encoder/NER and generation examples

Checkpoint

  1. Why load a tokenizer from the base model sometimes?
  2. Where do top_k/temperature go — serving options or generation config?
  3. What makes CLIP loading different from ViT?
Answers
  1. Fine-tuned repos often lack a Rust-compatible tokenizer.json; the base repo ships the same tokenizer architecture.
  2. The generation config — they parameterize the compiled decoding loop.
  3. The repo contains both vision and text encoders, so pass module: Bumblebee.Vision.ClipVision to select the encoder.

Next: Chapter 21 — Production Inference: Nx.Serving