diff --git a/CHANGELOG.md b/CHANGELOG.md index aa53e38..abbfcad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,453 @@ All notable changes to BaseRT. This project is pre-1.0, so minor versions may include behavior changes. Format loosely based on [Keep a Changelog](https://keepachangelog.com). +## [0.5.1] — 2026-11-16 + +**`basert serve` uses speculative decoding by default.** A model drafts with +the drafter the catalog pairs with it, or with the MTP head its file carries; +`--speculate off` serves it plainly. The C API also reports GPU faults. + +### Changed + +- **Speculative decoding by default in `basert serve`.** A start that names no + `--speculate` strategy works like `--speculate auto`, and downloads the + paired drafter first when it is not installed (1.4 GB for Qwen3.8-27B, 458 MB + for Qwen3.6-35B-A3B on a Mac). `--offline` downloads nothing. Greedy output + can differ slightly from plain decoding unless `--spec-bitexact` is set. The + automatically sized context window leaves room for the drafter. + +### Added + +- **GPU faults in the C API.** When a GPU command fails, `baseRT_prefill`, + `baseRT_decode_step` and the logits reads fail with `BASERT_ERR_GPU` and + leave the KV cache as it was, where they used to return success with the + logits unwritten. `baseRT_gpu_error()` reports a fault, and forward passes + refuse until `baseRT_clear_gpu_error()` is called. +- **More quantization formats for mixture-of-experts models on Macs.** Expert + weights in GGUF `Q4_K`, `Q5_K` or `IQ4_XS`, or in `base_q5` with groups of + 64, run with their own kernels. `basert convert --kquant-passthrough` keeps + `Q4_K`, `Q5_K` and `IQ4_XS` expert weights from a GGUF as they are. +- **AWQ in the converter.** `basert convert` runs AWQ's scale search itself and + folds the scales into the model's weights, so the result needs no special + kernel. New commands for quantization work: `basert overlay`, `merge`, + `fakequant`, `awq-search`, `fingerprint` and `inventory`. + +### Fixed + +- BaseQuant-V1 models load with their projections fused, without the + `k-quant fuse refused` warnings; output is unchanged. +- DGX Spark no longer refuses a model that fits: the free-memory check now + counts the file cache Linux hands back on demand. +- Models with 6-bit mixture-of-experts weights are no longer marked as + NVIDIA-only by the converter. Re-convert an older file to run it on a Mac. + +The engine ABI is unchanged since 0.4.0 (superfluid 0.1.13 serves it). + +## [0.5.0] — 2026-11-12 + +**BaseRT runs on AMD GPUs.** The engine, the `.base` files and `basert serve` +now run on Linux x86-64 with an AMD Ryzen AI Max (Strix Halo: Radeon 8060S or +8050S) or a Ryzen AI 300 / 400 with a Radeon 890M or 880M (Strix Point, +Gorgon Point). + +### Added + +- **AMD GPUs on Linux.** A new `basert-engine-linux-x64-rocm` bundle, taken by + the install script, `pip install basert`, npm and Homebrew on Linux. Needs + Ubuntu 24.04 or newer (glibc 2.39+), ROCm 10 from AMD's repository + (`amdrocm-blas10.0-gfx1151` on Strix Halo, `-gfx1150` on Strix Point and + Gorgon Point) and a recent kernel (Ubuntu 24.04's HWE kernel + 6.17.0-19.19~24.04.2 or later, its OEM kernel 6.14.0-1018 or later, or Linux + 6.18.4). `basert self update` works on Linux x86-64. +- **What runs on AMD:** dense and mixture-of-experts text models, the Qwen3.5 + and 3.6 hybrids, and gemma-4 with image input, with paged KV, prefix caching, + batching and a quantized KV cache, served through superfluid. +- **Speculative decoding on AMD** with MTP heads, DFlash, DSpark and EAGLE-3. + +### Changed + +- **Long context on DGX Spark.** gemma-4-E2B and 26B-A4B prefill 8K–32K-token + prompts 5 to 38 times as fast as in 0.4.7, and gemma-4 and Qwen3-8B decode + 1.6 to 4.6 times as fast at a 16K–32K context. +- gemma-4-26B-A4B decodes 6.7% faster on M5 Pro Macs, with the same output. + +### Fixed + +- Qwen3.6-35B-A3B prefill on M5 and M6 Macs uses the new expert kernels again + (4–8% faster than the fallback). +- Qwen3.5 and 3.6 prompts on NVIDIA GPUs are processed in full-size chunks + again, restoring 0.4.6's speed. +- gemma-4-26B-A4B serving no longer leaks GPU memory per generated token. +- A library user that exits with a Qwen3.5 or 3.6 model still loaded no longer + aborts at exit on M4, M5 and M6 Macs. +- When several long requests outgrow the KV cache, the engine declines the step + before changing anything instead of failing partway with an HTTP 500. +- Qwen3.5 and 3.6 loads on NVIDIA no longer print a `CUDA_ERROR_NOT_FOUND` line. +- A file that packs its quantization groups across rows is refused at load, + naming the tensor, instead of giving wrong output. + +## [0.4.7] — 2026-11-10 + +**Prefill with the Neural Engine on Apple Silicon**, and `basert` on PyPI. + +### Added + +- **Prefill on the Neural Engine.** On M4-, M5- and M6-generation Macs, a large + dense model's feed-forward layers, and the Qwen3.5 / 3.6 / 3.8 hybrids' + recurrent and attention projections, are split between the GPU and the + Neural Engine during prefill. Qwen3.8-27B at Q4 prefills 1k-token prompts at + about 700 tokens/s on an M5 Pro, from 531. The split computes in 8-bit + integers, so prefill output is no longer bit-for-bit the GPU's; perplexity is + unchanged within noise and decoding is untouched. +- Turn it off with `--no-ane` on `basert bench`, `chat` and `complete`, + `baseRT_set_neural_engine(0)` before loading (`setNeuralEngine(false)` in the + Swift and Node bindings), or superfluid's `--basert-neural-engine off`. + `baseRT_prepare_neural_engine()` compiles a model's Neural Engine programs + ahead of its first load. +- **`pip install basert`** installs the `basert` command, the prebuilt engine + and the Python bindings (macOS 15+ on Apple Silicon, Linux arm64 with CUDA 13; + Python 3.9+). Published since 0.4.6. + +### Changed + +- The hybrid models keep their recurrent state at every 64-, 256- and + 1024-token boundary, so a served prompt reuses more of a shared prefix. +- A DFlash drafter no longer holds up the first token. +- Faster prefill on 32-core and larger M5 GPUs, and faster speculative verify + on 16- to 20-core M5 GPUs. + +## [0.4.6] — 2026-11-06 + +### Added + +- `basert serve --speculate auto` drafts Qwen3.8-27B and + Qwen3.6-35B-A3B with their DFlash2 drafters, downloading the drafter the first + time (Apple Silicon; needs superfluid 0.1.10). + +### Changed + +- Faster DFlash2 speculative decoding on Apple Silicon (Qwen3.6-35B-A3B 179.0 → + 214.8 tokens/s at one request on an M5 Pro). `BASERT_SPEC_BITEXACT=1` keeps + the earlier, bitwise-plain route. +- gemma-4-26B-A4B decodes faster on Apple Silicon (17.04 → 13.34 ms a token on + an M5 Pro), and its MTP head accepts more drafts. Its token table is held at + 8 bits in memory, which changes plain-decode output slightly. + +### Fixed + +- `--speculate dflash:.base` with the drafter as a separate word no + longer reads the drafter as a second model to serve. + +## [0.4.5] — 2026-11-05 + +### Added + +- Speculative decoding on gemma-4-26B-A4B with Google's own assistant head, + now carried in the catalog bundles (`--speculate mtp-head` or `auto`). +- `basert add-speculator` embeds a head converted with `--quantize-drafter`, + not only f16 heads. +- Releases that come in sizes rather than quants (the BaseQuant repositories, + `-XS` … `-XL`) pull their Medium by default; a size names a variant + (`basert pull :small`), and `basert pull --dry-run` says which file + it would take. + +### Changed + +- On Apple Silicon, mixture-of-experts models verify speculative drafts on the + batched decode route (three rows at 1K context: 58 → 30 ms). + +## [0.4.4] — 2026-11-03 + +### Added + +- Speculative decoding for Qwen3.8-27B and Qwen3.6-35B-A3B on Apple Silicon + with the DFlash 2 block drafters, paired in the catalog + (`--speculate dflash:basecompute/Qwen3.8-27B-DFlash2`). + +### Changed + +- Gemma 4 prompts served from a paged KV cache prefill at `basert bench` speed. +- Under several concurrent requests, a request a gate takes out of + speculation keeps drafting along with the others instead of decoding plainly. +- Bundles converted from GGUF declare tensor shapes in the same order as every + other source. Older bundles keep working; re-converting restores fused QKV + attention for models with narrower K/V projections. + +### Fixed + +- Logits past 2 GiB in a 16,384-token prefill chunk came out zero on Apple + Silicon (32-bit tile offsets). +- Some served prompts of 512–4,096 tokens ran their first chunk without a + causal mask on Qwen3.5 / 3.6 full-attention layers (present since 0.3). +- Qwen3.5-2B at Q4 repeated its first token on a single request. +- Vocabulary entries shaped like markers (``, `[:]`) are tokenized as + ordinary text; only special added tokens are cut out. +- `basert self update --dry-run` names the superfluid the update would bring. + +## [0.4.3] — 2026-10-29 + +### Added + +- **`basert self update`** updates an install-script install: the newest + release is unpacked under `~/.basert/versions//`, its SHA-256 and launcher + checked, and made current in one step. `basert self use ` goes back, + `self check` and `self list` report. Package-manager installs are updated by + their package manager. +- Speculative decoding on Gemma 4 E2B and E4B with Google's assistant head, + carried in the catalog bundles (`--speculate mtp-head` or `auto`). + `basert add-speculator` and `basert convert --mtp-head` embed a head in a + bundle of your own. + +### Changed + +- Gemma 4 draft verification runs on the GPU argmax and decode attention + kernels on Apple Silicon. + +### Fixed + +- superfluid installed by Homebrew, npm, pip, uv or cargo now goes to BaseRT's + data directory and survives package upgrades. + +## [0.4.2] — 2026-10-27 + +### Added + +- **Package registries.** `brew install basecompute/tap/basert`, `npm install + -g @basecompute/basert` (the command and engine) or `npm install + @basecompute/basert` (Node bindings), and the `baseRT` / `baseRT-sys` crates + plus `cargo install basert-cli` on crates.io. For Apple Silicon on macOS 15+ + and Linux arm64 with an NVIDIA GPU and CUDA 13. +- The engine license covers Linux systems with an NVIDIA GPU. +- `basert pull :` pulls a named variant; an installed variant is + used without contacting Hugging Face. + +### Changed + +- Faster batched decode of GGUF k-quant bundles on M1 Max, M3 Ultra, M4 Max, + M5 Max and M6, and faster k-quant prefill on M5. +- 8-bit group-64 bundles prefill up to 2.3× faster on M5. + +### Fixed + +- Gemma 4 requests that declare tools no longer spend seconds tokenizing. + +## [0.4.1] — 2026-10-23 + +### Added + +- `basert pull --file ` downloads a `.base` by file name; + `basert list --json` reports the file each install came from. + +### Changed + +- When superfluid is missing, `basert serve` installs its newest release that + serves this engine. +- Batched decode of GGUF k-quant bundles is 1.5–3.5× faster on M1, M3, M4, M5 + and M6 Macs. +- A pull with no matching quant lists the repo's files and suggests `--file`. + +### Fixed + +- Gemma 4 decodes up to four times faster through `basert serve` with long + prompts. + +## [0.4.0] — 2026-10-22 + +### Added + +- GGUF `Q3_K`, `IQ4_XS`, `IQ2_XS`, `IQ2_S`, `IQ3_XXS` and `IQ3_S` weights run + natively on Macs, alongside `Q4_K`, `Q5_K` and `Q6_K`. +- `basert serve` installs and runs superfluid's own release. +- The engine library carries an ABI number (`BASERT_ABI_VERSION`, + `baseRT_abi_version()`), published with each release as + `basert-engine-abi-.txt`. + +### Fixed + +- Qwen 3.5 and 3.6 mixture-of-experts models decode up to 12% faster on Mac. +- Qwen 3.8 bundles with GGUF weights no longer decode garbage on M5 Max. +- A bundle with weights this build cannot run is refused when it opens. + +## [0.3.0] — 2026-10-08 + +**`basert serve` is a new server.** It keeps the command line and the +OpenAI-compatible API, and runs them on +[superfluid](https://github.com/basecompute/superfluid). This release also +carries the fixes prepared for 0.2.7, which was not published. + +### Added + +- **Serving.** Continuous batching and prefix reuse are always on; + `--continuous-batching [N]` or `--max-batch-size N` serves several requests + at once. Streamed tool calls arrive as partial deltas, `tool_choice` naming a + function or `required` is honoured, `/v1/completions` accepts `suffix`, and + `/v1/models` lists each model's capabilities. +- **Larger windows for hybrid models.** The paged KV cache charges only the + attention layers, so Qwen 3.5 / 3.6 / 3.8 get context windows up to four + times larger from the same memory. +- GLM 5.2 serves with continuous batching on Metal and speculates with its MTP + head. +- Block drafters with a reduced draft vocabulary convert and serve; + `basert complete --spec` turns speculation on for a bundle with its own head. + +### Changed + +- Flags the new server has no use for are accepted and noted on stderr. +- Server state lives under `$BASERT_STATE_DIR`, one directory per port. +- `/v1/models` reports the window as `meta.n_ctx`, `/metrics` series are named + `superfluid_*`, and replies say `system_fingerprint: superfluid`. +- Text that looks like a chat marker inside a message is content, never + framing. + +### Fixed + +- Gemma 4 26B-A4B misread every image (a vision-encoder step was skipped). +- Hybrid-model prefix reuse survives a replayed or branched conversation. +- Llama-family models no longer produce garbage in batch-invariant mode + (`BASERT_BATCH_INVARIANT=1`). +- On NVIDIA, a LoRA adapter on Qwen 3.5's shared-expert gate is applied during + generation, and two mixture-of-experts paths read mixed scale formats + correctly. +- The GPU sampler treated `top_k: 0` as greedy. + +## [0.2.6] — 2026-09-18 + +### Fixed + +- Qwen3.x 27B and 35B-A3B models produced garbage after the first token on + M1-family Macs (0.2.4 and 0.2.5). + +### Changed + +- A GPU dispatch the hardware would silently skip now stops with an error + naming the kernel. + +## [0.2.5] — 2026-09-17 + +### Added + +- **Streaming tool calls.** With `stream: true`, a tool call arrives as an + opening `delta.tool_calls` entry with its name, then `function.arguments` + fragments. A call cut short by the token budget keeps + `finish_reason: "length"`. +- `basert-benchmark-harness` reports telemetry from the measured run and gains + `--headline-first`, `--isolated-workloads`, `--workload` and + `--idle-baseline`. + +### Changed + +- Benchmark report schema: same-run telemetry is `basert-telemetry/4` + (breaking for report consumers). + +### Fixed + +- `basert pull ` from Hugging Face failed with + `no .safetensors shards` after downloading the whole model. + +## [0.2.4] — 2026-09-09 + +**Three new model families, and a context window that sizes itself.** + +### Added + +- **Automatic context sizing.** `basert serve`, `chat` and `complete` derive + the window from the GPU memory available, the weights and the KV cost per + token, capped at the model's trained window. `--max-context N` pins one. +- **gpt-oss** (`basecompute/gpt-oss-20b`, bf16 / Q8 / Q4), with its MXFP4 + experts carried verbatim and Harmony tool calls parsed. +- **Nemotron 3 Nano** (`basecompute/NVIDIA-Nemotron-3-Nano-30B-A3B`), a + Mamba-2 hybrid. +- **GLM 5.2**, with multi-head latent attention and the sparse indexer. + +### Changed + +- **`BaseRTModelConfig` changed layout** — recompile anything built against + 0.2.3 that reads it. +- The shared library reports its real version, and the macOS archive ships the + symlink its install name needs. + +### Fixed + +- gpt-oss NaNs and runaway generation after a tool call; a stray end-of-turn + token on large models under batching; LoRA adapters ignoring penalties, + `logit_bias` and `seed`; a temporary file left by a failed conversion. + +## [0.2.3] — 2026-08-19 + +**Model pulls that finish.** + +### Added + +- `basert pull` downloads over many connections at once and resumes per chunk + after an interruption, across process restarts. A stalled transfer is cut + off and retried, and a short one is reported instead of installed. Tunable + with `BASERT_HF_CONNECTIONS`, `BASERT_HF_CHUNK_MB`, + `BASERT_HF_READ_TIMEOUT_SECS` and `BASERT_HF_MAX_RETRIES`. +- Xet transfers behind `BASERT_HF_XET=1` (deduplicated, not resumable). + +### Fixed + +- Muse Glimmer's tool calls are parsed as tool calls. +- `--kquant-passthrough` embeddings on models other than Muse Glimmer. +- `developer` and `function` roles no longer break a model's native template. +- Chat templates using `is undefined` render instead of falling back to + ChatML. + +### Changed + +- Building `base-convert` requires Rust 1.85+. + +## [0.2.2] — 2026-08-12 + +**Muse Glimmer, and native GGUF k-quants.** + +### Added + +- Muse Glimmer 30B, text and vision (`basecompute/Muse-Glimmer-30B`). +- GGUF `Q4_K` / `Q5_K` / `Q6_K` (and `Q2_K`, `Q3_K`) run natively on Apple + Silicon. `basert convert --kquant-passthrough` copies GGUF super-blocks into a + `.base` verbatim, and `--mmproj` folds a companion `mmproj-*.gguf` vision + tower into the same bundle. + +### Changed + +- Short prompts prefill 1.4–1.55× faster on M5; k-quant prefill 3.4× faster. + +### Fixed + +- M3 Ultra was identified as a base M3. +- The Python, Rust and Node mirrors of the model-config struct had fallen + behind the C header; a test now holds them in step. +- Models converted from GGUF ignored the end-of-turn token. + +## [0.2.1] — 2026-08-09 + +**Speech-to-text.** All twelve OpenAI Whisper variants, `tiny` to +`large-v3-turbo` including the `.en` builds, run as `.base` bundles on Metal +and CUDA. + +### Added + +- Whisper conversion with `whisper-q8` and `whisper-q4` profiles. +- `POST /v1/audio/transcriptions` and `/v1/audio/translations`, including + `verbose_json`, and streaming transcription (`stream: true`). +- C API: `baseRT_load_model_ex` with `BaseRTLoadOptions`, Whisper task and + prompt setters with per-segment results, batched-logits helpers, and + `baseRT_capabilities`. + +### Changed + +- Faster shared-prefix serving and CUDA MoE decode; f32 accumulation on lossy + Metal GEMM paths. + +### Fixed + +- `context_length_exceeded` reports the real token count. +- Image requests under-reported usage and never returned + `finish_reason: "length"`. +- Gemma 4 audio embeddings, repetition penalty on some Apple GPUs, a KV-cache + shift data race, and unbounded rate-limit buckets. + ## [0.2.0] — 2026-07-31 **A second hardware backend.** BaseRT now runs on **NVIDIA GB10 (DGX Spark, diff --git a/README.md b/README.md index 9c4ac4b..16ce422 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ **Fastest LLM inference on Apple Silicon — now on NVIDIA GB10 (DGX Spark) and AMD Strix Halo / Strix Point, too.** -Pull a model from HuggingFace, chat with it, or serve an OpenAI-compatible API — all from one CLI. +Pull a model from HuggingFace, chat with it, or serve it over OpenAI-, Anthropic- and Ollama-compatible APIs — all from one CLI. -[![Docs](https://img.shields.io/badge/docs-docs.basecompute.co-5b8fa8)](https://docs.basecompute.co) +[![Docs](https://img.shields.io/badge/docs-basert.basecompute.co-5b8fa8)](https://basert.basecompute.co) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) [![Platform](https://img.shields.io/badge/platform-Apple%20Silicon%20%C2%B7%20NVIDIA%20GB10%20%C2%B7%20AMD%20Strix-black)](#requirements) [![Bindings](https://img.shields.io/badge/bindings-Python%20%C2%B7%20Node%20%C2%B7%20Rust%20%C2%B7%20Swift-444)](docs/bindings/index.md) @@ -22,21 +22,23 @@ engine: the `basert` CLI (model hub + converter), the `.base` model format, the public C API, and language bindings for Python, Node, Rust, and Swift. - **One CLI for everything** — `basert pull`, `chat`, `serve`, `convert`. -- **OpenAI-compatible server** — chat, completions, embeddings, transcription, - tool calls, continuous batching, paged-KV, and prefix caching. +- **A local API server** — `basert serve` runs + [Superfluid](https://github.com/basecompute/superfluid): OpenAI-, Anthropic- + and Ollama-compatible endpoints, tool calls, continuous batching, prefix + caching and speculative decoding. - **Multimodal** — text, vision, and audio on supported models. - **Its own `.base` format** — affine quantization (Q2–Q8), optional AWQ calibration, and signed bundles. - **Bindings everywhere** — Python, Node, Rust, and Swift over a stable C API. - **A drop-in coding-agent backend** — see [below](#use-it-as-a-coding-agent). -> **Documentation:** **[docs.basecompute.co](https://docs.basecompute.co)** (source in [`docs/`](docs/index.md)). +> **Documentation:** **[basert.basecompute.co](https://basert.basecompute.co)** (source in [`docs/`](docs/index.md)). The server's API is documented at [docs.basecompute.co](https://docs.basecompute.co). ## Requirements One of: -- Apple Silicon (M1 or later), macOS 14+. +- Apple Silicon (M1 or later), macOS 15+. - NVIDIA GB10 (DGX Spark), Linux / arm64 with a CUDA driver. - AMD Strix Halo (Ryzen AI Max, gfx1151) or Strix Point (Ryzen AI 300, gfx1150), Linux / x86-64 on Ubuntu 24.04 or newer, with the ROCm 10 runtime @@ -70,8 +72,18 @@ curl -LsSf https://basecompute.co/install.sh | sh This installs the prebuilt engine for your platform and the `basert` CLI to `~/.basert` and adds it to your `PATH`. Restart your shell afterward (or -`export PATH="$HOME/.basert:$PATH"`). See -[Installation](docs/getting-started/installation.md) for building from source. +`export PATH="$HOME/.basert:$PATH"`). Update later with `basert self update`. + +Or use a package manager: + +```sh +brew install basecompute/tap/basert +pip install basert # also pipx / uv tool +npm install -g @basecompute/basert +``` + +See [Installation](docs/getting-started/installation.md) for the details and +for building from source. ### 2. Pull a model @@ -80,8 +92,8 @@ basert pull Qwen/Qwen3-4B # download from HuggingFace + convert to .base basert list # show installed models ``` -Models are cached under `~/.cache/baseRT/models` (override with -`$BASERT_MODELS_DIR`). To pick a specific quant build, append `:default-q8` to +Models are cached under `~/Library/Caches/baseRT/models` on macOS and +`~/.cache/baseRT/models` on Linux (override with `$BASERT_MODELS_DIR`). To pick a specific quant build, append `:default-q8` to the id (or pass `--variant default-q8`). ### 3. Chat @@ -90,7 +102,7 @@ the id (or pass `--variant default-q8`). basert chat Qwen/Qwen3-4B ``` -### 4. Serve an OpenAI-compatible API +### 4. Serve an API ```sh basert serve Qwen/Qwen3-4B --api-key "$(uuidgen)" --port 8080 @@ -134,8 +146,9 @@ Inside pi, run `/model` to pick a served model. See the ## The `basert` CLI -`basert` is a single front-end. Model-management commands run natively; runtime -commands are forwarded to the matching `basert-` engine binary. +`basert` is a single front-end. Model-management commands run natively; `chat`, +`complete` and `bench` run the matching `basert-` engine binary, and `serve` +runs Superfluid, installing it on first use. | Command | What it does | | --- | --- | @@ -143,11 +156,14 @@ commands are forwarded to the matching `basert-` engine binary. | `basert list` | List installed models (`--remote` to include the catalog) | | `basert convert ` | Convert a local GGUF / HF / MLX checkpoint to `.base` | | `basert chat ` | Interactive chat | -| `basert serve ` | OpenAI-compatible HTTP server (`--model` repeats for multi-model) | +| `basert serve ` | HTTP server (Superfluid; `--model` repeats for multi-model) | | `basert complete ` | One-shot completion (text / image / audio) | | `basert bench ` | Throughput benchmark | | `basert inspect ` | Dump a `.base` header + tensor inventory | | `basert sign` / `verify` / `keygen` | ed25519 signing of `.base` bundles | +| `basert computearena` | Run a ComputeArena benchmark and save a signed report | +| `basert superfluid install` / `status` | Install or check the server `basert serve` runs | +| `basert self update` / `check` / `list` / `use` | Update basert, or switch between installed versions | Full flag reference: [CLI reference](docs/cli/reference.md). @@ -159,7 +175,7 @@ Full flag reference: [CLI reference](docs/cli/reference.md). | [`include/baseRT/`](include/baseRT/) | The stable public C API (`baseRT.h`, `types.h`). | | [`bindings/`](bindings/) | Python, Node, Rust, and Swift. | | [`benchmarks/`](benchmarks/) | Scripts and reference results. | -| [`docs/`](docs/index.md) | The documentation site. | +| [`docs/`](docs/index.md) | The documentation site ([basert.basecompute.co](https://basert.basecompute.co)). | This repository — the CLI, `.base` format, public headers, and bindings — is licensed under **Apache-2.0**. The engine ships as a separate prebuilt binary @@ -168,7 +184,7 @@ under its own license; see ## Links -- **[Documentation](https://docs.basecompute.co)** · [Server API](docs/reference/server-api.md) · [`.base` format](base-convert/FORMAT.md) +- **[Documentation](https://basert.basecompute.co)** · [Server API](docs/reference/server-api.md) · [`.base` format](base-convert/FORMAT.md) - [Security policy](SECURITY.md) · [Contributing](CONTRIBUTING.md) ## License diff --git a/SECURITY.md b/SECURITY.md index f859bce..b53833a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,9 +2,9 @@ ## Supported Versions -baseRT is pre-1.0. Security fixes are applied to the current `v1.0` -branch only. Once we tag a `v1.0.0` release, the latest minor will be -supported for security fixes; older minors may not be. +baseRT is pre-1.0. Security fixes go into the next release only; update +with `basert self update`. Once we tag a `v1.0.0` release, the latest +minor will be supported for security fixes; older minors may not be. ## Reporting a Vulnerability @@ -37,15 +37,20 @@ depend on severity; we will coordinate disclosure with you. ## Hardening notes for operators -The HTTP server shipped via `basert-serve` is intended for trusted -networks. Before exposing it to a public network: +`basert serve` runs [Superfluid](https://github.com/basecompute/superfluid), +which is intended for trusted networks. Before exposing it to a public +network: -- Always set `--api-key` to a non-empty value. The server will print a - loud warning at startup if no key is set. +- Always set `--api-key` to a non-empty value. The server prints a + warning at startup when it binds off loopback without one. - Bind to a specific interface; do not bind to `0.0.0.0` without an upstream auth layer. - Place it behind a reverse proxy (nginx, Caddy) that enforces TLS, rate limiting, and request-size limits independent of the server's own caps. - Restrict who can call `POST /v1/models/load` — that endpoint accepts - a file path, and on the host where the server runs. + a file path on the host where the server runs. + +See [Security](docs/reference/security.md) for the rest, and +[Superfluid's security policy](https://github.com/basecompute/superfluid/blob/main/SECURITY.md) +for issues in the server itself. diff --git a/base-convert/profiles/PROFILES.md b/base-convert/profiles/PROFILES.md index ec72cb1..5abbd5a 100644 --- a/base-convert/profiles/PROFILES.md +++ b/base-convert/profiles/PROFILES.md @@ -21,12 +21,13 @@ tensor, matched by glob pattern. Pass one with `--profile `. from most-specific to the catch-all `**`. - `dtype` — `f16`, `bf16`, `f32`, or a packed quant: `base_q2` … `base_q8` (see `CANONICAL_QUANT_SPEC.md` for the layouts). -- Optional `calibration` block enables AWQ: - ```json - "calibration": { "method": "awq", "tokens": 1024, "dataset": "wikitext-103" } - ``` - AWQ needs a calibration corpus; download WikiText-103 and pass - `--calib-file `. +- Optional `"algo": "awq"` on a rule asks for AWQ on the tensors it matches + (the default is `"rtn"`, round to nearest). AWQ also needs an + activation-stats sidecar, passed to `basert convert` with + `--awq-profile `; see + [AWQ calibration](../../docs/guides/converting.md#awq-calibration). +- A top-level `calibration` block is accepted and recorded, but does not turn + AWQ on; the per-rule `algo` does. ## Bundled profiles diff --git a/benchmarks/README.md b/benchmarks/README.md index 7c0d7c1..d063958 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -2,26 +2,20 @@ Reproduce baseRT throughput numbers on your own hardware. -## Prerequisites - -1. Download an engine release and unpack it into `build/` at the repo root - (see the top-level README's "Getting the engine"). You need `build/basert-bench`. -2. Convert a model to `.base` (see `base-convert/`) into `models/`. - ## Run -```sh -# benchmark every models/*.base, 5 reps, pp ∈ {128,256,512}, tg 128 -benchmarks/scripts/run_bench.sh +Install baseRT (see [Installation](../docs/getting-started/installation.md)), +then benchmark a model with `basert bench`: -# or a specific model / custom sweep -PP_VALS="128 512" REPS=3 benchmarks/scripts/run_bench.sh models/your-model.base +```sh +basert bench basecompute/Qwen3-4B # pp512 / tg128, 5 reps +basert bench ./models/your-model.base -p 128 -n 128 -r 3 ``` -Results are written to `benchmarks/results/_baseRT.csv` with columns -`model,size_mb,engine,test,tok_per_sec,stddev`. `ppN` rows are prefill -throughput at prompt length N; `tgN` rows are decode (token-generation) -throughput. +`ppN` is prefill throughput at prompt length N; `tgN` is decode +(token-generation) throughput. See +[Benchmarking](../docs/guides/benchmarking.md) for every flag and for +ComputeArena, which saves a signed report. ## Example results @@ -30,10 +24,9 @@ numbers from earlier runs (dated by commit). They are not continuously republished — regenerate locally for an apples-to-apples comparison with your build and models. -## Legacy / comparison scripts +## Scripts -The other scripts in `scripts/` (`mlx_benchmark.sh`, `gguf_benchmark.sh`, -`three_way_benchmark.sh`, `uzu_benchmark.sh`, …) compare against external engines -(mlx-lm, llama.cpp, uzu). They require those tools installed and predate the -`.base`-only loader, so they reference GGUF inputs — keep them as a reference for -methodology rather than a turnkey run. +The scripts in `scripts/` sweep `basert-bench` over a model list (override the +binary with `BASERT`) and compare against external engines (mlx-lm). They need +those tools installed and name their own model files; keep them as a reference +for methodology rather than a turnkey run. diff --git a/docs/bindings/index.md b/docs/bindings/index.md index 0b036ca..209d75e 100644 --- a/docs/bindings/index.md +++ b/docs/bindings/index.md @@ -1,33 +1,53 @@ # Bindings -BaseRT exposes a stable C API (`include/baseRT/baseRT.h`) and ships idiomatic -wrappers for four languages. All of them link the single `libbaseRT.dylib` -(Metal kernels embedded) — no separate `.metallib` to manage. +BaseRT exposes a C API (`include/baseRT/baseRT.h`) and ships idiomatic +wrappers for four languages. All of them drive the same engine library: +`libbaseRT.dylib` on macOS (Metal kernels embedded, no separate `.metallib` +to manage) and `libbaseRT.so` on Linux. -| Language | Package | Import | Source | +| Language | Install | Import | Source | | --- | --- | --- | --- | -| [Python](python.md) | `baseRT` | `import baseRT` | [`bindings/python`](https://github.com/basecompute/baseRT/tree/main/bindings/python) | -| [Node](node.md) | `@baseRT/node` | `import { BaseRTModel }` | [`bindings/node`](https://github.com/basecompute/baseRT/tree/main/bindings/node) | -| [Rust](rust.md) | `baseRT` | `use baseRT::…` | [`bindings/rust`](https://github.com/basecompute/baseRT/tree/main/bindings/rust) | -| [Swift](swift.md) | `BaseRT` | `import BaseRT` | [`bindings/swift`](https://github.com/basecompute/baseRT/tree/main/bindings/swift) | +| [Python](python.md) | `pip install basert` | `import baseRT` | [`bindings/python`](https://github.com/basecompute/baseRT/tree/main/bindings/python) | +| [Node](node.md) | `npm install @basecompute/basert` | `import { BaseRTModel } from "@basecompute/basert"` | [`bindings/node`](https://github.com/basecompute/baseRT/tree/main/bindings/node) | +| [Rust](rust.md) | `cargo add baseRT` | `use baseRT::…` | [`bindings/rust`](https://github.com/basecompute/baseRT/tree/main/bindings/rust) | +| [Swift](swift.md) | local Swift package | `import BaseRT` | [`bindings/swift`](https://github.com/basecompute/baseRT/tree/main/bindings/swift) | + +The PyPI and npm packages include the prebuilt engine for your platform. The +Rust crates and the Swift package link an engine you have installed. ## Finding the engine -Each binding needs to locate `libbaseRT.dylib` at runtime. Unpack an -[engine release](../reference/engine-releases.md) into `build/` at the repo root -(the default search path) or set: +Each binding needs to locate the engine library. Without an override, the +bindings look in this order: + +1. The engine inside the package (`pip install basert`, `npm install + @basecompute/basert`) — Python and Node. +2. A source checkout's `build/` directory. +3. An install-script engine: `$BASERT_INSTALL_DIR`, default `~/.basert`. +4. Homebrew: `/opt/homebrew/opt/basert/libexec` on macOS, + `/home/linuxbrew/.linuxbrew/opt/basert/libexec` on Linux. + +To point a binding at a specific engine instead, set: + +| Variable | Used by | Value | +| --- | --- | --- | +| `BASERT_LIB_PATH` | Python, Node | The library file itself | +| `BASERT_LIB_DIR` | Rust, Swift | The directory containing it | -| Variable | Used by | -| --- | --- | -| `BASERT_LIB_PATH` | Python, Node | -| `BASERT_LIB_DIR` | Rust, Swift | +The Swift package uses `BASERT_LIB_DIR`, or the checkout's `build/`, only. -The dylib carries the Metal kernels and its own framework/C++ dependencies, so -it's a single redistributable artifact across every binding. +An [engine release](../reference/engine-releases.md) unpacked into `build/` +at the repo root works for all four. ## Shared model All bindings load the same `.base` files you produce with `basert pull` / -`basert convert`, and expose the same primitives: encode/decode, prefill, single -or streaming generation, embeddings, chat-template formatting, and (for -Whisper-class models) transcription. +`basert convert`, and expose the same primitives: encode/decode, prefill, +single or streaming generation, multi-turn continuation from the KV cache, +embeddings, chat-template formatting, and (for Whisper models) transcription. +Python, Node and Swift add image and audio prefill for multimodal models. Node +and Swift also expose the process-wide engine settings, such as the KV-cache +width and the Neural Engine prefill split; set those before loading a model. + +A model handle is single-owner: use one model from one thread at a time, and +don't call a model from inside its own token callback. diff --git a/docs/bindings/node.md b/docs/bindings/node.md index add93b6..5332ce0 100644 --- a/docs/bindings/node.md +++ b/docs/bindings/node.md @@ -1,52 +1,105 @@ # Node -TypeScript / Node.js bindings (`@baseRT/node`) over the BaseRT C API via FFI. -Node 18+. +TypeScript / Node.js bindings over the BaseRT C API, built on the +[koffi](https://koffi.dev) FFI (no native addon to compile). Node 18+. ## Install ```sh -cd bindings/node -npm install -npm run build +npm install @basecompute/basert # the bindings, in a project +npm install -g @basecompute/basert # the basert command ``` -Point at the engine dylib if needed: +[`@basecompute/basert`](https://www.npmjs.com/package/@basecompute/basert) +carries the bindings and the `basert` command. The prebuilt engine comes as +one optional dependency per platform, and npm installs only the one that +matches the machine, so don't install with `--omit=optional`: + +| Engine package | Platform | +| --- | --- | +| `@basecompute/basert-darwin-arm64` | Apple Silicon, macOS 15 or later | +| `@basecompute/basert-linux-arm64-cuda` | Linux arm64 with an NVIDIA GPU and the CUDA 13 runtime | +| `@basecompute/basert-linux-x64-rocm` | Linux x86-64 with an AMD Strix Halo or Strix Point GPU and the ROCm 10 runtime | + +From a source checkout: ```sh -export BASERT_LIB_PATH=/path/to/build +cd bindings/node +npm install +npm run build +export BASERT_LIB_PATH=/path/to/libbaseRT.dylib # or libbaseRT.so on Linux ``` +Without `BASERT_LIB_PATH`, the bindings look for the npm engine package, then +the checkout's `build/`, then `~/.basert` (the install script) and Homebrew. +See [Finding the engine](index.md#finding-the-engine). + ## Generate text ```ts -import { BaseRTModel } from "@baseRT/node"; +import { BaseRTModel } from "@basecompute/basert"; const model = new BaseRTModel("models/your-model.base"); const tokens = model.encode("Hello, world!"); const stats = model.generate(tokens, 128, { temperature: 0.7 }, (id, text) => { process.stdout.write(text); // streamed token callback + return true; // false stops generation }); console.log(`\n\nGenerated ${stats.generatedTokens} tokens`); +model.close(); ``` +`new BaseRTModel(path, kernelLibraryPath = null, maxContext = 0)` loads a +bundle; `maxContext = 0` takes the model's default window. Calls are +synchronous and block the calling thread; run them in a `worker_thread` to +keep the event loop free. `close()` frees the GPU resources — call it before +the program exits. `generateText(tokens, maxTokens, sampling)` returns the +whole text instead of streaming it. + ## Continue a conversation `generateContinue` keeps the KV cache, so a follow-up prompt doesn't reprocess history: ```ts -model.generate(prompt1, 256, { temperature: 0.7 }, (id, t) => process.stdout.write(t)); -model.generateContinue(prompt2, 256, { temperature: 0.7 }, (id, t) => process.stdout.write(t)); +const write = (_id: number, t: string) => { process.stdout.write(t); return true; }; +model.generate(prompt1, 256, { temperature: 0.7 }, write); +model.generateContinue(prompt2, 256, { temperature: 0.7 }, write); ``` -## Inspect & embed +The sampling options are `temperature`, `topK`, `topP`, `minP`, +`repeatPenalty`, `presencePenalty`, `frequencyPenalty`, `seed` and +`logitBias`. + +## Inspect, embed and transcribe ```ts const model = new BaseRTModel("models/your-model.base"); -// model config, embeddings, tokenization helpers, and (for Whisper models) -// transcription are exposed on the model instance. +console.log(model.config.architecture, model.memoryUsage); + +const vec = model.embedText("hello world"); // embedding models +const prompt = model.formatChat("You are helpful.", "Hi!"); +``` + +Also on the model: `tokenCount()`, `decodeToken()`, `prefill()`, +`decodeStep()`, `chainDecode()`, `reset()`, `prefillImage()` / +`imageNumTokens()`, `prefillAudio()` / `audioNumTokens()`, `embed()`, +`embeddingDim`, `chatTemplate`, `position`, `setSpeculation()`, and for +Whisper models `transcribe()`, `transcribePcm()`, `transcribeStream()`, +`transcribePcmStream()` and `transcribeSegments()`. + +## Engine settings + +`Engine` holds the process-wide settings; set them before constructing a +model: + +```ts +import { Engine } from "@basecompute/basert"; + +console.log(Engine.version()); +Engine.setKvBits(8); // KV-cache width: 0 = auto, 8, 16 +Engine.setNeuralEngine(false); // prefill on the GPU alone (Apple Silicon) ``` See [`bindings/node`](https://github.com/basecompute/baseRT/tree/main/bindings/node) diff --git a/docs/bindings/python.md b/docs/bindings/python.md index 152641e..d3189f3 100644 --- a/docs/bindings/python.md +++ b/docs/bindings/python.md @@ -5,16 +5,30 @@ ## Install ```sh -cd bindings/python -pip install -e . +pip install basert ``` -Point the bindings at the engine dylib if it isn't in `build/`: +The [`basert`](https://pypi.org/project/basert/) package installs the +`basert` command, the prebuilt engine and the `baseRT` Python module in one +step. Wheels are published for: + +- Apple Silicon, macOS 15 or later; +- Linux arm64 with an NVIDIA GPU and the CUDA 13 runtime (cuBLAS); +- Linux x86-64 with an AMD Strix Halo (gfx1151) or Strix Point (gfx1150) GPU + and the ROCm 10 runtime in `/opt/rocm/core-10.0`. + +From a source checkout, install the module alone and give it an engine: ```sh -export BASERT_LIB_PATH=/path/to/build # dir containing libbaseRT.dylib +cd bindings/python +pip install -e . +export BASERT_LIB_PATH=/path/to/libbaseRT.dylib # or libbaseRT.so on Linux ``` +Without `BASERT_LIB_PATH`, the module looks for the engine bundled in the +wheel, then the checkout's `build/`, then `~/.basert` (the install script) and +Homebrew. See [Finding the engine](index.md#finding-the-engine). + ## Generate text ```python @@ -24,6 +38,11 @@ m = baseRT.Model("models/your-model.base") print(m.generate_text("The capital of France is", max_tokens=64, temperature=0.7)) ``` +`Model(path, kernel_library_path=None, max_context=0)` loads a bundle; +`max_context=0` takes the model's default window. `m.close()` frees the GPU +resources, and `Model` also works as a context manager (`with +baseRT.Model(...) as m:`). + ## Stream tokens ```python @@ -34,32 +53,51 @@ for chunk in m.stream("Explain RoPE in one sentence.", max_tokens=128): ## Lower-level control ```python +def on_token(token_id: int, text: str) -> bool: + print(text, end="", flush=True) + return True # False stops generation + tokens = m.encode("Once upon a time") stats = m.generate(tokens, max_tokens=256, temperature=0.7, - top_k=40, top_p=0.9) # streaming via callback under the hood -print(stats.generated_tokens, stats.prefill_tokens_per_sec) + top_k=40, top_p=0.9, callback=on_token) +print(stats.generated_tokens, stats.decode_tokens_per_sec) ``` -Other `Model` methods: `config()`, `memory_bytes()`, `position()`, `reset()`, -`decode_token()`, `prefill()` / `prefill_image()`, `decode_step()`, -`embed()` / `embed_text()` / `embedding_dim()`, -`format_chat(system, user)` / `chat_template()`, `token_count()`, -`tensors()`, and `transcribe()` for Whisper-class models. +`generate_continue()` takes the same arguments and continues from the current +KV cache, so a follow-up turn doesn't reprocess the history. + +Other `Model` methods: `reset()`, `decode_token()`, `prefill()`, +`decode_step()`, `chain_decode()`, `prefill_image()` / `image_num_tokens()`, +`prefill_audio()` / `audio_num_tokens()`, `embed()` / `embed_text()`, +`format_chat(system, user)`, `token_count()`, `set_speculation()`, +`tensors()`, and the transcription methods below. Properties: `config`, +`memory_bytes`, `position`, `is_whisper`, `embedding_dim`, `chat_template`. +`baseRT.get_error()` returns the engine's last error message. ## Embeddings ```python m = baseRT.Model("models/embedding-model.base") vec = m.embed_text("hello world") -print(m.embedding_dim(), len(vec)) +print(m.embedding_dim, len(vec)) ``` ## Transcription ```python m = baseRT.Model("models/whisper-base.base") -# pass PCM samples / audio per the transcribe() signature +text, stats = m.transcribe("audio.wav", language="en") +print(text) + +for seg in m.transcribe_segments(): # per-segment detail of the last run + print(seg.start_ms, seg.end_ms, seg.text) ``` +`transcribe_pcm()` takes 16 kHz mono float samples instead of a file, and +`transcribe_stream()` / `transcribe_pcm_stream()` call back per segment. +`set_task("translate")`, `set_initial_prompt()`, +`set_condition_on_previous_text()` and `set_timestamps()` configure the next +run; `transcribe_language()` reports the detected language. + See [`bindings/python`](https://github.com/basecompute/baseRT/tree/main/bindings/python) for the full surface and tests. diff --git a/docs/bindings/rust.md b/docs/bindings/rust.md index 66ae5f4..77de43a 100644 --- a/docs/bindings/rust.md +++ b/docs/bindings/rust.md @@ -1,52 +1,88 @@ # Rust -Two crates: +Two crates, both on crates.io: - **`baseRT-sys`** — raw `#[repr(C)]` FFI bindings (unsafe). - **`baseRT`** — a safe, idiomatic wrapper with RAII, `Result` error handling, and closures for streaming. +The crates link an engine you have installed; they don't carry one. + ## Setup -Make `libbaseRT.dylib` available (from an [engine release](../reference/engine-releases.md) -or a local build) and point the crates at it: +Install the engine first, with Homebrew or the install script: ```sh -export BASERT_LIB_DIR=/path/to/build # dir containing libbaseRT.dylib +brew install basecompute/tap/basert +# or +curl -LsSf https://basecompute.co/install.sh | sh ``` -The `baseRT` crate embeds an rpath to that directory, so its own examples and -tests run without `DYLD_LIBRARY_PATH`. A downstream binary that depends on -`baseRT` must make the dylib discoverable at runtime — add an rpath in its -`build.rs` (`cargo:rustc-link-arg=-Wl,-rpath,`), install the dylib to a -standard location, or set `DYLD_LIBRARY_PATH=$BASERT_LIB_DIR`. - -Add it to your `Cargo.toml`: +Then add the crate: ```toml -baseRT = { path = "path/to/baseRT/bindings/rust/baseRT" } +[dependencies] +baseRT = "0.5" +``` + +The build looks for the engine library (`libbaseRT.dylib` on macOS, +`libbaseRT.so` on Linux) in `BASERT_LIB_DIR` when it is set, and otherwise in +the first of: a source checkout's `build/`, `$BASERT_INSTALL_DIR` (default +`~/.basert`), and Homebrew's `opt/basert/libexec`. To use an +[engine release](../reference/engine-releases.md) unpacked elsewhere: + +```sh +export BASERT_LIB_DIR=/path/to/engine # dir containing libbaseRT.dylib / .so ``` -To link the static engine archive instead (pulls in the frameworks manually), -enable the `static` feature: +To build against a checkout instead of crates.io: ```toml -baseRT = { path = "...", features = ["static"] } +baseRT = { path = "path/to/baseRT/bindings/rust/baseRT" } ``` +The `baseRT` crate embeds an rpath to the engine directory, so its own +examples and tests run without `DYLD_LIBRARY_PATH` / `LD_LIBRARY_PATH`. A +downstream binary that depends on `baseRT` must make the library discoverable +at runtime — add an rpath in its `build.rs` +(`cargo:rustc-link-arg=-Wl,-rpath,`), install the library to a standard +location, or set `DYLD_LIBRARY_PATH` (`LD_LIBRARY_PATH` on Linux). + +A crate that loads `libbaseRT` itself at run time can depend on `baseRT-sys` +with the `no-link` feature: nothing is linked, the types stay usable, and the +`extern` functions must not be called. Either way, `baseRT-sys` passes the +engine's C headers to dependents' build scripts as `DEP_BASERT_INCLUDE`. + ## Usage ```rust -use baseRT::Model; - -let model = Model::open("models/your-model.base")?; -let tokens = model.encode("Once upon a time")?; -let stats = model.generate(&tokens, 256, Default::default(), |_id, text| { - print!("{text}"); - true // keep going -})?; -println!("\n{} tokens", stats.generated_tokens); +use baseRT::{Model, SamplingConfig}; + +fn main() -> baseRT::Result<()> { + // kernel library None → auto-detect; max_context 0 → the model default. + let model = Model::load("models/your-model.base", None, 0)?; + let tokens = model.encode("Once upon a time")?; + + let stats = model.generate(&tokens, 256, SamplingConfig::greedy(), |_id, text| { + print!("{text}"); + true // return false to stop early + })?; + println!("\n{} tokens, {:.0} tok/s", stats.generated_tokens, stats.decode_tokens_per_sec); + Ok(()) +} ``` +`SamplingConfig::with_temperature(0.7)` samples instead of decoding greedily; +the struct also has `top_k`, `top_p`, `min_p`, `repeat_penalty`, +`presence_penalty`, `frequency_penalty`, `seed` and `logit_bias`. +`generate_continue` continues from the KV cache for a follow-up turn, and +`generate_text` returns the whole text with the stats. + +`Model` also has `config()`, `memory()`, `architecture()`, `prefill()`, +`decode_step()`, `chain_decode()`, `reset()`, `embed()` / `embed_text()`, +`format_chat()`, `chat_template()`, `token_count()`, `tensors()`, and for +Whisper models `transcribe()`, `transcribe_pcm()`, the `_stream` variants and +`transcribe_segments()`. The model is freed when it is dropped. + See [`bindings/rust`](https://github.com/basecompute/baseRT/tree/main/bindings/rust) -for the full API, the `static` feature, and examples. +for the full API and examples. diff --git a/docs/bindings/swift.md b/docs/bindings/swift.md index f8b5761..48b1cfa 100644 --- a/docs/bindings/swift.md +++ b/docs/bindings/swift.md @@ -2,20 +2,30 @@ A Swift package wrapping the BaseRT engine. The C headers (`baseRT.h` / `types.h`) are vendored into the `CBaseRT` module; the `BaseRT` target links -`-lbaseRT` and embeds an rpath. Swift 5.9+. +`-lbaseRT` and embeds an rpath. Swift 5.9+. The manifest declares macOS 13+ / +iOS 16+, but the prebuilt engine needs an Apple Silicon Mac on macOS 15 or +later. ## Setup -Make `libbaseRT.dylib` available and point the package at it: +Install the engine (Homebrew, the install script, or an +[engine release](../reference/engine-releases.md)) and point the package at +the directory containing `libbaseRT.dylib`: ```sh -export BASERT_LIB_DIR=/path/to/build +export BASERT_LIB_DIR=/opt/homebrew/opt/basert/libexec # Homebrew +# or: export BASERT_LIB_DIR=$HOME/.basert # install script ``` -Add the package as a dependency: +Without it, the package uses the checkout's `build/` directory. The package is +used from a local checkout (its linker flags keep it out of remote package +resolution): ```swift -dependencies: [.product(name: "BaseRT", package: "BaseRT")] +dependencies: [.package(path: "/path/to/baseRT/bindings/swift")], +targets: [ + .target(name: "MyApp", dependencies: [.product(name: "BaseRT", package: "BaseRT")]), +] ``` ## Usage @@ -24,18 +34,37 @@ dependencies: [.product(name: "BaseRT", package: "BaseRT")] import BaseRT // Optional engine-wide config before loading: -// BaseRTEngine.setPagedKV(true) // BaseRTEngine.setKVBits(8) +// BaseRTEngine.setNeuralEngine(false) // prefill on the GPU alone print("engine \(BaseRTEngine.version)") let model = try BaseRTModel(modelPath: "models/your-model.base") let tokens = try model.encode(text: "Once upon a time") -let stats = model.generate(tokens: tokens, maxTokens: 256) { token in - print(token, terminator: "") +let stats = try model.generate(tokens: tokens, maxTokens: 256) { token in + print(token.text, terminator: "") return true // keep generating } +print("\n\(stats.generatedTokens) tokens") ``` +Or as an `AsyncSequence`: + +```swift +for await token in model.stream(tokens: tokens, maxTokens: 256) { + print(token.text, terminator: "") +} +``` + +`generate` and `stream` take an optional `SamplingConfig(temperature:topK:topP: +minP:repeatPenalty:presencePenalty:frequencyPenalty:seed:logitBias:)`; +`generateContinue` / `streamContinue` continue from the KV cache. The model +also has `generateText`, `embed` / `embedText`, `formatChat`, `tokenCount`, +`prefillImage` / `prefillAudio`, `saveState` / `loadState`, LoRA adapters +(`loadLoRA`, `unloadLoRA`), and for Whisper models `transcribe` / +`transcribePCM`. Calls that touch the model throw +`BaseRTError.reentrantModelCall` if made from inside that model's token +callback. + See [`bindings/swift`](https://github.com/basecompute/baseRT/tree/main/bindings/swift) for the full API. diff --git a/docs/cli/overview.md b/docs/cli/overview.md index 643b49f..9c36575 100644 --- a/docs/cli/overview.md +++ b/docs/cli/overview.md @@ -1,12 +1,15 @@ # The `basert` CLI -`basert` is a single front-end with two kinds of commands: +`basert` is a single front-end with three kinds of commands: - **Native** (run by the CLI itself): `pull`, `list`, `convert`, `inspect`, - `sign`, `verify`, `keygen`. These are the model hub + converter. -- **Forwarded** (dispatched to the engine): `serve`, `chat`, `complete`, - `bench`, `profile`, `transcribe`. These exec the matching `basert-` - runtime binary. + `sign`, `verify`, `keygen`, `add-speculator`, `superfluid`, `self`. These + are the model hub, the converter, and installation management. +- **Forwarded** (dispatched to the engine): `chat`, `complete`, `bench`, + `transcribe`. These exec the matching `basert-` runtime binary. +- **Served**: `serve` runs [Superfluid](https://github.com/basecompute/superfluid), + the open-source server, with the engine beside `basert`. `computearena` + runs the separately installed ComputeArena CLI with BaseRT selected. ``` basert [args...] @@ -14,32 +17,54 @@ basert [args...] ## How forwarding works -When you run a forwarded command, `basert` looks for the matching engine binary -and replaces the current process with it (`exec`). Resolution order: +When you run a forwarded command, `basert` first resolves any model id in the +arguments (see [Model arguments](#model-arguments)), then looks for the +matching engine binary and replaces the current process with it (`exec`). +Resolution order: 1. `basert-` next to the `basert` executable (how a release ships). -2. `basert-` on your `PATH`. -3. `baseRT_` (local dev builds). +2. `baseRT_` next to it (local dev builds). +3. `basert-`, then `baseRT_`, on your `PATH`. -This is why putting the engine bundle directory and the CLI on the same `PATH` -makes `basert serve`/`chat`/… work without any extra wiring. See +This is why a release bundle, which keeps the CLI and the tools in one +directory, works without any extra wiring. See [Installation](../getting-started/installation.md). +## How `serve` works + +`basert serve` reads the same command line the earlier built-in server took, +finds the engine library beside `basert` (or the one `BASERT_LIB` names), +finds a Superfluid that can serve it, and runs `superfluid serve` with the +model. When no installed Superfluid can serve the engine, it installs the +newest release that can, asking first in a terminal. +`basert superfluid install` does this ahead of time, and +`basert superfluid status` shows what is installed. + +Flags `basert serve` does not know are handed to `superfluid serve` as they +are. `basert serve --print-command` prints the Superfluid command line a start +would run. See [Serving an API](../guides/serving.md) and +[Superfluid's docs](https://docs.basecompute.co/latest/). + ## Model arguments -Anywhere a model is expected, you can pass a **hub id** (resolved from the cache, -e.g. `Qwen/Qwen3-4B`) or a **path** to a `.base` file. `chat`/`complete` take the -model positionally; `serve` takes it via `--model` (repeatable). +Anywhere a model is expected, you can pass a **hub id** (e.g. +`basecompute/Qwen3-4B`) or a **path** to a `.base` file. A hub id is resolved +from the local cache and pulled on first use. `chat`, `complete`, `bench` and +`serve` take the model positionally; `serve --model` adds more models. + +Pick a build with an inline `:variant` (`basecompute/Qwen3-4B:default-q8`) or +the `--variant` flag, which applies to ids without one. `--offline` on +`basert serve` uses only what is installed and downloads nothing. ## Discoverability -`basert --help` lists native commands and the forwarded runtime tools. Each tool -has its own help: +`basert --help` lists the commands. Each command has its own help: ```sh basert --help basert serve --help basert chat --help +basert self --help ``` See the [command reference](reference.md) for every flag. diff --git a/docs/cli/reference.md b/docs/cli/reference.md index 2c68dab..197cf96 100644 --- a/docs/cli/reference.md +++ b/docs/cli/reference.md @@ -1,28 +1,38 @@ # Command reference -Every `basert` command and its flags. Run `basert --help` for the -authoritative, version-specific list. +Every `basert` command and its flags, as of BaseRT 0.5.1. Run +`basert --help` for the authoritative, version-specific list. --- ## `basert pull` Download a model into the local hub cache — a pre-converted `.base` from the -catalog, or a raw HuggingFace repo converted on the fly. +catalog, or a raw Hugging Face repo converted on the fly. ```sh -basert pull [options] +basert pull [:] [options] ``` | Flag | Default | Purpose | | --- | --- | --- | | `` | — | `basecompute/` (catalog) or `org/model` (raw HF repo). | -| `--profile ` | — | Override the auto-selected quant profile. | -| `--target ` | `base-q4` | Quant scheme for convert-on-pull when no profile applies. | +| `:` | — | A variant as `basert list` names it (`default-q8`), a quant (`q8`), or a size (`small`) of a release that comes in sizes. | +| `--profile ` | — | Override the auto-selected quant profile (path to a profile JSON). | +| `--target ` | `base-q4` | Quant scheme for convert-on-pull when no profile applies. Given, it also picks a pre-converted repo's file by quant. | +| `--file ` | — | Take this `.base` file from the repo (e.g. `Foo-Medium.base`) rather than picking one by quant or size. | | `--revision ` | `main` | HF revision / branch / tag. | | `--force` | off | Re-download / re-convert even if cached. | | `--dry-run` | off | Resolve and print the plan without downloading. | +`--target` takes `base-q2`, `base-q3`, `base-q4`, `base-q5`, `base-q6`, +`base-q8`, `bf16`, `mxfp4` or `nvfp4`. + +A release that comes in sizes (files named `-XS`, `-Small`, `-Medium`, +`-Large`, `-XL`) takes the Medium when nothing names a file, and refuses a +`--target`. A variant already installed is used as it is, without contacting +Hugging Face. + ## `basert list` List models in the local cache. @@ -34,11 +44,11 @@ basert list [--remote] [--json] | Flag | Purpose | | --- | --- | | `--remote` | Also list catalog models that aren't installed yet. | -| `--json` | Emit JSON instead of a table. | +| `--json` | Emit JSON instead of a table, with each model's path and source file. | ## `basert convert` -Convert a source model (GGUF / HF / MLX) to `.base`. +Convert a source model (GGUF / HF safetensors / MLX) to `.base`. ```sh basert convert [options] @@ -48,15 +58,26 @@ basert convert [options] | --- | --- | --- | | `` | — | Source model path (or a bundle name with `--synthetic`). | | `-o, --output ` | `.base` | Output `.base` file. | -| `--target ` | — | Quant scheme (or fallback when `--profile` is set). | -| `--profile ` | — | Per-tensor canonical-quant profile JSON. | -| `--calibration ` | — | UTF-8 calibration text (required for AWQ). | -| `--calibration-tokens ` | — | Number of calibration tokens. | -| `--awq-mode ` | — | AWQ calibration mode. | -| `--awq-profile ` | — | Precomputed AWQ activation-stats sidecar. | +| `--target ` | `base-q4` | Quant scheme (the fallback when `--profile` is set). Same values as `pull --target`. | +| `--profile ` | — | Per-tensor canonical-quant profile JSON, e.g. `base-convert/profiles/default-q4.json`. | +| `--awq-profile ` | — | AWQ activation-stats sidecar JSON; needs `--profile`. See [AWQ calibration](../guides/converting.md#awq-calibration). | +| `--imatrix` | off | Importance-weighted rounding from the `--awq-profile` sidecar instead of AWQ's rotation. | +| `--allow-quant-from-quant` | off | Allow `--profile` on an already-quantized source (GGUF, MLX 4/8-bit). | +| `--kquant-passthrough` | off | GGUF only: copy k-quant and IQ super-blocks into the bundle as they are. | +| `--mlx-passthrough` | off | Copy an MLX 4-bit (group 64) checkpoint's packed weights as they are. Needs `--target base-q4` and no `--profile`. | +| `--validate` | off | After `--mlx-passthrough`, compare every written tensor with the source. | +| `--mmproj ` | — | GGUF only: fold a companion `mmproj-*.gguf` vision tower into the bundle. | +| `--mmproj-config ` | — | HF `config.json` for the multimodal settings an mmproj GGUF cannot carry. | +| `--mtp-head ` | — | Embed a converted Gemma 4 MTP head in the bundle, as `add-speculator` does. | +| `--quantize-drafter` | off | Drafter sidecars only: quantize the drafter's layers with `--target`. | +| `--direct-write` | off | Write straight into the output file (peak disk use is the bundle size, not 2×). | | `--synthetic` | off | Generate a dummy bundle (CI/testing). | -See [Converting models](../guides/converting.md). +Less common flags (`--no-mlx-passthrough`, `--no-synth-tied-head`, +`--speculator-lm-head`, `--mtp-head-version`, `--mtp-draft-ranking`, +`--mtp-draft-vocab`, `--keep-drafter-fc-f16`, `--awq-search-rows`) are +described in `basert convert --help`. See +[Converting models](../guides/converting.md). ## `basert inspect` @@ -70,17 +91,33 @@ basert inspect [--verify-checksums] | --- | --- | | `--verify-checksums` | Also verify per-tensor xxhash64 (slow for large models). | +## `basert add-speculator` + +Embed a converted MTP head in a bundle as its built-in speculator head (Gemma +4's separate `-assistant` checkpoint). + +```sh +basert add-speculator --head --output [--head-version ] +``` + +| Flag | Purpose | +| --- | --- | +| `` | The bundle the head drafts for. | +| `--head ` | The head, converted on its own (`basert convert google/gemma-4-E4B-it-assistant`), f16 or quantized (`--quantize-drafter --target base-q8`). | +| `-o, --output ` | Where to write the bundle (refused if it exists). | +| `--head-version ` | A version for the head, recorded in the bundle. | + ## `basert keygen` Generate an ed25519 keypair for signing. ```sh -basert keygen --output [--name ] +basert keygen --out [--name ] ``` | Flag | Default | Purpose | | --- | --- | --- | -| `-o, --output ` | — | Output directory. Writes `.secret` and `.pub`. | +| `-o, --out ` | — | Output directory. Writes `.secret` and `.pub`. | | `--name ` | `baseRT-key` | Base name for the key files. | ## `basert sign` @@ -115,13 +152,50 @@ See [Signing & verification](../guides/signing.md). --- -## Runtime commands (forwarded to the engine) +## `basert self` -These exec `basert-`. Full flags in their guides. +Update basert, or switch between the versions installed here. See +[Updating](../getting-started/installation.md#updating). -**Selecting a quant variant.** For the model-taking commands (`serve`, `chat`, -`complete`, `bench`, `profile`), choose which quant build to load with an inline -`:variant` on the hub id, or the `--variant` flag: +| Command | Purpose | +| --- | --- | +| `basert self update` | Install the newest release for this machine and make it the one in use, with the Superfluid it needs. | +| `basert self check` | Say whether a newer release exists, without installing it. | +| `basert self list` | The versions installed here, and which is in use. | +| `basert self use ` | Make an installed version the one in use (the one it replaces stays). | +| `basert self install --from ` | Place an unpacked release bundle and make it the one in use (what the install script runs). | + +`basert self update` flags: + +| Flag | Purpose | +| --- | --- | +| `--version ` | Go to this release instead of the newest (an older one too), e.g. `0.5.0`. | +| `--dry-run` | Say what would be done, and change nothing. | +| `-y, --yes` | For a copy Homebrew, npm, pipx, uv or cargo installed: run that manager's update without asking (needed without a terminal). | + +`basert self install` takes `--root `, the install directory (default +`$BASERT_INSTALL_DIR`, else `~/.basert`). + +## `basert superfluid` + +Install or check [Superfluid](https://github.com/basecompute/superfluid), the +server `basert serve` runs. + +| Command | Purpose | +| --- | --- | +| `basert superfluid install [--force]` | Install the newest Superfluid release that serves this engine where `basert serve` looks for it. `--force` installs again even when that release, or a newer one, is there. | +| `basert superfluid status` | Show the release this basert was tested with, what is installed where, and whether it can serve the engine. Exits 0 when an installed Superfluid can, 1 when none is installed, 2 when none installed can. | + +--- + +## Runtime commands + +`chat`, `complete`, `bench` and `transcribe` exec `basert-`; `serve` +runs Superfluid. Full flags in their guides. + +**Selecting a quant variant.** For the model-taking commands, choose which +build to load with an inline `:variant` on the hub id, or the `--variant` +flag: ```sh basert serve basecompute/gemma-4-E2B-it:default-q8 @@ -134,16 +208,52 @@ given. ### `basert serve` -OpenAI-compatible HTTP server. See [Serving an API](../guides/serving.md). +OpenAI-compatible HTTP server, run by Superfluid. See +[Serving an API](../guides/serving.md). ```sh -basert serve --model [--model ...] [options] +basert serve [--model ...] [options] ``` -Key flags: `--host`, `--port`, `--api-key`, `--max-context`, `--max-tokens`, -`--kv-bits`, `--paged-kv`, `--continuous-batching [N]`, `--prefix-cache`, -`--rate-limit`, `--idle-timeout`, `--request-timeout`, `--drain-timeout`, -`--files-dir`, `--log-file`. +| Flag | Default | Purpose | +| --- | --- | --- | +| `` | — | A `.base` path or a hub id, pulled on first use. | +| `--model ` | — | Another model to serve. Repeatable. | +| `--host ` | `127.0.0.1` | Bind address. | +| `--port ` | `8453` | Bind port. | +| `--api-key ` | — | Require Bearer token authentication. | +| `--max-context ` | auto | Context window. Sized for this machine's GPU memory, capped at the model's trained window. | +| `--max-tokens ` | rest of window | Cap on generated tokens for a request that names none. | +| `--kv-bits 4\|8\|16\|84` | per model | KV cache element width (`84` = K at Q8, V at Q4). | +| `--max-batch-size ` | `1` | Max concurrent sequences (`--max-batch` is an alias). | +| `--continuous-batching [N]` | off (`8` without N) | Serve up to N requests at once through one shared forward pass. | +| `--prefill-budget ` | — | Max prompt tokens per engine tick (64–4096). | +| `--speculate ` | `auto` | Speculative decoding: `auto` (the drafter the catalog pairs with the model, else the head its file carries, else none), `off`, `mtp-head`, `prompt-lookup`, or `dflash:`. | +| `--offline` | off | Download nothing (no model, drafter or catalog); serve what is installed. | +| `--model-dir ` | — | Register every `*.base` under ``, loaded on first request. | +| `--idle-timeout ` | `0` | Unload a model idle for N seconds (`0` = never). | +| `--rate-limit ` | `0` | Requests per minute per client (`0` = unlimited). | +| `--request-timeout ` | — | Bounds fill-in-the-middle completions only. | +| `--drain-timeout ` | `60` | Seconds to wait for in-flight requests on `SIGUSR1`. | +| `--sessions ` | per port, in the state directory | Request-log directory. | +| `--files-max-bytes ` | — | Reject uploads that would push stored bytes above N. | +| `--files-expiry ` | — | Remove uploaded files older than N seconds. | +| `--files-sweep ` | `300` | Sweep cadence in seconds, with `--files-expiry`. | +| `--log-file ` | stderr | Write the access log and diagnostics here. | +| `--basert-lib ` | beside `basert` | The engine library directory to serve with. | +| `-v, --verbose` | off | Engine diagnostics (load, GPU). | +| `--print-command` | — | Print the Superfluid command line this start would run, and exit. | +| `--version` | — | Print the version, and the Superfluid a start would run. | + +Any other `--flag` is handed to `superfluid serve` as it is (for example +`--spec-bitexact`); everything after `--` is handed over untouched. See +[Superfluid's server docs](https://docs.basecompute.co/latest/serving/openai_compatible_server/). + +Accepted so that existing command lines keep working, and no longer used: +`--paged-kv` and `--prefix-cache` (always on), `--prefix-cache-file`, +`--prefix-cache-save-interval`, `--files-dir`, `--media-dir`, `--metallib`, +`--prefill-chunk`, `--paged-weights`, `--no-paged-weights-retry`, +`--gpu-wait-timeout-ms`, `--decode-replay`, `--no-baked-decode`. ### `basert chat` @@ -153,9 +263,23 @@ Interactive chat. See [Chat & completion](../guides/chat-complete.md). basert chat [options] ``` -Key flags: `--temp`, `--top-k`, `--top-p`, `--min-p`, `--repeat-penalty`, -`--max-tokens`, `--max-context`, `--think`/`--no-think`, `--kv-bits`, -`--paged-kv`, `--max-batch-size`. +| Flag | Default | Purpose | +| --- | --- | --- | +| `--temp F` | `0.7` | Temperature. | +| `--top-k N` | `40` | Top-K candidates. | +| `--top-p F` | `0.9` | Nucleus sampling threshold. | +| `--min-p F` | `0.0` | Min-P filter. | +| `--repeat-penalty F` | `1.1` | Repetition penalty. | +| `--max-tokens N` | `2048` | Max tokens per response. | +| `--max-context N` | auto | Context window, sized for this machine. | +| `--think` / `--no-think` | `--no-think` | Show or hide the model's reasoning. | +| `--kv-bits 4\|8\|16\|84` | per model | KV cache element width. | +| `--paged-kv` | off | Paged KV cache. | +| `--max-batch-size N` | `1` | Max concurrent sequences for batched decode. | +| `--no-ane` | off | Prefill on the GPU alone (no Neural Engine split on Apple Silicon). | +| `-v, --verbose` | off | Engine diagnostics. | + +In the prompt, `/clear` resets the conversation and `quit` exits. ### `basert complete` @@ -165,26 +289,73 @@ One-shot completion (text / image / audio). basert complete --prompt [options] ``` -Key flags: `--prompt`, `--system`, `--chat`, `--image`, `--audio`, -`--max-tokens`, `--temp`, `--top-k`, `--top-p`, `--repeat-penalty`, `--kv-bits`, -`--paged-kv`. +| Flag | Default | Purpose | +| --- | --- | --- | +| `--prompt ` | — | Prompt text (`-` reads stdin). Required unless `--prompt-file`. | +| `--prompt-file ` | — | Read the prompt from a file. | +| `--chat` | off | Wrap the prompt in the model's chat template (recommended for instruct models). | +| `--system ` | — | System prompt (with `--chat`). | +| `--image ` | — | Image input, for a vision model. | +| `--audio ` | — | Audio input, for an audio model. | +| `-n, --max-tokens N` | `2048` | Max tokens to generate. | +| `--temp F` | `0.0` | Temperature (`0` = greedy). | +| `--top-k N` | `40` | Top-K. | +| `--top-p F` | `0.9` | Top-P. | +| `--repeat-penalty F` | `1.0` | Repetition penalty. | +| `--spec` | off | Speculative decoding with the head the model's file carries. | +| `--kv-bits 4\|8\|16\|84` | per model | KV cache element width. | +| `--paged-kv` | off | Paged KV cache. | +| `--max-batch-size N` | `1` | Max concurrent sequences. | +| `--max-context N` | auto | Context budget, sized for this machine. | +| `--no-ane` | off | Prefill on the GPU alone. | +| `-v, --verbose` | off | Engine diagnostics. | ### `basert bench` Throughput benchmark. See [Benchmarking](../guides/benchmarking.md). ```sh -basert bench [-p N] [-n N] [-r N] [-w N] [--paged-kv] +basert bench [-p N] [-n N] [-r N] [-w N] [options] ``` +| Flag | Default | Purpose | +| --- | --- | --- | +| `-p, --pp N` | `512` | Prefill length (`0` skips it). | +| `-n, --tg N` | `128` | Decode length (`0` skips it). | +| `--tg-at LIST` | — | Decode at each listed context (e.g. `1k,4k,8k`). | +| `-r, --reps N` | `5` | Timed repetitions per test. | +| `-w, --warmup N` | `3` | Minimum warmup reps, extended until two reps agree within 2% (at most 12). | +| `--fill MODE` | `bos` | Prefill tokens: `bos`, `random[:SEED]` or `corpus[:PATH]`. | +| `--paged-kv` | off | Paged KV cache. | +| `--no-ane` | off | Prefill on the GPU alone. | + ### `basert transcribe` -Audio transcription (Whisper-class models). +Audio transcription with a Whisper model. ```sh -basert transcribe