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
//! Serving LLMs (feature `llm`): the OpenAI chat and completions API, with streaming, next to
//! the other models of the same server.
//!
//! Furnace owns the server side of an LLM: the OpenAI-compatible routes and their errors, SSE
//! streaming, cancellation when the client goes away, admission and backpressure, and the
//! metrics (time to first token, inter-token latency, tokens per second). The engine that runs
//! the model sits behind one of two traits:
//!
//! - [`LlmEngine`]: a request goes in, a stream of [`Event`]s comes out, and dropping the stream
//! cancels the request. Engines with their own scheduler implement it directly.
//! - [`StepModel`]: a plain model that can prefill a prompt and decode one token at a time over
//! an opaque per-sequence state. [`Scheduled`] turns one into an [`LlmEngine`], with a
//! [`TextPipeline`] for the chat template, the tokenizer, sampling, incremental detokenization
//! and stop strings. This is the way in for your own Burn LLM, and for the candle adapter
//! (the `furnace-candle` crate).
//!
//! [`Server::llm`](crate::Server::llm) serves an engine on `POST /v1/chat/completions`,
//! `POST /v1/completions` and `GET /v1/models`, behind the server's API keys, rate limit,
//! concurrency limit and TLS.
//!
//! # Your own Burn LLM
//!
//! A toy: a Burn model that maps tokens to next-token logits, served with step-wise decoding.
//! It keeps no KV cache, so each step runs the whole sequence again; a real model keeps its
//! cache in the [`StepModel::Sequence`], and furnace drops it when the request ends or the
//! client disconnects.
//!
//! ```no_run
//! use burn::module::Module;
//! use burn::nn::{Embedding, EmbeddingConfig, Linear, LinearConfig};
//! use burn::tensor::{Device, Int, Tensor, TensorData};
//! use furnace::llm::{BoxError, Logits, Scheduled, StepModel, TextPipeline};
//! use furnace::{BackendKind, Server};
//!
//! #[derive(Module, Debug)]
//! struct TinyLm {
//! embedding: Embedding,
//! head: Linear,
//! }
//!
//! impl TinyLm {
//! fn new(vocab: usize, device: &Device) -> Self {
//! Self {
//! embedding: EmbeddingConfig::new(vocab, 64).init(device),
//! head: LinearConfig::new(64, vocab).init(device),
//! }
//! }
//!
//! /// `[1, seq]` token ids -> `[1, seq, vocab]` logits
//! fn forward(&self, ids: Tensor<2, Int>) -> Tensor<3> {
//! self.head.forward(self.embedding.forward(ids))
//! }
//! }
//!
//! #[derive(Debug)]
//! struct BurnLm {
//! net: TinyLm,
//! device: Device,
//! }
//!
//! impl BurnLm {
//! /// The logits after the last of `tokens`
//! fn next_logits(&self, tokens: &[u32]) -> Result<Logits, BoxError> {
//! let ids: Vec<i64> = tokens.iter().map(|&t| i64::from(t)).collect();
//! let ids = Tensor::from_data(TensorData::new(ids, [1, tokens.len()]), &self.device);
//! let logits = self.net.forward(ids); // [1, seq, vocab]
//! let [_, seq, vocab] = logits.dims();
//! let last = logits.slice([0..1, seq - 1..seq, 0..vocab]).flatten::<1>(0, 2);
//! Ok(Logits(last.into_data().try_into_vec::<f32>()?))
//! }
//! }
//!
//! impl StepModel for BurnLm {
//! /// The tokens so far; a real model keeps its KV cache and position here
//! type Sequence = Vec<u32>;
//!
//! fn name(&self) -> &str {
//! "tiny-lm"
//! }
//!
//! fn max_context(&self) -> usize {
//! 512
//! }
//!
//! fn prefill(&self, prompt: &[u32]) -> Result<(Vec<u32>, Logits), BoxError> {
//! Ok((prompt.to_vec(), self.next_logits(prompt)?))
//! }
//!
//! fn decode(&self, tokens: &mut Vec<u32>, token: u32) -> Result<Logits, BoxError> {
//! tokens.push(token);
//! self.next_logits(tokens)
//! }
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), BoxError> {
//! // The tokenizer and chat template your model was trained with
//! let pipeline = TextPipeline::from_files("tokenizer.json", Some("tokenizer_config.json".as_ref()))?;
//! let device = BackendKind::Cpu.device();
//! let mut net = TinyLm::new(pipeline.tokenizer().get_vocab_size(true), &device);
//! furnace::weights::load_burnpack(&mut net, "tiny-lm.bpk".as_ref())?;
//!
//! let engine = Scheduled::new(BurnLm { net, device }, pipeline);
//! Server::new().port(8080).llm(engine).serve().await?;
//! Ok(())
//! }
//! ```
use fmt;
pub use ;
pub use ;
pub use ;
pub use Sampler;
pub use ;
pub use StopStrings;
/// Any error a model returns; furnace reports its message
pub type BoxError = ;
/// One message of a chat
/// What to generate from
/// How to pick tokens; `None` means the engine's default
/// A request for an engine, parsed and checked by the HTTP layer
/// Why generation ended
/// What an engine sends back, in order: `Started` once, `Text` any number of times, then
/// `Finished` or `Error`
/// Why an engine refused or failed a request
/// An LLM furnace can serve.
///
/// [`generate`](Self::generate) checks and queues a request and returns its events. Dropping the
/// receiver cancels the request: the engine must stop generating for it and free its memory.
/// Engines with their own scheduler implement this; plain models implement [`StepModel`] and are
/// wrapped in [`Scheduled`].