Repository navigation
feat(examples): experimental ONNX Runtime Web embeddings example - #877
Conversation
Six tiny ONNX models, generated by a committed script, that run per pixel on a [1, 64, h, w] AlphaEarth embedding tile: cosine similarity to a query, nearest of k centroids, and a logistic regression. Weights are model inputs, so a new query or new centroids need no new model. Each comes in an int8 variant that dequantizes in the graph and a float32 variant that takes dequantized values. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Explore the AlphaEarth Foundations GeoZarr embeddings with ONNX Runtime Web on WebGPU: click a pixel for a similarity map, cluster the loaded tiles with k-means, or label a few points and draw a logistic regression's probability map. The RGB composite of the aef-mosaic example stays underneath. Each tile keeps its int8 embeddings on the CPU. The analysis keeps its own registry of resident tiles, runs the current model on every one, and writes the results into each tile's existing r32float texture, so a new query updates the map without refetching tiles. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…U Cast Time the first session from the mode's own `prepare` call rather than a similarity session created on the side, and log only errors for the int8 models, whose `Cast` on the CPU provider otherwise prints a warning through `console.error` on every session. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A pass could queue a run for a tile that deck.gl unloads before the run starts, and the run would read the tile's destroyed GPU buffer. Passes now skip tiles unloaded since they started, and tiles are freed once the runs already queued are done. Also shorten the model input labels so they fit the panel. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… example The README follows the other experimental examples. NOTES.md records the design, the alternatives rejected, measurements (per-tile and per-query times, memory, load time, bundle size), which nodes ran on the GPU, a friction log, and what the example says about ONNX Runtime Web as an engine. The screenshots show each mode drawing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Switching the model input freed every tile's GPU buffer once the old runner went idle, which could free buffers the new runner had just made. Only free them when the old runner was the GPU path. Also make releasing a runner tolerate a session that failed to load, and cap the k-means sample at the requested size. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A GPU buffer lives on its runner's ONNX Runtime device, so a runner now replaces a buffer another runner made, and a runner that is switched away frees only its own buffers. Tiles whose load was aborted skip the model run, and a tile whose content deck.gl replaces under the same key frees the old one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
There was a problem hiding this comment.
let's put these in the PR description rather than including them all in the git history and repo
There was a problem hiding this comment.
Note
This reply was written by Claude (Claude Code), not by @kylebarron.
Removed from the repository in 83778f4, and all seven are now in the PR description, five of them under a "More screenshots" fold.
One caveat: the description's images are served from the earlier commit on this branch that contains them. That commit stays reachable through the pull request, and a squash merge keeps the files out of main's history, but they are still in this branch's own history. Getting them out of that too means uploading them as GitHub attachments, which only works by dragging them into the description in the browser. If you do that, I can then drop the old commits.
🤖 Written by Claude Code
…nxscript Each model is now a decorated Python function with ordinary operators, where the script used to assemble graph nodes by hand. The script declares its dependencies inline, so `uv run models/make_models.py public/models` is the whole command, and it always checks the models against NumPy. The regenerated models have the same inputs and outputs. Their float32 variants still run entirely on the WebGPU provider. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…X example The screenshots live in the pull request description instead of the repository. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ample The example cleared its tile registry by hand when the year changed, on the belief that replacing the inner TileLayer drops tiles without unloading them. RasterTileset2D.finalize already calls onTileUnload for every cached tile, so the manual cleanup freed each tile a second time. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Review feedback on the example's interface: - Similarity, clusters and the classifier now draw over the plain basemap. The RGB composite is its own mode and no longer sits under the other modes, and the Backdrop control is gone. Pixels below the threshold are not drawn. - A mode with nothing to show draws nothing, so clearing the classifier removes its map. - The Model input help lists each option with what it costs, and the selected option's cost shows under the control. Mode, the thresholds, the color range and the cluster count have help text too. - The zoom notice sits in the middle of the page. - Eight more preset locations. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Removed again in the next commit, so they never reach main. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
…nded tile count More review feedback on the ONNX example: - Similarity starts with the pixel in the middle of the map as its query, and picks a new one after a location change, so the mode never opens on an empty map. - A "Show embeddings underneath" checkbox draws the dimmed RGB composite under the other modes' results, as a cue for where data has loaded. It is on by default. - Changing location jumps instead of flying, and the minimum zoom is 12.5. deck.gl trims its cache only when a tile is created, so a flight through wide views left hundreds of tiles loaded. - The Salar de Atacama preset had no data at its center; Almería replaces it. Every preset opens at zoom 13. - The int8 model input's description says which step runs on the CPU. Co-Authored-By: Claude Fable 5.2 <[email protected]>
weiji14
left a comment
There was a problem hiding this comment.
Mentioned below that I'm not a typescript dev, nor have I ran this locally yet. So just some very light suggestions from a very surficial look.
| * How a tile's embeddings reach the model. | ||
| * | ||
| * - `int8`: the raw int8 array, as a CPU tensor. The model dequantizes. Its | ||
| * `Cast` from int8 has no WebGPU kernel, so it runs on the CPU provider. | ||
| * - `float32`: dequantized in JavaScript into one reused buffer, as a CPU | ||
| * tensor. Every node runs on WebGPU; the 16 MB tensor is uploaded per run. | ||
| * - `gpu`: dequantized once per tile into a buffer on ONNX Runtime's WebGPU | ||
| * device, which stays there until the tile unloads. 16 MB of GPU memory per | ||
| * 256 × 256 tile. |
There was a problem hiding this comment.
I can't read typescript so will just comment on this comment 😄 Is the dequantization step to float32 strictly necessary? Can the similarity search model (really, just a cosine similarity formula) not operate on int8/byte arrays to produce float32 values directly?
There was a problem hiding this comment.
Note
This reply was written by Claude (Claude Code), not by @kylebarron.
There are two parts to this.
Is the conversion needed at all? For AlphaEarth, yes, because the stored bytes are not a linear encoding. A stored int8 v stands for (v / 127.5)² · sign(v). A dot product of the raw bytes is therefore not proportional to the dot product of the embeddings, and it ranks pixels differently. For a linearly quantized embedding the conversion would only be a scale factor and could be skipped.
Does it have to happen on the CPU? No, and this question led to a fix in df8f4efd. The first version of the int8 models began with Cast, which ONNX Runtime Web runs on the CPU for int8. They now begin with DequantizeLinear (scale 1 / 127.5) followed by x * |x|, and all of it runs on WebGPU. The app sends the raw 4 MB int8 tile, and every session is created with the CPU fallback disabled, so a node that could not run on the GPU would be an error.
| Per 256 × 256 × 64 tile | Time |
|---|---|
int8 in, Cast on the CPU (before) |
5.7 ms |
int8 in, DequantizeLinear on WebGPU (now) |
3.3 ms |
| float32 in, dequantized in JavaScript first | 7.2 ms |
The other two "Model input" options, float32 from JavaScript and float32 kept on the GPU, are still in the panel for comparison.
🤖 Written by Claude Code
There was a problem hiding this comment.
Ok, it makes sense to me why the conversion is needed, because the source int8 data isn't linearly the same as the actual data.
I feel like if int8 with dequantization on the GPU is strictly better (faster and less memory) than a float32 approach, then we shouldn't even offer the options for float32
There was a problem hiding this comment.
Note
This reply was written by Claude (Claude Code), not by @kylebarron.
Removed the "float32, converted in JavaScript" option in c597ee44. int8 is strictly better than it: 3.3 ms against 7.2 ms per tile, and it saves no memory.
I kept "float32, kept on the GPU", because int8 is not strictly better than that one. It is a trade of memory for speed:
| Raw int8 (default) | float32 kept on the GPU | |
|---|---|---|
| One run on one tile, nothing else on the page | 3.3 ms | 1.2 ms |
| One query change over 15 tiles, in the app | 62 to 120 ms | 34 to 96 ms |
| Extra GPU memory per tile | none | 16 MiB |
It is faster because a run uploads nothing. Keeping the int8 bytes on the GPU instead would cost 4 MiB per tile, but Tensor.fromGpuBuffer in ONNX Runtime Web does not accept int8.
If you would prefer the simpler example, I can remove this option too. That would also remove the "Model input" control, the three float32 models and the per-tile GPU buffer code.
🤖 Written by Claude Code
There was a problem hiding this comment.
Note
This reply was written by Claude (Claude Code), not by @kylebarron.
Removed the "float32, kept on the GPU" option as well, in a3c633da. At 16 MiB of GPU memory per tile it held 432 MB for 27 loaded tiles, which is too much for a demo.
int8 is now the only way a tile reaches a model, so this commit also removes:
- the "Model input" control,
- the three float32 models, leaving
similarity.onnx,clusters.onnxandclassifier.onnx, - the per-tile GPU buffers and the code that kept them alive until queued runs finished.
NOTES.md keeps the measurements of both removed options.
🤖 Written by Claude Code
There was a problem hiding this comment.
Yep, I think we want to lean on the lower memory aspect at the expense of a bit more compute (the dequantization-on-the-fly step, which is luckily fast on WebGPU).
| import onnx.inliner | ||
| import onnxruntime as ort | ||
| from onnxscript import FLOAT, INT8, script | ||
| from onnxscript import opset20 as op |
There was a problem hiding this comment.
Highest opset version currently is opset28 according to https://microsoft.github.io/onnxscript/api/opsets.html#onnxscript.onnx_opset.opset28, but I think we can go up to opset27 for compatibility with ONNX web runtime 1.31. Higher opsets might allow for better lower precision math actually (ask your friend Claude).
| from onnxscript import opset20 as op | |
| from onnxscript import opset27 as op |
There was a problem hiding this comment.
Note
This reply was written by Claude (Claude Code), not by @kylebarron.
Updated in df8f4efd, to opset 23 and not 27. This is what I found with onnxruntime 1.31.1, onnxruntime-web 1.31.1 and onnxscript 0.7.2:
- Opsets 27 and 28 do not load. The script checks every model against NumPy with the Python
onnxruntime, and 1.31.1 rejects opset 27 and 28 at session creation. 26 is the highest it accepts. - Above opset 23, the int8 conversion leaves the GPU. In ONNX Runtime Web,
DequantizeLinearfrom int8 runs on WebGPU in a model at opset 20, 21 or 23, and on the CPU in the same model at opset 24, 25 or 26.Castfrom int8 runs on the CPU at every opset I tried.
| Opset | DequantizeLinear from int8 runs on |
Similarity, per 256 × 256 × 64 tile |
|---|---|---|
| 20 | WebGPU | 3.5 ms |
| 21 | WebGPU | 3.6 ms |
| 23 | WebGPU | 3.4 ms |
| 24 | CPU | 9.6 ms |
| 25 | CPU | 8.8 ms |
| 26 | CPU | 9.1 ms |
So 23 is the highest opset at which the int8 models stay entirely on the GPU, and there is a comment saying so beside the import. Where a node runs depends on which kernels the WebGPU provider registers for that opset, so a newer opset did not buy better integer support here. I have not tried float16 inputs, which would halve the memory of the float32-on-GPU path.
🤖 Written by Claude Code
There was a problem hiding this comment.
This is kinda weird though, why would a new opset change an operation from GPU to CPU? What is an "opset"? Is that like a version that increments for "better" code?
There was a problem hiding this comment.
Note
This reply was written by Claude (Claude Code), not by @kylebarron.
An opset is the version of the ONNX operator catalogue that a model is written against. It is a spec version, not a quality level. A higher number does not mean faster or better code.
The move to the CPU comes from how the runtime matches operators to implementations. I checked this in the ONNX Runtime 1.31.1 source:
- Each operator has its own version history. When the spec changes an operator's definition, that operator gets a new version at that opset.
DequantizeLinearhas versions 10, 13, 19, 21, 23, 24 and 25. Version 24 only added a new type for the scale input (float8e8m0), and version 25 added 2-bit integer inputs. Nothing changed for int8. - Each backend implements each operator version separately. ONNX Runtime will not run a newer version of an operator on an implementation written for an older one, because the definition may have changed. An implementation registered as "23 and later" matches version 23 only.
- The WebGPU backend registers
DequantizeLinearfor versions 10 to 23. The CPU backend has every version. In a model at opset 24 the node is version 24, the WebGPU backend has nothing registered for it, and the node runs on the CPU backend.
So the WebGPU backend is behind the spec for this one operator, and main is the same today. The other operators in these models stayed on WebGPU at every opset I tried, 20 to 26.
In practice, choosing an opset means choosing the newest catalogue that the backend you care about fully implements for the operators you use. Here that is 23.
🤖 Written by Claude Code
There was a problem hiding this comment.
This is kinda weird though, why would a new opset change an operation from GPU to CPU?
...
- The WebGPU backend registers
DequantizeLinearfor versions 10 to 23.
Yeah so the WebGPU backend is a little behind. Let's keep things at opset 23 for now then.
| samples: Float32Array, | ||
| labels: Uint8Array, | ||
| dims: number, | ||
| { l2 = 1e-3, iterations = 2000, learningRate = 2 } = {}, |
There was a problem hiding this comment.
Might be useful to surface these hyperparameters. A learningRate=2 seems high (usually we go for fractions like 0.1, 0.001), but maybe this works 🤷
There was a problem hiding this comment.
Note
This reply was written by Claude (Claude Code), not by @kylebarron.
Surfaced in df8f4efd. Classifier mode now has three selects, each with a "?" tooltip: learning rate (0.01 to 2), steps (100 to 10,000) and L2 penalty (0 to 0.1). Changing one refits the classifier and redraws the tiles.
On the learning rate of 2: it is high by deep-learning habits, but it is the standard step for this particular problem.
- The loss is a class-weighted mean over the labeled points, not a sum, and AlphaEarth embeddings are unit vectors. The gradient's Lipschitz constant
Lis then at most0.25 · (‖x‖² + 1) = 0.5, where the+ 1is the bias term. - Gradient descent on a convex loss is stable for steps below
2 / L = 4, and1 / L = 2is the textbook choice. - It is full-batch, so there is no minibatch noise that a small rate would have to damp.
Smaller rates work but need many more steps. On 12 synthetic unit vectors, with no penalty, the loss after 2,000 steps was:
| Learning rate | Loss after 2,000 steps |
|---|---|
| 0.01 | 0.122 |
| 0.1 | 0.012 |
| 2 | 0.0006 |
With the select at 0.01 the map shows it: every probability stays close to 0.5.
🤖 Written by Claude Code
There was a problem hiding this comment.
@weiji14 I don't particularly understand this, so happy to take your feedback here
There was a problem hiding this comment.
Right, so a higher learning rate is ok since it's doing full-batch gradient descent rather than mini-batch gradient descent (which is typically noisy). Let's just keep this as is then since it's only a 'demo'.
…ht before width Review feedback on the ONNX embeddings example: - The int8 models start with `DequantizeLinear` instead of `Cast`. ONNX Runtime Web runs `Cast` from int8 on the CPU, and `DequantizeLinear` on WebGPU, so every session now disables the CPU fallback. A 256 x 256 tile takes 3.3 ms instead of 5.7. - The models move from opset 20 to 23, the highest at which `DequantizeLinear` stays on WebGPU. - The classifier's learning rate, number of steps and L2 penalty are controls in the panel. - Tile dimensions are ordered height before width, and rows before columns. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Now that the int8 models dequantize on the GPU, sending float32 from JavaScript is slower than sending int8 and saves no memory. The "Model input" control keeps int8 and float32 kept on the GPU, which is faster per run but holds 16 MiB of GPU memory per tile. Co-Authored-By: Claude Fable 5.2 <[email protected]>
The float32 copy of each tile kept on ONNX Runtime's device made a run about three times faster, but held 16 MiB of GPU memory per tile, 432 MiB for 27 tiles. That is too much for a demo, so the option goes, and with it the "Model input" control, the float32 models and the per-tile GPU buffers. The three remaining models lose their `_int8` suffix. Co-Authored-By: Claude Fable 5.2 <[email protected]>
There was a problem hiding this comment.
what does it means for the k-means (this is the clustering, right?) to be computed in JS? Which parts happen in JS vs the GPU?
There was a problem hiding this comment.
Note
This reply was written by Claude (Claude Code), not by @kylebarron.
Yes, k-means is the clustering. It has two steps, and they run in different places.
| Step | Where | Input | Cost at the default view |
|---|---|---|---|
Fit: find the k centroids |
JavaScript, on the CPU main thread | a sample of about 1,000 pixels per loaded tile, 15,360 for 15 tiles | about 220 ms |
| Assign: give every pixel its nearest centroid | the clusters ONNX model, on the GPU |
every pixel of every loaded tile, about 983,000 for 15 tiles | about 6 ms per tile |
The fit is this file. It loops at most 25 times over the sample and returns k vectors of 64 numbers. Those centroids are then an input of the model, like the query pixel in Similarity mode, so a new fit needs no new model.
The fit runs when you enter Clusters mode, change k, or press "Fit on loaded tiles". It does not run when you pan: tiles that load later are assigned to the existing centroids.
The classifier is split the same way. The logistic regression is fitted in JavaScript on the points you click, and the classifier model applies it to every pixel on the GPU.
I added two lines to this function's docstring saying so, in a6aea0eb.
🤖 Written by Claude Code
Without WebGPU the model modes showed nothing and gave no reason. The example now checks for a WebGPU adapter at startup. If there is none, a modal dialog explains that the models need WebGPU and offers the RGB mode, which draws without a model. Models are only loaded and run once WebGPU is confirmed. Also say "C order" where the tile layout is described, and note in the k-means docstring that it runs on the CPU and only finds the centroids. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Classifier mode draws nothing until it has a positive and a negative example, and only a small line in the panel said so. A notice at the bottom of the map now names the example that is still missing. Clicks pass through it to the map. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Similarity and Classifier modes pick a colormap by name only. The shared `ColormapPreview` strip, as in the other examples, now shows its colors under the select. Co-Authored-By: Claude Fable 5.2 <[email protected]>
> [!NOTE] > This PR was written by Claude (Claude Code) on behalf of @kylebarron, not by @kylebarron. Adds the experimental ONNX embeddings example (#877) to the docs Examples page, as the last card under "Experimental Examples". The example is already built and deployed by the docs workflow, so this only adds the card. Like the Sentinel-2 card, it cycles through three screenshots, one per mode, all over San Francisco (the example's default location): - **Similarity**: cosine similarity to the pixel in the middle of the map. - **Clusters**: k-means centroids, every pixel colored by its nearest one. - **Classifier**: three positive clicks on parks (Golden Gate Park, Buena Vista) and four negative ones on streets and water. The screenshots are map-only (control panel hidden), 1800 x 1013, taken from the live example. 🤖 Written by [Claude Code](https://claude.com/claude-code) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Note
This PR was written by Claude (Claude Code) on behalf of @kylebarron, not by @kylebarron.
An experimental example that runs small ONNX models over AlphaEarth embeddings in the browser. It reads the same GeoZarr mosaic as
aef-mosaic(64-band int8 embeddings) withZarrLayer, and uses ONNX Runtime Web on WebGPU to compute a result per pixel for every loaded tile, drawn through deck.gl-raster's WebGL2 pipeline.What it does
aef-mosaic, as its own mode.A "Show embeddings underneath" checkbox, on by default, draws the RGB composite dimmed under the model modes' results, as a cue for where data has loaded. With it off, results draw over the plain basemap, pixels below the threshold are not drawn, and a mode with nothing to show yet draws nothing.
In a browser without WebGPU, a dialog says that the models need it and offers the RGB mode, which draws without a model.
How it works
models/make_models.pythat onnxscript translates to ONNX, committed underpublic/models/.uv run models/make_models.py public/modelsrebuilds them and checks them against NumPy. The query vector, the centroids and the classifier weights are model inputs, so they change per run without a new model. The models use opset 23, the highest at which ONNX Runtime Web 1.31 keeps the int8 conversion on WebGPU.session.runcalls in flight on one session never resolve.DequantizeLinearnode. Every session disables ONNX Runtime's CPU fallback, so every node of every model runs on WebGPU.Numbers
Measured on an M2 Pro in headless Chromium; tiles are 256 x 256 x 64 int8.
Each loaded tile holds 4 MiB of int8 embeddings on the CPU and a 4 MiB texture for the RGB composite. An earlier version could also keep a float32 copy of each tile on ONNX Runtime's GPU device. That made a run about three times faster but cost 16 MiB of GPU memory per tile, so it was removed.
The in-app times vary that much from run to run.
NOTES.mdhas every measurement.The ONNX Runtime WebAssembly file is 28.7 MB, 7.3 MB gzipped, loaded when the first model runs.
Things to decide before this is more than a draft
/examples/onnx-embeddings/, including the 28.7 MB WebAssembly file.NOTES.mdis a findings log: the design, a friction log for ONNX Runtime Web, and measurements. It is useful background but unusual for an example directory, and can be dropped.aef-mosaicmight leak textures when the year changes. That was wrong:RasterTileset2D.finalize()callsonTileUnloadfor every cached tile when the inner TileLayer is replaced, and ten year changes inaef-mosaicleft no orphaned textures. This example's own cleanup on a year change was therefore freeing tiles twice, and is removed. The leak that does exist is the known one for tiles evicted while still loading (A tile aborted while it decodes still gets a texture, which is never freed #876, fix(geo-layers) callonTileUnloadwhen finalizing a TileLayer visgl/deck.gl#10883), whichmaxCacheSize: 10makes common in both examples.Test plan
typecheckpasses,biome cipasses on its directory, andvite buildproduces a site that serves the WebAssembly file locally.navigator.gpuand with no adapter, a dialog explains that the models need it and offers the RGB mode. No errors are logged.🤖 Written by Claude Code