Powered by AppSignal & Oban Pro

A chat server with ContinuousBatching

notebooks/chat_server.livemd

A chat server with ContinuousBatching

# Choose :emlx on Apple silicon, or :exla on Linux.
backend = :emlx

{backend_dep, backend_opts} =
  case backend do
    :emlx -> {{:emlx, "~> 0.5"}, [backend: EMLX.Backend, defn_options: [compiler: EMLX]]}
    :exla -> {{:exla, "~> 1.0"}, [backend: EXLA.Backend, defn_options: [compiler: EXLA]]}
  end

Mix.install([
  # The telemetry events of this notebook are not on Hex yet. When a Hex release after 2.0.0
  # has them, change this line to {:transmuter, "~> 2.1"}.
  {:transmuter, github: "georgeguimaraes/transmuter", ref: "a093615e0b1fea902c1ba2bf395df0e0e6aa5e8a"},
  backend_dep,
  # EMLX 0.5.0 and EXLA 1.0.0 do not compile with fine 0.2, which a new install takes.
  {:fine, "~> 0.1.6", runtime: false},
  {:tokenizers, "~> 0.5"},
  {:otera, "~> 0.1"},
  {:kino, "~> 0.19"}
])

if backend == :emlx, do: EMLX.set_cache_limit(1_000_000_000)

Start the server

A Transmuter.ContinuousBatching server runs a language model for many callers at the same time. A request joins the running rows at the next step, so it does not wait for the other requests to end.

This server has 4 rows (slots: 4). With compile_steps: true, it compiles each step shape before it starts, so the first requests do not wait for a compile.

spec =
  {Transmuter.ContinuousBatching,
   [
     name: Chat,
     source: {:hf, "HuggingFaceTB/SmolLM2-360M-Instruct"},
     slots: 4,
     max_new_tokens: 200,
     compile_steps: true
   ] ++ backend_opts}

{:ok, _pid} = Kino.start_child(spec)

Collect the metrics

The server emits telemetry events for each step and for each request. A handler runs in the process of the server, so this handler only sends a message to an Agent. The agent keeps the finished requests, the tokens of the steps in the last 5 seconds, the rows that run and the last KV cache values.

{:ok, metrics} =
  Agent.start_link(fn ->
    %{requests: [], steps: [], running: 0, waiting: 0, kv_used: 0, kv_capacity: 0}
  end)

ms = &(System.convert_time_unit(&1, :native, :microsecond) / 1000)

handler = fn
  [_, _, :step, :stop], m, metadata, agent ->
    Agent.cast(agent, fn state ->
      since = m.monotonic_time - System.convert_time_unit(5, :second, :native)
      steps = for {time, _tokens} = step <- state.steps, time > since, do: step

      %{
        state
        | steps: [{m.monotonic_time, m.tokens} | steps],
          waiting: m.waiting,
          kv_used: m.kv_used,
          kv_capacity: metadata.slots * m.kv_capacity
      }
    end)

  [_, _, :request, :admit], _m, _metadata, agent ->
    Agent.cast(agent, &%{&1 | running: &1.running + 1})

  [_, _, :request, :stop], m, metadata, agent ->
    Agent.cast(agent, fn state ->
      # A request that the caller cancels before it gets a row has no :index.
      running = if metadata.index, do: state.running - 1, else: state.running

      requests =
        if metadata.result == :done,
          do: [{ms.(m.time_to_first_token), ms.(m.time_per_output_token)} | state.requests],
          else: state.requests

      %{state | running: running, requests: requests}
    end)
end

:telemetry.attach_many(
  "chat-notebook",
  [
    [:transmuter, :continuous_batching, :step, :stop],
    [:transmuter, :continuous_batching, :request, :admit],
    [:transmuter, :continuous_batching, :request, :stop]
  ],
  handler,
  metrics
)

This frame shows the metrics each second. The output rate counts the tokens of the last 5 seconds, so it goes to 0 when the server has no requests.

frame = Kino.Frame.new()

Kino.listen(1_000, fn _tick ->
  state = Agent.get(metrics, & &1)
  since = System.monotonic_time() - System.convert_time_unit(5, :second, :native)
  recent = for {time, tokens} <- state.steps, time > since, do: tokens
  mean = fn values -> if values == [], do: 0.0, else: Float.round(Enum.sum(values) / length(values), 1) end

  rows = [
    %{metric: "Requests done", value: "#{length(state.requests)}"},
    %{metric: "Mean time to first token (ms)", value: "#{mean.(Enum.map(state.requests, &elem(&1, 0)))}"},
    %{metric: "Mean time per output token (ms)", value: "#{mean.(Enum.map(state.requests, &elem(&1, 1)))}"},
    %{metric: "Tokens per second (last 5 s)", value: "#{Enum.sum(recent) / 5}"},
    %{metric: "Running rows", value: "#{state.running}"},
    %{metric: "Waiting requests", value: "#{state.waiting}"},
    %{metric: "KV cache in use", value: "#{state.kv_used} of #{state.kv_capacity} rows"}
  ]

  Kino.Frame.render(frame, Kino.DataTable.new(rows, name: "Server", keys: [:metric, :value]))
end)

frame

Chat with the server

Each question streams its answer into its own frame. The 6 questions run at the same time, so the server runs 4 of them in its rows, and 2 wait in the queue. Look at the metrics above while the answers come.

questions = [
  "What is the capital of France?",
  "Explain how a rainbow forms.",
  "Write a haiku about the sea.",
  "Why is the sky blue?",
  "Give three tips to sleep well.",
  "What is a prime number?"
]

frames = for _question <- questions, do: Kino.Frame.new()

for {question, frame} <- Enum.zip(questions, frames) do
  Task.start(fn ->
    chat = %{messages: [%{role: "user", content: question}]}

    Chat
    |> Transmuter.ContinuousBatching.stream(chat)
    |> Enum.reduce("", fn chunk, text ->
      text = text <> chunk
      Kino.Frame.render(frame, Kino.Markdown.new("**#{question}**\n\n#{text}"))
      text
    end)
  end)
end

Kino.Layout.grid(frames, columns: 2)

Use the metrics in an application

In an application, define the metrics with Telemetry.Metrics and send them to a service such as Prometheus. The guide "Telemetry in production" shows how.