bunsen-tool 0.43.0

bunsen's models on the command line: speech to text (Parakeet, Qwen3-ASR, Voxtral Realtime, Whisper) and who spoke when (Sortformer), text to speech (ZONOS3, Qwen3-TTS), chat (Qwen3, Qwen3.5, Gemma, nanochat) and typed decisions (Laya). The chat driver is also a library, `bunsen_tool::chat`.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! The flags `chat run` and `chat repl` share.

use std::{
    io::{
        BufRead,
        Write,
    },
    sync::Arc,
};

use bunsen::{
    data::builds::BuildSummary,
    errors::{
        BunsenResult,
        sys_at,
    },
    kits::support::decoding::SearchConfig,
    ops::transformers::attention::KVCacheStorage,
};
use bunsen_app::{
    cache::WeightsCacheArgs,
    device::{
        BackendArgs,
        DeviceSession,
    },
    logging::{
        LevelFilter,
        LogArgs,
        LogPolicy,
    },
    precision::MinPrecisionArgs,
};
use clap::ArgMatches;

use crate::{
    chat::{
        ChatBackend,
        ChatMessage,
        ChatModel,
        ChatModelFamily,
        ChatModelFamilyFlags,
        ChatReply,
        ChatSession,
        ChatSessionConfig,
        ChatVisitor,
        LoadedChat,
        choose_checkpoint,
        search_config,
    },
    support::{
        ChooseArgs,
        with_patch,
        with_presets,
    },
};

/// How the checkpoint is loaded and a reply generated.
#[derive(clap::Args, Debug)]
pub struct ChatGenerateFlags {
    #[clap(flatten)]
    logging: LogArgs,

    #[clap(flatten)]
    cache: WeightsCacheArgs,

    /// The device. The checkpoint loads at the precision it ships in where
    /// the device accelerates it, else in f32: Qwen3's bf16 on cuda and
    /// metal, f32 on vulkan, wgpu and the CPU (`LoadPolicy::performance`);
    /// `--min-precision` puts a floor under that.
    #[clap(flatten)]
    device: BackendArgs,

    /// The narrowest float the checkpoint's weights are placed in.
    #[clap(flatten)]
    precision: MinPrecisionArgs,

    /// The checkpoint, chosen among the family's builds (outside `family`,
    /// every chat family's) by `--model` and the stage flags, the presets
    /// keeping only the builds that offer them. The family's default when
    /// nothing is named; an `hf:org/repo` outside `family` is a Qwen3.
    #[clap(flatten)]
    choose: ChooseArgs,

    /// A system prompt.
    #[arg(long)]
    system: Option<String>,

    /// The most tokens a reply generates.
    #[arg(long, default_value_t = 1024)]
    max_new_tokens: usize,

    /// Decode greedily, whatever the checkpoint's generation defaults say.
    #[arg(long)]
    greedy: bool,

    /// The sampling temperature, over the checkpoint's.
    #[arg(long)]
    temperature: Option<f64>,

    /// Sample from the top-k tokens only, over the checkpoint's.
    #[arg(long)]
    top_k: Option<usize>,

    /// Sample from the top-p nucleus only, over the checkpoint's.
    #[arg(long)]
    top_p: Option<f64>,

    /// Seed the device's random numbers, for a repeatable sampled reply.
    #[arg(long)]
    seed: Option<u64>,

    /// The positions the KV cache holds; the checkpoint's trained length by
    /// default.
    #[arg(long)]
    context: Option<usize>,

    /// How the KV cache stores its history.
    #[arg(long, value_enum, default_value_t = ChatKvStorage::Auto)]
    kv_storage: ChatKvStorage,

    /// Print the model and the reply's token counts and speeds, to stderr.
    ///
    /// After each reply: the model's lookup expression (its name and presets)
    /// on a line of its own, then the counts and speeds.
    #[arg(long)]
    stats: bool,
}

/// `--kv-storage`.
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
enum ChatKvStorage {
    Auto,
    Concat,
    PerLayer,
    MultiLayer,
}

impl ChatKvStorage {
    fn storage(self) -> KVCacheStorage {
        match self {
            Self::Auto => KVCacheStorage::Auto,
            Self::Concat => KVCacheStorage::Concat,
            Self::PerLayer => KVCacheStorage::PerLayer,
            Self::MultiLayer => KVCacheStorage::MultiLayer,
        }
    }
}

impl ChatGenerateFlags {
    /// The checkpoint these flags choose, with `presets` (the family flags'
    /// own, such as `--think`'s) among the presets, its family, and every
    /// preset to apply: within `family` (its default when nothing is named),
    /// or outside `family` across every family ([`choose_checkpoint`]).
    /// `matches` are the command's own, for the stage flags' order.
    pub(super) fn checkpoint(
        &self,
        family: Option<ChatModelFamily>,
        presets: &[(&str, &str)],
        matches: &ArgMatches,
    ) -> BunsenResult<(ChatModelFamily, String, Vec<String>)> {
        let mut flags = self.choose.flags(matches)?;
        for (preset, flag) in presets {
            flags = flags.with_preset(*preset, *flag);
        }
        let (family, name) = choose_checkpoint(family, &self.choose.model, &flags)?;
        Ok((family, name, flags.presets.presets))
    }

    /// Opens the device, and loads the checkpoint on it: `family`'s, or
    /// outside `family` whichever `--model` names. Also returns the lookup
    /// expression it loaded (the checkpoint's name, with the presets
    /// `--preset` and `family`'s flags add), and the build that answered
    /// it, for a command to report ([`log_build`](crate::support::log_build)).
    pub(super) fn load(
        &self,
        family: Option<ChatModelFamily>,
        presets: &[(&str, &str)],
        matches: &ArgMatches,
    ) -> BunsenResult<(DeviceSession, LoadedChat, String, BuildSummary)> {
        self.logging
            .init(LogPolicy::new(LevelFilter::Warn, LevelFilter::Warn))?;
        let cache = self.cache.init()?;
        let device = self.device.open()?;
        if let Some(seed) = self.seed {
            device.seed(seed);
        }
        let (family, mut name, presets) = self.checkpoint(family, presets, matches)?;
        if !presets.is_empty() {
            let presets: Vec<&str> = presets.iter().map(String::as_str).collect();
            name = with_presets(&name, &presets)?;
        }
        if let Some(patch) = self.choose.patch()? {
            name = with_patch(&name, &patch)?;
        }
        let (chat, build) = family.load(&name, &cache, &device, self.precision.load_policy())?;
        Ok((device, chat, name, build))
    }

    /// The session config these flags and `family`'s give, over `chat`'s
    /// defaults.
    fn config<B: ChatBackend>(
        &self,
        chat: &ChatModel<B>,
    ) -> ChatSessionConfig {
        let defaults = search_config(chat.generation());
        let search = if self.greedy {
            SearchConfig::new()
        } else {
            SearchConfig {
                temperature: self.temperature.unwrap_or(defaults.temperature),
                top_k: self.top_k.or(defaults.top_k),
                top_p: self.top_p.or(defaults.top_p),
                ..defaults
            }
        };
        ChatSessionConfig::new()
            .with_max_new_tokens(self.max_new_tokens)
            .with_search(Some(search))
            .with_context(self.context)
            .with_storage(self.kv_storage.storage())
    }

    /// A session over `chat`, opened with the system prompt.
    fn session<B: ChatBackend>(
        &self,
        chat: &Arc<ChatModel<B>>,
        config: ChatSessionConfig,
        device: &DeviceSession,
    ) -> ChatSession<B> {
        let mut session = chat.session(config, device);
        if let Some(system) = &self.system {
            session.push(ChatMessage::system(system.clone()));
        }
        session
    }

    /// Sends `user`, streaming the reply to stdout (its thinking only when
    /// `family`'s flags show it), and reports it under `--stats`: `model`,
    /// the lookup expression loaded, on a line of its own, then the reply's
    /// numbers.
    fn reply<B: ChatBackend>(
        &self,
        session: &mut ChatSession<B>,
        family: &impl ChatModelFamilyFlags,
        model: &str,
        user: &str,
    ) -> BunsenResult<ChatReply> {
        let mut out = std::io::stdout().lock();
        let mut hidden = ChatThinkingFilter::new(family.hide_thinking());
        let mut failed = None;
        let reply = session.send(user, &mut |delta| {
            let shown = hidden.push(delta);
            if let Err(e) = out.write_all(shown.as_bytes()).and_then(|()| out.flush()) {
                failed.get_or_insert(e);
            }
        })?;
        writeln!(out).map_err(sys_at("write to", "stdout"))?;
        if !hidden.done {
            eprintln!("[the reply ran out of tokens while thinking; --show-thinking shows it]");
        }
        if let Some(e) = failed {
            return Err(sys_at("write to", "stdout")(e));
        }
        if self.stats {
            let rate = |n: usize, t: std::time::Duration| n as f64 / t.as_secs_f64().max(1e-9);
            eprintln!("[model {model}]");
            eprintln!(
                "[{:?}; prompt {} tokens, {} prefilled in {:.2} s ({:.0} tok/s); reply {} tokens in {:.2} s ({:.1} tok/s); {:?}]",
                session.model().float_dtype(),
                reply.prompt_tokens,
                reply.prefilled_tokens,
                reply.prefill_time.as_secs_f64(),
                rate(reply.prefilled_tokens, reply.prefill_time),
                reply.ids.len(),
                reply.decode_time.as_secs_f64(),
                rate(reply.ids.len(), reply.decode_time),
                reply.stop,
            );
        }
        Ok(reply)
    }

    /// Answers `prompt` with `chat`, `model` the lookup expression loaded,
    /// once.
    pub(super) fn run_once(
        &self,
        chat: &LoadedChat,
        family: &impl ChatModelFamilyFlags,
        device: &DeviceSession,
        model: &str,
        prompt: &str,
    ) -> BunsenResult<()> {
        chat.visit(RunOnce {
            flags: self,
            family,
            device,
            model,
            prompt,
        })
    }

    /// Holds a conversation on stdin with `chat`, `model` the lookup
    /// expression loaded.
    pub(super) fn converse(
        &self,
        chat: &LoadedChat,
        family: &impl ChatModelFamilyFlags,
        device: &DeviceSession,
        model: &str,
    ) -> BunsenResult<()> {
        chat.visit(Converse {
            flags: self,
            family,
            device,
            model,
        })
    }

    /// Answers `prompt` with `model`, the lookup expression loaded, once.
    fn run_once_with<B: ChatBackend>(
        &self,
        chat: &Arc<ChatModel<B>>,
        family: &impl ChatModelFamilyFlags,
        device: &DeviceSession,
        model: &str,
        prompt: &str,
    ) -> BunsenResult<()> {
        let mut session = self.session(chat, self.config(chat), device);
        self.reply(&mut session, family, model, prompt)?;
        Ok(())
    }

    /// Holds a conversation on stdin with `model`, the lookup expression
    /// loaded.
    fn converse_with<B: ChatBackend>(
        &self,
        chat: &Arc<ChatModel<B>>,
        family: &impl ChatModelFamilyFlags,
        device: &DeviceSession,
        model: &str,
    ) -> BunsenResult<()> {
        let config = self.config(chat);
        let mut session = self.session(chat, config.clone(), device);
        let stdin = std::io::stdin();
        let mut lines = stdin.lock().lines();
        loop {
            eprint!("> ");
            let Some(line) = lines.next() else { break };
            let line = line.map_err(sys_at("read", "stdin"))?;
            match line.trim() {
                "" => continue,
                "/quit" => break,
                "/reset" => {
                    session = self.session(chat, config.clone(), device);
                    eprintln!("[a new conversation]");
                }
                user => {
                    self.reply(&mut session, family, model, user)?;
                }
            }
        }
        Ok(())
    }
}

/// [`ChatGenerateFlags::run_once`] over a typed model.
struct RunOnce<'a, F> {
    flags: &'a ChatGenerateFlags,
    family: &'a F,
    device: &'a DeviceSession,
    model: &'a str,
    prompt: &'a str,
}

impl<F: ChatModelFamilyFlags> ChatVisitor for RunOnce<'_, F> {
    type Output = BunsenResult<()>;

    fn visit<B: ChatBackend>(
        self,
        chat: &Arc<ChatModel<B>>,
    ) -> Self::Output {
        self.flags
            .run_once_with(chat, self.family, self.device, self.model, self.prompt)
    }
}

/// [`ChatGenerateFlags::converse`] over a typed model.
struct Converse<'a, F> {
    flags: &'a ChatGenerateFlags,
    family: &'a F,
    device: &'a DeviceSession,
    model: &'a str,
}

impl<F: ChatModelFamilyFlags> ChatVisitor for Converse<'_, F> {
    type Output = BunsenResult<()>;

    fn visit<B: ChatBackend>(
        self,
        chat: &Arc<ChatModel<B>>,
    ) -> Self::Output {
        self.flags
            .converse_with(chat, self.family, self.device, self.model)
    }
}

/// Hides a reply's thinking from the stream: everything up to and through
/// `</think>`, when the reply opens with `<think>`.
struct ChatThinkingFilter {
    seen: String,
    done: bool,
    /// The thinking just ended: the newlines before the answer are dropped.
    trim: bool,
}

impl ChatThinkingFilter {
    fn new(hide: bool) -> Self {
        Self {
            seen: String::new(),
            done: !hide,
            trim: false,
        }
    }

    fn push(
        &mut self,
        delta: &str,
    ) -> String {
        if self.done {
            if !self.trim {
                return delta.to_string();
            }
            let shown = delta.trim_start_matches('\n');
            self.trim = shown.is_empty();
            return shown.to_string();
        }
        self.seen.push_str(delta);
        let opening = self.seen.trim_start();
        if !"<think>".starts_with(opening) && !opening.starts_with("<think>") {
            // Not a thinking reply after all.
            self.done = true;
            return std::mem::take(&mut self.seen);
        }
        match self.seen.split_once("</think>") {
            Some((_, answer)) => {
                self.done = true;
                let answer = answer.trim_start_matches('\n').to_string();
                self.trim = answer.is_empty();
                self.seen.clear();
                answer
            }
            None => String::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use bunsen::kits::language::generation::{
        nanochat::pretrained::DEFAULT_NANOCHAT_MODEL,
        qwen3::pretrained::DEFAULT_QWEN3_MODEL,
    };
    use clap::{
        CommandFactory,
        FromArgMatches,
    };

    use super::*;

    /// The flags alone, as `chat run` and `chat repl` flatten them.
    #[derive(clap::Parser, Debug)]
    struct Args {
        #[clap(flatten)]
        flags: ChatGenerateFlags,
    }

    #[test]
    fn test_thinking_filter() {
        let mut hide = ChatThinkingFilter::new(true);
        let shown: String = ["<thi", "nk>\nhm", "\n</think>", "\n\nBlue."]
            .iter()
            .map(|d| hide.push(d))
            .collect();
        assert_eq!(shown, "Blue.");

        let mut plain = ChatThinkingFilter::new(true);
        let shown: String = ["Bl", "ue."].iter().map(|d| plain.push(d)).collect();
        assert_eq!(shown, "Blue.");

        let mut show = ChatThinkingFilter::new(false);
        assert_eq!(show.push("<think>x"), "<think>x");
    }

    /// In `family`, an omitted `--model` is the family's default; outside
    /// it, Qwen3's.
    #[test]
    fn test_checkpoint() {
        let matches = Args::command().try_get_matches_from(["run"]).unwrap();
        let Args { flags } = Args::from_arg_matches(&matches).unwrap();
        assert_eq!(
            flags.checkpoint(None, &[], &matches).unwrap(),
            (
                ChatModelFamily::Qwen3,
                DEFAULT_QWEN3_MODEL.to_string(),
                Vec::new()
            )
        );
        assert_eq!(
            flags
                .checkpoint(Some(ChatModelFamily::NanoChat), &[], &matches)
                .unwrap(),
            (
                ChatModelFamily::NanoChat,
                DEFAULT_NANOCHAT_MODEL.to_string(),
                Vec::new()
            )
        );
    }

    /// A family flag's preset (`--think`'s) chooses among the builds that
    /// offer it and reaches the load for every family that has it, Qwen3.5's
    /// as well as Qwen3's (#673); a family without it chooses nothing.
    #[test]
    fn test_family_presets_choose_and_load() {
        let matches = Args::command().try_get_matches_from(["run"]).unwrap();
        let Args { flags } = Args::from_arg_matches(&matches).unwrap();
        let think = [("thinking", "--think")];
        let no_think = [("no-thinking", "--no-think")];

        let (family, _, presets) = flags
            .checkpoint(Some(ChatModelFamily::Qwen3_5), &think, &matches)
            .unwrap();
        assert_eq!(family, ChatModelFamily::Qwen3_5);
        assert_eq!(presets, ["thinking"]);
        let (family, _, presets) = flags.checkpoint(None, &no_think, &matches).unwrap();
        assert_eq!(family, ChatModelFamily::Qwen3);
        assert_eq!(presets, ["no-thinking"]);
        assert!(
            flags
                .checkpoint(Some(ChatModelFamily::NanoChat), &think, &matches)
                .is_err()
        );
    }
}