1 //! The toy plugin: a real decoder over a generated GGUF file.2 //!3 //! It exercises the whole author path without a download: a test writes a4 //! small model, the plugin reads and reserves it, decodes greedily to a stop5 //! string, streams tokens, and unloads when the socket closes.6 use inf3r_gguf::{Gguf, TensorType, Value as GgufValue, Window};7 use inf3r_plugin_sdk::capability::{Failure, Report, Request};8 use inf3r_plugin_sdk::emitter::{EmitError, Emitter};9 use inf3r_plugin_sdk::serve::{Plugin, RuntimeVersion};10 use inf3r_plugin_sdk::{USAGE_FIRST_TOKEN_MS, USAGE_TOKENS_OUT, USAGE_TOKENS_PER_S};11 use inf3r_proto::body::{12 Cancel, Capability, Catalogue, ErrorCode, Grant, Model as WireModel, PartKind, Queue, Ready,13 Stops, Target,14 };15 use inf3r_text::stop::{Stop, StopSet};16 use std::collections::BTreeMap;17 use std::fmt;18 use std::fs::File;19 use std::io::Read;20 use std::os::fd::OwnedFd;21 use std::path::Path;22 use std::sync::{Arc, Mutex, MutexGuard};23 use std::time::Instant;24 /// The one model that this plugin serves.25 const MODEL: &str = "toy";26 /// The target name in the catalogue. There is no device.27 const TARGET: &str = "x64-cpu";28 /// The backend name in the catalogue. The decoder is plain Rust.29 const BACKEND: &str = "cpu";30 /// The vocabulary version that the chat capability declares.31 const VOCAB: &str = "chat.v1";32 /// The role of the dependency that carries the weight file.33 const WEIGHTS_ROLE: &str = "weights";34 /// The metadata key that holds the vocabulary as an array of strings.35 const VOCAB_KEY: &str = "toy.vocab";36 /// The metadata key that holds the stop string.37 const STOP_KEY: &str = "toy.stop";38 /// The name of the only tensor that the decoder reads.39 const EMBED: &str = "embed";40 /// The width of one token's row. The decoder looks at the last eight ids.41 const WIDTH: usize = 8;42 /// The GGUF kind number of a little-endian f32.43 const F32_KIND: u32 = 0;44 /// The tokens that one job may produce. Without a stop, a model would otherwise45 /// generate until the budget expires.46 const MAX_NEW_TOKENS: usize = 8;47 /// The channel that carries the decoded text.48 const TEXT_CHANNEL: &str = "text";49 /// The MIME type of the decoded text.50 const TEXT_MIME: &str = "text/plain; charset=utf-8";51 /// One second in milliseconds, the denominator of a rate.52 const MS_PER_SECOND: u64 = 1_000;53 /// Hundredths per whole token per second. The usage field is an integer, so a54 /// rate that keeps two decimal places is multiplied by this.55 const HUNDREDTHS: u64 = 100;56 /// The plugin.57 #[derive(Default)]58 struct Toy {59 /// The model that `load` put here.60 model: Mutex<Option<Arc<Loaded>>>,61 }62 /// The parsed model: the vocabulary, the stop set, and the embedding rows.63 struct Loaded {64 vocab: Vec<String>,65 stops: StopSet,66 embed: Vec<f32>,67 weights_bytes: u64,68 load_ms: u32,69 }70 /// The reason a load could not produce a model.71 #[derive(Debug)]72 enum LoadError {73 /// The grant does not name a path that the plugin can open.74 Grant,75 /// The file could not be opened or read.76 Read(String),77 /// The bytes are not a GGUF index that this reader carries.78 Gguf(String),79 /// A required metadata key is missing or has the wrong type.80 Meta(&'static str),81 /// The `embed` tensor is missing or is not `[vocab, WIDTH]` f32.82 Tensor,83 }84 impl fmt::Display for LoadError {85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {86 match self {87 LoadError::Grant => f.write_str("the grant names no weight path"),88 LoadError::Read(why) => write!(f, "the weights could not be read: {why}"),89 LoadError::Gguf(why) => write!(f, "the weights are not GGUF: {why}"),90 LoadError::Meta(key) => write!(f, "the metadata {key} is missing or wrong"),91 LoadError::Tensor => write!(f, "the tensor {EMBED} is not [vocab, {WIDTH}] f32"),92 }93 }94 }95 impl std::error::Error for LoadError {}96 impl Loaded {97 /// Reads a model from a path. The file is opened read-only.98 fn open(path: &Path) -> Result<Loaded, LoadError> {99 let file = File::open(path).map_err(|why| LoadError::Read(why.to_string()))?;100 Loaded::read(file)101 }102 /// Reads a model from a descriptor that the grant carried.103 ///104 /// The descriptor is the file. The plugin duplicates it into a `File`; it105 /// does not look up a path and does not use `/proc/self/fd`.106 fn open_fd(fd: &OwnedFd) -> Result<Loaded, LoadError> {107 let owned = fd108 .try_clone()109 .map_err(|why| LoadError::Read(why.to_string()))?;110 Loaded::read(File::from(owned))111 }112 /// Reads the header and the one tensor that this decoder uses.113 ///114 /// The weights are never read as one buffer. The header is streamed from115 /// the descriptor, and the tensor arrives through a bounded window at its116 /// own offset. A bundle that maps instead of reading owns that choice.117 fn read(mut file: File) -> Result<Loaded, LoadError> {118 let file_len = file119 .metadata()120 .map_err(|why| LoadError::Read(why.to_string()))?121 .len();122 let gguf = Gguf::read_with_len(&mut file, file_len)123 .map_err(|why| LoadError::Gguf(why.to_string()))?;124 let vocab = gguf125 .meta126 .get(VOCAB_KEY)127 .and_then(GgufValue::as_array)128 .ok_or(LoadError::Meta(VOCAB_KEY))?129 .iter()130 .map(|item| item.as_str().map(str::to_string))131 .collect::<Option<Vec<_>>>()132 .filter(|vocab| !vocab.is_empty())133 .ok_or(LoadError::Meta(VOCAB_KEY))?;134 let stop = gguf135 .meta136 .get(STOP_KEY)137 .and_then(GgufValue::as_str)138 .ok_or(LoadError::Meta(STOP_KEY))?;139 let tensor = gguf.tensor(EMBED).ok_or(LoadError::Tensor)?;140 let shape = [vocab.len() as u64, WIDTH as u64];141 if tensor.kind != TensorType(F32_KIND) || tensor.dims != shape {142 return Err(LoadError::Tensor);143 }144 let byte_count = usize::try_from(tensor.bytes).map_err(|_| LoadError::Tensor)?;145 let mut window = Window::from_index(file, &gguf, EMBED)146 .map_err(|why| LoadError::Gguf(why.to_string()))?;147 let mut data = vec![0u8; byte_count];148 let mut at = 0usize;149 while at < byte_count {150 let offset = u64::try_from(at).map_err(|_| LoadError::Tensor)?;151 let read = window152 .read_at(offset, &mut data[at..])153 .map_err(|why| LoadError::Gguf(why.to_string()))?;154 if read == 0 {155 return Err(LoadError::Read(156 "the weight file ends inside the tensor".to_string(),157 ));158 }159 at = at.saturating_add(read);160 }161 let data = data.as_slice();162 let (values, rest) = data.as_chunks::<4>();163 if !rest.is_empty() {164 return Err(LoadError::Tensor);165 }166 let embed: Vec<f32> = values.iter().map(|b| f32::from_le_bytes(*b)).collect();167 if embed.len() != vocab.len() * WIDTH {168 return Err(LoadError::Tensor);169 }170 Ok(Loaded {171 vocab,172 stops: StopSet::from([stop.to_string()]),173 embed,174 weights_bytes: file_len,175 load_ms: 0,176 })177 }178 /// The token whose row has the highest dot product with the history. A tie179 /// goes to the lower token id.180 fn argmax(&self, history: &[usize; WIDTH]) -> usize {181 let mut best = 0;182 let mut best_score = f32::NEG_INFINITY;183 let (rows, _) = self.embed.as_chunks::<WIDTH>();184 for (token, row) in rows.iter().enumerate() {185 let score = row186 .iter()187 .zip(history)188 .fold(0.0f32, |sum, (value, id)| sum + value * (*id as f32));189 if score > best_score {190 best_score = score;191 best = token;192 }193 }194 best195 }196 /// The prompt history. A toy has no tokenizer, so a byte is an id modulo197 /// the vocabulary. The newest id comes first.198 fn history(&self, text: &str) -> [usize; WIDTH] {199 let mut history = [0usize; WIDTH];200 for (slot, byte) in text.bytes().rev().take(WIDTH).enumerate() {201 history[slot] = usize::from(byte) % self.vocab.len();202 }203 history204 }205 }206 impl Toy {207 fn report(208 &self,209 model: &Loaded,210 tokens_in: u64,211 tokens_out: u64,212 started: Instant,213 first_token_ms: Option<u64>,214 ) -> Report {215 let elapsed_ms = elapsed_ms(started);216 let first_token_ms = first_token_ms.unwrap_or(elapsed_ms);217 let usage = BTreeMap::from([218 ("tokens_in".to_string(), tokens_in),219 (USAGE_TOKENS_OUT.to_string(), tokens_out),220 (USAGE_FIRST_TOKEN_MS.to_string(), first_token_ms),221 (222 USAGE_TOKENS_PER_S.to_string(),223 tokens_per_s(tokens_out, elapsed_ms),224 ),225 ("weights_bytes".to_string(), model.weights_bytes),226 ]);227 Report {228 usage,229 meta: BTreeMap::new(),230 }231 }232 /// A cancel is a normal end; the SDK reads the flag and marks the outcome.233 fn emit_failed(234 &self,235 model: &Loaded,236 tokens_in: u64,237 tokens_out: u64,238 started: Instant,239 first_token_ms: Option<u64>,240 why: EmitError,241 ) -> Result<Report, Failure> {242 match why {243 EmitError::Cancelled => {244 Ok(self.report(model, tokens_in, tokens_out, started, first_token_ms))245 }246 EmitError::Blocked => Err(Failure::new(ErrorCode::Timeout, "the window never opened")),247 }248 }249 }250 impl Plugin for Toy {251 fn max_inflight(&self) -> u16 {252 // The decoder is synchronous and keeps no per-job device state.253 1254 }255 fn runtime(&self) -> Option<RuntimeVersion> {256 None257 }258 fn catalogue(&self) -> Catalogue {259 // Before a load the lifecycle numbers are zero. After one they are the260 // file length and the measured time.261 let (weights_bytes, load_ms) = match lock(&self.model).as_ref() {262 Some(model) => (model.weights_bytes, model.load_ms),263 None => (0, 0),264 };265 Catalogue {266 target: Target {267 id: TARGET.to_string(),268 backend: BACKEND.to_string(),269 arch: vec![std::env::consts::ARCH.to_string()],270 devices: 0,271 vram_mb: Vec::new(),272 },273 models: vec![WireModel {274 serve: MODEL.to_string(),275 alias_of: None,276 weights_bytes,277 load_ms,278 capabilities: BTreeMap::from([(279 "chat".to_string(),280 Capability {281 vocab: VOCAB.to_string(),282 parts: vec![PartKind::Text],283 channels: vec![TEXT_CHANNEL.to_string()],284 limits: BTreeMap::from([("max_tokens".to_string(), MAX_NEW_TOKENS as u64)]),285 cancel: Cancel::Token,286 stops: Stops::Plugin,287 queue: Queue::None,288 },289 )]),290 }],291 runtime: None,292 cache: None,293 }294 }295 fn load(&self, grant: &Grant) -> Result<Ready, Failure> {296 self.load_fds(grant, &[])297 }298 fn load_fds(&self, grant: &Grant, fds: &[OwnedFd]) -> Result<Ready, Failure> {299 let started = Instant::now();300 let mut model = match fds.first() {301 Some(fd) => Loaded::open_fd(fd),302 None => {303 let dep = grant304 .deps305 .iter()306 .find(|dep| dep.role == WEIGHTS_ROLE)307 .or_else(|| grant.deps.first())308 .filter(|dep| !dep.path.is_empty())309 .ok_or_else(|| Failure::dependency(LoadError::Grant.to_string()))?;310 Loaded::open(Path::new(&dep.path))311 }312 }313 .map_err(|why| Failure::dependency(why.to_string()))?;314 let load_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);315 model.load_ms = load_ms;316 *lock(&self.model) = Some(Arc::new(model));317 Ok(Ready {318 load_ms,319 cache_fingerprint: None,320 })321 }322 fn run(323 &self,324 capability: &str,325 req: Request<'_>,326 out: &mut dyn Emitter,327 ) -> Result<Report, Failure> {328 if capability != "chat" {329 return Err(Failure::capability(capability));330 }331 let model = lock(&self.model)332 .clone()333 .ok_or_else(|| Failure::dependency("the model is not loaded"))?;334 let text = req335 .parts336 .iter()337 .filter(|part| part.kind == PartKind::Text)338 .find_map(|part| match part.body {339 inf3r_plugin_sdk::capability::PartBody::Inline(bytes) => {340 std::str::from_utf8(bytes).ok().map(str::to_string)341 }342 inf3r_plugin_sdk::capability::PartBody::File(_) => {343 let mut text = String::new();344 part.reader().read_to_string(&mut text).ok()?;345 Some(text)346 }347 })348 .ok_or_else(|| Failure::part("a chat needs a text part"))?;349 let tokens_in = text.len() as u64;350 let mut history = model.history(&text);351 let started = Instant::now();352 let mut first_token_ms = None;353 let mut pending = String::new();354 let mut tokens_out = 0u64;355 for _ in 0..MAX_NEW_TOKENS {356 // The next token is the first unit of work that a cancel can skip.357 if out.cancelled() {358 return Ok(self.report(&model, tokens_in, tokens_out, started, first_token_ms));359 }360 let id = model.argmax(&history);361 history.copy_within(0..WIDTH - 1, 1);362 history[0] = id;363 tokens_out += 1;364 pending.push_str(&model.vocab[id]);365 match model.stops.feed(&pending) {366 Stop::Nothing => {367 if let Err(why) = out.emit(TEXT_CHANNEL, TEXT_MIME, pending.as_bytes()) {368 return self.emit_failed(369 &model,370 tokens_in,371 tokens_out,372 started,373 first_token_ms,374 why,375 );376 }377 first_token_ms.get_or_insert_with(|| elapsed_ms(started));378 pending.clear();379 }380 // The tail may still become the stop string.381 Stop::Partial => {}382 Stop::Matched { upto, .. } => {383 if upto > 0384 && let Err(why) =385 out.emit(TEXT_CHANNEL, TEXT_MIME, &pending.as_bytes()[..upto])386 {387 return self.emit_failed(388 &model,389 tokens_in,390 tokens_out,391 started,392 first_token_ms,393 why,394 );395 }396 if upto > 0 {397 first_token_ms.get_or_insert_with(|| elapsed_ms(started));398 }399 return Ok(self.report(&model, tokens_in, tokens_out, started, first_token_ms));400 }401 }402 }403 Ok(self.report(&model, tokens_in, tokens_out, started, first_token_ms))404 }405 }406 /// Whole milliseconds since `started`, with a floor of one so that a rate has a407 /// denominator.408 fn elapsed_ms(started: Instant) -> u64 {409 u64::try_from(started.elapsed().as_millis())410 .unwrap_or(u64::MAX)411 .max(1)412 }413 /// Hundredths of a token per second over the whole job.414 fn tokens_per_s(tokens_out: u64, elapsed_ms: u64) -> u64 {415 tokens_out416 .saturating_mul(MS_PER_SECOND)417 .saturating_mul(HUNDREDTHS)418 / elapsed_ms419 }420 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {421 m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())422 }423 fn main() -> std::io::Result<()> {424 inf3r_plugin_sdk::launch(Arc::new(Toy::default()))425 }