Rendered from AUTHORING.md at commit af54ddad5. The package is imported here by its 0.2.0 name, typeshade.
The CPU oracle
After this page you can run a module on the CPU in double precision and compare its numbers against what a GPU produced.
The CPU oracle is a third backend over the same IR the WGSL and GLSL writers read. It evaluates the module in JavaScript, with no device and no browser, and every function in the module becomes a callable you pass numbers to and read numbers back from. It answers what the shader should compute, which is the reference a GPU run is held against when a pixel comes out wrong. It runs the same validation the two GPU writers run, so a module it rejects is a module they would reject too.
Compiling a module for the CPU
compileModule(m) returns a CpuModule: a fns record keyed by function name, plus a
setBinding method for the resources the module reads. Entry points and helpers are both in
fns, under the names they were declared with. Values crossing the boundary are plain
JavaScript. A scalar is a number or a boolean, a vector or a matrix is a flat number[],
and a struct is an object keyed by field name.
"use typeshade";
export function len(p: vec2): f32 { return sqrt(dot(p, p));}import { compile, compileModule } from 'typeshade'
const cpu = compileModule(compile(source).module) // source: the file above, as textcpu.fns.len([3, 4]) // → 5compileModule walks the IR node by node on every call. compileModuleJs(m) takes the same
arguments and returns the same shape, and it walks each function body once, emits JavaScript
source for it and builds that source with new Function. Reach for it when the same module
runs thousands of times, on a per-frame path or across a whole buffer of rows. A body it cannot
generate falls back to the interpreter for that one function, so a module can be part compiled
and part interpreted with no change at the call site. The one case a caller handles is a host
that forbids eval, where new Function itself throws and compileModule is the way through.
compile() returns an eval(name, args) of its own beside the module, for a quick call. And
with the Vite plugin, host code calls an exported helper directly, as
Calling a module’s helpers from host code shows.
Bindings and calls
A binding is a resource the pipeline supplies: a uniform block, a storage buffer, a texture, a
sampler. The oracle has no GPU memory behind those, so you supply each value with
setBinding(name, value) before the first call. The name is the one the declare const
carries. reflect(m).bindGroups lists every binding a host must fill, including the ones a
lowering injects. The oracle asks only for the ones a function it runs actually reads, so a
module with f64 arithmetic needs no value for the injected _fp64 guard texture that
fp64 describes. A binding a function reads and nothing set throws
typeshade/cpu: unbound <name>.
"use typeshade";
interface Params { scale: f32;}
declare const u: uniform<Params>;declare const data: storage<array<f32>>;
export function scaleAt(i: u32): f32 { return data[i] * u.scale;}const m = compile(source).module // source: the file above, as textconst cpu = compileModule(m)cpu.setBinding('u', { scale: 2 }) // a uniform block: an object keyed by field namecpu.setBinding('data', [1, 2, 3]) // a buffer: one flat arraycpu.fns.scaleAt(2) // → 6Arrays and structs are held by reference, so a read_write storage buffer is written in place:
bind an array, run the calls, then read that same array back for the results. An f64 value is
one JavaScript number on this side. The GPU carries it as a pair of f32 values, a high part
and a low part, and splitF64(x) returns that pair for the host to pack into the buffer, so
the two sides describe the same number in the shape each one needs.
The f64 and f32 precision modes
Both compile functions take a precision option, and it decides how f32 arithmetic is
evaluated. Under 'f64', the default, every operation runs in JavaScript’s double precision
with no rounding in between, so the result is the mathematically intended one to 53 significand
bits. Use it to ask whether the module picked the right operations in the right order. It is
blind by construction to an error that appears only once a value is squeezed into 32 bits.
Under 'f32', every f32-typed operation rounds to f32 afterwards, with an infinity on
overflow, over the same module the GPU backends are given. Use it to ask whether the target
computes this value, and a comparison against a GPU readback can then be an ulp-scale one
instead of a tolerance wide enough to hide a real disagreement.
"use typeshade";
export function acc(a: f32, b: f32): f32 { return a + b;}const m = compile(source).module // source: the file above, as text
compileModule(m).fns.acc(1, 2 ** -30) // → 1.0000000009313226compileModule(m, { precision: 'f32' }).fns.acc(1, 2 ** -30) // → 1The mode is separate from the emulated f64 type, which fp64
covers. It stays a full double here while the GPU runs it as a pair of f32 values carrying
about 48 significand bits. The WGSL, GLSL and CPU results for such a module agree within
that width.
A comparison then reads the buffer the GPU wrote and walks it against the same module on the CPU, one row at a time.
import { compileModuleJs } from 'typeshade'
// m: the module of the bindings sample above.const cpu = compileModuleJs(m, { precision: 'f32' })cpu.setBinding('u', { scale: 2 })cpu.setBinding('data', Array.from(rows)) // rows: the input the GPU run was given
// gpuOut: the Float32Array read back from that GPU run.for (let i = 0; i < gpuOut.length; i++) { const expected = cpu.fns.scaleAt(i) as number if (Math.abs(gpuOut[i] - expected) > 1e-6) { throw new Error(`row ${i}: GPU ${gpuOut[i]}, CPU ${expected}`) }}Calls the CPU tier does not run yet
Some calls throw when a call reaches them. They are not supported yet on the CPU tier.
They are the texture reads textureSample, textureSampleLevel, textureLoad and their array,
bias, grad, gather and depth-comparison forms, textureStore, the queries
textureDimensions and textureNumLayers, and the derivatives dpdx, dpdy and fwidth
with their coarse and fine forms. The full set is exported as ORACLE_GPU_STUB_NAMES. A
module the IR builder assembled can also hold a raw statement, target text the oracle never
reads (docs/ir-builder.md).
A texture of the CPU tier’s memory is the exception. device.texture() makes one on a device with
no WebGPU device (change 0077). Bound with setBinding, it is read by textureLoad and
textureDimensions and written by textureStore, in compileModule and in compileModuleJs
alike, with or without gpuStubs. A sampled read (textureSample and its forms) is not supported yet on the CPU tier
(Rule 11.7). It keeps the stub contract.
Compiling with { gpuStubs: true } turns those intrinsics into placeholder values: opaque
black for a texture read, zero for a derivative, a 1 by 1 size for textureDimensions and
one layer for textureNumLayers. The throw names the intrinsic and that option. Pass it
when a stand-in value is acceptable for the question being asked, such as checking the
geometry a fragment function computes around a sample it does not depend on. The binding
still has to be set, because the module reads the texture and sampler variables before the
call is stubbed.
"use typeshade";
declare const tex: texture_2d<f32>;declare const smp: sampler;
@fragmentexport function shade(uv: location<0, vec2>): vec4 { return textureSample(tex, smp, uv);}const cpu = compileModule(compile(source).module, { gpuStubs: true })
cpu.setBinding('tex', 0) // the value is never read under a stubcpu.setBinding('smp', 0)cpu.fns.shade([0.5, 0.5]) // → [0, 0, 0, 1]Derivatives with grad
grad(m, fn, param) differentiates a function of the module with respect to one of its
parameters and returns { module, name }: the module with a new function added, which takes
the same arguments as fn and returns d fn / d param at them, with the type of fn’s
result. The new function is ordinary IR, so the oracle runs it, and the WGSL and GLSL writers
emit it for an entry that calls it.
"use typeshade";
export function wave(x: f32, k: f32): f32 { return sin(k * x) * k;}import { compile, compileModule, grad } from 'typeshade'
const m = compile(source).module // source: the file above, as textconst d = grad(m, 'wave', 'k')
compileModule(d.module).fns[d.name](0.5, 2) // → cos(1) * 0.5 * 2 + sin(1) = 1.3817…It works in forward mode: every f32, float vector and float matrix gets a derivative beside
its value, and if, switch and for carry both through their bodies. A call to another
function of the module goes through a helper, g_jvp, generated once per callee. The
component-wise builtins have their textbook rules; floor, ceil, round, trunc, sign
and step have a zero derivative, which is the derivative everywhere but at their jumps. For a
vector parameter, pass { direction: [...] } and the result is the derivative along it.
A construct with no derivative rule is refused with SD0118 naming it, a texture sample, a
derivative builtin or a struct the parameter would flow into among them, and only when the
parameter reaches it; the pass never returns a zero derivative it did not derive. The generated
function is checked against a central finite difference on the oracle, which is how to check
one of your own.
grad(m, fn, wrt, { mode: 'reverse' }) differentiates with respect to every name of wrt at
once (change 0056). The new function, <fn>_vjp by default, takes the same arguments followed
by a seed dy of the result’s type, and returns a struct with one field for each name: the
vector-Jacobian product dy · d fn / d name. One call gives the whole gradient, so it is the
mode to use when the parameters are many and the result is small, as in a loss. On the CPU the
struct is an object, and d.adjoints names its field for each parameter.
const r = grad(m, 'wave', ['x', 'k'], { mode: 'reverse' })compileModule(r.module).fns[r.name](0.5, 2, 1) // → { x: …, k: … }Reverse mode runs the function’s body forward, then sweeps it backward. It keeps what the backward sweep reads in the function’s own variables, so it allocates no buffer. It differentiates the same arithmetic, builtins, branches and calls as forward mode, and a jump still has a zero derivative.
A loop is swept backward under a checkpoint schedule in function memory. Its trip count comes
from the header of a counted for, or from a count sweep that runs a while or a loop with a
break once more. The loop’s state is saved every ceil(N / C) iterations into C slots
(opts.checkpoints, 32 by default), and each segment is run again from its slot. Up to C²
iterations the body runs about three times forward and once backward. Past C² the time grows
as N² / C. d.tapeBytes reports the function memory the schedule takes per call. A call or a
discard whose effect would repeat when an iteration runs again is refused with SD0118, and so
is a write to a module variable or a binding.
opts.custom gives a function an author-written adjoint: { custom: { g: 'g_adjoint' } } makes
each call to g take its adjoints from g_adjoint(g's arguments, dy), which returns a struct
with a field for each float parameter of g. Use it for a recurrence you can invert, such as
the transmittance of front-to-back compositing.
gradCheck(m, fn, { wrt, at, mode }) compares a derivative of either mode with a central
difference on the f64 oracle at the argument lists at, and returns { ok, checked, worst }.
worst names the parameter, the point and the components where the results differ.
Calling a module’s helpers from host code
A "use typeshade" module is also a module your application can import. With the Vite plugin in
place, an ordinary .ts file imports a .shade.ts and calls the helper functions it exports.
Each call runs that function’s code on the CPU, not on the GPU, at f32 precision, the way a
GPU would round it. It is how host code shares a shader’s math, for a height query, a picking
test or a unit test. A compute entry imported the same way runs on the GPU instead: await entry(bindings, workgroups) dispatches it on WebGPU and reads what it wrote back into your arrays,
and entry(bindings, workgroups, { constants: { WIDTH: 32 } }) selects declared overrides
with the same validation as program.compute. A plan keeps its existing submission and reports
the selected workgroup shape. CPU calls use generated closures with the same constants;
On the WebGL2 tier, the pass program uses the declared default workgroup shape and array lengths. Selecting another shape or length is not supported yet on the WebGL2 tier (Rule 11.8, Rule 8.24). An imported fragment
entry called as entry(canvas, bindings) draws a full-screen fragment entry into a canvas
(docs/use-typeshade-surface.md §67). If it reaches no host-supplied binding, including through
its helpers, call entry(canvas); explicit undefined or {} has the same meaning. Unused
declarations and runtime-owned resources do not require a bindings argument. Compute calls
keep their leading bindings object:
// app.ts, ordinary TypeScript: terrain.shade.ts exports `height(p: vec2, k: vec4): f32`import { height } from './terrain.shade.ts'
const h = height([0.5, 0.5], [1, 0.5, 2, 0.25]) // a numberFor a complete compute example, read
host-compute.shade.ts and its
host.ts. run() keeps the authored defaults.
The extra runSpecialized() selects GAIN in a direct call, then selects WIDTH in device.fuse().
It sizes the dispatch with Math.ceil(n / width) and checks bounds in the shader, so 259
elements include a partly occupied last workgroup. On WebGPU its entry group reports
workgroupShapes: [[32, 1, 1]], one dispatch and one submission. A later output.read() is a
separate readback. WebGL2 keeps the default width of 64 while still selecting ordinary constants.
The CPU tier uses the selected shape and constants. A barrier is not supported yet on the CPU tier (Rule 8.24).
Repeated normalized constants reuse the pipeline on the same device, entry and fp64 flavor. Choose among a small set of measured sizes rather than creating a new pipeline for every input length. The runtime checks names, scalar ranges, workgroup dimensions and shared-memory limits; selection does not choose an optimal size or change the caller’s workgroup count. Values are captured when the entry is called, including while a plan is recorded.
The values are plain: a scalar is a number or a boolean, a vector a tuple ([x, y]), a
matrix a flat column-major array, an array<T, N> an array and a struct an object. The call
checks each argument and throws a TypeError naming the parameter when one does not fit, and
what it returns is a fresh value. It is synchronous.
What a host can call is an exported function that is not an entry point, not generic, takes no
function, and reaches no binding and no GPU-only builtin. Everything else the module exports
appears to the host as never, with the reason, so calling it is a type error where you wrote
the call. With the published or built package, run npx tshc init in an existing Vite project
to configure the plugin, host views and synchronization scripts (change 0085).
An installed GitHub source archive requires bun node_modules/typeshade/src/cli/bin.ts init.
It has no generated typeshade/shade declaration, and its CLI and Vite plugin cannot run under Node.
Initialization does not remove those limits; see installation.
The command preserves unrelated settings and JSONC comments and refuses conflicts before writing.
Repeated initialization changes no file. Manual setup and tshc sync remain supported.
Shader checks use the shared tshc check diagnostics; ordinary tsc reports TS1206 on each stage attribute and on vector arithmetic, which TypeScript has no operator overloading for, so tshc check and the editor are the checks of a shader file.
The surface reference describes setup and host values: docs/use-typeshade-surface.md §64.
A loop over an array
An exported function that takes an array with no size, array<T>, is a kernel function: host
code awaits it, and its array is the caller’s, written in place. Each for at the top of its body
runs on the GPU, one invocation per iteration, when the compiler proves that no iteration touches
what another one does, and on the CPU otherwise, with a TS8070 warning that names the line and
the remedy (docs/use-typeshade-surface.md §65).
The dispatch is that top-level loop’s, so a loop nested in it runs whole inside each invocation:
a grid written as two nested loops is one invocation per row. When each cell should be its own
invocation, write the grid as one flat loop, for (let i: u32 = 0; i < w * h; i++), and take
x = i % w and y = i / w from the index.
The compiler chooses the workgroup size of a kernel function’s loops. A kernel function may state it with the optional attribute @workgroup_size([128]), @workgroup_size([128]) export function k(xs: array<f32>) { … }, one whole number in the array, as @compute([128]) sets an entry’s (docs/use-typeshade-surface.md §3 and §65). A loop that reduces always runs in workgroups of 256, so a reduction in such a function is refused with TS8077: move the reduction into a function of its own.
A kernel function may also take a texture (docs/use-typeshade-surface.md §65): a
texture_2d<f32> it reads with textureLoad, and a 2D storage texture, texture_storage_2d<F, A>,
which makes the function a kernel function and which its loop stores into at
vec2u(i % w, i / w). Make the storage texture with device.texture({ size, format, storage: true })
and call the function normally: it selects that texture’s owner (change 0085). Use device.fuse()
for an ordered scope. A texture call runs on WebGPU, and on the CPU
tier where there is none: a device of the CPU tier holds its textures in memory, and an
ImageData is copied there. WebGL2 does not run it yet.
On a WebGPU device that has the subgroups feature, an integer reduction (u32 or i32 with
any operator, f32 with min or max) and a scatter into an integer array whose write a lane
makes at most once run as a second text of the function, in which each subgroup folds first with
the subgroup functions (change 0119, Rule 11.23). Nothing in the source names a subgroup, and the
bits are the tree’s: the runtime runs a known-answer probe when the device opens and dispatches
that text only where the probe passed. device.info.subgroups shows what the probe saw,
device.statistics.variants which text each function’s last call ran, and
createDevice({ subgroups: 'off' }) keeps every call on the tree. An f32 sum keeps the tree
in both texts, since its bits depend on the order (Rule 7.2).
A chain of calls in one dispatch
A host that calls several kernel functions over the same data pays a dispatch, and a submission,
for each call. fuse from typeshade/fuse records the calls its body makes and runs them
together: in one submission, and, when each call reads what the one before it wrote at the same
index, as one dispatch. device.fuse() needs no registration import; the named fuse remains available.
The Vite plugin and hostFace() write eligible kernels’ fusion facts by default.
fuse: false omits them to reduce generated size; fuse: true keeps the default.
An ordinary call can still use private input projection with those facts present. Calls on a Buffer and fused calls retain the full layout.
These three kernel functions are one dispatch:
"use typeshade";
export function add(out: array<f32>, a: array<f32>, b: array<f32>): void { for (let i: u32 = 0; i < out.length; i++) { out[i] = a[i] + b[i]; }}
export function mul(out: array<f32>, a: array<f32>, b: array<f32>): void { for (let i: u32 = 0; i < out.length; i++) { out[i] = a[i] * b[i]; }}
export function relu(out: array<f32>, x: array<f32>): void { for (let i: u32 = 0; i < out.length; i++) { out[i] = max(x[i], 0.); }}import { array } from 'typeshade/runtime'import { fuse } from 'typeshade/fuse'import { add, mul, relu } from './ops.shade.ts'
const out = array(n, 'f32') // zeros, with no upload; a, b and c are Buffers tooconst report = await fuse((scope) => { const t = scope.scratch(n) const u = scope.scratch(n) add(t, a, b) mul(u, t, c) relu(out, u)})report.dispatches // 1const y = await out.read()A device owner’s device.fuse() uses the same recorder without a registration import (change 0085).
It runs the body synchronously and loads its local executor after reserving the queue position.
Deploy all emitted chunks. The named fuse import remains supported for default-owner arrays.
Three habits make a chain fuse. Write each function with one loop, and index every array with the
loop’s counter alone, out[i] = a[i] + b[i]: a call joins the one before it when it reads what
that call wrote at the same index. Keep an intermediate in a scratch array, scope.scratch(n),
and not in a Buffer the host reads: a fused group holds a scratch array in a variable of its
own, so no buffer is made for t and u above, and read() of one is an error. End a chain with
a reduction when you want its sum: total(u) as the last call of the scope takes the calls before
it into its own loop, and nothing joins a group after a reduction.
An entry call (a compute entry) in the body is recorded too. It runs as a dispatch of its own, in the
order the body made it: no kernel call joins it, and it joins none. Its storage arrays with no
size are array(...) values, and a host array in its place is a TypeError.
A call stands apart from the one before it, and runs as a dispatch of its own, when it reads a
neighbour (t[i - 1], t[i ^ 1]), writes at another index (out[2 * i]), writes what the call
before it reads, runs over another count, or has a second loop, a continue or a scatter. It
stands apart too when the group would bind more storage buffers than the device allows, when the
module has no fusion facts (fuse: false, or older generated code), and on WebGL2 and the CPU tier, which run the calls apart. The
arrays and the results are the same either way: fusing changes the dispatches and nothing else.
The report says which calls fused and why the others did not, in your names. report.groups
lists the groups in order, each with its calls, whether it is fused, and, for a group that
stands apart from the one before it, a why:
mul and blur run as two dispatches because blur reads `t[i - 1]` (line 9)report.dispatches and report.submissions count what the plan gave the device. The surface
reference has every fact the plan checks, each wording of the report and of the errors, the
scratch arrays and the tiers: docs/use-typeshade-surface.md §71.
A shader module that imports another
A "use typeshade" file imports what another one exports, as any TypeScript module does:
import { fbm } from './noise.shade.ts'. The file you compile and the shader files it imports,
directly or through another, are one program, and the program becomes one module. An ordinary
import brings the declarations your file reaches: helpers, structs, constants and bindings.
Unrelated entry points stay out. Each file keeps its own scope, so two files can each have
a private hash; the module emits the second one under a name of its own.
A file kept as a pure alias contains only the shader directive and one value export-star.
Here k.shade.ts is the alias; the first file supplies its target:
"use typeshade";declare const unused: uniform<f32>;declare const gain: uniform<f32>;function privateHelper(x: f32): f32 { return x * 2.; }export function scale(x: f32): f32 { return x * gain; }
// k.shade.ts"use typeshade";export * from "./new/k.shade.ts";Compiling that alias preserves its terminal target’s declarations and binding slots, including unused bindings and private helpers. Further pure aliases form a chain. This exception starts only at the requested root; ordinary imports remain selective. Extra statements, named or type-only re-exports, multiple stars and import attributes do not form a pure alias. Private declarations stay private, and target errors retain their original file and span. The alias keeps its requested path and default fusion identity, so generated artifacts need not be byte-identical to the target’s. See surface §68 for the complete contract (change 0126).
compile() reads what a source imports through a readDocument you pass it, which returns a
file’s text by its path, or undefined when there is none. The Vite plugin, tshc check,
tshc sync and the editor read the files themselves.
import { existsSync, readFileSync } from 'node:fs'import { compile } from 'typeshade'
const read = (path: string) => (existsSync(path) ? readFileSync(path, 'utf8') : undefined)const { wgsl, diagnostics } = compile(read('src/clouds.shade.ts')!, { fileName: 'src/clouds.shade.ts', readDocument: read,})A shader library installs from npm like any other package, and a shader file imports it by the
package’s name: import { fbm } from 'shade-noise'. The package is found in node_modules from
the importing file’s directory up, as Node finds one, and the file read is the one its
package.json publishes under the typeshade condition of exports, beside the JavaScript it
publishes for host code:
{ "name": "shade-noise", "exports": { ".": { "typeshade": "./src/index.shade.ts", "default": "./dist/index.js" }, "./*": { "typeshade": "./src/*.shade.ts" } }}'shade-noise' reads the package’s src/index.shade.ts, and 'shade-noise/hash' the
hash.shade.ts beside it. A package with no exports is imported by the path of its file,
'shade-noise/noise.shade.ts'. readDocument is asked for each package.json too, so the read
above follows a package with no change. A program holds one copy of a package version however
many dependencies reach it, and a helper of a package that the module renames is named for the
package and its file, shade_noise_noise_hash.
A mistake in an imported file is reported at that file, line and column. An import the compiler
cannot follow is a TS8072 on the import: a path that names no file, a file that does not begin
with the directive, a package no node_modules holds, a subpath its exports does not name, a
name the file does not export, a default import. The surface reference has every form an import
takes, the names the module emits and each refusal: docs/use-typeshade-surface.md §68.
An object a function writes, and a value it gives back
An object is a struct, an instance of a class or an array, and it has the identity a JavaScript
object has: a function that writes a field or an element of its parameter changes the object the
caller passed, and the author writes no mark on either side. A number, a bool, a vector and a
matrix are values, as a JavaScript primitive is, so a function that changes one gives it back,
and [a, b] = f(a, b) assigns more than one. @inout and @out are removed (TS8073), and
tshc migrate deletes them from an object parameter.
"use typeshade";
class Ray { origin: vec3; dir: vec3;}
function swap(a: f32, b: f32): [f32, f32] { return [b, a];}
function add(a: f32, b: f32): f32 { return a + b;}
function advance(r: Ray, t: f32): void { r.origin = r.origin + r.dir * t;}
export function demo(): f32 { let x: f32 = 1.; let y: f32 = 2.; [x, y] = swap(x, y); // x is 2. and y is 1. let s: f32; s = add(x, y); // s is 3. let r = new Ray(); r.dir = vec3(1., 0., 0.); advance(r, 3.); // r.origin.x is 3. return x + s + r.origin.x;}WGSL receives a pointer for advance, advance(&r, 3.0) with (*r).origin = … in the body, and
GLSL ES 3.00 an inout parameter; the CPU oracle copies the object in and stores it back. The
argument is a let, a const that built its object, a module variable, an element of a
read_write storage binding, or a field or an element of one. One call may not take two names
for one object that the function writes, swapFields(r, r), which is TS8074. A read before a
variable is assigned is TS8075. A function of the file or of a namespace takes the caller’s
object; a method, an entry and a local function take values for now, and a local function inside
such a function may still read and write the parameter, as it reads and writes any variable around
it. The surface reference has every rule and refusal: docs/use-typeshade-surface.md §70.