Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 9 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
[workspace]
resolver = "2"
members = ["crates/dluth-core", "crates/dluth-kernels", "crates/dluth-model", "crates/dluth", "crates/dluth-cuda"]
members = [
"crates/dluth-core",
"crates/dluth-kernels",
"crates/dluth-model",
"crates/dluth-serve",
"crates/dluth",
"crates/dluth-cuda",
]
# Plain `cargo build` and `cargo test` use these. A crate that needs a vendor
# toolchain (dluth-cuda needs the CUDA toolkit) is in `members` only and is built
# with `-p <crate>`.
default-members = ["crates/dluth-core", "crates/dluth-kernels", "crates/dluth-model", "crates/dluth"]
default-members = ["crates/dluth-core", "crates/dluth-kernels", "crates/dluth-model", "crates/dluth-serve", "crates/dluth"]

[workspace.package]
version = "0.0.0"
Expand Down
63 changes: 52 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,66 @@ A lean, from-scratch LLM inference engine in Rust. Planned targets: Apple Silico
GB10 and B200. The engine contains no Python and does no just-in-time compilation; kernels are compiled ahead
of time.

Status: early. Two models run on the CPU, slowly, each checked against a trusted reference implementation as
described below. Not usable yet.
Status: early, and usable for one model on one machine. Inkling 2 Mini runs on an NVIDIA GB10 with every
value of the forward pass on the GPU, and can be served in the chat-completions format. Two models run on the
CPU, slowly, as the reference each faster path is checked against.

- **Qwen3-8B** (dense). Its output matches the reference token for token.
- **Qwen3-8B** (dense), CPU only. Its output matches the reference implementation token for token.
- **Inkling 2 Mini** (text input only, no images): a looped mixture-of-experts model with 4-bit and 8-bit
weights, run straight from the released checkpoint. Against the reference run in 32-bit floats it picks
the same token at every recorded step, and every recorded log-probability is within four times the
reference's own difference from itself (about 0.00015; measured: 0.00005). A tiny model of the same
architecture, small enough to exercise every rule, is checked the same way in CI.
weights, run straight from the released checkpoint, on the CPU and on the GB10. Against the reference run
in 32-bit floats, both pick the same token at every recorded step, and every recorded log-probability is
within four times the reference's own difference from itself (about 0.00015; measured: 0.00005). A tiny
model of the same architecture, small enough to exercise every rule, is checked the same way in CI.

Deliberately planted bugs must make named tests fail, for both models. One trivial kernel runs on an NVIDIA
GB10 to prove the GPU path. Speed is the next work.
On the GB10, Inkling 2 Mini generates about 24 tokens per second one token at a time and reads a prompt at
about 120 tokens per second. Guessed tokens are checked several per sweep of the weights, which speeds up
text that repeats itself; the model's own draft head is not used yet. Deliberately planted bugs must make
named tests fail, on the CPU and on the GPU.

cargo run --release -- generate --model <model directory> --prompt "What is the capital of Ireland?"

The program reads the model type from the directory's `config.json`. For Inkling, `--effort` sets the
reasoning effort (none, minimal, low, medium, high, xhigh; the default is high).

## Serve

cargo run --release -p dluth-cuda --bin dluth-cuda -- serve --model <model directory>

serves an Inkling 2 model from the GPU at `http://127.0.0.1:8080/v1` (`dluth serve` does the same on the
CPU, which is only good for trying the interface). It answers `POST /v1/chat/completions`, streamed or whole,
`GET /v1/models` and `GET /health`.

| Argument | Meaning | Default |
|---|---|---|
| `--listen <address:port>` | where to listen; `0.0.0.0:8080` for other machines | `127.0.0.1:8080` |
| `--context <tokens>` | longest conversation, prompt and reply together | 8192 |
| `--name <name>` | the name the model is listed under | the directory's name |
| `--guesses <n>` | guessed tokens checked per sweep; 0 for none | 4 |
| `--match <n>` | last tokens that must have appeared before for a guess | 2 |
| `--prompt-batch <n>` | tokens of a prompt read per sweep, at most 16 on the GPU | 16 |
| `--temperature <t>` | used when a request does not set one; 0 is greedy | 1 |
| `--effort <level>` | reasoning effort when a request does not set `reasoning_effort` | high |
| `--queue <n>` | requests that may wait for the model | 8 |

If the environment variable `DLUTH_API_KEY` is set, requests under `/v1/` must send it as a bearer token.

What to know before relying on it:

- One model, one conversation at a time. Requests are answered in turn; when the queue is full a request
gets a 503 at once. A client that stops reading its streamed reply without closing the connection holds
the model for up to 30 seconds before it is given up on.
- From a request it reads `messages` (text; system, user and assistant), `max_completion_tokens` or
`max_tokens`, `temperature`, `top_p`, `seed`, `stop`, `stream`, `stream_options.include_usage` and
`reasoning_effort`. Tools, images and `n` above 1 are refused with a 400, not ignored.
- The model's thinking comes back as `reasoning_content`, apart from `content`.
- The server keeps the conversation it answered last. A request that continues it (the same messages, the
reply as it was given, apart from spaces around it, then more) only reads the new messages; `usage.prompt_tokens_details.cached_tokens`
says how many tokens were not read again.
- Message text is put into the model's chat format as it is. Text that contains the model's special token
strings is read as those tokens, as with the model's own template. Do not expose the server to people
you would not let write the whole prompt.
- It speaks plain HTTP. Put it behind something that does TLS if it leaves a trusted network.

## Build

cargo build --release
Expand All @@ -38,8 +80,7 @@ toolkit (found through `CUDA_HOME`, default `/usr/local/cuda`) and libclang:
cargo test -p dluth-cuda

Its kernels are compiled for one GPU architecture, currently `sm_121` (the GB10). Loading the built-in
kernels checks the device first and refuses any other architecture. In M0 it holds a single kernel that proves the path from source to a launched kernel; the model
itself still runs on the CPU.
kernels checks the device first and refuses any other architecture.

Design notes written for readers new to inference engines are in `docs/learning/`.

Expand Down
2 changes: 2 additions & 0 deletions crates/dluth-cuda/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ dluth-model = { version = "0.0.0", path = "../dluth-model" }
# The CPU reference every GPU kernel is compared with in tests; the device model also uses
# its expert choice and the few scalar formulas that stay on the host.
dluth-kernels = { version = "0.0.0", path = "../dluth-kernels" }
# The chat-completions server, for the program that serves a model from the GPU.
dluth-serve = { version = "0.0.0", path = "../dluth-serve" }

[dev-dependencies]
# Reads the recorded runs of the reference implementation that the golden tests compare with.
Expand Down
57 changes: 57 additions & 0 deletions crates/dluth-cuda/src/bin/dluth-cuda.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//! Serves an Inkling 2 model from a CUDA device in the chat-completions format.
//!
//! dluth-cuda serve --model <directory> [--listen <address:port>] [--context <tokens>] ...
//!
//! The arguments are those of `dluth serve`. Before it listens, the program runs one token
//! through the model, which copies every layer's weights to the device, so that the first
//! request does not pay for that.

use dluth_cuda::ops::CudaOps;
use dluth_cuda::{CudaDevice, Module};
use dluth_model::inkling::{load_config, model_kind, Inkling, ModelKind};
use dluth_model::tokenizer::Tokenizer;
use dluth_model::weights::Weights;
use dluth_serve::cli;
use std::process::ExitCode;
use std::time::Instant;

fn run(args: &[String]) -> Result<(), String> {
if args.first().map(String::as_str) != Some("serve") {
return Err(format!("usage: dluth-cuda {}", cli::USAGE));
}
let args = cli::parse(&args[1..])?;
let text = |e: &dyn std::fmt::Display| e.to_string();
if model_kind(&args.model).map_err(|e| text(&e))? != ModelKind::Inkling2Loop {
return Err("serve takes an Inkling 2 model".into());
}
let weights = Weights::open_dir(&args.model).map_err(|e| text(&e))?;
let tokenizer = Tokenizer::from_file(&args.model.join("tokenizer.json")).map_err(|e| text(&e))?;
let cfg = load_config(&args.model).map_err(|e| text(&e))?;
let dev = CudaDevice::open(0).map_err(|e| text(&e))?;
let module = Module::load_embedded(&dev).map_err(|e| text(&e))?;
let ops = CudaOps::new(&dev, &module).map_err(|e| text(&e))?;
let mut model = Inkling::with_ops(cfg, &weights, args.context, ops).map_err(|e| text(&e))?;

// Any token will do: each layer's weights go to the device the first time the layer runs.
let started = Instant::now();
model.forward_token(0, 0).map_err(|e| text(&e))?;
eprintln!(
"{:.1} GB of weights on the device after {:.0} s",
model.ops().weight_bytes() as f64 / 1e9,
started.elapsed().as_secs_f64()
);
cli::run(model, &tokenizer, &args)
}

fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
match run(&args) {
Ok(()) => ExitCode::SUCCESS,
Err(message) => {
// One line whatever the message quotes.
let line: String = message.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
eprintln!("dluth-cuda: {line}");
ExitCode::from(1)
}
}
}
1 change: 1 addition & 0 deletions crates/dluth-model/src/inkling/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod config;
pub mod draft;
pub mod model;
pub mod prompt;
pub mod sample;

pub use config::{load_config, model_kind, validate_weights, Checked, ExpertFormat, InklingConfig, ModelKind};
pub use draft::{DraftStats, Drafter, LookupDrafter, NoDraft};
Expand Down
97 changes: 76 additions & 21 deletions crates/dluth-model/src/inkling/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1118,6 +1118,16 @@ impl<'w, O: Ops> Inkling<'w, O> {
self.cached
}

/// How many positions a sequence can have: the room reserved when the model was made.
pub fn capacity(&self) -> usize {
self.max_seq
}

/// The model's configuration.
pub fn config(&self) -> &InklingConfig {
&self.cfg
}

/// Feeds one token at position `pos` and returns the scores for the token after it.
/// Positions must be fed in order. Position 0 starts a new sequence.
pub fn forward_token(&mut self, token: u32, pos: usize) -> Result<Vec<f32>, ModelError> {
Expand Down Expand Up @@ -1200,30 +1210,75 @@ impl<'w, O: Ops> Inkling<'w, O> {
self.max_seq
)));
}
let mut pos = 0;
if max_new > 0 {
for batch in prompt_ids.chunks(self.prompt_batch) {
self.advance(batch, pos)?;
pos += batch.len();
}
}
let mut text = prompt_ids.to_vec();
let mut emit = |token| {
on_token(token);
true
};
let stats =
self.continue_drafted(&mut text, max_new, eos, drafter, most, &mut |scores| argmax(scores), &mut emit)?;
Ok((text.split_off(prompt_ids.len()), stats))
}

/// Generation from where the model stands: `text` is every token fed so far (at least
/// one), and up to `max_new` more are chosen, appended to `text` and reported.
///
/// `pick` chooses a token from the scores of a position: the highest for greedy
/// generation, or a draw from them. Guesses are checked against what `pick` returns, so
/// the text is distributed exactly as without guesses whatever `pick` is. `on_token` is
/// given each token the moment it is chosen and returns false to stop there. Generation
/// also stops after `eos` (which is reported and appended).
///
/// On return the model has been fed all of `text` except its last token, unless nothing
/// was generated.
#[allow(clippy::too_many_arguments)]
pub fn continue_drafted(
&mut self,
text: &mut Vec<u32>,
max_new: usize,
eos: u32,
drafter: &mut dyn Drafter,
most: usize,
pick: &mut dyn FnMut(&[f32]) -> u32,
on_token: &mut dyn FnMut(u32) -> bool,
) -> Result<DraftStats, ModelError> {
let mut stats = DraftStats::default();
let mut generated = Vec::with_capacity(max_new);
if max_new == 0 {
return Ok((generated, stats));
return Ok(stats);
}
let mut pos = 0;
for batch in prompt_ids.chunks(self.prompt_batch) {
self.advance(batch, pos)?;
pos += batch.len();
let mut pos = text.len();
if pos == 0 || pos != self.cached {
return Err(ModelError::Capacity(format!(
"generation continues a text of {pos} tokens, and the model has been fed {}",
self.cached
)));
}
if max_new > self.max_seq - pos {
return Err(ModelError::Capacity(format!(
"a text of {pos} tokens plus {max_new} new tokens exceeds the history of {} positions",
self.max_seq
)));
}
let (vocab, vocab_out) = (self.cfg.vocab, self.cfg.vocab_out);
let mut text = prompt_ids.to_vec();
let mut next = argmax(&self.logits(true)?);
generated.push(next);
let mut generated = 1;
let mut next = pick(&self.logits(true)?);
text.push(next);
on_token(next);
while next != eos && generated.len() < max_new {
let mut go_on = on_token(next);
while go_on && next != eos && generated < max_new {
// A sweep with k guesses can produce k + 1 tokens: no more guesses than there
// is room for tokens. The positions fit, because the prompt and `max_new`
// is room for tokens. The positions fit, because the text and `max_new`
// tokens do.
let room = (max_new - generated.len() - 1).min(most).min(MAX_DRAFT);
let room = (max_new - generated - 1).min(most).min(MAX_DRAFT);
let mut batch = vec![next];
if room > 0 {
let guesses = drafter.draft(&text, room);
let guesses = drafter.draft(text, room);
// A guess is only a guess: never more than asked for, never outside the
// vocabulary.
batch.extend(guesses.into_iter().take(room).take_while(|g| (*g as usize) < vocab));
Expand All @@ -1237,16 +1292,16 @@ impl<'w, O: Ops> Inkling<'w, O> {
};
stats.sweeps += 1;
stats.drafted += guessed;
// Position i's scores are for the token after batch[i]. While the model's
// choice is the next guess, that guess stands and the next position counts.
// Position i's scores are for the token after batch[i]. While the choice made
// from them is the next guess, that guess stands and the next position counts.
let mut kept = 0;
for (i, at) in scores.chunks_exact(vocab_out).enumerate() {
next = argmax(at);
next = pick(at);
kept = i + 1;
generated.push(next);
generated += 1;
text.push(next);
on_token(next);
if next == eos || generated.len() == max_new || batch.get(i + 1) != Some(&next) {
go_on = on_token(next);
if !go_on || next == eos || generated == max_new || batch.get(i + 1) != Some(&next) {
break;
}
}
Expand All @@ -1259,7 +1314,7 @@ impl<'w, O: Ops> Inkling<'w, O> {
self.undo(batch.len() - kept)?;
pos += kept;
}
Ok((generated, stats))
Ok(stats)
}
}

Expand Down
Loading
Loading