SonicBoom

Route 2 C ABI draft: the inference backend behind (sonicboom serve backend)

Status: the serving path is implemented — (sonicboom serve real-backend) drives libsonicboom.so through these functions. §2 keeps the design’s fuller declaration list; what the path does not use yet is listed in §6.

This document maps the backend protocol of the Guile inference service (bindings/guile/scheme/sonicboom/serve/backend.scm) to the C ABI that libsonicboom.so exports, so the mock backend can be replaced by a libsonicboom one without changing the service.

“Route 2” is Path 2 of the execution-path plan: GGUF → model loader → planner spine → native-torch / hand-written CUDA / MLIR kernels (Gemma 4 E4B today). The functions below are a facade over that path. They follow capi/include/sonicboom/capi.h and the C API rules of CLAUDE.md:

The prefix boom_llm_ keeps these functions apart from the S-Expr graph API (boom_parse / boom_compile / …) already in capi.h.

1. Protocol → ABI map

(sonicboom serve backend) C ABI notes
load-model boom_llm_model_load, boom_llm_model_free GGUF path + config struct
model-info boom_llm_model_get_info id, family, context length, vocabulary size, EOS ids
tokenize boom_llm_tokenize special tokens parsed as whole tokens
detokenize boom_llm_detokenize UTF-8 bytes; may end inside a character
render-chat none stays in Scheme (serve/chat-template.scm); the ABI only reports the family
create-session, free-session boom_llm_session_new, boom_llm_session_free a KV cache + its token history
fork-session (optional) boom_llm_session_fork copies the first n positions; may return BOOM_ERR_UNSUPPORTED
prefill boom_llm_prefill returns the number of reused tokens
sampler (make-sampler) boom_llm_sampling + boom_llm_decode parameters per call; draw state lives in the session
step boom_llm_decode (max_tokens 1) sample, append, return the token; repeated calls continue the same stream
generate (batched delivery) boom_llm_session_set_token_batch_callback + boom_llm_decode the callback receives one decode step’s tokens at once; the per-token boom_llm_token_cb delivers the same stream one token at a time
constraint hook boom_llm_session_set_grammar, boom_llm_session_set_json_schema, boom_llm_session_clear_grammar installed on the session, restarted by each prefill
backend-stats boom_llm_model_get_stats prefill / reuse / step counters
model-embedding (optional) boom_llm_model_embedding residual width: the steering vector length and the capture row width
residual-capture (optional) boom_llm_residual_capture residual rows of a text at one block, tooling for style vectors
prefill style argument (optional) boom_llm_session_set_steering, boom_llm_session_clear_steering one fixed residual vector added after a block, set once per style change
provenance seed (optional) boom_llm_session_last_seed the seed the session’s last decode passed (0 before the first); greedy is temperature 0, so the caller says “greedy” from its own request and prints “seed N” for sampled replies

Chat templates stay out of the ABI on purpose: GGUF carries the template as Jinja text (tokenizer.chat_template), which SonicBoom does not interpret; the service renders by family with hand-written Scheme templates. The ABI reports the family (from general.architecture and the template, e.g. gemma, qwen) and the service picks the template.

2. Declarations

/* Opaque handles. */
typedef struct boom_llm_model boom_llm_model;      /* weights, plan, tokenizer      */
typedef struct boom_llm_session boom_llm_session;  /* a KV cache and its tokens     */
typedef struct boom_llm_sampler boom_llm_sampler;  /* sampling parameters + RNG     */

typedef int32_t boom_token;                      /* a vocabulary index            */

/* Status codes appended to boom_status (appending keeps the ABI). */
/*   BOOM_ERR_CONTEXT     = 7   the session would exceed its context length      */
/*   BOOM_ERR_CONSTRAINT  = 8   the constraint callback failed or allowed nothing */
/*   BOOM_ERR_UNSUPPORTED = 9   an optional function this backend doesn't have   */

typedef enum boom_llm_device {
  BOOM_LLM_DEVICE_CPU = 0,
  BOOM_LLM_DEVICE_CUDA = 1,
} boom_llm_device;

/* Versioned by size: the caller sets struct_size = sizeof(...); fields are
 * only ever appended, and the implementation reads the ones that fit. */
typedef struct boom_llm_model_config {
  size_t struct_size;
  boom_llm_device device;
  uint64_t max_context;     /* 0: the model's own context length            */
  uint32_t n_threads;       /* CPU threads, 0: default                       */
} boom_llm_model_config;

typedef struct boom_llm_model_info {
  size_t struct_size;
  const char *id;           /* e.g. the GGUF general.name; owned by the model */
  const char *family;       /* "gemma", "qwen", ...; owned by the model       */
  uint64_t context_length;
  uint32_t vocab_size;
  const boom_token *eos;      /* tokens that end a reply; owned by the model    */
  size_t n_eos;
} boom_llm_model_info;

typedef struct boom_llm_sampler_params {
  size_t struct_size;
  float temperature;        /* 0: greedy                                     */
  float top_p;              /* 1: off                                        */
  uint32_t top_k;           /* 0: off                                        */
  uint64_t seed;
  int has_seed;             /* 0: seeded from a clock                        */
} boom_llm_sampler_params;

/* Constraint: fills mask[0 .. vocab_size) with 1 for allowed tokens, 0 for
 * the others, given the tokens generated so far by this request. Returns 0,
 * or non-zero to fail the step (BOOM_ERR_CONSTRAINT). */
typedef struct boom_llm_constraint {
  size_t struct_size;
  void *user;
  int (*allow)(void *user, const boom_token *generated, size_t n_generated,
               uint8_t *mask, size_t vocab_size);
} boom_llm_constraint;

typedef struct boom_llm_stats {
  size_t struct_size;
  uint64_t prefill_calls, prefill_tokens, reused_tokens, computed_tokens;
  uint64_t steps, sessions_live, forks;
} boom_llm_stats;

/* Model */
boom_status boom_llm_model_load(const char *gguf_path, const boom_llm_model_config *config,
                            boom_llm_model **model_out, boom_error **err_out);
void boom_llm_model_free(boom_llm_model *model);
/* Return the device buffers kept for reuse (a released session's free list) to
 * the driver. Live weights and KV caches are untouched. */
void boom_device_trim(void);
boom_status boom_llm_model_get_info(const boom_llm_model *model, boom_llm_model_info *info_out,
                                boom_error **err_out);
boom_status boom_llm_model_get_stats(const boom_llm_model *model, boom_llm_stats *stats_out,
                                 boom_error **err_out);

/* Tokenizer. Two-call sizing like boom_retrieve_output: with cap too small the
 * call returns BOOM_ERR_BINDING and writes the needed count to *n_out. */
boom_status boom_llm_tokenize(const boom_llm_model *model, const char *text, size_t len,
                          boom_token *out, size_t cap, size_t *n_out, boom_error **err_out);
boom_status boom_llm_detokenize(const boom_llm_model *model, const boom_token *tokens, size_t n,
                            char *out, size_t cap, size_t *len_out, boom_error **err_out);

/* Sessions */
boom_status boom_llm_session_new(boom_llm_model *model, uint64_t n_ctx,
                             boom_llm_session **session_out, boom_error **err_out);
void boom_llm_session_free(boom_llm_session *session);
boom_status boom_llm_session_fork(const boom_llm_session *session, uint64_t n_tokens,
                              boom_llm_session **session_out, boom_error **err_out);

/* Make the session hold exactly tokens[0 .. n); keep the longest common prefix
 * with what it holds, compute the rest. *n_reused_out: tokens kept. */
boom_status boom_llm_prefill(boom_llm_session *session, const boom_token *tokens, size_t n,
                         uint64_t *n_reused_out, boom_error **err_out);

/* Sampler */
boom_status boom_llm_sampler_new(const boom_llm_sampler_params *params,
                             boom_llm_sampler **sampler_out, boom_error **err_out);
void boom_llm_sampler_free(boom_llm_sampler *sampler);

/* Sample the next token from the logits after the session's last token
 * (constraint may be NULL), append it (run its forward step, so its KV and
 * the next logits exist), return it. */
boom_status boom_llm_step(boom_llm_session *session, boom_llm_sampler *sampler,
                      const boom_llm_constraint *constraint, boom_token *token_out,
                      boom_error **err_out);

/* Style steering (the appending subset the service uses). The vector is added
 * to the residual stream after block `layer`, for the rest of the session's
 * life; n must equal the model's embedding length. Any change other than
 * setting the vector already held retires the session's prompt prefix. */
boom_status boom_llm_model_embedding(const boom_llm_model *model,
                                 uint64_t *width_out, boom_error **err_out);
boom_status boom_llm_session_set_steering(boom_llm_session *session, int32_t layer,
                                      const float *vector, size_t n,
                                      boom_error **err_out);
void boom_llm_session_clear_steering(boom_llm_session *session);
/* The residual stream after block `layer` of `tokens`, position-major f32,
 * n * embedding_length floats; two-call sizing, on a throwaway cache. */
boom_status boom_llm_residual_capture(const boom_llm_model *model,
                                  const boom_token *tokens, size_t n, int32_t layer,
                                  float *out, size_t cap, size_t *n_out,
                                  boom_error **err_out);

3. Semantics

4. Ownership and threading

5. Guile side

(sonicboom serve real-backend) builds a make-backend record from these functions through (system foreign) (bindings/guile/scheme/sonicboom/ffi.scm plus the (sonicboom inference) wrappers):

6. What the core provides

the serving path uses today
persistent sessions boom_llm_session_new over planner::KvCacheSession; boom_llm_prefill keeps the longest common prefix
sampling (temperature, top-k, top-p, min-p, seed, penalties) boom_llm_decode over boom_llm_sampling; its sampled path keeps draw state in the session, so repeated max_tokens 1 calls are the serving path’s per-token step
logit mask before sampling the session’s compiled grammar; the argmax / sampled-select kernel applies its bitmap
tokenizer and EOS ids from GGUF metadata boom_llm_tokenize(_ex), boom_llm_detokenize, boom_llm_model_eos
model introspection (not used by the serving path) boom_llm_model_info / boom_image_model_info: a JSON document read from the model’s own files (header-level), with the architecture, parameter count, quantization mixture, context length, vocabulary size and capability flags; the Guile model-info / image-model-info bindings return it parsed
style steering and residual capture a steer node the prefill and decode graphs carry after block L (one add_bias over the residual rows, the vector in a device slot the backend owns), and the prefill graph truncated after block L for the capture; a steered session runs the executor’s uncaptured steps

Not in the ABI yet: session fork (boom_llm_session_fork), a sampler handle (boom_llm_sampler_new — parameters are passed to each boom_llm_decode call instead), and stats counters. The service above the backend supplies its own request statistics.