zyth.io / demos
Demos
Each one runs in this browser tab: Zyth compiled to WebAssembly, with WebGPU when the browser has it and the CPU when it does not. Nothing is sent to a server. Two need programs on your computer (Python, npm, building an executable): their output below was recorded when this page was built.
AI and 3D components in a React + Redux app runs here
Two components written in Zyth, installed as npm packages: a network trained in the page, and a cube drawn on the GPU. A TypeScript panel drives the same network from the Redux store.
Open the React + Redux app// A React component that trains a neural network in the browser. The component compiles to
// JavaScript; `train` and `predictions` use tensors, so they run in WebAssembly in the same
// package (zyth build --target npm-jsx xor.zyth -o xor), and the component calls them from an
// event handler and from `use_async`.
use zyth.react.{div, h2, button, p, ul, li, use_state, use_async, Element}
use zyth.optim.AdamW
seed(7)
model MLPNet(hidden: i64) {
fc1 = Linear(2 -> hidden)
fc2 = Linear(hidden -> 2)
fn forward(self, x: tensor<f32, [B, 2]>) -> tensor<f32, [B, 2]> {
return x |> self.fc1 |> relu |> self.fc2
}
}
let data = tensor.from([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]])
let labels = tensor.from([0, 1, 1, 0])
let net = MLPNet(16)
let opt = AdamW(net.params, lr: 0.05, weight_decay: 0.0)
/// Train `steps` more steps; the loss after the last one.
@export
fn train(steps: i64) -> f64 {
var loss = 0.0
for _ in 0..steps {
let l = net(data) |> cross_entropy(labels)
opt.step(grad(l, wrt: net.params))
loss = l.item()
}
return loss
}
/// The network's answers for 00, 01, 10 and 11.
@export
fn predictions() -> str = "{net(data).argmax(axis: -1).tolist()}"
fn param_count() -> i64 = net.param_count()
/// Trains XOR in the browser, `steps` steps per click.
@export
fn XorTrainer(steps: i64 = 50) -> Element {
let none: f64[] = []
let (losses, set_losses) = use_state(none)
let (answers, set_answers) = use_state("not trained yet")
let params = use_async(|| param_count(), deps: [])
return div(class: "xor") {
h2 { "XOR, trained in your browser" }
p(class: "params") { if params == None { "loading the model..." } else { "{params ?? 0} parameters" } }
button(on_click: || {
let loss = train(steps)
set_losses(losses + [loss])
set_answers(predictions())
}) { "train {steps} steps" }
ul {
for (i, loss) in losses.enumerate() {
li { "after {(i + 1) * steps} steps: loss {loss:.4}" }
}
}
p(class: "answers") { "answers for 00, 01, 10, 11: {answers}" }
}
}// A React component with a 3D view drawn by Zyth on the GPU (WebGPU). The component compiles to
// JavaScript; the drawing (`zyth.gfx`) runs in WebAssembly in the same package. The canvas goes
// into the component's `div(id: "zyth-cube")`, and `use_frame` draws one frame per animation
// frame, at the speed the buttons set (React state).
// zyth build --target npm-jsx cube.zyth -o cube
use zyth.react.{div, h2, p, button, use_state, use_frame, Element}
use zyth.gfx
let s = gfx.window(title: "Zyth cube", width: 320, height: 320, host: "zyth-cube")
let shader = gfx.shader(r"""
struct U { angle: f32, tilt: f32, _a: f32, _b: f32 }
@group(0) @binding(0) var<uniform> u: U;
struct Out { @builtin(position) pos: vec4f, @location(0) color: vec3f }
@vertex fn vs(@location(0) p: vec3f, @location(1) n: vec3f, @location(2) c: vec3f) -> Out {
let ca = cos(u.angle);
let sa = sin(u.angle);
let ct = cos(u.tilt);
let st = sin(u.tilt);
// turn around y, then tilt around x
let ry = vec3f(ca * p.x + sa * p.z, p.y, -sa * p.x + ca * p.z);
let q = vec3f(ry.x, ct * ry.y - st * ry.z, st * ry.y + ct * ry.z);
let ny = vec3f(ca * n.x + sa * n.z, n.y, -sa * n.x + ca * n.z);
let m = vec3f(ny.x, ct * ny.y - st * ny.z, st * ny.y + ct * ny.z);
let light = max(dot(m, normalize(vec3f(0.4, 0.7, -0.6))), 0.0);
var o: Out;
// a camera 4 units away; depth from 0 (z = 1) to 1 (z = 7), so nearer faces hide farther ones
let z = q.z + 4.0;
o.pos = vec4f(q.x * 1.3, q.y * 1.3, (z - 1.0) / 6.0 * z, z);
o.color = c * (0.25 + 0.75 * light);
return o;
}
@fragment fn fs(o: Out) -> @location(0) vec4f { return vec4f(o.color, 1.0); }
""")
let pipe = s.pipeline(shader, buffers: [["f32x3", "f32x3", "f32x3"]], depth: true)
/// Two triangles for one face of the unit cube: corner positions, the face's normal, its color.
fn face(n: f64[], u: f64[], v: f64[], color: f64[]) -> f64[] {
var out: f64[] = []
for (a, b) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] {
for i in 0..3 {
out.push(n[i] + a * u[i] + b * v[i])
}
out = out + n + color
}
return out
}
fn cube() -> f64[] {
return face([0.0, 0.0, -1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.95, 0.42, 0.24]) +
face([0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.30, 0.75, 0.55]) +
face([1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.98, 0.78, 0.26]) +
face([-1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0], [0.35, 0.55, 0.95]) +
face([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.85, 0.85, 0.88]) +
face([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.55, 0.35, 0.70])
}
let vertices = gfx.buffer(cube())
let uniforms = gfx.buffer([0.0, 0.5, 0.0, 0.0])
/// Draw one frame with the cube turned by `angle` (radians).
@export
fn draw(angle: f64) {
uniforms.write([angle, 0.5, 0.0, 0.0])
s.frame(clear: [0.07, 0.08, 0.10]) { f -> f.draw(pipe, vertices: [vertices], bind: [uniforms]) }
}
/// A turning cube; the buttons change its speed.
@export
fn Cube() -> Element {
let (speed, set_speed) = use_state(1.0)
let (angle, set_angle) = use_state(0.0)
let (last, set_last) = use_state(0.0)
use_frame(|t| {
let a = angle + (t - last) * speed
draw(a)
set_angle(a)
set_last(t)
})
return div(class: "cube") {
h2 { "A cube drawn by Zyth on the GPU" }
div(id: "zyth-cube", class: "view")
button(on_click: || set_speed(max(speed * 2.0, 0.5))) { "faster" }
button(on_click: || set_speed(speed / 2.0)) { "slower" }
button(on_click: || set_speed(0.0)) { "stop" }
p(class: "speed") { "speed {speed:.2} radians a second" }
}
}A shape error caught before running runs here
In a live editor: press Run, and the checker stops the program before it starts, saying where each dimension came from. Change the line it names and run again.
Open it in the editor// The checker finds this bug before the program runs.
// Press Run: nothing executes, and the error explains where 512 and 256 came from.
model Classifier {
fc1 = Linear(784 -> 512)
fc2 = Linear(256 -> 10)
fn forward(self, x: tensor<f32, [B, 784]>) -> tensor<f32, [B, 10]> {
return x |> self.fc1 |> relu |> self.fc2
}
}
let model = Classifier()
print(model(tensor.randn(32, 784)).shape)
Training in the browser runs here
A small network learns XOR with automatic differentiation and AdamW, in WebAssembly.
Open it in the editoruse zyth.optim.AdamW
seed(3)
model MLP {
fc1 = Linear(2 -> 16)
fc2 = Linear(16 -> 2)
fn forward(self, x: tensor<f32, [B, 2]>) -> tensor<f32, [B, 2]> {
return x |> self.fc1 |> relu |> self.fc2
}
}
let x = tensor.from([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]])
let y = tensor.from([0, 1, 1, 0])
let model = MLP()
let opt = AdamW(model.params, lr: 0.05, weight_decay: 0.0)
for step in 0..300 {
let loss = model(x) |> cross_entropy(y)
opt.step(grad(loss, wrt: model.params))
if step % 50 == 0 { print("step {step}: loss {loss:.4f}") }
}
print("predictions {model(x).argmax(axis: -1).tolist()} (expected [0, 1, 1, 0])")
A GPT in about 12 lines runs here
A character-level transformer trained on Shakespeare in the tab, then asked to continue "ROMEO:". It is tiny (one layer, 150 steps), so expect Shakespeare-shaped noise.
Open it in the editor// A character-level GPT trained in your browser tab (CPU, WebAssembly).
use zyth.nn.Transformer
use zyth.data.text
use zyth.optim.AdamW
seed(42)
let tok = text.tokenizer("char")
let data = text.stream("data/tinyshakespeare.txt", tokenizer: tok, context: 32).batch(8)
let model = Transformer(layers: 1, heads: 2, dim: 32, vocab: tok.vocab_size, context: 32)
let opt = AdamW(model.params, lr: 5e-3)
for (step, batch) in data.take(150).enumerate() {
let loss = model(batch.x) |> cross_entropy(batch.y)
opt.step(grad(loss, wrt: model.params))
if step % 25 == 0 { print("step {step}: loss {loss:.3f}") }
}
print(model.generate(tok.encode("ROMEO:"), max_tokens: 120) |> tok.decode)
A chat assistant on your GPU runs here
Qwen2.5-Instruct (0.5B or 1.5B) answering in the tab, on your graphics card through WebGPU, with Zyth's language-model engine. zyth build --target web packs the weights to 4 bits (330 or 940 MB, downloaded once and kept by the browser); the answer appears as it is written, about 120 words a second on an RTX 3090 with the small model. Nothing typed leaves the device.
Talk to it
@target(web)
use zyth.web.{dom}
// A chat assistant running in the visitor's browser: Qwen2.5-Instruct on their GPU (WebGPU),
// through Zyth's language-model engine. The page downloads the weights once (4-bit, packed by
// `zyth build --target web`) and keeps them; nothing typed here leaves the device.
let system = "You are the assistant on zyth.io. You run entirely inside this web browser, on the visitor's own GPU, in a program written in the Zyth programming language; nothing they type leaves their device. Be friendly and brief."
let chats = {
"small": ai.chat("Qwen/Qwen2.5-0.5B-Instruct", format: "q4_0", device: gpu, context: 2048, max_tokens: 400, system: system),
"large": ai.chat("Qwen/Qwen2.5-1.5B-Instruct", format: "q4_0", device: gpu, context: 2048, max_tokens: 400, system: system),
}
var chat = chats["small"]
var ready = false
var busy = false
var turn = 0
var log = ""
fn escape(s: str) -> str {
s.replace("&", "&").replace("<", "<").replace(">", ">")
}
fn mb(bytes: int) -> str {
"{(bytes.to_float() / 1048576.0).round().to_int()} MB"
}
dom.on("#load", "click") { _ ->
if ready || busy { return }
busy = true
let pick = dom.value("#model")
chat = chats[pick]
dom.add_class("body", "loading")
let t0 = now()
var last = t0
var last_bytes = 0
var speed = ""
let info = chat.load(on_progress: { p ->
dom.set_attr("#bar", "style", "width: {p.percent}%")
let t = now()
if t - last > 0.5 {
speed = " · {((p.loaded - last_bytes).to_float() / 1048576.0 / (t - last)).round().to_int()} MB/s"
last = t
last_bytes = p.loaded
}
if p.done {
dom.set_text("#progress", "Starting the model on your GPU…")
} else {
dom.set_text("#progress", "Downloading {mb(p.loaded)} of {mb(p.total)}{speed}")
}
})
let secs = (now() - t0) * 10.0
dom.set_text("#hud-model", if pick == "small" { "Qwen2.5 0.5B" } else { "Qwen2.5 1.5B" })
dom.set_text("#hud-device", if info["device"] == "gpu" { "your GPU" } else { "your CPU" })
dom.set_text("#hud-load", "{secs.round() / 10.0} s")
dom.remove_class("body", "loading")
dom.add_class("body", "ready")
ready = true
busy = false
}
dom.on("#ask", "submit") { _ ->
let q = dom.value("#q").trim()
if !ready || busy || q == "" { return }
busy = true
dom.set_value("#q", "")
dom.add_class("body", "busy")
turn += 1
log = log + "<div class=\"msg you\">{escape(q)}</div><div class=\"msg bot\" id=\"a{turn}\"><span class=\"dots\"></span></div>"
dom.set_html("#log", log)
let t0 = now()
var first = 0.0
var tokens = 0
let answer = chat.say(q, on_text: { text ->
if tokens == 0 { first = now() - t0 }
tokens += 1
dom.set_text("#a{turn}", text)
})
let secs = now() - t0 - first
log = log.replace("id=\"a{turn}\"><span class=\"dots\"></span>", "id=\"a{turn}\">{escape(answer)}")
if tokens > 1 && secs > 0.0 {
dom.set_text("#hud-speed", "{(tokens.to_float() / secs).round().to_int()} tokens/s")
}
dom.set_text("#hud-first", "{(first * 1000.0).round().to_int()} ms")
dom.remove_class("body", "busy")
busy = false
}
dom.on("#clear", "click") { _ ->
if busy { return }
chat.clear()
turn = 0
log = ""
dom.set_html("#log", "")
}
A language model in the page runs here
A small GPT (452 KB of weights, trained beforehand on Shakespeare by examples/gpt.zyth, a character at a time), built into a page with zyth build --target web. It continues your text in the style of what it read; it is far too small to answer questions.
@target(web)
use zyth.web.{dom}
use zyth.nn.Transformer
use zyth.data.text
// The model was trained on Shakespeare a character at a time (examples/gpt.zyth); these are
// the 65 characters of that text, which the tokenizer numbers in this order.
let tok = text.tokenizer("char")
tok.fit("\n !$&',-.3:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
let model = Transformer.load("tiny-gpt.zyth.model")?
dom.on("#go", "click") { _ ->
let prompt = dom.value("#prompt")
dom.set_text("#output", model.generate(tok.encode(prompt), max_tokens: 300) |> tok.decode)
}
The solar system on your GPU runs here
One Zyth program draws the Sun, the planets, Saturn's rings and the Milky Way with zyth.gfx on WebGPU, moves 24,000 asteroids as GPU tensors every frame and draws them from the same memory, then adds a glow pass. Drag, scroll, or fly to a planet.
The smallest drawing program, for comparison: 4,096 points computed as tensors and drawn where they are.
Python and npm libraries from Zyth recorded
NumPy and the standard library through Python, lodash and date-fns through npm (a JavaScript engine inside zyth; no Node needed).
// Python libraries from Zyth (spec Section 14.2). Needs a build with Python support:
// cargo build --release --features python
// zyth run examples/python_interop.zyth
use python.math
use python.numpy as np
use python.statistics.{mean, stdev}
print("math.sqrt(2) = {math.sqrt(2.0)}")
let a = np.arange(6).reshape(2, 3)
print("numpy says the sum is {a.sum()} and the shape is {a.shape}")
// NumPy arrays convert to tensors explicitly, and tensors become NumPy arrays.
let t = tensor.from(a).to(f32)
let w = tensor.randn(3, 2)
print("tensor result shape {(t @ w).shape}")
print("back in numpy: {np.asarray(t * 2.0).tolist()}")
print("statistics: mean {mean([1, 2, 3, 4])}, stdev {stdev([1.0, 2.0, 3.0, 4.0]):.3f}")$ zyth run python_interop.zyth
math.sqrt(2) = 1.4142135623730951
numpy says the sum is 15 and the shape is (2, 3)
tensor result shape [2, 2]
back in numpy: [[0.0, 2.0, 4.0], [6.0, 8.0, 10.0]]
statistics: mean 2.5, stdev 1.291// npm packages from Zyth: the JavaScript runs in an engine inside zyth (no Node needed).
use npm.lodash as _
use npm."date-fns".{format, addDays, parseISO}
print(_.chunk([1, 2, 3, 4, 5], 2))
print(_.kebabCase("Zyth Calls JavaScript"))
let day = addDays(parseISO("2026-11-30"), 3)
print(format(day, "yyyy-MM-dd"))$ zyth run app.zyth
[[1, 2], [3, 4], [5]]
zyth-calls-java-script
2026-12-03One file to ship recorded
zyth build makes one executable with the program and the runtime inside; the computer it runs on needs nothing else.
$ zyth build hello.zyth -o hello
built hello (10.3 MB, self-contained, with the static zyth-rt-static runtime (no npm, C libraries or GPU); run it with ./hello)
$ ./hello
Hello, Zyth!
Recorded on 2026-11-14 with zyth 0.1.0-dev.2. Every page here is opened by a browser test before the site is published (deploy/www/check.cjs).