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
15 changes: 11 additions & 4 deletions examples/web-chat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,20 @@ publish = false
crate-type = ["cdylib"]

[dependencies]
ed-agent = { path = "../../crates/ed-agent" }
# Used only for web_store::download_model; ed-agent does not re-export it. The
# browser engine and web_store arrived in onde 1.5.0.
onde = "1.5.0"
# The inference engine: GGUF loading, the Qwen2 forward pass and sampling.
vectoron = "0.2"
tokenizers = { version = "0.22", default-features = false, features = ["unstable_wasm"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = [
"Cache",
"CacheStorage",
"Headers",
"ReadableStream",
"ReadableStreamDefaultReader",
"Response",
] }
serde = { version = "1", features = ["derive"] }
serde-wasm-bindgen = "0.6"
console_error_panic_hook = "0.1"
Expand Down
42 changes: 23 additions & 19 deletions examples/web-chat/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# web-chat

Ed running a model entirely in the browser. The page talks to a Web Worker
that owns one `Ed` instance compiled to `wasm32-unknown-unknown`. Nothing you
type is sent to a server.
that owns one model, compiled to `wasm32-unknown-unknown`. Nothing you type is
sent to a server. Inference runs on [vectoron](https://github.com/setoelkahfi/vectoron):
it loads the GGUF file, runs the Qwen2 forward pass and samples tokens.

## Build and run

Expand All @@ -16,12 +17,9 @@ python3 -m http.server -d www 8080
Open <http://localhost:8080>. No bundler, npm or special headers are needed.
Cache Storage needs a secure context, which `localhost` counts as.

The browser engine comes from `onde` 1.5.0 on crates.io. To try a local `onde`
checkout instead, pass a patch through to cargo:

```bash
./build.sh --config 'patch.crates-io.onde.path="../../../onde"'
```
`vectoron` comes from its `feature/v1` branch as a git dependency (see
`Cargo.toml`). To build against a local checkout instead, change that line to
`vectoron = { path = "../../../onde-vectoron" }`.

## Deploy

Expand Down Expand Up @@ -49,23 +47,29 @@ from disk without downloading again. **Remove model** in the footer deletes it.

## Phones and tablets

Loading the model peaks at about three times the file in memory (the cached
bytes, the copy handed to the engine, and the tensors built from it), so a bit
over 1 GB. Mobile browsers kill the tab before that. On phones and tablets the
page shows a warning instead of starting, with a link to Siti AI in the App
Store or Google Play (Onde in a native app) and a **Try anyway** button. The
same warning appears on any device whose previous visit was killed while the
model was loading. Lowering the peak is work for onde's `web_store`.
Loading copies the cached file into wasm memory once, and vectoron computes
with the quantized weights in place. The peak is therefore about twice the file
(the JS buffer plus the wasm copy) until the browser frees the JS buffer, so
roughly 800 MB. That figure comes from the code; it has not been profiled. The
earlier engine peaked at over 1 GB, and mobile browsers still kill the tab
around these sizes. On phones and tablets the page shows a warning instead of
starting, with a link to Siti AI in the App Store or Google Play (Onde in a
native app) and a **Try anyway** button. The same warning appears on any device
whose previous visit was killed while the model was loading.

## Speed

Inference is CPU only, single threaded, using WebAssembly SIMD. Expect one to three
tokens per second on a laptop (measured 1.2 to 2.5 on an Apple Silicon Mac). Stop ends the worker and starts a new one, so it
also resets the conversation.
Inference is CPU only, single threaded, using WebAssembly SIMD. On an Apple
Silicon Mac a reply ran at 3.9 to 5.1 tokens per second, counting the prompt.
A follow-up only runs the new part of the prompt, because the conversation's
earlier tokens stay in the model's cache. Stop ends the worker and starts a new
one, so it also resets the conversation.

## Layout

- `src/lib.rs`: the wasm-bindgen API (`WebChat`) around `Ed`.
- `src/lib.rs`: the wasm-bindgen API (`WebChat`).
- `src/chat.rs`: the conversation, its ChatML prompt and streaming generation.
- `src/store.rs`: downloads and caches the model and tokenizer in Cache Storage.
- `www/worker.js`: owns the wasm module and the `WebChat`.
- `www/main.js`, `index.html`, `style.css`: the UI.

Expand Down
3 changes: 1 addition & 2 deletions examples/web-chat/build.sh
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#!/usr/bin/env bash
# Build the wasm package into www/pkg. Serve www/ with any static server:
# python3 -m http.server -d www 8080
# Extra arguments go to `cargo`, e.g. a local onde checkout:
# ./build.sh --config 'patch.crates-io.onde.path="../../../onde"'
# Extra arguments go to `cargo`, e.g. `./build.sh --offline`.
set -euo pipefail
cd "$(dirname "$0")"

Expand Down
200 changes: 200 additions & 0 deletions examples/web-chat/src/chat.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
//! A chat session over one vectoron model: the conversation, its ChatML
//! prompt, and streaming generation.

use tokenizers::Tokenizer;
use vectoron::{Qwen2Model, Sampler, SamplerConfig};
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;

/// Prompt tokens run per forward pass. Between chunks the worker yields, so
/// a long prompt does not hold its event loop for seconds.
const PREFILL_CHUNK: usize = 64;
const MAX_TOKENS: usize = 512;

#[derive(Clone, Copy)]
enum Role {
User,
Assistant,
}

pub struct Chat {
model: Qwen2Model,
tokenizer: Tokenizer,
eos: Vec<u32>,
system: Option<String>,
history: Vec<(Role, String)>,
/// The tokens whose keys and values are in the model's cache, so the
/// next turn only runs what changed.
cached: Vec<u32>,
}

impl Chat {
pub fn new(
model: Qwen2Model,
tokenizer: Tokenizer,
system: Option<String>,
) -> Result<Self, String> {
let eos: Vec<u32> = ["<|im_end|>", "<|endoftext|>"]
.iter()
.filter_map(|t| tokenizer.token_to_id(t))
.collect();
if eos.is_empty() {
return Err("the tokenizer has no end-of-turn token".into());
}
Ok(Self {
model,
tokenizer,
eos,
system,
history: Vec::new(),
cached: Vec::new(),
})
}

pub fn history_len(&self) -> usize {
self.history.len()
}

/// Forgets the conversation. Returns how many messages were dropped.
pub fn reset(&mut self) -> usize {
let dropped = self.history.len();
self.history.clear();
self.cached.clear();
self.model.clear_kv_cache();
dropped
}

/// The conversation as a ChatML prompt ending in an open assistant turn.
fn prompt(&self) -> String {
let mut out = String::new();
let mut turn = |role: &str, content: &str| {
out.push_str("<|im_start|>");
out.push_str(role);
out.push('\n');
out.push_str(content);
out.push_str("<|im_end|>\n");
};
if let Some(system) = &self.system {
turn("system", system);
}
for (role, content) in &self.history {
let role = match role {
Role::User => "user",
Role::Assistant => "assistant",
};
turn(role, content);
}
out.push_str("<|im_start|>assistant\n");
out
}

/// Answers `message`, calling `on_piece` with each new piece of text.
/// Returns the whole reply, which is added to the conversation.
pub async fn send(
&mut self,
message: String,
on_piece: impl FnMut(&str),
) -> Result<String, String> {
self.history.push((Role::User, message));
match self.generate(on_piece).await {
Ok(reply) => {
self.history.push((Role::Assistant, reply.clone()));
Ok(reply)
}
Err(e) => {
self.history.pop();
Err(e)
}
}
}

async fn generate(&mut self, mut on_piece: impl FnMut(&str)) -> Result<String, String> {
let ids = self
.tokenizer
.encode(self.prompt(), false)
.map_err(|e| e.to_string())?
.get_ids()
.to_vec();

// Reuse the cached positions the new prompt shares with the last one.
let mut start = self
.cached
.iter()
.zip(&ids)
.take_while(|(a, b)| a == b)
.count();
if start == ids.len() {
start -= 1;
Comment thread
setoelkahfi marked this conversation as resolved.
Resolved
}
// `cached` mirrors the model's cache, which forward() truncates to
// `start` before running a chunk.
self.cached.truncate(start);
let mut logits = Vec::new();
for chunk in ids[start..].chunks(PREFILL_CHUNK) {
logits = self
.model
.forward(chunk, start)
.map_err(|e| e.to_string())?;
self.cached.extend_from_slice(chunk);
start += chunk.len();
yield_to_event_loop().await;
}

let mut sampler = Sampler::new(SamplerConfig {
seed: seed(),
..SamplerConfig::default()
});
let mut generated: Vec<u32> = Vec::new();
let mut shown = 0;
let mut reply = String::new();
for _ in 0..MAX_TOKENS {
let next = sampler.sample(&mut logits, &generated);
if self.eos.contains(&next) {
break;
}
generated.push(next);
let text = self
.tokenizer
.decode(&generated, true)
.map_err(|e| e.to_string())?;
// Hold back a piece that ends inside a multi-byte character.
if !text.ends_with('\u{fffd}') && text.len() > shown {
on_piece(&text[shown..]);
shown = text.len();
reply = text;
}
if self.model.cache_len() + 1 >= self.model.config().context_length {
Comment thread
setoelkahfi marked this conversation as resolved.
Resolved
break;
}
logits = self
.model
.forward(&[next], self.model.cache_len())
.map_err(|e| e.to_string())?;
self.cached.push(next);
yield_to_event_loop().await;
}
Ok(reply)
}
}

/// A seed that differs between replies.
fn seed() -> u64 {
let now = js_sys::Date::now() as u64;
let random = (js_sys::Math::random() * u32::MAX as f64) as u64;
now ^ (random << 20)
}

/// Lets the worker's event loop run (a `setTimeout(0)` macrotask).
async fn yield_to_event_loop() {
let promise = js_sys::Promise::new(&mut |resolve, _reject| {
let global = js_sys::global();
if let Ok(set_timeout) = js_sys::Reflect::get(&global, &"setTimeout".into()) {
if let Ok(set_timeout) = set_timeout.dyn_into::<js_sys::Function>() {
let _ = set_timeout.call2(&global, &resolve, &JsValue::from(0));
return;
}
}
let _ = resolve.call0(&JsValue::UNDEFINED);
});
let _ = JsFuture::from(promise).await;
}
Loading
Loading