# Lab 6 — Bumblebee: Semantic Search for a Support Desk

The closing lab is the one closest to shipping: a semantic search engine over
a support-desk FAQ, built from three pre-trained Bumblebee models — an
embedding model for retrieval, a cross-encoder for re-ranking, and a
named-entity recognizer for routing. No training at all. This is the
"inference-first" pattern Chapter 20 promised, now end-to-end. All-new
examples: we build a small FAQ search engine over support-desk snippets —
embed with a sentence-transformer, retrieve by cosine similarity,
re-score the shortlist with a cross-encoder, and extract entities from
tickets with NER. No training, no Python.

> **From Erlang you know:** each Bumblebee serving is a supervised
> process you call with `Nx.Serving.run/2` — the GenServer boundary is
> already there. Wrapping three servings in one façade module is just
> writing a clean API over three workers.

## What You'll Build

1. **Embedding retrieval** — E5 sentence embeddings with L2
   normalization, so `Nx.dot` *is* cosine similarity.
2. **Cross-encoder re-ranking** — retrieve wide with the fast bi-encoder,
   re-score the top few with the accurate-but-O(n) cross-encoder.
3. **NER routing** — pull `PER`/`ORG`/`LOC` entities out of free-form
   tickets for automatic queue assignment.

```elixir
Mix.install([
  {:bumblebee, "~> 0.7"},
  {:axon, "~> 0.8"},
  {:nx, "~> 0.13"},
  {:exla, "~> 0.13"},
  {:kino, "~> 0.14"}
])
```

```elixir
Nx.global_default_backend(EXLA.Backend)
Nx.Defn.default_options(compiler: EXLA)
```

## Section 1 — The corpus

A tiny knowledge base. In production this would come from Ecto; here it
is inline so the lab is self-contained:

```elixir
faqs = [
  "Customers can reset their password from the login page using the Forgot password link.",
  "Refunds are processed to the original payment method within 5 to 7 business days.",
  "Team administrators can invite or remove members from the workspace settings page.",
  "Our API rate limit is 60 requests per minute for every authentication token.",
  "Subscriptions can be cancelled any time; access continues until the end of the billing period.",
  "Two-factor authentication can be enabled under Security settings using any TOTP app.",
  "Exported reports are available in CSV and PDF formats from the Reports page.",
  "Invoices are emailed automatically on the first day of each billing cycle.",
  "Mobile push notifications can be muted per project from the notification preferences.",
  "Data residency options for EU customers can be requested through your account manager."
]

query = "how do I stop paying but keep access until the month ends?"
```

## Section 2 — Text embeddings

E5 models expect the literal prefixes `query: ` and `passage: ` — bake
them into a small wrapper. These asymmetric prefixes mark each side's
role: dropping them silently degrades ranking, a reminder that
pre-trained models carry contracts, and reading the model card is part of
integration, not documentation theater. L2 normalization makes plain dot
products equivalent to cosine similarity:

```elixir
{:ok, embed_model} = Bumblebee.load_model({:hf, "intfloat/e5-small-v2"})
{:ok, embed_tokenizer} = Bumblebee.load_tokenizer({:hf, "intfloat/e5-small-v2"})

embedding_serving =
  Bumblebee.Text.text_embedding(embed_model, embed_tokenizer,
    # mean-pooling works on the rank-3 hidden states; the default
    # :pooled_state attribute is already rank 2 (one vector per input)
    output_attribute: :hidden_state,
    output_pool: :mean_pooling,
    embedding_processor: :l2_norm,
    compile: [batch_size: 16, sequence_length: 96],
    defn_options: [compiler: EXLA]
  )

embed = fn prefix, text ->
  Nx.Serving.run(embedding_serving, prefix <> text).embedding
end
```

A serving called with a **list** returns a list of results; called with
one string it returns one result. The `case` below handles both shapes so
the lab survives library evolution:

```elixir
doc_matrix =
  faqs
  |> Enum.map(&"passage: " <> &1)
  |> then(&Nx.Serving.run(embedding_serving, &1))
  |> case do
    %{embedding: single} -> [single]
    list when is_list(list) -> Enum.map(list, & &1.embedding)
  end
  |> Nx.stack()

{Nx.shape(doc_matrix), Nx.type(doc_matrix)}
```

## Section 3 — Retrieve by similarity

Every vector is unit length, so `Nx.dot` is the cosine similarity:

```elixir
query_vec = embed.("query: ", query)

# {10, 384} dot {384} contracts the last axis -> one similarity score per doc
scores = Nx.dot(doc_matrix, query_vec)

top5 =
  scores
  |> Nx.to_flat_list()
  |> Enum.with_index()
  |> Enum.sort_by(fn {score, _} -> -score end)
  |> Enum.take(5)
  |> Enum.map(fn {score, i} ->
    %{score: Float.round(score, 4), faq: Enum.at(faqs, i)}
  end)

Kino.DataTable.new(top5, name: "Embedding retrieval")
```

## Section 4 — Re-rank the shortlist with a cross-encoder

Two-stage retrieval: cheap filter, expensive judge.

```
query ──▶ bi-encoder ──▶ top-5 (dot products) ──▶ cross-encoder ──▶ best answer
        (embed once,      over ALL docs)          (reads query + doc
          compare vs                               jointly, per pair)
          every doc)
```

The bi-encoder compares every document independently — fast, and the doc
matrix can be embedded offline; a cross-encoder reads query and document
**together** in one transformer pass, which is far more accurate but must
run per candidate. Production RAG systems are almost universally this
two-stage shape; this lab builds it in ~30 lines. Retrieve wide, re-rank
narrow:

```elixir
{:ok, rerank_model} = Bumblebee.load_model({:hf, "cross-encoder/ms-marco-MiniLM-L-6-v2"})
{:ok, rerank_tokenizer} = Bumblebee.load_tokenizer({:hf, "cross-encoder/ms-marco-MiniLM-L-6-v2"})

rerank_serving =
  Bumblebee.Text.cross_encoding(rerank_model, rerank_tokenizer,
    compile: [batch_size: 5, sequence_length: 128],
    defn_options: [compiler: EXLA]
  )

top5
|> Enum.map(& &1.faq)
|> Enum.map(&{query, &1})
|> then(&Nx.Serving.run(rerank_serving, &1))
|> case do
  %{score: single} -> [%{score: single}]
  list -> list
end
|> Enum.zip(top5)
|> Enum.map(fn {%{score: s}, hit} -> %{rerank_score: Float.round(s, 4), faq: hit.faq} end)
|> Enum.sort_by(& &1.rerank_score, :desc)
|> Kino.DataTable.new(name: "Cross-encoder re-ranking")
```

## Section 5 — Extract entities from a support ticket

Named entity recognition rounds out the pipeline — pull people, orgs, and
locations out of free-form tickets so they can be routed automatically:

```elixir
{:ok, ner_model} = Bumblebee.load_model({:hf, "dslim/bert-base-NER"})
{:ok, ner_tokenizer} = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-cased"})

ner_serving =
  Bumblebee.Text.token_classification(ner_model, ner_tokenizer,
    aggregation: :same,
    compile: [batch_size: 1, sequence_length: 128],
    defn_options: [compiler: EXLA]
  )

ticket =
  "Priya Nair from Acme Logistics in Rotterdam says invoice #4471 was " <>
    "emailed twice and the refund has not arrived yet."

Nx.Serving.run(ner_serving, ticket)
```

## Section 6 — One function, three models

The whole desk in a single façade — an Erlang dev will recognize this as
a thin module over three supervised servings. `Nx.Serving.run/2` hides a
GenServer that owns the compiled program and device memory. In production
(Chapter 21) you register servings under names in a supervision tree and
call `Nx.Serving.batched_run/2`; the façade below is the single place
those names would live:

```elixir
defmodule SupportDesk do
  @faqs [
    "Customers can reset their password from the login page using the Forgot password link.",
    "Refunds are processed to the original payment method within 5 to 7 business days.",
    "Team administrators can invite or remove members from the workspace settings page.",
    "Our API rate limit is 60 requests per minute for every authentication token.",
    "Subscriptions can be cancelled any time; access continues until the end of the billing period.",
    "Two-factor authentication can be enabled under Security settings using any TOTP app.",
    "Exported reports are available in CSV and PDF formats from the Reports page.",
    "Invoices are emailed automatically on the first day of each billing cycle.",
    "Mobile push notifications can be muted per project from the notification preferences.",
    "Data residency options for EU customers can be requested through your account manager."
  ]

  def answer(query, embedding_serving, rerank_serving) do
    docs =
      @faqs
      |> Enum.map(&"passage: " <> &1)
      |> then(&Nx.Serving.run(embedding_serving, &1))
      |> Enum.map(& &1.embedding)

    matrix = Nx.stack(docs)

    %{embedding: q} = Nx.Serving.run(embedding_serving, "query: " <> query)

    top3 =
      matrix
      |> Nx.dot(q)
      |> Nx.to_flat_list()
      |> Enum.with_index()
      |> Enum.sort_by(fn {s, _} -> -s end)
      |> Enum.take(3)

    top3
    |> Enum.map(fn {_, i} -> {query, Enum.at(@faqs, i)} end)
    |> then(&Nx.Serving.run(rerank_serving, &1))
    |> Enum.map(& &1.score)
    |> Enum.zip(Enum.map(top3, fn {_, i} -> Enum.at(@faqs, i) end))
    |> Enum.sort_by(fn {s, _} -> -s end)
    |> then(fn [{_s, best} | _] -> best end)
  end
end

SupportDesk.answer("where do I add a new teammate?", embedding_serving, rerank_serving)
```

## Checkpoint

1. Why does L2 normalization make dot products equal to cosine
   similarity?
2. You must re-rank 500 candidates with the cross-encoder instead of 5.
   What breaks first — correctness or latency — and what is the fix?
3. Where would you persist `doc_matrix` so a release restart skips
   re-embedding 10,000 documents?

**Answers**

1. For unit vectors, `dot(a, b) = |a||b|cos(θ) = cos(θ)` — the norms are
   1, so the product of magnitudes vanishes.
2. Latency: the cross-encoder runs one transformer pass per pair, so 500
   pairs is 100× the compute. Fix: keep the shortlist narrow, batch the
   pairs, or move the re-ranker to a bigger device — never widen it
   casually.
3. Anywhere durable — ETS is lost on restart. `Nx.to_binary/1` plus the
   type/shape metadata (the Ch 17 persistence triple) into a file or
   object store; reload with `Nx.from_binary/2`.

## Where to next

- Exercise: register both servings under names in a `Kino.start_child`
  supervision setup and switch the façade to `Nx.Serving.batched_run/2`;
  measure throughput with 1 vs 8 concurrent callers.
- Exercise: swap `intfloat/e5-small-v2` for a larger embedding model and
  observe how the ranking of the trickier queries changes.
- Exercise: persist `doc_matrix` with `Nx.to_binary/1` + type/shape
  metadata (the pattern from Ch 17) so restarts skip re-embedding.
- Exercise: add a fallback — when the best re-rank score is below a
  threshold, answer "no confident match" instead of the top hit.
- Exercise: add a second stage that routes tickets by NER labels —
  `ORG` tickets go to the billing queue, `PER` to a human reviewer — and
  log the routing decisions to decide which entities deserve their own
  queues.
