Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

WebGPU runtime (#380)

uuuvnf1231705cc7e
diff --git a/.config/platforms.toml b/.config/platforms.toml
index ebab54dc6..fd545dbfc 100644
--- a/.config/platforms.toml
+++ b/.config/platforms.toml
@@ -71,7 +71,7 @@ capabilities_supported = ["grammar"]
capabilities_default = ["grammar"]
[targets."wasm32-unknown-unknown"]
-backend = "cpu"
+backend = "webgpu"
aliases = ["wasm"]
capabilities_supported = []
capabilities_default = []
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index fabc4b99e..570c11a54 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -44,7 +44,7 @@ jobs:
- name: Lint with clippy
if: ${{ !cancelled() && steps.setup.outcome == 'success' }}
- run: cargo +nightly clippy --workspace --all-targets -- -D warnings
+ run: cargo +nightly clippy --workspace --all-targets --features uzu-engine/webgpu -- -D warnings
- name: Check that Cargo.lock is consistent with Cargo.toml
if: ${{ !cancelled() && steps.setup.outcome == 'success' }}
@@ -62,7 +62,7 @@ jobs:
run: cargo tools sync --check
tests:
- name: ${{ matrix.host }}${{ matrix.target && format(' ({0})', matrix.target) }}
+ name: ${{ matrix.host }}${{ matrix.backend && format(' ({0})', matrix.backend) }}${{ matrix.target && format(' ({0})', matrix.target) }}
runs-on: ${{ matrix.host == 'linux' && 'uzu-n4std16' || 'prefect-github-actions' }}
timeout-minutes: 120
@@ -70,8 +70,16 @@ jobs:
matrix:
include:
- host: 'macos'
+ backend: 'metal'
tests: true
benches: true
+ - host: 'macos'
+ backend: 'webgpu'
+ tests: true
+ benches: true
+ crates: ['uzu-engine']
+ no-default-features: true
+ features: ['uzu-engine/webgpu', 'uzu-engine/cpu', 'uzu-engine/grammar']
- host: 'linux'
crates: ['cli']
- host: 'linux'
@@ -99,6 +107,8 @@ jobs:
run: |
cargo +${{ matrix.nightly && 'nightly' || 'stable' }} build \
${{ matrix.target && format('--target {0}', matrix.target) || '' }} \
+ ${{ matrix.no-default-features && '--no-default-features' || '' }} \
+ ${{ matrix.features && format('--features {0}', join(matrix.features, ',')) || '' }} \
${{ matrix.crates && format('-p {0}', join(matrix.crates, ' -p ')) || '' }}
- name: Build benches
@@ -106,6 +116,8 @@ jobs:
run: |
cargo +nightly bench --no-run \
${{ matrix.target && format('--target {0}', matrix.target) || '' }} \
+ ${{ matrix.no-default-features && '--no-default-features' || '' }} \
+ ${{ matrix.features && format('--features {0}', join(matrix.features, ',')) || '' }} \
${{ matrix.crates && format('-p {0}', join(matrix.crates, ' -p ')) || '' }}
- name: Run tests
@@ -113,6 +125,9 @@ jobs:
run: |
cargo +nightly nextest run --profile=ci \
${{ matrix.target && format('--target {0}', matrix.target) || '' }} \
+ ${{ matrix.no-default-features && '--no-default-features' || '' }} \
+ ${{ matrix.features && format('--features {0}', join(matrix.features, ',')) || '' }} \
+ ${{ matrix.tests != 'kernels' && matrix.crates && format('-p {0}', join(matrix.crates, ' -p ')) || '' }} \
${{ matrix.tests == 'kernels' && '-p uzu-engine backends::common::kernel::tests --lib' || '' }}
validate-bindings:
diff --git a/Cargo.lock b/Cargo.lock
index e462ebec5..73a493c89 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -228,6 +228,15 @@ dependencies = [
"stable_deref_trait",
]
+[[package]]
+name = "ash"
+version = "0.38.0+1.3.281"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"
+dependencies = [
+ "libloading 0.8.9",
+]
+
[[package]]
name = "askama"
version = "0.14.0"
@@ -331,6 +340,17 @@ dependencies = [
"slab",
]
+[[package]]
+name = "async-fs"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5"
+dependencies = [
+ "async-lock",
+ "blocking",
+ "futures-lite",
+]
+
[[package]]
name = "async-io"
version = "2.6.0"
@@ -678,6 +698,26 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72"
+[[package]]
+name = "bindgen"
+version = "0.72.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
+dependencies = [
+ "bitflags 2.13.2",
+ "cexpr",
+ "clang-sys",
+ "itertools 0.13.0",
+ "log",
+ "prettyplease 0.2.37",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "rustc-hash 2.1.3",
+ "shlex 1.3.0",
+ "syn 2.0.119",
+]
+
[[package]]
name = "bindings"
version = "0.6.13"
@@ -725,6 +765,15 @@ dependencies = [
"bit-vec 0.8.0",
]
+[[package]]
+name = "bit-set"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
+dependencies = [
+ "bit-vec 0.9.1",
+]
+
[[package]]
name = "bit-set"
version = "0.11.1"
@@ -746,6 +795,12 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
+[[package]]
+name = "bit-vec"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
+
[[package]]
name = "bit-vec"
version = "0.10.1"
@@ -847,7 +902,7 @@ checksum = "2706da6c749998cc555d04184909608956a69ad3f8ab1a076fbc867b4a3c3ce5"
dependencies = [
"darling 0.24.1",
"ident_case",
- "prettyplease",
+ "prettyplease 0.3.0",
"proc-macro2",
"quote",
"syn 3.0.9",
@@ -1087,7 +1142,7 @@ dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
- "shlex",
+ "shlex 2.0.1",
]
[[package]]
@@ -1096,6 +1151,15 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
+[[package]]
+name = "cexpr"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
+dependencies = [
+ "nom 7.1.3",
+]
+
[[package]]
name = "cfb"
version = "0.14.0"
@@ -1191,6 +1255,17 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "clang-sys"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
+dependencies = [
+ "glob",
+ "libc",
+ "libloading 0.8.9",
+]
+
[[package]]
name = "clap"
version = "4.6.7"
@@ -1305,6 +1380,17 @@ dependencies = [
"cc",
]
+[[package]]
+name = "codespan-reporting"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
+dependencies = [
+ "serde",
+ "termcolor",
+ "unicode-width 0.2.2",
+]
+
[[package]]
name = "color_quant"
version = "1.1.0"
@@ -2070,6 +2156,15 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "dlib"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
+dependencies = [
+ "libloading 0.8.9",
+]
+
[[package]]
name = "dlopen2"
version = "0.8.2"
@@ -2966,6 +3061,17 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "gl_generator"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"
+dependencies = [
+ "khronos_api",
+ "log",
+ "xml-rs",
+]
+
[[package]]
name = "glib"
version = "0.18.5"
@@ -3045,6 +3151,27 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "glow"
+version = "0.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5"
+dependencies = [
+ "js-sys",
+ "slotmap",
+ "wasm-bindgen",
+ "web-sys",
+]
+
+[[package]]
+name = "glutin_wgl_sys"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"
+dependencies = [
+ "gl_generator",
+]
+
[[package]]
name = "gobject-sys"
version = "0.18.0"
@@ -3067,6 +3194,20 @@ dependencies = [
"scroll",
]
+[[package]]
+name = "gpu-allocator"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"
+dependencies = [
+ "ash",
+ "hashbrown 0.16.1",
+ "log",
+ "presser",
+ "thiserror 2.0.21",
+ "windows 0.62.2",
+]
+
[[package]]
name = "grid"
version = "0.14.0"
@@ -3201,6 +3342,17 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
+]
+
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -4143,6 +4295,23 @@ dependencies = [
"log",
]
+[[package]]
+name = "khronos-egl"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"
+dependencies = [
+ "libc",
+ "libloading 0.8.9",
+ "pkg-config",
+]
+
+[[package]]
+name = "khronos_api"
+version = "3.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
+
[[package]]
name = "kiban"
version = "0.6.13"
@@ -4239,6 +4408,16 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "libloading"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
[[package]]
name = "libloading"
version = "0.9.0"
@@ -4756,6 +4935,42 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
+[[package]]
+name = "naga"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "arrayvec",
+ "bit-set 0.10.0",
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "codespan-reporting",
+ "half",
+ "hashbrown 0.17.1",
+ "indexmap 2.14.2",
+ "libm",
+ "log",
+ "naga-types",
+ "num-traits",
+ "once_cell",
+ "rustc-hash 1.1.0",
+ "spirv",
+ "thiserror 2.0.21",
+ "unicode-ident",
+]
+
+[[package]]
+name = "naga-types"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "hashbrown 0.17.1",
+ "indexmap 2.14.2",
+ "rustc-hash 1.1.0",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "nagare"
version = "0.6.13"
@@ -5376,6 +5591,18 @@ dependencies = [
"objc2-foundation",
]
+[[package]]
+name = "objc2-metal"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-foundation",
+]
+
[[package]]
name = "objc2-osa-kit"
version = "0.3.2"
@@ -5397,7 +5624,9 @@ dependencies = [
"bitflags 2.13.2",
"objc2",
"objc2-core-foundation",
+ "objc2-core-graphics",
"objc2-foundation",
+ "objc2-metal",
]
[[package]]
@@ -5959,6 +6188,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "pollster"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336"
+
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -6004,6 +6239,22 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
+[[package]]
+name = "presser"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
+
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn 2.0.119",
+]
+
[[package]]
name = "prettyplease"
version = "0.3.0"
@@ -6490,6 +6741,12 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "range-alloc"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
+
[[package]]
name = "rangemap"
version = "1.8.0"
@@ -6662,6 +6919,18 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+[[package]]
+name = "raw-window-metal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"
+dependencies = [
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "objc2-quartz-core",
+]
+
[[package]]
name = "rawpointer"
version = "0.2.1"
@@ -6796,6 +7065,12 @@ version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"
+[[package]]
+name = "renderdoc-sys"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+
[[package]]
name = "reqwest"
version = "0.12.28"
@@ -7671,6 +7946,22 @@ dependencies = [
"digest",
]
+[[package]]
+name = "shader-slang"
+version = "0.1.0"
+source = "git+https://github.com/trymirai/slang-rs.git?branch=unsigned_char_fix#2e6d0c23aa2eadf79ed5ecd8ac5b5bcd57bc30f0"
+dependencies = [
+ "shader-slang-sys",
+]
+
+[[package]]
+name = "shader-slang-sys"
+version = "0.1.0"
+source = "git+https://github.com/trymirai/slang-rs.git?branch=unsigned_char_fix#2e6d0c23aa2eadf79ed5ecd8ac5b5bcd57bc30f0"
+dependencies = [
+ "bindgen",
+]
+
[[package]]
name = "sharded-slab"
version = "0.1.7"
@@ -7680,6 +7971,12 @@ dependencies = [
"lazy_static",
]
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
[[package]]
name = "shlex"
version = "2.0.1"
@@ -7898,6 +8195,15 @@ version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
+[[package]]
+name = "spirv"
+version = "0.4.0+sdk-1.4.341.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
[[package]]
name = "spm_precompiled"
version = "0.1.4"
@@ -8653,6 +8959,15 @@ dependencies = [
"new_debug_unreachable",
]
+[[package]]
+name = "termcolor"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
+dependencies = [
+ "winapi-util",
+]
+
[[package]]
name = "termina"
version = "0.3.3"
@@ -9766,6 +10081,7 @@ name = "uzu-engine"
version = "0.6.13"
dependencies = [
"anyhow",
+ "async-fs",
"bitflags 2.13.2",
"blake3",
"bytemuck",
@@ -9782,13 +10098,15 @@ dependencies = [
"libtest-mimic",
"monostate 1.0.3",
"mtl-rs",
+ "naga",
"ndarray",
"num-traits",
"obfstr",
"objc2",
"objc2-foundation",
"parking_lot",
- "prettyplease",
+ "pollster",
+ "prettyplease 0.3.0",
"proc-macro2",
"proptest",
"quote",
@@ -9796,11 +10114,14 @@ dependencies = [
"rand_distr",
"rangemap",
"rayon",
+ "regex",
"rhai",
"rstest",
"schemars 1.2.3",
"serde",
"serde_json",
+ "shader-slang",
+ "shader-slang-sys",
"shoji",
"syn 3.0.9",
"tempfile",
@@ -9811,6 +10132,10 @@ dependencies = [
"uzu",
"uzu-engine-macros",
"walkdir",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "wgpu",
"xgrammar-rs",
"xxhash-rust",
]
@@ -10014,6 +10339,18 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "wayland-sys"
+version = "0.31.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
+dependencies = [
+ "dlib",
+ "log",
+ "once_cell",
+ "pkg-config",
+]
+
[[package]]
name = "web-sys"
version = "0.3.106"
@@ -10229,6 +10566,171 @@ dependencies = [
"wezterm-dynamic",
]
+[[package]]
+name = "wgpu"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "arrayvec",
+ "bitflags 2.13.2",
+ "bytemuck",
+ "cfg-if",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.17.1",
+ "js-sys",
+ "log",
+ "naga",
+ "parking_lot",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "smallvec",
+ "static_assertions",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "wgpu-core",
+ "wgpu-hal",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "arrayvec",
+ "bit-set 0.10.0",
+ "bit-vec 0.9.1",
+ "bitflags 2.13.2",
+ "bytemuck",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.17.1",
+ "indexmap 2.14.2",
+ "log",
+ "naga",
+ "naga-types",
+ "once_cell",
+ "parking_lot",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "rustc-hash 1.1.0",
+ "smallvec",
+ "thiserror 2.0.21",
+ "wgpu-core-deps-apple",
+ "wgpu-core-deps-emscripten",
+ "wgpu-core-deps-windows-linux-android",
+ "wgpu-hal",
+ "wgpu-naga-bridge",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core-deps-apple"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-core-deps-emscripten"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-core-deps-windows-linux-android"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-hal"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "android_system_properties",
+ "arrayvec",
+ "ash",
+ "bit-set 0.10.0",
+ "bitflags 2.13.2",
+ "block2",
+ "bytemuck",
+ "cfg-if",
+ "cfg_aliases",
+ "glow",
+ "glutin_wgl_sys",
+ "gpu-allocator",
+ "hashbrown 0.17.1",
+ "js-sys",
+ "khronos-egl",
+ "libc",
+ "libloading 0.8.9",
+ "log",
+ "naga",
+ "naga-types",
+ "ndk-sys",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "objc2-metal",
+ "objc2-quartz-core",
+ "once_cell",
+ "ordered-float 4.6.0",
+ "parking_lot",
+ "portable-atomic",
+ "portable-atomic-util",
+ "profiling",
+ "range-alloc",
+ "raw-window-handle",
+ "raw-window-metal",
+ "renderdoc-sys",
+ "smallvec",
+ "static_assertions",
+ "thiserror 2.0.21",
+ "wasm-bindgen",
+ "wayland-sys",
+ "web-sys",
+ "wgpu-naga-bridge",
+ "wgpu-types",
+ "windows 0.62.2",
+ "windows-core",
+ "windows-result",
+]
+
+[[package]]
+name = "wgpu-naga-bridge"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "naga",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-types"
+version = "30.0.1"
+source = "git+https://github.com/gfx-rs/wgpu?branch=v30#852d819c41a0b178aa1a4681bf1e0503bb90ca39"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytemuck",
+ "js-sys",
+ "log",
+ "naga-types",
+ "raw-window-handle",
+ "static_assertions",
+ "web-sys",
+]
+
[[package]]
name = "winapi"
version = "0.3.9"
@@ -10866,6 +11368,12 @@ dependencies = [
"tokenizers",
]
+[[package]]
+name = "xml-rs"
+version = "0.8.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f"
+
[[package]]
name = "xxhash-rust"
version = "0.8.19"
diff --git a/Cargo.toml b/Cargo.toml
index 34af100a0..e78793bb9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -82,6 +82,7 @@ objc2-core-foundation = "0.3.2"
objc2-io-kit = { version = "0.3.2", default-features = false, features = ["libc", "ps"] }
obfstr = "0.4.6"
metal = { package = "mtl-rs", version = "0.3.0" }
+wgpu = { git = "https://github.com/gfx-rs/wgpu", branch = "v30" } # TODO: switch to published version after upstream releases one with next trait solver overflow fix
block2 = "0.6.2"
bytemuck = "1.25.2"
bytesize = "2.7.0"
@@ -108,12 +109,16 @@ walkdir = "2.5.0"
depfile = "0.1.1"
tempfile = "3.27.0"
clang-ast = "0.1.35"
+shader-slang = { git = "https://github.com/trymirai/slang-rs.git", branch = "unsigned_char_fix" }
+shader-slang-sys = { git = "https://github.com/trymirai/slang-rs.git", branch = "unsigned_char_fix" }
+naga = { git = "https://github.com/gfx-rs/wgpu", branch = "v30" }
rangemap = "1.8.0"
parking_lot = "0.12.5"
futures = "0.3.34"
tokio = "1.53.3"
tokio-stream = { version = "0.1.19", features = ["sync"] }
tokio-util = { version = "0.7.20", default-features = false, features = ["rt"] }
+pollster = "1.0.1"
blake3 = "1.8.7"
quote = "1.0.47"
proc-macro2 = "1.0.107"
@@ -138,6 +143,7 @@ tracing-tree = "0.4.1"
tracing-appender = "0.2.5"
llm_json = "1.0.3"
futures-util = "0.3.34"
+async-fs = "2.2.0"
http = "1.5.0"
httparse = "1.10.1"
stream_throttle = "0.5.1"
@@ -173,7 +179,7 @@ pyo3-build-config = "0.29.3"
pyo3-async-runtimes = { version = "0.29.0", features = ["tokio-runtime"] }
pyo3-stub-gen = "0.23.1"
inventory = "0.3.25"
-wasm-bindgen = { version = "0.2.129", features = ["serde-serialize"] }
+wasm-bindgen = { version = "=0.2.129", features = ["serde-serialize"] }
serde-wasm-bindgen = "0.6.5"
wasm-bindgen-futures = "0.4.79"
tsify = { version = "0.5.8", features = ["js"] }
diff --git a/README.md b/README.md
index 511799197..62f5758a3 100644
--- a/README.md
+++ b/README.md
@@ -1420,6 +1420,7 @@ It supports:
- Backends:
- `metal`
+ - `webgpu`
- `cpu`
- Targets:
- `aarch64-apple-darwin`
diff --git a/crates/legacy/cli-tools/src/sync/readme.rs b/crates/legacy/cli-tools/src/sync/readme.rs
index 837ec34d0..93899fcf9 100644
--- a/crates/legacy/cli-tools/src/sync/readme.rs
+++ b/crates/legacy/cli-tools/src/sync/readme.rs
@@ -1,4 +1,8 @@
-use std::{collections::BTreeMap, fs, path::Path};
+use std::{
+ collections::{BTreeMap, BTreeSet},
+ fs,
+ path::Path,
+};
use anyhow::{Context, Result, anyhow};
use minijinja::{Environment, context, value::Serde};
@@ -89,7 +93,7 @@ impl SyncTask for ReadmeSyncTask {
})
.collect();
- let mut binding_targets: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
+ let mut binding_targets: BTreeSet<String> = BTreeSet::new();
for language_config in platforms.languages.values() {
if !language_config.bindings.is_empty() {
binding_targets.extend(language_config.targets.iter().cloned());
@@ -104,13 +108,14 @@ impl SyncTask for ReadmeSyncTask {
})
.collect();
- let mut backends: Vec<String> = Vec::new();
- for target_config in platforms.targets.values() {
- let name = target_config.backend.name();
- if !backends.contains(&name) {
- backends.push(name);
- }
- }
+ let backends: Vec<String> = platforms
+ .targets
+ .values()
+ .map(|target| target.backend)
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .map(|backend| backend.name())
+ .collect();
let rendered = template.render(context! {
title => "uzu",
diff --git a/crates/legacy/cli-tools/src/types/backend.rs b/crates/legacy/cli-tools/src/types/backend.rs
index e2e868a0f..b2f55e210 100644
--- a/crates/legacy/cli-tools/src/types/backend.rs
+++ b/crates/legacy/cli-tools/src/types/backend.rs
@@ -1,9 +1,10 @@
use serde::{Deserialize, Serialize};
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Backend {
Metal,
+ WebGPU,
Cpu,
}
@@ -11,6 +12,7 @@ impl Backend {
pub fn name(self) -> String {
match self {
Backend::Metal => "metal".to_string(),
+ Backend::WebGPU => "webgpu".to_string(),
Backend::Cpu => "cpu".to_string(),
}
}
@@ -18,6 +20,7 @@ impl Backend {
pub fn feature(self) -> String {
match self {
Backend::Metal => "backend-metal".to_string(),
+ Backend::WebGPU => "backend-webgpu".to_string(),
Backend::Cpu => "backend-cpu".to_string(),
}
}
diff --git a/crates/legacy/cli/Cargo.toml b/crates/legacy/cli/Cargo.toml
index 273054341..28ddf273d 100644
--- a/crates/legacy/cli/Cargo.toml
+++ b/crates/legacy/cli/Cargo.toml
@@ -16,6 +16,7 @@ path = "src/main.rs"
default = ["backend-cpu", "backend-metal", "capability-grammar"]
backend-cpu = ["uzu/backend-cpu"]
backend-metal = ["uzu/backend-metal"]
+backend-webgpu = ["uzu/backend-webgpu"]
capability-grammar = ["uzu/capability-grammar"]
[dependencies]
diff --git a/crates/legacy/uzu/Cargo.toml b/crates/legacy/uzu/Cargo.toml
index 6df303c57..af8e18586 100644
--- a/crates/legacy/uzu/Cargo.toml
+++ b/crates/legacy/uzu/Cargo.toml
@@ -18,6 +18,7 @@ crate-type = ["lib", "cdylib", "staticlib"]
default = ["backend-cpu", "backend-metal", "capability-grammar"]
backend-cpu = ["uzu-engine/cpu"]
backend-metal = ["uzu-engine/metal"]
+backend-webgpu = ["uzu-engine/webgpu"]
capability-grammar = ["uzu-engine/grammar"]
bindings = [
"bindings-uniffi",
diff --git a/crates/legacy/uzu/src/engine/bridge/chat_token_backend.rs b/crates/legacy/uzu/src/engine/bridge/chat_token_backend.rs
index d0cfbbf77..43fe29eb3 100644
--- a/crates/legacy/uzu/src/engine/bridge/chat_token_backend.rs
+++ b/crates/legacy/uzu/src/engine/bridge/chat_token_backend.rs
@@ -59,7 +59,7 @@ impl<B: Backend> UzuChatTokenBackendInstance<B> {
) -> Result<Self, BackendError> {
let engine = Engine::<B>::new().await.map_err(|err| err.to_string())?;
let model_path = PathBuf::from(model_path);
- let model = engine.load_language_model(&model_path).map_err(|err| err.to_string())?;
+ let model = engine.load_language_model(&model_path).await.map_err(|err| err.to_string())?;
let generation_config = model.generation_config();
let stop_token_ids = generation_config.stop_token_ids.iter().map(|id| *id as i32).collect();
@@ -171,41 +171,34 @@ impl<B: Backend> BackendInstance for UzuChatTokenBackendInstance<B> {
let metrics = stream.metrics().clone();
let inner = stream::unfold(
- (stream, 0, cancel_token.child_token(), false),
- move |(mut stream, mut tokens_generated, cancel_token, finished)| async move {
- if finished {
- return None;
- }
-
- let cancelled = cancel_token.is_cancelled();
- let output = if cancelled || token_limit.is_some_and(|token_limit| tokens_generated >= token_limit) {
- match stream.close().await {
- Ok(()) if cancelled => return None,
- Ok(()) => Ok(TokenStreamOutput::LimitReached),
- Err(error) => Err(BackendError::from(error.to_string())),
- }
+ (Some(stream), 0, cancel_token.child_token()),
+ move |(stream, mut tokens_generated, cancel_token)| async move {
+ let mut stream = stream?;
+ let (mut output, finished) = if cancel_token.is_cancelled() {
+ (None, true)
+ } else if token_limit.is_some_and(|token_limit| tokens_generated >= token_limit) {
+ (Some(Ok(TokenStreamOutput::LimitReached)), true)
} else {
match stream.generate().await.map_err(|error| BackendError::from(error.to_string())) {
Ok(Some(token)) => {
tokens_generated += 1;
- Ok(TokenStreamOutput::Token(token))
- },
- Ok(None) => match stream.close().await {
- Ok(()) => return None,
- Err(error) => Err(BackendError::from(error.to_string())),
- },
- Err(error) => {
- let _ = stream.close().await;
- Err(error)
+ (Some(Ok(TokenStreamOutput::Token(token))), self.stop_token_ids.contains(&(token as i32)))
},
+ Ok(None) => (None, true),
+ Err(error) => (Some(Err(error)), true),
}
};
- let finished = !matches!(&output, Ok(TokenStreamOutput::Token(_)));
- if output.is_err() {
+ if finished {
cancel_token.cancel();
+ if let Err(error) = stream.close().await
+ && !matches!(&output, Some(Err(_)))
+ {
+ output = Some(Err(BackendError::from(error.to_string())));
+ }
}
let metrics = stream.metrics().clone();
- Some(((output, metrics), (stream, tokens_generated, cancel_token, finished)))
+ output
+ .map(|output| ((output, metrics), ((!finished).then_some(stream), tokens_generated, cancel_token)))
},
);
diff --git a/crates/legacy/uzu/src/engine/bridge/classification_backend.rs b/crates/legacy/uzu/src/engine/bridge/classification_backend.rs
index 9f2072517..293fcc190 100644
--- a/crates/legacy/uzu/src/engine/bridge/classification_backend.rs
+++ b/crates/legacy/uzu/src/engine/bridge/classification_backend.rs
@@ -30,7 +30,7 @@ impl<B: Backend> UzuClassificationBackendInstance<B> {
pub async fn new(model_path: String) -> Result<Self, BackendError> {
let engine = Engine::<B>::new().await.map_err(|err| err.to_string())?;
let model_path = PathBuf::from(model_path);
- let model = engine.load_classifier_model(&model_path).map_err(|err| err.to_string())?;
+ let model = engine.load_classifier_model(&model_path).await.map_err(|err| err.to_string())?;
Ok(Self {
model: Arc::new(model),
})
diff --git a/crates/legacy/uzu/src/engine/mod.rs b/crates/legacy/uzu/src/engine/mod.rs
index b42bab1e8..a4ac34d75 100644
--- a/crates/legacy/uzu/src/engine/mod.rs
+++ b/crates/legacy/uzu/src/engine/mod.rs
@@ -558,6 +558,7 @@ impl Engine {
if Path::new(&path).is_dir() {
let backend = UzuLlmBackend::new();
return LocalRegistry::model_at_path(Path::new(&path), backend.identifier(), backend.version())
+ .await
.map(Some)
.map_err(EngineError::from);
}
diff --git a/crates/legacy/uzu/src/engine/model_info.rs b/crates/legacy/uzu/src/engine/model_info.rs
index b811b8b0f..c31fdf255 100644
--- a/crates/legacy/uzu/src/engine/model_info.rs
+++ b/crates/legacy/uzu/src/engine/model_info.rs
@@ -3,7 +3,7 @@ use std::path::Path;
use hanashi::chat::EncodingConfig;
use shoji::types::{basic::ReasoningEffort, model::Model, session::chat::ChatModelCapabilities};
-use super::{Engine, EngineError};
+use crate::engine::{Engine, EngineError};
/// Chat metadata available without loading model weights or allocating a session.
#[bindings::export(Structure(Class))]
@@ -33,26 +33,20 @@ impl Engine {
}
let path = self.model_path(model).await;
let encoding = model.encoding.clone();
- tokio::task::spawn_blocking(move || {
- let encoding = encoding.ok_or_else(|| EngineError::ModelConfig {
- message: "Chat model has no supported encoding".into(),
- })?;
- let config: EncodingConfig = serde_json::from_str(&encoding.json).map_err(config_error)?;
- Ok(Some(ChatModelInfo {
- context_length: match path {
- Some(path) => {
- uzu_engine::engine::resolve_model_context_length(Path::new(&path)).map_err(config_error)?
- },
- None => None,
+ let encoding = encoding.ok_or_else(|| EngineError::ModelConfig {
+ message: "Chat model has no supported encoding".into(),
+ })?;
+ let config: EncodingConfig = serde_json::from_str(&encoding.json).map_err(config_error)?;
+ Ok(Some(ChatModelInfo {
+ context_length: match path {
+ Some(path) => {
+ uzu_engine::engine::resolve_model_context_length(Path::new(&path)).await.map_err(config_error)?
},
- capabilities: config.capabilities().map_err(config_error)?,
- default_reasoning_effort: config.default_reasoning_effort().map_err(config_error)?,
- }))
- })
- .await
- .map_err(|error| EngineError::TokioError {
- message: error.to_string(),
- })?
+ None => None,
+ },
+ capabilities: config.capabilities().map_err(config_error)?,
+ default_reasoning_effort: config.default_reasoning_effort().map_err(config_error)?,
+ }))
}
}
diff --git a/crates/legacy/uzu/src/engine/sampling.rs b/crates/legacy/uzu/src/engine/sampling.rs
index b2fbb537d..765a4b7d6 100644
--- a/crates/legacy/uzu/src/engine/sampling.rs
+++ b/crates/legacy/uzu/src/engine/sampling.rs
@@ -3,7 +3,7 @@ use std::path::Path;
use shoji::types::{basic::SamplingMethod, model::Model};
use uzu_engine::engine::{language_model::stream::SamplingMethod as UzuSamplingMethod, resolve_model_sampling_method};
-use super::{Engine, EngineError};
+use crate::engine::{Engine, EngineError};
impl Engine {
/// Read a local model's sampling defaults without loading its weights or creating a session.
@@ -14,16 +14,12 @@ impl Engine {
let Some(path) = self.model_path(model).await else {
return Ok(None);
};
- tokio::task::spawn_blocking(move || read_sampling_defaults(Path::new(&path))).await.map_err(|error| {
- EngineError::TokioError {
- message: error.to_string(),
- }
- })?
+ read_sampling_defaults(Path::new(&path)).await
}
}
-fn read_sampling_defaults(model_path: &Path) -> Result<Option<SamplingMethod>, EngineError> {
- resolve_model_sampling_method(model_path).map(|method| method.map(sampling_method)).map_err(|error| {
+async fn read_sampling_defaults(model_path: &Path) -> Result<Option<SamplingMethod>, EngineError> {
+ resolve_model_sampling_method(model_path).await.map(|method| method.map(sampling_method)).map_err(|error| {
EngineError::ModelConfig {
message: error.to_string(),
}
@@ -90,7 +86,7 @@ mod tests {
});
std::fs::write(directory.path().join("config.json"), serde_json::to_vec(&config).unwrap()).unwrap();
assert_eq!(
- read_sampling_defaults(directory.path()).unwrap(),
+ futures::executor::block_on(read_sampling_defaults(directory.path())).unwrap(),
Some(SamplingMethod::Stochastic {
temperature: None,
top_k: Some(20),
diff --git a/crates/legacy/uzu/src/registry/local/mod.rs b/crates/legacy/uzu/src/registry/local/mod.rs
index 97eb06257..42757054c 100644
--- a/crates/legacy/uzu/src/registry/local/mod.rs
+++ b/crates/legacy/uzu/src/registry/local/mod.rs
@@ -20,14 +20,14 @@ pub struct Registry {
}
impl Registry {
- pub(crate) fn model_at_path(
+ pub(crate) async fn model_at_path(
path: &Path,
backend_identifier: String,
backend_version: String,
) -> Result<Model, RegistryError> {
let registry =
Self::new(Config::new(backend_identifier, backend_version, path.to_string_lossy().into_owned()))?;
- registry.model(Path::new(&registry.config.path))
+ registry.model(Path::new(&registry.config.path)).await
}
pub fn new(mut config: Config) -> Result<Self, RegistryError> {
@@ -55,7 +55,7 @@ impl RegistryTrait for Registry {
Box::pin(async {
let path = Path::new(&self.config.path);
if path.join("config.json").is_file() {
- return Ok(vec![self.model(path)?]);
+ return Ok(vec![self.model(path).await?]);
}
let entries = fs::read_dir(path).map_err(|error| RegistryError::UnableToGetModels {
@@ -74,7 +74,7 @@ impl RegistryTrait for Registry {
if !file_type.is_dir() {
continue;
}
- match self.model(&path) {
+ match self.model(&path).await {
Ok(model) => models.push(model),
Err(error) => {
tracing::warn!(?error, path = %path.display(), "skipping invalid local model");
@@ -88,7 +88,7 @@ impl RegistryTrait for Registry {
}
impl Registry {
- fn model(
+ async fn model(
&self,
path: &Path,
) -> Result<Model, RegistryError> {
@@ -96,6 +96,7 @@ impl Registry {
message: format!("Invalid local model path: {}", path.display()),
})?;
let specialization = resolve_model_type(path)
+ .await
.map(|model_type| match model_type {
ModelType::LanguageModel => ModelSpecialization::Chat {},
ModelType::Classifier => ModelSpecialization::Classification {},
diff --git a/crates/uzu-engine/Cargo.toml b/crates/uzu-engine/Cargo.toml
index f3ecd2da6..5aa9ecd3c 100644
--- a/crates/uzu-engine/Cargo.toml
+++ b/crates/uzu-engine/Cargo.toml
@@ -13,9 +13,7 @@ build = "build/main.rs"
workspace = true
[features]
-default = ["cpu", "metal", "grammar"]
-
-cpu = [] # TODO: move libm here
+default = ["metal", "cpu", "grammar"]
metal = [
"dep:rayon",
@@ -30,6 +28,20 @@ metal = [
"dep:metal",
]
+webgpu = [
+ "dep:rayon",
+ "dep:serde_json",
+ "dep:blake3",
+ "dep:shader-slang",
+ "dep:shader-slang-sys",
+ "dep:regex",
+ "dep:naga",
+ "dep:wgpu",
+ "dep:pollster",
+]
+
+cpu = [] # TODO: move libm here
+
grammar = ["dep:xgrammar", "dep:schemars"]
[build-dependencies]
@@ -43,14 +55,18 @@ syn.workspace = true
prettyplease.workspace = true
itertools.workspace = true
rhai.workspace = true
+shader-slang = { workspace = true, optional = true }
+shader-slang-sys = { workspace = true, optional = true }
+regex = { workspace = true, optional = true }
+naga = { workspace = true, optional = true, features = ["wgsl-in"] }
+blake3 = { workspace = true, optional = true }
+serde_json = { workspace = true, features = ["unbounded_depth"], optional = true }
+rayon = { workspace = true, optional = true }
[target.'cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "visionos"))'.build-dependencies]
-rayon = { workspace = true, optional = true }
clang-ast = { workspace = true, optional = true }
depfile = { workspace = true, optional = true }
tempfile = { workspace = true, optional = true }
-serde_json = { workspace = true, features = ["unbounded_depth"], optional = true }
-blake3 = { workspace = true, optional = true }
xxhash-rust = { workspace = true, features = ["xxh3"], optional = true }
[dependencies]
@@ -71,6 +87,8 @@ libm.workspace = true
futures.workspace = true
itertools.workspace = true
parking_lot.workspace = true
+wgpu = { workspace = true, optional = true }
+pollster = { workspace = true, optional = true }
[target.'cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "visionos"))'.dependencies]
objc2 = { workspace = true, optional = true }
@@ -78,10 +96,31 @@ obfstr = { workspace = true, optional = true }
xxhash-rust = { workspace = true, features = ["xxh3"], optional = true }
metal = { workspace = true, optional = true }
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+tokenizers = { workspace = true, features = ["unstable_wasm"] }
+wgpu = { workspace = true, optional = true, features = ["fragile-send-sync-non-atomic-wasm"] }
+
+[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
+wasm-bindgen.workspace = true
+wasm-bindgen-futures.workspace = true
+web-sys = { workspace = true, features = [
+ "Blob",
+ "DomException",
+ "File",
+ "FileSystemDirectoryHandle",
+ "FileSystemFileHandle",
+ "Navigator",
+ "StorageManager",
+ "Window",
+] }
+
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
xgrammar = { workspace = true, optional = true }
schemars = { workspace = true, optional = true }
+[target.'cfg(not(all(target_arch = "wasm32", target_os = "unknown")))'.dependencies]
+async-fs.workspace = true
+
[dev-dependencies]
test-tag.workspace = true
proptest.workspace = true
diff --git a/crates/uzu-engine/build/common/caching.rs b/crates/uzu-engine/build/common/caching.rs
index fe08d1541..46f70e5bc 100644
--- a/crates/uzu-engine/build/common/caching.rs
+++ b/crates/uzu-engine/build/common/caching.rs
@@ -1,4 +1,4 @@
-#![cfg(all(feature = "metal", target_os = "macos"))]
+#![cfg(any(all(feature = "metal", target_os = "macos"), feature = "webgpu"))]
use std::{
fs,
diff --git a/crates/uzu-engine/build/common/kernel.rs b/crates/uzu-engine/build/common/kernel.rs
index c66dc2423..961a8c60f 100644
--- a/crates/uzu-engine/build/common/kernel.rs
+++ b/crates/uzu-engine/build/common/kernel.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use super::identifiers::{ArgumentName, KernelName};
-#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
+#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Copy)]
pub enum KernelBufferAccess {
Read,
ReadWrite,
diff --git a/crates/uzu-engine/build/common/mangling.rs b/crates/uzu-engine/build/common/mangling.rs
index af2c86465..4c4303650 100644
--- a/crates/uzu-engine/build/common/mangling.rs
+++ b/crates/uzu-engine/build/common/mangling.rs
@@ -1,9 +1,12 @@
-#![cfg(all(feature = "metal", target_os = "macos"))]
+#![cfg(any(all(feature = "metal", target_os = "macos"), feature = "webgpu"))]
+#[cfg(all(feature = "metal", target_os = "macos"))]
use std::iter::repeat_n;
use itertools::Itertools;
+#[cfg(all(feature = "metal", target_os = "macos"))]
use proc_macro2::TokenStream;
+#[cfg(all(feature = "metal", target_os = "macos"))]
use quote::quote;
pub fn static_mangle(
@@ -25,6 +28,7 @@ pub fn static_mangle(
)
}
+#[cfg(all(feature = "metal", target_os = "macos"))]
pub fn dynamic_mangle(
function_name: impl AsRef<str>,
variant: impl IntoIterator<Item = TokenStream>,
diff --git a/crates/uzu-engine/build/common/traitgen.rs b/crates/uzu-engine/build/common/traitgen.rs
index 7881f6217..a9c53d57c 100644
--- a/crates/uzu-engine/build/common/traitgen.rs
+++ b/crates/uzu-engine/build/common/traitgen.rs
@@ -96,11 +96,16 @@ pub fn traitgen_all(
let mut kernels: HashMap<KernelPath, Box<[Kernel]>> = HashMap::new();
+ let mut mismatches = Vec::new();
+
for backend_kernels in backends_kernels {
for (file_path, file_kernels) in backend_kernels {
if let Some(cached_kernels) = kernels.get(&file_path) {
if cached_kernels != &file_kernels {
- bail!("{cached_kernels:?} != {file_kernels:?}");
+ mismatches.push(format!(
+ "kernel metadata mismatch at {}:\nfirst: {cached_kernels:?}\nsecond: {file_kernels:?}",
+ file_path.join("::")
+ ));
}
} else {
kernels.insert(file_path, file_kernels);
@@ -108,6 +113,10 @@ pub fn traitgen_all(
}
}
+ if !mismatches.is_empty() {
+ bail!("{}", mismatches.join("\n\n"));
+ }
+
let mut kernel_traits = Vec::new();
let mut kernel_types = Vec::new();
diff --git a/crates/uzu-engine/build/cpu/compiler.rs b/crates/uzu-engine/build/cpu/compiler.rs
index b6317d0cb..ba6082651 100644
--- a/crates/uzu-engine/build/cpu/compiler.rs
+++ b/crates/uzu-engine/build/cpu/compiler.rs
@@ -44,7 +44,7 @@ impl FunctionArgument {
name: ArgumentName::from(self.name.to_string()),
conditional: self.conditional.is_some(),
ty: match &self.ty {
- FunctionArgumentType::Buffer(access) => KernelArgumentType::Buffer(access.clone()),
+ FunctionArgumentType::Buffer(access) => KernelArgumentType::Buffer(*access),
FunctionArgumentType::Constant(ty, None) => KernelArgumentType::Constant(
format!("&[{}]", canonicalize_type_text(ty, gpu_type_paths)).into_boxed_str(),
),
diff --git a/crates/uzu-engine/build/main.rs b/crates/uzu-engine/build/main.rs
index a4873b5c2..30124f456 100644
--- a/crates/uzu-engine/build/main.rs
+++ b/crates/uzu-engine/build/main.rs
@@ -5,11 +5,17 @@ use anyhow::Context;
mod common;
use common::{compiler::Compiler, envs, gpu_type_paths::GpuTypePaths, gpu_types::GpuTypes, traitgen::traitgen_all};
-mod cpu;
-
#[cfg(all(feature = "metal", target_os = "macos"))]
mod metal;
+#[cfg(feature = "webgpu")]
+mod slang;
+
+#[cfg(feature = "webgpu")]
+mod webgpu;
+
+mod cpu;
+
fn main() -> anyhow::Result<ExitCode> {
println!("cargo::rerun-if-changed=build");
@@ -20,18 +26,23 @@ fn main() -> anyhow::Result<ExitCode> {
let target_arch = env::var("CARGO_CFG_TARGET_ARCH")?;
let target_os = env::var("CARGO_CFG_TARGET_OS")?;
- println!("cargo::rustc-check-cfg=cfg(backend, values(\"cpu\", \"metal\"))");
-
- let backend_cpu = cfg!(feature = "cpu");
- if backend_cpu {
- println!("cargo::rustc-cfg=backend=\"cpu\"");
- }
+ println!("cargo::rustc-check-cfg=cfg(backend, values(\"metal\", \"webgpu\", \"cpu\"))");
let backend_metal = cfg!(feature = "metal") && matches!(target_os.as_ref(), "macos" | "ios" | "tvos" | "visionos");
if backend_metal {
println!("cargo::rustc-cfg=backend=\"metal\"");
}
+ let backend_webgpu = cfg!(feature = "webgpu");
+ if backend_webgpu {
+ println!("cargo::rustc-cfg=backend=\"webgpu\"");
+ }
+
+ let backend_cpu = cfg!(feature = "cpu");
+ if backend_cpu {
+ println!("cargo::rustc-cfg=backend=\"cpu\"");
+ }
+
let grammar = cfg!(feature = "grammar") && target_arch != "wasm32";
println!("cargo::rustc-check-cfg=cfg(grammar)");
if grammar {
@@ -56,15 +67,20 @@ fn main() -> anyhow::Result<ExitCode> {
let mut compilers: Vec<Box<dyn Compiler>> = Vec::new();
- if backend_cpu {
- compilers.push(Box::new(cpu::CpuCompiler::new()?));
- }
-
#[cfg(all(feature = "metal", target_os = "macos"))]
if backend_metal {
compilers.push(Box::new(metal::MetalCompiler::new()?));
}
+ #[cfg(feature = "webgpu")]
+ if backend_webgpu {
+ compilers.push(Box::new(slang::SlangCompiler::<webgpu::WebGPU>::new()?));
+ }
+
+ if backend_cpu {
+ compilers.push(Box::new(cpu::CpuCompiler::new()?));
+ }
+
if compilers.is_empty() {
println!("cargo::error=uzu requires at least one backend to be compiled in!");
return Ok(ExitCode::FAILURE);
diff --git a/crates/uzu-engine/build/metal/bindgen/mod.rs b/crates/uzu-engine/build/metal/bindgen/mod.rs
index ee9cc10d1..d2c4bbdf2 100644
--- a/crates/uzu-engine/build/metal/bindgen/mod.rs
+++ b/crates/uzu-engine/build/metal/bindgen/mod.rs
@@ -161,7 +161,7 @@ pub fn bindgen_global(kernels: &[(impl AsRef<std::path::Path>, &[Kernel])]) -> R
use objc2::{rc::Retained, runtime::ProtocolObject};
use crate::backends::{
- common::{BufferRef, CommandBufferEncoding, BufferMut},
+ common::{BufferRef, CommandBufferEncoding, CpuBuffer},
metal::{
context::MetalContext,
error::MetalError,
diff --git a/crates/uzu-engine/build/slang/compiler.rs b/crates/uzu-engine/build/slang/compiler.rs
new file mode 100644
index 000000000..91c7814ae
--- /dev/null
+++ b/crates/uzu-engine/build/slang/compiler.rs
@@ -0,0 +1,111 @@
+use std::{
+ collections::HashMap,
+ fs,
+ path::PathBuf,
+ sync::{Arc, Mutex},
+};
+
+use anyhow::Context;
+use rayon::prelude::*;
+use walkdir::WalkDir;
+
+use crate::{
+ common::{
+ codegen::write_tokens, compiler::Compiler, gpu_type_paths::GpuTypePaths, gpu_types::GpuTypes,
+ identifiers::KernelPath, kernel::Kernel,
+ },
+ slang::{
+ compiler_internal::{BlockingSlangCompiler, SlangCompilerFields, SlangTarget},
+ gpu_types::gpu_type_gen,
+ },
+};
+
+pub struct SlangCompiler<T: SlangTarget> {
+ fields: SlangCompilerFields<T>,
+ blocking_compiler_pool: Mutex<Vec<BlockingSlangCompiler<T>>>,
+}
+
+impl<T: SlangTarget> SlangCompiler<T> {
+ pub fn new() -> anyhow::Result<Self> {
+ let fields = SlangCompilerFields::new()?;
+ let blocking_compiler_pool = Mutex::new(Vec::new());
+
+ Ok(Self {
+ fields,
+ blocking_compiler_pool,
+ })
+ }
+
+ fn with_blocking_compiler<R, F>(
+ &self,
+ f: F,
+ ) -> anyhow::Result<R>
+ where
+ F: FnOnce(&mut BlockingSlangCompiler<T>) -> anyhow::Result<R>,
+ {
+ let blocking_compiler = if let Some(blocking_compiler) = self.blocking_compiler_pool.lock().unwrap().pop() {
+ blocking_compiler
+ } else {
+ BlockingSlangCompiler::new(self.fields.clone()).context("cannot create blocking compiler")?
+ };
+
+ let mut blocking_compiler = blocking_compiler;
+ let result = f(&mut blocking_compiler);
+
+ self.blocking_compiler_pool.lock().unwrap().push(blocking_compiler);
+
+ result
+ }
+}
+
+impl<T: SlangTarget> Compiler for SlangCompiler<T> {
+ fn build(
+ &self,
+ gpu_types: &GpuTypes,
+ _gpu_type_paths: &GpuTypePaths,
+ ) -> anyhow::Result<HashMap<KernelPath, Box<[Kernel]>>> {
+ let gpu_type_map = Arc::new(
+ gpu_type_gen(&self.fields.source_directory.join("generated"), gpu_types)
+ .context("cannot generate shared gpu types")?,
+ );
+
+ let slang_sources: Vec<PathBuf> = WalkDir::new(&self.fields.source_directory)
+ .into_iter()
+ .filter_map(|res| res.ok())
+ .filter(|entry| {
+ entry.path().is_file()
+ && entry.path().extension().and_then(|s| s.to_str()) == Some("slang")
+ && fs::read(entry.path()).map(|p| !p.starts_with(b"implementing")).unwrap_or(true)
+ })
+ .map(|e| e.into_path())
+ .collect();
+
+ let kernels = slang_sources
+ .into_par_iter()
+ .map(|path| {
+ self.with_blocking_compiler(|compiler| compiler.compile(path.clone(), gpu_type_map.clone()))
+ .with_context(|| format!("cannot compile {}", path.display()))
+ })
+ .collect::<anyhow::Result<HashMap<Box<[Box<str>]>, Box<[Kernel]>>>>()?;
+
+ let mut kernels_bindgen = kernels
+ .iter()
+ .filter(|(_segments, kernels)| !kernels.is_empty())
+ .map(|(segments, kernels)| {
+ (self.fields.output_directory.join(segments.join("/")).with_extension("rs"), kernels.as_ref())
+ })
+ .collect::<Vec<(PathBuf, &[Kernel])>>();
+
+ kernels_bindgen.sort_by(|(a_path, _a_kernels), (b_path, _b_kernels)| a_path.cmp(b_path));
+
+ let bindgen_tokens = T::bindgen_global(&kernels_bindgen).context("cannot bindgen global")?;
+ write_tokens(bindgen_tokens, self.fields.output_directory.with_extension("rs"))
+ .context("cannot write global bindgen file")?;
+
+ Ok(kernels
+ .into_iter()
+ .filter(|(_, kernels)| !kernels.is_empty())
+ .map(|(segments, kernels)| (segments.iter().map(|segment| segment.to_string()).collect(), kernels))
+ .collect())
+ }
+}
diff --git a/crates/uzu-engine/build/slang/compiler_internal.rs b/crates/uzu-engine/build/slang/compiler_internal.rs
new file mode 100644
index 000000000..163b0464b
--- /dev/null
+++ b/crates/uzu-engine/build/slang/compiler_internal.rs
@@ -0,0 +1,268 @@
+use std::{
+ collections::HashMap,
+ env,
+ ffi::CString,
+ fs,
+ iter::once,
+ marker::PhantomData,
+ path::{Path, PathBuf},
+ sync::Arc,
+};
+
+use anyhow::Context;
+use itertools::Itertools;
+use proc_macro2::TokenStream;
+use serde::{Deserialize, Serialize};
+use shader_slang::{
+ CompilerOptions, ComponentType, GlobalSession, ModifierID, OptimizationLevel, Session, SessionDesc, TargetDesc,
+};
+
+use crate::{
+ common::{caching, codegen::write_tokens, kernel::Kernel},
+ debug_log,
+ slang::{reflection::SlangKernel, slang_sys_ext::SessionLoadModuleWithDiagnosticsExt, wrapper},
+};
+
+pub trait SlangTarget: Send + Sync + Clone + 'static {
+ const TARGET_NAME: &'static str;
+ const OUTPUT_EXTENSION: &'static str;
+
+ fn create_target_desc<'a>(global_session: &'a GlobalSession) -> TargetDesc<'a>;
+
+ fn validate_output(path: &Path) -> anyhow::Result<()>;
+
+ fn bindgen_file(
+ linked_component: &ComponentType,
+ kernels: &[SlangKernel],
+ gpu_type_map: &HashMap<String, String>,
+ constants: &HashMap<String, String>,
+ object_file: &Path,
+ ) -> anyhow::Result<TokenStream>;
+
+ fn bindgen_global(kernels: &[(impl AsRef<Path>, &[Kernel])]) -> anyhow::Result<TokenStream>;
+}
+
+#[derive(Clone)]
+pub struct SlangCompilerFields<T: SlangTarget> {
+ pub source_directory: PathBuf,
+ pub output_directory: PathBuf,
+ pub optimization_level: OptimizationLevel,
+ _phantom: PhantomData<T>,
+}
+
+impl<T: SlangTarget> SlangCompilerFields<T> {
+ pub fn new() -> anyhow::Result<Self> {
+ let source_directory = PathBuf::from(env::var("CARGO_MANIFEST_DIR").context("missing CARGO_MANIFEST_DIR")?)
+ .join("src/backends/slang/kernel");
+
+ println!("cargo::rerun-if-changed={}", source_directory.display());
+
+ let output_directory = PathBuf::from(env::var("OUT_DIR").context("missing OUT_DIR")?).join(T::TARGET_NAME);
+
+ let optimization_level = match env::var("OPT_LEVEL").context("missing OPT_LEVEL")?.as_str() {
+ "0" => OptimizationLevel::Default,
+ _ => OptimizationLevel::High,
+ };
+
+ Ok(Self {
+ source_directory,
+ output_directory,
+ optimization_level,
+ _phantom: PhantomData,
+ })
+ }
+}
+
+#[derive(Serialize, Deserialize)]
+struct Cached {
+ buildsystem_hash: [u8; blake3::OUT_LEN],
+ compiler_version: String,
+ dependency_hashes: HashMap<String, [u8; blake3::OUT_LEN]>,
+ public_kernels: Box<[Kernel]>,
+}
+
+pub struct BlockingSlangCompiler<T: SlangTarget> {
+ session: Session,
+ global_session: GlobalSession,
+ fields: SlangCompilerFields<T>,
+}
+
+unsafe impl<T: SlangTarget> Send for BlockingSlangCompiler<T> {}
+
+impl<T: SlangTarget> BlockingSlangCompiler<T> {
+ pub fn new(fields: SlangCompilerFields<T>) -> anyhow::Result<Self> {
+ let global_session = GlobalSession::new().context("cannot create global session")?;
+
+ let compiler_options = CompilerOptions::default()
+ .optimization(fields.optimization_level)
+ .emit_spirv_directly(true)
+ .vulkan_use_entry_point_name(true);
+
+ let search_path = CString::new(fields.source_directory.to_string_lossy().as_bytes())
+ .context("cannot convert src_dir to CString")?;
+ let search_paths = [search_path.as_ptr()];
+
+ let target_desc = T::create_target_desc(&global_session);
+ let targets = [target_desc];
+
+ let session_desc =
+ SessionDesc::default().options(&compiler_options).search_paths(&search_paths).targets(&targets);
+
+ let session = global_session.create_session(&session_desc).context("cannot create session")?;
+
+ Ok(Self {
+ session,
+ global_session,
+ fields,
+ })
+ }
+
+ pub fn compile(
+ &self,
+ source_path: PathBuf,
+ gpu_type_map: Arc<HashMap<String, String>>,
+ ) -> anyhow::Result<(Box<[Box<str>]>, Box<[Kernel]>)> {
+ let source_path_relative =
+ source_path.strip_prefix(&self.fields.source_directory).context("source is not in src_dir")?;
+ let source_path_relative_str = source_path_relative.to_str().unwrap();
+ debug_log!("compile start: {source_path_relative_str}");
+
+ let source_path_relative_segments: Box<[Box<str>]> = source_path_relative
+ .with_extension("")
+ .components()
+ .map(|s| s.as_os_str().to_str().unwrap().to_string().into_boxed_str())
+ .collect();
+
+ let output_base_path = self.fields.output_directory.join(source_path_relative).with_extension("");
+ fs::create_dir_all(output_base_path.parent().context("cannot get output directory")?)
+ .context("cannot create output directory")?;
+
+ let wrapper_file = output_base_path.with_extension("slang");
+ let output_file = output_base_path.with_extension(T::OUTPUT_EXTENSION);
+ let bindgen_file = output_base_path.with_extension("rs");
+ let cached_file = output_base_path.with_extension("cached");
+
+ let buildsystem_hash: &[u8; blake3::OUT_LEN] =
+ caching::build_system_hash().context("cannot get build system hash")?.as_bytes();
+
+ if let Ok(cached_contents) = fs::read(&cached_file)
+ && let Ok(cached) = serde_json::from_slice::<Cached>(&cached_contents)
+ && &cached.buildsystem_hash == buildsystem_hash
+ && cached.compiler_version == self.global_session.build_tag_string()
+ && cached.dependency_hashes.iter().all(|(path, hash)| {
+ fs::read(path)
+ .map(|dependency_contents| blake3::hash(&dependency_contents).as_bytes() == hash)
+ .unwrap_or(false)
+ })
+ {
+ debug_log!("compile cached: {source_path_relative_str}");
+ return Ok((source_path_relative_segments, cached.public_kernels));
+ }
+
+ let (source_module, source_diagnostics) =
+ self.session.load_module_with_diagnostics(&source_path).context("cannot load source module")?;
+
+ if let Some(source_diagnostics) = source_diagnostics {
+ for source_diagnostics_line in source_diagnostics.lines() {
+ println!("cargo::warning={source_diagnostics_line}");
+ }
+ }
+
+ let dependency_hashes = source_module
+ .dependency_file_paths()
+ .map(|d| Ok((d.into(), blake3::hash(&fs::read(d).with_context(|| format!("cannot read {d}"))?).into())))
+ .collect::<anyhow::Result<HashMap<String, [u8; blake3::OUT_LEN]>>>()
+ .context("cannot hash dependencies")?;
+
+ let kernels = source_module
+ .module_reflection()
+ .children()
+ .filter_map(|decl| SlangKernel::from_reflection(decl).transpose())
+ .collect::<anyhow::Result<Vec<SlangKernel>>>()
+ .context("cannot collect kernels")?;
+
+ if !kernels.is_empty() {
+ let constants = source_module
+ .module_reflection()
+ .children()
+ .filter_map(|decl| decl.as_variable())
+ .filter(|variable| variable.find_modifier(ModifierID::SlangModifierConst).is_some())
+ .filter_map(|variable| Some((variable.name()?.to_owned(), variable.default_value_int()?.to_string())))
+ .collect();
+ let wrapper_blocks = kernels
+ .iter()
+ .map(|kernel| {
+ wrapper::kernel_wrappers(kernel)
+ .with_context(|| format!("cannot generate wrappers for kernel '{}'", kernel.name))
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?
+ .into_iter()
+ .flatten();
+
+ let wrapper_contents = once(format!("#include {source_path:?}")).chain(wrapper_blocks).join("\n\n");
+
+ fs::write(&wrapper_file, wrapper_contents.as_bytes()).context("cannot write wrapper file")?;
+
+ let (wrapper_module, wrapper_diagnostics) =
+ self.session.load_module_with_diagnostics(&wrapper_file).context("cannot load wrapper module")?;
+
+ if let Some(wrapper_diagnostics) = wrapper_diagnostics {
+ for wrapper_diagnostics_line in wrapper_diagnostics.lines() {
+ println!("cargo::warning={wrapper_diagnostics_line}");
+ }
+ }
+
+ let entry_points =
+ wrapper_module.entry_points().map(|entry_point| entry_point.into()).collect::<Vec<ComponentType>>();
+
+ let wrapper_component: ComponentType = wrapper_module.into();
+
+ let composite_component = self
+ .session
+ .create_composite_component_type(
+ &once(wrapper_component).chain(entry_points).collect::<Vec<ComponentType>>(),
+ )
+ .context("cannot create composite component")?;
+
+ let linked_component = composite_component.link().context("cannot link wrapper module")?;
+
+ let linked_blob = linked_component.target_code(0).context("cannot get target code")?;
+
+ fs::write(&output_file, linked_blob.as_slice()).context("cannot write output file")?;
+
+ T::validate_output(&output_file).with_context(|| format!("cannot validate {}", output_file.display()))?;
+
+ let bindgen_tokens = T::bindgen_file(&linked_component, &kernels, &gpu_type_map, &constants, &output_file)
+ .context("cannot generate bindings")?;
+
+ write_tokens(bindgen_tokens, &bindgen_file).context("cannot write bindgen file")?;
+ }
+
+ let common_gpu_type_map = gpu_type_map.keys().map(|name| (name.clone(), name.clone())).collect();
+ let public_kernels = kernels
+ .iter()
+ .filter_map(|slang_kernel| {
+ slang_kernel
+ .to_common(&common_gpu_type_map)
+ .with_context(|| format!("cannot convert {} to common kernel", slang_kernel.name))
+ .transpose()
+ })
+ .collect::<anyhow::Result<Box<[Kernel]>>>()?;
+
+ fs::write(
+ &cached_file,
+ &serde_json::to_vec_pretty(&Cached {
+ buildsystem_hash: *buildsystem_hash,
+ compiler_version: self.global_session.build_tag_string().to_owned(),
+ dependency_hashes,
+ public_kernels: public_kernels.clone(),
+ })
+ .context("cannot serialize cache")?,
+ )
+ .context("cannot write cache file")?;
+
+ debug_log!("compile end: {source_path_relative_str}");
+
+ Ok((source_path_relative_segments, public_kernels))
+ }
+}
diff --git a/crates/uzu-engine/build/slang/gpu_types/gpu_type_constant.rs b/crates/uzu-engine/build/slang/gpu_types/gpu_type_constant.rs
new file mode 100644
index 000000000..78423056c
--- /dev/null
+++ b/crates/uzu-engine/build/slang/gpu_types/gpu_type_constant.rs
@@ -0,0 +1,9 @@
+use anyhow::Context;
+
+use crate::{common::gpu_types::GpuTypeConstant, slang::types::rust2slang};
+
+pub fn gpu_type_gen_constant(constant: &GpuTypeConstant) -> anyhow::Result<String> {
+ let ty = rust2slang(&constant.ty).with_context(|| format!("cannot convert {} to slang type", constant.ty))?;
+ let array_suffix = constant.array_length.as_ref().map(|length| format!("[{length}]")).unwrap_or_default();
+ Ok(format!("static const {ty} {}{array_suffix} = {};", constant.name, constant.value_expression))
+}
diff --git a/crates/uzu-engine/build/slang/gpu_types/gpu_type_enum.rs b/crates/uzu-engine/build/slang/gpu_types/gpu_type_enum.rs
new file mode 100644
index 000000000..709b7c81d
--- /dev/null
+++ b/crates/uzu-engine/build/slang/gpu_types/gpu_type_enum.rs
@@ -0,0 +1,12 @@
+use std::iter::once;
+
+use itertools::Itertools;
+
+use crate::common::gpu_types::GpuTypeEnum;
+
+pub fn gpu_type_gen_enum(gpu_type_enum: &GpuTypeEnum) -> anyhow::Result<String> {
+ Ok(once(format!("enum {} : uint32_t {{", gpu_type_enum.name.as_ref()))
+ .chain(gpu_type_enum.variants.iter().map(|variant| format!(" {} = {},", variant.name, variant.discriminant)))
+ .chain(once("};".into()))
+ .join("\n"))
+}
diff --git a/crates/uzu-engine/build/slang/gpu_types/gpu_type_option_set.rs b/crates/uzu-engine/build/slang/gpu_types/gpu_type_option_set.rs
new file mode 100644
index 000000000..bd28763f4
--- /dev/null
+++ b/crates/uzu-engine/build/slang/gpu_types/gpu_type_option_set.rs
@@ -0,0 +1,25 @@
+use std::iter::once;
+
+use anyhow::Context;
+use itertools::Itertools;
+
+use crate::{common::gpu_types::GpuTypeOptionSet, slang::types::rust2slang};
+
+/// Emit a Slang-side option-set as a struct wrapping the underlying primitive,
+/// with named static constants for each flag and a `contains()` helper,
+/// mirroring the Metal-side generation.
+pub fn gpu_type_gen_option_set(option_set: &GpuTypeOptionSet) -> anyhow::Result<String> {
+ let name = &option_set.name;
+ let underlying_slang = rust2slang(&option_set.underlying_type)
+ .with_context(|| format!("cannot convert {} to slang type", option_set.underlying_type))?;
+
+ once(Ok(format!("struct {name} {{")))
+ .chain(once(Ok(format!(" {underlying_slang} raw_value;"))))
+ .chain(option_set.variants.iter().map(|variant| {
+ Ok(format!(" static const {underlying_slang} {} = {};", variant.name, variant.value_expression))
+ }))
+ .chain(once(Ok(format!(" bool contains({underlying_slang} flag) {{ return (raw_value & flag) != 0; }}"))))
+ .chain(once(Ok(format!(" {underlying_slang} bits() {{ return raw_value; }}"))))
+ .chain(once(Ok("};".to_string())))
+ .process_results(|mut it| it.join("\n"))
+}
diff --git a/crates/uzu-engine/build/slang/gpu_types/gpu_type_struct.rs b/crates/uzu-engine/build/slang/gpu_types/gpu_type_struct.rs
new file mode 100644
index 000000000..5f20c7125
--- /dev/null
+++ b/crates/uzu-engine/build/slang/gpu_types/gpu_type_struct.rs
@@ -0,0 +1,32 @@
+use std::iter::once;
+
+use anyhow::Context;
+use itertools::Itertools;
+
+use crate::{
+ common::gpu_types::{GpuTypeStruct, GpuTypeStructFieldType},
+ slang::types::rust2slang,
+};
+
+pub fn gpu_type_gen_struct(gpu_type_struct: &GpuTypeStruct) -> anyhow::Result<String> {
+ once(Ok(format!("struct {} {{", gpu_type_struct.name.as_ref())))
+ .chain(gpu_type_struct.fields.iter().map(|field| match &field.ty {
+ GpuTypeStructFieldType::Scalar(ty) => Ok(format!(
+ " {} {};",
+ rust2slang(ty.as_ref()).with_context(|| format!("cannot convert {} to slang type", ty.as_ref()))?,
+ field.name
+ )),
+ GpuTypeStructFieldType::Array {
+ element,
+ length,
+ } => Ok(format!(
+ " {} {}[{}];",
+ rust2slang(element.as_ref())
+ .with_context(|| format!("cannot convert {} to slang type", element.as_ref()))?,
+ field.name,
+ *length
+ )),
+ }))
+ .chain(once(Ok("};".to_string())))
+ .process_results(|mut it| it.join("\n"))
+}
diff --git a/crates/uzu-engine/build/slang/gpu_types/mod.rs b/crates/uzu-engine/build/slang/gpu_types/mod.rs
new file mode 100644
index 000000000..ee5d99a39
--- /dev/null
+++ b/crates/uzu-engine/build/slang/gpu_types/mod.rs
@@ -0,0 +1,76 @@
+use std::{
+ collections::{HashMap, hash_map::Entry},
+ path::Path,
+};
+
+use anyhow::{Context, bail};
+use itertools::Itertools;
+
+use crate::common::gpu_types::{GpuType, GpuTypeFile, GpuTypes};
+
+mod gpu_type_constant;
+mod gpu_type_enum;
+mod gpu_type_option_set;
+mod gpu_type_struct;
+
+use gpu_type_constant::gpu_type_gen_constant;
+use gpu_type_enum::gpu_type_gen_enum;
+use gpu_type_option_set::gpu_type_gen_option_set;
+use gpu_type_struct::gpu_type_gen_struct;
+
+pub fn gpu_type_gen(
+ gpu_types_dir: &Path,
+ gpu_types: &GpuTypes,
+) -> anyhow::Result<HashMap<String, String>> {
+ let mut gpu_types_map = HashMap::new();
+
+ for gpu_type_file in &gpu_types.files {
+ gpu_type_gen_file(&gpu_types_dir.join(gpu_type_file.name.as_ref()).with_extension("slang"), gpu_type_file)
+ .with_context(|| format!("Cannot generate gpu types for {}", gpu_type_file.name.as_ref()))?;
+ for gpu_type in &gpu_type_file.types {
+ let name: &str = match gpu_type {
+ GpuType::Enum(gpu_type_enum) => gpu_type_enum.name.as_ref(),
+ GpuType::Struct(gpu_type_struct) => gpu_type_struct.name.as_ref(),
+ GpuType::OptionSet(gpu_type_option_set) => gpu_type_option_set.name.as_ref(),
+ GpuType::Constant(_) => continue,
+ };
+
+ match gpu_types_map.entry(name.to_string()) {
+ Entry::Occupied(_) => bail!("{name} is duplicated"),
+ Entry::Vacant(vacant) => {
+ vacant.insert(format!("crate::backends::common::gpu_types::{}::{}", gpu_type_file.name, name))
+ },
+ };
+ }
+ }
+
+ Ok(gpu_types_map)
+}
+
+fn gpu_type_gen_file(
+ file_path: &Path,
+ gpu_types_file: &GpuTypeFile,
+) -> anyhow::Result<()> {
+ let new_contents = gpu_types_file
+ .types
+ .iter()
+ .map(|gpu_type| match gpu_type {
+ GpuType::Constant(gpu_type_constant) => gpu_type_gen_constant(gpu_type_constant)
+ .with_context(|| format!("Failed to generate bindings for {gpu_type_constant:?}")),
+ GpuType::Enum(gpu_type_enum) => gpu_type_gen_enum(gpu_type_enum)
+ .with_context(|| format!("Failed to generate bindings for {gpu_type_enum:?}")),
+ GpuType::Struct(gpu_type_struct) => gpu_type_gen_struct(gpu_type_struct)
+ .with_context(|| format!("Failed to generate bindings for {gpu_type_struct:?}")),
+ GpuType::OptionSet(gpu_type_option_set) => gpu_type_gen_option_set(gpu_type_option_set)
+ .with_context(|| format!("Failed to generate bindings for {gpu_type_option_set:?}")),
+ })
+ .process_results(|mut it| it.join("\n\n"))?;
+
+ // Avoid advancing mtime if the contents are the same
+ if !std::fs::read(file_path).is_ok_and(|old_contents| old_contents == new_contents.as_bytes()) {
+ std::fs::create_dir_all(file_path.parent().unwrap()).context("cannot create output directory")?;
+ std::fs::write(file_path, new_contents).context("cannot write output")?;
+ }
+
+ Ok(())
+}
diff --git a/crates/uzu-engine/build/slang/mod.rs b/crates/uzu-engine/build/slang/mod.rs
new file mode 100644
index 000000000..0aa78c058
--- /dev/null
+++ b/crates/uzu-engine/build/slang/mod.rs
@@ -0,0 +1,14 @@
+// TODO: gigaslop, clean up
+
+mod compiler;
+mod compiler_internal;
+mod gpu_types;
+mod reflection;
+mod slang_sys_ext;
+mod types;
+mod wrapper;
+
+pub use compiler::SlangCompiler;
+pub use compiler_internal::SlangTarget;
+pub use reflection::{SlangArgumentType, SlangBufferAccess, SlangKernel, SlangParameterType};
+pub use types::{Specializer, slang2rust};
diff --git a/crates/uzu-engine/build/slang/reflection/argument.rs b/crates/uzu-engine/build/slang/reflection/argument.rs
new file mode 100644
index 000000000..c8072313a
--- /dev/null
+++ b/crates/uzu-engine/build/slang/reflection/argument.rs
@@ -0,0 +1,286 @@
+use std::{
+ borrow::Cow,
+ collections::{HashMap, hash_map::Entry},
+};
+
+use anyhow::{Context, anyhow, bail};
+use shader_slang::reflection::{UserAttribute, Variable};
+
+use crate::{
+ common::{
+ identifiers::ArgumentName,
+ kernel::{KernelArgument, KernelArgumentType, KernelBufferAccess, KernelParameter, KernelParameterType},
+ },
+ slang::types::slang2rust,
+};
+
+#[derive(Debug)]
+pub enum SlangBufferAccess {
+ Read {
+ is_constant: bool,
+ },
+ ReadWrite,
+}
+
+#[derive(Debug)]
+pub enum SlangArgumentType {
+ Buffer {
+ access_type: SlangBufferAccess,
+ condition: Option<String>,
+ },
+ Constant {
+ condition: Option<String>,
+ },
+ Specialize {
+ condition: Option<String>,
+ },
+ Axis {
+ threads: String,
+ threads_in_group: String,
+ },
+ Groups {
+ groups: String,
+ },
+ Threads {
+ threads: String,
+ },
+ ThreadContext,
+}
+
+#[derive(Debug)]
+pub struct SlangArgument {
+ pub name: String,
+ pub slang_type: String,
+ pub argument_type: SlangArgumentType,
+}
+
+impl SlangArgument {
+ pub fn from_reflection(variable: &Variable) -> anyhow::Result<Self> {
+ let name = variable.name().unwrap().to_string();
+
+ let ty = variable.ty().unwrap();
+
+ let type_name = ty.name().unwrap();
+ let type_full_name = ty.full_name().unwrap().as_str().unwrap().to_string();
+
+ let mut user_attributes = variable.user_attributes().try_fold(HashMap::new(), |mut acc, user_attributes| {
+ match acc.entry(user_attributes.name().unwrap()) {
+ Entry::Occupied(occupied) => Err(anyhow!("duplicate {} attribute", occupied.key())),
+ Entry::Vacant(vacant) => {
+ vacant.insert(user_attributes);
+ Ok(acc)
+ },
+ }
+ })?;
+
+ let get_condition = |user_attributes: &mut HashMap<&str, &UserAttribute>| {
+ let Some(optional_attribute) = user_attributes.remove("Optional") else {
+ return Ok(None);
+ };
+
+ if optional_attribute.argument_count() != 1 {
+ bail!("optional expected 1 argument, found {}", optional_attribute.argument_count());
+ }
+
+ Ok(Some(optional_attribute.argument_value_string(0).unwrap().to_string()))
+ };
+
+ let no_attributes = |user_attributes: &HashMap<&str, &UserAttribute>, name: &str| {
+ if !user_attributes.is_empty() {
+ bail!("{name} has unexpected attributes: {:?}", user_attributes.keys().copied().collect::<Vec<&str>>());
+ }
+
+ Ok(())
+ };
+
+ let argument_type = if let Some(specialize_attribute) = user_attributes.remove("Specialize") {
+ if specialize_attribute.argument_count() != 0 {
+ bail!("specialize expected no argument, found {}", specialize_attribute.argument_count());
+ }
+
+ let condition = get_condition(&mut user_attributes)?;
+ no_attributes(&user_attributes, "specialize")?;
+
+ SlangArgumentType::Specialize {
+ condition,
+ }
+ } else if let Some(axis_attribute) = user_attributes.remove("Axis") {
+ if axis_attribute.argument_count() != 2 {
+ bail!("axis expected 2 argument, found {}", axis_attribute.argument_count());
+ }
+
+ let threads = axis_attribute.argument_value_string(0).unwrap().to_string();
+ let threads_in_group = axis_attribute.argument_value_string(1).unwrap().to_string();
+
+ no_attributes(&user_attributes, "axis")?;
+
+ SlangArgumentType::Axis {
+ threads,
+ threads_in_group,
+ }
+ } else if let Some(groups_attribute) = user_attributes.remove("Groups") {
+ if groups_attribute.argument_count() != 1 {
+ bail!("groups expected 1 argument, found {}", groups_attribute.argument_count());
+ }
+
+ let groups = groups_attribute.argument_value_string(0).unwrap().to_string();
+
+ no_attributes(&user_attributes, "groups")?;
+
+ SlangArgumentType::Groups {
+ groups,
+ }
+ } else if let Some(threads_attribute) = user_attributes.remove("Threads") {
+ if threads_attribute.argument_count() != 1 {
+ bail!("threads expected 1 argument, found {}", threads_attribute.argument_count());
+ }
+
+ let threads = threads_attribute.argument_value_string(0).unwrap().to_string();
+
+ no_attributes(&user_attributes, "threads")?;
+
+ SlangArgumentType::Threads {
+ threads,
+ }
+ } else if type_name == "ThreadContext" {
+ no_attributes(&user_attributes, "thread context")?;
+
+ SlangArgumentType::ThreadContext
+ } else if type_name == "StructuredBuffer" {
+ let condition = get_condition(&mut user_attributes)?;
+ let is_constant = user_attributes.remove("Constant").is_some();
+
+ no_attributes(&user_attributes, "buffer (read-only)")?;
+
+ SlangArgumentType::Buffer {
+ access_type: SlangBufferAccess::Read {
+ is_constant,
+ },
+ condition,
+ }
+ } else if type_name == "RWStructuredBuffer" {
+ let condition = get_condition(&mut user_attributes)?;
+
+ no_attributes(&user_attributes, "buffer (read-write)")?;
+
+ SlangArgumentType::Buffer {
+ access_type: SlangBufferAccess::ReadWrite,
+ condition,
+ }
+ } else {
+ let condition = get_condition(&mut user_attributes)?;
+
+ no_attributes(&user_attributes, "constant")?;
+
+ SlangArgumentType::Constant {
+ condition,
+ }
+ };
+
+ Ok(SlangArgument {
+ name,
+ slang_type: type_full_name,
+ argument_type,
+ })
+ }
+
+ pub fn rust_type(
+ &self,
+ gpu_type_map: &HashMap<String, String>,
+ ) -> anyhow::Result<Box<str>> {
+ let slang_type = if matches!(
+ self.argument_type,
+ SlangArgumentType::Buffer {
+ access_type: SlangBufferAccess::Read {
+ is_constant: true,
+ },
+ condition: _,
+ }
+ ) {
+ let element_type = self.slang_type
+ .strip_prefix("StructuredBuffer<")
+ .and_then(|slang_type| slang_type.strip_suffix(", DefaultDataLayout>")).with_context(|| format!("buffer-constant argument doesn't match the StructuredBuffer<T, DefaultDataLayout> template: {}", self.slang_type))?;
+
+ Cow::Owned(format!("{element_type}[]"))
+ } else {
+ Cow::Borrowed(&self.slang_type)
+ };
+
+ Ok(slang2rust(&slang_type, gpu_type_map)
+ .with_context(|| format!("cannot convert slang {} to rust", self.slang_type))?
+ .to_string()
+ .into_boxed_str())
+ }
+
+ pub fn to_common_parameter(
+ &self,
+ gpu_type_map: &HashMap<String, String>,
+ ) -> anyhow::Result<Option<KernelParameter>> {
+ let SlangArgumentType::Specialize {
+ condition,
+ } = &self.argument_type
+ else {
+ return Ok(None);
+ };
+
+ Ok(Some(KernelParameter {
+ name: self.name.clone().into_boxed_str(),
+ ty: KernelParameterType::Value(if condition.is_some() {
+ format!("Option < {} >", self.rust_type(gpu_type_map)?).into_boxed_str()
+ } else {
+ self.rust_type(gpu_type_map)?
+ }),
+ }))
+ }
+
+ pub fn to_common_argument(
+ &self,
+ gpu_type_map: &HashMap<String, String>,
+ indirect_used: &mut bool,
+ ) -> anyhow::Result<Option<KernelArgument>> {
+ match &self.argument_type {
+ SlangArgumentType::Buffer {
+ access_type:
+ access_type @ (SlangBufferAccess::Read {
+ is_constant: false,
+ }
+ | SlangBufferAccess::ReadWrite),
+ condition,
+ } => Ok(Some(KernelArgument {
+ name: ArgumentName::from(self.name.clone()),
+ conditional: condition.is_some(),
+ ty: KernelArgumentType::Buffer(match *access_type {
+ SlangBufferAccess::Read {
+ is_constant: _,
+ } => KernelBufferAccess::Read,
+ SlangBufferAccess::ReadWrite => KernelBufferAccess::ReadWrite,
+ }),
+ })),
+ SlangArgumentType::Constant {
+ condition,
+ }
+ | SlangArgumentType::Buffer {
+ access_type: SlangBufferAccess::Read {
+ is_constant: true,
+ },
+ condition,
+ } => Ok(Some(KernelArgument {
+ name: ArgumentName::from(self.name.clone()),
+ conditional: condition.is_some(),
+ ty: KernelArgumentType::Constant(self.rust_type(gpu_type_map)?),
+ })),
+ SlangArgumentType::Groups {
+ groups,
+ } if !*indirect_used && groups == "INDIRECT" => {
+ *indirect_used = true;
+
+ Ok(Some(KernelArgument {
+ name: ArgumentName::from("__dsl_indirect_dispatch_buffer".to_string()),
+ conditional: false,
+ ty: KernelArgumentType::Buffer(KernelBufferAccess::Read),
+ }))
+ },
+ _ => Ok(None),
+ }
+ }
+}
diff --git a/crates/uzu-engine/build/slang/reflection/kernel.rs b/crates/uzu-engine/build/slang/reflection/kernel.rs
new file mode 100644
index 000000000..5cb768ad4
--- /dev/null
+++ b/crates/uzu-engine/build/slang/reflection/kernel.rs
@@ -0,0 +1,170 @@
+use std::collections::HashMap;
+
+use anyhow::{Context, bail};
+use itertools::Itertools;
+use shader_slang::{
+ DeclKind,
+ reflection::{Decl, UserAttribute},
+};
+
+use crate::{
+ common::{
+ constraints,
+ kernel::{Kernel, KernelArgument, KernelParameter},
+ },
+ slang::{
+ SlangParameterType,
+ reflection::{SlangArgument, SlangParameter},
+ },
+};
+
+pub struct SlangKernel {
+ pub parameters: Vec<SlangParameter>,
+ pub constraints: Vec<String>,
+ pub public: bool,
+ pub name: String,
+ pub arguments: Vec<SlangArgument>,
+}
+
+impl SlangKernel {
+ pub fn from_reflection(toplevel_decl: &Decl) -> anyhow::Result<Option<Self>> {
+ let (generic_decl, function_decl) = if toplevel_decl.kind() == DeclKind::Generic {
+ (Some(toplevel_decl), toplevel_decl.as_generic().unwrap().inner_decl().unwrap())
+ } else {
+ (None, toplevel_decl)
+ };
+
+ if function_decl.kind() != DeclKind::Func {
+ return Ok(None);
+ }
+
+ let function = function_decl.as_function().unwrap();
+ let function_attributes = function.user_attributes().collect::<Vec<&UserAttribute>>();
+
+ if !function_attributes.iter().any(|user_attribute| user_attribute.name() == Some("Kernel")) {
+ return Ok(None);
+ };
+
+ let parameters =
+ SlangParameter::from_reflection(&function_attributes, generic_decl).context("cannot collect parameters")?;
+
+ let constraints = function_attributes
+ .iter()
+ .map(|user_attribute| {
+ if user_attribute.name() == Some("Constraint") {
+ if user_attribute.argument_count() != 1 {
+ bail!("expected 1 argument, found {}", user_attribute.argument_count());
+ }
+
+ Ok(Some(
+ user_attribute
+ .argument_value_string(0)
+ .context("cannot get name argument string value")?
+ .trim()
+ .to_string(),
+ ))
+ } else {
+ Ok(None)
+ }
+ })
+ .filter_map(|r| r.transpose())
+ .collect::<anyhow::Result<Vec<String>>>()
+ .context("cannot collect constraints")?;
+
+ let public = function_attributes.iter().any(|user_attribute| user_attribute.name() == Some("Public"));
+
+ let name = function.name().unwrap().to_string();
+
+ let arguments = function
+ .parameters()
+ .map(SlangArgument::from_reflection)
+ .collect::<anyhow::Result<Vec<SlangArgument>>>()
+ .context("cannot collect arguments")?;
+
+ Ok(Some(SlangKernel {
+ parameters,
+ constraints,
+ public,
+ name,
+ arguments,
+ }))
+ }
+
+ pub fn variants(&self) -> impl Iterator<Item = Vec<(&str, &str)>> {
+ let evaluator = constraints::Constraints::new(
+ self.parameters
+ .iter()
+ .filter_map(|parameter| match &parameter.ty {
+ SlangParameterType::Type {
+ variants,
+ }
+ | SlangParameterType::Value {
+ value_type: _,
+ variants,
+ } => Some(variants.iter().map(|variant| variant.as_str())),
+ SlangParameterType::GroupShared {
+ value_type: _,
+ length: _,
+ } => None,
+ })
+ .flatten(),
+ &self.constraints,
+ );
+ self.parameters
+ .iter()
+ .filter_map(|parameter| match &parameter.ty {
+ SlangParameterType::Type {
+ variants,
+ }
+ | SlangParameterType::Value {
+ value_type: _,
+ variants,
+ } => Some(variants.iter().map(move |variant| (parameter.name.as_str(), variant.as_str()))),
+ SlangParameterType::GroupShared {
+ value_type: _,
+ length: _,
+ } => None,
+ })
+ .multi_cartesian_product()
+ .filter(move |variant| evaluator.satisfied(variant.iter().copied()))
+ }
+
+ pub fn to_common(
+ &self,
+ gpu_type_map: &HashMap<String, String>,
+ ) -> anyhow::Result<Option<Kernel>> {
+ if !self.public {
+ return Ok(None);
+ }
+
+ Ok(Some(Kernel {
+ name: self.name.clone().into(),
+ parameters: self
+ .parameters
+ .iter()
+ .filter_map(|parameter| {
+ SlangParameter::to_common(parameter, gpu_type_map)
+ .with_context(|| format!("cannot convert parameter {} to common parameter", parameter.name))
+ .transpose()
+ })
+ .chain(self.arguments.iter().filter_map(|argument| {
+ SlangArgument::to_common_parameter(argument, gpu_type_map)
+ .with_context(|| format!("cannot convert argument {} to common parameter", argument.name))
+ .transpose()
+ }))
+ .collect::<anyhow::Result<Box<[KernelParameter]>>>()?,
+ arguments: {
+ let mut indirect_used = false;
+
+ self.arguments
+ .iter()
+ .filter_map(|argument| {
+ SlangArgument::to_common_argument(argument, gpu_type_map, &mut indirect_used)
+ .with_context(|| format!("cannot convert argument {} to common argument", argument.name))
+ .transpose()
+ })
+ .collect::<anyhow::Result<Box<[KernelArgument]>>>()?
+ },
+ }))
+ }
+}
diff --git a/crates/uzu-engine/build/slang/reflection/mod.rs b/crates/uzu-engine/build/slang/reflection/mod.rs
new file mode 100644
index 000000000..ff3cc7a23
--- /dev/null
+++ b/crates/uzu-engine/build/slang/reflection/mod.rs
@@ -0,0 +1,7 @@
+mod argument;
+mod kernel;
+mod parameter;
+
+pub use argument::{SlangArgument, SlangArgumentType, SlangBufferAccess};
+pub use kernel::SlangKernel;
+pub use parameter::{SlangParameter, SlangParameterType};
diff --git a/crates/uzu-engine/build/slang/reflection/parameter.rs b/crates/uzu-engine/build/slang/reflection/parameter.rs
new file mode 100644
index 000000000..49d2d1e54
--- /dev/null
+++ b/crates/uzu-engine/build/slang/reflection/parameter.rs
@@ -0,0 +1,303 @@
+use std::collections::HashMap;
+
+use anyhow::{Context, anyhow, bail};
+use shader_slang::reflection::{Decl, UserAttribute};
+
+use crate::{
+ common::kernel::{KernelParameter, KernelParameterType},
+ slang::types::slang2rust,
+};
+
+#[derive(Debug)]
+pub enum SlangParameterType {
+ Type {
+ variants: Vec<String>,
+ },
+ GroupShared {
+ value_type: String,
+ length: String,
+ },
+ Value {
+ value_type: String,
+ variants: Vec<String>,
+ },
+}
+
+#[derive(Debug)]
+pub struct SlangParameter {
+ pub name: String,
+ pub ty: SlangParameterType,
+}
+
+impl SlangParameter {
+ pub fn from_reflection(
+ function_attributes: &[&UserAttribute],
+ generic_decl: Option<&Decl>,
+ ) -> anyhow::Result<Vec<Self>> {
+ enum ParameterAttributeType<'a> {
+ Variants {
+ variants: Vec<&'a str>,
+ },
+ GroupShared {
+ length: &'a str,
+ },
+ }
+
+ struct ParameterAttribute<'a> {
+ name: &'a str,
+ ty: ParameterAttributeType<'a>,
+ }
+
+ let parameters_attributes = function_attributes
+ .iter()
+ .map(|user_attribute| {
+ Ok(match user_attribute.name() {
+ Some("Variants") => {
+ if user_attribute.argument_count() != 2 {
+ bail!("expected 2 arguments, found {}", user_attribute.argument_count());
+ }
+
+ let name = user_attribute
+ .argument_value_string(0)
+ .context("cannot get name argument string value")?
+ .trim();
+
+ let variants = user_attribute
+ .argument_value_string(1)
+ .context("cannot get variants argument string value")?
+ .split(',')
+ .map(|variant| variant.trim())
+ .filter(|variant| !variant.is_empty())
+ .collect::<Vec<&str>>();
+
+ Some(ParameterAttribute {
+ name,
+ ty: ParameterAttributeType::Variants {
+ variants,
+ },
+ })
+ },
+ Some("GroupShared") => {
+ if user_attribute.argument_count() != 2 {
+ bail!("expected 2 arguments, found {}", user_attribute.argument_count());
+ }
+
+ let name = user_attribute
+ .argument_value_string(0)
+ .context("cannot get name argument string value")?
+ .trim();
+
+ let length = user_attribute
+ .argument_value_string(1)
+ .context("cannot get length argument string value")?
+ .trim();
+
+ Some(ParameterAttribute {
+ name,
+ ty: ParameterAttributeType::GroupShared {
+ length,
+ },
+ })
+ },
+ _ => None,
+ })
+ })
+ .filter_map(|attr| attr.transpose())
+ .collect::<anyhow::Result<Vec<_>>>()
+ .context("failed to collect parameter attributes")?;
+
+ enum ParameterGenericType {
+ Type {
+ constraints: Vec<String>,
+ },
+ Value {
+ value_type: String,
+ },
+ }
+
+ struct ParameterGeneric<'a> {
+ name: &'a str,
+ ty: ParameterGenericType,
+ }
+
+ let parameters_generics = generic_decl
+ .map(|generic_decl| -> anyhow::Result<_> {
+ let generic = generic_decl.as_generic().unwrap();
+
+ let mut generics_unordered = generic
+ .type_parameters()
+ .map(|type_parameter| {
+ (
+ type_parameter.name().unwrap(),
+ ParameterGenericType::Type {
+ constraints: (0..generic.type_parameter_constraint_count(type_parameter))
+ .map(|i| {
+ generic
+ .type_parameter_constraint_by_index(type_parameter, i)
+ .unwrap()
+ .full_name()
+ .unwrap()
+ .as_str()
+ .unwrap()
+ .to_string()
+ })
+ .collect(),
+ },
+ )
+ })
+ .chain(generic.value_parameters().map(|value_parameter| {
+ (
+ value_parameter.name().unwrap(),
+ ParameterGenericType::Value {
+ value_type: value_parameter
+ .ty()
+ .unwrap()
+ .full_name()
+ .unwrap()
+ .as_str()
+ .unwrap()
+ .to_string(),
+ },
+ )
+ }))
+ .collect::<HashMap<&str, ParameterGenericType>>();
+
+ let mut generics = Vec::with_capacity(generics_unordered.len());
+
+ for generic_name in
+ generic_decl.children().filter_map(|generic_parameter_decl| generic_parameter_decl.name())
+ {
+ if let Some(generic_type) = generics_unordered.remove(generic_name) {
+ generics.push(ParameterGeneric {
+ name: generic_name,
+ ty: generic_type,
+ });
+ }
+ }
+
+ if !generics_unordered.is_empty() {
+ bail!(
+ "generics present in parameters api but not generic decl children: {:?}",
+ generics_unordered.keys().copied().collect::<Vec<&str>>()
+ );
+ }
+
+ Ok(generics)
+ })
+ .transpose()
+ .context("failed to collect generic parameters")?
+ .unwrap_or_default();
+
+ let parameters_attributes_names =
+ parameters_attributes.iter().map(|parameter_attribute| parameter_attribute.name).collect::<Vec<&str>>();
+ let parameters_generics_names =
+ parameters_generics.iter().map(|parameter_generic| parameter_generic.name).collect::<Vec<&str>>();
+ if parameters_attributes_names != parameters_generics_names {
+ bail!(
+ "variants attributes {:?} do not match function generics {:?}",
+ parameters_attributes_names,
+ parameters_generics_names,
+ );
+ }
+
+ let parameters = parameters_attributes
+ .into_iter()
+ .zip(parameters_generics)
+ .map(|(parameter_attribute, parameter_generic)| {
+ Ok(SlangParameter {
+ name: parameter_generic.name.to_string(),
+ ty: match (parameter_generic.ty, parameter_attribute.ty) {
+ (
+ ParameterGenericType::Type {
+ constraints: _,
+ },
+ ParameterAttributeType::Variants {
+ variants,
+ },
+ ) => SlangParameterType::Type {
+ variants: variants.into_iter().map(|variant| variant.to_string()).collect(),
+ },
+ (
+ ParameterGenericType::Type {
+ constraints,
+ },
+ ParameterAttributeType::GroupShared {
+ length,
+ },
+ ) => {
+ if constraints.len() != 1 {
+ bail!(
+ "type generic associated with GroupShared must have exactly 1 constraint, found {}",
+ constraints.len()
+ );
+ }
+ let constraint = constraints[0].as_str();
+
+ SlangParameterType::GroupShared {
+ value_type: constraint
+ .strip_prefix("IGroupShared<")
+ .and_then(|s| s.strip_suffix(">"))
+ .ok_or_else(|| anyhow!("{constraint} doesn't match IGroupShared<T> pattern"))?
+ .to_string(),
+ length: length.to_string(),
+ }
+ },
+ (
+ ParameterGenericType::Value {
+ value_type,
+ },
+ ParameterAttributeType::Variants {
+ variants,
+ },
+ ) => SlangParameterType::Value {
+ value_type,
+ variants: variants.into_iter().map(|variant| variant.to_string()).collect(),
+ },
+ (
+ ParameterGenericType::Value {
+ value_type: _,
+ },
+ ParameterAttributeType::GroupShared {
+ length: _,
+ },
+ ) => bail!("value generic cannot be the target of GroupShared annotation"),
+ },
+ })
+ })
+ .collect::<anyhow::Result<Vec<SlangParameter>>>()?;
+
+ Ok(parameters)
+ }
+
+ pub fn to_common(
+ &self,
+ gpu_type_map: &HashMap<String, String>,
+ ) -> anyhow::Result<Option<KernelParameter>> {
+ let name = self.name.clone().into_boxed_str();
+
+ match &self.ty {
+ SlangParameterType::Type {
+ variants: _,
+ } => Ok(Some(KernelParameter {
+ name,
+ ty: KernelParameterType::Type,
+ })),
+ SlangParameterType::GroupShared {
+ value_type: _,
+ length: _,
+ } => Ok(None),
+ SlangParameterType::Value {
+ value_type,
+ variants: _,
+ } => Ok(Some(KernelParameter {
+ name,
+ ty: KernelParameterType::Value(
+ slang2rust(value_type, gpu_type_map)
+ .with_context(|| format!("cannot convert {value_type} to rust"))?
+ .to_string()
+ .into_boxed_str(),
+ ),
+ })),
+ }
+ }
+}
diff --git a/crates/uzu-engine/build/slang/slang_sys_ext/load_module_with_diagnostics.rs b/crates/uzu-engine/build/slang/slang_sys_ext/load_module_with_diagnostics.rs
new file mode 100644
index 000000000..3d6bf2ba4
--- /dev/null
+++ b/crates/uzu-engine/build/slang/slang_sys_ext/load_module_with_diagnostics.rs
@@ -0,0 +1,41 @@
+use std::{
+ ffi::{CString, c_void},
+ mem,
+ path::Path,
+ ptr::{NonNull, null_mut},
+};
+
+use anyhow::anyhow;
+use shader_slang::{Blob, Interface, Module, Session};
+
+pub trait SessionLoadModuleWithDiagnosticsExt {
+ fn load_module_with_diagnostics(
+ &self,
+ path: &Path,
+ ) -> anyhow::Result<(Module, Option<String>)>;
+}
+
+impl SessionLoadModuleWithDiagnosticsExt for Session {
+ fn load_module_with_diagnostics(
+ &self,
+ path: &Path,
+ ) -> anyhow::Result<(Module, Option<String>)> {
+ let path_cstr = CString::new(path.to_str().unwrap()).unwrap();
+ let mut diagnostics_ptr = null_mut();
+
+ let module_ptr = vcall!(self, loadModule(path_cstr.as_ptr(), &mut diagnostics_ptr));
+
+ let diagnostics = NonNull::new(diagnostics_ptr as *mut c_void)
+ .map(|diagnostics_ptr_nn| -> Blob { unsafe { mem::transmute(diagnostics_ptr_nn) } })
+ .map(|blob| blob.as_str().unwrap().to_owned());
+
+ let Some(module_ptr_nn) = NonNull::new(module_ptr as *mut c_void) else {
+ return Err(anyhow!("{}", diagnostics.as_deref().unwrap_or("<no diagnostics>")));
+ };
+
+ let module: Module = unsafe { mem::transmute(module_ptr_nn) };
+ unsafe { (module.as_unknown().vtable().ISlangUnknown_addRef)(module.as_raw()) };
+
+ Ok((module, diagnostics))
+ }
+}
diff --git a/crates/uzu-engine/build/slang/slang_sys_ext/mod.rs b/crates/uzu-engine/build/slang/slang_sys_ext/mod.rs
new file mode 100644
index 000000000..95d25a905
--- /dev/null
+++ b/crates/uzu-engine/build/slang/slang_sys_ext/mod.rs
@@ -0,0 +1,9 @@
+macro_rules! vcall {
+ ($self:expr, $method:ident($($args:expr),*)) => {
+ unsafe { ($self.vtable().$method)($self.as_raw(), $($args),*) }
+ };
+}
+
+mod load_module_with_diagnostics;
+
+pub use load_module_with_diagnostics::SessionLoadModuleWithDiagnosticsExt;
diff --git a/crates/uzu-engine/build/slang/types.rs b/crates/uzu-engine/build/slang/types.rs
new file mode 100644
index 000000000..5ed6f8d59
--- /dev/null
+++ b/crates/uzu-engine/build/slang/types.rs
@@ -0,0 +1,87 @@
+use std::{borrow::Cow, collections::HashMap};
+
+use itertools::Itertools;
+use regex::Regex;
+
+pub fn rust2slang(ty: &str) -> Option<&'static str> {
+ match ty {
+ "bool" => Some("bool"),
+ "i8" => Some("int8_t"),
+ "u8" => Some("uint8_t"),
+ "i16" => Some("int16_t"),
+ "u16" => Some("uint16_t"),
+ "i32" => Some("int"),
+ "u32" => Some("uint"),
+ "i64" => Some("int64_t"),
+ "u64" => Some("uint64_t"),
+ "usize" => Some("uint64_t"),
+ "isize" => Some("int64_t"),
+ "f16" => Some("half"),
+ "bf16" => Some("BFloat16"),
+ "f32" => Some("float"),
+ "f64" => Some("double"),
+ _ => None,
+ }
+}
+
+pub fn slang2rust<'a>(
+ ty: &str,
+ gpu_type_map: &'a HashMap<String, String>,
+) -> Option<Cow<'a, str>> {
+ match ty {
+ "bool" => Some(Cow::Borrowed("bool")),
+ "int8_t" => Some(Cow::Borrowed("i8")),
+ "uint8_t" => Some(Cow::Borrowed("u8")),
+ "int16_t" => Some(Cow::Borrowed("i16")),
+ "uint16_t" => Some(Cow::Borrowed("u16")),
+ "int" => Some(Cow::Borrowed("i32")),
+ "uint" => Some(Cow::Borrowed("u32")),
+ "int64_t" => Some(Cow::Borrowed("i64")),
+ "uint64_t" => Some(Cow::Borrowed("u64")),
+ "half" => Some(Cow::Borrowed("f16")),
+ "BFloat16" => Some(Cow::Borrowed("bf16")),
+ "float" => Some(Cow::Borrowed("f32")),
+ "double" => Some(Cow::Borrowed("f64")),
+ _ if let Some(ty_translated) = gpu_type_map.get(ty) => Some(Cow::Borrowed(ty_translated)),
+ _ => {
+ let (scalar_ty, size) = ty.rsplit_once('[')?;
+ let size = size.strip_suffix(']')?;
+ let elem = slang2rust(scalar_ty, gpu_type_map)?;
+ Some(Cow::Owned(if size.is_empty() {
+ format!("&[{elem}]")
+ } else {
+ let size: usize = size.parse().ok()?;
+ format!("&[{elem}; {size}]")
+ }))
+ },
+ }
+}
+
+pub struct Specializer<'a> {
+ regex: Regex,
+ map: &'a [(&'a str, &'a str)],
+}
+
+impl<'a> Specializer<'a> {
+ pub fn new(map: &'a [(&'a str, &'a str)]) -> Self {
+ let regex =
+ Regex::new(&format!(r"\b(?:{})\b", map.iter().map(|(key, _value)| regex::escape(key)).join("|"))).unwrap();
+
+ Self {
+ regex,
+ map,
+ }
+ }
+
+ pub fn specialize<'b>(
+ &self,
+ generic_type: &'b str,
+ ) -> Cow<'b, str> {
+ if self.map.is_empty() {
+ return Cow::Borrowed(generic_type);
+ }
+ self.regex.replace_all(generic_type, |c: &regex::Captures| {
+ self.map.iter().find_map(|(key, value)| (*key == &c[0]).then_some(*value)).unwrap()
+ })
+ }
+}
diff --git a/crates/uzu-engine/build/slang/wrapper.rs b/crates/uzu-engine/build/slang/wrapper.rs
new file mode 100644
index 000000000..9b60c9ba6
--- /dev/null
+++ b/crates/uzu-engine/build/slang/wrapper.rs
@@ -0,0 +1,296 @@
+use std::{borrow::Cow, iter::repeat_n};
+
+use anyhow::bail;
+use itertools::Itertools;
+
+use crate::{
+ common::mangling,
+ slang::{
+ reflection::{SlangArgumentType, SlangKernel, SlangParameterType},
+ types::Specializer,
+ },
+};
+
+pub fn kernel_wrappers(kernel: &SlangKernel) -> anyhow::Result<Vec<String>> {
+ let inner_function_name = kernel.name.as_str();
+
+ let mut wrappers = Vec::new();
+
+ let mut wrapper = Vec::new();
+ for specialize in &kernel.arguments {
+ let SlangArgumentType::Specialize {
+ ..
+ } = &specialize.argument_type
+ else {
+ continue;
+ };
+
+ wrapper.push("[SpecializationConstant]".to_string());
+ wrapper.push(format!("const {} {}_specialize_{};", specialize.slang_type, kernel.name, specialize.name));
+ wrapper.push(String::new());
+ }
+ wrappers.push(wrapper.into_iter().join("\n"));
+
+ for variant in kernel.variants() {
+ let outer_function_name =
+ mangling::static_mangle(inner_function_name, variant.iter().map(|(_key, value)| *value));
+ let specialization_names = kernel
+ .arguments
+ .iter()
+ .filter(|argument| matches!(argument.argument_type, SlangArgumentType::Specialize { .. }))
+ .map(|argument| (argument.name.as_str(), format!("{}_specialize_{}", kernel.name, argument.name)))
+ .collect::<Vec<_>>();
+ let substitutions = variant
+ .iter()
+ .copied()
+ .chain(specialization_names.iter().map(|(name, symbol)| (*name, symbol.as_str())))
+ .collect::<Vec<_>>();
+ let specializer = Specializer::new(&substitutions);
+
+ let mut wrapper = Vec::new();
+
+ for parameter in &kernel.parameters {
+ let SlangParameterType::GroupShared {
+ value_type,
+ length,
+ } = &parameter.ty
+ else {
+ continue;
+ };
+
+ let base_name = format!("{}_groupshared_{}", outer_function_name, parameter.name);
+ let value_type = specializer.specialize(value_type);
+ let length = specializer.specialize(length);
+
+ wrapper.push(format!("groupshared {value_type} {base_name}_var[{length}];"));
+ wrapper.push(String::new());
+ wrapper.push(format!("struct {base_name}_Struct: IGroupShared<{value_type}> {{"));
+ wrapper.push(format!(" static func load(uint idx) -> {value_type} {{"));
+ wrapper.push(format!(" return {base_name}_var[idx];"));
+ wrapper.push(" }".to_string());
+ wrapper.push(format!(" static func store(uint idx, {value_type} value) {{"));
+ wrapper.push(format!(" {base_name}_var[idx] = value;"));
+ wrapper.push(" }".to_string());
+ wrapper.push("};".to_string());
+ wrapper.push(String::new());
+ }
+
+ let mut numthreads = kernel
+ .arguments
+ .iter()
+ .filter_map(|argument| match &argument.argument_type {
+ SlangArgumentType::Axis {
+ threads: _,
+ threads_in_group,
+ } => Some(specializer.specialize(threads_in_group)),
+ SlangArgumentType::Threads {
+ threads,
+ } => Some(specializer.specialize(threads)),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+
+ if numthreads.len() > 3 {
+ bail!("numthreads cannot be more than 3d: {numthreads:?}");
+ }
+
+ numthreads.extend(repeat_n(Cow::Borrowed("1"), 3 - numthreads.len()));
+
+ wrapper.push("[shader(\"compute\")]".to_string());
+ wrapper.push(format!("[numthreads({})]", numthreads.join(", ")));
+ wrapper.push(format!("func {outer_function_name}("));
+
+ let mut has_axis = false;
+ let mut has_groups = false;
+ let mut has_threads = false;
+
+ for argument in &kernel.arguments {
+ match &argument.argument_type {
+ SlangArgumentType::Buffer {
+ ..
+ } => {
+ wrapper.push(format!(" {} {},", specializer.specialize(&argument.slang_type), argument.name));
+ },
+ SlangArgumentType::Constant {
+ ..
+ } => {
+ wrapper.push(format!(
+ " uniform {} {},",
+ specializer.specialize(&argument.slang_type),
+ argument.name
+ ));
+ },
+ SlangArgumentType::Axis {
+ ..
+ } if !has_axis => {
+ has_axis = true;
+ wrapper.push(" uint3 __dsl_axis_idx : SV_DispatchThreadID,".to_string());
+ },
+ SlangArgumentType::Groups {
+ ..
+ } if !has_groups => {
+ has_groups = true;
+ wrapper.push(" uint3 __dsl_groups_idx : SV_GroupID,".to_string());
+ },
+ SlangArgumentType::Threads {
+ ..
+ } if !has_threads => {
+ has_threads = true;
+ wrapper.push(" uint3 __dsl_threads_idx : SV_GroupThreadID,".to_string());
+ },
+ _ => (),
+ };
+ }
+
+ if has_axis && (has_groups || has_threads) {
+ bail!("Cannot mix axis and groups/threads");
+ }
+
+ wrapper.push(") {".to_string());
+ if has_axis {
+ let axis_guards = kernel
+ .arguments
+ .iter()
+ .filter_map(|argument| match &argument.argument_type {
+ SlangArgumentType::Axis {
+ threads,
+ threads_in_group: _,
+ } => Some(specializer.specialize(&slang_axis_expr(threads, kernel)).into_owned()),
+ _ => None,
+ })
+ .zip(["x", "y", "z"])
+ .map(|(threads, axis)| format!("__dsl_axis_idx.{axis} >= uint({threads})"))
+ .join(" || ");
+ wrapper.push(format!(" if ({axis_guards}) {{ return; }}"));
+ }
+
+ let inner_function_parameters = kernel
+ .parameters
+ .iter()
+ .map(|parameter| match &parameter.ty {
+ SlangParameterType::Type {
+ ..
+ }
+ | SlangParameterType::Value {
+ ..
+ } => specializer.specialize(&parameter.name),
+ SlangParameterType::GroupShared {
+ ..
+ } => Cow::Owned(format!("{}_groupshared_{}_Struct", outer_function_name, parameter.name)),
+ })
+ .collect::<Vec<_>>();
+
+ let mut group_axis_letters = ["x", "y", "z"].iter();
+ let mut thread_axis_letters = ["x", "y", "z"].iter();
+ let inner_function_arguments = kernel
+ .arguments
+ .iter()
+ .map(|argument| match &argument.argument_type {
+ SlangArgumentType::Buffer {
+ ..
+ }
+ | SlangArgumentType::Constant {
+ ..
+ } => argument.name.to_string(),
+ SlangArgumentType::Specialize {
+ ..
+ } => {
+ format!("{}_specialize_{}", kernel.name, argument.name)
+ },
+ SlangArgumentType::Axis {
+ ..
+ } => format!("__dsl_axis_idx.{}", group_axis_letters.next().unwrap()),
+ SlangArgumentType::Groups {
+ ..
+ } => format!("__dsl_groups_idx.{}", group_axis_letters.next().unwrap()),
+ SlangArgumentType::Threads {
+ ..
+ } => format!("__dsl_threads_idx.{}", thread_axis_letters.next().unwrap()),
+ SlangArgumentType::ThreadContext => "ThreadContext()".to_string(),
+ })
+ .collect::<Vec<_>>();
+
+ if inner_function_parameters.is_empty() {
+ wrapper.push(format!(" {inner_function_name}({});", inner_function_arguments.into_iter().join(", ")));
+ } else {
+ wrapper.push(format!(
+ " {inner_function_name}<{}>({});",
+ inner_function_parameters.into_iter().join(", "),
+ inner_function_arguments.into_iter().join(", ")
+ ));
+ }
+
+ wrapper.push("}".to_string());
+
+ wrappers.push(wrapper.into_iter().join("\n"));
+ }
+
+ Ok(wrappers)
+}
+
+fn slang_axis_expr(
+ expr: &str,
+ kernel: &SlangKernel,
+) -> String {
+ let expr = rewrite_slang_method(expr, "unwrap_or", |receiver, fallback| {
+ let condition = kernel
+ .arguments
+ .iter()
+ .find_map(|argument| {
+ if argument.name != receiver {
+ return None;
+ }
+ match &argument.argument_type {
+ SlangArgumentType::Constant {
+ condition,
+ } => condition.as_deref(),
+ _ => None,
+ }
+ })
+ .expect("unwrap_or receiver must be an optional constant");
+ format!("(({condition}) ? ({receiver}) : ({fallback}))")
+ });
+ let expr = rewrite_slang_method(&expr, "div_ceil", |receiver, argument| {
+ format!("(({receiver}) / ({argument}) + uint(({receiver}) % ({argument}) != 0))")
+ });
+ let expr =
+ rewrite_slang_method(&expr, "saturating_mul", |receiver, argument| format!("(({receiver}) * ({argument}))"));
+
+ rewrite_slang_method(&expr, "saturating_sub", |receiver, argument| {
+ format!("(({receiver}) > ({argument}) ? ({receiver}) - ({argument}) : 0)")
+ })
+}
+
+fn rewrite_slang_method(
+ expr: &str,
+ method: &str,
+ rewrite: impl Fn(&str, &str) -> String,
+) -> String {
+ let pattern = format!(".{method}(");
+ let Some(dot) = expr.find(&pattern) else {
+ return expr.to_string();
+ };
+
+ let receiver_start = expr[..dot].rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).map_or(0, |idx| idx + 1);
+ let argument_start = dot + pattern.len();
+ let mut depth = 1;
+ let mut argument_end = argument_start;
+ for (offset, ch) in expr[argument_start..].char_indices() {
+ match ch {
+ '(' => depth += 1,
+ ')' => {
+ depth -= 1;
+ if depth == 0 {
+ argument_end = argument_start + offset;
+ break;
+ }
+ },
+ _ => (),
+ }
+ }
+
+ let receiver = &expr[receiver_start..dot];
+ let argument = &expr[argument_start..argument_end];
+ let rewritten = rewrite(receiver, argument);
+ format!("{}{}{}", &expr[..receiver_start], rewritten, &expr[argument_end + 1..])
+}
diff --git a/crates/uzu-engine/build/webgpu/bindgen_file.rs b/crates/uzu-engine/build/webgpu/bindgen_file.rs
new file mode 100644
index 000000000..9ce77eba9
--- /dev/null
+++ b/crates/uzu-engine/build/webgpu/bindgen_file.rs
@@ -0,0 +1,872 @@
+use std::{
+ collections::{HashMap, hash_map::Entry},
+ path::Path,
+};
+
+use anyhow::{Context, bail, ensure};
+use proc_macro2::TokenStream;
+use quote::{format_ident, quote};
+use shader_slang::{
+ ComponentType, LayoutRules, ParameterCategory, TypeKind,
+ reflection::{Shader, TypeLayout},
+};
+use syn::{Expr, Ident, Type};
+
+use crate::{
+ common::{kernel::KernelParameterType, mangling::static_mangle},
+ slang::{SlangArgumentType, SlangBufferAccess, SlangKernel, SlangParameterType, Specializer, slang2rust},
+};
+
+pub fn bindgen_file(
+ linked_component: &ComponentType,
+ kernels: &[SlangKernel],
+ gpu_type_map: &HashMap<String, String>,
+ constants: &HashMap<String, String>,
+ object_file: &Path,
+) -> anyhow::Result<TokenStream> {
+ let shader = linked_component.layout(0).context("cannot get layout")?;
+ let object_file = object_file.to_str().unwrap();
+ let object_constant = format_ident!("WGSL_{}", blake3::hash(object_file.as_bytes()).to_hex().to_uppercase());
+
+ let generated_kernels = kernels
+ .iter()
+ .map(|kernel| bindgen_kernel(linked_component, shader, kernel, gpu_type_map, constants, &object_constant))
+ .collect::<anyhow::Result<Vec<TokenStream>>>()?;
+
+ Ok(quote! {
+ #[allow(dead_code)]
+ const #object_constant: &str = include_str!(#object_file);
+
+ #(#generated_kernels)*
+ })
+}
+
+fn bindgen_kernel(
+ linked_component: &ComponentType,
+ shader: &Shader,
+ kernel: &SlangKernel,
+ gpu_type_map: &HashMap<String, String>,
+ constants: &HashMap<String, String>,
+ object_constant: &Ident,
+) -> anyhow::Result<TokenStream> {
+ let kernel_trait_name = format_ident!("{}Kernel", kernel.name.as_str());
+ let kernel_struct_name = format_ident!("{}WebGPUKernel", kernel.name.as_str());
+
+ let globals = shader.global_params_type_layout().unwrap();
+
+ struct SpecializationConstant {
+ index: usize,
+ value: TokenStream,
+ }
+
+ let (
+ kernel_new_arguments_definitions,
+ wrapper_new_arguments_definitions,
+ kernel_new_match_arguments,
+ kernel_wrapper_new_arguments,
+ specialization_constants,
+ ) = kernel
+ .parameters
+ .iter()
+ .map(|parameter| match &parameter.ty {
+ SlangParameterType::Type {
+ variants: _,
+ } => {
+ let name = format_ident!("{}", parameter.name.as_str());
+ Ok(Some((
+ quote! { #[allow(non_snake_case, unused)] #name: crate::data_type::DataType },
+ None,
+ Some(quote! { #name }),
+ None,
+ None,
+ )))
+ },
+ SlangParameterType::Value {
+ value_type,
+ variants: _,
+ } => {
+ let name = format_ident!("{}", parameter.name.as_str());
+
+ let ty: Type = slang2rust(value_type, gpu_type_map)
+ .with_context(|| format!("cannot convert to rust the type of parameter {}", parameter.name))
+ .and_then(|ty| {
+ syn::parse_str(&ty)
+ .with_context(|| format!("cannot parse the type of parameter {}", parameter.name))
+ })?;
+
+ Ok(Some((
+ quote! { #[allow(non_snake_case, unused)] #name: #ty },
+ None,
+ Some(quote! { #name }),
+ None,
+ None,
+ )))
+ },
+ SlangParameterType::GroupShared {
+ ..
+ } => Ok(None),
+ })
+ .chain(kernel.arguments.iter().map(|argument| {
+ if let SlangArgumentType::Specialize {
+ condition,
+ } = &argument.argument_type
+ {
+ let slang_name = format!("{}_specialize_{}", kernel.name, argument.name.as_str());
+ let wgsl_idx = globals
+ .field_by_index(globals.find_field_index_by_name(&slang_name) as u32)
+ .unwrap()
+ .offset(ParameterCategory::SpecializationConstant);
+ let name = format_ident!("{}", argument.name.as_str());
+ let scalar = if gpu_type_map.contains_key(&argument.slang_type) || argument.slang_type == "bool" {
+ quote! { value as i64 as f64 }
+ } else {
+ quote! { value as f64 }
+ };
+ let value = if condition.is_some() {
+ quote! { #name.map_or(0.0, |value| #scalar) }
+ } else {
+ quote! { { let value = #name; #scalar } }
+ };
+ let ty: Type = argument.rust_type(gpu_type_map).and_then(|ty| {
+ syn::parse_str(&ty).with_context(|| format!("cannot parse the type of argument {}", argument.name))
+ })?;
+ let ty = if condition.is_some() {
+ quote! { Option<#ty> }
+ } else {
+ quote! { #ty }
+ };
+ Ok(Some((
+ quote! { #[allow(unused)] #name: #ty },
+ Some(quote! { #[allow(unused)] #name: #ty }),
+ None,
+ Some(quote! { #name }),
+ Some(SpecializationConstant {
+ index: wgsl_idx,
+ value,
+ }),
+ )))
+ } else {
+ Ok(None)
+ }
+ }))
+ .filter_map(|x| x.transpose())
+ .collect::<anyhow::Result<(
+ Vec<TokenStream>,
+ Vec<Option<TokenStream>>,
+ Vec<Option<TokenStream>>,
+ Vec<Option<TokenStream>>,
+ Vec<Option<SpecializationConstant>>,
+ )>>()?;
+ let wrapper_new_arguments_definitions =
+ wrapper_new_arguments_definitions.into_iter().flatten().collect::<Vec<TokenStream>>();
+ let kernel_new_match_arguments = kernel_new_match_arguments.into_iter().flatten().collect::<Vec<TokenStream>>();
+ let kernel_wrapper_new_arguments = kernel_wrapper_new_arguments.into_iter().flatten().collect::<Vec<TokenStream>>();
+ let specialization_constants = specialization_constants.into_iter().flatten().collect::<Vec<_>>();
+
+ let mut indirect_used = false;
+
+ let (kernel_encode_arguments_definitions, wrapper_encode_arguments_definitions, kernel_wrapper_call_arguments) = kernel
+ .arguments
+ .iter()
+ .map(|argument| {
+ match &argument.argument_type {
+ SlangArgumentType::Buffer {
+ access_type: _,
+ condition,
+ }
+ | SlangArgumentType::Constant {
+ condition,
+ } => {
+ let argument_name = format_ident!("{}", argument.name);
+
+ let (mut kernel_argument_type, mut wrapper_argument_type, mut kernel_wrapper_call_argument) = match &argument.argument_type {
+ SlangArgumentType::Buffer {
+ access_type:
+ access_type @ (SlangBufferAccess::Read {
+ is_constant: false,
+ }
+ | SlangBufferAccess::ReadWrite),
+ condition: _,
+ } => {
+ let buffer_arg_type = match access_type {
+ SlangBufferAccess::Read { .. } => quote! { BufferRef },
+ SlangBufferAccess::ReadWrite => quote! { BufferMut },
+ };
+
+ (
+ quote! { impl crate::backends::common::#buffer_arg_type<Backend = crate::backends::webgpu::WebGPU> },
+ quote! { (&wgpu::Buffer, usize, usize) },
+ Some(quote! { { let (buffer, range) = #argument_name.parts(); binding_parts(buffer, range) } }),
+ )
+ },
+ SlangArgumentType::Constant {
+ condition: _,
+ }
+ | SlangArgumentType::Buffer {
+ access_type:
+ SlangBufferAccess::Read {
+ is_constant: true,
+ },
+ condition: _,
+ } => {
+ let ty: Type = argument.rust_type(gpu_type_map).and_then(|ty| {
+ syn::parse_str(&ty).with_context(|| format!("cannot parse the type of argument {}", argument.name))
+ })?;
+
+ (quote! { #ty }, quote! { #ty }, None)
+ },
+ _ => unreachable!(),
+ };
+
+ if let Some(_condition) = condition {
+ kernel_argument_type = quote! { Option<#kernel_argument_type> };
+ wrapper_argument_type = quote! { Option<#wrapper_argument_type> };
+ kernel_wrapper_call_argument = kernel_wrapper_call_argument.map(|conversion| {
+ quote! { #argument_name.map(|#argument_name| #conversion) }
+ });
+ }
+
+ let kernel_wrapper_call_argument = kernel_wrapper_call_argument.unwrap_or_else(|| quote! { #argument_name });
+
+ Ok(Some((
+ quote! { #argument_name: #kernel_argument_type },
+ quote! { #[allow(unused)] #argument_name: #wrapper_argument_type },
+ quote! { #kernel_wrapper_call_argument },
+ )))
+ },
+ SlangArgumentType::Groups { groups } if !indirect_used && groups == "INDIRECT" => {
+ indirect_used = true;
+
+ Ok(Some((
+ quote! { __dsl_indirect_dispatch_buffer: impl crate::backends::common::BufferRef<Backend = crate::backends::webgpu::WebGPU> },
+ quote! { #[allow(unused)] __dsl_indirect_dispatch_buffer: (&wgpu::Buffer, usize, usize) },
+ quote! { { let (buffer, range) = __dsl_indirect_dispatch_buffer.parts(); binding_parts(buffer, range) } },
+ )))
+ },
+ _ => Ok(None)
+ }
+ })
+ .filter_map(|x| x.transpose())
+ .collect::<anyhow::Result<(Vec<TokenStream>, Vec<TokenStream>, Vec<TokenStream>)>>()?;
+
+ let wrapper_trait_name = format_ident!("{}KernelTrait", kernel.name.as_str());
+
+ let mut wrappers = Vec::new();
+ let mut kernel_new_match_arms: Vec<TokenStream> = Vec::new();
+
+ for variant in kernel.variants() {
+ let specialization_fields = kernel
+ .arguments
+ .iter()
+ .filter(|argument| matches!(argument.argument_type, SlangArgumentType::Specialize { .. }))
+ .map(|argument| (argument.name.as_str(), format!("self.{}", argument.name)))
+ .collect::<Vec<_>>();
+ let substitutions = variant
+ .iter()
+ .copied()
+ .chain(specialization_fields.iter().map(|(name, field)| (*name, field.as_str())))
+ .chain(gpu_type_map.iter().map(|(name, path)| (name.as_str(), path.as_str())))
+ .chain(constants.iter().map(|(name, value)| (name.as_str(), value.as_str())))
+ .collect::<Vec<_>>();
+ let specializer = Specializer::new(&substitutions);
+ let mangled_name = static_mangle(&kernel.name, variant.iter().map(|(_k, v)| *v));
+ let wrapper_struct_name = format_ident!("{}KernelWrapper{}", kernel.name.as_str(), mangled_name);
+
+ let (entry_point_index, entry_point) = shader
+ .entry_points()
+ .enumerate()
+ .find(|(_, entry_point)| entry_point.name() == Some(mangled_name.as_str()))
+ .with_context(|| format!("cannot get entry point {mangled_name}"))?;
+ let metadata = linked_component
+ .entry_point_metadata(entry_point_index as i64, 0)
+ .with_context(|| format!("cannot get metadata for entry point {mangled_name}"))?;
+ let binding_base = entry_point.var_layout().unwrap().binding_index() as usize;
+
+ enum BindGroupEntryBindingType {
+ StorageBuffer {
+ read_only: bool,
+ },
+ UniformBuffer,
+ }
+
+ #[derive(Debug)]
+ pub enum SourceTypeKind {
+ Struct {
+ fields: Vec<(String, usize, SourceType)>,
+ },
+ Array {
+ element_type: Box<SourceType>,
+ element_stride: usize,
+ length: usize,
+ },
+ Scalar,
+ }
+
+ #[derive(Debug)]
+ pub struct SourceType {
+ kind: SourceTypeKind,
+ size: usize,
+ }
+
+ impl SourceType {
+ fn from_type_layout(type_layout: &TypeLayout) -> anyhow::Result<Self> {
+ let type_categories = type_layout.categories().collect::<Vec<_>>();
+ ensure!(&type_categories == &[ParameterCategory::Uniform]);
+
+ let kind = match type_layout.kind() {
+ TypeKind::Struct => {
+ let fields = type_layout
+ .fields()
+ .map(|field| {
+ Ok((
+ field.name().unwrap().to_string(),
+ field.offset(ParameterCategory::Uniform),
+ Self::from_type_layout(field.type_layout().unwrap())?,
+ ))
+ })
+ .collect::<anyhow::Result<_>>()?;
+
+ SourceTypeKind::Struct {
+ fields,
+ }
+ },
+ TypeKind::Array => {
+ let element_type = Self::from_type_layout(type_layout.element_type_layout().unwrap())?;
+
+ SourceTypeKind::Array {
+ element_type: Box::new(element_type),
+ element_stride: type_layout.element_stride(ParameterCategory::Uniform),
+ length: type_layout.element_count().unwrap(),
+ }
+ },
+ TypeKind::Scalar => SourceTypeKind::Scalar,
+ type_layout_kind => bail!("unexpected type layout kind: {type_layout_kind:?}"),
+ };
+
+ let size = type_layout.size(ParameterCategory::Uniform);
+
+ Ok(Self {
+ kind,
+ size,
+ })
+ }
+
+ fn generate_write(
+ &self,
+ destination: TokenStream,
+ source: TokenStream,
+ ) -> TokenStream {
+ self.generate_write_with_depth(destination, source, 0)
+ }
+
+ fn generate_write_with_depth(
+ &self,
+ destination: TokenStream,
+ source: TokenStream,
+ depth: usize,
+ ) -> TokenStream {
+ match &self.kind {
+ SourceTypeKind::Struct {
+ fields,
+ } => {
+ let writes = fields.iter().map(|(field_name, field_offset, field_type)| {
+ let field_ident = format_ident!("{}", field_name);
+ field_type.generate_write_with_depth(
+ quote! { #destination[#field_offset..] },
+ quote! { #source.#field_ident },
+ depth,
+ )
+ });
+
+ quote! { #(#writes)* }
+ },
+ SourceTypeKind::Array {
+ element_type,
+ element_stride,
+ length,
+ } => {
+ let index_ident = format_ident!("__dsl_index_{depth}");
+ let next_depth = depth + 1;
+ let element_write = element_type.generate_write_with_depth(
+ quote! { #destination[#index_ident * #element_stride..] },
+ quote! { #source[#index_ident] },
+ next_depth,
+ );
+
+ quote! {
+ for #index_ident in 0..#length {
+ #element_write
+ }
+ }
+ },
+ SourceTypeKind::Scalar => {
+ let size = self.size;
+
+ quote! {
+ {
+ let __dsl_source = &(#source);
+ let __dsl_source_bytes = unsafe {
+ std::slice::from_raw_parts(
+ __dsl_source as *const _ as *const u8,
+ std::mem::size_of_val(__dsl_source),
+ )
+ };
+ debug_assert!(__dsl_source_bytes.len() <= #size);
+ #destination[..__dsl_source_bytes.len()].copy_from_slice(__dsl_source_bytes);
+ }
+ }
+ },
+ }
+ }
+ }
+
+ enum BindGroupEntrySourceType {
+ Buffer {
+ conditional: bool,
+ },
+ Constant {
+ buffer_size: usize,
+ fields: Vec<(usize, String, bool, SourceType)>,
+ },
+ Slice {
+ element_type: SourceType,
+ },
+ }
+
+ struct BindGroupEntry {
+ buffer_name: String,
+ binding_type: BindGroupEntryBindingType,
+ source_type: BindGroupEntrySourceType,
+ }
+
+ let mut dsl_uniform_index = 0;
+ let mut bind_group_entries = HashMap::new();
+
+ for parameter in entry_point.parameters() {
+ let parameter_name = parameter.name().unwrap();
+ let parameter_category = parameter.category().unwrap();
+
+ let kernel_argument = kernel.arguments.iter().find(|argument| argument.name == parameter_name);
+
+ match parameter_category {
+ ParameterCategory::DescriptorTableSlot => {
+ let SlangArgumentType::Buffer {
+ access_type,
+ condition,
+ } = &kernel_argument.unwrap().argument_type
+ else {
+ unreachable!();
+ };
+
+ let binding = binding_base + parameter.offset(ParameterCategory::DescriptorTableSlot);
+
+ let Entry::Vacant(vacant) = bind_group_entries.entry(binding as u32) else {
+ bail!("binding {binding} repeated")
+ };
+
+ let buffer_name = parameter_name.to_string();
+
+ let read_only = matches!(access_type, SlangBufferAccess::Read { .. });
+
+ let source_type = if matches!(
+ access_type,
+ SlangBufferAccess::Read {
+ is_constant: true
+ }
+ ) {
+ let element_type = parameter.type_layout().unwrap().resource_result_type().unwrap();
+ let element_type_layout =
+ shader.type_layout(element_type, LayoutRules::DefaultStructuredBuffer).unwrap();
+
+ BindGroupEntrySourceType::Slice {
+ element_type: SourceType::from_type_layout(element_type_layout)?,
+ }
+ } else {
+ BindGroupEntrySourceType::Buffer {
+ conditional: condition.is_some(),
+ }
+ };
+
+ vacant.insert(BindGroupEntry {
+ buffer_name,
+ binding_type: BindGroupEntryBindingType::StorageBuffer {
+ read_only,
+ },
+ source_type,
+ });
+ },
+ ParameterCategory::Uniform => {
+ let SlangArgumentType::Constant {
+ condition,
+ } = &kernel_argument.unwrap().argument_type
+ else {
+ unreachable!();
+ };
+
+ let binding = binding_base + parameter.offset(ParameterCategory::DescriptorTableSlot);
+ let offset = parameter.offset(ParameterCategory::Uniform);
+
+ let source_type = SourceType::from_type_layout(parameter.type_layout().unwrap())?;
+ let field_buffer_size = (offset + source_type.size).next_multiple_of(16);
+
+ match bind_group_entries.entry(binding as u32) {
+ Entry::Occupied(mut occupied) => {
+ if !matches!(occupied.get().binding_type, BindGroupEntryBindingType::UniformBuffer) {
+ bail!("binding {binding} repeated as uniform and non-uniform")
+ }
+ let BindGroupEntrySourceType::Constant {
+ buffer_size,
+ fields,
+ } = &mut occupied.get_mut().source_type
+ else {
+ bail!("binding {binding} repeated as buffer and constant")
+ };
+ *buffer_size = usize::max(*buffer_size, field_buffer_size);
+ fields.push((offset, parameter_name.to_string(), condition.is_some(), source_type))
+ },
+ Entry::Vacant(vacant) => {
+ let buffer_name = format!("__dsl_uniform_{}", dsl_uniform_index);
+ dsl_uniform_index += 1;
+
+ vacant.insert(BindGroupEntry {
+ buffer_name,
+ binding_type: BindGroupEntryBindingType::UniformBuffer,
+ source_type: BindGroupEntrySourceType::Constant {
+ buffer_size: field_buffer_size,
+ fields: vec![(
+ offset,
+ parameter_name.to_string(),
+ condition.is_some(),
+ source_type,
+ )],
+ },
+ });
+ },
+ }
+ },
+ ParameterCategory::None => (),
+ parameter_category => panic!("unsupported parameter category: {parameter_category:?}"),
+ }
+ }
+
+ let mut bind_group_entries = bind_group_entries.into_iter().collect::<Vec<_>>();
+ bind_group_entries.sort_by_key(|(idx, _)| *idx);
+
+ let bind_group_layout_entries = bind_group_entries.iter().map(|(binding, entry)| {
+ let buffer_binding_type = match entry.binding_type {
+ BindGroupEntryBindingType::StorageBuffer {
+ read_only,
+ } => {
+ quote! { wgpu::BufferBindingType::Storage { read_only: #read_only } }
+ },
+ BindGroupEntryBindingType::UniformBuffer => quote! { wgpu::BufferBindingType::Uniform },
+ };
+
+ quote! {
+ wgpu::BindGroupLayoutEntry {
+ binding: #binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: #buffer_binding_type,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }
+ }
+ });
+
+ let (prologue, bind_group_entries) = bind_group_entries.iter().map(|(binding, entry)| {
+ let buffer_name_ident = format_ident!("{}", entry.buffer_name);
+
+ let prologue = match &entry.source_type {
+ BindGroupEntrySourceType::Buffer { conditional: true } => {
+ let (buffer_maybe_mut, buffer_arg_type, buffer_ref_type) = if matches!(entry.binding_type, BindGroupEntryBindingType::StorageBuffer { read_only: false }) {
+ (quote!{ mut }, quote! { BufferMut }, quote! { as_mut })
+ } else {
+ (quote! {}, quote! { BufferRef }, quote! { as_ref })
+ };
+
+ Some(quote! {
+ let #buffer_maybe_mut __dsl_dummy_allocation = #buffer_name_ident.is_none().then(|| encoder.allocate_scratch(256).unwrap());
+ let #buffer_name_ident = #buffer_name_ident.unwrap_or_else(|| {
+ use crate::backends::common::#buffer_arg_type;
+
+ { let (buffer, range) = (__dsl_dummy_allocation.#buffer_ref_type().unwrap()).parts(); binding_parts(buffer, range) }
+ });
+ })
+ }
+ BindGroupEntrySourceType::Constant { buffer_size, fields } => {
+ let field_writes = fields.iter().map(|(offset, name, conditional, source_type)| {
+ let name = format_ident!("{}", name);
+ let write = source_type.generate_write(quote! { buffer_slice[#offset..] }, quote! { #name });
+
+ if *conditional {
+ quote! {
+ if let Some(#name) = #name {
+ #write
+ }
+ }
+ } else {
+ write
+ }
+ });
+
+ Some(quote! {
+ let mut __dsl_allocation = encoder.allocate_constant(#buffer_size).unwrap();
+ let #buffer_name_ident = {
+ use crate::backends::common::{BufferRef, CpuBuffer};
+
+ let buffer_slice = __dsl_allocation.as_slice_mut::<u8>();
+
+ buffer_slice.fill(0);
+ #(#field_writes)*
+
+ { let (buffer, range) = (&__dsl_allocation).parts(); binding_parts(buffer, range) }
+ };
+ })
+ }
+ BindGroupEntrySourceType::Slice { element_type } => {
+ let element_size = element_type.size;
+ let element_write = element_type.generate_write(
+ quote! { buffer_slice[__dsl_offset..] },
+ quote! { #buffer_name_ident[__dsl_index] },
+ );
+
+ Some(quote! {
+ let mut __dsl_allocation = encoder.allocate_constant(#element_size * #buffer_name_ident.len()).unwrap();
+ let #buffer_name_ident = {
+ use crate::backends::common::{BufferRef, CpuBuffer};
+
+ let buffer_slice = __dsl_allocation.as_slice_mut::<u8>();
+
+ buffer_slice.fill(0);
+ for __dsl_index in 0..#buffer_name_ident.len() {
+ let __dsl_offset = __dsl_index * #element_size;
+ #element_write
+ }
+
+ { let (buffer, range) = (&__dsl_allocation).parts(); binding_parts(buffer, range) }
+ };
+ })
+ }
+ _ => None,
+ };
+
+ (
+ prologue,
+ quote! {
+ wgpu::BindGroupEntry {
+ binding: #binding,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: #buffer_name_ident.0, offset: #buffer_name_ident.1 as u64, size: Some(std::num::NonZero::new(#buffer_name_ident.2 as u64).unwrap()) }),
+ }
+ }
+ )
+ }).collect::<(Vec<_>, Vec<_>)>();
+
+ let prologue = prologue.into_iter().flatten();
+
+ let wrapper_specialization_constants = specialization_constants
+ .iter()
+ .map(|specialization_constant| {
+ let used = metadata
+ .is_parameter_location_used(
+ ParameterCategory::SpecializationConstant,
+ 0,
+ specialization_constant.index as u64,
+ )
+ .with_context(|| {
+ format!(
+ "cannot query specialization constant {} for entry point {mangled_name}",
+ specialization_constant.index
+ )
+ })?;
+
+ Ok(used.then(|| {
+ let wgsl_idx = specialization_constant.index.to_string();
+ let value = &specialization_constant.value;
+ quote! { (#wgsl_idx, #value) }
+ }))
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+
+ let mut axis_dispatch_counts = Vec::new();
+ let mut group_dispatch_counts = Vec::new();
+ let mut has_indirect_dispatch = false;
+
+ for argument in &kernel.arguments {
+ match &argument.argument_type {
+ SlangArgumentType::Axis {
+ threads,
+ threads_in_group,
+ } => {
+ let threads = specializer.specialize(threads);
+ let threads_in_group = specializer.specialize(threads_in_group);
+ let threads: Expr = syn::parse_str(&threads)
+ .with_context(|| format!("cannot parse axis threads expression {threads:?}"))?;
+ let threads_in_group: Expr = syn::parse_str(&threads_in_group)
+ .with_context(|| format!("cannot parse axis group size expression {threads_in_group:?}"))?;
+
+ axis_dispatch_counts.push(quote! { u32::div_ceil(#threads, #threads_in_group) });
+ },
+ SlangArgumentType::Groups {
+ groups,
+ } if groups == "INDIRECT" => {
+ has_indirect_dispatch = true;
+ },
+ SlangArgumentType::Groups {
+ groups,
+ } => {
+ let groups = specializer.specialize(groups);
+ let groups: Expr = syn::parse_str(&groups)
+ .with_context(|| format!("cannot parse groups expression {groups:?}"))?;
+
+ group_dispatch_counts.push(quote! { #groups });
+ },
+ _ => (),
+ }
+ }
+
+ let dispatch = if has_indirect_dispatch {
+ quote! {
+ compute_pass.dispatch_workgroups_indirect(
+ __dsl_indirect_dispatch_buffer.0,
+ __dsl_indirect_dispatch_buffer.1 as u64,
+ );
+ }
+ } else {
+ let dispatch_counts = if axis_dispatch_counts.is_empty() {
+ group_dispatch_counts
+ } else {
+ axis_dispatch_counts
+ };
+ let mut dispatch_counts = dispatch_counts.into_iter();
+ let dispatch_x = dispatch_counts.next().unwrap_or_else(|| quote! { 1u32 });
+ let dispatch_y = dispatch_counts.next().unwrap_or_else(|| quote! { 1u32 });
+ let dispatch_z = dispatch_counts.next().unwrap_or_else(|| quote! { 1u32 });
+
+ quote! {
+ compute_pass.dispatch_workgroups(#dispatch_x, #dispatch_y, #dispatch_z);
+ }
+ };
+
+ wrappers.push(quote! {
+ #[allow(non_camel_case_types)]
+ struct #wrapper_struct_name {
+ #(#wrapper_new_arguments_definitions ,)*
+ pipeline: wgpu::ComputePipeline,
+ bind_group_layout: wgpu::BindGroupLayout,
+ }
+
+ impl #wrapper_struct_name {
+ fn new(
+ #[allow(unused)] context: &crate::backends::webgpu::context::WebGPUContext,
+ #(#wrapper_new_arguments_definitions ,)*
+ ) -> Result<Self, crate::backends::webgpu::error::WebGPUError> {
+ let shader_module = context.get_shader_module(#object_constant);
+ let bind_group_layout = context.get_bind_group_layout(vec![#(#bind_group_layout_entries ,)*]);
+ let pipeline_layout = context.get_pipeline_layout(bind_group_layout.clone());
+ let constants = vec![#(#wrapper_specialization_constants ,)*];
+ let pipeline = context.get_pipeline(shader_module, pipeline_layout, constants, #mangled_name);
+
+ Ok(Self { #(#kernel_wrapper_new_arguments ,)* pipeline, bind_group_layout })
+ }
+ }
+
+ impl #wrapper_trait_name for #wrapper_struct_name {
+ fn encode(
+ &self,
+ #(#wrapper_encode_arguments_definitions ,)*
+ encoder: &mut crate::backends::webgpu::command_buffer::WebGPUCommandBufferEncoding,
+ ) {
+ #(#prologue)*
+ let bind_group_entries = vec![#(#bind_group_entries ,)*];
+ let bind_group = encoder.context().device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &self.bind_group_layout,
+ entries: &bind_group_entries,
+ });
+
+ let compute_pass = encoder.ensure_compute();
+ compute_pass.set_pipeline(&self.pipeline);
+ compute_pass.set_bind_group(0, Some(&bind_group), &[]);
+ #dispatch
+ }
+ }
+ });
+ let kernel_new_match_arm_conditions = kernel
+ .parameters
+ .iter()
+ .filter_map(|kernel_parameter| kernel_parameter.to_common(gpu_type_map).unwrap())
+ .zip(variant.iter())
+ .map(|(kernel_parameter, (variant_name, variant_value))| {
+ assert!(kernel_parameter.name.as_ref() == *variant_name);
+
+ match kernel_parameter.ty {
+ KernelParameterType::Type => {
+ let variant_value: Expr =
+ syn::parse_str(&slang2rust(variant_value, gpu_type_map).unwrap().to_uppercase()).unwrap();
+
+ quote! { crate::data_type::DataType::#variant_value }
+ },
+ KernelParameterType::Value(_) => {
+ let variant_value: Expr = syn::parse_str(&specializer.specialize(variant_value)).unwrap();
+
+ quote! { #variant_value }
+ },
+ }
+ });
+ kernel_new_match_arms.push(quote! {
+ (#(#kernel_new_match_arm_conditions ,)*) => Ok(Self(Box::new(#wrapper_struct_name::new(context, #(#kernel_wrapper_new_arguments ,)*)?)))
+ })
+ }
+
+ let (public_trait_impl, public_type_backend, private_pub) = if kernel.public {
+ (
+ quote! { crate::backends::common::kernel::#kernel_trait_name for },
+ quote! { type Backend = crate::backends::webgpu::WebGPU; },
+ quote! {},
+ )
+ } else {
+ (quote! {}, quote! {}, quote! { pub })
+ };
+
+ Ok(quote! {
+ #(#wrappers)*
+
+ trait #wrapper_trait_name: Send + Sync {
+ fn encode(
+ &self,
+ #(#wrapper_encode_arguments_definitions ,)*
+ encoder: &mut crate::backends::webgpu::command_buffer::WebGPUCommandBufferEncoding,
+ );
+ }
+
+ pub struct #kernel_struct_name(Box<dyn #wrapper_trait_name>);
+
+ impl #public_trait_impl #kernel_struct_name {
+ #public_type_backend
+
+ #private_pub fn new(
+ #[allow(unused)] context: &crate::backends::webgpu::context::WebGPUContext,
+ #(#kernel_new_arguments_definitions ,)*
+ ) -> Result<Self, crate::backends::webgpu::error::WebGPUError> {
+ match (#(#kernel_new_match_arguments ,)*) {
+ #(#kernel_new_match_arms ,)*
+ #[allow(unreachable_patterns)]
+ __dsl_configuration => Err(crate::backends::webgpu::error::WebGPUError::UnsupportedKernelVariant(format!("{__dsl_configuration:?}"))),
+ }
+ }
+ #private_pub fn encode(
+ &self,
+ #(#kernel_encode_arguments_definitions ,)*
+ encoder: &mut crate::backends::webgpu::command_buffer::WebGPUCommandBufferEncoding,
+ ) {
+ self.0.encode(#(#kernel_wrapper_call_arguments ,)* encoder);
+ }
+ }
+ })
+}
diff --git a/crates/uzu-engine/build/webgpu/bindgen_global.rs b/crates/uzu-engine/build/webgpu/bindgen_global.rs
new file mode 100644
index 000000000..59dfc0e8b
--- /dev/null
+++ b/crates/uzu-engine/build/webgpu/bindgen_global.rs
@@ -0,0 +1,39 @@
+use std::path::Path;
+
+use proc_macro2::TokenStream;
+use quote::{format_ident, quote};
+
+use crate::common::kernel::Kernel;
+
+pub fn bindgen_global(kernels: &[(impl AsRef<Path>, &[Kernel])]) -> anyhow::Result<TokenStream> {
+ let includes = kernels.iter().map(|(path, _kernels)| {
+ let path = path.as_ref().to_str().unwrap();
+
+ quote! {
+ include!(#path);
+ }
+ });
+
+ let types = kernels.iter().flat_map(|(_path, kernels)| kernels.iter()).map(|kernel| {
+ let kernel_trait_name = format_ident!("{}Kernel", kernel.name.as_ref());
+ let kernel_struct_name = format_ident!("{}WebGPUKernel", kernel.name.as_ref());
+
+ quote! {
+ type #kernel_trait_name = #kernel_struct_name;
+ }
+ });
+
+ let tokens = quote! {
+ #(#includes)*
+
+ macro_rules! autogen_kernels {
+ () => {
+ #(#types)*
+ };
+ }
+
+ pub struct WebGPUKernels;
+ };
+
+ Ok(tokens)
+}
diff --git a/crates/uzu-engine/build/webgpu/mod.rs b/crates/uzu-engine/build/webgpu/mod.rs
new file mode 100644
index 000000000..4ff34c34b
--- /dev/null
+++ b/crates/uzu-engine/build/webgpu/mod.rs
@@ -0,0 +1,58 @@
+use std::{collections::HashMap, fs, path::Path};
+
+use anyhow::Context;
+use naga::{
+ front::wgsl,
+ valid::{Capabilities, ValidationFlags, Validator},
+};
+use proc_macro2::TokenStream;
+use shader_slang::{CompileTarget, ComponentType, GlobalSession, TargetDesc};
+
+use crate::slang::{SlangKernel, SlangTarget};
+
+mod bindgen_file;
+mod bindgen_global;
+
+#[derive(Clone)]
+pub struct WebGPU;
+
+impl SlangTarget for WebGPU {
+ const TARGET_NAME: &'static str = "webgpu";
+ const OUTPUT_EXTENSION: &'static str = "wgsl";
+
+ fn create_target_desc<'a>(_global_session: &'a GlobalSession) -> TargetDesc<'a> {
+ TargetDesc::default().format(CompileTarget::Wgsl)
+ }
+
+ fn validate_output(path: &Path) -> anyhow::Result<()> {
+ let source = fs::read_to_string(path).with_context(|| format!("cannot read {path:?}"))?;
+
+ let module = wgsl::parse_str(&source)?;
+
+ let flags = ValidationFlags::all();
+
+ let capabilities = Capabilities::SHADER_FLOAT16
+ | Capabilities::SHADER_FLOAT16_IN_FLOAT32
+ // NOTE: subgroup stuff is only supported on chrome!!!!
+ | Capabilities::SUBGROUP
+ | Capabilities::SUBGROUP_BARRIER;
+
+ Validator::new(flags, capabilities).validate(&module)?;
+
+ Ok(())
+ }
+
+ fn bindgen_file(
+ linked_component: &ComponentType,
+ kernels: &[SlangKernel],
+ gpu_type_map: &HashMap<String, String>,
+ constants: &HashMap<String, String>,
+ object_file: &Path,
+ ) -> anyhow::Result<TokenStream> {
+ bindgen_file::bindgen_file(linked_component, kernels, gpu_type_map, constants, object_file)
+ }
+
+ fn bindgen_global(kernels: &[(impl AsRef<Path>, &[crate::common::kernel::Kernel])]) -> anyhow::Result<TokenStream> {
+ bindgen_global::bindgen_global(kernels)
+ }
+}
diff --git a/crates/uzu-engine/src/backends/common/allocator/block.rs b/crates/uzu-engine/src/backends/common/allocator/block.rs
index cc0806fcb..e038425db 100644
--- a/crates/uzu-engine/src/backends/common/allocator/block.rs
+++ b/crates/uzu-engine/src/backends/common/allocator/block.rs
@@ -1,7 +1,9 @@
-use std::{collections::HashMap, mem::ManuallyDrop, range::Range, sync::Arc};
+use std::{collections::HashMap, mem::ManuallyDrop, os::raw::c_void, ptr::NonNull, range::Range, sync::Arc};
use parking_lot::Mutex;
+use crate::backends::common::{Buffer, CpuBuffer, GpuBuffer};
+
// TODO: this is a stub, real block allocator should suballocate from large pages
pub struct BlockAllocator<T> {
@@ -65,6 +67,22 @@ impl<T> BlockAllocation<T> {
}
}
+impl<T: Buffer> Buffer for BlockAllocation<T> {
+ type Backend = T::Backend;
+
+ fn size(&self) -> usize {
+ self.range().iter().len()
+ }
+}
+
+impl<T: GpuBuffer> GpuBuffer for BlockAllocation<T> {}
+
+impl<T: CpuBuffer> CpuBuffer for BlockAllocation<T> {
+ fn cpu_ptr(&self) -> NonNull<c_void> {
+ unsafe { self.page().cpu_ptr().byte_add(self.range().start) }
+ }
+}
+
impl<T> Drop for BlockAllocation<T> {
fn drop(&mut self) {
self.allocator.free(unsafe { ManuallyDrop::take(&mut self.page) }, self.range);
diff --git a/crates/uzu-engine/src/backends/common/allocator/bump.rs b/crates/uzu-engine/src/backends/common/allocator/bump.rs
index 77abe7dec..0ccc44077 100644
--- a/crates/uzu-engine/src/backends/common/allocator/bump.rs
+++ b/crates/uzu-engine/src/backends/common/allocator/bump.rs
@@ -1,4 +1,6 @@
-use std::{range::Range, sync::Arc};
+use std::{os::raw::c_void, ptr::NonNull, range::Range, sync::Arc};
+
+use crate::backends::common::{Buffer, CpuBuffer, GpuBuffer};
struct BumpAllocatorPage<T> {
page: Arc<T>,
@@ -8,13 +10,18 @@ struct BumpAllocatorPage<T> {
pub struct BumpAllocator<T> {
min_page_size: usize,
+ page_size_alignment: usize,
pages: Vec<BumpAllocatorPage<T>>,
}
impl<T> BumpAllocator<T> {
- pub fn new(min_page_size: usize) -> Self {
+ pub fn new(
+ min_page_size: usize,
+ page_size_alignment: usize,
+ ) -> Self {
Self {
min_page_size,
+ page_size_alignment,
pages: Vec::new(),
}
}
@@ -22,12 +29,11 @@ impl<T> BumpAllocator<T> {
pub fn allocate<E>(
&mut self,
size: usize,
+ alignment: usize,
upstream: impl FnOnce(usize) -> Result<T, E>,
) -> Result<BumpAllocation<T>, E> {
assert!(size > 0);
- let alignment = usize::min(size, 64).next_power_of_two();
-
if let Some(page) = self.pages.last_mut()
&& let page_offset_aligned = page.offset.next_multiple_of(alignment)
&& page_offset_aligned + size <= page.size
@@ -40,7 +46,7 @@ impl<T> BumpAllocator<T> {
return Ok(allocation);
}
- let new_page_size = usize::max(size, self.min_page_size);
+ let new_page_size = usize::max(size, self.min_page_size).next_multiple_of(self.page_size_alignment);
let new_page = Arc::new(upstream(new_page_size)?);
self.pages.push(BumpAllocatorPage {
page: new_page.clone(),
@@ -73,3 +79,19 @@ impl<T> BumpAllocation<T> {
self.range
}
}
+
+impl<T: Buffer> Buffer for BumpAllocation<T> {
+ type Backend = T::Backend;
+
+ fn size(&self) -> usize {
+ self.range().iter().len()
+ }
+}
+
+impl<T: GpuBuffer> GpuBuffer for BumpAllocation<T> {}
+
+impl<T: CpuBuffer> CpuBuffer for BumpAllocation<T> {
+ fn cpu_ptr(&self) -> NonNull<c_void> {
+ unsafe { self.page().cpu_ptr().byte_add(self.range().start) }
+ }
+}
diff --git a/crates/uzu-engine/src/backends/common/allocator/pool.rs b/crates/uzu-engine/src/backends/common/allocator/pool.rs
index 65e7d0ec1..520caff59 100644
--- a/crates/uzu-engine/src/backends/common/allocator/pool.rs
+++ b/crates/uzu-engine/src/backends/common/allocator/pool.rs
@@ -1,7 +1,9 @@
-use std::{collections::VecDeque, mem::ManuallyDrop, range::Range, sync::Arc};
+use std::{collections::VecDeque, mem::ManuallyDrop, os::raw::c_void, ptr::NonNull, range::Range, sync::Arc};
use parking_lot::Mutex;
+use crate::backends::common::{Buffer, CpuBuffer, GpuBuffer};
+
pub struct PoolAllocator<T> {
pages: [Mutex<VecDeque<T>>; 32],
}
@@ -58,6 +60,22 @@ impl<T> PoolAllocation<T> {
}
}
+impl<T: Buffer> Buffer for PoolAllocation<T> {
+ type Backend = T::Backend;
+
+ fn size(&self) -> usize {
+ self.range().iter().len()
+ }
+}
+
+impl<T: GpuBuffer> GpuBuffer for PoolAllocation<T> {}
+
+impl<T: CpuBuffer> CpuBuffer for PoolAllocation<T> {
+ fn cpu_ptr(&self) -> NonNull<c_void> {
+ unsafe { self.page().cpu_ptr().byte_add(self.range().start) }
+ }
+}
+
impl<T> Drop for PoolAllocation<T> {
fn drop(&mut self) {
self.allocator.alias(unsafe { ManuallyDrop::take(&mut self.page) }, self.range);
diff --git a/crates/uzu-engine/src/backends/common/backend.rs b/crates/uzu-engine/src/backends/common/backend.rs
index 3aa01329a..b2a86048b 100644
--- a/crates/uzu-engine/src/backends/common/backend.rs
+++ b/crates/uzu-engine/src/backends/common/backend.rs
@@ -1,14 +1,17 @@
use std::{error::Error, ops::DerefMut};
-use super::{CommandBuffer, ConstantBuffer, Context, GlobalBuffer, Kernels, ScratchBuffer, SparseBuffer};
+use super::{
+ Buffer, CommandBuffer, Context, CpuBuffer, GlobalBufferCpuGpu, GlobalGpuBuffer, GpuBuffer, Kernels, SparseBuffer,
+};
pub trait Backend: Clone + Send + Sync + 'static {
type Context: Context<Backend = Self>;
type CommandBuffer: CommandBuffer<Backend = Self>;
type DebugGroupSpan<'a>: DerefMut<Target = <Self::CommandBuffer as CommandBuffer>::Encoding> + 'a;
- type GlobalBuffer: GlobalBuffer<Backend = Self>;
- type ConstantBuffer: ConstantBuffer<Backend = Self>;
- type ScratchBuffer: ScratchBuffer<Backend = Self>;
+ type GlobalGpuBuffer: GlobalGpuBuffer<Backend = Self>;
+ type GlobalBufferCpuGpu: GlobalBufferCpuGpu<Backend = Self>;
+ type ConstantBuffer: Buffer<Backend = Self> + GpuBuffer + CpuBuffer;
+ type ScratchBuffer: GpuBuffer<Backend = Self>;
type SparseBuffer: SparseBuffer<Backend = Self>;
type AllocationPool: Send + Sync;
type CaptureSpan: Send + Sync;
diff --git a/crates/uzu-engine/src/backends/common/buffer/constant.rs b/crates/uzu-engine/src/backends/common/buffer/constant.rs
deleted file mode 100644
index 294f94088..000000000
--- a/crates/uzu-engine/src/backends/common/buffer/constant.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-use crate::backends::common::{Backend, BufferCpuAccessible};
-
-pub trait ConstantBuffer: BufferCpuAccessible<Backend: Backend<ConstantBuffer = Self>> {}
diff --git a/crates/uzu-engine/src/backends/common/buffer/cpu_accessible.rs b/crates/uzu-engine/src/backends/common/buffer/cpu_accessible.rs
deleted file mode 100644
index 297093484..000000000
--- a/crates/uzu-engine/src/backends/common/buffer/cpu_accessible.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-use std::{os::raw::c_void, ptr::NonNull};
-
-use crate::backends::common::Buffer;
-
-pub trait BufferCpuAccessible: Buffer {
- fn cpu_ptr(&self) -> NonNull<c_void>;
-}
diff --git a/crates/uzu-engine/src/backends/common/buffer/global.rs b/crates/uzu-engine/src/backends/common/buffer/global.rs
index 2f2981f1f..a117557d8 100644
--- a/crates/uzu-engine/src/backends/common/buffer/global.rs
+++ b/crates/uzu-engine/src/backends/common/buffer/global.rs
@@ -1,3 +1,7 @@
-use crate::backends::common::{Backend, BufferCpuAccessible};
+use crate::backends::common::{Backend, CpuBuffer, GpuBuffer};
-pub trait GlobalBuffer: BufferCpuAccessible<Backend: Backend<GlobalBuffer = Self>> {}
+pub trait GlobalGpuBuffer: GpuBuffer<Backend: Backend<GlobalGpuBuffer = Self>> {}
+
+pub trait GlobalBufferCpuGpu: CpuBuffer<Backend: Backend<GlobalBufferCpuGpu = Self>> {
+ fn handoff(self) -> <Self::Backend as Backend>::GlobalGpuBuffer;
+}
diff --git a/crates/uzu-engine/src/backends/common/buffer/mod.rs b/crates/uzu-engine/src/backends/common/buffer/mod.rs
index 7a2515a5e..75082bacc 100644
--- a/crates/uzu-engine/src/backends/common/buffer/mod.rs
+++ b/crates/uzu-engine/src/backends/common/buffer/mod.rs
@@ -1,11 +1,10 @@
-use std::{any::Any, range::Range};
+use std::{any::Any, os::raw::c_void, ptr::NonNull, range::Range};
+
+use bytemuck::{AnyBitPattern, NoUninit};
use crate::backends::common::{Backend, BufferMut, BufferRef};
-pub mod constant;
-pub mod cpu_accessible;
pub mod global;
-pub mod scratch;
pub mod sparse;
pub mod reference;
@@ -16,7 +15,34 @@ pub trait Buffer: Any + Send + Sync + Unpin {
fn size(&self) -> usize;
}
-impl<B: Buffer + ?Sized> BufferRef for &B {
+pub trait GpuBuffer: Buffer {}
+
+pub trait CpuBuffer: Buffer {
+ fn cpu_ptr(&self) -> NonNull<c_void>;
+
+ fn as_slice<T: AnyBitPattern>(&self) -> &[T] {
+ let bytes = unsafe { std::slice::from_raw_parts(self.cpu_ptr().as_ptr().cast::<u8>(), self.size()) };
+ bytemuck::cast_slice(bytes)
+ }
+
+ fn as_slice_mut<T: NoUninit + AnyBitPattern>(&mut self) -> &mut [T] {
+ let bytes = unsafe { std::slice::from_raw_parts_mut(self.cpu_ptr().as_ptr().cast::<u8>(), self.size()) };
+ bytemuck::cast_slice_mut(bytes)
+ }
+
+ fn copyin(
+ &mut self,
+ data: &[impl NoUninit + AnyBitPattern],
+ ) {
+ self.as_slice_mut().copy_from_slice(data);
+ }
+
+ fn copyout<T: AnyBitPattern>(&self) -> Vec<T> {
+ self.as_slice().to_vec()
+ }
+}
+
+impl<B: GpuBuffer + ?Sized> BufferRef for &B {
type Backend = B::Backend;
type Buffer = B;
@@ -32,7 +58,7 @@ impl<B: Buffer + ?Sized> BufferRef for &B {
}
}
-impl<B: Buffer + ?Sized> BufferMut for &mut B {
+impl<B: GpuBuffer + ?Sized> BufferMut for &mut B {
type Backend = B::Backend;
type Buffer = B;
diff --git a/crates/uzu-engine/src/backends/common/buffer/reference.rs b/crates/uzu-engine/src/backends/common/buffer/reference.rs
index 8affca261..97bb8d67e 100644
--- a/crates/uzu-engine/src/backends/common/buffer/reference.rs
+++ b/crates/uzu-engine/src/backends/common/buffer/reference.rs
@@ -3,17 +3,15 @@ use std::{
range::Range,
};
-use bytemuck::{AnyBitPattern, NoUninit};
-
-use crate::backends::common::{Backend, Buffer, BufferCpuAccessible};
+use crate::backends::common::{Backend, GpuBuffer};
// TODO: revisit as_slice/copy bounds and remove horrible unsafe metal kernel argument copyin hack
// TODO: also I'm not a big fan of this implementation. The implementation can be clean when BufferRef is on T
// TODO: but then &(impl BufferRef + ?Sized) everywhere it's used is much worse than a slightly messy trait system
-pub trait BufferRef: Copy {
+pub trait BufferRef: Copy + Send {
type Backend: Backend;
- type Buffer: Buffer<Backend = Self::Backend> + ?Sized;
+ type Buffer: GpuBuffer<Backend = Self::Backend> + ?Sized;
fn size(&self) -> usize;
@@ -21,25 +19,6 @@ pub trait BufferRef: Copy {
where
Self: 'a;
- fn as_slice<'a, T: AnyBitPattern>(self) -> &'a [T]
- where
- Self::Buffer: BufferCpuAccessible,
- Self: 'a,
- {
- let (buffer, range) = self.parts();
- let bytes = unsafe {
- std::slice::from_raw_parts(buffer.cpu_ptr().as_ptr().cast::<u8>().add(range.start), range.iter().len())
- };
- bytemuck::cast_slice(bytes)
- }
-
- fn copyout<T: AnyBitPattern>(self) -> Vec<T>
- where
- Self::Buffer: BufferCpuAccessible,
- {
- self.as_slice().to_vec()
- }
-
fn subrange<'a>(
self,
range: impl RangeBounds<usize>,
@@ -55,9 +34,9 @@ pub trait BufferRef: Copy {
}
}
-pub trait BufferMut: Sized {
+pub trait BufferMut: Sized + Send {
type Backend: Backend;
- type Buffer: Buffer<Backend = Self::Backend> + ?Sized;
+ type Buffer: GpuBuffer<Backend = Self::Backend> + ?Sized;
fn size(&self) -> usize;
@@ -69,28 +48,6 @@ pub trait BufferMut: Sized {
fn as_ref(&self) -> impl BufferRef<Backend = Self::Backend, Buffer = Self::Buffer>;
- #[expect(clippy::wrong_self_convention)]
- fn as_slice_mut<'a, T: NoUninit + AnyBitPattern>(self) -> &'a mut [T]
- where
- Self::Buffer: BufferCpuAccessible,
- Self: 'a,
- {
- let (buffer, range) = self.parts();
- let bytes = unsafe {
- std::slice::from_raw_parts_mut(buffer.cpu_ptr().as_ptr().cast::<u8>().add(range.start), range.iter().len())
- };
- bytemuck::cast_slice_mut(bytes)
- }
-
- fn copyin(
- self,
- data: &[impl NoUninit + AnyBitPattern],
- ) where
- Self::Buffer: BufferCpuAccessible,
- {
- self.as_slice_mut().copy_from_slice(data);
- }
-
fn subrange_mut<'a>(
self,
range: impl RangeBounds<usize>,
@@ -128,19 +85,19 @@ pub trait BufferMut: Sized {
}
}
-pub struct Subbuffer<'a, B: Buffer + ?Sized, const MUTABLE: bool> {
+pub struct Subbuffer<'a, B: GpuBuffer + ?Sized, const MUTABLE: bool> {
buffer: &'a B,
range: Range<usize>,
}
-impl<B: Buffer + ?Sized> Clone for Subbuffer<'_, B, false> {
+impl<B: GpuBuffer + ?Sized> Clone for Subbuffer<'_, B, false> {
fn clone(&self) -> Self {
*self
}
}
-impl<B: Buffer + ?Sized> Copy for Subbuffer<'_, B, false> {}
+impl<B: GpuBuffer + ?Sized> Copy for Subbuffer<'_, B, false> {}
-impl<B: Buffer + ?Sized> BufferRef for Subbuffer<'_, B, false> {
+impl<B: GpuBuffer + ?Sized> BufferRef for Subbuffer<'_, B, false> {
type Backend = B::Backend;
type Buffer = B;
@@ -156,7 +113,7 @@ impl<B: Buffer + ?Sized> BufferRef for Subbuffer<'_, B, false> {
}
}
-impl<B: Buffer + ?Sized> BufferMut for Subbuffer<'_, B, true> {
+impl<B: GpuBuffer + ?Sized> BufferMut for Subbuffer<'_, B, true> {
type Backend = B::Backend;
type Buffer = B;
diff --git a/crates/uzu-engine/src/backends/common/buffer/scratch.rs b/crates/uzu-engine/src/backends/common/buffer/scratch.rs
deleted file mode 100644
index e417e3b38..000000000
--- a/crates/uzu-engine/src/backends/common/buffer/scratch.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-use crate::backends::common::{Backend, Buffer};
-
-pub trait ScratchBuffer: Buffer<Backend: Backend<ScratchBuffer = Self>> {}
diff --git a/crates/uzu-engine/src/backends/common/buffer/sparse.rs b/crates/uzu-engine/src/backends/common/buffer/sparse.rs
index 9fdbdc2cf..8c97ee648 100644
--- a/crates/uzu-engine/src/backends/common/buffer/sparse.rs
+++ b/crates/uzu-engine/src/backends/common/buffer/sparse.rs
@@ -1,6 +1,6 @@
-use crate::backends::common::{Backend, Buffer};
+use crate::backends::common::{Backend, GpuBuffer};
-pub trait SparseBuffer: Buffer<Backend: Backend<SparseBuffer = Self>> {
+pub trait SparseBuffer: GpuBuffer<Backend: Backend<SparseBuffer = Self>> {
fn map(
&mut self,
until: usize,
diff --git a/crates/uzu-engine/src/backends/common/command_buffer.rs b/crates/uzu-engine/src/backends/common/command_buffer.rs
index ddb17038b..629aa716c 100644
--- a/crates/uzu-engine/src/backends/common/command_buffer.rs
+++ b/crates/uzu-engine/src/backends/common/command_buffer.rs
@@ -3,7 +3,7 @@ use std::{mem::size_of_val, time::Duration};
use bytemuck::{AnyBitPattern, NoUninit};
use crate::{
- backends::common::{Backend, BufferMut, BufferRef, TimestampSpan},
+ backends::common::{Backend, BufferMut, BufferRef, CpuBuffer, TimestampSpan},
data_type::DataType,
utils::size_for_shape::size_for_shape,
};
@@ -111,7 +111,7 @@ pub trait CommandBufferPending: Send {
pub trait CommandBufferCompleted: Send {
type CommandBuffer: CommandBuffer<Completed = Self>;
- fn gpu_execution_time(&self) -> Duration;
+ fn gpu_execution_time(&self) -> Option<Duration>;
fn timestamps(&self) -> &[TimestampSpan];
}
diff --git a/crates/uzu-engine/src/backends/common/context.rs b/crates/uzu-engine/src/backends/common/context.rs
index 381e4136e..4fd9747a2 100644
--- a/crates/uzu-engine/src/backends/common/context.rs
+++ b/crates/uzu-engine/src/backends/common/context.rs
@@ -1,6 +1,8 @@
use std::{path::Path, sync::Arc};
-use crate::backends::common::{Backend, CommandBuffer, DeviceCapabilities};
+use bytemuck::AnyBitPattern;
+
+use crate::backends::common::{Backend, BufferRef, CommandBuffer, DeviceCapabilities};
pub trait Context: Sized + Send + Sync {
type Backend: Backend<Context = Self>;
@@ -15,16 +17,26 @@ pub trait Context: Sized + Send + Sync {
allocation_pool: Option<Arc<<Self::Backend as Backend>::AllocationPool>>,
) -> Result<<<Self::Backend as Backend>::CommandBuffer as CommandBuffer>::Encoding, <Self::Backend as Backend>::Error>;
- fn create_buffer(
+ fn create_buffer_gpu(
+ &self,
+ size: usize,
+ ) -> Result<<Self::Backend as Backend>::GlobalGpuBuffer, <Self::Backend as Backend>::Error>;
+
+ fn create_buffer_cpu_gpu(
&self,
size: usize,
- ) -> Result<<Self::Backend as Backend>::GlobalBuffer, <Self::Backend as Backend>::Error>;
+ ) -> Result<<Self::Backend as Backend>::GlobalBufferCpuGpu, <Self::Backend as Backend>::Error>;
fn create_sparse_buffer(
&self,
capacity: usize,
) -> Result<<Self::Backend as Backend>::SparseBuffer, <Self::Backend as Backend>::Error>;
+ fn copyout<T: AnyBitPattern>(
+ &self,
+ buffer: impl BufferRef<Backend = Self::Backend, Buffer = <Self::Backend as Backend>::GlobalGpuBuffer>,
+ ) -> impl Future<Output = Result<Vec<T>, <Self::Backend as Backend>::Error>> + Send;
+
fn create_allocation_pool(&self) -> Arc<<Self::Backend as Backend>::AllocationPool>;
fn peak_memory_usage(&self) -> Option<usize>;
diff --git a/crates/uzu-engine/src/backends/common/device_capabilities.rs b/crates/uzu-engine/src/backends/common/device_capabilities.rs
index cc6852156..c219308cb 100644
--- a/crates/uzu-engine/src/backends/common/device_capabilities.rs
+++ b/crates/uzu-engine/src/backends/common/device_capabilities.rs
@@ -4,6 +4,7 @@ bitflags! {
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DeviceCapabilities: u32 {
- const SPARSE_BUFFERS = 1 << 0;
+ const GLOBAL_BUFFERS_CPU_ACCESSIBLE = 1 << 0;
+ const SPARSE_BUFFERS = 1 << 1;
}
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs
index 8563d165c..73018d002 100644
--- a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs
@@ -146,7 +146,7 @@ impl<B: Backend> ActivationTransform<B> {
self.kernel.encode(
Some(input),
Some(output),
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
None::<&mut B::ScratchBuffer>,
None::<&mut B::ScratchBuffer>,
None::<&mut B::ScratchBuffer>,
@@ -161,7 +161,7 @@ impl<B: Backend> ActivationTransform<B> {
&self,
data: impl BufferMut<Backend = B>,
rht_factors: impl BufferRef<Backend = B>,
- bias: Option<&B::GlobalBuffer>,
+ bias: Option<&B::GlobalGpuBuffer>,
batch_size: u32,
element_count: u32,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
@@ -206,7 +206,7 @@ impl<B: Backend> ActivationTransform<B> {
self.kernel.encode(
Some(input),
None::<&mut B::ScratchBuffer>,
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
Some(q_out),
Some(scales_out),
group_sums_out,
diff --git a/crates/uzu-engine/src/backends/common/kernel/attention.rs b/crates/uzu-engine/src/backends/common/kernel/attention.rs
index 22f14a53d..2266daa37 100644
--- a/crates/uzu-engine/src/backends/common/kernel/attention.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/attention.rs
@@ -59,7 +59,7 @@ pub struct AttentionKernelConfig {
pub struct AttentionArguments<'a, B: Backend, TT: BufferRef<Backend = B>, GT: BufferRef<Backend = B>> {
pub suffix_length: u32,
pub trie: Option<TT>,
- pub sinks: Option<&'a B::GlobalBuffer>,
+ pub sinks: Option<&'a B::GlobalGpuBuffer>,
pub cache: KVCacheView,
pub gate: Option<GT>,
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/delta_net_chunked_prefill.rs b/crates/uzu-engine/src/backends/common/kernel/delta_net_chunked_prefill.rs
index e51798d8f..033d4b994 100644
--- a/crates/uzu-engine/src/backends/common/kernel/delta_net_chunked_prefill.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/delta_net_chunked_prefill.rs
@@ -1,4 +1,4 @@
-#[cfg(backend = "cpu")]
+#[cfg(any(backend = "webgpu", backend = "cpu"))]
use crate::backends::common::kernel::Unsupported;
use crate::{
backends::common::{Backend, CommandBuffer, Kernels},
@@ -7,9 +7,9 @@ use crate::{
pub struct DeltaNetChunkedPrefillArgs<'a, B: Backend> {
pub in_projected: &'a B::ScratchBuffer,
- pub a_log: &'a B::GlobalBuffer,
- pub dt_bias: &'a B::GlobalBuffer,
- pub ssm_state: &'a mut B::GlobalBuffer,
+ pub a_log: &'a B::GlobalGpuBuffer,
+ pub dt_bias: &'a B::GlobalGpuBuffer,
+ pub ssm_state: &'a mut B::GlobalGpuBuffer,
pub delta_output: &'a mut B::ScratchBuffer,
pub num_heads: u32,
pub num_groups: u32,
@@ -41,7 +41,7 @@ pub trait DeltaNetChunkedPrefill: Sized + Send + Sync {
) -> Result<(), <Self::Backend as Backend>::Error>;
}
-#[cfg(backend = "cpu")]
+#[cfg(any(backend = "webgpu", backend = "cpu"))]
impl<B: Backend<Kernels: Kernels<DeltaNetChunkedPrefill = Unsupported<B>>>> DeltaNetChunkedPrefill for Unsupported<B> {
type Backend = B;
diff --git a/crates/uzu-engine/src/backends/common/kernel/delta_net_tree_verify.rs b/crates/uzu-engine/src/backends/common/kernel/delta_net_tree_verify.rs
index 25c659881..9a326ae21 100644
--- a/crates/uzu-engine/src/backends/common/kernel/delta_net_tree_verify.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/delta_net_tree_verify.rs
@@ -1,4 +1,4 @@
-#[cfg(backend = "cpu")]
+#[cfg(any(backend = "webgpu", backend = "cpu"))]
use crate::backends::common::kernel::Unsupported;
use crate::{
backends::common::{Backend, CommandBuffer, Kernels},
@@ -22,7 +22,7 @@ pub trait DeltaNetTreeVerify: Sized + Send + Sync {
) -> Result<<Self::Backend as Backend>::ScratchBuffer, <Self::Backend as Backend>::Error>;
}
-#[cfg(backend = "cpu")]
+#[cfg(any(backend = "webgpu", backend = "cpu"))]
impl<B: Backend<Kernels: Kernels<DeltaNetTreeVerify = Unsupported<B>>>> DeltaNetTreeVerify for Unsupported<B> {
type Backend = B;
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs
index 7a300a96a..6ebd2f4f7 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs
@@ -2,8 +2,8 @@ use crate::backends::common::{Backend, gpu_types::gemm::GemmDTransform};
pub struct MatmulDOps<'a, B: Backend> {
pub ab_scale: f32,
- pub bias: Option<&'a B::GlobalBuffer>,
- pub rht_factors: Option<&'a B::GlobalBuffer>,
+ pub bias: Option<&'a B::GlobalGpuBuffer>,
+ pub rht_factors: Option<&'a B::GlobalGpuBuffer>,
pub soft_cap: Option<f32>,
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs
index a31674ea0..717da5b7c 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs
@@ -58,10 +58,10 @@ pub trait MatmulKernel: Sized + Send + Sync {
fn optimize_weights_layout(
&self,
- _a8_shape: &MatmulShape,
- _weights: &mut <Self::Backend as Backend>::GlobalBuffer,
+ a8_shape: &MatmulShape,
+ _weights: &mut <Self::Backend as Backend>::GlobalGpuBuffer,
_context: &<Self::Backend as Backend>::Context,
- ) -> Result<Self::WeightsLayout, <Self::Backend as Backend>::Error> {
- Ok(Self::WeightsLayout::default())
+ ) -> Result<(Self::WeightsLayout, bool), <Self::Backend as Backend>::Error> {
+ Ok((Self::WeightsLayout::default(), a8_shape.signed_codes))
}
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs
index 84df3422b..d70ba1475 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs
@@ -13,7 +13,9 @@ pub use matmul_a::{Int8CodeLayout, MatmulA};
pub use matmul_b::{MatmulB, QuantizedB, QuantizedCorrection};
#[cfg(backend = "metal")]
pub use matmul_b::{TRELLIS_CODES_TAIL_BYTES, TrellisFormat};
-pub use output::{MatmulOutput, MatmulOutputError};
+pub use output::MatmulOutput;
+#[cfg(any(backend = "cpu", backend = "metal"))] // TODO: webgpu
+pub use output::MatmulOutputError;
pub use routing::{ActivationFormat, MatmulShape};
use crate::backends::common::{
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/output.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/output.rs
index 8a73f67e1..ea7bc4d8b 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/output.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/output.rs
@@ -1,7 +1,9 @@
+#[cfg(any(backend = "cpu", backend = "metal"))] // TODO: webgpu
use thiserror::Error;
use crate::backends::common::{Backend, BufferMut, kernel::matmul::MatmulDOps};
+#[cfg(any(backend = "cpu", backend = "metal"))] // TODO: webgpu
#[derive(Debug, Error)]
#[error("Unsupported output row stride {stride} for {columns} columns on path {path}")]
pub struct MatmulOutputError {
@@ -29,6 +31,7 @@ impl<'d, B: Backend, T: BufferMut<Backend = B>> MatmulOutput<'d, B, T> {
}
}
+ #[cfg(any(backend = "cpu", backend = "metal"))] // TODO: webgpu
pub(crate) fn into_contiguous(
self,
columns: u32,
diff --git a/crates/uzu-engine/src/backends/common/kernel/mod.rs b/crates/uzu-engine/src/backends/common/kernel/mod.rs
index 03ea2eb09..034b6672c 100644
--- a/crates/uzu-engine/src/backends/common/kernel/mod.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/mod.rs
@@ -1,4 +1,4 @@
-#[cfg(backend = "cpu")]
+#[cfg(any(backend = "webgpu", backend = "cpu"))]
use std::{convert::Infallible, marker::PhantomData};
use crate::backends::common::Backend;
@@ -36,7 +36,7 @@ pub trait Kernels: Sized {
type RadixTopKSmall: radix_top_k_small::RadixTopKSmall<Backend = Self::Backend>;
}
-#[cfg(backend = "cpu")]
+#[cfg(any(backend = "webgpu", backend = "cpu"))]
pub struct Unsupported<B: Backend> {
never: Infallible,
_marker: PhantomData<fn() -> B>,
diff --git a/crates/uzu-engine/src/backends/common/kernel/radix_top_k_small.rs b/crates/uzu-engine/src/backends/common/kernel/radix_top_k_small.rs
index ace5351ce..ed1369857 100644
--- a/crates/uzu-engine/src/backends/common/kernel/radix_top_k_small.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/radix_top_k_small.rs
@@ -1,5 +1,6 @@
use crate::backends::common::{Backend, BufferMut, BufferRef, CommandBuffer, Kernels};
+#[cfg(any(backend = "cpu", backend = "metal"))] // TODO: webgpu
pub const MAX_K: u32 = 512;
pub trait RadixTopKSmall: Sized + Send + Sync {
diff --git a/crates/uzu-engine/src/backends/common/mod.rs b/crates/uzu-engine/src/backends/common/mod.rs
index 9bf74ac18..db0bf9577 100644
--- a/crates/uzu-engine/src/backends/common/mod.rs
+++ b/crates/uzu-engine/src/backends/common/mod.rs
@@ -11,12 +11,9 @@ mod timestamp_span;
pub use backend::Backend;
pub use buffer::{
- Buffer,
- constant::ConstantBuffer,
- cpu_accessible::BufferCpuAccessible,
- global::GlobalBuffer,
+ Buffer, CpuBuffer, GpuBuffer,
+ global::{GlobalBufferCpuGpu, GlobalGpuBuffer},
reference::{BufferMut, BufferRef},
- scratch::ScratchBuffer,
sparse::SparseBuffer,
};
pub use command_buffer::{
diff --git a/crates/uzu-engine/src/backends/cpu/backend.rs b/crates/uzu-engine/src/backends/cpu/backend.rs
index 0555fcdaf..13e7eb48e 100644
--- a/crates/uzu-engine/src/backends/cpu/backend.rs
+++ b/crates/uzu-engine/src/backends/cpu/backend.rs
@@ -9,7 +9,7 @@ use crate::backends::{
},
},
cpu::{
- buffer::{dense::CpuBuffer, sparse::CpuSparseBuffer},
+ buffer::{dense::CpuDenseBuffer, sparse::CpuSparseBuffer},
command_buffer::{CpuCommandBuffer, CpuCommandBufferEncoding},
context::CpuContext,
error::CpuError,
@@ -24,11 +24,12 @@ impl Backend for Cpu {
type Context = CpuContext;
type CommandBuffer = CpuCommandBuffer;
type DebugGroupSpan<'a> = &'a mut CpuCommandBufferEncoding;
- type GlobalBuffer = CpuBuffer;
- type ConstantBuffer = BumpAllocation<Self::GlobalBuffer>;
- type ScratchBuffer = PoolAllocation<Self::GlobalBuffer>;
+ type GlobalGpuBuffer = CpuDenseBuffer;
+ type GlobalBufferCpuGpu = CpuDenseBuffer;
+ type ConstantBuffer = BumpAllocation<CpuDenseBuffer>;
+ type ScratchBuffer = PoolAllocation<CpuDenseBuffer>;
type SparseBuffer = CpuSparseBuffer;
- type AllocationPool = PoolAllocator<Self::GlobalBuffer>;
+ type AllocationPool = PoolAllocator<CpuDenseBuffer>;
type CaptureSpan = Infallible;
type Kernels = CpuKernels;
type Error = CpuError;
diff --git a/crates/uzu-engine/src/backends/cpu/buffer/constant.rs b/crates/uzu-engine/src/backends/cpu/buffer/constant.rs
deleted file mode 100644
index cd27a4c89..000000000
--- a/crates/uzu-engine/src/backends/cpu/buffer/constant.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use std::{os::raw::c_void, ptr::NonNull};
-
-use crate::backends::{
- common::{Backend, Buffer, BufferCpuAccessible, ConstantBuffer, allocator::bump::BumpAllocation},
- cpu::Cpu,
-};
-
-impl Buffer for BumpAllocation<<Cpu as Backend>::GlobalBuffer> {
- type Backend = Cpu;
-
- fn size(&self) -> usize {
- self.range().iter().len()
- }
-}
-
-impl BufferCpuAccessible for BumpAllocation<<Cpu as Backend>::GlobalBuffer> {
- fn cpu_ptr(&self) -> NonNull<c_void> {
- unsafe { self.page().cpu_ptr().byte_add(self.range().start) }
- }
-}
-
-impl ConstantBuffer for BumpAllocation<<Cpu as Backend>::GlobalBuffer> {}
diff --git a/crates/uzu-engine/src/backends/cpu/buffer/dense.rs b/crates/uzu-engine/src/backends/cpu/buffer/dense.rs
index 0ba3445ed..d354743e5 100644
--- a/crates/uzu-engine/src/backends/cpu/buffer/dense.rs
+++ b/crates/uzu-engine/src/backends/cpu/buffer/dense.rs
@@ -5,17 +5,17 @@ use std::{
};
use crate::backends::{
- common::{Buffer, BufferCpuAccessible, GlobalBuffer},
+ common::{Buffer, CpuBuffer, GlobalBufferCpuGpu, GlobalGpuBuffer, GpuBuffer},
cpu::Cpu,
};
#[derive(Debug)]
-pub struct CpuBuffer {
+pub struct CpuDenseBuffer {
ptr: NonNull<c_void>,
layout: Layout,
}
-impl CpuBuffer {
+impl CpuDenseBuffer {
pub(in crate::backends::cpu) fn new(size: usize) -> Self {
assert!(size > 0, "CPU buffer size must be nonzero");
let layout = Layout::from_size_align(size, 64).expect("invalid CPU buffer layout");
@@ -28,16 +28,16 @@ impl CpuBuffer {
}
// The allocation has a stable address; callers synchronize access through buffer borrows and command buffers.
-unsafe impl Send for CpuBuffer {}
-unsafe impl Sync for CpuBuffer {}
+unsafe impl Send for CpuDenseBuffer {}
+unsafe impl Sync for CpuDenseBuffer {}
-impl Drop for CpuBuffer {
+impl Drop for CpuDenseBuffer {
fn drop(&mut self) {
unsafe { dealloc(self.ptr.as_ptr().cast(), self.layout) };
}
}
-impl Buffer for CpuBuffer {
+impl Buffer for CpuDenseBuffer {
type Backend = Cpu;
fn size(&self) -> usize {
@@ -45,10 +45,18 @@ impl Buffer for CpuBuffer {
}
}
-impl BufferCpuAccessible for CpuBuffer {
+impl GpuBuffer for CpuDenseBuffer {}
+
+impl CpuBuffer for CpuDenseBuffer {
fn cpu_ptr(&self) -> NonNull<c_void> {
self.ptr
}
}
-impl GlobalBuffer for CpuBuffer {}
+impl GlobalGpuBuffer for CpuDenseBuffer {}
+
+impl GlobalBufferCpuGpu for CpuDenseBuffer {
+ fn handoff(self) -> Self {
+ self
+ }
+}
diff --git a/crates/uzu-engine/src/backends/cpu/buffer/mod.rs b/crates/uzu-engine/src/backends/cpu/buffer/mod.rs
index a462662fa..490aa36e7 100644
--- a/crates/uzu-engine/src/backends/cpu/buffer/mod.rs
+++ b/crates/uzu-engine/src/backends/cpu/buffer/mod.rs
@@ -2,20 +2,18 @@ use std::{os::raw::c_void, ptr::NonNull};
use crate::{
backends::{
- common::{Backend, Buffer, BufferCpuAccessible},
+ common::{Backend, CpuBuffer, GpuBuffer},
cpu::Cpu,
},
utils::downcast::downcast_ref,
};
-pub mod constant;
pub mod dense;
-pub mod scratch;
pub mod sparse;
-pub(super) trait CpuBufferExt: Buffer<Backend = Cpu> {
+pub(super) trait CpuBufferExt: GpuBuffer<Backend = Cpu> {
fn cpu_address(&self) -> NonNull<c_void> {
- if let Some(buffer) = downcast_ref::<<Cpu as Backend>::GlobalBuffer>(self) {
+ if let Some(buffer) = downcast_ref::<<Cpu as Backend>::GlobalGpuBuffer>(self) {
buffer.cpu_ptr()
} else if let Some(buffer) = downcast_ref::<<Cpu as Backend>::ConstantBuffer>(self) {
buffer.cpu_ptr()
@@ -27,4 +25,4 @@ pub(super) trait CpuBufferExt: Buffer<Backend = Cpu> {
}
}
-impl<T: Buffer<Backend = Cpu> + ?Sized> CpuBufferExt for T {}
+impl<T: GpuBuffer<Backend = Cpu> + ?Sized> CpuBufferExt for T {}
diff --git a/crates/uzu-engine/src/backends/cpu/buffer/scratch.rs b/crates/uzu-engine/src/backends/cpu/buffer/scratch.rs
deleted file mode 100644
index c44f8b96d..000000000
--- a/crates/uzu-engine/src/backends/cpu/buffer/scratch.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use std::{os::raw::c_void, ptr::NonNull};
-
-use crate::backends::{
- common::{Backend, Buffer, BufferCpuAccessible, ScratchBuffer, allocator::pool::PoolAllocation},
- cpu::Cpu,
-};
-
-impl Buffer for PoolAllocation<<Cpu as Backend>::GlobalBuffer> {
- type Backend = Cpu;
-
- fn size(&self) -> usize {
- self.range().iter().len()
- }
-}
-
-impl BufferCpuAccessible for PoolAllocation<<Cpu as Backend>::GlobalBuffer> {
- fn cpu_ptr(&self) -> NonNull<c_void> {
- unsafe { self.page().cpu_ptr().byte_add(self.range().start) }
- }
-}
-
-impl ScratchBuffer for PoolAllocation<<Cpu as Backend>::GlobalBuffer> {}
diff --git a/crates/uzu-engine/src/backends/cpu/buffer/sparse.rs b/crates/uzu-engine/src/backends/cpu/buffer/sparse.rs
index c9ea40556..1c3f8a17e 100644
--- a/crates/uzu-engine/src/backends/cpu/buffer/sparse.rs
+++ b/crates/uzu-engine/src/backends/cpu/buffer/sparse.rs
@@ -1,7 +1,7 @@
use std::convert::Infallible;
use crate::backends::{
- common::{Backend, Buffer, SparseBuffer},
+ common::{Backend, Buffer, GpuBuffer, SparseBuffer},
cpu::Cpu,
};
@@ -18,6 +18,8 @@ impl Buffer for CpuSparseBuffer {
}
}
+impl GpuBuffer for CpuSparseBuffer {}
+
impl SparseBuffer for CpuSparseBuffer {
fn map(
&mut self,
diff --git a/crates/uzu-engine/src/backends/cpu/command_buffer.rs b/crates/uzu-engine/src/backends/cpu/command_buffer.rs
index e76af9676..a40a0f2a7 100644
--- a/crates/uzu-engine/src/backends/cpu/command_buffer.rs
+++ b/crates/uzu-engine/src/backends/cpu/command_buffer.rs
@@ -13,7 +13,7 @@ use crate::{
},
cpu::{
Cpu,
- buffer::{CpuBufferExt, dense::CpuBuffer},
+ buffer::{CpuBufferExt, dense::CpuDenseBuffer},
context::CpuContext,
error::CpuError,
},
@@ -34,16 +34,16 @@ impl CommandBuffer for CpuCommandBuffer {
pub struct CpuCommandBufferEncoding {
commands: Vec<Box<dyn FnOnce() + Send>>,
- constant_allocator: BumpAllocator<<Cpu as Backend>::GlobalBuffer>,
+ constant_allocator: BumpAllocator<CpuDenseBuffer>,
allocation_pool: Arc<<Cpu as Backend>::AllocationPool>,
context: Arc<CpuContext>,
}
impl CpuCommandBufferEncoding {
pub fn new(
- constant_allocator: BumpAllocator<<Cpu as Backend>::GlobalBuffer>,
- allocation_pool: Arc<<Cpu as Backend>::AllocationPool>,
context: Arc<CpuContext>,
+ constant_allocator: BumpAllocator<CpuDenseBuffer>,
+ allocation_pool: Arc<<Cpu as Backend>::AllocationPool>,
) -> CpuCommandBufferEncoding {
CpuCommandBufferEncoding {
commands: Vec::new(),
@@ -72,14 +72,15 @@ impl CommandBufferEncoding for CpuCommandBufferEncoding {
&mut self,
size: usize,
) -> Result<<Cpu as Backend>::ConstantBuffer, CpuError> {
- self.constant_allocator.allocate(size, |size| Ok(CpuBuffer::new(size)))
+ let alignment = usize::min(size, 64).next_power_of_two();
+ self.constant_allocator.allocate(size, alignment, |size| Ok(CpuDenseBuffer::new(size)))
}
fn allocate_scratch(
&mut self,
size: usize,
) -> Result<<Cpu as Backend>::ScratchBuffer, CpuError> {
- self.allocation_pool.allocate(size, |size| Ok(CpuBuffer::new(size)))
+ self.allocation_pool.allocate(size, |size| Ok(CpuDenseBuffer::new(size)))
}
fn encode_copy(
@@ -126,7 +127,7 @@ impl CommandBufferEncoding for CpuCommandBufferEncoding {
}
fn with_timestamps(self) -> Self {
- panic!("the CPU backend does not record timestamps")
+ unimplemented!()
}
fn end_encoding(self) -> CpuCommandBufferExecutable {
@@ -142,7 +143,7 @@ impl CommandBufferEncoding for CpuCommandBufferEncoding {
pub struct CpuCommandBufferExecutable {
commands: Vec<Box<dyn FnOnce() + Send>>,
- constant_allocator: BumpAllocator<<Cpu as Backend>::GlobalBuffer>,
+ constant_allocator: BumpAllocator<CpuDenseBuffer>,
allocation_pool: Arc<<Cpu as Backend>::AllocationPool>,
context: Arc<CpuContext>,
}
@@ -203,11 +204,11 @@ pub struct CpuCommandBufferCompleted {
impl CommandBufferCompleted for CpuCommandBufferCompleted {
type CommandBuffer = CpuCommandBuffer;
- fn gpu_execution_time(&self) -> Duration {
- self.gpu_execution_time
+ fn gpu_execution_time(&self) -> Option<Duration> {
+ Some(self.gpu_execution_time)
}
fn timestamps(&self) -> &[TimestampSpan] {
- &[]
+ unimplemented!()
}
}
diff --git a/crates/uzu-engine/src/backends/cpu/context.rs b/crates/uzu-engine/src/backends/cpu/context.rs
index 6b9e0743b..61e01b9bf 100644
--- a/crates/uzu-engine/src/backends/cpu/context.rs
+++ b/crates/uzu-engine/src/backends/cpu/context.rs
@@ -7,10 +7,10 @@ use std::{
use crate::backends::{
common::{
- Backend, Context, DeviceCapabilities,
+ Backend, BufferRef, Context, CpuBuffer, DeviceCapabilities,
allocator::{bump::BumpAllocator, pool::PoolAllocator},
},
- cpu::{Cpu, buffer::dense::CpuBuffer, command_buffer::CpuCommandBufferEncoding, error::CpuError},
+ cpu::{Cpu, buffer::dense::CpuDenseBuffer, command_buffer::CpuCommandBufferEncoding, error::CpuError},
};
pub struct CpuContext {
@@ -45,16 +45,23 @@ impl Context for CpuContext {
_name: Option<&str>,
allocation_pool: Option<Arc<<Cpu as Backend>::AllocationPool>>,
) -> Result<CpuCommandBufferEncoding, CpuError> {
- let constant_allocator = BumpAllocator::new(256 * 1024);
+ let constant_allocator = BumpAllocator::new(256 * 1024, 1);
let allocation_pool = allocation_pool.unwrap_or_else(|| self.create_allocation_pool());
- Ok(CpuCommandBufferEncoding::new(constant_allocator, allocation_pool, self.weak_self.upgrade().unwrap()))
+ Ok(CpuCommandBufferEncoding::new(self.weak_self.upgrade().unwrap(), constant_allocator, allocation_pool))
}
- fn create_buffer(
+ fn create_buffer_gpu(
&self,
size: usize,
- ) -> Result<<Cpu as Backend>::GlobalBuffer, CpuError> {
- Ok(CpuBuffer::new(size))
+ ) -> Result<<Cpu as Backend>::GlobalGpuBuffer, CpuError> {
+ Ok(CpuDenseBuffer::new(size))
+ }
+
+ fn create_buffer_cpu_gpu(
+ &self,
+ size: usize,
+ ) -> Result<<Cpu as Backend>::GlobalBufferCpuGpu, CpuError> {
+ Ok(CpuDenseBuffer::new(size))
}
fn create_sparse_buffer(
@@ -64,6 +71,17 @@ impl Context for CpuContext {
Err(CpuError::NotSupported)
}
+ async fn copyout<T: bytemuck::AnyBitPattern>(
+ &self,
+ buffer: impl BufferRef<Backend = Cpu, Buffer = CpuDenseBuffer>,
+ ) -> Result<Vec<T>, CpuError> {
+ let (buffer, range) = buffer.parts();
+ let bytes = unsafe {
+ std::slice::from_raw_parts(buffer.cpu_ptr().as_ptr().cast::<u8>().add(range.start), range.iter().len())
+ };
+ Ok(bytemuck::cast_slice(bytes).to_vec())
+ }
+
fn create_allocation_pool(&self) -> Arc<<Cpu as Backend>::AllocationPool> {
PoolAllocator::new()
}
@@ -80,6 +98,6 @@ impl Context for CpuContext {
}
fn device_capabilities(&self) -> DeviceCapabilities {
- DeviceCapabilities::empty()
+ DeviceCapabilities::GLOBAL_BUFFERS_CPU_ACCESSIBLE
}
}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs
index 732cd0e9f..f41c4869d 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs
@@ -1,7 +1,7 @@
use crate::{
backends::{
common::{
- Backend, BufferCpuAccessible, BufferMut, BufferRef, Kernels,
+ Backend, BufferMut, BufferRef, CpuBuffer, Kernels,
gpu_types::quantization::QuantizationMode,
kernel::{
ActivationTransform, TensorAddBiasKernel,
diff --git a/crates/uzu-engine/src/backends/metal/backend.rs b/crates/uzu-engine/src/backends/metal/backend.rs
index bd8a2d71f..dd52bc897 100644
--- a/crates/uzu-engine/src/backends/metal/backend.rs
+++ b/crates/uzu-engine/src/backends/metal/backend.rs
@@ -24,11 +24,12 @@ impl Backend for Metal {
type Context = MetalContext;
type CommandBuffer = MetalCommandBuffer;
type DebugGroupSpan<'a> = MetalDebugGroupSpan<'a>;
- type GlobalBuffer = BlockAllocation<MetalDenseBuffer>;
- type ConstantBuffer = BumpAllocation<Self::GlobalBuffer>;
- type ScratchBuffer = PoolAllocation<Self::GlobalBuffer>;
+ type GlobalGpuBuffer = BlockAllocation<MetalDenseBuffer>;
+ type GlobalBufferCpuGpu = BlockAllocation<MetalDenseBuffer>;
+ type ConstantBuffer = BumpAllocation<Self::GlobalGpuBuffer>;
+ type ScratchBuffer = PoolAllocation<Self::GlobalGpuBuffer>;
type SparseBuffer = MetalSparseBuffer;
- type AllocationPool = PoolAllocator<Self::GlobalBuffer>;
+ type AllocationPool = PoolAllocator<Self::GlobalGpuBuffer>;
type CaptureSpan = MetalCaptureSpan;
type Kernels = MetalKernels;
type Error = MetalError;
diff --git a/crates/uzu-engine/src/backends/metal/buffer/constant.rs b/crates/uzu-engine/src/backends/metal/buffer/constant.rs
deleted file mode 100644
index 760e5d795..000000000
--- a/crates/uzu-engine/src/backends/metal/buffer/constant.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use std::{os::raw::c_void, ptr::NonNull};
-
-use crate::backends::{
- common::{Backend, Buffer, BufferCpuAccessible, ConstantBuffer, allocator::bump::BumpAllocation},
- metal::Metal,
-};
-
-impl Buffer for BumpAllocation<<Metal as Backend>::GlobalBuffer> {
- type Backend = Metal;
-
- fn size(&self) -> usize {
- self.range().iter().len()
- }
-}
-
-impl BufferCpuAccessible for BumpAllocation<<Metal as Backend>::GlobalBuffer> {
- fn cpu_ptr(&self) -> NonNull<c_void> {
- unsafe { self.page().cpu_ptr().byte_add(self.range().start) }
- }
-}
-
-impl ConstantBuffer for BumpAllocation<<Metal as Backend>::GlobalBuffer> {}
diff --git a/crates/uzu-engine/src/backends/metal/buffer/dense.rs b/crates/uzu-engine/src/backends/metal/buffer/dense.rs
index 17310a21d..9a21df27c 100644
--- a/crates/uzu-engine/src/backends/metal/buffer/dense.rs
+++ b/crates/uzu-engine/src/backends/metal/buffer/dense.rs
@@ -1,10 +1,17 @@
-use std::sync::{Arc, atomic::Ordering};
+use std::{
+ os::raw::c_void,
+ ptr::NonNull,
+ sync::{Arc, atomic::Ordering},
+};
use metal::{MTLBuffer, MTLDevice, MTLDeviceExt, MTLResidencySet, MTLResourceOptions};
use objc2::{rc::Retained, runtime::ProtocolObject};
use parking_lot::Mutex;
-use crate::backends::metal::{context::MetalContext, error::MetalError};
+use crate::backends::{
+ common::{Buffer, CpuBuffer, GlobalBufferCpuGpu, GlobalGpuBuffer, GpuBuffer, allocator::block::BlockAllocation},
+ metal::{Metal, context::MetalContext, error::MetalError},
+};
pub struct MetalDenseBuffer {
buffer: Retained<ProtocolObject<dyn MTLBuffer>>,
@@ -47,3 +54,27 @@ impl Drop for MetalDenseBuffer {
residency_set_locked.commit();
}
}
+
+impl Buffer for MetalDenseBuffer {
+ type Backend = Metal;
+
+ fn size(&self) -> usize {
+ self.buffer.length()
+ }
+}
+
+impl GpuBuffer for MetalDenseBuffer {}
+
+impl CpuBuffer for MetalDenseBuffer {
+ fn cpu_ptr(&self) -> NonNull<c_void> {
+ self.buffer.contents()
+ }
+}
+
+impl GlobalGpuBuffer for BlockAllocation<MetalDenseBuffer> {}
+
+impl GlobalBufferCpuGpu for BlockAllocation<MetalDenseBuffer> {
+ fn handoff(self) -> Self {
+ self
+ }
+}
diff --git a/crates/uzu-engine/src/backends/metal/buffer/global.rs b/crates/uzu-engine/src/backends/metal/buffer/global.rs
deleted file mode 100644
index 897385e7d..000000000
--- a/crates/uzu-engine/src/backends/metal/buffer/global.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use std::{os::raw::c_void, ptr::NonNull};
-
-use metal::MTLBuffer;
-
-use crate::backends::{
- common::{Buffer, BufferCpuAccessible, GlobalBuffer, allocator::block::BlockAllocation},
- metal::{Metal, buffer::dense::MetalDenseBuffer},
-};
-
-impl Buffer for BlockAllocation<MetalDenseBuffer> {
- type Backend = Metal;
-
- fn size(&self) -> usize {
- self.range().iter().len()
- }
-}
-
-impl BufferCpuAccessible for BlockAllocation<MetalDenseBuffer> {
- fn cpu_ptr(&self) -> NonNull<c_void> {
- unsafe { self.page().mtl_buffer().contents().byte_add(self.range().start) }
- }
-}
-
-impl GlobalBuffer for BlockAllocation<MetalDenseBuffer> {}
diff --git a/crates/uzu-engine/src/backends/metal/buffer/mod.rs b/crates/uzu-engine/src/backends/metal/buffer/mod.rs
index b6b9ef5de..302c83144 100644
--- a/crates/uzu-engine/src/backends/metal/buffer/mod.rs
+++ b/crates/uzu-engine/src/backends/metal/buffer/mod.rs
@@ -5,21 +5,18 @@ use objc2::{rc::Retained, runtime::ProtocolObject};
use crate::{
backends::{
- common::{Backend, Buffer},
+ common::{Backend, GpuBuffer},
metal::Metal,
},
utils::downcast::downcast_ref,
};
-pub mod constant;
pub mod dense;
-pub mod global;
-pub mod scratch;
pub mod sparse;
-pub(super) trait MetalBufferExt: Buffer<Backend = Metal> {
+pub(super) trait MetalBufferExt: GpuBuffer<Backend = Metal> {
fn downcast(&self) -> (&Retained<ProtocolObject<dyn MTLBuffer>>, usize) {
- if let Some(buffer) = downcast_ref::<<Metal as Backend>::GlobalBuffer>(self) {
+ if let Some(buffer) = downcast_ref::<<Metal as Backend>::GlobalGpuBuffer>(self) {
(buffer.page().mtl_buffer(), buffer.range().start)
} else if let Some(buffer) = downcast_ref::<<Metal as Backend>::ConstantBuffer>(self) {
let (page, offset) = buffer.page().downcast();
@@ -49,4 +46,4 @@ pub(super) trait MetalBufferExt: Buffer<Backend = Metal> {
}
}
-impl<T: Buffer<Backend = Metal> + ?Sized> MetalBufferExt for T {}
+impl<T: GpuBuffer<Backend = Metal> + ?Sized> MetalBufferExt for T {}
diff --git a/crates/uzu-engine/src/backends/metal/buffer/scratch.rs b/crates/uzu-engine/src/backends/metal/buffer/scratch.rs
deleted file mode 100644
index 4479c2757..000000000
--- a/crates/uzu-engine/src/backends/metal/buffer/scratch.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use std::{os::raw::c_void, ptr::NonNull};
-
-use crate::backends::{
- common::{Backend, Buffer, BufferCpuAccessible, ScratchBuffer, allocator::pool::PoolAllocation},
- metal::Metal,
-};
-
-impl Buffer for PoolAllocation<<Metal as Backend>::GlobalBuffer> {
- type Backend = Metal;
-
- fn size(&self) -> usize {
- self.range().iter().len()
- }
-}
-
-impl BufferCpuAccessible for PoolAllocation<<Metal as Backend>::GlobalBuffer> {
- fn cpu_ptr(&self) -> NonNull<c_void> {
- unsafe { self.page().cpu_ptr().byte_add(self.range().start) }
- }
-}
-
-impl ScratchBuffer for PoolAllocation<<Metal as Backend>::GlobalBuffer> {}
diff --git a/crates/uzu-engine/src/backends/metal/buffer/sparse.rs b/crates/uzu-engine/src/backends/metal/buffer/sparse.rs
index 6499bb79b..b3d4799c3 100644
--- a/crates/uzu-engine/src/backends/metal/buffer/sparse.rs
+++ b/crates/uzu-engine/src/backends/metal/buffer/sparse.rs
@@ -8,7 +8,7 @@ use metal::{
use objc2::{rc::Retained, runtime::ProtocolObject};
use crate::backends::{
- common::{Buffer, SparseBuffer},
+ common::{Buffer, GpuBuffer, SparseBuffer},
metal::{
Metal, context::MetalContext, error::MetalError, heaps::MetalHeapPage, metal_extensions::SparsePageSizeExt,
},
@@ -66,6 +66,8 @@ impl Buffer for MetalSparseBuffer {
}
}
+impl GpuBuffer for MetalSparseBuffer {}
+
impl SparseBuffer for MetalSparseBuffer {
fn map(
&mut self,
diff --git a/crates/uzu-engine/src/backends/metal/command_buffer.rs b/crates/uzu-engine/src/backends/metal/command_buffer.rs
index b4e433d22..acaedfa38 100644
--- a/crates/uzu-engine/src/backends/metal/command_buffer.rs
+++ b/crates/uzu-engine/src/backends/metal/command_buffer.rs
@@ -53,7 +53,7 @@ pub struct MetalCommandBufferEncoding {
pub(super) argument_table: Retained<ProtocolObject<dyn MTL4ArgumentTable>>,
reads: RangeSet<u64>,
writes: RangeSet<u64>,
- constant_allocator: Option<BumpAllocator<<Metal as Backend>::GlobalBuffer>>,
+ constant_allocator: Option<BumpAllocator<<Metal as Backend>::GlobalGpuBuffer>>,
allocation_pool: Arc<<Metal as Backend>::AllocationPool>,
pub(super) context: Arc<MetalContext>,
timestamps: Option<MetalTimestampRecorder>,
@@ -96,7 +96,7 @@ impl MetalCommandBufferEncoding {
.map_err(|error| MetalError::CannotCreateArgumentTable(error.to_string()))?;
compute_encoder.set_argument_table(Some(&argument_table));
- let constant_allocator = BumpAllocator::new(256 * 1024);
+ let constant_allocator = BumpAllocator::new(256 * 1024, 1);
let allocation_pool = allocation_pool.unwrap_or_else(|| context.create_allocation_pool());
@@ -152,14 +152,15 @@ impl CommandBufferEncoding for MetalCommandBufferEncoding {
&mut self,
size: usize,
) -> Result<<Metal as Backend>::ConstantBuffer, MetalError> {
- self.constant_allocator.as_mut().unwrap().allocate(size, |size| self.context.create_buffer(size))
+ let alignment = usize::min(size, 64).next_power_of_two();
+ self.constant_allocator.as_mut().unwrap().allocate(size, alignment, |size| self.context.create_buffer_gpu(size))
}
fn allocate_scratch(
&mut self,
size: usize,
) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {
- self.allocation_pool.allocate(size, |size| self.context.create_buffer(size))
+ self.allocation_pool.allocate(size, |size| self.context.create_buffer_gpu(size))
}
fn encode_copy(
@@ -286,7 +287,7 @@ impl Drop for MetalDebugGroupSpan<'_> {
pub struct MetalCommandBufferExecutable {
command_allocator: Retained<ProtocolObject<dyn MTL4CommandAllocator>>,
command_buffer: Retained<ProtocolObject<dyn MTL4CommandBuffer>>,
- constant_allocator: BumpAllocator<<Metal as Backend>::GlobalBuffer>,
+ constant_allocator: BumpAllocator<<Metal as Backend>::GlobalGpuBuffer>,
allocation_pool: Arc<<Metal as Backend>::AllocationPool>,
context: Arc<MetalContext>,
timestamps: Option<MetalTimestampRecorder>,
@@ -364,8 +365,8 @@ pub struct MetalCommandBufferCompleted {
impl CommandBufferCompleted for MetalCommandBufferCompleted {
type CommandBuffer = MetalCommandBuffer;
- fn gpu_execution_time(&self) -> Duration {
- self.gpu_execution_time
+ fn gpu_execution_time(&self) -> Option<Duration> {
+ Some(self.gpu_execution_time)
}
fn timestamps(&self) -> &[TimestampSpan] {
diff --git a/crates/uzu-engine/src/backends/metal/context.rs b/crates/uzu-engine/src/backends/metal/context.rs
index f11138d2f..57c2b1784 100644
--- a/crates/uzu-engine/src/backends/metal/context.rs
+++ b/crates/uzu-engine/src/backends/metal/context.rs
@@ -17,7 +17,7 @@ use parking_lot::Mutex;
use crate::backends::{
common::{
- Backend, Context, DeviceCapabilities,
+ Backend, BufferRef, Context, CpuBuffer, DeviceCapabilities,
allocator::{block::BlockAllocator, pool::PoolAllocator},
capture_matcher::CAPTURE_MATCHER,
},
@@ -196,10 +196,17 @@ impl Context for MetalContext {
MetalCommandBufferEncoding::new(self.weak_self.upgrade().unwrap(), name, allocation_pool)
}
- fn create_buffer(
+ fn create_buffer_gpu(
&self,
size: usize,
- ) -> Result<<Metal as Backend>::GlobalBuffer, MetalError> {
+ ) -> Result<<Metal as Backend>::GlobalGpuBuffer, MetalError> {
+ self.block_allocator.allocate(size, |size| MetalDenseBuffer::new(&self.weak_self.upgrade().unwrap(), size))
+ }
+
+ fn create_buffer_cpu_gpu(
+ &self,
+ size: usize,
+ ) -> Result<<Metal as Backend>::GlobalBufferCpuGpu, MetalError> {
self.block_allocator.allocate(size, |size| MetalDenseBuffer::new(&self.weak_self.upgrade().unwrap(), size))
}
@@ -210,6 +217,17 @@ impl Context for MetalContext {
MetalSparseBuffer::new(self.weak_self.upgrade().unwrap(), capacity)
}
+ async fn copyout<T: bytemuck::AnyBitPattern>(
+ &self,
+ buffer: impl BufferRef<Backend = Metal, Buffer = <Self::Backend as Backend>::GlobalGpuBuffer>,
+ ) -> Result<Vec<T>, MetalError> {
+ let (buffer, range) = buffer.parts();
+ let bytes = unsafe {
+ std::slice::from_raw_parts(buffer.cpu_ptr().as_ptr().cast::<u8>().add(range.start), range.iter().len())
+ };
+ Ok(bytemuck::cast_slice(bytes).to_vec())
+ }
+
fn create_allocation_pool(&self) -> Arc<<Metal as Backend>::AllocationPool> {
PoolAllocator::new()
}
@@ -226,7 +244,7 @@ impl Context for MetalContext {
}
fn device_capabilities(&self) -> DeviceCapabilities {
- let mut capabilities = DeviceCapabilities::empty();
+ let mut capabilities = DeviceCapabilities::GLOBAL_BUFFERS_CPU_ACCESSIBLE;
if self.device.supports_placement_sparse_resources() {
capabilities |= DeviceCapabilities::SPARSE_BUFFERS;
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/convolution/separable_causal_conv.metal b/crates/uzu-engine/src/backends/metal/kernel/convolution/separable_causal_conv.metal
index ea9644820..62086f8f2 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/convolution/separable_causal_conv.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/convolution/separable_causal_conv.metal
@@ -23,7 +23,7 @@ PUBLIC KERNEL(SeparableCausalConv)(
const uint group_size SPECIALIZE,
const bool has_bias SPECIALIZE,
uint token AXIS(sequence_length, TOKENS_PER_THREADGROUP),
- uint channel_block_index AXIS((model_dim + CHANNELS_PER_BLOCK - 1u) / CHANNELS_PER_BLOCK, CHANNEL_BLOCKS_PER_THREADGROUP)
+ uint channel_block_index AXIS(model_dim.div_ceil(CHANNELS_PER_BLOCK), CHANNEL_BLOCKS_PER_THREADGROUP)
){
using ValueBlock = vec<T, CHANNELS_PER_BLOCK>;
using AccumulatorBlock = vec<float, CHANNELS_PER_BLOCK>;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs
index d1ac09dfb..6c273750c 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs
@@ -110,7 +110,7 @@ impl GemmKernel {
}
pub fn prepare_gemm_b_layout(
- weights: &mut <Metal as Backend>::GlobalBuffer,
+ weights: &mut <Metal as Backend>::GlobalGpuBuffer,
rows: u32,
k: u32,
bits: u32,
@@ -495,8 +495,8 @@ impl GemmKernel {
scales,
biases,
zero_points,
- None::<&<Metal as Backend>::GlobalBuffer>,
- None::<&<Metal as Backend>::GlobalBuffer>,
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
a_int8,
a_scales,
a_group_sums,
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_metal_kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_metal_kernel.rs
index a4632a0f3..f58754c59 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_metal_kernel.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_metal_kernel.rs
@@ -3,7 +3,7 @@ use metal::MTLGPUFamily;
use crate::{
backends::{
common::{
- Backend, BufferMut, BufferRef, CommandBufferEncoding,
+ Backend, BufferMut, BufferRef, CommandBufferEncoding, CpuBuffer,
kernel::{
ActivationQuantization,
activation_transform::ACTIVATION_SCALE_GROUP_SIZE,
@@ -245,11 +245,26 @@ impl MatmulKernel for MatmulMetalKernel {
fn optimize_weights_layout(
&self,
a8_shape: &MatmulShape,
- weights: &mut <Metal as Backend>::GlobalBuffer,
+ weights: &mut <Metal as Backend>::GlobalGpuBuffer,
context: &MetalContext,
- ) -> Result<GemmBLayout, MetalError> {
- if self.select_activation_quantization(a8_shape, context).is_none() {
- return Ok(GemmBLayout::RowMajor);
+ ) -> Result<(GemmBLayout, bool), MetalError> {
+ let prepared_shape = MatmulShape {
+ signed_codes: a8_shape.signed_codes || a8_shape.b_bits == Some(8),
+ ..*a8_shape
+ };
+ if self.select_activation_quantization(&prepared_shape, context).is_none() {
+ return Ok((GemmBLayout::RowMajor, a8_shape.signed_codes));
+ }
+ if !a8_shape.signed_codes && prepared_shape.signed_codes {
+ let bytes = unsafe {
+ std::slice::from_raw_parts_mut(
+ weights.cpu_ptr().as_ptr().cast::<u8>(),
+ crate::backends::common::Buffer::size(weights),
+ )
+ };
+ let (prefix, words, suffix) = bytemuck::pod_align_to_mut::<u8, u64>(bytes);
+ words.iter_mut().for_each(|word| *word ^= 0x8080_8080_8080_8080);
+ prefix.iter_mut().chain(suffix.iter_mut()).for_each(|code| *code ^= 0x80);
}
GemmKernel::prepare_gemm_b_layout(
weights,
@@ -258,7 +273,7 @@ impl MatmulKernel for MatmulMetalKernel {
a8_shape.b_bits.expect("quantized weights"),
context,
)?;
- Ok(GemmBLayout::MxuTiled)
+ Ok((GemmBLayout::MxuTiled, prepared_shape.signed_codes))
}
fn encode(
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_output_work.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_output_work.rs
index a46201fd9..2543a9408 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_output_work.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_output_work.rs
@@ -32,7 +32,7 @@ impl MatmulOutputWork {
&self,
output: impl BufferMut<Backend = Metal>,
factors: impl BufferRef<Backend = Metal>,
- bias: Option<&<Metal as Backend>::GlobalBuffer>,
+ bias: Option<&<Metal as Backend>::GlobalGpuBuffer>,
m: u32,
n: u32,
command_buffer: &mut MetalCommandBufferEncoding,
diff --git a/crates/uzu-engine/src/backends/mod.rs b/crates/uzu-engine/src/backends/mod.rs
index 3868c1ab3..7f9a2d01b 100644
--- a/crates/uzu-engine/src/backends/mod.rs
+++ b/crates/uzu-engine/src/backends/mod.rs
@@ -1,10 +1,14 @@
pub(crate) mod common;
-#[cfg(backend = "cpu")]
-pub(crate) mod cpu;
#[cfg(backend = "metal")]
pub(crate) mod metal;
+#[cfg(backend = "webgpu")]
+pub(crate) mod webgpu;
+
+#[cfg(backend = "cpu")]
+pub(crate) mod cpu;
+
pub use common::Backend;
pub trait BackendSelection {
@@ -20,6 +24,8 @@ pub async fn select_backend<S: BackendSelection>(
) -> Result<S::Output, S::Error> {
let default = if cfg!(backend = "metal") {
"metal"
+ } else if cfg!(backend = "webgpu") {
+ "webgpu"
} else if cfg!(backend = "cpu") {
"cpu"
} else {
@@ -28,10 +34,12 @@ pub async fn select_backend<S: BackendSelection>(
// TODO: remove magic env var
match std::env::var("UZU_BACKEND").map(|s| s.to_lowercase()).as_deref().unwrap_or(default) {
- #[cfg(backend = "cpu")]
- "cpu" => selection.select::<cpu::Cpu>().await,
#[cfg(backend = "metal")]
"metal" => selection.select::<metal::Metal>().await,
+ #[cfg(backend = "webgpu")]
+ "webgpu" => selection.select::<webgpu::WebGPU>().await,
+ #[cfg(backend = "cpu")]
+ "cpu" => selection.select::<cpu::Cpu>().await,
_ => Err(unknown),
}
}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/activation/activation.slang b/crates/uzu-engine/src/backends/slang/kernel/activation/activation.slang
new file mode 100644
index 000000000..25eb0f8c3
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/activation/activation.slang
@@ -0,0 +1,15 @@
+// Autogenerated stub
+import definitions;
+import generated.activation_type;
+
+[[Variants("T", "half, float, BFloat16")]]
+[[Public]] [[Kernel]] func Activation<T>(
+ [[Optional("!in_place")]] StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint n,
+ ActivationType act_type,
+ [[Specialize]] bool in_place,
+ [[Axis("n", "256")]] uint tid,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/activation_transform/activation_transform.slang b/crates/uzu-engine/src/backends/slang/kernel/activation_transform/activation_transform.slang
new file mode 100644
index 000000000..70d933335
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/activation_transform/activation_transform.slang
@@ -0,0 +1,29 @@
+// Autogenerated stub
+import definitions;
+import generated.activation_transform;
+
+[[Variants("T", "float, BFloat16")]]
+[[Variants("BiasT", "float, BFloat16")]]
+[[Public]] [[Kernel]] func ActivationTransform<T, BiasT>(
+ [[Optional("!in_place")]] StructuredBuffer<T> input,
+ [[Optional("!(ops == ActivationTransformOp::Quantize || ops == ActivationTransformOp::QuantizeWithGroupSums)")]] RWStructuredBuffer<T> fp_out,
+ [[Optional("has_bias")]] StructuredBuffer<BiasT> bias,
+ [[Optional("(ops == ActivationTransformOp::Quantize || ops == ActivationTransformOp::QuantizeWithGroupSums)")]] RWStructuredBuffer<int8_t> q_out,
+ [[Optional("(ops == ActivationTransformOp::Quantize || ops == ActivationTransformOp::QuantizeWithGroupSums)")]] RWStructuredBuffer<float> scales_out,
+ [[Optional("(ops == ActivationTransformOp::QuantizeWithGroupSums)")]] RWStructuredBuffer<int> group_sums_out,
+ StructuredBuffer<int> rht_factors,
+ uint batch_size,
+ uint element_count,
+ [[Specialize]] ActivationTransformOp ops,
+ [[Specialize]] bool grouped_by_weight_nibble,
+ [[Specialize]] bool in_place,
+ [[Specialize]] uint activation_scale_group_size,
+ [[Specialize]] uint sum_group_size,
+ [[Specialize]] bool has_bias,
+ [[Groups("element_count.div_ceil(4* 32* 4)")]] uint activation_tile_index,
+ [[Groups("batch_size")]] uint batch_index,
+ [[Threads("4* 32")]] uint thread_index,
+ ThreadContext thread_context,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/activation_transform/trellis.slang b/crates/uzu-engine/src/backends/slang/kernel/activation_transform/trellis.slang
new file mode 100644
index 000000000..1c7499f65
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/activation_transform/trellis.slang
@@ -0,0 +1,18 @@
+// Autogenerated stub
+import definitions;
+
+[[Public]] [[Kernel]] func TrellisTransform(
+ StructuredBuffer<BFloat16> input,
+ StructuredBuffer<float> rht_factors,
+ StructuredBuffer<float> mixing,
+ RWStructuredBuffer<int8_t> activations,
+ RWStructuredBuffer<vector<float, 4>> column_group_sums,
+ RWStructuredBuffer<float> scales,
+ uint batch,
+ [[Specialize]] uint dimension,
+ [[Groups("batch")]] uint token,
+ [[Threads("512")]] uint thread_index,
+ ThreadContext thread_context,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/ancestor_attention.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/ancestor_attention.slang
new file mode 100644
index 000000000..eee29c2a4
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/ancestor_attention.slang
@@ -0,0 +1,28 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("HEAD_DIM", "128")]]
+[[Public]] [[Kernel]] func AncestorAttention<let HEAD_DIM: uint>(
+ StructuredBuffer<BFloat16> prefix_kv,
+ RWStructuredBuffer<BFloat16> node_kv,
+ StructuredBuffer<BFloat16> current_qkv,
+ StructuredBuffer<float> cosines,
+ StructuredBuffer<float> sines,
+ StructuredBuffer<uint> node_metadata,
+ StructuredBuffer<uint> ancestor_indices,
+ StructuredBuffer<uint> ancestor_counts,
+ StructuredBuffer<uint> node_indices,
+ RWStructuredBuffer<BFloat16> output,
+ uint rows,
+ uint prefix_length,
+ uint ancestor_stride,
+ uint node_capacity,
+ uint max_depth,
+ float scale,
+ [[Specialize]] uint num_heads,
+ ThreadContext thread_context,
+ [[Groups("(rows * num_heads).div_ceil(4)")]] uint group,
+ [[Threads("(4 * 32)")]] uint lid,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/attention_prepare.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/attention_prepare.slang
new file mode 100644
index 000000000..87495c4ae
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/attention_prepare.slang
@@ -0,0 +1,27 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("ElementT", "BFloat16")]]
+[[Variants("RopeT", "float")]]
+[[Public]] [[Kernel]] func AttentionPrepare<ElementT, RopeT>(
+ StructuredBuffer<ElementT> qkvg,
+ RWStructuredBuffer<ElementT> queries,
+ [[Optional("has_kv")]] RWStructuredBuffer<ElementT> keys,
+ [[Optional("has_kv")]] RWStructuredBuffer<ElementT> values,
+ [[Optional("has_rope")]] StructuredBuffer<RopeT> cosines,
+ [[Optional("has_rope")]] StructuredBuffer<RopeT> sines,
+ uint num_q_heads,
+ [[Optional("has_kv")]] uint num_kv_heads,
+ uint head_dim,
+ [[Optional("has_rope")]] uint rope_dim,
+ [[Optional("has_kv")]] uint kv_token_offset,
+ uint input_row_stride,
+ uint batch_dim,
+ [[Specialize]] bool has_kv,
+ [[Specialize]] bool has_rope,
+ [[Axis("head_dim", "128")]] uint head_dim_idx,
+ [[Axis("num_q_heads + num_kv_heads.unwrap_or(0) * 2", "1")]] uint head_idx,
+ [[Axis("batch_dim", "1")]] uint batch_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/attention_single_pass.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/attention_single_pass.slang
new file mode 100644
index 000000000..be760d281
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/attention_single_pass.slang
@@ -0,0 +1,37 @@
+// Autogenerated stub
+import definitions;
+import generated.ring;
+import generated.trie;
+
+[[Variants("T", "BFloat16")]]
+[[Variants("HEAD_DIM", "64, 128, 256, 512")]]
+[[Public]] [[Kernel]] func AttentionSinglePass<T, let HEAD_DIM: uint>(
+ StructuredBuffer<T> queries,
+ StructuredBuffer<T> keys,
+ StructuredBuffer<T> values,
+ RWStructuredBuffer<T> out,
+ uint gqa_factor,
+ uint sequence_length,
+ uint k_head_stride,
+ uint k_seq_stride,
+ uint v_head_stride,
+ uint v_seq_stride,
+ [[Optional("is_kv_cache_ring")]] RingParams ring_params,
+ float scale,
+ [[Optional("is_trie")]] StructuredBuffer<TrieNode> trie,
+ [[Optional("is_sliding_window")]] uint sliding_window_size,
+ [[Optional("has_sinks")]] StructuredBuffer<T> sinks,
+ uint num_heads,
+ uint suffix_length,
+ [[Specialize]] bool has_sinks,
+ [[Specialize]] bool is_kv_cache_ring,
+ [[Specialize]] bool is_causal,
+ [[Specialize]] bool is_trie,
+ [[Specialize]] bool is_sliding_window,
+ ThreadContext thread_context,
+ [[Groups("num_heads")]] uint head_idx,
+ [[Groups("suffix_length")]] uint q_seq_idx,
+ [[Threads("1024")]] uint tid,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/kv_cache_update.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/kv_cache_update.slang
new file mode 100644
index 000000000..08f70936e
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/kv_cache_update.slang
@@ -0,0 +1,29 @@
+// Autogenerated stub
+import definitions;
+import generated.kv_cache_update;
+
+[[Variants("T", "BFloat16")]]
+[[Public]] [[Kernel]] func KVCacheUpdate<T>(
+ RWStructuredBuffer<T> in_place_keys,
+ RWStructuredBuffer<T> in_place_values,
+ [[Constant]] StructuredBuffer<Copy> copies,
+ uint copy_count,
+ uint element_dim,
+ [[Axis("element_dim", "256")]] uint element_idx,
+) {
+ // TODO
+}
+
+[[Public]] [[Kernel]] func KVCacheUpdateInt8(
+ RWStructuredBuffer<int8_t> in_place_k_codes,
+ RWStructuredBuffer<uint8_t> in_place_v_codes,
+ RWStructuredBuffer<BFloat16> in_place_k_scales,
+ RWStructuredBuffer<BFloat16> in_place_v_scales,
+ [[Constant]] StructuredBuffer<Copy> copies,
+ uint copy_count,
+ [[Specialize]] uint head_dim,
+ [[Specialize]] uint num_kv_heads,
+ [[Axis("num_kv_heads* head_dim", "256")]] uint element,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/prepare_int8.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/prepare_int8.slang
new file mode 100644
index 000000000..f51596adf
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/prepare_int8.slang
@@ -0,0 +1,33 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("ElementT", "BFloat16")]]
+[[Variants("RopeT", "float")]]
+[[Variants("HEAD_DIM", "128, 256")]]
+[[Public]] [[Kernel]] func AttentionPrepareInt8<ElementT, RopeT, let HEAD_DIM: uint>(
+ StructuredBuffer<ElementT> qkvg,
+ [[Optional("!quantize_queries")]] RWStructuredBuffer<ElementT> queries,
+ [[Optional("quantize_queries")]] RWStructuredBuffer<int8_t> q_codes,
+ [[Optional("quantize_queries")]] RWStructuredBuffer<ElementT> q_scales,
+ [[Optional("append_kv")]] RWStructuredBuffer<int8_t> k_codes,
+ [[Optional("append_kv")]] RWStructuredBuffer<ElementT> k_scales,
+ [[Optional("append_kv")]] RWStructuredBuffer<uint8_t> v_codes,
+ [[Optional("append_kv")]] RWStructuredBuffer<ElementT> v_scales,
+ [[Optional("has_rope")]] StructuredBuffer<RopeT> cosines,
+ [[Optional("has_rope")]] StructuredBuffer<RopeT> sines,
+ uint num_q_heads,
+ [[Optional("has_rope")]] uint rope_dim,
+ uint kv_token_offset,
+ uint input_row_stride,
+ uint suffix_length,
+ uint query_rows,
+ [[Specialize]] bool has_rope,
+ [[Specialize]] bool quantize_queries,
+ [[Specialize]] uint num_kv_heads,
+ [[Specialize]] bool append_kv,
+ [[Groups("suffix_length")]] uint token_idx,
+ [[Groups("num_q_heads + num_kv_heads * 2")]] uint head_idx,
+ [[Threads("32")]] uint lane,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/qkv_norm.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/qkv_norm.slang
new file mode 100644
index 000000000..77cba1ab9
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/qkv_norm.slang
@@ -0,0 +1,27 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("InputT", "float, BFloat16")]]
+[[Variants("ScaleT", "float, BFloat16")]]
+[[Variants("OutputT", "float, BFloat16")]]
+[[Variants("AccumT", "float")]]
+[[Public]] [[Kernel]] func QKVNorm<InputT, ScaleT, OutputT, AccumT>(
+ [[Optional("!in_place")]] StructuredBuffer<InputT> qkvg_input,
+ [[Optional("has_scales")]] StructuredBuffer<ScaleT> scales,
+ RWStructuredBuffer<OutputT> qkvg_output,
+ uint batch_size,
+ uint input_row_stride,
+ uint head_dim,
+ float epsilon,
+ float scale_offset,
+ uint head_offset,
+ uint head_count,
+ bool full_layer,
+ [[Groups("batch_size")]] uint batch_idx,
+ [[Groups("head_count")]] uint head_idx,
+ [[Threads("32")]] uint lane_id,
+ [[Specialize]] bool in_place,
+ [[Specialize]] bool has_scales,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/attention/sigmoid_gate.slang b/crates/uzu-engine/src/backends/slang/kernel/attention/sigmoid_gate.slang
new file mode 100644
index 000000000..3cb02704b
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/attention/sigmoid_gate.slang
@@ -0,0 +1,15 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "BFloat16")]]
+[[Public]] [[Kernel]] func SigmoidGate<T>(
+ StructuredBuffer<T> gate,
+ RWStructuredBuffer<T> output,
+ uint gate_dim,
+ uint batch_dim,
+ uint gate_row_stride,
+ [[Axis("gate_dim", "256")]] uint gate_idx,
+ [[Axis("batch_dim", "1")]] uint batch_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/convolution/separable_causal_conv.slang b/crates/uzu-engine/src/backends/slang/kernel/convolution/separable_causal_conv.slang
new file mode 100644
index 000000000..43062ff42
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/convolution/separable_causal_conv.slang
@@ -0,0 +1,21 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "BFloat16")]]
+[[Public]] [[Kernel]] func SeparableCausalConv<T>(
+ StructuredBuffer<T> input,
+ StructuredBuffer<T> coefficient_deltas,
+ StructuredBuffer<T> weights,
+ [[Optional("has_bias")]] StructuredBuffer<T> bias,
+ RWStructuredBuffer<T> output,
+ uint sequence_length,
+ uint coefficient_row_stride,
+ [[Specialize]] uint model_dim,
+ [[Specialize]] uint kernel_size,
+ [[Specialize]] uint group_size,
+ [[Specialize]] bool has_bias,
+ [[Axis("sequence_length", "1")]] uint token,
+ [[Axis("model_dim.div_ceil(4)", "128")]] uint channel_block_index,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/definitions.slang b/crates/uzu-engine/src/backends/slang/kernel/definitions.slang
new file mode 100644
index 000000000..012718946
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/definitions.slang
@@ -0,0 +1,6 @@
+module definitions;
+
+__include definitions.bf16;
+__include definitions.thread_context;
+__include definitions.groupshared;
+__include definitions.dsl;
diff --git a/crates/uzu-engine/src/backends/slang/kernel/definitions/bf16.slang b/crates/uzu-engine/src/backends/slang/kernel/definitions/bf16.slang
new file mode 100644
index 000000000..cf60ce508
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/definitions/bf16.slang
@@ -0,0 +1,6 @@
+implementing definitions;
+
+// TODO: BF16 conversions and arithmetic.
+public struct BFloat16 {
+ uint16_t bits;
+};
diff --git a/crates/uzu-engine/src/backends/slang/kernel/definitions/dsl.slang b/crates/uzu-engine/src/backends/slang/kernel/definitions/dsl.slang
new file mode 100644
index 000000000..633875d54
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/definitions/dsl.slang
@@ -0,0 +1,55 @@
+implementing definitions;
+
+// Kernel annotations
+
+[[__AttributeUsage(_AttributeTargets.Function)]]
+struct VariantsAttribute {
+ string name;
+ string variants;
+};
+
+[[__AttributeUsage(_AttributeTargets.Function)]]
+struct GroupSharedAttribute {
+ string name;
+ string size;
+};
+
+[[__AttributeUsage(_AttributeTargets.Function)]]
+struct ConstraintAttribute {
+ string constraint;
+};
+
+[[__AttributeUsage(_AttributeTargets.Function)]]
+struct PublicAttribute;
+
+[[__AttributeUsage(_AttributeTargets.Function)]]
+struct KernelAttribute;
+
+// Kernel argument annotation
+
+[[__AttributeUsage(_AttributeTargets.Param)]]
+struct ConstantAttribute;
+
+[[__AttributeUsage(_AttributeTargets.Param)]]
+struct OptionalAttribute {
+ string condition;
+};
+
+[[__AttributeUsage(_AttributeTargets.Param)]]
+struct SpecializeAttribute;
+
+[[__AttributeUsage(_AttributeTargets.Param)]]
+struct AxisAttribute {
+ string threads;
+ string threads_in_group;
+};
+
+[[__AttributeUsage(_AttributeTargets.Param)]]
+struct GroupsAttribute {
+ string groups;
+};
+
+[[__AttributeUsage(_AttributeTargets.Param)]]
+struct ThreadsAttribute {
+ string threads;
+};
diff --git a/crates/uzu-engine/src/backends/slang/kernel/definitions/groupshared.slang b/crates/uzu-engine/src/backends/slang/kernel/definitions/groupshared.slang
new file mode 100644
index 000000000..d11d07920
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/definitions/groupshared.slang
@@ -0,0 +1,6 @@
+implementing definitions;
+
+public interface IGroupShared<T> {
+ static func load(uint idx) -> T;
+ static func store(uint idx, T value);
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/definitions/thread_context.slang b/crates/uzu-engine/src/backends/slang/kernel/definitions/thread_context.slang
new file mode 100644
index 000000000..9be5f73b6
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/definitions/thread_context.slang
@@ -0,0 +1,5 @@
+implementing definitions;
+
+public struct ThreadContext {
+ uint dummy = 0;
+};
diff --git a/crates/uzu-engine/src/backends/slang/kernel/embedding/input_embedding_lookup.slang b/crates/uzu-engine/src/backends/slang/kernel/embedding/input_embedding_lookup.slang
new file mode 100644
index 000000000..b830f3fd7
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/embedding/input_embedding_lookup.slang
@@ -0,0 +1,32 @@
+// Autogenerated stub
+import definitions;
+import generated.embedding;
+import generated.quantization;
+import generated.quantization_method;
+
+[[Variants("T", "float, BFloat16")]]
+[[Public]] [[Kernel]] func InputEmbeddingLookup<T>(
+ StructuredBuffer<uint> token_ids,
+ StructuredBuffer<uint8_t> values,
+ [[Optional("table_kind != EmbeddingTableKind::Dense")]] StructuredBuffer<T> scales,
+ [[Optional("table_kind == EmbeddingTableKind::Quantized && quantization_method == QuantizationMethod::ScaleZeroPoint")]] StructuredBuffer<uint8_t> zero_points,
+ [[Optional("table_kind == EmbeddingTableKind::Quantized && quantization_method == QuantizationMethod::ScaleBias")]] StructuredBuffer<T> biases,
+ [[Optional("use_hadamard")]] StructuredBuffer<int> hadamard_factors,
+ [[Optional("table_kind == EmbeddingTableKind::D4S4")]] StructuredBuffer<uint8_t> ladder_indices,
+ [[Optional("table_kind == EmbeddingTableKind::D4S4")]] StructuredBuffer<half> ladder,
+ [[Optional("table_kind == EmbeddingTableKind::D4S4")]] StructuredBuffer<vector<int8_t, 4>> codebook,
+ RWStructuredBuffer<T> output,
+ uint batch_size,
+ uint vocab_size,
+ uint model_dim,
+ float input_scale,
+ [[Specialize]] EmbeddingTableKind table_kind,
+ [[Specialize]] [[Optional("table_kind == EmbeddingTableKind::Quantized")]] uint group_size,
+ [[Specialize]] [[Optional("table_kind == EmbeddingTableKind::Quantized")]] QuantizationMode quantization_mode,
+ [[Specialize]] [[Optional("table_kind == EmbeddingTableKind::Quantized")]] QuantizationMethod quantization_method,
+ [[Specialize]] bool use_hadamard,
+ [[Axis("model_dim", "256")]] uint dim_idx,
+ [[Axis("batch_size", "1")]] uint batch_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gated_act_mul/gated_act_mul.slang b/crates/uzu-engine/src/backends/slang/kernel/gated_act_mul/gated_act_mul.slang
new file mode 100644
index 000000000..25889a958
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gated_act_mul/gated_act_mul.slang
@@ -0,0 +1,40 @@
+// Autogenerated stub
+import definitions;
+import generated.activation_type;
+import generated.gated_act_mul;
+
+[[Variants("T", "float, BFloat16")]]
+[[Public]] [[Kernel]] func GatedActMul<T>(
+ StructuredBuffer<T> act_operand,
+ [[Optional("!interleaved")]] StructuredBuffer<T> value_operand,
+ [[Optional("!(ops == GatedActMulOp::Quantize || ops == GatedActMulOp::QuantizeWithGroupSums)")]] RWStructuredBuffer<T> fp_out,
+ [[Optional("(ops == GatedActMulOp::Quantize || ops == GatedActMulOp::QuantizeWithGroupSums)")]] RWStructuredBuffer<int8_t> q_out,
+ [[Optional("(ops == GatedActMulOp::Quantize || ops == GatedActMulOp::QuantizeWithGroupSums)")]] RWStructuredBuffer<float> scales_out,
+ [[Optional("(ops == GatedActMulOp::QuantizeWithGroupSums)")]] RWStructuredBuffer<int> group_sums_out,
+ [[Optional("use_hadamard")]] StructuredBuffer<int> hadamard_factors,
+ uint gated_dim,
+ uint batch_dim,
+ uint value_offset,
+ uint value_row_stride,
+ ActivationType act_type,
+ [[Optional("custom_activation_alpha")]] float activation_alpha,
+ [[Optional("clip_gate")]] float gate_clip_min,
+ [[Optional("clip_gate")]] float gate_clip_max,
+ [[Optional("clip_value")]] float value_clip_min,
+ [[Optional("clip_value")]] float value_clip_max,
+ [[Specialize]] GatedActMulOp ops,
+ [[Specialize]] bool grouped_by_weight_nibble,
+ [[Specialize]] bool interleaved,
+ [[Specialize]] bool use_hadamard,
+ [[Specialize]] uint activation_scale_group_size,
+ [[Specialize]] uint sum_group_size,
+ [[Specialize]] bool custom_activation_alpha,
+ [[Specialize]] bool clip_gate,
+ [[Specialize]] bool clip_value,
+ [[Groups("gated_dim.div_ceil(4* 32* 4)")]] uint activation_tile_index,
+ [[Groups("batch_dim")]] uint batch_idx,
+ [[Threads("4* 32")]] uint thread_index,
+ ThreadContext thread_context,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/conv_pack.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/conv_pack.slang
new file mode 100644
index 000000000..beacb6103
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/conv_pack.slang
@@ -0,0 +1,18 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Variants("KERNEL_SIZE", "4")]]
+[[Public]] [[Kernel]] func DeltaNetConvPack<T, let KERNEL_SIZE: uint>(
+ StructuredBuffer<float> state_in,
+ StructuredBuffer<T> x,
+ RWStructuredBuffer<float> packed,
+ uint suffix_len,
+ uint tile_tokens,
+ uint row_stride,
+ uint conv_dim,
+ [[Axis("conv_dim", "128")]] uint channel_idx,
+ [[Axis("suffix_len.div_ceil(tile_tokens)", "1")]] uint tile_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/conv_scan.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/conv_scan.slang
new file mode 100644
index 000000000..3932e9071
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/conv_scan.slang
@@ -0,0 +1,21 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Variants("KERNEL_SIZE", "4")]]
+[[Public]] [[Kernel]] func DeltaNetConvScan<T, let KERNEL_SIZE: uint>(
+ StructuredBuffer<float> packed,
+ StructuredBuffer<float> conv_weight,
+ [[Optional("has_bias")]] StructuredBuffer<float> bias,
+ RWStructuredBuffer<T> in_proj,
+ RWStructuredBuffer<float> state_out,
+ uint suffix_len,
+ uint tile_tokens,
+ uint conv_dim,
+ uint out_stride,
+ [[Specialize]] bool has_bias,
+ [[Axis("conv_dim / 8", "32")]] uint channel_group,
+ [[Axis("suffix_len.div_ceil(tile_tokens)", "4")]] uint tile_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/conv_update.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/conv_update.slang
new file mode 100644
index 000000000..17cc7067c
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/conv_update.slang
@@ -0,0 +1,17 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Public]] [[Kernel]] func DeltaNetConvUpdate<T>(
+ StructuredBuffer<float> conv_weight,
+ [[Optional("has_bias")]] StructuredBuffer<float> bias,
+ RWStructuredBuffer<T> in_out,
+ RWStructuredBuffer<float> state,
+ uint kernel_size,
+ uint conv_dim,
+ uint state_stride,
+ [[Specialize]] bool has_bias,
+ [[Axis("conv_dim", "256")]] uint channel_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/norm_gate.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/norm_gate.slang
new file mode 100644
index 000000000..feb36ccfb
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/norm_gate.slang
@@ -0,0 +1,22 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Public]] [[Kernel]] func DeltaNetNormGate<T>(
+ RWStructuredBuffer<T> in_out,
+ StructuredBuffer<T> in_proj,
+ StructuredBuffer<float> norm_weight,
+ uint num_v_heads,
+ uint head_v_dim,
+ uint value_dim,
+ uint conv_dim,
+ uint total_proj_dim,
+ float norm_epsilon,
+ uint suffix_len,
+ ThreadContext thread_context,
+ [[Groups("suffix_len")]] uint token_idx,
+ [[Groups("num_v_heads")]] uint hv_idx,
+ [[Threads("128")]] uint tid,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/prefill.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/prefill.slang
new file mode 100644
index 000000000..74ac76467
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/prefill.slang
@@ -0,0 +1,26 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Variants("HEAD_K_DIM", "128")]]
+[[Public]] [[Kernel]] func DeltaNetPrefill<T, let HEAD_K_DIM: uint>(
+ StructuredBuffer<float> q_norm,
+ StructuredBuffer<float> k_norm,
+ StructuredBuffer<float> beta_buf,
+ StructuredBuffer<float> decay_buf,
+ StructuredBuffer<T> in_proj,
+ RWStructuredBuffer<float> state,
+ RWStructuredBuffer<T> out,
+ uint num_v_heads,
+ uint num_k_heads,
+ uint head_v_dim,
+ uint key_dim,
+ uint value_dim,
+ uint suffix_len,
+ uint num_dv_groups,
+ [[Groups("num_v_heads")]] uint hv_idx,
+ [[Groups("num_dv_groups")]] uint dv_group,
+ [[Threads("128")]] uint tid,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/prefill_prep.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/prefill_prep.slang
new file mode 100644
index 000000000..634cd6ccf
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/prefill_prep.slang
@@ -0,0 +1,28 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Variants("QKT", "float, BFloat16")]]
+[[Variants("HEAD_K_DIM", "128")]]
+[[Public]] [[Kernel]] func DeltaNetPrefillPrep<T, QKT, let HEAD_K_DIM: uint>(
+ StructuredBuffer<T> in_proj,
+ StructuredBuffer<float> a_log,
+ StructuredBuffer<float> dt_bias,
+ RWStructuredBuffer<QKT> q_norm_out,
+ RWStructuredBuffer<QKT> k_norm_out,
+ [[Optional("write_compact_v")]] RWStructuredBuffer<T> compact_v_out,
+ RWStructuredBuffer<float> beta_out,
+ RWStructuredBuffer<float> decay_out,
+ uint num_v_heads,
+ uint num_k_heads,
+ uint key_dim,
+ uint value_dim,
+ uint suffix_len,
+ [[Groups("suffix_len")]] uint token_idx,
+ [[Groups("num_k_heads")]] uint hk_idx,
+ [[Specialize]] bool write_log_decay,
+ [[Specialize]] bool write_compact_v,
+ [[Threads("32")]] uint lane,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/tree_verify/conv_scan.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/tree_verify/conv_scan.slang
new file mode 100644
index 000000000..ff4ac6727
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/tree_verify/conv_scan.slang
@@ -0,0 +1,22 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Public]] [[Kernel]] func ConvTreeScan<T>(
+ StructuredBuffer<T> in_proj,
+ StructuredBuffer<float> conv_weight,
+ [[Optional("has_bias")]] StructuredBuffer<float> bias,
+ StructuredBuffer<float> base_state,
+ StructuredBuffer<int> parents,
+ RWStructuredBuffer<T> out_proj,
+ RWStructuredBuffer<float> suffix_state,
+ uint suffix_len,
+ [[Specialize]] uint kernel_size,
+ uint total_proj_dim,
+ uint conv_dim,
+ [[Specialize]] bool has_bias,
+ [[Axis("suffix_len", "1")]] uint node_idx,
+ [[Axis("total_proj_dim", "256")]] uint channel_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/tree_verify/state_advance.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/tree_verify/state_advance.slang
new file mode 100644
index 000000000..bf855e2e8
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/tree_verify/state_advance.slang
@@ -0,0 +1,22 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Variants("HEAD_K_DIM", "128")]]
+[[Public]] [[Kernel]] func StateAdvance<T, let HEAD_K_DIM: uint>(
+ StructuredBuffer<T> k_norm,
+ StructuredBuffer<T> v,
+ StructuredBuffer<float> log_decay_buf,
+ StructuredBuffer<float> beta_buf,
+ StructuredBuffer<uint> accepted_indices,
+ RWStructuredBuffer<float> state,
+ uint accepted_len,
+ [[Specialize]] uint num_v_heads,
+ [[Specialize]] uint num_k_heads,
+ ThreadContext thread_context,
+ [[Groups("num_v_heads")]] uint hv_idx,
+ [[Groups("8")]] uint dv_group_idx,
+ [[Threads("128")]] uint thread_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/tree_verify/tree_verify.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/tree_verify/tree_verify.slang
new file mode 100644
index 000000000..5e5a0724d
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/tree_verify/tree_verify.slang
@@ -0,0 +1,34 @@
+// Autogenerated stub
+import definitions;
+import generated.trie;
+
+[[Variants("T", "float, BFloat16")]]
+[[Variants("NB", "1, 2")]]
+[[Public]] [[Kernel]] func TreeVerify<T, let NB: uint>(
+ StructuredBuffer<T> q,
+ StructuredBuffer<T> k,
+ StructuredBuffer<T> v,
+ StructuredBuffer<TrieNode> trie,
+ StructuredBuffer<float> log_decay,
+ StructuredBuffer<float> beta,
+ StructuredBuffer<float> h0,
+ StructuredBuffer<T> in_proj,
+ StructuredBuffer<float> norm_weight,
+ RWStructuredBuffer<T> o,
+ float scale,
+ float norm_epsilon,
+ uint batch_size,
+ uint tree_size,
+ uint num_k_heads,
+ uint num_v_heads,
+ uint head_k_dim,
+ uint head_v_dim,
+ uint conv_dim,
+ uint total_proj_dim,
+ ThreadContext thread_context,
+ [[Groups("batch_size")]] uint batch_idx,
+ [[Groups("num_v_heads")]] uint hv_idx,
+ [[Threads("(8 + NB) * 32")]] uint thread_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/gdn/update.slang b/crates/uzu-engine/src/backends/slang/kernel/gdn/update.slang
new file mode 100644
index 000000000..068d0fd3a
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/gdn/update.slang
@@ -0,0 +1,24 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Variants("HEAD_K_DIM", "128")]]
+[[Public]] [[Kernel]] func DeltaNetUpdate<T, let HEAD_K_DIM: uint>(
+ StructuredBuffer<T> in_proj,
+ StructuredBuffer<float> a_log,
+ StructuredBuffer<float> dt_bias,
+ StructuredBuffer<float> norm_weight,
+ RWStructuredBuffer<float> state,
+ RWStructuredBuffer<T> out,
+ uint num_v_heads,
+ uint num_k_heads,
+ uint head_v_dim,
+ uint key_dim,
+ uint value_dim,
+ float norm_epsilon,
+ ThreadContext thread_context,
+ [[Groups("num_v_heads")]] uint hv_idx,
+ [[Threads("512")]] uint tid,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/activation_transform.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/activation_transform.slang
new file mode 100644
index 000000000..d27114722
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/activation_transform.slang
@@ -0,0 +1,6 @@
+enum ActivationTransformOp : uint32_t {
+ InputRht = 0,
+ OutputRht = 1,
+ Quantize = 2,
+ QuantizeWithGroupSums = 3,
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/activation_type.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/activation_type.slang
new file mode 100644
index 000000000..2af7b2eb4
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/activation_type.slang
@@ -0,0 +1,11 @@
+static const float GELU_K0 = 0.044715;
+
+static const float GELU_K1 = 0.7978846;
+
+enum ActivationType : uint32_t {
+ SILU = 0,
+ GELUApprox = 1,
+ GELUExact = 2,
+ IDENTITY = 3,
+ SOFTPLUS = 4,
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/d4s4.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/d4s4.slang
new file mode 100644
index 000000000..8b12da5d4
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/d4s4.slang
@@ -0,0 +1,9 @@
+static const uint VALUES_PER_CODE = 4;
+
+static const uint CODEBOOK_SIZE = 256;
+
+static const uint COLUMNS_PER_LADDER_SCALE = 64;
+
+static const uint COLUMNS_PER_LADDER_INDEX_BYTE = 2 * COLUMNS_PER_LADDER_SCALE;
+
+static const uint LADDER_SIZE = 16;
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/embedding.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/embedding.slang
new file mode 100644
index 000000000..82ec0fbfe
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/embedding.slang
@@ -0,0 +1,5 @@
+enum EmbeddingTableKind : uint32_t {
+ Dense = 0,
+ Quantized = 1,
+ D4S4 = 2,
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/gated_act_mul.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/gated_act_mul.slang
new file mode 100644
index 000000000..4dc5f0b03
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/gated_act_mul.slang
@@ -0,0 +1,5 @@
+enum GatedActMulOp : uint32_t {
+ FullPrecision = 0,
+ Quantize = 1,
+ QuantizeWithGroupSums = 2,
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/gemm.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/gemm.slang
new file mode 100644
index 000000000..8fb1b3833
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/gemm.slang
@@ -0,0 +1,16 @@
+enum GemmBPrologueKind : uint32_t {
+ FullPrecision = 0,
+ ScaleBiasDequant = 1,
+ ScaleZeroPointDequant = 2,
+ ScaleSymmetricDequant = 3,
+};
+
+struct GemmDTransform {
+ uint raw_value;
+ static const uint SCALE = 1 << 0;
+ static const uint BIAS = 1 << 1;
+ static const uint RHT = 1 << 2;
+ static const uint SOFT_CAP = 1 << 3;
+ bool contains(uint flag) { return (raw_value & flag) != 0; }
+ uint bits() { return raw_value; }
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/hadamard_order.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/hadamard_order.slang
new file mode 100644
index 000000000..911632f6d
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/hadamard_order.slang
@@ -0,0 +1 @@
+static const uint HADAMARD_TRANSFORM_BLOCK_SIZE = 32;
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/kv_cache_update.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/kv_cache_update.slang
new file mode 100644
index 000000000..840948324
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/kv_cache_update.slang
@@ -0,0 +1,4 @@
+struct Copy {
+ uint source;
+ uint destination;
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/kv_layout.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/kv_layout.slang
new file mode 100644
index 000000000..723611220
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/kv_layout.slang
@@ -0,0 +1,21 @@
+static const uint TILE_KEYS = 32;
+
+static const uint TILE_QUERIES = 16;
+
+static const uint TILE_DIMS = 16;
+
+static const uint FRAGMENT_BYTES = TILE_KEYS * TILE_DIMS;
+
+static const uint SLICE_DIMS = 64;
+
+static const int16_t V_CODE_BIAS = 128;
+
+static const uint GROUP_ROWS = 8;
+
+static const uint LANE_COLS = 4;
+
+static const uint LANE_BYTES = TILE_KEYS / GROUP_ROWS * LANE_COLS;
+
+static const uint WORD_BITS = 32;
+
+static const uint ROTATION_SIGN_BITS[8] = {2654435769, 2246822507, 3266489909, 668265263, 374761393, 3210233709, 2496678331, 3605593784};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/matmul.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/matmul.slang
new file mode 100644
index 000000000..4084cb707
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/matmul.slang
@@ -0,0 +1 @@
+static const uint QUANT_PARAMS_GROUP_OUTPUT_ALIGNMENT = 4;
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/quantization.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/quantization.slang
new file mode 100644
index 000000000..165712637
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/quantization.slang
@@ -0,0 +1,5 @@
+enum QuantizationMode : uint32_t {
+ U4 = 0,
+ I8 = 1,
+ U8 = 2,
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/quantization_method.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/quantization_method.slang
new file mode 100644
index 000000000..95c729f29
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/quantization_method.slang
@@ -0,0 +1,5 @@
+enum QuantizationMethod : uint32_t {
+ ScaleBias = 0,
+ ScaleZeroPoint = 1,
+ ScaleSymmetric = 2,
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/ring.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/ring.slang
new file mode 100644
index 000000000..f0c5bcfd2
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/ring.slang
@@ -0,0 +1,4 @@
+struct RingParams {
+ uint ring_offset;
+ uint ring_length;
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/trellis.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/trellis.slang
new file mode 100644
index 000000000..33a6cd1f1
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/trellis.slang
@@ -0,0 +1 @@
+static const uint COLUMN_GROUP_COUNT = 4;
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/trie.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/trie.slang
new file mode 100644
index 000000000..755fb62b5
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/trie.slang
@@ -0,0 +1,5 @@
+struct TrieNode {
+ uint trie_start;
+ uint trie_end;
+ uint height;
+};
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/weaver.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/weaver.slang
new file mode 100644
index 000000000..4cea07d09
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/weaver.slang
@@ -0,0 +1,40 @@
+static const uint CANDIDATES_MAX = 512;
+
+enum WeaverSelectionMode : uint32_t {
+ Children = 0,
+ Frontier = 1,
+ Fused = 2,
+};
+
+enum FrontierIdx : uint32_t {
+ TokenId = 0,
+ ParentSlot = 1,
+ Depth = 2,
+ PathLogprobBits = 3,
+ EdgeLogprobBits = 4,
+ PathScoreKey = 5,
+ Active = 6,
+};
+
+enum TreeIdx : uint32_t {
+ TokenId = 0,
+ ParentSlot = 1,
+ Depth = 2,
+ PathLogprobBits = 3,
+ EdgeLogprobBits = 4,
+ Valid = 5,
+};
+
+enum MetadataIdx : uint32_t {
+ Depth = 0,
+ AncestorCount = 1,
+ TreeSlot = 2,
+};
+
+static const uint FRONTIER_NO_WINNER = ~0;
+
+static const uint FRONTIER_MAX_SLOTS = 2048;
+
+static const uint FRONTIER_MAX_WIDTH = 32;
+
+static const uint PADDING_DEPTH = 0;
\ No newline at end of file
diff --git a/crates/uzu-engine/src/backends/slang/kernel/logit_transform/logit_transform.slang b/crates/uzu-engine/src/backends/slang/kernel/logit_transform/logit_transform.slang
new file mode 100644
index 000000000..777afd865
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/logit_transform/logit_transform.slang
@@ -0,0 +1,14 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Public]] [[Kernel]] func LogitTransform<T>(
+ RWStructuredBuffer<T> logits,
+ uint length,
+ float scale,
+ float soft_cap,
+ [[Axis("length", "256")]] uint position,
+ [[Specialize]] bool has_soft_cap,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/normalization/normalization.slang b/crates/uzu-engine/src/backends/slang/kernel/normalization/normalization.slang
new file mode 100644
index 000000000..d1f9261cb
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/normalization/normalization.slang
@@ -0,0 +1,35 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("InputT", "float, half, BFloat16")]]
+[[Variants("AffineT", "float, half, BFloat16")]]
+[[Variants("OutputT", "float, half, BFloat16")]]
+[[Variants("AccumT", "float")]]
+[[Public]] [[Kernel]] func Normalization<InputT, AffineT, OutputT, AccumT>(
+ [[Optional("!in_place")]] StructuredBuffer<InputT> input,
+ [[Optional("has_scales")]] StructuredBuffer<AffineT> scales,
+ [[Optional("has_biases")]] StructuredBuffer<AffineT> biases,
+ RWStructuredBuffer<OutputT> output,
+ [[Optional("copy_to_shortcut")]] RWStructuredBuffer<InputT> shortcut,
+ [[Optional("use_hadamard")]] StructuredBuffer<int> hadamard_factors,
+ uint batch_size,
+ uint element_count,
+ float epsilon,
+ float scale_offset,
+ float post_layer_scalar,
+ [[Specialize]] bool in_place,
+ [[Specialize]] bool subtract_mean,
+ [[Specialize]] bool full_layer,
+ [[Specialize]] bool copy_to_shortcut,
+ [[Specialize]] bool residual_add,
+ [[Specialize]] bool use_hadamard,
+ [[Specialize]] bool scale_residual_sum,
+ [[Specialize]] bool scale_output,
+ [[Specialize]] bool has_biases,
+ [[Specialize]] bool has_scales,
+ ThreadContext thread_context,
+ [[Groups("batch_size")]] uint batch_idx,
+ [[Threads("1024")]] uint thread_in_row,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/pooling/pooling.slang b/crates/uzu-engine/src/backends/slang/kernel/pooling/pooling.slang
new file mode 100644
index 000000000..1cdbea91b
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/pooling/pooling.slang
@@ -0,0 +1,15 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, half, BFloat16")]]
+[[Public]] [[Kernel]] func PoolingMean<T>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint seq_len,
+ uint hidden_dim,
+ uint batch_size,
+ [[Axis("hidden_dim", "16")]] uint dim_idx,
+ [[Axis("batch_size", "16")]] uint batch_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/sampling/context_ring_update.slang b/crates/uzu-engine/src/backends/slang/kernel/sampling/context_ring_update.slang
new file mode 100644
index 000000000..c12bbb84f
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/sampling/context_ring_update.slang
@@ -0,0 +1,12 @@
+// Autogenerated stub
+import definitions;
+
+[[Public]] [[Kernel]] func ContextRingUpdate(
+ StructuredBuffer<uint> input,
+ RWStructuredBuffer<uint> context_ring,
+ uint suffix_repetition_length,
+ uint input_length,
+ [[Threads("256")]] uint thread_index,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/sampling/repetition_penalty.slang b/crates/uzu-engine/src/backends/slang/kernel/sampling/repetition_penalty.slang
new file mode 100644
index 000000000..830b9d227
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/sampling/repetition_penalty.slang
@@ -0,0 +1,18 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Public]] [[Kernel]] func RepetitionPenalty<T>(
+ StructuredBuffer<T> original_logits,
+ RWStructuredBuffer<T> logits_copy,
+ StructuredBuffer<uint> context_ring,
+ StructuredBuffer<uint> token_ids,
+ float repetition_penalty,
+ uint suffix_repetition_length,
+ uint vocab_size,
+ uint sampling_start,
+ uint sampling_length,
+ [[Axis("sampling_length * suffix_repetition_length", "256")]] uint position,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/sampling/unified_sampling.slang b/crates/uzu-engine/src/backends/slang/kernel/sampling/unified_sampling.slang
new file mode 100644
index 000000000..97fc9bb4c
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/sampling/unified_sampling.slang
@@ -0,0 +1,27 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, BFloat16")]]
+[[Public]] [[Kernel]] func UnifiedSampling<T>(
+ StructuredBuffer<T> logits,
+ RWStructuredBuffer<uint> output,
+ [[Optional("is_stochastic")]] StructuredBuffer<uint64_t> seeds,
+ [[Optional("has_bitmask")]] StructuredBuffer<uint> bitmask,
+ [[Optional("has_temperature")]] float temperature,
+ [[Optional("has_top_k")]] uint top_k,
+ [[Optional("has_top_p")]] float top_p,
+ [[Optional("has_min_p")]] float min_p,
+ uint vocab_size,
+ uint batch_size,
+ [[Specialize]] bool is_stochastic,
+ [[Specialize]] bool has_bitmask,
+ [[Specialize]] bool has_temperature,
+ [[Specialize]] bool has_top_k,
+ [[Specialize]] bool has_top_p,
+ [[Specialize]] bool has_min_p,
+ ThreadContext thread_context,
+ [[Groups("batch_size")]] uint batch_idx,
+ [[Threads("1024")]] uint thread_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/short_conv/short_conv.slang b/crates/uzu-engine/src/backends/slang/kernel/short_conv/short_conv.slang
new file mode 100644
index 000000000..e3e0034f4
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/short_conv/short_conv.slang
@@ -0,0 +1,81 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, half, BFloat16")]]
+[[Public]] [[Kernel]] func ShortConvPack<T>(
+ StructuredBuffer<T> state_in,
+ StructuredBuffer<T> in_proj,
+ RWStructuredBuffer<T> padded,
+ uint state_stride,
+ uint suffix_len,
+ uint in_proj_stride,
+ uint model_dim,
+ [[Axis("model_dim", "256")]] uint channel_idx,
+ [[Axis("state_stride + suffix_len", "1")]] uint row_idx,
+) {
+ // TODO
+}
+
+[[Variants("T", "float, half, BFloat16")]]
+[[Variants("WeightT", "float")]]
+[[Public]] [[Kernel]] func ShortConvPrefill<T, WeightT>(
+ StructuredBuffer<T> padded,
+ StructuredBuffer<T> in_proj,
+ StructuredBuffer<WeightT> w,
+ [[Optional("has_bias")]] StructuredBuffer<WeightT> b,
+ RWStructuredBuffer<T> out,
+ RWStructuredBuffer<T> state_out,
+ uint suffix_len,
+ uint kernel_size,
+ uint in_proj_stride,
+ uint state_stride,
+ uint model_dim,
+ [[Specialize]] bool has_bias,
+ [[Axis("suffix_len + kernel_size.saturating_sub(1)", "1")]] uint token_idx,
+ [[Axis("model_dim", "256")]] uint channel_idx,
+) {
+ // TODO
+}
+
+[[Variants("T", "float, half, BFloat16")]]
+[[Variants("WeightT", "float")]]
+[[Public]] [[Kernel]] func ShortConvDecode<T, WeightT>(
+ StructuredBuffer<T> in_proj,
+ StructuredBuffer<WeightT> w,
+ [[Optional("has_bias")]] StructuredBuffer<WeightT> b,
+ [[Optional("!state_in_place")]] StructuredBuffer<T> state,
+ RWStructuredBuffer<T> out,
+ RWStructuredBuffer<T> next_state,
+ uint suffix_len,
+ uint kernel_size,
+ uint in_proj_stride,
+ uint state_stride,
+ uint model_dim,
+ [[Specialize]] bool has_bias,
+ [[Specialize]] bool state_in_place,
+ [[Axis("suffix_len", "1")]] uint token_idx,
+ [[Axis("model_dim", "256")]] uint channel_idx,
+) {
+ // TODO
+}
+
+[[Variants("T", "float, half, BFloat16")]]
+[[Variants("WeightT", "float")]]
+[[Public]] [[Kernel]] func ShortConvTrie<T, WeightT>(
+ StructuredBuffer<T> in_proj,
+ StructuredBuffer<WeightT> w,
+ [[Optional("has_bias")]] StructuredBuffer<WeightT> b,
+ StructuredBuffer<T> base_state,
+ StructuredBuffer<int> parents,
+ RWStructuredBuffer<T> out,
+ RWStructuredBuffer<T> suffix_state,
+ uint suffix_len,
+ uint kernel_size,
+ uint in_proj_stride,
+ uint state_stride,
+ uint model_dim,
+ [[Specialize]] bool has_bias,
+ [[Axis("model_dim", "256")]] uint channel_idx,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/softmax/softmax.slang b/crates/uzu-engine/src/backends/slang/kernel/softmax/softmax.slang
new file mode 100644
index 000000000..0a422c4ca
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/softmax/softmax.slang
@@ -0,0 +1,17 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, half, BFloat16")]]
+[[Public]] [[Kernel]] func Softmax<T>(
+ RWStructuredBuffer<T> values,
+ [[Optional("has_sinks")]] StructuredBuffer<T> sinks,
+ uint row_length,
+ uint outer_dim,
+ uint batch_dim,
+ [[Specialize]] bool has_sinks,
+ [[Groups("outer_dim")]] uint outer_index,
+ [[Groups("batch_dim")]] uint batch_index,
+ [[Threads("256")]] uint tid,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/tensor_add_bias/tensor_add_bias.slang b/crates/uzu-engine/src/backends/slang/kernel/tensor_add_bias/tensor_add_bias.slang
new file mode 100644
index 000000000..a2fbd1aef
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/tensor_add_bias/tensor_add_bias.slang
@@ -0,0 +1,16 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, half, BFloat16")]]
+[[Variants("BiasT", "float, half, BFloat16")]]
+[[Public]] [[Kernel]] func TensorAddBias<T, BiasT>(
+ [[Optional("!in_place")]] StructuredBuffer<T> input,
+ StructuredBuffer<BiasT> bias,
+ RWStructuredBuffer<T> output,
+ uint num_cols,
+ uint length,
+ [[Axis("length", "32")]] uint position,
+ [[Specialize]] bool in_place,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/tensor_add_scale/tensor_add_scale.slang b/crates/uzu-engine/src/backends/slang/kernel/tensor_add_scale/tensor_add_scale.slang
new file mode 100644
index 000000000..80971b51c
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/tensor_add_scale/tensor_add_scale.slang
@@ -0,0 +1,16 @@
+// Autogenerated stub
+import definitions;
+
+[[Variants("T", "float, half, BFloat16")]]
+[[Public]] [[Kernel]] func TensorAddScale<T>(
+ [[Optional("!in_place")]] StructuredBuffer<T> input,
+ StructuredBuffer<T> bias,
+ RWStructuredBuffer<T> output,
+ uint num_cols,
+ uint length,
+ float scale,
+ [[Axis("length", "32")]] uint position,
+ [[Specialize]] bool in_place,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/test_kernel.slang b/crates/uzu-engine/src/backends/slang/kernel/test_kernel.slang
new file mode 100644
index 000000000..699835183
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/test_kernel.slang
@@ -0,0 +1,325 @@
+import definitions;
+import generated.activation_type;
+import generated.kv_cache_update;
+import generated.quantization;
+import generated.ring;
+
+// TODO: remove after real kernels working
+
+static const uint threadgroup_size = 256;
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelGroupThread<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input_0,
+ StructuredBuffer<T> input_1,
+ RWStructuredBuffer<T> output,
+ uint size,
+ [[Groups("size.div_ceil(threadgroup_size)")]] uint group_idx,
+ [[Threads("threadgroup_size")]] uint thread_idx,
+) {
+ uint idx = group_idx * threadgroup_size + thread_idx;
+
+ if (idx < size) {
+ output[idx] = input_0[idx] + input_1[idx];
+ }
+}
+
+[[Variants("T", "float, half")]]
+[[Variants("BS", "2, 4, 8")]]
+[[Kernel]] func TestKernelAxis<T: __BuiltinFloatingPointType, let BS: uint32_t>(
+ StructuredBuffer<T> input_0,
+ StructuredBuffer<T> input_1,
+ RWStructuredBuffer<T> output,
+ uint size,
+ [[Axis("size", "threadgroup_size")]] uint idx,
+) {
+ output[idx] = input_0[idx] + input_1[idx];
+}
+
+[[Kernel]] func TestKernelAxisFloat(
+ StructuredBuffer<float> input_0,
+ StructuredBuffer<float> input_1,
+ RWStructuredBuffer<float> output,
+ uint size,
+ [[Axis("size", "threadgroup_size")]] uint idx,
+) {
+ output[idx] = input_0[idx] + input_1[idx];
+}
+
+[[Variants("I", "float, half")]]
+[[Variants("O", "float, half")]]
+[[Kernel]] func TestKernelMultispecialize<I: __BuiltinFloatingPointType, O: __BuiltinFloatingPointType>(
+ StructuredBuffer<I> input,
+ RWStructuredBuffer<O> output,
+ uint size,
+ [[Axis("size", "threadgroup_size")]] uint idx,
+) {
+ output[idx] = O(input[idx].toFloat());
+}
+
+[[Variants("T", "float, half")]]
+[[Variants("BM", "16, 32, 64")]]
+[[Variants("BN", "16, 32, 64")]]
+[[Constraint("BM * BN <= 1024")]]
+[[Kernel]] func TestKernelConstraint<T: __BuiltinFloatingPointType, let BM: uint32_t, let BN: uint32_t>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint rows,
+ uint cols,
+ [[Axis("rows", "BM")]] uint row,
+ [[Axis("cols", "BN")]] uint col,
+) {
+ output[row * cols + col] = input[row * cols + col];
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelSpecialize<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint size,
+ [[Specialize]] bool in_place,
+ [[Axis("size", "threadgroup_size")]] uint idx,
+) {
+ if (in_place) {
+ output[idx] = output[idx] + T(1.0);
+ } else {
+ output[idx] = input[idx];
+ }
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelOptional<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ [[Optional("use_bias")]] StructuredBuffer<T> bias,
+ RWStructuredBuffer<T> output,
+ [[Optional("use_bias")]] uint size,
+ [[Specialize]] bool use_bias,
+ [[Axis("size.unwrap_or(257)", "threadgroup_size")]] uint idx,
+) {
+ T v = input[idx];
+ if (use_bias) {
+ v = v + bias[idx];
+ }
+ output[idx] = v;
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelIndirect<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ StructuredBuffer<uint> tile_map,
+ RWStructuredBuffer<T> output,
+ [[Groups("INDIRECT")]] uint tile_idx,
+ [[Threads("64")]] uint lane,
+) {
+ uint element = tile_map[tile_idx] * 64 + lane;
+ output[element] = input[element];
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelConstantArray<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ int factors[16],
+ RWStructuredBuffer<T> output,
+ uint size,
+ [[Axis("size", "threadgroup_size")]] uint idx,
+) {
+ output[idx] = input[idx] * T(factors[idx % 16]);
+}
+
+[[Variants("T", "float, half")]]
+[[GroupShared("Scratch", "128")]]
+[[Kernel]] func TestKernelGroupsharedSized<T: __BuiltinFloatingPointType, Scratch: IGroupShared<T>>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint batch_size,
+ uint element_count,
+ [[Groups("batch_size")]] uint batch_idx,
+ [[Threads("128")]] uint lane,
+) {
+ T sum = T(0.0);
+ for (uint i = lane; i < element_count; i += 128) {
+ sum += input[batch_idx * element_count + i];
+ }
+ Scratch.store(lane, sum);
+ GroupMemoryBarrierWithGroupSync();
+
+ if (lane == 0) {
+ T total = T(0.0);
+ for (uint i = 0; i < 128; ++i) {
+ total += Scratch.load(i);
+ }
+ output[batch_idx] = total;
+ }
+}
+
+[[Variants("T", "float, half")]]
+[[GroupShared("Carry", "1")]]
+[[Kernel]] func TestKernelGroupsharedRef<T: __BuiltinFloatingPointType, Carry: IGroupShared<T>>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint batch_size,
+ uint element_count,
+ [[Groups("batch_size")]] uint batch_idx,
+ [[Threads("128")]] uint lane,
+) {
+ if (lane == 0) {
+ Carry.store(0, input[batch_idx]);
+ }
+ GroupMemoryBarrierWithGroupSync();
+ if (lane < element_count) {
+ output[batch_idx * element_count + lane] = Carry.load(0);
+ }
+}
+
+groupshared float carry;
+
+struct Carry: IGroupShared<float> {
+ static func load(uint idx) -> float {
+ return carry;
+ }
+ static func store(uint idx, float value) {
+ carry = value;
+ }
+}
+
+[shader("compute")]
+[numthreads(128,1,1)]
+func TestKernelGroupsharedRefEntryFloat(
+ StructuredBuffer<float> input,
+ RWStructuredBuffer<float> output,
+ uniform uint batch_size,
+ uniform uint element_count,
+ uint3 groupId : SV_GroupID,
+ uint3 threadId : SV_GroupThreadID
+) {
+ TestKernelGroupsharedRef<float, Carry>(input, output, batch_size, element_count, groupId.x, threadId.x);
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelAxis2d<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint rows,
+ uint cols,
+ [[Axis("rows", "8")]] uint row,
+ [[Axis("cols", "32")]] uint col,
+) {
+ output[row * cols + col] = input[row * cols + col];
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelGroups2d<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint rows,
+ uint cols,
+ [[Groups("rows.div_ceil(32)")]] uint row_block,
+ [[Groups("cols.div_ceil(32)")]] uint col_block,
+ [[Threads("32")]] uint lane_row,
+ [[Threads("32")]] uint lane_col,
+) {
+ uint row = row_block * 32 + lane_row;
+ uint col = col_block * 32 + lane_col;
+ if (row < rows && col < cols) {
+ output[row * cols + col] = input[row * cols + col];
+ }
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelEnumSpecialize<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint size,
+ [[Specialize]] ActivationType act,
+ [[Axis("size", "threadgroup_size")]] uint idx,
+) {
+ float x = input[idx].toFloat();
+ float y;
+ if (act == ActivationType::SILU) {
+ y = x / (1.0 + exp(-x));
+ } else if (act == ActivationType::GELUApprox) {
+ y = 0.5 * x * (1.0 + tanh(0.7978845608 * (x + 0.044715 * x * x * x)));
+ } else if (act == ActivationType::SOFTPLUS) {
+ y = log(1.0 + exp(x));
+ } else {
+ y = x;
+ }
+ output[idx] = T(y);
+}
+
+[[Kernel]] func TestKernelStructBuffer(
+ StructuredBuffer<Copy> pairs,
+ RWStructuredBuffer<Copy> out_pairs,
+ RWStructuredBuffer<uint> indices,
+ RingParams ring,
+ uint size,
+ [[Axis("size", "threadgroup_size")]] uint idx,
+) {
+ Copy p = pairs[idx];
+ uint dst = (idx + ring.ring_offset) % ring.ring_length;
+ out_pairs[dst] = p;
+ indices[dst] = p.source;
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelEnumRuntime<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ uint size,
+ QuantizationMode mode,
+ [[Axis("size", "threadgroup_size")]] uint idx,
+) {
+ float scale;
+ if (mode == QuantizationMode::U4) {
+ scale = 15.0;
+ } else if (mode == QuantizationMode::I8) {
+ scale = 127.0;
+ } else {
+ scale = 255.0;
+ }
+ output[idx] = T(input[idx].toFloat() * scale);
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelStructScalar<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ Copy copy,
+ uint stride,
+ [[Axis("stride", "threadgroup_size")]] uint idx,
+) {
+ output[copy.destination * stride + idx] = input[copy.source * stride + idx];
+}
+
+[[Variants("T", "float, half")]]
+[[Kernel]] func TestKernelStructConstant<T: __BuiltinFloatingPointType>(
+ StructuredBuffer<T> input,
+ RWStructuredBuffer<T> output,
+ Copy[16] copy,
+ uint stride,
+ [[Axis("stride", "threadgroup_size")]] uint idx,
+) {
+ output[copy[8].destination * stride + idx] = input[copy[8].source * stride + idx];
+}
+
+[shader("compute")]
+[numthreads(threadgroup_size,1,1)]
+func TestKernelStructConstantEntryFloat(
+ StructuredBuffer<float> input,
+ RWStructuredBuffer<float> output,
+ uniform Copy[16] copy,
+ uniform uint stride,
+ uint3 groupId : SV_GroupID,
+ uint3 threadId : SV_GroupThreadID
+) {
+ TestKernelStructConstant<float>(input, output, copy, stride, groupId.x * threadgroup_size + threadId.x);
+}
+
+[[Kernel]] func TestKernelThreadContext(
+ RWStructuredBuffer<ThreadContext> output,
+ uint size,
+ [[Axis("size", "threadgroup_size")]] uint idx,
+ ThreadContext thread_context
+) {
+ output[idx] = thread_context;
+}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/weaver/weaver_selection.slang b/crates/uzu-engine/src/backends/slang/kernel/weaver/weaver_selection.slang
new file mode 100644
index 000000000..576454b3a
--- /dev/null
+++ b/crates/uzu-engine/src/backends/slang/kernel/weaver/weaver_selection.slang
@@ -0,0 +1,40 @@
+// Autogenerated stub
+import definitions;
+import generated.weaver;
+
+[[Variants("BLOCK_THREADS", "256, 1024")]]
+[[Public]] [[Kernel]] func WeaverSelect<let BLOCK_THREADS: uint>(
+ [[Optional("mode != WeaverSelectionMode::Frontier")]] StructuredBuffer<BFloat16> residual_logits,
+ [[Optional("mode != WeaverSelectionMode::Frontier")]] StructuredBuffer<uint64_t> depth_seeds,
+ RWStructuredBuffer<uint> frontier,
+ RWStructuredBuffer<uint> packed_tree,
+ [[Optional("mode != WeaverSelectionMode::Children")]] RWStructuredBuffer<uint> slot_ancestors,
+ [[Optional("mode != WeaverSelectionMode::Children")]] RWStructuredBuffer<uint> node_token_ids,
+ RWStructuredBuffer<uint> node_metadata,
+ [[Optional("mode != WeaverSelectionMode::Children")]] RWStructuredBuffer<uint> node_ancestor_indices,
+ RWStructuredBuffer<uint> node_valid,
+ StructuredBuffer<uint> candidate_pool_ids,
+ StructuredBuffer<float> candidate_pool_logits,
+ RWStructuredBuffer<uint> node_candidate_ids,
+ RWStructuredBuffer<float> node_candidate_logits,
+ uint children_rows,
+ uint children_from_pool,
+ uint candidates,
+ uint expand_width,
+ uint vocab_size,
+ uint frontier_capacity,
+ uint tree_slot_count,
+ uint node_count,
+ uint batch_start_slot,
+ uint ancestor_stride,
+ uint lookahead_count,
+ uint candidate_depth_count,
+ [[Optional("has_prune_noise")]] float prune_noise_scale,
+ [[Specialize]] WeaverSelectionMode mode,
+ [[Specialize]] bool has_prune_noise,
+ ThreadContext global_context,
+ [[Groups("if mode == WeaverSelectionMode::Children { children_rows } else {1}")]] uint group_index,
+ [[Threads("BLOCK_THREADS")]] uint global_lid,
+) {
+ // TODO
+}
diff --git a/crates/uzu-engine/src/backends/webgpu/backend.rs b/crates/uzu-engine/src/backends/webgpu/backend.rs
new file mode 100644
index 000000000..48ccfac68
--- /dev/null
+++ b/crates/uzu-engine/src/backends/webgpu/backend.rs
@@ -0,0 +1,41 @@
+use std::convert::Infallible;
+
+use crate::backends::{
+ common::{
+ Backend,
+ allocator::{
+ bump::BumpAllocation,
+ pool::{PoolAllocation, PoolAllocator},
+ },
+ },
+ webgpu::{
+ buffer::{
+ dense::{WebGPUDenseBufferCpuGpu, WebGPUDenseBufferGpu},
+ sparse::WebGPUSparseBuffer,
+ },
+ command_buffer::{WebGPUCommandBuffer, WebGPUCommandBufferEncoding},
+ context::WebGPUContext,
+ error::WebGPUError,
+ kernel::WebGPUKernels,
+ },
+};
+
+#[derive(Debug, Clone)]
+pub struct WebGPU;
+
+impl Backend for WebGPU {
+ type Context = WebGPUContext;
+ type CommandBuffer = WebGPUCommandBuffer;
+ type DebugGroupSpan<'a> = &'a mut WebGPUCommandBufferEncoding;
+ type GlobalGpuBuffer = WebGPUDenseBufferGpu;
+ type GlobalBufferCpuGpu = WebGPUDenseBufferCpuGpu;
+ type ConstantBuffer = BumpAllocation<WebGPUDenseBufferCpuGpu>;
+ type ScratchBuffer = PoolAllocation<WebGPUDenseBufferGpu>;
+ type AllocationPool = PoolAllocator<WebGPUDenseBufferGpu>;
+ type CaptureSpan = Infallible;
+ type SparseBuffer = WebGPUSparseBuffer;
+ type Kernels = WebGPUKernels;
+ type Error = WebGPUError;
+
+ const NAME: &'static str = "webgpu";
+}
diff --git a/crates/uzu-engine/src/backends/webgpu/buffer/dense.rs b/crates/uzu-engine/src/backends/webgpu/buffer/dense.rs
new file mode 100644
index 000000000..2caf69f0f
--- /dev/null
+++ b/crates/uzu-engine/src/backends/webgpu/buffer/dense.rs
@@ -0,0 +1,128 @@
+use std::{mem::ManuallyDrop, os::raw::c_void, ptr::NonNull};
+
+use crate::{
+ backends::{
+ common::{Buffer, CpuBuffer, GlobalBufferCpuGpu, GlobalGpuBuffer, GpuBuffer, allocator::bump::BumpAllocation},
+ webgpu::{WebGPU, context::WebGPUContext, error::WebGPUError},
+ },
+ utils::pointers::SendPtrMut,
+};
+
+#[derive(Debug)]
+pub struct WebGPUDenseBufferGpu {
+ buffer: wgpu::Buffer,
+ size: usize,
+}
+
+impl WebGPUDenseBufferGpu {
+ pub(in crate::backends::webgpu) fn new(
+ context: &WebGPUContext,
+ size: usize,
+ ) -> Result<Self, WebGPUError> {
+ let buffer = context.device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size: size.next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT as usize) as u64,
+ usage: wgpu::BufferUsages::UNIFORM
+ | wgpu::BufferUsages::STORAGE
+ | wgpu::BufferUsages::INDIRECT
+ | wgpu::BufferUsages::COPY_SRC
+ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+
+ Ok(Self {
+ buffer,
+ size,
+ })
+ }
+
+ pub(in crate::backends::webgpu) fn wgpu_buffer(&self) -> &wgpu::Buffer {
+ &self.buffer
+ }
+}
+
+impl Buffer for WebGPUDenseBufferGpu {
+ type Backend = WebGPU;
+
+ fn size(&self) -> usize {
+ self.size
+ }
+}
+
+impl GpuBuffer for WebGPUDenseBufferGpu {}
+
+impl GlobalGpuBuffer for WebGPUDenseBufferGpu {}
+
+#[derive(Debug)]
+pub struct WebGPUDenseBufferCpuGpu {
+ cpu_ptr: SendPtrMut<c_void>,
+ view: ManuallyDrop<wgpu::BufferViewMut>,
+ buffer: wgpu::Buffer,
+ size: usize,
+}
+
+impl WebGPUDenseBufferCpuGpu {
+ pub(in crate::backends::webgpu) fn new(
+ context: &WebGPUContext,
+ size: usize,
+ ) -> Result<Self, WebGPUError> {
+ let buffer = context.device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size: size.next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT as usize) as u64,
+ usage: wgpu::BufferUsages::UNIFORM
+ | wgpu::BufferUsages::STORAGE
+ | wgpu::BufferUsages::INDIRECT
+ | wgpu::BufferUsages::COPY_SRC
+ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: true,
+ });
+
+ let mut view = buffer.get_mapped_range_mut(..)?;
+ let cpu_ptr = SendPtrMut(view.slice(..).as_raw_element_ptr().cast().as_ptr());
+
+ Ok(Self {
+ cpu_ptr,
+ view: ManuallyDrop::new(view),
+ buffer,
+ size,
+ })
+ }
+
+ pub(in crate::backends::webgpu) fn wgpu_buffer(&self) -> &wgpu::Buffer {
+ &self.buffer
+ }
+}
+
+impl Drop for WebGPUDenseBufferCpuGpu {
+ fn drop(&mut self) {
+ unsafe { ManuallyDrop::drop(&mut self.view) };
+ self.buffer.unmap();
+ }
+}
+
+impl Buffer for WebGPUDenseBufferCpuGpu {
+ type Backend = WebGPU;
+
+ fn size(&self) -> usize {
+ self.size
+ }
+}
+
+impl GpuBuffer for BumpAllocation<WebGPUDenseBufferCpuGpu> {}
+
+impl CpuBuffer for WebGPUDenseBufferCpuGpu {
+ fn cpu_ptr(&self) -> NonNull<c_void> {
+ unsafe { NonNull::new_unchecked(self.cpu_ptr.as_ptr()) }
+ }
+}
+
+impl GlobalBufferCpuGpu for WebGPUDenseBufferCpuGpu {
+ fn handoff(self) -> WebGPUDenseBufferGpu {
+ let gpu = WebGPUDenseBufferGpu {
+ buffer: self.buffer.clone(),
+ size: self.size,
+ };
+ drop(self);
+ gpu
+ }
+}
diff --git a/crates/uzu-engine/src/backends/webgpu/buffer/mod.rs b/crates/uzu-engine/src/backends/webgpu/buffer/mod.rs
new file mode 100644
index 000000000..38c324561
--- /dev/null
+++ b/crates/uzu-engine/src/backends/webgpu/buffer/mod.rs
@@ -0,0 +1,28 @@
+use std::range::Range;
+
+use crate::{
+ backends::{
+ common::{Backend, GpuBuffer},
+ webgpu::WebGPU,
+ },
+ utils::downcast::downcast_ref,
+};
+
+pub mod dense;
+pub mod sparse;
+
+pub fn binding_parts(
+ buffer: &(impl GpuBuffer<Backend = WebGPU> + ?Sized),
+ range: Range<usize>,
+) -> (&wgpu::Buffer, usize, usize) {
+ let (buffer, offset) = if let Some(buffer) = downcast_ref::<<WebGPU as Backend>::GlobalGpuBuffer>(buffer) {
+ (buffer.wgpu_buffer(), 0)
+ } else if let Some(buffer) = downcast_ref::<<WebGPU as Backend>::ConstantBuffer>(buffer) {
+ (buffer.page().wgpu_buffer(), buffer.range().start)
+ } else if let Some(buffer) = downcast_ref::<<WebGPU as Backend>::ScratchBuffer>(buffer) {
+ (buffer.page().wgpu_buffer(), buffer.range().start)
+ } else {
+ unreachable!()
+ };
+ (buffer, offset + range.start, range.iter().len())
+}
diff --git a/crates/uzu-engine/src/backends/webgpu/buffer/sparse.rs b/crates/uzu-engine/src/backends/webgpu/buffer/sparse.rs
new file mode 100644
index 000000000..aab46a575
--- /dev/null
+++ b/crates/uzu-engine/src/backends/webgpu/buffer/sparse.rs
@@ -0,0 +1,28 @@
+use std::convert::Infallible;
+
+use crate::backends::{
+ common::{Buffer, GpuBuffer, SparseBuffer},
+ webgpu::{WebGPU, error::WebGPUError},
+};
+
+#[derive(Debug)]
+pub struct WebGPUSparseBuffer(Infallible);
+
+impl Buffer for WebGPUSparseBuffer {
+ type Backend = WebGPU;
+
+ fn size(&self) -> usize {
+ match self.0 {}
+ }
+}
+
+impl GpuBuffer for WebGPUSparseBuffer {}
+
+impl SparseBuffer for WebGPUSparseBuffer {
+ fn map(
+ &mut self,
+ _until: usize,
+ ) -> Result<(), WebGPUError> {
+ match self.0 {}
+ }
+}
diff --git a/crates/uzu-engine/src/backends/webgpu/command_buffer.rs b/crates/uzu-engine/src/backends/webgpu/command_buffer.rs
new file mode 100644
index 000000000..09bb25205
--- /dev/null
+++ b/crates/uzu-engine/src/backends/webgpu/command_buffer.rs
@@ -0,0 +1,221 @@
+#[cfg(not(target_arch = "wasm32"))]
+use std::thread;
+use std::{sync::Arc, time::Duration};
+
+use futures::channel::oneshot;
+
+use crate::backends::{
+ common::{
+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferCompleted, CommandBufferEncoding,
+ CommandBufferExecutable, CommandBufferPending, TimestampSpan, allocator::bump::BumpAllocator,
+ },
+ webgpu::{
+ WebGPU,
+ buffer::{
+ binding_parts,
+ dense::{WebGPUDenseBufferCpuGpu, WebGPUDenseBufferGpu},
+ },
+ context::WebGPUContext,
+ error::WebGPUError,
+ },
+};
+
+pub struct WebGPUCommandBuffer;
+
+impl CommandBuffer for WebGPUCommandBuffer {
+ type Backend = WebGPU;
+
+ type Encoding = WebGPUCommandBufferEncoding;
+ type Executable = WebGPUCommandBufferExecutable;
+ type Pending = WebGPUCommandBufferPending;
+ type Completed = WebGPUCommandBufferCompleted;
+}
+
+pub struct WebGPUCommandBufferEncoding {
+ compute_pass: Option<wgpu::ComputePass<'static>>,
+ command_encoder: wgpu::CommandEncoder,
+ constant_allocator: BumpAllocator<WebGPUDenseBufferCpuGpu>,
+ allocation_pool: Arc<<WebGPU as Backend>::AllocationPool>,
+ context: Arc<WebGPUContext>,
+}
+
+// TODO: workaround for wgpu trait solver overflow
+unsafe impl Send for WebGPUCommandBufferEncoding {}
+
+impl WebGPUCommandBufferEncoding {
+ pub fn new(
+ context: Arc<WebGPUContext>,
+ name: Option<&str>,
+ allocation_pool: Arc<<WebGPU as Backend>::AllocationPool>,
+ ) -> Self {
+ let command_encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: name,
+ });
+
+ let constant_allocator = BumpAllocator::new(256 * 1024, wgpu::COPY_BUFFER_ALIGNMENT as usize);
+
+ Self {
+ compute_pass: None,
+ command_encoder,
+ constant_allocator,
+ allocation_pool,
+ context,
+ }
+ }
+
+ fn ensure_none(&mut self) {
+ self.compute_pass = None;
+ }
+
+ pub(super) fn ensure_compute(&mut self) -> &mut wgpu::ComputePass<'static> {
+ if self.compute_pass.is_none() {
+ let compute_pass = self.command_encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default());
+ self.compute_pass = Some(compute_pass.forget_lifetime());
+ }
+
+ self.compute_pass.as_mut().unwrap()
+ }
+}
+
+impl CommandBufferEncoding for WebGPUCommandBufferEncoding {
+ type CommandBuffer = WebGPUCommandBuffer;
+
+ fn context(&self) -> &WebGPUContext {
+ &self.context
+ }
+
+ fn allocate_constant(
+ &mut self,
+ size: usize,
+ ) -> Result<<WebGPU as Backend>::ConstantBuffer, WebGPUError> {
+ let alignment = usize::min(size, 64)
+ .next_power_of_two()
+ .max(self.context.limits.min_uniform_buffer_offset_alignment as usize)
+ .max(self.context.limits.min_storage_buffer_offset_alignment as usize)
+ .max(wgpu::COPY_BUFFER_ALIGNMENT as usize);
+ self.constant_allocator.allocate(size, alignment, |size| WebGPUDenseBufferCpuGpu::new(&self.context, size))
+ }
+
+ fn allocate_scratch(
+ &mut self,
+ size: usize,
+ ) -> Result<<WebGPU as Backend>::ScratchBuffer, WebGPUError> {
+ self.allocation_pool.allocate(size, |size| WebGPUDenseBufferGpu::new(&self.context, size))
+ }
+
+ fn encode_copy(
+ &mut self,
+ src: impl BufferRef<Backend = WebGPU>,
+ dst: impl BufferMut<Backend = WebGPU>,
+ ) {
+ self.ensure_none();
+ let (src, src_range) = src.parts();
+ let (dst, dst_range) = dst.parts();
+ let (src, src_offset, src_size) = binding_parts(src, src_range);
+ let (dst, dst_offset, dst_size) = binding_parts(dst, dst_range);
+ assert_eq!(src_size, dst_size);
+ self.command_encoder.copy_buffer_to_buffer(src, src_offset as u64, dst, dst_offset as u64, dst_size as u64);
+ }
+
+ fn encode_fill(
+ &mut self,
+ dst: impl BufferMut<Backend = WebGPU>,
+ value: u8,
+ ) {
+ assert!(value == 0, "non-zero fill not supported yet"); // TODO
+ self.ensure_none();
+ let (dst, range) = dst.parts();
+ let (dst, offset, size) = binding_parts(dst, range);
+ self.command_encoder.clear_buffer(dst, offset as u64, Some(size as u64));
+ }
+
+ fn debug_group(
+ &mut self,
+ _name: &str,
+ ) -> <WebGPU as Backend>::DebugGroupSpan<'_> {
+ self
+ }
+
+ fn debug_point(
+ &mut self,
+ _name: &str,
+ ) {
+ }
+
+ fn with_timestamps(self) -> Self {
+ unimplemented!()
+ }
+
+ fn end_encoding(mut self) -> WebGPUCommandBufferExecutable {
+ self.ensure_none();
+
+ assert!(self.constant_allocator.is_done(), "attempted to end encoding while constants are still alive");
+
+ WebGPUCommandBufferExecutable {
+ command_buffer: self.command_encoder.finish(),
+ context: self.context,
+ }
+ }
+}
+
+pub struct WebGPUCommandBufferExecutable {
+ command_buffer: wgpu::CommandBuffer,
+ context: Arc<WebGPUContext>,
+}
+
+impl CommandBufferExecutable for WebGPUCommandBufferExecutable {
+ type CommandBuffer = WebGPUCommandBuffer;
+
+ fn submit(self) -> WebGPUCommandBufferPending {
+ let (sender, receiver) = oneshot::channel();
+
+ self.command_buffer.on_submitted_work_done(move || {
+ let _ = sender.send(());
+ });
+
+ let submission_index = self.context.queue.submit([self.command_buffer]);
+
+ #[cfg(not(target_arch = "wasm32"))]
+ thread::spawn(move || {
+ let _ = self.context.device.poll(wgpu::PollType::Wait {
+ submission_index: Some(submission_index),
+ timeout: None,
+ });
+ });
+
+ #[cfg(target_arch = "wasm32")]
+ let _ = submission_index;
+
+ WebGPUCommandBufferPending {
+ completed_signal: receiver,
+ }
+ }
+}
+
+pub struct WebGPUCommandBufferPending {
+ completed_signal: oneshot::Receiver<()>,
+}
+
+impl CommandBufferPending for WebGPUCommandBufferPending {
+ type CommandBuffer = WebGPUCommandBuffer;
+
+ async fn wait_until_completed(self) -> Result<WebGPUCommandBufferCompleted, WebGPUError> {
+ self.completed_signal.await.map_err(|_| WebGPUError::CommandBuffer)?;
+
+ Ok(WebGPUCommandBufferCompleted)
+ }
+}
+
+pub struct WebGPUCommandBufferCompleted;
+
+impl CommandBufferCompleted for WebGPUCommandBufferCompleted {
+ type CommandBuffer = WebGPUCommandBuffer;
+
+ fn gpu_execution_time(&self) -> Option<Duration> {
+ None
+ }
+
+ fn timestamps(&self) -> &[TimestampSpan] {
+ unimplemented!()
+ }
+}
diff --git a/crates/uzu-engine/src/backends/webgpu/context.rs b/crates/uzu-engine/src/backends/webgpu/context.rs
new file mode 100644
index 000000000..932afad10
--- /dev/null
+++ b/crates/uzu-engine/src/backends/webgpu/context.rs
@@ -0,0 +1,274 @@
+#[cfg(not(target_arch = "wasm32"))]
+use std::thread;
+use std::{
+ borrow::Cow,
+ collections::{HashMap, hash_map::Entry},
+ convert::Infallible,
+ path::Path,
+ sync::{Arc, Weak},
+};
+
+use futures::channel::oneshot;
+use parking_lot::Mutex;
+
+use crate::backends::{
+ common::{Backend, BufferRef, Context, DeviceCapabilities, allocator::pool::PoolAllocator},
+ webgpu::{
+ WebGPU,
+ buffer::dense::{WebGPUDenseBufferCpuGpu, WebGPUDenseBufferGpu},
+ command_buffer::WebGPUCommandBufferEncoding,
+ error::WebGPUError,
+ },
+};
+
+#[derive(PartialEq, Eq, Hash)]
+struct PipelineCacheKey {
+ shader_module: wgpu::ShaderModule,
+ pipeline_layout: wgpu::PipelineLayout,
+ constants: Vec<(&'static str, [u8; 8])>,
+ entry_point: &'static str,
+}
+
+pub struct WebGPUContext {
+ pipeline_cache: Mutex<HashMap<PipelineCacheKey, wgpu::ComputePipeline>>,
+ pipeline_layout_cache: Mutex<HashMap<wgpu::BindGroupLayout, wgpu::PipelineLayout>>,
+ bind_group_layout_cache: Mutex<HashMap<Vec<wgpu::BindGroupLayoutEntry>, wgpu::BindGroupLayout>>,
+ shader_module_cache: Mutex<HashMap<&'static str, wgpu::ShaderModule>>,
+ pub(super) queue: wgpu::Queue,
+ pub(super) limits: wgpu::Limits,
+ pub(super) device: wgpu::Device,
+ _adapter: wgpu::Adapter,
+ _instance: wgpu::Instance,
+ device_name: String,
+ weak_self: Weak<WebGPUContext>,
+}
+
+impl WebGPUContext {
+ pub(super) fn get_shader_module(
+ &self,
+ source: &'static str,
+ ) -> wgpu::ShaderModule {
+ match self.shader_module_cache.lock().entry(source) {
+ Entry::Occupied(occupied) => occupied.get().clone(),
+ Entry::Vacant(vacant) => {
+ let module = self.device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: None,
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(source)),
+ });
+ vacant.insert(module).clone()
+ },
+ }
+ }
+
+ pub(super) fn get_bind_group_layout(
+ &self,
+ entries: impl IntoIterator<Item = wgpu::BindGroupLayoutEntry>,
+ ) -> wgpu::BindGroupLayout {
+ let entries = entries.into_iter().collect::<Vec<wgpu::BindGroupLayoutEntry>>();
+
+ match self.bind_group_layout_cache.lock().entry(entries) {
+ Entry::Occupied(occupied) => occupied.get().clone(),
+ Entry::Vacant(vacant) => {
+ let bind_group_layout = self.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: None,
+ entries: vacant.key(),
+ });
+ vacant.insert(bind_group_layout).clone()
+ },
+ }
+ }
+
+ pub(super) fn get_pipeline_layout(
+ &self,
+ bind_group_layout: wgpu::BindGroupLayout,
+ ) -> wgpu::PipelineLayout {
+ match self.pipeline_layout_cache.lock().entry(bind_group_layout) {
+ Entry::Occupied(occupied) => occupied.get().clone(),
+ Entry::Vacant(vacant) => {
+ let pipeline_layout = self.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[Some(vacant.key())],
+ immediate_size: 0,
+ });
+ vacant.insert(pipeline_layout).clone()
+ },
+ }
+ }
+
+ pub(super) fn get_pipeline(
+ &self,
+ shader_module: wgpu::ShaderModule,
+ pipeline_layout: wgpu::PipelineLayout,
+ constants: Vec<(&'static str, f64)>,
+ entry_point: &'static str,
+ ) -> wgpu::ComputePipeline {
+ let constants =
+ constants.into_iter().map(|(k, v)| (k, bytemuck::cast(v))).collect::<Vec<(&'static str, [u8; 8])>>();
+
+ match self.pipeline_cache.lock().entry(PipelineCacheKey {
+ shader_module,
+ pipeline_layout,
+ constants,
+ entry_point,
+ }) {
+ Entry::Occupied(occupied) => occupied.get().clone(),
+ Entry::Vacant(vacant) => {
+ let key = vacant.key();
+
+ let constants =
+ key.constants.iter().map(|(k, v)| (*k, bytemuck::cast(*v))).collect::<Vec<(&'static str, f64)>>();
+
+ let pipeline = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None,
+ layout: Some(&key.pipeline_layout),
+ module: &key.shader_module,
+ entry_point: Some(key.entry_point),
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &constants,
+ zero_initialize_workgroup_memory: true, // required on non-native
+ },
+ cache: None,
+ });
+ vacant.insert(pipeline).clone()
+ },
+ }
+ }
+}
+
+impl Context for WebGPUContext {
+ type Backend = WebGPU;
+
+ async fn new() -> Result<Arc<Self>, WebGPUError> {
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
+ let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions::default()).await?;
+ if !adapter.get_downlevel_capabilities().flags.contains(wgpu::DownlevelFlags::SHADER_F16_IN_F32) {
+ return Err(WebGPUError::NotSupported);
+ }
+ let (device, queue) = adapter
+ .request_device(&wgpu::DeviceDescriptor {
+ required_features: wgpu::Features::SHADER_F16
+ | wgpu::Features::SUBGROUP
+ | wgpu::Features::SUBGROUP_BARRIER,
+ required_limits: adapter.limits(), // TODO: specify actual limits
+ ..Default::default()
+ })
+ .await?;
+
+ Ok(Arc::new_cyclic(|weak_self| WebGPUContext {
+ pipeline_cache: Mutex::new(HashMap::new()),
+ pipeline_layout_cache: Mutex::new(HashMap::new()),
+ bind_group_layout_cache: Mutex::new(HashMap::new()),
+ shader_module_cache: Mutex::new(HashMap::new()),
+ queue,
+ limits: device.limits(),
+ device,
+ device_name: adapter.get_info().name,
+ _adapter: adapter,
+ _instance: instance,
+ weak_self: weak_self.clone(),
+ }))
+ }
+
+ fn device_name(&self) -> Option<&str> {
+ Some(&self.device_name)
+ }
+
+ fn create_command_buffer(
+ &self,
+ name: Option<&str>,
+ allocation_pool: Option<Arc<<WebGPU as Backend>::AllocationPool>>,
+ ) -> Result<WebGPUCommandBufferEncoding, WebGPUError> {
+ Ok(WebGPUCommandBufferEncoding::new(
+ self.weak_self.upgrade().unwrap(),
+ name,
+ allocation_pool.unwrap_or_else(|| self.create_allocation_pool()),
+ ))
+ }
+
+ fn create_buffer_gpu(
+ &self,
+ size: usize,
+ ) -> Result<<WebGPU as Backend>::GlobalGpuBuffer, WebGPUError> {
+ WebGPUDenseBufferGpu::new(self, size)
+ }
+
+ fn create_buffer_cpu_gpu(
+ &self,
+ size: usize,
+ ) -> Result<<WebGPU as Backend>::GlobalBufferCpuGpu, WebGPUError> {
+ WebGPUDenseBufferCpuGpu::new(self, size)
+ }
+
+ fn copyout<T: bytemuck::AnyBitPattern>(
+ &self,
+ buffer: impl BufferRef<Backend = WebGPU, Buffer = WebGPUDenseBufferGpu>,
+ ) -> impl Future<Output = Result<Vec<T>, <Self::Backend as Backend>::Error>> + Send {
+ let (buffer, buffer_range) = buffer.parts();
+
+ let cpu_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size: buffer_range.iter().len() as u64,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+
+ let mut command_encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ command_encoder.copy_buffer_to_buffer(
+ buffer.wgpu_buffer(),
+ buffer_range.start as u64,
+ &cpu_buffer,
+ 0,
+ buffer_range.iter().len() as u64,
+ );
+ let submission_index = self.queue.submit([command_encoder.finish()]);
+
+ let (sender, receiver) = oneshot::channel();
+ cpu_buffer.map_async(wgpu::MapMode::Read, .., move |err| {
+ let _ = sender.send(err);
+ });
+
+ #[cfg(not(target_arch = "wasm32"))]
+ let context = self.weak_self.upgrade().unwrap();
+ #[cfg(not(target_arch = "wasm32"))]
+ thread::spawn(move || {
+ let _ = context.device.poll(wgpu::PollType::Wait {
+ submission_index: Some(submission_index),
+ timeout: None,
+ });
+ });
+
+ #[cfg(target_arch = "wasm32")]
+ let _ = submission_index;
+
+ async move {
+ receiver.await.map_err(|_| WebGPUError::CommandBuffer)??;
+ Ok(bytemuck::cast_slice(&cpu_buffer.get_mapped_range(..)?).to_vec())
+ }
+ }
+
+ fn create_allocation_pool(&self) -> Arc<<WebGPU as Backend>::AllocationPool> {
+ PoolAllocator::new()
+ }
+
+ fn create_sparse_buffer(
+ &self,
+ _capacity: usize,
+ ) -> Result<<Self::Backend as Backend>::SparseBuffer, <Self::Backend as Backend>::Error> {
+ Err(WebGPUError::NotSupported)
+ }
+
+ fn peak_memory_usage(&self) -> Option<usize> {
+ None
+ }
+
+ fn start_capture(
+ &self,
+ _trace_path: &Path,
+ ) -> Result<Infallible, WebGPUError> {
+ Err(WebGPUError::NotSupported)
+ }
+
+ fn device_capabilities(&self) -> DeviceCapabilities {
+ DeviceCapabilities::empty()
+ }
+}
diff --git a/crates/uzu-engine/src/backends/webgpu/error.rs b/crates/uzu-engine/src/backends/webgpu/error.rs
new file mode 100644
index 000000000..a7ea44605
--- /dev/null
+++ b/crates/uzu-engine/src/backends/webgpu/error.rs
@@ -0,0 +1,19 @@
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum WebGPUError {
+ #[error("Not supported")]
+ NotSupported,
+ #[error("Request adapter error: {0}")]
+ RequestAdapter(#[from] wgpu::RequestAdapterError),
+ #[error("Request device error: {0}")]
+ RequestDevice(#[from] wgpu::RequestDeviceError),
+ #[error("Map range error: {0}")]
+ MapRange(#[from] wgpu::MapRangeError),
+ #[error("Async map error: {0}")]
+ AsyncMap(#[from] wgpu::BufferAsyncError),
+ #[error("Command buffer failed")]
+ CommandBuffer,
+ #[error("Unsupported kernel variant: {0}")]
+ UnsupportedKernelVariant(String),
+}
diff --git a/crates/uzu-engine/src/backends/webgpu/kernel.rs b/crates/uzu-engine/src/backends/webgpu/kernel.rs
new file mode 100644
index 000000000..c13682325
--- /dev/null
+++ b/crates/uzu-engine/src/backends/webgpu/kernel.rs
@@ -0,0 +1,112 @@
+use crate::{
+ backends::{
+ common::{
+ Backend, BufferMut, BufferRef, CommandBufferEncoding, Kernels,
+ kernel::{
+ AttentionArguments, AttentionInput, AttentionKernel, AttentionKernelConfig, Unsupported,
+ matmul::{MatmulArguments, MatmulKernel},
+ radix_top_k_small::RadixTopKSmall,
+ },
+ },
+ webgpu::{
+ WebGPU, buffer::binding_parts, command_buffer::WebGPUCommandBufferEncoding, context::WebGPUContext,
+ error::WebGPUError,
+ },
+ },
+ data_type::DataType,
+};
+
+include!(concat!(env!("OUT_DIR"), "/webgpu.rs"));
+
+impl Kernels for WebGPUKernels {
+ type Backend = WebGPU;
+
+ autogen_kernels!();
+ type AttentionKernel = Unsupported<WebGPU>;
+ type DeltaNetChunkedPrefill = Unsupported<WebGPU>;
+ type DeltaNetTreeVerify = Unsupported<WebGPU>;
+ type MatmulKernel = Unsupported<WebGPU>;
+ type RadixTopKSmall = Unsupported<WebGPU>;
+}
+
+impl AttentionKernel for Unsupported<WebGPU> {
+ type Backend = WebGPU;
+ type Error = WebGPUError;
+
+ fn new(
+ _context: &WebGPUContext,
+ _config: AttentionKernelConfig,
+ ) -> Result<Self, WebGPUError> {
+ Err(WebGPUError::NotSupported)
+ }
+
+ fn encode(
+ &self,
+ _input: AttentionInput<
+ impl BufferRef<Backend = WebGPU>,
+ impl BufferRef<Backend = WebGPU>,
+ impl BufferRef<Backend = WebGPU>,
+ >,
+ _arguments: AttentionArguments<'_, WebGPU, impl BufferRef<Backend = WebGPU>, impl BufferRef<Backend = WebGPU>>,
+ _command_buffer: &mut WebGPUCommandBufferEncoding,
+ ) -> Result<<WebGPU as Backend>::ScratchBuffer, WebGPUError> {
+ Err(WebGPUError::NotSupported)
+ }
+}
+
+impl MatmulKernel for Unsupported<WebGPU> {
+ type Backend = WebGPU;
+ type Error = WebGPUError;
+ type WeightsLayout = ();
+
+ fn new(
+ _context: &WebGPUContext,
+ _weights_data_type: DataType,
+ _input_data_type: DataType,
+ _output_data_type: DataType,
+ ) -> Result<Self, WebGPUError> {
+ Err(WebGPUError::NotSupported)
+ }
+
+ fn encode(
+ &mut self,
+ _arguments: MatmulArguments<
+ '_,
+ WebGPU,
+ impl BufferRef<Backend = WebGPU>,
+ impl BufferRef<Backend = WebGPU>,
+ impl BufferMut<Backend = WebGPU>,
+ impl BufferRef<Backend = WebGPU>,
+ >,
+ _command_buffer: &mut WebGPUCommandBufferEncoding,
+ ) -> Result<(), WebGPUError> {
+ Err(WebGPUError::NotSupported)
+ }
+}
+
+impl RadixTopKSmall for Unsupported<WebGPU> {
+ type Backend = WebGPU;
+
+ fn new(
+ _context: &WebGPUContext,
+ _columns: u32,
+ ) -> Result<Self, WebGPUError> {
+ Err(WebGPUError::NotSupported)
+ }
+
+ fn encode(
+ &self,
+ _input: impl BufferRef<Backend = WebGPU>,
+ _output_ids: impl BufferMut<Backend = WebGPU>,
+ _output_scores: impl BufferMut<Backend = WebGPU>,
+ _rows: u32,
+ _k: u32,
+ _command_buffer: &mut WebGPUCommandBufferEncoding,
+ ) -> Result<(), WebGPUError> {
+ Err(WebGPUError::NotSupported)
+ }
+}
+
+#[cfg(test)]
+#[path = "../../../unit/backends/webgpu/kernel/mod.rs"]
+mod tests;
diff --git a/crates/uzu-engine/src/backends/webgpu/mod.rs b/crates/uzu-engine/src/backends/webgpu/mod.rs
new file mode 100644
index 000000000..e4412beca
--- /dev/null
+++ b/crates/uzu-engine/src/backends/webgpu/mod.rs
@@ -0,0 +1,8 @@
+mod backend;
+mod buffer;
+mod command_buffer;
+mod context;
+mod error;
+mod kernel;
+
+pub use backend::WebGPU;
diff --git a/crates/uzu-engine/src/encodable_block/classifier.rs b/crates/uzu-engine/src/encodable_block/classifier.rs
index 3225f1ac4..9304eef10 100644
--- a/crates/uzu-engine/src/encodable_block/classifier.rs
+++ b/crates/uzu-engine/src/encodable_block/classifier.rs
@@ -47,10 +47,10 @@ pub struct Classifier<B: Backend> {
}
impl<B: Backend> Classifier<B> {
- pub fn new(
+ pub async fn new(
data_type: DataType,
config: &ClassifierConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, ClassifierError<B>> {
let (embedding, _) = Embedding::new(
@@ -60,7 +60,8 @@ impl<B: Backend> Classifier<B> {
&config.embedding_config,
&parameter_tree.subtree("embedding"),
context,
- )?;
+ )
+ .await?;
let embedding_norm = Normalization::new(
config.transformer_config.model_dim,
@@ -71,7 +72,8 @@ impl<B: Backend> Classifier<B> {
&config.embedding_norm_config,
&parameter_tree.subtree("embedding_norm"),
context,
- )?;
+ )
+ .await?;
let transformer = Transformer::new(
data_type,
@@ -79,7 +81,8 @@ impl<B: Backend> Classifier<B> {
&config.transformer_config,
&parameter_tree.subtree("transformer"),
context,
- )?;
+ )
+ .await?;
if config.classifier_pooling != PoolingType::Mean {
return Err(ClassifierError::UnsupportedConfiguration(format!(
@@ -97,7 +100,8 @@ impl<B: Backend> Classifier<B> {
&config.prediction_head_config,
&parameter_tree.subtree("prediction_head"),
context,
- )?;
+ )
+ .await?;
Ok(Self {
hidden_dim: config.hidden_dim,
diff --git a/crates/uzu-engine/src/encodable_block/convolution.rs b/crates/uzu-engine/src/encodable_block/convolution.rs
index 064c31cf8..cb2e375f0 100644
--- a/crates/uzu-engine/src/encodable_block/convolution.rs
+++ b/crates/uzu-engine/src/encodable_block/convolution.rs
@@ -23,19 +23,19 @@ pub enum ConvolutionNewError<B: Backend> {
pub struct SeparableCausalConv<B: Backend> {
model_dim: u32,
data_type: DataType,
- weights: B::GlobalBuffer,
- biases: Option<B::GlobalBuffer>,
+ weights: B::GlobalGpuBuffer,
+ biases: Option<B::GlobalGpuBuffer>,
kernel: <B::Kernels as Kernels>::SeparableCausalConvKernel,
}
impl<B: Backend> SeparableCausalConv<B> {
- pub fn new(
+ pub async fn new(
model_dim: u32,
kernel_size: u32,
group_size: u32,
data_type: DataType,
config: &SeparableCausalConvConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, ConvolutionNewError<B>> {
assert!(model_dim.is_multiple_of(4));
@@ -43,12 +43,13 @@ impl<B: Backend> SeparableCausalConv<B> {
assert!(model_dim.is_multiple_of(group_size));
assert_eq!(data_type, DataType::BF16, "SeparableCausalConv only supports BF16");
- let weights = parameter_tree.read_buffer("weights", &[model_dim, kernel_size], DataType::BF16)?;
+ let weights = parameter_tree.read_buffer("weights", &[model_dim, kernel_size], DataType::BF16).await?;
- let biases = config
- .has_biases
- .then(|| parameter_tree.read_buffer("biases", &[model_dim], DataType::BF16))
- .transpose()?;
+ let biases = if config.has_biases {
+ Some(parameter_tree.read_buffer("biases", &[model_dim], DataType::BF16).await?)
+ } else {
+ None
+ };
let kernel = <B::Kernels as Kernels>::SeparableCausalConvKernel::new(
context,
diff --git a/crates/uzu-engine/src/encodable_block/decoder.rs b/crates/uzu-engine/src/encodable_block/decoder.rs
index b35078f49..e219213fd 100644
--- a/crates/uzu-engine/src/encodable_block/decoder.rs
+++ b/crates/uzu-engine/src/encodable_block/decoder.rs
@@ -51,10 +51,10 @@ impl<B: Backend> Decoder<B> {
&self.embedding
}
- pub fn new(
+ pub async fn new(
data_type: DataType,
config: &DecoderConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, DecoderError<B>> {
let (embedding, readout_input_hadamard_factors) = Embedding::new(
@@ -64,12 +64,11 @@ impl<B: Backend> Decoder<B> {
&config.embedding_config,
&parameter_tree.subtree("embedding"),
context,
- )?;
+ )
+ .await?;
- let embedding_norm = config
- .embedding_norm_config
- .as_ref()
- .map(|norm_config| {
+ let embedding_norm = if let Some(norm_config) = &config.embedding_norm_config {
+ Some(
Normalization::new(
config.transformer_config.model_dim,
data_type,
@@ -80,8 +79,11 @@ impl<B: Backend> Decoder<B> {
&parameter_tree.subtree("embedding_norm"),
context,
)
- })
- .transpose()?;
+ .await?,
+ )
+ } else {
+ None
+ };
let per_layer_embedding = if let Some(ple_config) = &config.ple_model_config {
assert_eq!(
@@ -89,13 +91,16 @@ impl<B: Backend> Decoder<B> {
config.transformer_config.layer_configs.len() as u32,
"per-layer embedding num_layers must match transformer layer count"
);
- Some(PerLayerEmbedding::new(
- config.transformer_config.model_dim,
- data_type,
- ple_config,
- &parameter_tree.subtree("per_layer_embedding"),
- context,
- )?)
+ Some(
+ PerLayerEmbedding::new(
+ config.transformer_config.model_dim,
+ data_type,
+ ple_config,
+ &parameter_tree.subtree("per_layer_embedding"),
+ context,
+ )
+ .await?,
+ )
} else {
None
};
@@ -106,7 +111,8 @@ impl<B: Backend> Decoder<B> {
&config.transformer_config,
&parameter_tree.subtree("transformer"),
context,
- )?;
+ )
+ .await?;
Ok(Self {
embedding,
diff --git a/crates/uzu-engine/src/encodable_block/dflash.rs b/crates/uzu-engine/src/encodable_block/dflash.rs
index 3beac9005..aa2dc8731 100644
--- a/crates/uzu-engine/src/encodable_block/dflash.rs
+++ b/crates/uzu-engine/src/encodable_block/dflash.rs
@@ -91,10 +91,10 @@ pub enum DFlashEncodeError<B: Backend> {
}
impl<B: Backend> DFlash<B> {
- pub fn new(
+ pub async fn new(
data_type: DataType,
config: &DFlashDraftConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, DFlashNewError<B>> {
let mask_token_id = config.mask_token_id as u32;
@@ -106,7 +106,8 @@ impl<B: Backend> DFlash<B> {
false,
&parameter_tree.subtree("context_projection"),
context,
- )?;
+ )
+ .await?;
let projected_feature_norm = Normalization::new(
config.model_dim,
data_type,
@@ -116,7 +117,8 @@ impl<B: Backend> DFlash<B> {
&config.context_norm_config,
&parameter_tree.subtree("context_norm"),
context,
- )?;
+ )
+ .await?;
let layers_tree = parameter_tree.subtree("layers");
let first_layer_config = config.layer_configs.first().expect("DFlash draft model must have at least one layer");
let AnyTokenMixerConfig::AttentionConfig(attention_config) = &first_layer_config.mixer_config else {
@@ -131,12 +133,11 @@ impl<B: Backend> DFlash<B> {
false,
&parameter_tree.subtree("state_kv_projection"),
context,
- )?;
- let layers = config
- .layer_configs
- .iter()
- .zip(0u32..)
- .map(|(layer_config, index)| {
+ )
+ .await?;
+ let mut layers = Vec::with_capacity(num_layers as usize);
+ for (layer_config, index) in config.layer_configs.iter().zip(0u32..) {
+ layers.push(
TransformerLayer::new(
config.model_dim,
config.hidden_dim,
@@ -147,8 +148,9 @@ impl<B: Backend> DFlash<B> {
&layers_tree.subtree(&index.to_string()),
context,
)
- })
- .collect::<Result<Box<[_]>, TransformerLayerError<B>>>()?;
+ .await?,
+ );
+ }
let output_norm = Normalization::new(
config.model_dim,
data_type,
@@ -158,14 +160,15 @@ impl<B: Backend> DFlash<B> {
&config.output_norm_config,
&parameter_tree.subtree("output_norm"),
context,
- )?;
+ )
+ .await?;
Ok(Self {
target_feature_projection,
projected_feature_norm,
state_kv_projection,
layer_kv_dim,
- layers,
+ layers: layers.into_boxed_slice(),
output_norm,
rope_config: config.rope_config.clone(),
model_dim: config.model_dim,
diff --git a/crates/uzu-engine/src/encodable_block/embedding.rs b/crates/uzu-engine/src/encodable_block/embedding.rs
index 434948441..7bdfd2a72 100644
--- a/crates/uzu-engine/src/encodable_block/embedding.rs
+++ b/crates/uzu-engine/src/encodable_block/embedding.rs
@@ -72,28 +72,28 @@ impl<B: Backend> Embedding<B> {
self.model_dim
}
- pub fn new(
+ pub async fn new(
vocab_size: u32,
model_dim: u32,
data_type: DataType,
config: &AnyEmbeddingConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Self, Option<B::GlobalBuffer>), EmbeddingError<B>> {
+ ) -> Result<(Self, Option<B::GlobalGpuBuffer>), EmbeddingError<B>> {
let (tying, readout_input_hadamard_factors) = match config {
AnyEmbeddingConfig::TiedEmbeddingConfig(_) => {
let embedding_tree = parameter_tree.subtree("embedding");
- let table = EmbeddingTable::load(vocab_size, model_dim, data_type, &embedding_tree, context)?;
+ let table = EmbeddingTable::load(vocab_size, model_dim, data_type, &embedding_tree, context).await?;
if table.as_matrix().is_none() {
return Err(EmbeddingError::UnsupportedConfiguration("tied embeddings need a matrix table".into()));
}
// The output norm fuses the readout's input rotation, so it needs its own copy of the factors.
- let readout_input_hadamard_factors =
- if let AnyWeightMatrixSpec::HybridSpec(_) = embedding_tree.metadata("spec")? {
- Some(read_output_signs(&embedding_tree, model_dim)?)
- } else {
- None
- };
+ let spec = embedding_tree.metadata("spec")?;
+ let readout_input_hadamard_factors = if let AnyWeightMatrixSpec::HybridSpec(_) = spec {
+ Some(read_output_signs(&embedding_tree, model_dim).await?)
+ } else {
+ None
+ };
(
EmbeddingTying::Tied {
table,
@@ -105,7 +105,7 @@ impl<B: Backend> Embedding<B> {
AnyEmbeddingConfig::UntiedEmbeddingConfig(_) => {
let input_embedding_tree = parameter_tree.subtree("input_embedding");
let input_table =
- EmbeddingTable::load(vocab_size, model_dim, data_type, &input_embedding_tree, context)?;
+ EmbeddingTable::load(vocab_size, model_dim, data_type, &input_embedding_tree, context).await?;
let output_embedding_tree = parameter_tree.subtree("output_embedding");
let output_embedding_spec = output_embedding_tree.metadata("spec")?;
let output = UntiedReadout::load(
@@ -115,7 +115,8 @@ impl<B: Backend> Embedding<B> {
output_embedding_spec,
&output_embedding_tree,
context,
- )?;
+ )
+ .await?;
(
EmbeddingTying::Untied {
input_table,
diff --git a/crates/uzu-engine/src/encodable_block/embedding_table.rs b/crates/uzu-engine/src/encodable_block/embedding_table.rs
index b1970e563..2ccbba2d7 100644
--- a/crates/uzu-engine/src/encodable_block/embedding_table.rs
+++ b/crates/uzu-engine/src/encodable_block/embedding_table.rs
@@ -33,11 +33,11 @@ pub enum EmbeddingTableError<B: Backend> {
/// Lookup-only D4S4 table: one codebook entry per 4 columns and a ladder scale per 64 columns.
struct D4S4Table<B: Backend> {
- codes: B::GlobalBuffer,
- row_scales: B::GlobalBuffer,
- ladder_indices: B::GlobalBuffer,
- ladder: B::GlobalBuffer,
- codebook: B::GlobalBuffer,
+ codes: B::GlobalGpuBuffer,
+ row_scales: B::GlobalGpuBuffer,
+ ladder_indices: B::GlobalGpuBuffer,
+ ladder: B::GlobalGpuBuffer,
+ codebook: B::GlobalGpuBuffer,
}
enum Storage<B: Backend> {
@@ -46,13 +46,13 @@ enum Storage<B: Backend> {
}
struct LookupBindings<'a, B: Backend> {
- values: &'a B::GlobalBuffer,
- scales: Option<&'a B::GlobalBuffer>,
- zero_points: Option<&'a B::GlobalBuffer>,
- biases: Option<&'a B::GlobalBuffer>,
- ladder_indices: Option<&'a B::GlobalBuffer>,
- ladder: Option<&'a B::GlobalBuffer>,
- codebook: Option<&'a B::GlobalBuffer>,
+ values: &'a B::GlobalGpuBuffer,
+ scales: Option<&'a B::GlobalGpuBuffer>,
+ zero_points: Option<&'a B::GlobalGpuBuffer>,
+ biases: Option<&'a B::GlobalGpuBuffer>,
+ ladder_indices: Option<&'a B::GlobalGpuBuffer>,
+ ladder: Option<&'a B::GlobalGpuBuffer>,
+ codebook: Option<&'a B::GlobalGpuBuffer>,
}
impl<B: Backend> Storage<B> {
@@ -82,18 +82,18 @@ impl<B: Backend> Storage<B> {
pub struct EmbeddingTable<B: Backend> {
storage: Storage<B>,
- output_hadamard_factors: Option<B::GlobalBuffer>,
+ output_hadamard_factors: Option<B::GlobalGpuBuffer>,
lookup: LookupKernel<B>,
vocab_size: u32,
embedding_dim: u32,
}
impl<B: Backend> EmbeddingTable<B> {
- pub fn load(
+ pub async fn load(
vocab_size: u32,
embedding_dim: u32,
data_type: DataType,
- tree: &ParameterTree<B>,
+ tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, EmbeddingTableError<B>> {
if !matches!(data_type, DataType::F32 | DataType::BF16) {
@@ -101,12 +101,13 @@ impl<B: Backend> EmbeddingTable<B> {
"input embedding lookup does not support {data_type:?}"
)));
}
- let load_matrix = |tree: &ParameterTree<B>, spec| {
- WeightMatrix::load(embedding_dim, vocab_size, data_type, spec, Layout::InputOutput, tree)
+ let load_matrix = async |tree: &ParameterTree<B>, spec| {
+ WeightMatrix::load(embedding_dim, vocab_size, data_type, spec, Layout::InputOutput, tree).await
};
- let (storage, output_hadamard_factors) = match tree.metadata::<AnyWeightMatrixSpec>("spec")? {
+ let spec = tree.metadata::<AnyWeightMatrixSpec>("spec")?;
+ let (storage, output_hadamard_factors) = match spec {
AnyWeightMatrixSpec::D4S4Spec(spec) => {
- let (table, factors) = load_d4s4(tree, vocab_size, embedding_dim, data_type, spec)?;
+ let (table, factors) = load_d4s4(tree, vocab_size, embedding_dim, data_type, spec).await?;
(Storage::D4S4(table), Some(factors))
},
AnyWeightMatrixSpec::HybridSpec(HybridSpec {
@@ -115,20 +116,20 @@ impl<B: Backend> EmbeddingTable<B> {
incoherence_processing_mode: IncoherenceProcessingMode::Output,
..
}) if embedding_dim.is_multiple_of(HADAMARD_TRANSFORM_BLOCK_SIZE) => {
- let matrix = load_matrix(&tree.subtree("quantized"), *quantization_spec)?;
+ let matrix = load_matrix(&tree.subtree("quantized"), *quantization_spec).await?;
if matrix.quantization().is_none() {
return Err(EmbeddingTableError::UnsupportedConfiguration(
"output-Hadamard factors require a quantized table".into(),
));
}
- (Storage::Matrix(matrix), Some(read_output_signs(tree, embedding_dim)?))
+ (Storage::Matrix(matrix), Some(read_output_signs(tree, embedding_dim).await?))
},
spec @ AnyWeightMatrixSpec::HybridSpec(_) => {
return Err(EmbeddingTableError::UnsupportedConfiguration(format!(
"{spec:?} with embedding dim {embedding_dim}"
)));
},
- spec => (Storage::Matrix(load_matrix(tree, spec)?), None),
+ spec => (Storage::Matrix(load_matrix(tree, spec).await?), None),
};
let (table_kind, quantization) = match &storage {
@@ -195,38 +196,41 @@ impl<B: Backend> EmbeddingTable<B> {
}
}
-fn load_d4s4<B: Backend>(
- tree: &ParameterTree<B>,
+async fn load_d4s4<B: Backend>(
+ tree: &ParameterTree<'_, B>,
vocab_size: u32,
embedding_dim: u32,
data_type: DataType,
spec: D4S4Spec,
-) -> Result<(D4S4Table<B>, B::GlobalBuffer), EmbeddingTableError<B>> {
+) -> Result<(D4S4Table<B>, B::GlobalGpuBuffer), EmbeddingTableError<B>> {
if spec.layout != Layout::InputOutput || !embedding_dim.is_multiple_of(d4s4::COLUMNS_PER_LADDER_INDEX_BYTE) {
return Err(EmbeddingTableError::UnsupportedConfiguration(format!(
"{spec:?} with {data_type:?} and embedding dim {embedding_dim}"
)));
}
- let read = |name: &str, shape: &[u32], data_type| tree.read_buffer(name, shape, data_type);
+ let read = async |name: &str, shape: &[u32], data_type| tree.read_buffer(name, shape, data_type).await;
+ let codes = read("codes", &[vocab_size, embedding_dim / d4s4::VALUES_PER_CODE], DataType::U8).await?;
+ let row_scales = read("row_scales", &[vocab_size], data_type).await?;
+ let ladder_indices =
+ read("ladder_indices", &[vocab_size, embedding_dim / d4s4::COLUMNS_PER_LADDER_INDEX_BYTE], DataType::U8)
+ .await?;
+ let ladder = read("ladder", &[d4s4::LADDER_SIZE], DataType::F16).await?;
+ let codebook = read("table", &[d4s4::CODEBOOK_SIZE, d4s4::VALUES_PER_CODE], DataType::I8).await?;
let table = D4S4Table {
- codes: read("codes", &[vocab_size, embedding_dim / d4s4::VALUES_PER_CODE], DataType::U8)?,
- row_scales: read("row_scales", &[vocab_size], data_type)?,
- ladder_indices: read(
- "ladder_indices",
- &[vocab_size, embedding_dim / d4s4::COLUMNS_PER_LADDER_INDEX_BYTE],
- DataType::U8,
- )?,
- ladder: read("ladder", &[d4s4::LADDER_SIZE], DataType::F16)?,
- codebook: read("table", &[d4s4::CODEBOOK_SIZE, d4s4::VALUES_PER_CODE], DataType::I8)?,
+ codes,
+ row_scales,
+ ladder_indices,
+ ladder,
+ codebook,
};
- let factors = read("output_hadamard_factors", &[embedding_dim], DataType::I32)?;
+ let factors = read("output_hadamard_factors", &[embedding_dim], DataType::I32).await?;
Ok((table, factors))
}
-pub(super) fn read_output_signs<B: Backend>(
- tree: &ParameterTree<B>,
+pub(super) async fn read_output_signs<B: Backend>(
+ tree: &ParameterTree<'_, B>,
embedding_dim: u32,
-) -> Result<B::GlobalBuffer, EmbeddingTableError<B>> {
+) -> Result<B::GlobalGpuBuffer, EmbeddingTableError<B>> {
let signs = tree.subtree("incoherence_signs");
- Ok(signs.read_buffer("output_signs", &[embedding_dim], DataType::I32)?)
+ Ok(signs.read_buffer("output_signs", &[embedding_dim], DataType::I32).await?)
}
diff --git a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs b/crates/uzu-engine/src/encodable_block/linear/input_rht.rs
index 47ad13a45..c020b69c8 100644
--- a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/input_rht.rs
@@ -10,7 +10,7 @@ use crate::{
};
pub(super) struct InputRht<B: Backend> {
- rht_signs: B::GlobalBuffer,
+ rht_signs: B::GlobalGpuBuffer,
rht: ActivationTransform<B>,
quantizer: Option<ActivationTransform<B>>,
}
diff --git a/crates/uzu-engine/src/encodable_block/linear/matmul.rs b/crates/uzu-engine/src/encodable_block/linear/matmul.rs
index d0d5a8bfe..b86a60475 100644
--- a/crates/uzu-engine/src/encodable_block/linear/matmul.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/matmul.rs
@@ -41,40 +41,44 @@ pub enum LinearMatmulError<B: Backend> {
pub struct LinearMatmul<B: Backend> {
kernel: Mutex<<B::Kernels as Kernels>::MatmulKernel>,
matrix: WeightMatrix<B>,
- biases: Option<B::GlobalBuffer>,
- output_hadamard_factors: Option<B::GlobalBuffer>,
+ biases: Option<B::GlobalGpuBuffer>,
+ output_hadamard_factors: Option<B::GlobalGpuBuffer>,
input_dim: u32,
output_dim: u32,
output_data_type: DataType,
}
-fn load_biases<B: Backend>(
+async fn load_biases<B: Backend>(
weights_data_type: DataType,
output_data_type: DataType,
output_dim: u32,
- parameter_tree: Option<&ParameterTree<B>>,
-) -> Result<Option<B::GlobalBuffer>, LinearMatmulError<B>> {
+ parameter_tree: Option<&ParameterTree<'_, B>>,
+) -> Result<Option<B::GlobalGpuBuffer>, LinearMatmulError<B>> {
if parameter_tree.is_some() && weights_data_type != output_data_type {
return Err(LinearMatmulError::UnsupportedConfiguration(format!(
"mixed precision linear with biases is not supported: weights={weights_data_type:?}, output={output_data_type:?}",
)));
}
- Ok(parameter_tree.map(|tree| tree.read_buffer("biases", &[output_dim], weights_data_type)).transpose()?)
+ Ok(if let Some(tree) = parameter_tree {
+ Some(tree.read_buffer("biases", &[output_dim], weights_data_type).await?)
+ } else {
+ None
+ })
}
impl<B: Backend> LinearMatmul<B> {
/// Loads a linear over any parsed spec — full precision, MLX or Int. Hybrid
/// compositions live in the wrappers, not here.
- pub fn load(
+ pub async fn load(
input_dim: u32,
output_dim: u32,
weights_data_type: DataType,
input_data_type: DataType,
output_data_type: DataType,
spec: AnyWeightMatrixSpec,
- output_hadamard_factors: Option<B::GlobalBuffer>,
- weights_tree: &ParameterTree<B>,
- bias_tree: Option<&ParameterTree<B>>,
+ output_hadamard_factors: Option<B::GlobalGpuBuffer>,
+ weights_tree: &ParameterTree<'_, B>,
+ bias_tree: Option<&ParameterTree<'_, B>>,
context: &B::Context,
) -> Result<Self, LinearMatmulError<B>> {
for data_type in [weights_data_type, input_data_type, output_data_type] {
@@ -84,14 +88,15 @@ impl<B: Backend> LinearMatmul<B> {
}
let matrix =
- WeightMatrix::load(output_dim, input_dim, weights_data_type, spec, Layout::OutputInput, weights_tree)?;
+ WeightMatrix::load(output_dim, input_dim, weights_data_type, spec, Layout::OutputInput, weights_tree)
+ .await?;
if output_hadamard_factors.is_some() && matrix.quantization().is_none() {
return Err(LinearMatmulError::UnsupportedConfiguration(
"fused output-hadamard factors require quantized weights".into(),
));
}
- let biases = load_biases(weights_data_type, output_data_type, output_dim, bias_tree)?;
+ let biases = load_biases(weights_data_type, output_data_type, output_dim, bias_tree).await?;
let kernel =
<B::Kernels as Kernels>::MatmulKernel::new(context, weights_data_type, input_data_type, output_data_type)
@@ -108,22 +113,14 @@ impl<B: Backend> LinearMatmul<B> {
})
}
- pub(super) fn prepare_a8_matmul(
+ pub(super) fn optimize_weights_layout(
&mut self,
context: &B::Context,
) -> Result<Option<ActivationQuantization>, B::Error> {
- let mut candidate = self.matmul_shape(1, false);
- let Some(signed_codes) = self.matrix.a8_signed_codes() else {
- return Ok(None);
- };
- candidate.signed_codes = signed_codes;
+ let shape = self.matmul_shape(1, false);
let kernel = self.kernel.lock();
- let quantization = kernel.select_activation_quantization(&candidate, context);
- if quantization.is_none() || !self.matrix.try_prepare_a8_storage() {
- return Ok(None);
- }
- self.matrix.optimize_weights_layout(|weights| kernel.optimize_weights_layout(&candidate, weights, context))?;
- Ok(quantization)
+ self.matrix.optimize_weights_layout(|weights| kernel.optimize_weights_layout(&shape, weights, context))?;
+ Ok(kernel.select_activation_quantization(&self.matmul_shape(1, false), context))
}
pub(super) fn encode_with_a(
@@ -183,7 +180,7 @@ impl<B: Backend> LinearMatmul<B> {
}
}
- fn matmul_b(&self) -> MatmulB<&B::GlobalBuffer> {
+ fn matmul_b(&self) -> MatmulB<&B::GlobalGpuBuffer> {
self.matrix.matmul_b()
}
diff --git a/crates/uzu-engine/src/encodable_block/linear/mod.rs b/crates/uzu-engine/src/encodable_block/linear/mod.rs
index 2e9615cad..73f52ef53 100644
--- a/crates/uzu-engine/src/encodable_block/linear/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/mod.rs
@@ -102,7 +102,7 @@ impl<B: Backend> LinearInput<B> {
}
pub struct LinearInputPreparation<B: Backend> {
- pub rht_signs: B::GlobalBuffer,
+ pub rht_signs: B::GlobalGpuBuffer,
pub activation_quantization: Option<ActivationQuantization>,
}
@@ -119,14 +119,14 @@ pub enum LinearBlockError<B: Backend> {
}
impl<B: Backend> dyn Linear<B> {
- pub fn new_mixed_precision(
+ pub async fn new_mixed_precision(
input_dimension: u32,
output_dimension: u32,
weights_data_type: DataType,
input_data_type: DataType,
output_data_type: DataType,
has_biases: bool,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Box<dyn Linear<B>>, LinearBlockError<B>> {
let weights_tree = parameter_tree.subtree("weights");
@@ -146,33 +146,37 @@ impl<B: Backend> dyn Linear<B> {
&weights_tree,
has_biases.then_some(parameter_tree),
context,
- )?;
+ )
+ .await?;
Ok(Box::new(block))
},
AnyWeightMatrixSpec::HybridSpec(HybridSpec {
incoherence_block_size: Some(block_size),
incoherence_processing_mode: IncoherenceProcessingMode::InputOutput,
..
- }) if block_size == HADAMARD_TRANSFORM_BLOCK_SIZE => Ok(Box::new(RHTLinearWrapper::new(
- input_dimension,
- output_dimension,
- weights_data_type,
- input_data_type,
- output_data_type,
- has_biases,
- parameter_tree,
- context,
- )?)),
+ }) if block_size == HADAMARD_TRANSFORM_BLOCK_SIZE => Ok(Box::new(
+ RHTLinearWrapper::new(
+ input_dimension,
+ output_dimension,
+ weights_data_type,
+ input_data_type,
+ output_data_type,
+ has_biases,
+ parameter_tree,
+ context,
+ )
+ .await?,
+ )),
spec => Err(LinearBlockError::UnsupportedConfiguration(format!("{spec:?}"))),
}
}
- pub fn new(
+ pub async fn new(
input_dimension: u32,
output_dimension: u32,
data_type: DataType,
has_biases: bool,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Box<dyn Linear<B>>, LinearBlockError<B>> {
Self::new_mixed_precision(
@@ -185,18 +189,19 @@ impl<B: Backend> dyn Linear<B> {
parameter_tree,
context,
)
+ .await
}
- pub fn new_with_input_rht_mixed_precision(
+ pub async fn new_with_input_rht_mixed_precision(
input_dimension: u32,
output_dimension: u32,
weights_data_type: DataType,
input_data_type: DataType,
output_data_type: DataType,
has_biases: bool,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Box<dyn Linear<B>>, Option<B::GlobalBuffer>), LinearBlockError<B>> {
+ ) -> Result<(Box<dyn Linear<B>>, Option<B::GlobalGpuBuffer>), LinearBlockError<B>> {
if let Some(linear) = RHTLinearWrapper::try_new_with_input_preparation(
input_dimension,
output_dimension,
@@ -207,7 +212,9 @@ impl<B: Backend> dyn Linear<B> {
false,
parameter_tree,
context,
- )? {
+ )
+ .await?
+ {
return Ok((linear.0, linear.1.map(|preparation| preparation.rht_signs)));
}
@@ -220,16 +227,17 @@ impl<B: Backend> dyn Linear<B> {
has_biases,
parameter_tree,
context,
- )?;
+ )
+ .await?;
Ok((linear, None))
}
- pub fn new_for_fused_input(
+ pub async fn new_for_fused_input(
input_dimension: u32,
output_dimension: u32,
data_type: DataType,
has_biases: bool,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<(Box<dyn Linear<B>>, Option<LinearInputPreparation<B>>), LinearBlockError<B>> {
if let Some(linear) = RHTLinearWrapper::try_new_with_input_preparation(
@@ -242,7 +250,9 @@ impl<B: Backend> dyn Linear<B> {
true,
parameter_tree,
context,
- )? {
+ )
+ .await?
+ {
return Ok(linear);
}
@@ -255,18 +265,19 @@ impl<B: Backend> dyn Linear<B> {
has_biases,
parameter_tree,
context,
- )?;
+ )
+ .await?;
Ok((linear, None))
}
- pub fn new_with_input_rht(
+ pub async fn new_with_input_rht(
input_dimension: u32,
output_dimension: u32,
data_type: DataType,
has_biases: bool,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Box<dyn Linear<B>>, Option<B::GlobalBuffer>), LinearBlockError<B>> {
+ ) -> Result<(Box<dyn Linear<B>>, Option<B::GlobalGpuBuffer>), LinearBlockError<B>> {
Self::new_with_input_rht_mixed_precision(
input_dimension,
output_dimension,
@@ -277,5 +288,6 @@ impl<B: Backend> dyn Linear<B> {
parameter_tree,
context,
)
+ .await
}
}
diff --git a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
index ce00dda75..f26308b16 100644
--- a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
@@ -46,14 +46,14 @@ fn has_input_output_rht(spec: &AnyWeightMatrixSpec) -> bool {
}
impl<B: Backend> RHTLinearWrapper<B> {
- pub(super) fn new(
+ pub(super) async fn new(
input_dimension: u32,
output_dimension: u32,
weights_data_type: DataType,
input_data_type: DataType,
output_data_type: DataType,
has_biases: bool,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, RHTLinearWrapperError<B>> {
let weights_tree = parameter_tree.subtree("weights");
@@ -71,9 +71,10 @@ impl<B: Backend> RHTLinearWrapper<B> {
has_biases,
parameter_tree,
context,
- )?;
+ )
+ .await?;
let activation_quantization =
- inner_linear.prepare_a8_matmul(context).map_err(RHTLinearWrapperError::BackendError)?;
+ inner_linear.optimize_weights_layout(context).map_err(RHTLinearWrapperError::BackendError)?;
Self::build_self_contained(
input_data_type,
LinearInputPreparation {
@@ -85,7 +86,7 @@ impl<B: Backend> RHTLinearWrapper<B> {
)
}
- pub(super) fn try_new_with_input_preparation(
+ pub(super) async fn try_new_with_input_preparation(
input_dimension: u32,
output_dimension: u32,
weights_data_type: DataType,
@@ -93,7 +94,7 @@ impl<B: Backend> RHTLinearWrapper<B> {
output_data_type: DataType,
has_biases: bool,
allow_prequantized_activation: bool,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Option<(Box<dyn Linear<B>>, Option<LinearInputPreparation<B>>)>, RHTLinearWrapperError<B>> {
let weights_tree = parameter_tree.subtree("weights");
@@ -111,11 +112,12 @@ impl<B: Backend> RHTLinearWrapper<B> {
has_biases,
parameter_tree,
context,
- )?;
+ )
+ .await?;
let input_preparation = LinearInputPreparation {
rht_signs,
activation_quantization: inner_linear
- .prepare_a8_matmul(context)
+ .optimize_weights_layout(context)
.map_err(RHTLinearWrapperError::BackendError)?,
};
if input_preparation.activation_quantization.is_some() && !allow_prequantized_activation {
@@ -126,22 +128,23 @@ impl<B: Backend> RHTLinearWrapper<B> {
}
}
- fn load_inner_with_output_rht(
+ async fn load_inner_with_output_rht(
input_dimension: u32,
output_dimension: u32,
weights_data_type: DataType,
input_data_type: DataType,
output_data_type: DataType,
has_biases: bool,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(B::GlobalBuffer, LinearMatmul<B>), RHTLinearWrapperError<B>> {
+ ) -> Result<(B::GlobalGpuBuffer, LinearMatmul<B>), RHTLinearWrapperError<B>> {
let weights_tree = parameter_tree.subtree("weights");
let quantized_weights_tree = weights_tree.subtree("quantized");
let quantization_spec = quantized_weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;
- let rht_signs = weights_tree.read_buffer("incoherence_signs.input_signs", &[input_dimension], DataType::I32)?;
+ let rht_signs =
+ weights_tree.read_buffer("incoherence_signs.input_signs", &[input_dimension], DataType::I32).await?;
let output_factors =
- weights_tree.read_buffer("incoherence_signs.output_signs", &[output_dimension], DataType::I32)?;
+ weights_tree.read_buffer("incoherence_signs.output_signs", &[output_dimension], DataType::I32).await?;
let inner_linear = LinearMatmul::load(
input_dimension,
output_dimension,
@@ -153,7 +156,8 @@ impl<B: Backend> RHTLinearWrapper<B> {
&quantized_weights_tree,
has_biases.then_some(parameter_tree),
context,
- )?;
+ )
+ .await?;
Ok((rht_signs, inner_linear))
}
diff --git a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs
index 5c21fe3f0..33bf030f8 100644
--- a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs
@@ -21,12 +21,12 @@ pub struct UntiedReadout<B: Backend> {
}
impl<B: Backend> UntiedReadout<B> {
- pub fn load(
+ pub async fn load(
vocab_size: u32,
model_dim: u32,
data_type: DataType,
spec: AnyWeightMatrixSpec,
- tree: &ParameterTree<B>,
+ tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, LinearMatmulError<B>> {
let AnyWeightMatrixSpec::HybridSpec(HybridSpec {
@@ -39,7 +39,8 @@ impl<B: Backend> UntiedReadout<B> {
return Ok(Self {
linear: LinearMatmul::load(
model_dim, vocab_size, data_type, data_type, data_type, spec, None, tree, None, context,
- )?,
+ )
+ .await?,
input_rht: None,
});
};
@@ -55,11 +56,15 @@ impl<B: Backend> UntiedReadout<B> {
&tree.subtree("quantized"),
None,
context,
- )?;
- let rht_signs = tree.subtree("incoherence_signs").read_buffer("input_signs", &[model_dim], DataType::I32)?;
+ )
+ .await?;
+ let rht_signs =
+ tree.subtree("incoherence_signs").read_buffer("input_signs", &[model_dim], DataType::I32).await?;
let preparation = LinearInputPreparation {
rht_signs,
- activation_quantization: linear.prepare_a8_matmul(context).map_err(LinearMatmulError::BackendError)?,
+ activation_quantization: linear
+ .optimize_weights_layout(context)
+ .map_err(LinearMatmulError::BackendError)?,
};
let input_rht = InputRht::new(data_type, preparation, /* in_place */ false, context)
.map_err(LinearMatmulError::BackendError)?;
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/kv_storage.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/kv_storage.rs
index 6929d4de2..9f477b782 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/kv_storage.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/kv_storage.rs
@@ -2,7 +2,7 @@ use std::any::Any;
use crate::{
backends::common::{
- Backend, Buffer, CommandBuffer, Context, DeviceCapabilities, Kernels, SparseBuffer,
+ Backend, CommandBuffer, Context, DeviceCapabilities, GpuBuffer, Kernels, SparseBuffer,
gpu_types::kv_cache_update::Copy,
kernel::{KVCacheUpdateInt8Kernel, KVCacheUpdateKernel, KVFormat, kv_layout::Int8KVLayout},
},
@@ -16,28 +16,28 @@ pub enum KVStorage<B: Backend> {
}
pub struct BF16KV<B: Backend> {
- pub keys: Box<dyn Buffer<Backend = B>>,
- pub values: Box<dyn Buffer<Backend = B>>,
+ pub keys: Box<dyn GpuBuffer<Backend = B>>,
+ pub values: Box<dyn GpuBuffer<Backend = B>>,
pub element_dim: u32,
pub data_type: DataType,
}
pub struct Int8KV<B: Backend> {
pub layout: Int8KVLayout,
- pub k_codes: Box<dyn Buffer<Backend = B>>,
- pub v_codes: Box<dyn Buffer<Backend = B>>,
- pub k_scales: Box<dyn Buffer<Backend = B>>,
- pub v_scales: Box<dyn Buffer<Backend = B>>,
+ pub k_codes: Box<dyn GpuBuffer<Backend = B>>,
+ pub v_codes: Box<dyn GpuBuffer<Backend = B>>,
+ pub k_scales: Box<dyn GpuBuffer<Backend = B>>,
+ pub v_scales: Box<dyn GpuBuffer<Backend = B>>,
}
fn create_kv_buffer<B: Backend>(
context: &B::Context,
bytes: usize,
-) -> Result<Box<dyn Buffer<Backend = B>>, B::Error> {
+) -> Result<Box<dyn GpuBuffer<Backend = B>>, B::Error> {
Ok(if context.device_capabilities().contains(DeviceCapabilities::SPARSE_BUFFERS) {
Box::new(context.create_sparse_buffer(bytes)?)
} else {
- Box::new(context.create_buffer(bytes)?)
+ Box::new(context.create_buffer_gpu(bytes)?)
})
}
@@ -82,7 +82,7 @@ impl<B: Backend> KVStorage<B> {
&mut self,
elements_required: u32,
) -> Result<(), B::Error> {
- let map = |buffer: &mut dyn Buffer<Backend = B>, bytes: usize| -> Result<(), B::Error> {
+ let map = |buffer: &mut dyn GpuBuffer<Backend = B>, bytes: usize| -> Result<(), B::Error> {
match (buffer as &mut dyn Any).downcast_mut::<B::SparseBuffer>() {
Some(sparse) => sparse.map(bytes),
None => Ok(()),
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
index a2832494a..d79e90bbf 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
@@ -46,7 +46,7 @@ pub struct Attention<B: Backend> {
projection: LinearProjection<B>,
prepare: <B::Kernels as Kernels>::AttentionPrepareKernel,
prepare_int8: Option<<B::Kernels as Kernels>::AttentionPrepareInt8Kernel>,
- sinks: Option<B::GlobalBuffer>,
+ sinks: Option<B::GlobalGpuBuffer>,
kernel: <B::Kernels as Kernels>::AttentionKernel,
out_projection: Box<dyn Linear<B>>,
}
@@ -76,14 +76,14 @@ pub enum AttentionEncodeError<B: Backend> {
}
impl<B: Backend> Attention<B> {
- pub fn new(
+ pub async fn new(
hidden_dim: u32,
data_type: DataType,
rope_config: Option<&AnyRoPEConfig>,
config: &AttentionConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Self, Option<B::GlobalBuffer>), AttentionNewError<B>> {
+ ) -> Result<(Self, Option<B::GlobalGpuBuffer>), AttentionNewError<B>> {
let is_kv_sharing = config.is_kv_sharing;
let head_dim = config.head_dim;
@@ -116,7 +116,8 @@ impl<B: Backend> Attention<B> {
config.has_qkvg_biases,
&projection_tree,
context,
- )?;
+ )
+ .await?;
let query_norm_config = config.query_norm_config.clone();
// TODO: Fix lalamo config, those two must be None if kv sharing.
@@ -133,7 +134,8 @@ impl<B: Backend> Attention<B> {
value_norm_config,
parameter_tree,
context,
- )?;
+ )
+ .await?;
let prepare = <B::Kernels as Kernels>::AttentionPrepareKernel::new(
context,
@@ -143,8 +145,11 @@ impl<B: Backend> Attention<B> {
rope_config.is_some(),
)
.map_err(AttentionNewError::Backend)?;
- let sinks =
- config.has_sinks.then(|| parameter_tree.read_buffer("sinks", &[num_q_heads], data_type)).transpose()?;
+ let sinks = if config.has_sinks {
+ Some(parameter_tree.read_buffer("sinks", &[num_q_heads], data_type).await?)
+ } else {
+ None
+ };
assert!(sliding_window_size.is_none_or(|size| size > 0), "zero sliding window size");
let ring_capacity = sliding_window_size;
@@ -190,7 +195,8 @@ impl<B: Backend> Attention<B> {
config.has_out_biases,
&parameter_tree.subtree("out_projection"),
context,
- )?;
+ )
+ .await?;
Ok((
Self {
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs
index 41de8bca4..b3d03b2cf 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs
@@ -1,6 +1,6 @@
use crate::{
backends::common::{
- Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding,
+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, GpuBuffer,
kernel::{
AttentionArguments, AttentionInput, AttentionKernel, AttentionPrepareInt8Kernel, AttentionPrepareKernel,
FullPrecisionInput, Int8Input,
@@ -26,8 +26,8 @@ use crate::{
enum KVBuffers<'a, B: Backend> {
BF16 {
- keys: MaybeMut<'a, dyn Buffer<Backend = B>>,
- values: MaybeMut<'a, dyn Buffer<Backend = B>>,
+ keys: MaybeMut<'a, dyn GpuBuffer<Backend = B>>,
+ values: MaybeMut<'a, dyn GpuBuffer<Backend = B>>,
},
Int8(MaybeMut<'a, Int8KV<B>>),
}
@@ -220,8 +220,8 @@ impl<B: Backend> Attention<B> {
fn prepare_bf16(
&self,
qkvg: impl BufferRef<Backend = B>,
- keys: &mut MaybeMut<'_, dyn Buffer<Backend = B>>,
- values: &mut MaybeMut<'_, dyn Buffer<Backend = B>>,
+ keys: &mut MaybeMut<'_, dyn GpuBuffer<Backend = B>>,
+ values: &mut MaybeMut<'_, dyn GpuBuffer<Backend = B>>,
kv_token_offset: u32,
num_q_heads: u32,
rope: Option<&PrecalculatedRoPE<B>>,
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs
index e2b6ce736..7cc46a84f 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs
@@ -21,7 +21,7 @@ pub enum QKVNormError<B: Backend> {
struct Head<B: Backend> {
kernel: <B::Kernels as Kernels>::QKVNormKernel,
- scales: Option<B::GlobalBuffer>,
+ scales: Option<B::GlobalGpuBuffer>,
config: NormalizationConfig,
}
@@ -36,7 +36,7 @@ pub struct QKVNorm<B: Backend> {
}
impl<B: Backend> QKVNorm<B> {
- pub fn new(
+ pub async fn new(
num_q_heads: u32,
num_kv_heads: Option<u32>,
projection_row_stride: u32,
@@ -45,22 +45,23 @@ impl<B: Backend> QKVNorm<B> {
query_config: Option<NormalizationConfig>,
key_config: Option<NormalizationConfig>,
value_config: Option<NormalizationConfig>,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, QKVNormError<B>> {
- let build_head = |config: Option<NormalizationConfig>, parameter_name: Option<&str>| {
+ let build_head = async |config: Option<NormalizationConfig>, parameter_name: Option<&str>| {
let Some(config) = config else {
return Ok::<_, QKVNormError<B>>(None);
};
- let scales =
- config
- .has_scale
- .then(|| {
- parameter_tree
- .subtree(parameter_name.expect("scaled norm requires parameter tree"))
- .read_buffer("scales", &[head_dim], DataType::F32)
- })
- .transpose()?;
+ let scales = if config.has_scale {
+ Some(
+ parameter_tree
+ .subtree(parameter_name.expect("scaled norm requires parameter tree"))
+ .read_buffer("scales", &[head_dim], DataType::F32)
+ .await?,
+ )
+ } else {
+ None
+ };
let kernel = <B::Kernels as Kernels>::QKVNormKernel::new(
context,
intermediate_data_type,
@@ -78,10 +79,13 @@ impl<B: Backend> QKVNorm<B> {
}))
};
+ let query = build_head(query_config, Some("query_norm")).await?;
+ let key = build_head(key_config, Some("key_norm")).await?;
+ let value = build_head(value_config, None).await?;
Ok(Self {
- query: build_head(query_config, Some("query_norm"))?,
- key: build_head(key_config, Some("key_norm"))?,
- value: build_head(value_config, None)?,
+ query,
+ key,
+ value,
num_q_heads,
num_kv_heads,
projection_row_stride,
diff --git a/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs b/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs
index 0011ca082..aa4b71282 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs
@@ -49,8 +49,8 @@ enum DeltaNetSuffixStatus<B: Backend> {
}
pub struct DeltaNetState<B: Backend> {
- conv_state: B::GlobalBuffer,
- ssm_state: B::GlobalBuffer,
+ conv_state: B::GlobalGpuBuffer,
+ ssm_state: B::GlobalGpuBuffer,
suffix_status: Option<DeltaNetSuffixStatus<B>>,
state_advance: <B::Kernels as Kernels>::StateAdvanceKernel,
is_empty: bool,
@@ -127,15 +127,15 @@ pub struct DeltaNet<B: Backend> {
kernel_size: u32,
outer_data_type: DataType,
in_projection: Box<dyn Linear<B>>,
- conv_weight: B::GlobalBuffer,
- conv_bias: Option<B::GlobalBuffer>,
+ conv_weight: B::GlobalGpuBuffer,
+ conv_bias: Option<B::GlobalGpuBuffer>,
conv_update: <B::Kernels as Kernels>::DeltaNetConvUpdateKernel,
conv_pack: <B::Kernels as Kernels>::DeltaNetConvPackKernel,
conv_scan: <B::Kernels as Kernels>::DeltaNetConvScanKernel,
conv_tree_scan: <B::Kernels as Kernels>::ConvTreeScanKernel,
- a_log: B::GlobalBuffer,
- dt_bias: B::GlobalBuffer,
- norm_weight: B::GlobalBuffer,
+ a_log: B::GlobalGpuBuffer,
+ dt_bias: B::GlobalGpuBuffer,
+ norm_weight: B::GlobalGpuBuffer,
norm_epsilon: f32,
delta_net_update: <B::Kernels as Kernels>::DeltaNetUpdateKernel,
delta_net_prefill_prep: <B::Kernels as Kernels>::DeltaNetPrefillPrepKernel,
@@ -160,13 +160,13 @@ pub enum DeltaNetNewError<B: Backend> {
}
impl<B: Backend> DeltaNet<B> {
- pub fn new(
+ pub async fn new(
hidden_dim: u32,
outer_data_type: DataType,
config: &DeltaNetConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Self, Option<B::GlobalBuffer>), DeltaNetNewError<B>> {
+ ) -> Result<(Self, Option<B::GlobalGpuBuffer>), DeltaNetNewError<B>> {
if config.kernel_size != 4 {
return Err(DeltaNetNewError::UnsupportedConfiguration(format!(
"kernel_size must be 4, got {}",
@@ -207,14 +207,15 @@ impl<B: Backend> DeltaNet<B> {
false,
&parameter_tree.subtree("in_proj"),
context,
- )?;
+ )
+ .await?;
let conv_config = &config.conv_config;
let conv_tree = parameter_tree.subtree("conv");
- let conv_weight = conv_tree.read_buffer("weights", &[conv_dim, config.kernel_size], INNER_DATA_TYPE)?;
+ let conv_weight = conv_tree.read_buffer("weights", &[conv_dim, config.kernel_size], INNER_DATA_TYPE).await?;
let conv_bias = if conv_config.has_biases {
- Some(conv_tree.read_buffer("biases", &[conv_dim], INNER_DATA_TYPE)?)
+ Some(conv_tree.read_buffer("biases", &[conv_dim], INNER_DATA_TYPE).await?)
} else {
None
};
@@ -239,9 +240,9 @@ impl<B: Backend> DeltaNet<B> {
)
.map_err(DeltaNetNewError::Backend)?;
- let a_log = parameter_tree.read_buffer("a_log", &[config.num_heads], INNER_DATA_TYPE)?;
- let dt_bias = parameter_tree.read_buffer("dt_bias", &[config.num_heads], INNER_DATA_TYPE)?;
- let norm_weight = parameter_tree.read_buffer("norm.scales", &[config.value_head_dim], INNER_DATA_TYPE)?;
+ let a_log = parameter_tree.read_buffer("a_log", &[config.num_heads], INNER_DATA_TYPE).await?;
+ let dt_bias = parameter_tree.read_buffer("dt_bias", &[config.num_heads], INNER_DATA_TYPE).await?;
+ let norm_weight = parameter_tree.read_buffer("norm.scales", &[config.value_head_dim], INNER_DATA_TYPE).await?;
let norm_epsilon = config.norm_config.epsilon;
let delta_net_update =
<B::Kernels as Kernels>::DeltaNetUpdateKernel::new(context, outer_data_type, config.head_dim)
@@ -305,7 +306,8 @@ impl<B: Backend> DeltaNet<B> {
false,
&parameter_tree.subtree("out_proj"),
context,
- )?;
+ )
+ .await?;
Ok((
Self {
@@ -459,9 +461,11 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {
context: &B::Context,
) -> Result<Box<dyn MixerState<B>>, B::Error> {
let conv_state =
- context.create_buffer(size_for_shape(&[self.conv_dim, self.kernel_size - 1], INNER_DATA_TYPE))?;
- let ssm_state = context
- .create_buffer(size_for_shape(&[self.num_heads, self.value_head_dim, self.head_dim], INNER_DATA_TYPE))?;
+ context.create_buffer_gpu(size_for_shape(&[self.conv_dim, self.kernel_size - 1], INNER_DATA_TYPE))?;
+ let ssm_state = context.create_buffer_gpu(size_for_shape(
+ &[self.num_heads, self.value_head_dim, self.head_dim],
+ INNER_DATA_TYPE,
+ ))?;
let state_advance = <B::Kernels as Kernels>::StateAdvanceKernel::new(
context,
diff --git a/crates/uzu-engine/src/encodable_block/mixer/delta_net/tree_verify.rs b/crates/uzu-engine/src/encodable_block/mixer/delta_net/tree_verify.rs
index ceb52e9e8..91bf7618f 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/delta_net/tree_verify.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/delta_net/tree_verify.rs
@@ -17,9 +17,9 @@ pub struct TreeVerifyEncodeArguments<'a, B: Backend> {
pub trie: &'a B::ConstantBuffer,
pub log_decay: &'a B::ScratchBuffer,
pub beta: &'a B::ScratchBuffer,
- pub h0: &'a B::GlobalBuffer,
+ pub h0: &'a B::GlobalGpuBuffer,
pub in_proj: &'a B::ScratchBuffer,
- pub norm_weight: &'a B::GlobalBuffer,
+ pub norm_weight: &'a B::GlobalGpuBuffer,
pub conv_dim: u32,
pub total_proj_dim: u32,
pub norm_epsilon: f32,
diff --git a/crates/uzu-engine/src/encodable_block/mixer/mod.rs b/crates/uzu-engine/src/encodable_block/mixer/mod.rs
index 80b81775e..7f4deeb7f 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/mod.rs
@@ -89,18 +89,18 @@ pub enum MixerNewError<B: Backend> {
}
impl<B: Backend> dyn Mixer<B> {
- pub fn new(
+ pub async fn new(
hidden_dim: u32,
data_type: DataType,
rope_config: Option<&AnyRoPEConfig>, // TODO: this shouldn't exist
config: &AnyTokenMixerConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Box<dyn Mixer<B>>, Option<B::GlobalBuffer>), MixerNewError<B>> {
+ ) -> Result<(Box<dyn Mixer<B>>, Option<B::GlobalGpuBuffer>), MixerNewError<B>> {
match config {
AnyTokenMixerConfig::AttentionConfig(config) => {
let (attention, in_projection_input_hadamard_factors) =
- Attention::new(hidden_dim, data_type, rope_config, config, parameter_tree, context)?;
+ Attention::new(hidden_dim, data_type, rope_config, config, parameter_tree, context).await?;
Ok((Box::new(attention), in_projection_input_hadamard_factors))
},
@@ -108,7 +108,7 @@ impl<B: Backend> dyn Mixer<B> {
assert!(rope_config.is_none(), "unexpected rope for delta net mixer");
let (delta_net, in_projection_input_hadamard_factors) =
- DeltaNet::new(hidden_dim, data_type, config, parameter_tree, context)?;
+ DeltaNet::new(hidden_dim, data_type, config, parameter_tree, context).await?;
Ok((Box::new(delta_net), in_projection_input_hadamard_factors))
},
@@ -116,7 +116,7 @@ impl<B: Backend> dyn Mixer<B> {
assert!(rope_config.is_none(), "unexpected rope for short conv mixer");
let (short_conv, in_projection_input_hadamard_factors) =
- ShortConv::new(hidden_dim, data_type, config, parameter_tree, context)?;
+ ShortConv::new(hidden_dim, data_type, config, parameter_tree, context).await?;
Ok((Box::new(short_conv), in_projection_input_hadamard_factors))
},
diff --git a/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs b/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs
index 306819f99..b4fb72a04 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs
@@ -27,7 +27,7 @@ enum ShortConvStateSuffixStatus<B: Backend> {
}
pub struct ShortConvState<B: Backend> {
- conv_state: B::GlobalBuffer,
+ conv_state: B::GlobalGpuBuffer,
suffix_state: Option<ShortConvStateSuffixStatus<B>>,
is_empty: bool,
}
@@ -83,8 +83,8 @@ pub struct ShortConv<B: Backend> {
short_conv_prefill: <B::Kernels as Kernels>::ShortConvPrefillKernel,
short_conv_decode: <B::Kernels as Kernels>::ShortConvDecodeKernel,
short_conv_trie: <B::Kernels as Kernels>::ShortConvTrieKernel,
- conv_weight: B::GlobalBuffer,
- conv_bias: Option<B::GlobalBuffer>,
+ conv_weight: B::GlobalGpuBuffer,
+ conv_bias: Option<B::GlobalGpuBuffer>,
}
#[derive(Debug, Error)]
@@ -100,13 +100,13 @@ pub enum ShortConvNewError<B: Backend> {
}
impl<B: Backend> ShortConv<B> {
- pub fn new(
+ pub async fn new(
hidden_dim: u32,
data_type: DataType,
config: &ShortConvConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Self, Option<B::GlobalBuffer>), ShortConvNewError<B>> {
+ ) -> Result<(Self, Option<B::GlobalGpuBuffer>), ShortConvNewError<B>> {
let kernel_size = config.kernel_size;
if kernel_size < 2 {
return Err(ShortConvNewError::UnsupportedConfiguration(format!(
@@ -122,7 +122,8 @@ impl<B: Backend> ShortConv<B> {
false,
&parameter_tree.subtree("in_projection"),
context,
- )?;
+ )
+ .await?;
let out_projection = <dyn Linear<B>>::new(
hidden_dim,
@@ -131,16 +132,17 @@ impl<B: Backend> ShortConv<B> {
false,
&parameter_tree.subtree("out_projection"),
context,
- )?;
+ )
+ .await?;
let conv_tree = parameter_tree.subtree("conv");
let conv_data_type = DataType::F32;
- let conv_weight = conv_tree.read_buffer("weights", &[hidden_dim, kernel_size], conv_data_type)?;
+ let conv_weight = conv_tree.read_buffer("weights", &[hidden_dim, kernel_size], conv_data_type).await?;
let has_bias = config.conv_config.has_biases;
let conv_bias = if has_bias {
- Some(conv_tree.read_buffer("biases", &[hidden_dim], conv_data_type)?)
+ Some(conv_tree.read_buffer("biases", &[hidden_dim], conv_data_type).await?)
} else {
None
};
@@ -186,7 +188,7 @@ impl<B: Backend> ShortConv<B> {
in_projected,
&self.conv_weight,
self.conv_bias.as_ref(),
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
&mut conv_output,
&mut state.conv_state,
1,
@@ -286,7 +288,7 @@ impl<B: Backend> Mixer<B> for ShortConv<B> {
context: &B::Context,
) -> Result<Box<dyn MixerState<B>>, B::Error> {
let conv_state =
- context.create_buffer(size_for_shape(&[self.kernel_size - 1, self.hidden_dim], self.data_type))?;
+ context.create_buffer_gpu(size_for_shape(&[self.kernel_size - 1, self.hidden_dim], self.data_type))?;
Ok(Box::new(ShortConvState {
conv_state,
diff --git a/crates/uzu-engine/src/encodable_block/mlp/dense.rs b/crates/uzu-engine/src/encodable_block/mlp/dense.rs
index 8bb398930..99f17292b 100644
--- a/crates/uzu-engine/src/encodable_block/mlp/dense.rs
+++ b/crates/uzu-engine/src/encodable_block/mlp/dense.rs
@@ -29,14 +29,14 @@ pub enum DenseMlpNewError<B: Backend> {
}
impl<B: Backend> DenseMlp<B> {
- pub fn new(
+ pub async fn new(
model_dimension: u32,
hidden_dimension: u32,
data_type: DataType,
config: &DenseMLPConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Self, Option<B::GlobalBuffer>), DenseMlpNewError<B>> {
+ ) -> Result<(Self, Option<B::GlobalGpuBuffer>), DenseMlpNewError<B>> {
let (up, up_input_hadamard_factors) = <dyn Linear<B>>::new_with_input_rht(
model_dimension,
2 * hidden_dimension,
@@ -44,7 +44,8 @@ impl<B: Backend> DenseMlp<B> {
config.has_up_biases,
&parameter_tree.subtree("up_projection"),
context,
- )?;
+ )
+ .await?;
let (down, down_input_preparation) = <dyn Linear<B>>::new_for_fused_input(
hidden_dimension,
@@ -53,7 +54,8 @@ impl<B: Backend> DenseMlp<B> {
config.has_down_biases,
&parameter_tree.subtree("down_projection"),
context,
- )?;
+ )
+ .await?;
let gate = MlpGateActMulEncodable::new(
hidden_dimension,
diff --git a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs
index 25e0d78ba..a97d1abaa 100644
--- a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs
+++ b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs
@@ -14,7 +14,7 @@ pub struct MlpGateActMulEncodable<B: Backend> {
activation: AnyActivation,
hidden_dim: u32,
data_type: DataType,
- hadamard_factors: Option<B::GlobalBuffer>,
+ hadamard_factors: Option<B::GlobalGpuBuffer>,
activation_quantization: Option<ActivationQuantization>,
quantized_kernel: Option<GatedActMul<B>>,
}
diff --git a/crates/uzu-engine/src/encodable_block/mlp/mod.rs b/crates/uzu-engine/src/encodable_block/mlp/mod.rs
index 5944294e5..b39ff8bf7 100644
--- a/crates/uzu-engine/src/encodable_block/mlp/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/mlp/mod.rs
@@ -41,18 +41,19 @@ pub enum MlpBlockNewError<B: Backend> {
}
impl<B: Backend> dyn Mlp<B> {
- pub fn new(
+ pub async fn new(
model_dimension: u32,
hidden_dimension: u32,
data_type: DataType,
config: &AnyMLPConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Box<dyn Mlp<B>>, Option<B::GlobalBuffer>), MlpBlockNewError<B>> {
+ ) -> Result<(Box<dyn Mlp<B>>, Option<B::GlobalGpuBuffer>), MlpBlockNewError<B>> {
match config {
AnyMLPConfig::DenseMLPConfig(config) => {
let (dense, up_input_hadamard_factors) =
- DenseMlp::new(model_dimension, hidden_dimension, data_type, config, parameter_tree, context)?;
+ DenseMlp::new(model_dimension, hidden_dimension, data_type, config, parameter_tree, context)
+ .await?;
Ok((Box::new(dense), up_input_hadamard_factors))
},
diff --git a/crates/uzu-engine/src/encodable_block/normalization.rs b/crates/uzu-engine/src/encodable_block/normalization.rs
index 04cfb0873..ffbe3d317 100644
--- a/crates/uzu-engine/src/encodable_block/normalization.rs
+++ b/crates/uzu-engine/src/encodable_block/normalization.rs
@@ -39,24 +39,24 @@ pub enum NormalizationNewError<B: Backend> {
pub struct Normalization<B: Backend> {
epsilon: f32,
scale_offset: Option<f32>,
- scales: Option<B::GlobalBuffer>,
- biases: Option<B::GlobalBuffer>,
+ scales: Option<B::GlobalGpuBuffer>,
+ biases: Option<B::GlobalGpuBuffer>,
element_count: u32,
- hadamard_factors: Option<B::GlobalBuffer>,
+ hadamard_factors: Option<B::GlobalGpuBuffer>,
post_layer_scalar_value: f32,
data_type: DataType,
kernel: <B::Kernels as Kernels>::NormalizationKernel,
}
impl<B: Backend> Normalization<B> {
- pub fn new(
+ pub async fn new(
element_count: u32,
data_type: DataType,
- hadamard_factors: Option<B::GlobalBuffer>,
+ hadamard_factors: Option<B::GlobalGpuBuffer>,
shortcut_mode: ShortcutMode,
post_layer_scalar: PostLayerScalar,
config: &NormalizationConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, NormalizationNewError<B>> {
let (copy_to_shortcut, residual_add) = match shortcut_mode {
@@ -65,14 +65,16 @@ impl<B: Backend> Normalization<B> {
ShortcutMode::Add => (true, true),
};
- let scales = config
- .has_scale
- .then(|| parameter_tree.read_buffer("scales", &[element_count], DataType::F32))
- .transpose()?;
- let biases = config
- .has_biases
- .then(|| parameter_tree.read_buffer("biases", &[element_count], DataType::F32))
- .transpose()?;
+ let scales = if config.has_scale {
+ Some(parameter_tree.read_buffer("scales", &[element_count], DataType::F32).await?)
+ } else {
+ None
+ };
+ let biases = if config.has_biases {
+ Some(parameter_tree.read_buffer("biases", &[element_count], DataType::F32).await?)
+ } else {
+ None
+ };
let (scale_residual_sum, scale_output, post_layer_scalar_value) = match post_layer_scalar {
PostLayerScalar::None => (false, false, 1.0),
diff --git a/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs b/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs
index d7a9f31c1..2826f5e98 100644
--- a/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs
+++ b/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs
@@ -46,11 +46,11 @@ pub struct PerLayerEmbedding<B: Backend> {
}
impl<B: Backend> PerLayerEmbedding<B> {
- pub fn new(
+ pub async fn new(
model_dim: u32,
data_type: DataType,
config: &PLEModelConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, PerLayerEmbeddingError<B>> {
let total_ple_dim = config.num_layers * config.ple_dim;
@@ -61,7 +61,8 @@ impl<B: Backend> PerLayerEmbedding<B> {
data_type,
&parameter_tree.subtree("token_embedding"),
context,
- )?;
+ )
+ .await?;
let model_projection = <dyn Linear<B>>::new(
model_dim,
@@ -70,7 +71,8 @@ impl<B: Backend> PerLayerEmbedding<B> {
false,
&parameter_tree.subtree("model_projection"),
context,
- )?;
+ )
+ .await?;
let scale_squared = config.model_projection_scale * config.model_projection_scale;
let projection_norm_config = {
@@ -87,7 +89,8 @@ impl<B: Backend> PerLayerEmbedding<B> {
&projection_norm_config,
&parameter_tree.subtree("projection_norm"),
context,
- )?;
+ )
+ .await?;
let add_scale = <B::Kernels as Kernels>::TensorAddScaleKernel::new(context, data_type, false)
.map_err(PerLayerEmbeddingError::BackendError)?;
@@ -173,23 +176,18 @@ pub struct PerLayerEmbeddingProjection<B: Backend> {
}
impl<B: Backend> PerLayerEmbeddingProjection<B> {
- pub fn new(
+ pub async fn new(
model_dim: u32,
num_layers: u32,
data_type: DataType,
post_layer_scalar: f32,
config: &PLELayerConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, PerLayerEmbeddingError<B>> {
- let gate = <dyn Linear<B>>::new(
- model_dim,
- config.ple_dim,
- data_type,
- false,
- &parameter_tree.subtree("gate"),
- context,
- )?;
+ let gate =
+ <dyn Linear<B>>::new(model_dim, config.ple_dim, data_type, false, &parameter_tree.subtree("gate"), context)
+ .await?;
let projection = <dyn Linear<B>>::new(
config.ple_dim,
model_dim,
@@ -197,7 +195,8 @@ impl<B: Backend> PerLayerEmbeddingProjection<B> {
false,
&parameter_tree.subtree("projection"),
context,
- )?;
+ )
+ .await?;
let norm = Normalization::new(
model_dim,
data_type,
@@ -207,7 +206,8 @@ impl<B: Backend> PerLayerEmbeddingProjection<B> {
&config.norm_config,
&parameter_tree.subtree("norm"),
context,
- )?;
+ )
+ .await?;
let activation_alpha = config.activation.alpha();
let settings = GatedActMulSettings {
@@ -272,7 +272,7 @@ impl<B: Backend> PerLayerEmbeddingProjection<B> {
&gate_out,
Some(per_layer_input),
&mut activated,
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
self.ple_dim,
batch_dim,
layer_index * self.ple_dim,
diff --git a/crates/uzu-engine/src/encodable_block/prediction_head.rs b/crates/uzu-engine/src/encodable_block/prediction_head.rs
index b5d2e094d..e7d644276 100644
--- a/crates/uzu-engine/src/encodable_block/prediction_head.rs
+++ b/crates/uzu-engine/src/encodable_block/prediction_head.rs
@@ -38,12 +38,12 @@ pub struct PredictionHead<B: Backend> {
}
impl<B: Backend> PredictionHead<B> {
- pub fn new(
+ pub async fn new(
hidden_dim: u32,
num_labels: u32,
data_type: DataType,
config: &PredictionHeadConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, PredictionHeadError<B>> {
let dense_projection = <dyn Linear<B>>::new(
@@ -53,7 +53,8 @@ impl<B: Backend> PredictionHead<B> {
config.use_dense_bias,
&parameter_tree.subtree("dense"),
context,
- )?;
+ )
+ .await?;
let activation = config.activation.act_type();
let activation_kernel = <B::Kernels as Kernels>::ActivationKernel::new(context, data_type, true)
@@ -68,10 +69,12 @@ impl<B: Backend> PredictionHead<B> {
&config.normalization_config,
&parameter_tree.subtree("norm"),
context,
- )?;
+ )
+ .await?;
let readout =
- <dyn Linear<B>>::new(hidden_dim, num_labels, data_type, true, &parameter_tree.subtree("readout"), context)?;
+ <dyn Linear<B>>::new(hidden_dim, num_labels, data_type, true, &parameter_tree.subtree("readout"), context)
+ .await?;
Ok(Self {
hidden_dim,
diff --git a/crates/uzu-engine/src/encodable_block/sampling/mod.rs b/crates/uzu-engine/src/encodable_block/sampling/mod.rs
index 5e607226d..21fd9dff8 100644
--- a/crates/uzu-engine/src/encodable_block/sampling/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/sampling/mod.rs
@@ -8,7 +8,7 @@ use parking_lot::Mutex;
use crate::{
backends::common::{
- Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, Context, Kernels,
+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, Context, GpuBuffer, Kernels,
kernel::{RepetitionPenaltyKernel, UnifiedSamplingKernel},
},
data_type::DataType,
@@ -91,7 +91,7 @@ impl<B: Backend> Sampling<B> {
sampling_range: Range<u32>,
sampling_method: &SamplingMethod,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::GlobalBuffer, B::Error> {
+ ) -> Result<B::GlobalGpuBuffer, B::Error> {
let command_buffer = &mut *command_buffer.debug_group("sampling");
let sampling_length = sampling_range.end - sampling_range.start;
@@ -149,10 +149,10 @@ impl<B: Backend> Sampling<B> {
None
};
let logits = match &penalized_logits {
- Some(logits) => (logits as &dyn Buffer<Backend = B>).subrange(..),
+ Some(logits) => (logits as &dyn GpuBuffer<Backend = B>).subrange(..),
None => {
let (buffer, range) = logits.parts();
- (buffer as &dyn Buffer<Backend = B>).subrange(range)
+ (buffer as &dyn GpuBuffer<Backend = B>).subrange(range)
},
};
@@ -178,7 +178,7 @@ impl<B: Backend> Sampling<B> {
},
};
- let mut output = command_buffer.context().create_buffer(sampling_length as usize * size_of::<u32>())?;
+ let mut output = command_buffer.context().create_buffer_gpu(sampling_length as usize * size_of::<u32>())?;
kernel.encode(
logits,
diff --git a/crates/uzu-engine/src/encodable_block/transformer.rs b/crates/uzu-engine/src/encodable_block/transformer.rs
index 0514d4065..745205db7 100644
--- a/crates/uzu-engine/src/encodable_block/transformer.rs
+++ b/crates/uzu-engine/src/encodable_block/transformer.rs
@@ -107,44 +107,41 @@ pub struct Transformer<B: Backend> {
}
impl<B: Backend> Transformer<B> {
- pub fn new(
+ pub async fn new(
data_type: DataType,
- output_norm_hadamard_factors: Option<B::GlobalBuffer>,
+ output_norm_hadamard_factors: Option<B::GlobalGpuBuffer>,
transformer_config: &TransformerConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, TransformerNewError<B>> {
let mut ropes: Vec<AnyRoPEConfig> = Vec::new();
let num_layers = transformer_config.layer_configs.len() as u32;
- let layers = transformer_config
- .layer_configs
- .iter()
- .zip(0u32..)
- .map(|(layer_config, layer_index)| {
- let layer_loader = parameter_tree.subtree(&format!("layers.{}", layer_index));
-
- let rope = layer_config.rope_config.as_ref().map(|layer_rope_config| {
- ropes.iter().position(|rope_config| rope_config == layer_rope_config).unwrap_or_else(|| {
- ropes.push(layer_rope_config.clone());
- ropes.len() - 1
- })
- });
-
- let layer = TransformerLayer::new(
- transformer_config.model_dim,
- transformer_config.hidden_dim,
- num_layers,
- layer_index,
- data_type,
- layer_config,
- &layer_loader,
- context,
- )?;
-
- Ok((layer, rope))
- })
- .collect::<Result<Box<[_]>, TransformerNewError<B>>>()?;
+ let mut layers = Vec::with_capacity(num_layers as usize);
+ for (layer_config, layer_index) in transformer_config.layer_configs.iter().zip(0u32..) {
+ let layer_loader = parameter_tree.subtree(&format!("layers.{}", layer_index));
+
+ let rope = layer_config.rope_config.as_ref().map(|layer_rope_config| {
+ ropes.iter().position(|rope_config| rope_config == layer_rope_config).unwrap_or_else(|| {
+ ropes.push(layer_rope_config.clone());
+ ropes.len() - 1
+ })
+ });
+
+ let layer = TransformerLayer::new(
+ transformer_config.model_dim,
+ transformer_config.hidden_dim,
+ num_layers,
+ layer_index,
+ data_type,
+ layer_config,
+ &layer_loader,
+ context,
+ )
+ .await?;
+
+ layers.push((layer, rope));
+ }
let output_norm = Normalization::new(
transformer_config.model_dim,
@@ -155,14 +152,15 @@ impl<B: Backend> Transformer<B> {
&transformer_config.output_norm_config,
&parameter_tree.subtree("output_norm"),
context,
- )?;
+ )
+ .await?;
let residual_add = <B::Kernels as Kernels>::TensorAddScaleKernel::new(context, data_type, false)
.map_err(TransformerNewError::Backend)?;
Ok(Self {
ropes: ropes.into_boxed_slice(),
- layers,
+ layers: layers.into_boxed_slice(),
output_norm,
model_dim: transformer_config.model_dim,
residual_add,
diff --git a/crates/uzu-engine/src/encodable_block/transformer_layer.rs b/crates/uzu-engine/src/encodable_block/transformer_layer.rs
index 30d12166f..1093bc694 100644
--- a/crates/uzu-engine/src/encodable_block/transformer_layer.rs
+++ b/crates/uzu-engine/src/encodable_block/transformer_layer.rs
@@ -58,7 +58,7 @@ struct TransformerLayerConv<B: Backend> {
pre_conv: SeparableCausalConv<B>,
kernel_projection: Box<dyn Linear<B>>,
post_conv: SeparableCausalConv<B>,
- input_rht: Option<(ActivationTransform<B>, B::GlobalBuffer)>,
+ input_rht: Option<(ActivationTransform<B>, B::GlobalGpuBuffer)>,
coefficient_count: u32,
}
@@ -79,12 +79,12 @@ pub struct TransformerLayer<B: Backend> {
}
impl<B: Backend> TransformerLayerConv<B> {
- fn new(
+ async fn new(
model_dim: u32,
data_type: DataType,
- input_hadamard_factors: Option<B::GlobalBuffer>,
+ input_hadamard_factors: Option<B::GlobalGpuBuffer>,
config: &TransformerLayerConvConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, TransformerLayerError<B>> {
let pre_conv = SeparableCausalConv::new(
@@ -95,7 +95,8 @@ impl<B: Backend> TransformerLayerConv<B> {
&config.conv_config,
&parameter_tree.subtree("pre_conv"),
context,
- )?;
+ )
+ .await?;
let post_conv = SeparableCausalConv::new(
model_dim,
config.conv_kernel_size,
@@ -104,7 +105,8 @@ impl<B: Backend> TransformerLayerConv<B> {
&config.conv_config,
&parameter_tree.subtree("post_conv"),
context,
- )?;
+ )
+ .await?;
let coefficient_count = config.conv_kernel_size * (model_dim / config.conv_group_size);
let projection_dim = coefficient_count * 2;
@@ -115,7 +117,8 @@ impl<B: Backend> TransformerLayerConv<B> {
false,
&parameter_tree.subtree("kernel_projection"),
context,
- )?;
+ )
+ .await?;
let input_rht = input_hadamard_factors
.map(|factors| ActivationTransform::input_rht(context, data_type, true).map(|kernel| (kernel, factors)))
@@ -171,14 +174,14 @@ impl<B: Backend> TransformerLayerConv<B> {
}
impl<B: Backend> TransformerLayer<B> {
- pub fn new(
+ pub async fn new(
model_dim: u32,
hidden_dim: u32,
num_layers: u32,
layer_index: u32,
data_type: DataType,
layer_config: &TransformerLayerConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, TransformerLayerError<B>> {
let post_layer_scalar = if layer_config.has_post_layer_scalar {
@@ -187,8 +190,7 @@ impl<B: Backend> TransformerLayer<B> {
layer_index,
});
}
- let scalar =
- dispatch_dtype!(|(T: data_type)| parameter_tree.read_slice::<T>("post_layer_scalar", &[1])?[0].as_());
+ let scalar = dispatch_dtype!(|(T: data_type)| parameter_tree.read_slice::<T>("post_layer_scalar", &[1]).await?[0].as_());
Some(scalar)
} else {
None
@@ -208,38 +210,45 @@ impl<B: Backend> TransformerLayer<B> {
&layer_config.mixer_config,
&parameter_tree.subtree("mixer"),
context,
- )?;
+ )
+ .await?;
let (mixer_conv, mixer_hadamard_factors) = match &layer_config.mixer_conv_config {
Some(config) => (
- Some(TransformerLayerConv::new(
- model_dim,
- data_type,
- mixer_hadamard_factors,
- config,
- &parameter_tree.subtree("mixer_conv"),
- context,
- )?),
+ Some(
+ TransformerLayerConv::new(
+ model_dim,
+ data_type,
+ mixer_hadamard_factors,
+ config,
+ &parameter_tree.subtree("mixer_conv"),
+ context,
+ )
+ .await?,
+ ),
None,
),
None => (None, mixer_hadamard_factors),
};
let pre_mixer_norm = if let Some(pre_mixer_norm_config) = &layer_config.pre_mixer_norm_config {
- Some(Normalization::new(
- model_dim,
- data_type,
- mixer_hadamard_factors,
- if layer_index > 0 {
- ShortcutMode::Add
- } else {
- ShortcutMode::Copy
- },
- PostLayerScalar::None,
- pre_mixer_norm_config,
- &parameter_tree.subtree("pre_mixer_norm"),
- context,
- )?)
+ Some(
+ Normalization::new(
+ model_dim,
+ data_type,
+ mixer_hadamard_factors,
+ if layer_index > 0 {
+ ShortcutMode::Add
+ } else {
+ ShortcutMode::Copy
+ },
+ PostLayerScalar::None,
+ pre_mixer_norm_config,
+ &parameter_tree.subtree("pre_mixer_norm"),
+ context,
+ )
+ .await?,
+ )
} else {
if layer_index != 0 || mixer_hadamard_factors.is_some() {
return Err(TransformerLayerError::MissingPreMixerNormConfig);
@@ -248,16 +257,19 @@ impl<B: Backend> TransformerLayer<B> {
};
let post_mixer_norm = if let Some(norm_config) = &layer_config.post_mixer_norm_config {
- Some(Normalization::new(
- model_dim,
- data_type,
- None,
- ShortcutMode::None,
- PostLayerScalar::None,
- norm_config,
- &parameter_tree.subtree("post_mixer_norm"),
- context,
- )?)
+ Some(
+ Normalization::new(
+ model_dim,
+ data_type,
+ None,
+ ShortcutMode::None,
+ PostLayerScalar::None,
+ norm_config,
+ &parameter_tree.subtree("post_mixer_norm"),
+ context,
+ )
+ .await?,
+ )
} else {
None
};
@@ -269,18 +281,22 @@ impl<B: Backend> TransformerLayer<B> {
&layer_config.mlp_config,
&parameter_tree.subtree("mlp"),
context,
- )?;
+ )
+ .await?;
let (mlp_conv, mlp_input_hadamard_factors) = match &layer_config.mlp_conv_config {
Some(config) => (
- Some(TransformerLayerConv::new(
- model_dim,
- data_type,
- mlp_input_hadamard_factors,
- config,
- &parameter_tree.subtree("mlp_conv"),
- context,
- )?),
+ Some(
+ TransformerLayerConv::new(
+ model_dim,
+ data_type,
+ mlp_input_hadamard_factors,
+ config,
+ &parameter_tree.subtree("mlp_conv"),
+ context,
+ )
+ .await?,
+ ),
None,
),
None => (None, mlp_input_hadamard_factors),
@@ -295,36 +311,45 @@ impl<B: Backend> TransformerLayer<B> {
&layer_config.pre_mlp_norm_config,
&parameter_tree.subtree("pre_mlp_norm"),
context,
- )?;
+ )
+ .await?;
let post_mlp_norm = if let Some(norm_config) = &layer_config.post_mlp_norm_config {
- Some(Normalization::new(
- model_dim,
- data_type,
- None,
- ShortcutMode::None,
- output_scalar,
- norm_config,
- &parameter_tree.subtree("post_mlp_norm"),
- context,
- )?)
+ Some(
+ Normalization::new(
+ model_dim,
+ data_type,
+ None,
+ ShortcutMode::None,
+ output_scalar,
+ norm_config,
+ &parameter_tree.subtree("post_mlp_norm"),
+ context,
+ )
+ .await?,
+ )
} else {
None
};
- let ple_projection = layer_config.ple_config.as_ref().map(|ple_config| {
+ let ple_projection = if let Some(ple_config) = &layer_config.ple_config {
let ple_loader = parameter_tree.subtree("ple");
- PerLayerEmbeddingProjection::new(
- model_dim,
- num_layers,
- data_type,
- post_layer_scalar.unwrap_or(1.0),
- ple_config,
- &ple_loader,
- context,
+ Some(
+ PerLayerEmbeddingProjection::new(
+ model_dim,
+ num_layers,
+ data_type,
+ post_layer_scalar.unwrap_or(1.0),
+ ple_config,
+ &ple_loader,
+ context,
+ )
+ .await
+ .expect("Failed to create per-layer embedding projection"),
)
- .expect("Failed to create per-layer embedding projection")
- });
+ } else {
+ None
+ };
Ok(Self {
layer_index,
diff --git a/crates/uzu-engine/src/encodable_block/weaver.rs b/crates/uzu-engine/src/encodable_block/weaver.rs
index 43a89cca4..694670440 100644
--- a/crates/uzu-engine/src/encodable_block/weaver.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver.rs
@@ -47,8 +47,8 @@ impl WeaverTreeShape {
}
pub struct EncodedWeaverTree<B: Backend> {
- packed_tree: B::GlobalBuffer,
- frontier: B::GlobalBuffer,
+ packed_tree: B::GlobalGpuBuffer,
+ frontier: B::GlobalGpuBuffer,
}
pub struct ProposalNode {
@@ -59,9 +59,15 @@ pub struct ProposalNode {
}
impl<B: Backend> EncodedWeaverTree<B> {
- pub fn read_nodes(self) -> Vec<ProposalNode> {
- let packed_tree = &self.packed_tree.copyout::<u32>();
- let frontier = &self.frontier.copyout::<u32>();
+ pub async fn read_nodes(
+ self,
+ context: &B::Context,
+ ) -> Result<Vec<ProposalNode>, B::Error> {
+ let (packed_tree, frontier) = futures::future::try_join(
+ context.copyout::<u32>(&self.packed_tree),
+ context.copyout::<u32>(&self.frontier),
+ )
+ .await?;
let tree_slot_count = packed_tree.len() / TreeIdx::COUNT;
let frontier_capacity = frontier.len() / FrontierIdx::COUNT;
@@ -108,7 +114,7 @@ impl<B: Backend> EncodedWeaverTree<B> {
child_indices: Vec::new(),
});
}
- nodes
+ Ok(nodes)
}
}
@@ -179,10 +185,10 @@ pub enum WeaverEncodeError<B: Backend> {
}
impl<B: Backend> Weaver<B> {
- pub fn new(
+ pub async fn new(
vocab_size: u32,
config: &WeaverConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, WeaverNewError<B>> {
if config.num_layers == 0 {
@@ -216,7 +222,8 @@ impl<B: Backend> Weaver<B> {
&config.norm_config,
&parameter_tree.subtree("embedding_norm"),
context,
- )?;
+ )
+ .await?;
let hidden_state_norm = Normalization::new(
config.target_model_dim,
DATA_TYPE,
@@ -226,7 +233,8 @@ impl<B: Backend> Weaver<B> {
&config.norm_config,
&parameter_tree.subtree("hidden_state_norm"),
context,
- )?;
+ )
+ .await?;
let token_embedding_projection = <dyn Linear<B>>::new(
config.target_embedding_dim,
config.model_dim,
@@ -234,11 +242,15 @@ impl<B: Backend> Weaver<B> {
true,
&parameter_tree.subtree("embedding_projection"),
context,
- )?;
+ )
+ .await?;
let layer_parameters = parameter_tree.subtree("blocks");
- let layers = (0..config.num_layers)
- .map(|index| WeaverLayer::new(index > 0, config, &layer_parameters.subtree(&index.to_string()), context))
- .collect::<Result<Box<[_]>, WeaverNewError<B>>>()?;
+ let mut layers = Vec::with_capacity(config.num_layers as usize);
+ for index in 0..config.num_layers {
+ layers.push(
+ WeaverLayer::new(index > 0, config, &layer_parameters.subtree(&index.to_string()), context).await?,
+ );
+ }
let readout_norm = Normalization::new(
config.model_dim,
DATA_TYPE,
@@ -248,7 +260,8 @@ impl<B: Backend> Weaver<B> {
&config.norm_config,
&parameter_tree.subtree("output_norm"),
context,
- )?;
+ )
+ .await?;
let hidden_state_projection = <dyn Linear<B>>::new(
config.target_model_dim,
config.model_dim,
@@ -256,7 +269,8 @@ impl<B: Backend> Weaver<B> {
true,
&parameter_tree.subtree("hidden_state_projection"),
context,
- )?;
+ )
+ .await?;
let readout_query_projection = <dyn Linear<B>>::new(
config.model_dim,
config.target_model_dim,
@@ -264,7 +278,8 @@ impl<B: Backend> Weaver<B> {
false,
&parameter_tree.subtree("query_projection"),
context,
- )?;
+ )
+ .await?;
let top_k =
<B::Kernels as Kernels>::RadixTopKSmall::new(context, vocab_size).map_err(WeaverNewError::Backend)?;
let top_children = <B::Kernels as Kernels>::WeaverSelectKernel::new(context, 256, Children, false)
@@ -281,7 +296,7 @@ impl<B: Backend> Weaver<B> {
token_embedding_projection,
hidden_state_norm,
hidden_state_projection,
- layers,
+ layers: layers.into_boxed_slice(),
readout_norm,
readout_query_projection,
rope_config: config.rope_config.clone(),
@@ -706,10 +721,10 @@ impl<B: Backend> Weaver<B> {
};
let mut packed_tree_readback =
- command_buffer.context().create_buffer(packed_tree.size()).map_err(WeaverEncodeError::Backend)?;
+ command_buffer.context().create_buffer_gpu(packed_tree.size()).map_err(WeaverEncodeError::Backend)?;
command_buffer.encode_copy(&packed_tree, &mut packed_tree_readback);
let mut frontier_readback =
- command_buffer.context().create_buffer(frontier.size()).map_err(WeaverEncodeError::Backend)?;
+ command_buffer.context().create_buffer_gpu(frontier.size()).map_err(WeaverEncodeError::Backend)?;
command_buffer.encode_copy(&frontier, &mut frontier_readback);
Ok(EncodedWeaverTree {
diff --git a/crates/uzu-engine/src/encodable_block/weaver_layer.rs b/crates/uzu-engine/src/encodable_block/weaver_layer.rs
index a94ad393a..8f639d48d 100644
--- a/crates/uzu-engine/src/encodable_block/weaver_layer.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver_layer.rs
@@ -41,10 +41,10 @@ pub struct WeaverLayer<B: Backend> {
}
impl<B: Backend> WeaverLayer<B> {
- pub fn new(
+ pub async fn new(
add_to_residual: bool,
config: &WeaverConfig,
- parameter_tree: &ParameterTree<B>,
+ parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, WeaverNewError<B>> {
let WeaverConfig {
@@ -65,7 +65,8 @@ impl<B: Backend> WeaverLayer<B> {
false,
&parameter_tree.subtree("qkv_projection"),
context,
- )?;
+ )
+ .await?;
let out_projection = <dyn Linear<B>>::new(
model_dim,
model_dim,
@@ -73,7 +74,8 @@ impl<B: Backend> WeaverLayer<B> {
false,
&parameter_tree.subtree("out_projection"),
context,
- )?;
+ )
+ .await?;
let prefix_attention = <B::Kernels as Kernels>::AttentionKernel::new(
context,
AttentionKernelConfig {
@@ -106,7 +108,8 @@ impl<B: Backend> WeaverLayer<B> {
norm_config,
&parameter_tree.subtree("pre_attention_norm"),
context,
- )?;
+ )
+ .await?;
let pre_mlp_norm = Normalization::new(
model_dim,
DATA_TYPE,
@@ -116,7 +119,8 @@ impl<B: Backend> WeaverLayer<B> {
norm_config,
&parameter_tree.subtree("pre_mlp_norm"),
context,
- )?;
+ )
+ .await?;
let mlp_config = AnyMLPConfig::DenseMLPConfig(DenseMLPConfig::unclipped(
linear_config.clone(),
AnyActivation::SiLU(SiLU::default()),
@@ -124,7 +128,8 @@ impl<B: Backend> WeaverLayer<B> {
true,
));
let (mlp, up_input_hadamard_factors) =
- <dyn Mlp<B>>::new(model_dim, hidden_dim, DATA_TYPE, &mlp_config, &parameter_tree.subtree("mlp"), context)?;
+ <dyn Mlp<B>>::new(model_dim, hidden_dim, DATA_TYPE, &mlp_config, &parameter_tree.subtree("mlp"), context)
+ .await?;
assert!(up_input_hadamard_factors.is_none(), "Weaver MLP does not support input Hadamard factors");
let ancestor_attention = <B::Kernels as Kernels>::AncestorAttentionKernel::new(context, head_dim, num_heads)
.map_err(WeaverNewError::Backend)?;
diff --git a/crates/uzu-engine/src/encodable_block/weight_matrix.rs b/crates/uzu-engine/src/encodable_block/weight_matrix.rs
index 0ad954d29..43378b46c 100644
--- a/crates/uzu-engine/src/encodable_block/weight_matrix.rs
+++ b/crates/uzu-engine/src/encodable_block/weight_matrix.rs
@@ -3,7 +3,7 @@ use thiserror::Error;
use crate::{
backends::common::{
- Backend, BufferCpuAccessible, BufferMut,
+ Backend,
gpu_types::{quantization::QuantizationMode, quantization_method::QuantizationMethod},
kernel::matmul::{MatmulB, QuantParams, QuantParamsLayout, QuantizedB, QuantizedCorrection, WeightsLayout},
},
@@ -81,8 +81,8 @@ pub fn parse_spec<B: Backend>(spec: &AnyWeightMatrixSpec) -> Result<ParsedWeight
}
struct Quantized<B: Backend> {
- scales: B::GlobalBuffer,
- correction: QuantizedCorrection<B::GlobalBuffer>,
+ scales: B::GlobalGpuBuffer,
+ correction: QuantizedCorrection<B::GlobalGpuBuffer>,
params: QuantParams,
info: QuantizationInfo,
signed_codes: bool,
@@ -90,18 +90,18 @@ struct Quantized<B: Backend> {
}
pub struct WeightMatrix<B: Backend> {
- values: B::GlobalBuffer,
+ values: B::GlobalGpuBuffer,
quantized: Option<Quantized<B>>,
}
impl<B: Backend> WeightMatrix<B> {
- pub fn load(
+ pub async fn load(
output_dim: u32,
input_dim: u32,
data_type: DataType,
spec: AnyWeightMatrixSpec,
required_layout: Layout,
- tree: &ParameterTree<B>,
+ tree: &ParameterTree<'_, B>,
) -> Result<Self, WeightMatrixError<B>> {
let ParsedWeightSpec {
layout,
@@ -115,7 +115,7 @@ impl<B: Backend> WeightMatrix<B> {
let (rows, columns) = physical_shape(&layout, output_dim, input_dim);
let Some(info) = quantization_info else {
- let values = tree.read_buffer("weights", &[rows, columns], data_type)?;
+ let values = tree.read_buffer("weights", &[rows, columns], data_type).await?;
return Ok(Self {
values,
quantized: None,
@@ -137,22 +137,22 @@ impl<B: Backend> WeightMatrix<B> {
}
let groups = columns.div_ceil(group_size);
- let values = tree.read_buffer("weights", &[rows, columns / packing_divisor], storage_data_type)?;
+ let values = tree.read_buffer("weights", &[rows, columns / packing_divisor], storage_data_type).await?;
let params = QuantParams::new(params_layout, rows, groups);
- let load_plane =
- |name: &str, shape: [u32; 2], storage_type: DataType| -> Result<B::GlobalBuffer, WeightMatrixError<B>> {
- Ok(tree.read_buffer(name, &shape, storage_type)?)
- };
- let scales = load_plane("scales", params.scale_shape(), data_type)?;
+ let load_plane = async |name: &str,
+ shape: [u32; 2],
+ storage_type: DataType|
+ -> Result<B::GlobalGpuBuffer, WeightMatrixError<B>> {
+ Ok(tree.read_buffer(name, &shape, storage_type).await?)
+ };
+ let scales = load_plane("scales", params.scale_shape(), data_type).await?;
let correction = match info.method {
QuantizationMethod::ScaleBias => {
- QuantizedCorrection::Biases(load_plane("biases", params.scale_shape(), data_type)?)
+ QuantizedCorrection::Biases(load_plane("biases", params.scale_shape(), data_type).await?)
},
- QuantizationMethod::ScaleZeroPoint => QuantizedCorrection::ZeroPoints(load_plane(
- "zero_points",
- params.zero_point_shape(info.mode),
- info.mode.storage_type(),
- )?),
+ QuantizationMethod::ScaleZeroPoint => QuantizedCorrection::ZeroPoints(
+ load_plane("zero_points", params.zero_point_shape(info.mode), info.mode.storage_type()).await?,
+ ),
QuantizationMethod::ScaleSymmetric => QuantizedCorrection::Symmetric,
};
@@ -169,7 +169,7 @@ impl<B: Backend> WeightMatrix<B> {
})
}
- pub fn values(&self) -> &B::GlobalBuffer {
+ pub fn values(&self) -> &B::GlobalGpuBuffer {
&self.values
}
@@ -177,19 +177,19 @@ impl<B: Backend> WeightMatrix<B> {
self.quantized.as_ref().map(|quantized| quantized.info)
}
- pub fn scales(&self) -> Option<&B::GlobalBuffer> {
+ pub fn scales(&self) -> Option<&B::GlobalGpuBuffer> {
self.quantized.as_ref().map(|quantized| &quantized.scales)
}
- pub fn zero_points(&self) -> Option<&B::GlobalBuffer> {
+ pub fn zero_points(&self) -> Option<&B::GlobalGpuBuffer> {
self.quantized.as_ref()?.correction.zero_points()
}
- pub fn biases(&self) -> Option<&B::GlobalBuffer> {
+ pub fn biases(&self) -> Option<&B::GlobalGpuBuffer> {
self.quantized.as_ref()?.correction.biases()
}
- pub fn matmul_b(&self) -> MatmulB<&B::GlobalBuffer> {
+ pub fn matmul_b(&self) -> MatmulB<&B::GlobalGpuBuffer> {
let Some(quantized) = self.quantized.as_ref() else {
return MatmulB::FullPrecision {
b: &self.values,
@@ -212,50 +212,16 @@ impl<B: Backend> WeightMatrix<B> {
pub fn optimize_weights_layout<E>(
&mut self,
- optimize: impl FnOnce(&mut B::GlobalBuffer) -> Result<WeightsLayout<B>, E>,
+ optimize: impl FnOnce(&mut B::GlobalGpuBuffer) -> Result<(WeightsLayout<B>, bool), E>,
) -> Result<(), E> {
let Some(quantized) =
self.quantized.as_mut().filter(|quantized| quantized.weights_layout == WeightsLayout::<B>::default())
else {
return Ok(());
};
- quantized.weights_layout = optimize(&mut self.values)?;
+ (quantized.weights_layout, quantized.signed_codes) = optimize(&mut self.values)?;
Ok(())
}
-
- pub fn try_prepare_a8_storage(&mut self) -> bool {
- let Some(quantized) = self.quantized.as_mut() else {
- return false;
- };
- quantized.prepare_a8_storage(&mut self.values)
- }
-
- pub fn a8_signed_codes(&self) -> Option<bool> {
- self.quantized.as_ref().map(|quantized| quantized.info.mode != QuantizationMode::U4)
- }
-}
-
-impl<B: Backend> Quantized<B> {
- fn prepare_a8_storage(
- &mut self,
- values: impl BufferMut<Buffer: BufferCpuAccessible>,
- ) -> bool {
- if self.params.layout() != QuantParamsLayout::GroupOutput {
- return false;
- }
- if self.info.mode != QuantizationMode::U4 {
- if !self.signed_codes
- && let Some(sign_flip_mask) = self.info.mode.weight_codes_sign_flip_mask()
- {
- let broadcast_mask = u64::from(sign_flip_mask) * 0x0101_0101_0101_0101;
- let (prefix, words, suffix) = bytemuck::pod_align_to_mut::<u8, u64>(values.as_slice_mut());
- words.iter_mut().for_each(|word| *word ^= broadcast_mask);
- prefix.iter_mut().chain(suffix.iter_mut()).for_each(|code| *code ^= sign_flip_mask);
- }
- self.signed_codes = true;
- }
- true
- }
}
fn physical_shape(
diff --git a/crates/uzu-engine/src/engine/classifier_model.rs b/crates/uzu-engine/src/engine/classifier_model.rs
index 151d12ad5..b606b444a 100644
--- a/crates/uzu-engine/src/engine/classifier_model.rs
+++ b/crates/uzu-engine/src/engine/classifier_model.rs
@@ -1,11 +1,4 @@
-use std::{
- cmp::min,
- collections::HashMap,
- fs::File,
- io::{self, BufReader},
- path::Path,
- sync::Arc,
-};
+use std::{cmp::min, collections::HashMap, io, path::Path, sync::Arc};
use derive_more::Debug;
use half::bf16;
@@ -17,14 +10,13 @@ use thiserror::Error;
use tokenizers::Tokenizer;
use crate::{
- backends::common::{
- Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,
- },
+ backends::common::{Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context},
config::{model::classifier_model::ClassifierModelConfig, token_codec::AnyTokenCodecConfig},
data_type::DataType,
encodable_block::classifier::{Classifier as ClassifierEncodable, ClassifierError as ClassifierEncodableError},
engine::Engine,
safetensors::{ParameterLoader, ParameterLoaderError},
+ utils::file,
};
pub struct ClassifierModel<B: Backend> {
@@ -51,26 +43,25 @@ pub enum EngineLoadClassifierError<B: Backend> {
}
impl<B: Backend> Engine<B> {
- pub fn load_classifier_model(
+ pub async fn load_classifier_model(
&self,
model_path: &Path,
) -> Result<ClassifierModel<B>, EngineLoadClassifierError<B>> {
let context = self.context.clone();
- let config: ClassifierModelConfig =
- serde_json::from_reader(BufReader::new(File::open(model_path.join("config.json"))?))?;
+ let config: ClassifierModelConfig = serde_json::from_slice(&file::read(model_path.join("config.json")).await?)?;
let data_type = DataType::BF16;
- let weights_file = File::open(model_path.join("model.safetensors"))?;
- let weight_loader = ParameterLoader::new(&weights_file, context.as_ref())?;
+ let weight_loader = ParameterLoader::new(model_path.join("model.safetensors"), context.as_ref()).await?;
let classifier = ClassifierEncodable::new(
data_type,
&config.classifier_config,
&weight_loader.tree().subtree("classifier"),
context.as_ref(),
- )?;
+ )
+ .await?;
let output_labels = if let Some(output_labels) = config.classifier_config.output_labels {
assert!(output_labels.len() as u32 == config.classifier_config.num_labels);
@@ -81,7 +72,7 @@ impl<B: Backend> Engine<B> {
weight_loader.assert_all_tensors_read()?;
- let tokenizer = Arc::new(Tokenizer::from_file(model_path.join("tokenizer.json"))?);
+ let tokenizer = Arc::new(Tokenizer::from_bytes(file::read(model_path.join("tokenizer.json")).await?)?);
let token_codec_config = config.token_codec_config;
Ok(ClassifierModel {
@@ -156,7 +147,7 @@ impl<B: Backend> ClassifierModel<B> {
let mut output_buffer = self
.context
- .create_buffer(self.output_labels.len() * self.data_type.size_in_bytes())
+ .create_buffer_gpu(self.output_labels.len() * self.data_type.size_in_bytes())
.map_err(ClassifierModelClassifyError::Backend)?;
command_buffer.encode_copy(&logits, &mut output_buffer);
@@ -173,7 +164,8 @@ impl<B: Backend> ClassifierModel<B> {
assert!(self.data_type == DataType::BF16);
- let logits_bf16: Vec<bf16> = output_buffer.copyout::<bf16>();
+ let logits_bf16 =
+ self.context.copyout::<bf16>(&output_buffer).await.map_err(ClassifierModelClassifyError::Backend)?;
let count = min(self.output_labels.len(), logits_bf16.len());
let mut logits: Vec<f32> = vec![0.0f32; count];
diff --git a/crates/uzu-engine/src/engine/language_model/mod.rs b/crates/uzu-engine/src/engine/language_model/mod.rs
index e1865a8b0..e8355eefc 100644
--- a/crates/uzu-engine/src/engine/language_model/mod.rs
+++ b/crates/uzu-engine/src/engine/language_model/mod.rs
@@ -1,4 +1,4 @@
-use std::{fs::File, io, io::BufReader, path::Path, sync::Arc};
+use std::{io, path::Path, sync::Arc};
use derive_more::Debug;
use thiserror::Error;
@@ -15,6 +15,7 @@ use crate::{
engine::Engine,
safetensors::{ParameterLoader, ParameterLoaderError},
speculators::dflash_tfm::{DFlashSpeculatorLoadError, DFlashTfmSpeculator},
+ utils::file,
};
pub use crate::{config::model::generation::GenerationConfig, utils::strict_serde::Unsupported};
@@ -56,21 +57,19 @@ pub enum EngineLoadLanguageModelError<B: Backend> {
}
impl<B: Backend> Engine<B> {
- pub fn load_language_model(
+ pub async fn load_language_model(
self: &Arc<Self>,
model_path: &Path,
) -> Result<LanguageModel<B>, EngineLoadLanguageModelError<B>> {
- let config: LanguageModelConfig =
- serde_json::from_reader(BufReader::new(File::open(model_path.join("config.json"))?))?;
+ let config: LanguageModelConfig = serde_json::from_slice(&file::read(model_path.join("config.json")).await?)?;
- let weights_file = File::open(model_path.join("model.safetensors"))?;
- let weight_loader = ParameterLoader::new(&weights_file, &*self.context)?;
+ let weight_loader = ParameterLoader::new(model_path.join("model.safetensors"), &*self.context).await?;
// TODO
let speculator_path = model_path.join("speculator");
- let speculator_path = speculator_path.exists().then_some(speculator_path);
+ let speculator_path = file::exists(&speculator_path).await.then_some(speculator_path);
- let tokenizer = Arc::new(Tokenizer::from_file(model_path.join("tokenizer.json"))?);
+ let tokenizer = Arc::new(Tokenizer::from_bytes(file::read(model_path.join("tokenizer.json")).await?)?);
let data_type = DataType::BF16;
@@ -79,18 +78,19 @@ impl<B: Backend> Engine<B> {
&config.decoder_config,
&weight_loader.tree().subtree("decoder"),
self.context.as_ref(),
- )?;
+ )
+ .await?;
assert!(
speculator_path.is_none() || decoder.speculation_supported(),
"attempted to load speculator for a model that doesn't support one"
);
- let speculator = speculator_path
- .as_deref()
- .map(|speculator_path| DFlashTfmSpeculator::new(speculator_path, self.context.clone()))
- .transpose()?
- .flatten();
+ let speculator = if let Some(speculator_path) = speculator_path.as_deref() {
+ DFlashTfmSpeculator::new(speculator_path, self.context.clone()).await?
+ } else {
+ None
+ };
let sampling = Sampling::new(config.decoder_config.vocab_size, data_type);
diff --git a/crates/uzu-engine/src/engine/language_model/stream/stream.rs b/crates/uzu-engine/src/engine/language_model/stream/stream.rs
index 93dfef6e0..54f1f68d2 100644
--- a/crates/uzu-engine/src/engine/language_model/stream/stream.rs
+++ b/crates/uzu-engine/src/engine/language_model/stream/stream.rs
@@ -12,8 +12,8 @@ use shoji::traits::backend::chat_token::TokenStreamMetrics;
use crate::engine::language_model::grammar::Grammar;
use crate::{
backends::common::{
- Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, CommandBufferExecutable, Context,
- TimestampSpan,
+ Backend, Buffer, BufferRef, CommandBuffer, CommandBufferEncoding, CommandBufferExecutable, Context, CpuBuffer,
+ DeviceCapabilities, GlobalBufferCpuGpu, GpuBuffer, TimestampSpan,
capture_matcher::{CAPTURE_MATCHER, CaptureMatcherSpan},
gpu_types::trie::TrieNode as GpuTrieNode,
kernel::ContextRingUpdateKernel,
@@ -43,6 +43,7 @@ enum ForwardPassChaining<B: Backend> {
impl<B: Backend> ForwardPassChaining<B> {
async fn resolve<'a>(
&'a mut self,
+ readback: &mut Option<impl Future<Output = Result<Vec<u32>, B::Error>> + Send>,
tokens: &mut Vec<u64>,
timestamps: Option<&Sender<Box<[TimestampSpan]>>>,
#[cfg(grammar)] grammar: Option<&mut Grammar>,
@@ -57,7 +58,11 @@ impl<B: Backend> ForwardPassChaining<B> {
for pending in replace(&mut in_flight.pending, Box::new([])) {
wait(pending, timestamps).await.map_err(LanguageModelStreamError::Backend)?;
}
- let output_tokens = in_flight.output_tokens.as_slice::<u32>();
+ let output_tokens = readback
+ .take()
+ .expect("in-flight output readback")
+ .await
+ .map_err(LanguageModelStreamError::Backend)?;
assert_eq!(output_tokens.len(), 1);
let token_id = output_tokens[0] as u64;
let output_norm = in_flight.output_norm.take();
@@ -100,8 +105,8 @@ struct DecodingStatePending<B: Backend> {
capture_span: Option<CaptureMatcherSpan>,
hidden_features: Option<Box<[B::ScratchBuffer]>>,
output_norm: Option<B::ScratchBuffer>,
- output_tokens: Arc<B::GlobalBuffer>,
- _input_token_source: Option<Arc<B::GlobalBuffer>>,
+ output_tokens: Arc<B::GlobalGpuBuffer>,
+ _input_token_source: Option<Arc<B::GlobalGpuBuffer>>,
}
enum DecodingState<B: Backend> {
@@ -139,7 +144,7 @@ pub struct LanguageModelStream<'a, B: Backend> {
model_state: &'a mut LanguageModelState<B>,
options: LanguageModelStreamOptions,
allocation_pool: Arc<B::AllocationPool>,
- context_ring: Option<B::GlobalBuffer>,
+ context_ring: Option<B::GlobalGpuBuffer>,
decoding_state: DecodingState<B>,
metrics: TokenStreamMetrics,
}
@@ -172,7 +177,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
let mut context_ring = model
.engine
.context
- .create_buffer(size_for_shape(&[2 + suffix_repetition_length], DataType::U32))
+ .create_buffer_cpu_gpu(size_for_shape(&[2 + suffix_repetition_length], DataType::U32))
.map_err(LanguageModelStreamError::Backend)?;
let state_tokens_range = Range::from(
@@ -188,7 +193,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
.collect::<Box<[_]>>(),
);
- Some(context_ring)
+ Some(context_ring.handoff())
} else {
None
};
@@ -379,6 +384,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
}
pub async fn generate(&mut self) -> Result<Option<u64>, LanguageModelStreamError<B>> {
+ let context = &self.model.engine.context;
let (mut prev_output, acceptance): (
ForwardPassChaining<B>,
Option<(<B::CommandBuffer as CommandBuffer>::Encoding, Option<CaptureMatcherSpan>)>,
@@ -410,12 +416,11 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
.await
.map_err(LanguageModelStreamError::Backend)?;
}
- let sampled_tokens = forward_pass_pending
- .output_tokens
- .as_slice::<u32>()
- .iter()
- .map(|x| *x as u64)
- .collect::<Box<[u64]>>();
+ let sampled_tokens = context
+ .copyout::<u32>(&*forward_pass_pending.output_tokens)
+ .await
+ .map_err(LanguageModelStreamError::Backend)?;
+ let sampled_tokens = sampled_tokens.iter().map(|token| u64::from(*token)).collect::<Box<[u64]>>();
let flat_trie = forward_pass_pending.input_trie.linearize();
let full = flat_trie.accept(
&sampled_tokens,
@@ -525,6 +530,12 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
DecodingState::Closed => return Ok(None),
};
+ let readback_buffer = match &prev_output {
+ ForwardPassChaining::InFlight(pending) => Some(pending.output_tokens.clone()),
+ _ => None,
+ };
+ let mut output_readback = readback_buffer.as_deref().map(|buffer| context.copyout::<u32>(buffer));
+
let context_length = self.model_state.transformer_state.context_length();
if self.model_state.max_context_length.is_some_and(|max_context_length| context_length >= max_context_length) {
@@ -532,6 +543,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
return Ok(Some(
prev_output
.resolve(
+ &mut output_readback,
&mut self.model_state.tokens,
self.options.timestamps.as_ref(),
#[cfg(grammar)]
@@ -558,6 +570,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
&& let (root_token, Some(output_norm)) = {
let resolved = prev_output
.resolve(
+ &mut output_readback,
&mut self.model_state.tokens,
self.options.timestamps.as_ref(),
#[cfg(grammar)]
@@ -619,7 +632,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
let scratch_token_ids;
let mut constant_token_ids = None;
- let token_ids: &dyn Buffer<Backend = B> = if let Some(chain_copy) = chain_copy.as_deref() {
+ let token_ids: &dyn GpuBuffer<Backend = B> = if let Some(chain_copy) = chain_copy.as_deref() {
let mut token_ids = command_buffer
.allocate_scratch(DataType::U32.size_in_bytes())
.map_err(LanguageModelStreamError::Backend)?;
@@ -680,7 +693,12 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
.map_err(LanguageModelStreamError::Backend)?;
prev_output
- .resolve(&mut self.model_state.tokens, self.options.timestamps.as_ref(), Some(grammar))
+ .resolve(
+ &mut output_readback,
+ &mut self.model_state.tokens,
+ self.options.timestamps.as_ref(),
+ Some(grammar),
+ )
.await?;
if grammar.next_bitmask(bitmask.as_slice_mut()) {
(Some(bitmask), command_buffer)
@@ -796,6 +814,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
Ok(Some(
prev_output
.resolve(
+ &mut output_readback,
&mut self.model_state.tokens,
self.options.timestamps.as_ref(),
#[cfg(grammar)]
@@ -848,7 +867,13 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
.map_err(LanguageModelStreamError::Backend)?;
}
- Some(in_flight.output_tokens.as_slice::<u32>()[0] as u64)
+ let context = &self.model.engine.context;
+ Some(
+ context
+ .copyout::<u32>(in_flight.output_tokens.subrange(..size_of::<u32>()))
+ .await
+ .map_err(LanguageModelStreamError::Backend)?[0] as u64,
+ )
},
DecodingState::Accepting {
full,
@@ -906,7 +931,14 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
impl<'a, B: Backend> Drop for LanguageModelStream<'a, B> {
fn drop(&mut self) {
- if !matches!(self.decoding_state, DecodingState::Closed) {
+ if !matches!(self.decoding_state, DecodingState::Closed)
+ && self
+ .model
+ .engine
+ .context
+ .device_capabilities()
+ .contains(DeviceCapabilities::GLOBAL_BUFFERS_CPU_ACCESSIBLE)
+ {
let _ = block_on(self.close());
}
}
diff --git a/crates/uzu-engine/src/engine/mod.rs b/crates/uzu-engine/src/engine/mod.rs
index 4d4f27087..95781931d 100644
--- a/crates/uzu-engine/src/engine/mod.rs
+++ b/crates/uzu-engine/src/engine/mod.rs
@@ -1,4 +1,4 @@
-use std::{fs::File, io::BufReader, path::Path, sync::Arc};
+use std::{path::Path, sync::Arc};
use derive_more::Debug;
use thiserror::Error;
@@ -58,22 +58,22 @@ pub enum ResolveModelTypeError {
UnableToDeserializeConfig(#[from] serde_json::Error),
}
-pub fn resolve_model_type(model_path: &Path) -> Result<ModelType, ResolveModelTypeError> {
- Ok(match read_model_config(model_path)? {
+pub async fn resolve_model_type(model_path: &Path) -> Result<ModelType, ResolveModelTypeError> {
+ Ok(match read_model_config(model_path).await? {
AnyModelConfig::LanguageModelConfig(_) => ModelType::LanguageModel,
AnyModelConfig::ClassifierModelConfig(_) => ModelType::Classifier,
})
}
-pub fn resolve_model_sampling_method(model_path: &Path) -> Result<Option<SamplingMethod>, ResolveModelTypeError> {
- Ok(match read_model_config(model_path)? {
+pub async fn resolve_model_sampling_method(model_path: &Path) -> Result<Option<SamplingMethod>, ResolveModelTypeError> {
+ Ok(match read_model_config(model_path).await? {
AnyModelConfig::LanguageModelConfig(config) => Some(config.generation_config.default_sampling_method()),
AnyModelConfig::ClassifierModelConfig(_) => None,
})
}
-pub fn resolve_model_context_length(model_path: &Path) -> Result<Option<u32>, ResolveModelTypeError> {
- let transformer = match read_model_config(model_path)? {
+pub async fn resolve_model_context_length(model_path: &Path) -> Result<Option<u32>, ResolveModelTypeError> {
+ let transformer = match read_model_config(model_path).await? {
AnyModelConfig::LanguageModelConfig(config) => config.decoder_config.transformer_config,
AnyModelConfig::ClassifierModelConfig(_) => return Ok(None),
};
@@ -85,7 +85,7 @@ pub fn resolve_model_context_length(model_path: &Path) -> Result<Option<u32>, Re
.min())
}
-fn read_model_config(model_path: &Path) -> Result<AnyModelConfig, ResolveModelTypeError> {
- let file = File::open(model_path.join("config.json"))?;
- Ok(serde_json::from_reader(BufReader::new(file))?)
+async fn read_model_config(model_path: &Path) -> Result<AnyModelConfig, ResolveModelTypeError> {
+ let bytes = crate::utils::file::read(model_path.join("config.json")).await?;
+ Ok(serde_json::from_slice(&bytes)?)
}
diff --git a/crates/uzu-engine/src/lib.rs b/crates/uzu-engine/src/lib.rs
index 3a23a313c..4ef17d123 100644
--- a/crates/uzu-engine/src/lib.rs
+++ b/crates/uzu-engine/src/lib.rs
@@ -1,6 +1,5 @@
#![cfg_attr(test, feature(custom_test_frameworks))]
#![cfg_attr(test, test_runner(crate::tests::harness::uzu_harness))]
-#![cfg_attr(target_family = "wasm", feature(wasi_ext))]
mod config;
mod data_type;
diff --git a/crates/uzu-engine/src/safetensors.rs b/crates/uzu-engine/src/safetensors.rs
index 2bdc7a785..3cc330c3a 100644
--- a/crates/uzu-engine/src/safetensors.rs
+++ b/crates/uzu-engine/src/safetensors.rs
@@ -1,17 +1,17 @@
-#[cfg(unix)]
-use std::os::unix::fs::FileExt;
-#[cfg(target_family = "wasm")]
-use std::os::wasi::fs::FileExt;
-use std::{cell::Cell, collections::HashMap, fs::File};
+use std::{
+ collections::HashMap,
+ path::Path,
+ sync::atomic::{AtomicBool, Ordering},
+};
use derive_more::Debug;
use serde::Deserialize;
use thiserror::Error;
use crate::{
- backends::common::{Backend, BufferMut, Context},
+ backends::common::{Backend, Context, CpuBuffer, GlobalBufferCpuGpu},
data_type::{DataType, DataTypeRepr},
- utils::{size_for_shape::size_for_shape, strict_serde::DeserializeStrictOwned},
+ utils::{file::File, size_for_shape::size_for_shape, strict_serde::DeserializeStrictOwned},
};
#[derive(Debug, Error)]
@@ -70,26 +70,27 @@ struct TensorInfo {
shape: Box<[u32]>,
data_offsets: (u64, u64),
#[serde(skip)]
- read: Cell<bool>,
+ read: AtomicBool,
}
pub struct ParameterLoader<'a, B: Backend> {
- file: &'a File,
+ file: File,
context: &'a B::Context,
header: Header,
data_offset: u64,
}
impl<'a, B: Backend> ParameterLoader<'a, B> {
- pub fn new(
- file: &'a File,
+ pub async fn new(
+ path: impl AsRef<Path>,
context: &'a B::Context,
) -> Result<Self, ParameterLoaderError<B>> {
+ let file = File::open(path).await?;
let mut header_size = [0; 8];
- file.read_exact_at(&mut header_size, 0)?;
+ file.read_exact_at(&mut header_size, 0).await?;
let header_size = u64::from_le_bytes(header_size);
let mut header = vec![0; header_size as usize];
- file.read_exact_at(&mut header, 8)?;
+ file.read_exact_at(&mut header, 8).await?;
let header: Header = serde_json::from_slice(&header)?;
Ok(Self {
file,
@@ -111,7 +112,7 @@ impl<'a, B: Backend> ParameterLoader<'a, B> {
.header
.tensors
.iter()
- .filter(|(_, tensor)| !tensor.read.get())
+ .filter(|(_, tensor)| !tensor.read.load(Ordering::Relaxed))
.map(|(key, _)| key.clone())
.collect::<Vec<_>>();
if unread.is_empty() {
@@ -186,22 +187,25 @@ impl<B: Backend> ParameterTree<'_, B> {
Ok(tensor)
}
- pub fn read_buffer(
+ pub async fn read_buffer(
&self,
name: &str,
shape: &[u32],
dtype: DataType,
- ) -> Result<B::GlobalBuffer, ParameterLoaderError<B>> {
+ ) -> Result<B::GlobalGpuBuffer, ParameterLoaderError<B>> {
let tensor = self.tensor(name, shape, dtype)?;
let (start, end) = tensor.data_offsets;
- let mut buffer =
- self.loader.context.create_buffer((end - start) as usize).map_err(ParameterLoaderError::BackendError)?;
- self.loader.file.read_exact_at(buffer.as_slice_mut::<u8>(), self.loader.data_offset + start)?;
- tensor.read.set(true);
- Ok(buffer)
+ let mut buffer = self
+ .loader
+ .context
+ .create_buffer_cpu_gpu((end - start) as usize)
+ .map_err(ParameterLoaderError::BackendError)?;
+ self.loader.file.read_exact_at(buffer.as_slice_mut::<u8>(), self.loader.data_offset + start).await?;
+ tensor.read.store(true, Ordering::Relaxed);
+ Ok(buffer.handoff())
}
- pub fn read_slice<T: DataTypeRepr>(
+ pub async fn read_slice<T: DataTypeRepr>(
&self,
name: &str,
shape: &[u32],
@@ -210,8 +214,8 @@ impl<B: Backend> ParameterTree<'_, B> {
let (start, end) = tensor.data_offsets;
let size = (end - start) as usize;
let mut data = vec![T::zeroed(); size / size_of::<T>()];
- self.loader.file.read_exact_at(bytemuck::cast_slice_mut(&mut data), self.loader.data_offset + start)?;
- tensor.read.set(true);
+ self.loader.file.read_exact_at(bytemuck::cast_slice_mut(&mut data), self.loader.data_offset + start).await?;
+ tensor.read.store(true, Ordering::Relaxed);
Ok(data.into_boxed_slice())
}
}
diff --git a/crates/uzu-engine/src/speculators/dflash_tfm.rs b/crates/uzu-engine/src/speculators/dflash_tfm.rs
index 83c108e8c..2d014cf01 100644
--- a/crates/uzu-engine/src/speculators/dflash_tfm.rs
+++ b/crates/uzu-engine/src/speculators/dflash_tfm.rs
@@ -1,7 +1,6 @@
use std::{
collections::HashMap,
- fs::File,
- io::{self, BufReader},
+ io,
path::Path,
sync::{Arc, mpsc::Sender},
};
@@ -29,7 +28,10 @@ use crate::{
},
safetensors::{ParameterLoader, ParameterLoaderError},
trie::TrieNode,
- utils::timestamps::{record, wait},
+ utils::{
+ file,
+ timestamps::{record, wait},
+ },
};
#[derive(Debug, Error)]
@@ -93,13 +95,12 @@ pub struct DFlashTfmSpeculator<B: Backend> {
}
impl<B: Backend> DFlashTfmSpeculator<B> {
- pub fn new(
+ pub async fn new(
model_path: &Path,
context: Arc<B::Context>,
) -> Result<Option<Self>, DFlashSpeculatorLoadError<B>> {
- let mut shapes = serde_json::from_reader::<_, HashMap<String, DFlashTfmTreeShape>>(BufReader::new(
- File::open(model_path.join("shapes.json"))?,
- ))?;
+ let mut shapes: HashMap<String, DFlashTfmTreeShape> =
+ serde_json::from_slice(&file::read(model_path.join("shapes.json")).await?)?;
let Some(shape) = context
.device_name()
@@ -111,27 +112,27 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
let data_type = DataType::BF16;
- let config: SpeculatorModelConfig =
- serde_json::from_reader(BufReader::new(File::open(model_path.join("config.json"))?))?;
+ let config: SpeculatorModelConfig = serde_json::from_slice(&file::read(model_path.join("config.json")).await?)?;
let AnySpeculatorConfig::DFlashSpeculatorConfig(config) = config.speculator_config;
- let weights_file = File::open(model_path.join("model.safetensors"))?;
- let weight_loader = ParameterLoader::new(&weights_file, &*context)?;
+ let weight_loader = ParameterLoader::new(model_path.join("model.safetensors"), &*context).await?;
let speculator_tree = weight_loader.tree().subtree("speculator");
- let dflash = DFlash::new(data_type, &config.draft_config, &speculator_tree.subtree("draft_model"), &*context)?;
- let weaver = config
- .weaver_config
- .as_ref()
- .map(|weaver_config| {
+ let dflash =
+ DFlash::new(data_type, &config.draft_config, &speculator_tree.subtree("draft_model"), &*context).await?;
+ let weaver = if let Some(weaver_config) = &config.weaver_config {
+ Some(
Weaver::new(
config.draft_config.vocab_size,
weaver_config,
&speculator_tree.subtree("weaver"),
&*context,
)
- })
- .transpose()?;
+ .await?,
+ )
+ } else {
+ None
+ };
weight_loader.assert_all_tensors_read()?;
@@ -266,7 +267,7 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
&dflash_output.logits,
None::<&B::ConstantBuffer>,
None::<&B::ConstantBuffer>,
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
None::<&B::ConstantBuffer>,
&batch_topology,
(0..chain_length).into(),
@@ -276,7 +277,7 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
.map_err(DFlashTreeError::Backend)?;
let completed =
wait(command_buffer.end_encoding().submit(), timestamps).await.map_err(DFlashTreeError::Backend)?;
- let tokens = sampled.copyout::<u32>();
+ let tokens = self.context.copyout::<u32>(&sampled).await.map_err(DFlashTreeError::Backend)?;
drop(completed);
nodes.extend(tokens.into_iter().zip(1u32..).map(|(token_id, depth)| ProposalNode {
token_id,
@@ -350,7 +351,7 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
)?;
let completed =
wait(command_buffer.end_encoding().submit(), timestamps).await.map_err(DFlashTreeError::Backend)?;
- let nodes = tree.read_nodes();
+ let nodes = tree.read_nodes(&self.context).await.map_err(DFlashTreeError::Backend)?;
drop(completed);
nodes
},
diff --git a/crates/uzu-engine/src/utils/file.rs b/crates/uzu-engine/src/utils/file.rs
new file mode 100644
index 000000000..345bff681
--- /dev/null
+++ b/crates/uzu-engine/src/utils/file.rs
@@ -0,0 +1,29 @@
+use std::{io, path::Path};
+
+pub use async_fs::read;
+use futures::{
+ io::{AsyncReadExt, AsyncSeekExt, SeekFrom},
+ lock::Mutex,
+};
+
+pub struct File(Mutex<async_fs::File>);
+
+impl File {
+ pub async fn open(path: impl AsRef<Path>) -> io::Result<Self> {
+ Ok(Self(Mutex::new(async_fs::File::open(path).await?)))
+ }
+
+ pub async fn read_exact_at(
+ &self,
+ buffer: &mut [u8],
+ offset: u64,
+ ) -> io::Result<()> {
+ let mut file = self.0.lock().await;
+ file.seek(SeekFrom::Start(offset)).await?;
+ file.read_exact(buffer).await
+ }
+}
+
+pub async fn exists(path: impl AsRef<Path>) -> bool {
+ async_fs::metadata(path).await.is_ok()
+}
diff --git a/crates/uzu-engine/src/utils/mod.rs b/crates/uzu-engine/src/utils/mod.rs
index bf1465e61..1c94393d8 100644
--- a/crates/uzu-engine/src/utils/mod.rs
+++ b/crates/uzu-engine/src/utils/mod.rs
@@ -1,9 +1,13 @@
pub mod dispatch_dtype;
pub mod downcast;
+#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), path = "wasm_file.rs")]
+pub mod file;
pub mod maybe_mut;
-#[cfg(backend = "cpu")]
+#[cfg(any(backend = "cpu", backend = "webgpu"))]
pub mod pointers;
pub mod size_for_shape;
pub mod strict_serde;
pub mod timestamps;
pub mod version;
+#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
+pub mod wasm_future;
diff --git a/crates/uzu-engine/src/utils/pointers.rs b/crates/uzu-engine/src/utils/pointers.rs
index 7b9b0556d..489501e6a 100644
--- a/crates/uzu-engine/src/utils/pointers.rs
+++ b/crates/uzu-engine/src/utils/pointers.rs
@@ -1,18 +1,26 @@
-pub struct SendPtr<T>(pub *const T);
-impl<T> SendPtr<T> {
- pub fn as_ptr(self) -> *const T {
- self.0
+#[cfg(backend = "cpu")]
+mod send_ptr {
+ #[derive(Debug)]
+ pub struct SendPtr<T>(pub *const T);
+ impl<T> SendPtr<T> {
+ pub fn as_ptr(self) -> *const T {
+ self.0
+ }
}
-}
-unsafe impl<T> Send for SendPtr<T> {}
-unsafe impl<T> Sync for SendPtr<T> {}
-impl<T> Clone for SendPtr<T> {
- fn clone(&self) -> Self {
- *self
+ unsafe impl<T> Send for SendPtr<T> {}
+ unsafe impl<T> Sync for SendPtr<T> {}
+ impl<T> Clone for SendPtr<T> {
+ fn clone(&self) -> Self {
+ *self
+ }
}
+ impl<T> Copy for SendPtr<T> {}
}
-impl<T> Copy for SendPtr<T> {}
+#[cfg(backend = "cpu")]
+pub use send_ptr::SendPtr;
+
+#[derive(Debug)]
pub struct SendPtrMut<T>(pub *mut T);
impl<T> SendPtrMut<T> {
pub fn as_ptr(self) -> *mut T {
diff --git a/crates/uzu-engine/src/utils/wasm_file.rs b/crates/uzu-engine/src/utils/wasm_file.rs
new file mode 100644
index 000000000..facddb4c2
--- /dev/null
+++ b/crates/uzu-engine/src/utils/wasm_file.rs
@@ -0,0 +1,85 @@
+use std::{
+ io::{self, Error, ErrorKind},
+ path::{Component, Path},
+};
+
+use wasm_bindgen::{JsCast, JsValue};
+use web_sys::{DomException, FileSystemDirectoryHandle, FileSystemFileHandle, js_sys::Uint8Array};
+
+use crate::utils::wasm_future::JsFuture;
+
+pub struct File(web_sys::File);
+
+impl File {
+ pub async fn open(path: impl AsRef<Path>) -> io::Result<Self> {
+ let path = path.as_ref();
+ let name =
+ path.file_name().and_then(|name| name.to_str()).ok_or_else(|| Error::from(ErrorKind::InvalidInput))?;
+ let directory = directory(path.parent().ok_or_else(|| Error::from(ErrorKind::InvalidInput))?).await?;
+ let handle =
+ FileSystemFileHandle::from(JsFuture::from(directory.get_file_handle(name)).await.map_err(io_error)?);
+ let file = JsFuture::from(handle.get_file()).await.map_err(io_error)?.into();
+ Ok(Self(file))
+ }
+
+ pub async fn read_exact_at(
+ &self,
+ buffer: &mut [u8],
+ offset: u64,
+ ) -> io::Result<()> {
+ let mut offset = offset;
+ for chunk in buffer.chunks_mut(16 * 1024 * 1024) {
+ let end = offset + chunk.len() as u64;
+ let blob = self.0.slice_with_f64_and_f64(offset as f64, end as f64).map_err(io_error)?;
+ let bytes = Uint8Array::new(&JsFuture::from(blob.array_buffer()).await.map_err(io_error)?);
+ if bytes.length() as usize != chunk.len() {
+ return Err(Error::from(ErrorKind::UnexpectedEof));
+ }
+ bytes.copy_to(chunk);
+ offset = end;
+ }
+ Ok(())
+ }
+}
+
+pub async fn read(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
+ let file = File::open(path).await?;
+ let buffer = JsFuture::from(file.0.array_buffer()).await.map_err(io_error)?;
+ Ok(Uint8Array::new(&buffer).to_vec())
+}
+
+pub async fn exists(path: impl AsRef<Path>) -> bool {
+ directory(path.as_ref()).await.is_ok() || File::open(path).await.is_ok()
+}
+
+async fn directory(path: &Path) -> io::Result<FileSystemDirectoryHandle> {
+ let window = web_sys::window().ok_or_else(|| Error::new(ErrorKind::Unsupported, "OPFS requires a window"))?;
+ let mut directory = FileSystemDirectoryHandle::from(
+ JsFuture::from(window.navigator().storage().get_directory()).await.map_err(io_error)?,
+ );
+ for component in path.components() {
+ match component {
+ Component::Normal(name) => {
+ let name = name.to_str().ok_or_else(|| Error::from(ErrorKind::InvalidInput))?;
+ directory = JsFuture::from(directory.get_directory_handle(name)).await.map_err(io_error)?.into();
+ },
+ Component::RootDir | Component::CurDir => {},
+ _ => return Err(Error::new(ErrorKind::InvalidInput, "OPFS paths cannot contain parent components")),
+ }
+ }
+ Ok(directory)
+}
+
+fn io_error(error: JsValue) -> Error {
+ if let Some(exception) = error.dyn_ref::<DomException>() {
+ let kind = match exception.name().as_str() {
+ "NotFoundError" => ErrorKind::NotFound,
+ "NotAllowedError" | "SecurityError" => ErrorKind::PermissionDenied,
+ "TypeMismatchError" | "TypeError" => ErrorKind::InvalidInput,
+ _ => ErrorKind::Other,
+ };
+ Error::new(kind, exception.message())
+ } else {
+ Error::other(format!("{error:?}"))
+ }
+}
diff --git a/crates/uzu-engine/src/utils/wasm_future.rs b/crates/uzu-engine/src/utils/wasm_future.rs
new file mode 100644
index 000000000..71512e742
--- /dev/null
+++ b/crates/uzu-engine/src/utils/wasm_future.rs
@@ -0,0 +1,29 @@
+use std::{
+ pin::Pin,
+ task::{Context, Poll},
+};
+
+use wasm_bindgen::JsValue;
+use web_sys::js_sys::Promise;
+
+pub struct JsFuture(wasm_bindgen_futures::JsFuture);
+
+impl From<Promise> for JsFuture {
+ fn from(promise: Promise) -> Self {
+ Self(promise.into())
+ }
+}
+
+impl Future for JsFuture {
+ type Output = Result<JsValue, JsValue>;
+
+ fn poll(
+ self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ ) -> Poll<Self::Output> {
+ Pin::new(&mut self.get_mut().0).poll(cx)
+ }
+}
+
+#[cfg(not(target_feature = "atomics"))]
+unsafe impl Send for JsFuture {}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/activation_test.rs b/crates/uzu-engine/unit/backends/common/kernel/activation_test.rs
index 308988289..fd684b881 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/activation_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/activation_test.rs
@@ -45,16 +45,16 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
if input.in_place {
let mut output_buffer = create_buffer_with_data::<B, T>(&context, &input.data);
let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to get command buffer");
- kernel.encode(None::<&B::GlobalBuffer>, &mut output_buffer, n as u32, input.act_type, &mut command_buffer);
+ kernel.encode(None::<&B::GlobalGpuBuffer>, &mut output_buffer, n as u32, input.act_type, &mut command_buffer);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&output_buffer)
+ buffer_to_vec::<B, T>(&context, &output_buffer)
} else {
let input_buffer = create_buffer_with_data::<B, T>(&context, &input.data);
let mut output_buffer = create_buffer::<B, T>(&context, n);
let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to get command buffer");
kernel.encode(Some(&input_buffer), &mut output_buffer, n as u32, input.act_type, &mut command_buffer);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&output_buffer)
+ buffer_to_vec::<B, T>(&context, &output_buffer)
}
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs b/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs
index d67fae9e4..4196fee4d 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs
@@ -51,13 +51,16 @@ fn run<T: DataTypeRepr + Float + Debug, B: Backend>(
}
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
if !in_place {
- assert_eq!(buffer_to_vec::<B, T>(&input), data);
+ assert_eq!(buffer_to_vec::<B, T>(&context, &input), data);
}
- buffer_to_vec(if in_place {
- &input
- } else {
- &output
- })
+ buffer_to_vec(
+ &*context,
+ if in_place {
+ &input
+ } else {
+ &output
+ },
+ )
}
fn check<T: DataTypeRepr + Float + Debug>(tolerance: f64) {
@@ -139,7 +142,7 @@ fn output_rht_fused_bias_matches_separate_mixed_dtype() {
.expect("fused transform")
.encode_fp_in_place(&mut fused, &factors, Some(&bias), 2, channels as u32, &mut command_buffer);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- assert_eq!(buffer_to_vec::<B, bf16>(&fused), expected);
+ assert_eq!(buffer_to_vec::<B, bf16>(&context, &fused), expected);
});
}
@@ -206,7 +209,11 @@ mod quantize {
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- (buffer_to_vec(&values), buffer_to_vec(&scales), group_sums.as_ref().map(buffer_to_vec))
+ (
+ buffer_to_vec(&*context, &values),
+ buffer_to_vec(&*context, &scales),
+ group_sums.as_ref().map(|buffer| buffer_to_vec(&*context, buffer)),
+ )
}
fn check_quantize(
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs
index b8cd42997..b4f0b8274 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs
@@ -28,16 +28,16 @@ const MAX_DEPTH: u32 = 8;
struct Runner<B: Backend> {
context: Arc<B::Context>,
kernel: <B::Kernels as Kernels>::AncestorAttentionKernel,
- prefix_kv: B::GlobalBuffer,
- node_kv: B::GlobalBuffer,
- current_qkv: B::GlobalBuffer,
- cosines: B::GlobalBuffer,
- sines: B::GlobalBuffer,
- node_metadata: B::GlobalBuffer,
- ancestor_indices: B::GlobalBuffer,
- ancestor_counts: B::GlobalBuffer,
- node_indices: B::GlobalBuffer,
- output: B::GlobalBuffer,
+ prefix_kv: B::GlobalGpuBuffer,
+ node_kv: B::GlobalGpuBuffer,
+ current_qkv: B::GlobalGpuBuffer,
+ cosines: B::GlobalGpuBuffer,
+ sines: B::GlobalGpuBuffer,
+ node_metadata: B::GlobalGpuBuffer,
+ ancestor_indices: B::GlobalGpuBuffer,
+ ancestor_counts: B::GlobalGpuBuffer,
+ node_indices: B::GlobalGpuBuffer,
+ output: B::GlobalGpuBuffer,
rows: u32,
prefix_length: u32,
ancestor_stride: u32,
@@ -139,7 +139,7 @@ impl<B: Backend> Runner<B> {
&mut command_buffer,
);
}
- block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap().gpu_execution_time()
+ block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap().gpu_execution_time().unwrap()
}
}
@@ -147,13 +147,13 @@ impl<B: Backend> Runner<B> {
fn ancestor_attention_matches_cpu() {
let mut cpu = Runner::<Cpu>::new(4, 5, 3, 16);
cpu.encode(1);
- let expected_output = buffer_to_vec::<Cpu, bf16>(&cpu.output);
- let expected_node_kv = buffer_to_vec::<Cpu, bf16>(&cpu.node_kv);
+ let expected_output = buffer_to_vec::<Cpu, bf16>(&cpu.context, &cpu.output);
+ let expected_node_kv = buffer_to_vec::<Cpu, bf16>(&cpu.context, &cpu.node_kv);
let mut metal = Runner::<Metal>::new(4, 5, 3, 16);
metal.encode(1);
- let actual_output = buffer_to_vec::<Metal, bf16>(&metal.output);
- let actual_node_kv = buffer_to_vec::<Metal, bf16>(&metal.node_kv);
+ let actual_output = buffer_to_vec::<Metal, bf16>(&metal.context, &metal.output);
+ let actual_node_kv = buffer_to_vec::<Metal, bf16>(&metal.context, &metal.node_kv);
assert_eq_float(&expected_output, &actual_output, 0.02, "AncestorAttention output");
assert_eq!(actual_node_kv, expected_node_kv);
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs
index 018b74a64..6ef24aeac 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs
@@ -46,8 +46,8 @@ fn run<B: Backend>() -> Output {
&mut queries,
Some(&mut keys),
Some(&mut values),
- None::<&B::GlobalBuffer>,
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
2,
Some(1),
2,
@@ -60,9 +60,9 @@ fn run<B: Backend>() -> Output {
block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("Failed to wait command buffer");
Output {
- queries: buffer_to_vec(&queries),
- keys: buffer_to_vec(&keys),
- values: buffer_to_vec(&values),
+ queries: buffer_to_vec(&*context, &queries),
+ keys: buffer_to_vec(&*context, &keys),
+ values: buffer_to_vec(&*context, &values),
}
}
@@ -98,10 +98,10 @@ fn run_query_only<B: Backend>() -> Vec<bf16> {
kernel.encode(
&qg,
&mut queries,
- None::<&mut B::GlobalBuffer>,
- None::<&mut B::GlobalBuffer>,
- None::<&B::GlobalBuffer>,
- None::<&B::GlobalBuffer>,
+ None::<&mut B::GlobalGpuBuffer>,
+ None::<&mut B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
2,
None,
2,
@@ -113,7 +113,7 @@ fn run_query_only<B: Backend>() -> Vec<bf16> {
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("Failed to wait command buffer");
- buffer_to_vec(&queries)
+ buffer_to_vec(&*context, &queries)
}
#[uzu_test]
@@ -166,15 +166,15 @@ fn run_int8<B: Backend>(num_q_heads: u32) -> Int8Output {
let mut command_buffer = context.create_command_buffer(None, None).unwrap();
kernel.encode(
&qkvg,
- None::<&mut B::GlobalBuffer>,
+ None::<&mut B::GlobalGpuBuffer>,
Some(&mut q_codes),
Some(&mut q_scales),
Some(&mut k_codes),
Some(&mut k_scales),
Some(&mut v_codes),
Some(&mut v_scales),
- None::<&B::GlobalBuffer>,
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
+ None::<&B::GlobalGpuBuffer>,
num_q_heads,
None,
33,
@@ -186,8 +186,8 @@ fn run_int8<B: Backend>(num_q_heads: u32) -> Int8Output {
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
Int8Output {
- codes: [&q_codes, &k_codes, &v_codes].map(buffer_to_vec::<B, u8>),
- scales: [&q_scales, &k_scales, &v_scales].map(buffer_to_vec::<B, bf16>),
+ codes: [&q_codes, &k_codes, &v_codes].map(|buffer| buffer_to_vec::<B, u8>(&context, buffer)),
+ scales: [&q_scales, &k_scales, &v_scales].map(|buffer| buffer_to_vec::<B, bf16>(&context, buffer)),
}
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs
index 505112ae2..afe029377 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs
@@ -61,7 +61,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- (buffer_to_vec(&keys), buffer_to_vec(&values))
+ (buffer_to_vec(&*context, &keys), buffer_to_vec(&*context, &values))
}
/// Single copy between two different positions.
@@ -279,5 +279,8 @@ fn get_int8_output<B: Backend>() -> ([Vec<u8>; 2], [Vec<bf16>; 2]) {
&mut command_buffer,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- ([&keys, &values].map(buffer_to_vec::<B, u8>), [&key_scales, &value_scales].map(buffer_to_vec::<B, bf16>))
+ (
+ [&keys, &values].map(|buffer| buffer_to_vec::<B, u8>(&context, buffer)),
+ [&key_scales, &value_scales].map(|buffer| buffer_to_vec::<B, bf16>(&context, buffer)),
+ )
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs
index a893f2b57..d8c6c758d 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs
@@ -141,7 +141,7 @@ fn get_output<
let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
kernel.encode(
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
scales.as_ref(),
&mut qkvg,
input.batch_size,
@@ -156,7 +156,7 @@ fn get_output<
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("Failed to wait command buffer");
- buffer_to_vec(&qkvg)
+ buffer_to_vec(&*context, &qkvg)
}
fn test_internal<
diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs
index 008c188f6..96c22a054 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs
@@ -51,7 +51,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec(&output)
+ buffer_to_vec(&*context, &output)
}
fn run_test<T: DataTypeRepr + Float + Debug>(config: &Config) {
diff --git a/crates/uzu-engine/unit/backends/common/kernel/embedding/input_embedding_lookup_test.rs b/crates/uzu-engine/unit/backends/common/kernel/embedding/input_embedding_lookup_test.rs
index 38f505af2..646c1c559 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/embedding/input_embedding_lookup_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/embedding/input_embedding_lookup_test.rs
@@ -137,7 +137,7 @@ fn lookup<B: Backend, T: DataTypeRepr + Float>(
&mut command_buffer,
);
submit_command_buffer(command_buffer);
- buffer_to_vec::<B, T>(&output)
+ buffer_to_vec::<B, T>(context, &output)
}
fn check<T: DataTypeRepr + Float + Display>(
diff --git a/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs
index 6ab686238..cceaec422 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs
@@ -65,7 +65,7 @@ fn run_interleaved<T: DataTypeRepr + Float, B: Backend>(
let mut command_buffer = context.create_command_buffer(None, None).expect("create command buffer");
kernel.encode_fp(
&fused_up,
- None::<&<B as Backend>::GlobalBuffer>,
+ None::<&<B as Backend>::GlobalGpuBuffer>,
&mut output,
use_hadamard.then_some(&hadamard_factors),
input.gated_dim,
@@ -77,7 +77,7 @@ fn run_interleaved<T: DataTypeRepr + Float, B: Backend>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&output)
+ buffer_to_vec::<B, T>(&context, &output)
}
fn interleaved_test<T: DataTypeRepr + Float + Debug + Display>(act_type: ActivationType) {
@@ -135,7 +135,7 @@ fn run_nibble_grouped_quantized<B: Backend>(input: &InterleavedInput<bf16>) -> (
&act_operand,
&mut values,
&mut scales,
- None::<&mut B::GlobalBuffer>,
+ None::<&mut B::GlobalGpuBuffer>,
&factors,
input.gated_dim,
input.batch_dim,
@@ -143,7 +143,7 @@ fn run_nibble_grouped_quantized<B: Backend>(input: &InterleavedInput<bf16>) -> (
&mut command_buffer,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- (buffer_to_vec(&values), buffer_to_vec(&scales))
+ (buffer_to_vec(&*context, &values), buffer_to_vec(&*context, &scales))
}
#[uzu_test]
@@ -232,7 +232,7 @@ fn run_separate<T: DataTypeRepr + Float, B: Backend>(input: &SeparateInput<T>) -
&gate_out,
Some(&per_layer_input),
&mut output,
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
input.gated_dim,
input.batch_dim,
input.value_offset,
@@ -242,7 +242,7 @@ fn run_separate<T: DataTypeRepr + Float, B: Backend>(input: &SeparateInput<T>) -
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&output)
+ buffer_to_vec::<B, T>(&context, &output)
}
fn separate_test<T: DataTypeRepr + Float + Debug>() {
@@ -305,9 +305,9 @@ fn transformed_interleaved_test<T: DataTypeRepr + Float + Debug + Display>(
let mut command_buffer = context.create_command_buffer(None, None).expect("create command buffer");
kernel.encode_fp(
&fused_up,
- None::<&<B as Backend>::GlobalBuffer>,
+ None::<&<B as Backend>::GlobalGpuBuffer>,
&mut output,
- None::<&<B as Backend>::GlobalBuffer>,
+ None::<&<B as Backend>::GlobalGpuBuffer>,
GATED_DIM,
1,
0,
@@ -317,7 +317,7 @@ fn transformed_interleaved_test<T: DataTypeRepr + Float + Debug + Display>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let output = buffer_to_vec::<B, T>(&output);
+ let output = buffer_to_vec::<B, T>(&context, &output);
assert_eq_float(
&expected,
&output,
diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/conv_pack_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/conv_pack_test.rs
index 19e17b92b..a24d5ae11 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/conv_pack_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/conv_pack_test.rs
@@ -75,7 +75,7 @@ fn get_output<B: Backend, T: DataTypeRepr + Float>(input: &Input<T>) -> Vec<f32>
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("Failed to wait command buffer");
- buffer_to_vec(&packed)
+ buffer_to_vec(&*context, &packed)
}
fn test_internal<T: DataTypeRepr + Float + Debug + Display>(
diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/delta_net_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/delta_net_test.rs
index 20607f3a6..c389b607a 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/delta_net_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/delta_net_test.rs
@@ -55,8 +55,8 @@ fn run_conv_update<B: Backend>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let out = buffer_prefix_to_vec::<B, f32>(&in_out, conv_dim as usize);
- let new_state = buffer_to_vec::<B, f32>(&state_buffer);
+ let out = buffer_prefix_to_vec::<B, f32>(&context, &in_out, conv_dim as usize);
+ let new_state = buffer_to_vec::<B, f32>(&context, &state_buffer);
(out, new_state)
}
@@ -103,8 +103,9 @@ fn run_delta_net_update<B: Backend, T: DataTypeRepr>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let out = buffer_to_vec::<B, T>(&out).into_iter().map(|value| value.to_f32().expect("output to f32")).collect();
- let new_state = buffer_to_vec::<B, f32>(&state_buffer);
+ let out =
+ buffer_to_vec::<B, T>(&context, &out).into_iter().map(|value| value.to_f32().expect("output to f32")).collect();
+ let new_state = buffer_to_vec::<B, f32>(&context, &state_buffer);
(out, new_state)
}
@@ -234,7 +235,7 @@ fn test_delta_net_conv_scan_impl<B: Backend>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let in_proj_result: Vec<bf16> = buffer_to_vec(&in_proj_array);
+ let in_proj_result: Vec<bf16> = buffer_to_vec(&*context, &in_proj_array);
let in_proj_result: Vec<f32> = in_proj_result.into_iter().map(f32::from).collect();
let mut scan_outputs = vec![0.0f32; suffix_len * conv_dim];
for t in 0..suffix_len {
@@ -246,7 +247,7 @@ fn test_delta_net_conv_scan_impl<B: Backend>(
in_proj_f32[t * total_proj_dim + conv_dim..(t + 1) * total_proj_dim],
);
}
- let scan_state: Vec<f32> = buffer_to_vec(&state_array);
+ let scan_state: Vec<f32> = buffer_to_vec(&*context, &state_array);
assert_close(&ref_outputs, &scan_outputs, 1e-4, 1e-3, "ConvScan output");
assert_close(&ref_state, &scan_state, 1e-5, 1e-4, "ConvScan state");
@@ -386,7 +387,7 @@ fn run_prefill_with_norm_gate_typed<B: Backend, T: DataTypeRepr>(
&dt_bias_array,
&mut q_norm_array,
&mut k_norm_array,
- None::<&mut B::GlobalBuffer>,
+ None::<&mut B::GlobalGpuBuffer>,
&mut beta_array,
&mut decay_array,
num_v_heads as u32,
@@ -428,9 +429,9 @@ fn run_prefill_with_norm_gate_typed<B: Backend, T: DataTypeRepr>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let out: Vec<T> = buffer_to_vec(&out_array);
+ let out: Vec<T> = buffer_to_vec(&*context, &out_array);
let out = out.into_iter().map(|value| value.to_f32().expect("output to f32")).collect();
- let state = buffer_to_vec(&state_array);
+ let state = buffer_to_vec(&*context, &state_array);
(out, state)
}
@@ -576,11 +577,11 @@ fn test_delta_net_prefill_prep() {
);
block_on(cpu_enc.end_encoding().submit().wait_until_completed()).unwrap();
- let ref_q = buffer_to_vec::<Cpu, bf16>(&cpu_q).into_iter().map(f32::from).collect::<Vec<_>>();
- let ref_k = buffer_to_vec::<Cpu, bf16>(&cpu_k).into_iter().map(f32::from).collect::<Vec<_>>();
- let ref_v: Vec<bf16> = buffer_to_vec(&cpu_v);
- let ref_beta: Vec<f32> = buffer_to_vec(&cpu_beta);
- let ref_decay: Vec<f32> = buffer_to_vec(&cpu_decay);
+ let ref_q = buffer_to_vec::<Cpu, bf16>(&cpu_ctx, &cpu_q).into_iter().map(f32::from).collect::<Vec<_>>();
+ let ref_k = buffer_to_vec::<Cpu, bf16>(&cpu_ctx, &cpu_k).into_iter().map(f32::from).collect::<Vec<_>>();
+ let ref_v: Vec<bf16> = buffer_to_vec(&*cpu_ctx, &cpu_v);
+ let ref_beta: Vec<f32> = buffer_to_vec(&*cpu_ctx, &cpu_beta);
+ let ref_decay: Vec<f32> = buffer_to_vec(&*cpu_ctx, &cpu_decay);
let expected_v = in_proj
.chunks_exact(total_proj_dim)
.flat_map(|row| row[2 * key_dim..2 * key_dim + value_dim].iter().copied())
@@ -628,11 +629,11 @@ fn test_delta_net_prefill_prep() {
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let gpu_q = buffer_to_vec::<Metal, bf16>(&q_norm_array).into_iter().map(f32::from).collect::<Vec<_>>();
- let gpu_k = buffer_to_vec::<Metal, bf16>(&k_norm_array).into_iter().map(f32::from).collect::<Vec<_>>();
- let gpu_v: Vec<bf16> = buffer_to_vec(&compact_v_array);
- let gpu_beta: Vec<f32> = buffer_to_vec(&beta_array);
- let gpu_decay: Vec<f32> = buffer_to_vec(&decay_array);
+ let gpu_q = buffer_to_vec::<Metal, bf16>(&context, &q_norm_array).into_iter().map(f32::from).collect::<Vec<_>>();
+ let gpu_k = buffer_to_vec::<Metal, bf16>(&context, &k_norm_array).into_iter().map(f32::from).collect::<Vec<_>>();
+ let gpu_v: Vec<bf16> = buffer_to_vec(&*context, &compact_v_array);
+ let gpu_beta: Vec<f32> = buffer_to_vec(&*context, &beta_array);
+ let gpu_decay: Vec<f32> = buffer_to_vec(&*context, &decay_array);
assert_close(&gpu_q, &ref_q, 1e-4, 1e-3, "prep q_norm");
assert_close(&gpu_k, &ref_k, 1e-4, 1e-3, "prep k_norm");
@@ -710,7 +711,7 @@ fn bench_delta_net_prefill() {
&dt_bias_array,
&mut q_norm_array,
&mut k_norm_array,
- None::<&mut <Metal as Backend>::GlobalBuffer>,
+ None::<&mut <Metal as Backend>::GlobalGpuBuffer>,
&mut beta_array,
&mut decay_array,
num_v_heads as u32,
@@ -736,7 +737,7 @@ fn bench_delta_net_prefill() {
&dt_bias_array,
&mut q_norm_array,
&mut k_norm_array,
- None::<&mut <Metal as Backend>::GlobalBuffer>,
+ None::<&mut <Metal as Backend>::GlobalGpuBuffer>,
&mut beta_array,
&mut decay_array,
num_v_heads as u32,
diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/conv_scan_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/conv_scan_test.rs
index a8573f772..60cbb0c3c 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/conv_scan_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/conv_scan_test.rs
@@ -101,8 +101,13 @@ fn run<B: Backend>(
&mut command_buffer,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- assert_eq_float(&base_state, &buffer_to_vec(&base_state_buffer), 0.0, &format!("base state {shape} T={tree_size}"));
- (buffer_to_vec(&output), buffer_to_vec(&suffix_state))
+ assert_eq_float(
+ &base_state,
+ &buffer_to_vec(&*context, &base_state_buffer),
+ 0.0,
+ &format!("base state {shape} T={tree_size}"),
+ );
+ (buffer_to_vec(&*context, &output), buffer_to_vec(&*context, &suffix_state))
}
#[uzu_test]
@@ -129,9 +134,9 @@ fn test_conv_tree_scan() {
#[cfg(backend = "metal")]
struct Buffers {
- input: <Metal as Backend>::GlobalBuffer,
- output: <Metal as Backend>::GlobalBuffer,
- suffix_state: <Metal as Backend>::GlobalBuffer,
+ input: <Metal as Backend>::GlobalGpuBuffer,
+ output: <Metal as Backend>::GlobalGpuBuffer,
+ suffix_state: <Metal as Backend>::GlobalGpuBuffer,
}
#[cfg(backend = "metal")]
diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rs
index 26987ff44..638469c81 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rs
@@ -77,7 +77,7 @@ fn run<B: Backend, T: DataTypeRepr + Float>(accepted_indices: &[u32]) -> Vec<f32
&mut command_buffer,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec(&committed_state)
+ buffer_to_vec(&*context, &committed_state)
}
#[uzu_test]
diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_verify_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_verify_test.rs
index b99a2e72f..d09315717 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_verify_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_verify_test.rs
@@ -77,7 +77,7 @@ fn run<B: Backend, T: DataTypeRepr + Float>(n: usize) -> Vec<T> {
&mut command_buffer,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec(&o)
+ buffer_to_vec(&*context, &o)
}
#[uzu_test]
diff --git a/crates/uzu-engine/unit/backends/common/kernel/logit_transform_test.rs b/crates/uzu-engine/unit/backends/common/kernel/logit_transform_test.rs
index e2cc91676..7ecce9de0 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/logit_transform_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/logit_transform_test.rs
@@ -35,7 +35,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(
kernel.encode(&mut logits_buffer, logits.len() as u32, scale, soft_cap.unwrap_or(0.0), &mut command_buffer);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&logits_buffer)
+ buffer_to_vec::<B, T>(&context, &logits_buffer)
}
fn test_logit_transform<T: DataTypeRepr + Float + Display>(
diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs
index ea7f5ac26..711d76e2e 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs
@@ -102,7 +102,7 @@ fn run_gemv<B: Backend, T: DataTypeRepr + Float>(
)
.expect("encode failed");
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&d)
+ buffer_to_vec::<B, T>(context, &d)
}
fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
@@ -172,7 +172,7 @@ fn group_major_gemv_bf16(
&context,
&buffers.x,
buffers.matmul_b(&input),
- None::<&<Metal as Backend>::GlobalBuffer>,
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
1,
input.n as usize,
input.k as usize,
@@ -256,7 +256,7 @@ fn quant_gather_case(
let ids_alloc = create_buffer_with_data::<B, u32>(&context, &ids);
let b = || buffers.matmul_b(&input);
(
- run_gemv::<B, bf16>(&context, &buffers.x, b(), None::<&<B as Backend>::GlobalBuffer>, m, vocab, k, None),
+ run_gemv::<B, bf16>(&context, &buffers.x, b(), None::<&<B as Backend>::GlobalGpuBuffer>, m, vocab, k, None),
run_gemv::<B, bf16>(&context, &buffers.x, b(), Some(&ids_alloc), m, ids_per_row, k, None),
)
});
diff --git a/crates/uzu-engine/unit/backends/common/kernel/normalization_test.rs b/crates/uzu-engine/unit/backends/common/kernel/normalization_test.rs
index 1278d3d9b..1f1f4f7b7 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/normalization_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/normalization_test.rs
@@ -64,9 +64,9 @@ fn get_output<
kernel.encode(
Some(&input_buffer),
scales_buffer.as_ref(),
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
&mut output_buffer,
- None::<&mut B::GlobalBuffer>,
+ None::<&mut B::GlobalGpuBuffer>,
hadamard_factors_buffer.as_ref(),
batch_size,
element_count,
@@ -77,7 +77,7 @@ fn get_output<
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("Failed to wait command buffer");
- buffer_to_vec::<B, OutputT>(&output_buffer)
+ buffer_to_vec::<B, OutputT>(&context, &output_buffer)
}
fn test_internal<
@@ -186,7 +186,7 @@ fn test_hadamard<T: DataTypeRepr + Float + Debug + Display>() {
&mut command_buffer,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("Failed to wait command buffer");
- let expected = buffer_to_vec::<Cpu, T>(&expected_buffer);
+ let expected = buffer_to_vec::<Cpu, T>(&context, &expected_buffer);
let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
1e-2
diff --git a/crates/uzu-engine/unit/backends/common/kernel/pooling/pooling_mean_test.rs b/crates/uzu-engine/unit/backends/common/kernel/pooling/pooling_mean_test.rs
index f6aa15f35..ad14ff5e6 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/pooling/pooling_mean_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/pooling/pooling_mean_test.rs
@@ -61,7 +61,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
kernel.encode(&input_buffer, &mut output, input.seq_len, input.hidden_dim, input.batch_size, &mut command_buffer);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec(&output)
+ buffer_to_vec(&*context, &output)
}
fn test_internal<T: DataTypeRepr + Float + Debug + Display>(
diff --git a/crates/uzu-engine/unit/backends/common/kernel/radix_top_k_small_test.rs b/crates/uzu-engine/unit/backends/common/kernel/radix_top_k_small_test.rs
index a4721ff10..ee9a5d2ca 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/radix_top_k_small_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/radix_top_k_small_test.rs
@@ -42,7 +42,7 @@ fn radix_top_k_small<B: Backend>(
let mut command_buffer = context.create_command_buffer(None, None).unwrap();
kernel.encode(&input, &mut ids, &mut scores, rows as u32, k as u32, &mut command_buffer).unwrap();
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- (buffer_to_vec(&ids), buffer_to_vec(&scores))
+ (buffer_to_vec(&*context, &ids), buffer_to_vec(&*context, &scores))
}
fn reference(
@@ -137,7 +137,7 @@ fn benchmark_radix_top_k_small() {
kernel.encode(&input, &mut ids, &mut scores, ROWS as u32, TARGET_K as u32, &mut command_buffer).unwrap();
}
let completed = block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- (completed.gpu_execution_time().div_f64(BATCH as f64), start.elapsed().div_f64(BATCH as f64))
+ (completed.gpu_execution_time().unwrap().div_f64(BATCH as f64), start.elapsed().div_f64(BATCH as f64))
};
for _ in 0..5 {
run();
diff --git a/crates/uzu-engine/unit/backends/common/kernel/separable_causal_conv_test.rs b/crates/uzu-engine/unit/backends/common/kernel/separable_causal_conv_test.rs
index 8225b8d3d..5a7e1d85b 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/separable_causal_conv_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/separable_causal_conv_test.rs
@@ -54,7 +54,7 @@ fn run_kernel<B: Backend>() -> Vec<bf16> {
&input,
&coefficient_deltas,
&weights,
- None::<&B::GlobalBuffer>,
+ None::<&B::GlobalGpuBuffer>,
&mut output,
SEQUENCE_LENGTH,
COEFFICIENT_ROW_STRIDE,
@@ -62,7 +62,7 @@ fn run_kernel<B: Backend>() -> Vec<bf16> {
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, bf16>(&output)
+ buffer_to_vec::<B, bf16>(&context, &output)
}
#[uzu_test]
diff --git a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs
index 3b27d7fa0..b53774400 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs
@@ -85,7 +85,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- (buffer_to_vec(&out), buffer_to_vec(&next_state))
+ (buffer_to_vec(&*context, &out), buffer_to_vec(&*context, &next_state))
}
fn get_test_data_basic<T: DataTypeRepr + Float>(
diff --git a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs
index c727f950d..3988448f6 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs
@@ -55,7 +55,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec(&padded)
+ buffer_to_vec(&*context, &padded)
}
/// Build test input for ShortConvPack.
diff --git a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs
index d0ea63c25..696f1ac35 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs
@@ -72,7 +72,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- (buffer_to_vec(&out), buffer_to_vec(&state_out))
+ (buffer_to_vec(&*context, &out), buffer_to_vec(&*context, &state_out))
}
fn get_test_data_basic<T: DataTypeRepr + Float>(
diff --git a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs
index 25830f172..6249a0a63 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs
@@ -85,7 +85,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- (buffer_to_vec(&out), buffer_to_vec(&suffix_state))
+ (buffer_to_vec(&*context, &out), buffer_to_vec(&*context, &suffix_state))
}
/// Linear chain: node 0 has parent -1 (root), node i has parent i-1.
diff --git a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_bias_test.rs b/crates/uzu-engine/unit/backends/common/kernel/tensor_add_bias_test.rs
index 1baf9c006..237a3eca4 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_bias_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/tensor_add_bias_test.rs
@@ -89,7 +89,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&output_buffer)
+ buffer_to_vec::<B, T>(&context, &output_buffer)
}
fn test<T: DataTypeRepr + Float + Debug>(in_place: bool) {
diff --git a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_scale_test.rs b/crates/uzu-engine/unit/backends/common/kernel/tensor_add_scale_test.rs
index 38129063c..f607693ec 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_scale_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/tensor_add_scale_test.rs
@@ -68,7 +68,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&output_buffer)
+ buffer_to_vec::<B, T>(&context, &output_buffer)
}
fn get_test_data_basic<T: DataTypeRepr + Float>() -> (Input<T>, Vec<T>) {
diff --git a/crates/uzu-engine/unit/backends/common/kernel/trellis_test.rs b/crates/uzu-engine/unit/backends/common/kernel/trellis_test.rs
index 213043630..19ffc199a 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/trellis_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/trellis_test.rs
@@ -68,9 +68,9 @@ fn run<B: Backend>(
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
(
- buffer_to_vec::<B, i8>(&activations),
- buffer_to_vec::<B, f32>(&column_group_sums),
- buffer_to_vec::<B, f32>(&scales),
+ buffer_to_vec::<B, i8>(&context, &activations),
+ buffer_to_vec::<B, f32>(&context, &column_group_sums),
+ buffer_to_vec::<B, f32>(&context, &scales),
)
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs
index 02d0fc252..ec8f0ae70 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs
@@ -80,8 +80,8 @@ fn select<B: Backend>() -> Vec<u32> {
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
[frontier, tree, slot_ancestors, token, metadata, ancestors, valid, candidate_ids]
.iter()
- .flat_map(buffer_to_vec)
- .chain(buffer_to_vec::<B, f32>(&candidate_scores).into_iter().map(f32::to_bits))
+ .flat_map(|buffer| buffer_to_vec(&*context, buffer))
+ .chain(buffer_to_vec::<B, f32>(&context, &candidate_scores).into_iter().map(f32::to_bits))
.collect()
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs
index b580fc232..3de9d8f99 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs
@@ -100,7 +100,7 @@ fn run_top_children<B: Backend>(
&mut command_buffer,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec(&frontier)
+ buffer_to_vec(&*context, &frontier)
}
fn top_children<B: Backend>(prune_noise_scale: Option<f32>) -> (Vec<u32>, Vec<f32>, Option<Vec<f32>>) {
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs
index 62f1b0110..5d8fad960 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs
@@ -98,10 +98,10 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(fixture: &Input<T>) -> Vec<T>
});
let args = AttentionArguments {
suffix_length: fixture.suffix_length as u32,
- trie: None::<&B::GlobalBuffer>,
+ trie: None::<&B::GlobalGpuBuffer>,
sinks: None,
cache: KVCacheView::full(segment_prefix_length as u32),
- gate: None::<&B::GlobalBuffer>,
+ gate: None::<&B::GlobalGpuBuffer>,
};
let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
@@ -114,7 +114,7 @@ fn get_output<T: DataTypeRepr + Float, B: Backend>(fixture: &Input<T>) -> Vec<T>
drop(pooled_output);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&output_buffer)
+ buffer_to_vec::<B, T>(&context, &output_buffer)
}
fn get_gemm_output<T: DataTypeRepr + Float>(input: &Input<T>) -> Vec<T> {
@@ -134,10 +134,10 @@ fn get_gemm_output<T: DataTypeRepr + Float>(input: &Input<T>) -> Vec<T> {
},
AttentionArguments {
suffix_length: input.suffix_length as u32,
- trie: None::<&<Metal as Backend>::GlobalBuffer>,
+ trie: None::<&<Metal as Backend>::GlobalGpuBuffer>,
sinks: None,
cache,
- gate: None::<&<Metal as Backend>::GlobalBuffer>,
+ gate: None::<&<Metal as Backend>::GlobalGpuBuffer>,
},
&mut command_buffer,
)
@@ -147,7 +147,7 @@ fn get_gemm_output<T: DataTypeRepr + Float>(input: &Input<T>) -> Vec<T> {
command_buffer.encode_copy(&pooled, &mut output);
drop(pooled);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<Metal, T>(&output)
+ buffer_to_vec::<Metal, T>(&context, &output)
}
fn test_internal<T: DataTypeRepr + Float + Debug + Display>(
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs
index d76b31263..86b5f3d72 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs
@@ -94,14 +94,14 @@ fn run_attention_with_kernel<B: Backend>(
trie: trie.as_ref(),
sinks: sinks.as_ref(),
cache,
- gate: None::<&B::GlobalBuffer>,
+ gate: None::<&B::GlobalGpuBuffer>,
};
let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");
let pooled = kernel.encode(input, arguments, &mut command_buffer).expect("encode");
let mut output = create_buffer::<B, bf16>(context, suffix_length * num_q_heads * head_dim);
command_buffer.encode_copy(&pooled, &mut output);
submit_command_buffer(command_buffer);
- buffer_to_vec::<B, bf16>(&output)
+ buffer_to_vec::<B, bf16>(context, &output)
}
#[uzu_test]
@@ -237,7 +237,7 @@ fn check_attention_gate<B: Backend>(
});
let arguments = |gate| AttentionArguments {
suffix_length: suffix_length as u32,
- trie: None::<&B::GlobalBuffer>,
+ trie: None::<&B::GlobalGpuBuffer>,
sinks: None,
cache: KVCacheView::full(prefix_length as u32),
gate,
@@ -259,8 +259,8 @@ fn check_attention_gate<B: Backend>(
command_buffer.encode_copy(&expected, &mut expected_out);
command_buffer.encode_copy(&fused, &mut fused_out);
submit_command_buffer(command_buffer);
- let expected = buffer_to_vec::<B, bf16>(&expected_out);
- let fused = buffer_to_vec::<B, bf16>(&fused_out);
+ let expected = buffer_to_vec::<B, bf16>(context, &expected_out);
+ let fused = buffer_to_vec::<B, bf16>(context, &fused_out);
assert_eq!(expected, fused, "gated attention differs at S{suffix_length} L{prefix_length}");
}
@@ -367,15 +367,15 @@ fn int8_attention_matches_cpu() {
let trie = trie.map(|nodes| command_buffer.allocate_constant_from_slice(nodes).unwrap());
prepare.encode(
&create_buffer_with_data::<Metal, bf16>(&metal, rows),
- None::<&mut <Metal as Backend>::GlobalBuffer>,
+ None::<&mut <Metal as Backend>::GlobalGpuBuffer>,
Some(&mut query_codes),
Some(&mut query_scales),
append_kv.then_some(kv.k_codes.as_mut()),
append_kv.then_some(kv.k_scales.as_mut()),
append_kv.then_some(kv.v_codes.as_mut()),
append_kv.then_some(kv.v_scales.as_mut()),
- None::<&<Metal as Backend>::GlobalBuffer>,
- None::<&<Metal as Backend>::GlobalBuffer>,
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
+ None::<&<Metal as Backend>::GlobalGpuBuffer>,
q_heads as u32,
None,
prefix as u32,
@@ -397,14 +397,14 @@ fn int8_attention_matches_cpu() {
suffix_length: suffix as u32,
trie: trie.as_ref(),
cache: KVCacheView::full(prefix as u32),
- gate: None::<&<Metal as Backend>::GlobalBuffer>,
+ gate: None::<&<Metal as Backend>::GlobalGpuBuffer>,
};
let pooled = kernel.encode(input, arguments, &mut command_buffer).unwrap();
let mut output = create_buffer::<Metal, bf16>(&metal, suffix * q_heads * head_dim);
command_buffer.encode_copy(&pooled, &mut output);
drop((pooled, trie));
submit_command_buffer(command_buffer);
- buffer_to_vec::<Metal, bf16>(&output)
+ buffer_to_vec::<Metal, bf16>(&metal, &output)
};
step(&rows[..prefix * stride], 0, None, true);
let mut actual = step(&rows[prefix * stride..], prefix, nodes, true);
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/gdn/chunked_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/gdn/chunked_test.rs
index c73cedbb4..0c3ae8d76 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/gdn/chunked_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/gdn/chunked_test.rs
@@ -8,7 +8,7 @@ use super::*;
use crate::{
backends::{
common::{
- Backend, BufferMut, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, CpuBuffer, Kernels,
kernel::{DeltaNetPrefillKernel, DeltaNetPrefillPrepKernel},
},
metal::Metal,
@@ -51,7 +51,7 @@ fn run_prefill(
context: &MetalContext,
in_proj_data: &[bf16],
chunked: Option<&MetalDeltaNetChunkedPrefill>,
- state: &mut <Metal as Backend>::GlobalBuffer,
+ state: &mut <Metal as Backend>::GlobalGpuBuffer,
) -> Vec<f32> {
let suffix_len = in_proj_data.len() / TOTAL_PROJ_DIM;
// a_log = ln U(1, 16) and dt_bias = softplus^-1(logU(1e-3, 1e-1)) as in Qwen3-Next
@@ -106,7 +106,7 @@ fn run_prefill(
&dt_bias,
&mut q,
&mut k,
- None::<&mut <Metal as Backend>::GlobalBuffer>,
+ None::<&mut <Metal as Backend>::GlobalGpuBuffer>,
&mut beta,
&mut decay,
NUM_V_HEADS as u32,
@@ -137,7 +137,8 @@ fn run_prefill(
);
}
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<Metal, bf16>(&out).into_iter().map(f32::from).collect()
+ let out = crate::tests::helpers::buffer_readback::<Metal>(context, &out);
+ buffer_to_vec::<Metal, bf16>(context, &out).into_iter().map(f32::from).collect()
}
fn check(
@@ -156,7 +157,7 @@ fn check(
.collect();
let recurrent_out = run_prefill(context, in_proj, None, &mut recurrent_state);
let (chunked_state, recurrent_state) =
- (buffer_to_vec::<Metal, f32>(&chunked_state), buffer_to_vec::<Metal, f32>(&recurrent_state));
+ (buffer_to_vec::<Metal, f32>(context, &chunked_state), buffer_to_vec::<Metal, f32>(context, &recurrent_state));
assert!(
is_close::default().abs_tol(5e-3).rel_tol(1e-3).all_close(chunked_out, recurrent_out),
@@ -185,7 +186,7 @@ fn chunked_prefill_matches_recurrent_prefill() {
let (warmup, tokens) = in_proj.split_at(WARMUP_TOKENS * TOTAL_PROJ_DIM);
let mut state = create_buffer_with_data::<Metal, f32>(&context, &vec![0.0; NUM_V_HEADS * HEAD_V_DIM * HEAD_K_DIM]);
run_prefill(&context, warmup, None, &mut state);
- let state0 = buffer_to_vec::<Metal, f32>(&state);
+ let state0 = buffer_to_vec::<Metal, f32>(&context, &state);
assert!(state0.iter().any(|value| *value != 0.0), "initial state is zero");
for suffix_len in [2 * CHUNK_SIZE as usize + 1, 512, 1024] {
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/a8w_bench.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/a8w_bench.rs
index e3fb0eded..236352bf0 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/a8w_bench.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/a8w_bench.rs
@@ -51,16 +51,16 @@ impl BenchPath {
}
struct BenchmarkData {
- unsigned_weights: <Metal as Backend>::GlobalBuffer,
- a8_weights: <Metal as Backend>::GlobalBuffer,
- weight_scales: <Metal as Backend>::GlobalBuffer,
+ unsigned_weights: <Metal as Backend>::GlobalGpuBuffer,
+ a8_weights: <Metal as Backend>::GlobalGpuBuffer,
+ weight_scales: <Metal as Backend>::GlobalGpuBuffer,
/// The `[G, N]` scale plane the A8 MXU route reads.
- group_major_weight_scales: <Metal as Backend>::GlobalBuffer,
- activations: <Metal as Backend>::GlobalBuffer,
- rht_factors: <Metal as Backend>::GlobalBuffer,
- a_working: <Metal as Backend>::GlobalBuffer,
- a_int8: <Metal as Backend>::GlobalBuffer,
- a_scales: <Metal as Backend>::GlobalBuffer,
+ group_major_weight_scales: <Metal as Backend>::GlobalGpuBuffer,
+ activations: <Metal as Backend>::GlobalGpuBuffer,
+ rht_factors: <Metal as Backend>::GlobalGpuBuffer,
+ a_working: <Metal as Backend>::GlobalGpuBuffer,
+ a_int8: <Metal as Backend>::GlobalGpuBuffer,
+ a_scales: <Metal as Backend>::GlobalGpuBuffer,
m: u32,
k: u32,
n: u32,
@@ -85,8 +85,9 @@ impl BenchmarkData {
let a8_weights = input.weights_for_upload();
let a8_weights = create_buffer_with_data::<Metal, u32>(context, &a8_weights);
let weight_scales = create_buffer_with_data::<Metal, bf16>(context, &input.scales);
- let mut group_major_weight_scales = create_buffer_with_data::<Metal, bf16>(context, &input.scales);
- transpose_metadata(group_major_weight_scales.as_slice_mut(), n, k.div_ceil(group_size), 16);
+ let mut group_major_weight_scales = input.scales.clone();
+ transpose_metadata(bytemuck::cast_slice_mut(&mut group_major_weight_scales), n, k.div_ceil(group_size), 16);
+ let group_major_weight_scales = create_buffer_with_data::<Metal, bf16>(context, &group_major_weight_scales);
let activations = create_buffer_with_data::<Metal, bf16>(context, &input.x);
let rht: Vec<i32> = (0..k)
.map(|index| {
@@ -128,10 +129,10 @@ impl BenchmarkData {
) -> MatmulArguments<
'a,
Metal,
- &'a <Metal as Backend>::GlobalBuffer,
- &'a <Metal as Backend>::GlobalBuffer,
+ &'a <Metal as Backend>::GlobalGpuBuffer,
+ &'a <Metal as Backend>::GlobalGpuBuffer,
D,
- &'a <Metal as Backend>::GlobalBuffer,
+ &'a <Metal as Backend>::GlobalGpuBuffer,
> {
MatmulArguments {
a: MatmulA::FullPrecision {
@@ -174,44 +175,45 @@ fn encode_step(
&data.activations,
&mut data.a_int8,
&mut data.a_scales,
- None::<&mut <Metal as Backend>::GlobalBuffer>,
+ None::<&mut <Metal as Backend>::GlobalGpuBuffer>,
&data.rht_factors,
data.m,
data.k,
command_buffer,
);
- let args =
- MatmulArguments::<Metal, _, &<Metal as Backend>::GlobalBuffer, _, &<Metal as Backend>::GlobalBuffer> {
- a: MatmulA::Int8Symmetric {
- values: &data.a_int8,
- scales: &data.a_scales,
- group_sums: None,
- scale_group_size: 128,
- code_layout: Int8CodeLayout::for_right_bits(DataType::from(data.mode).size_in_bits() as u32)
- .expect("W4/W8 benchmark"),
- },
- b: MatmulB::Quantized(QuantizedB {
- codes: &data.a8_weights,
- scales: &data.group_major_weight_scales,
- correction: QuantizedCorrection::Symmetric,
- params: QuantParams::new(
- QuantParamsLayout::GroupOutput,
- data.n,
- data.k.div_ceil(data.group_size),
- ),
- mode: data.mode,
- group_size: data.group_size,
- signed_codes: !matches!(data.mode, QuantizationMode::U4),
- weights_layout: GemmBLayout::RowMajor,
- }),
- b_leading_dimension: None,
- b_transpose: true,
- output: MatmulOutput::new(output, MatmulDOps::none()),
- gather_indices: None,
- m: data.m,
- n: data.n,
- k: data.k,
- };
+ let args = MatmulArguments::<
+ Metal,
+ _,
+ &<Metal as Backend>::GlobalGpuBuffer,
+ _,
+ &<Metal as Backend>::GlobalGpuBuffer,
+ > {
+ a: MatmulA::Int8Symmetric {
+ values: &data.a_int8,
+ scales: &data.a_scales,
+ group_sums: None,
+ scale_group_size: 128,
+ code_layout: Int8CodeLayout::for_right_bits(DataType::from(data.mode).size_in_bits() as u32)
+ .expect("W4/W8 benchmark"),
+ },
+ b: MatmulB::Quantized(QuantizedB {
+ codes: &data.a8_weights,
+ scales: &data.group_major_weight_scales,
+ correction: QuantizedCorrection::Symmetric,
+ params: QuantParams::new(QuantParamsLayout::GroupOutput, data.n, data.k.div_ceil(data.group_size)),
+ mode: data.mode,
+ group_size: data.group_size,
+ signed_codes: !matches!(data.mode, QuantizationMode::U4),
+ weights_layout: GemmBLayout::RowMajor,
+ }),
+ b_leading_dimension: None,
+ b_transpose: true,
+ output: MatmulOutput::new(output, MatmulDOps::none()),
+ gather_indices: None,
+ m: data.m,
+ n: data.n,
+ k: data.k,
+ };
matmul.encode_with_gemm_engine(args, GemmEngine::Mxu, command_buffer).expect("a8 gemm mxu encode");
},
BenchPath::Bf16GemmMxu => {
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm_bench.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm_bench.rs
index 48faf8722..627f755cc 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm_bench.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm_bench.rs
@@ -62,7 +62,7 @@ fn bench_gemm(c: &mut Criterion) {
b_leading_dimension: None,
b_transpose: true,
output: MatmulOutput::new(&mut d, MatmulDOps::none()),
- gather_indices: None::<&<Metal as Backend>::GlobalBuffer>,
+ gather_indices: None::<&<Metal as Backend>::GlobalGpuBuffer>,
m,
n,
k,
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs
index d4f9f730a..eb5b606a5 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs
@@ -45,10 +45,48 @@ fn tile_weights<T: DataTypeRepr + Float>(
..MatmulShape::from_arguments(&quant_arguments(buffers, input))
};
buffers.weights_layout =
- matmul.optimize_weights_layout(&shape, &mut buffers.w, context).expect("optimize weights layout");
+ matmul.optimize_weights_layout(&shape, &mut buffers.w, context).expect("optimize weights layout").0;
assert_eq!(buffers.weights_layout, GemmBLayout::MxuTiled);
}
+#[uzu_test]
+fn optimize_weights_layout_prepares_unsigned_codes() {
+ let context = block_on(MetalContext::new()).expect("Metal context");
+ if !context.supports_mxu {
+ return;
+ }
+ let kernel = MatmulMetalKernel::new(&context, bf16::data_type(), bf16::data_type(), bf16::data_type()).unwrap();
+ let signed = QuantInput::<bf16>::new(16, 512, 64, 64, 8, QuantizationMethod::ScaleSymmetric, 0)
+ .with_group_output()
+ .with_prepared_a(ACTIVATION_SCALE_GROUP_SIZE, None);
+ let mut unsigned = signed.clone();
+ unsigned.signed_codes = false;
+ let mut expected = QuantBuffers::<Metal, bf16>::allocate(&context, &signed);
+ let mut actual = QuantBuffers::<Metal, bf16>::allocate(&context, &unsigned);
+ let signed_shape = MatmulShape::from_arguments(&quant_arguments(&mut expected, &signed));
+ let unsigned_shape = MatmulShape::from_arguments(&quant_arguments(&mut actual, &unsigned));
+
+ let unsupported_shape = MatmulShape {
+ a_full_precision: true,
+ ..unsigned_shape
+ };
+ assert_eq!(
+ kernel.optimize_weights_layout(&unsupported_shape, &mut actual.w, &context).unwrap(),
+ (GemmBLayout::RowMajor, false),
+ );
+ assert_eq!(buffer_to_vec::<Metal, u32>(&context, &actual.w), unsigned.weights_for_upload());
+
+ assert_eq!(
+ kernel.optimize_weights_layout(&signed_shape, &mut expected.w, &context).unwrap(),
+ (GemmBLayout::MxuTiled, true),
+ );
+ assert_eq!(
+ kernel.optimize_weights_layout(&unsigned_shape, &mut actual.w, &context).unwrap(),
+ (GemmBLayout::MxuTiled, true),
+ );
+ assert_eq!(buffer_to_vec::<Metal, u32>(&context, &actual.w), buffer_to_vec::<Metal, u32>(&context, &expected.w));
+}
+
fn run_quant_metal<T: DataTypeRepr + Float>(
context: &MetalContext,
input: &QuantInput<T>,
@@ -74,7 +112,7 @@ fn run_quant_metal<T: DataTypeRepr + Float>(
matmul.encode(args, &mut command_buffer).expect("matmul encode failed");
}
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<Metal, T>(&buffers.y)
+ buffer_to_vec::<Metal, T>(context, &buffers.y)
}
fn check_tolerance(
@@ -241,7 +279,7 @@ fn parity_bf16_gs32_4bit_mlx_with_bias() {
};
matmul.encode_with_gemm_engine(args, GemmEngine::Simdgroup, &mut command_buffer).expect("encode quant with bias");
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let actual = buffer_to_vec::<Metal, bf16>(&buffers.y);
+ let actual = buffer_to_vec::<Metal, bf16>(&context, &buffers.y);
let mut reference = run_quant_cpu::<bf16>(&input);
for i in 0..(input.m as usize) {
@@ -292,7 +330,7 @@ fn parity_bf16_gemv_qmv_fused_scale_bias() {
};
matmul.encode(args, &mut command_buffer).expect("encode quant gemv with scale+bias");
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let actual = buffer_to_vec::<Metal, bf16>(&buffers.y);
+ let actual = buffer_to_vec::<Metal, bf16>(&context, &buffers.y);
assert_parity::<bf16>("gemv_qmv_scale_bias", &reference, &actual, 0.05, 0.4);
}
@@ -396,7 +434,7 @@ fn parity_bf16_quant_rht(
};
cpu_matmul.encode(cpu_args, &mut cpu_command_buffer).expect("cpu encode quant+rht");
block_on(cpu_command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let reference = buffer_to_vec::<Cpu, bf16>(&cpu_buffers.y);
+ let reference = buffer_to_vec::<Cpu, bf16>(&cpu_context, &cpu_buffers.y);
let mut buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);
let metal_rht = crate::tests::helpers::create_buffer_with_data::<Metal, i32>(&context, &rht);
@@ -417,7 +455,7 @@ fn parity_bf16_quant_rht(
};
matmul.encode(args, &mut command_buffer).expect("encode quant matmul with rht");
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let actual = buffer_to_vec::<Metal, bf16>(&buffers.y);
+ let actual = buffer_to_vec::<Metal, bf16>(&context, &buffers.y);
assert_parity::<bf16>(
if with_bias {
@@ -488,7 +526,7 @@ fn quant_gemm_parameter_layout_prefix_matches_cpu(
args.n = logical_n;
matmul.encode_with_gemm_engine(args, engine, &mut command_buffer).unwrap();
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let actual = buffer_to_vec::<Metal, bf16>(&buffers.y);
+ let actual = buffer_to_vec::<Metal, bf16>(&context, &buffers.y);
let expected: Vec<_> = reference
.chunks_exact(input.n as usize)
.flat_map(|row| row[..logical_n as usize].iter().copied())
@@ -713,7 +751,7 @@ fn a8w_mxu_output_bias_parity_bf16(
};
cpu_matmul.encode(cpu_arguments, &mut cpu_command_buffer).expect("CPU A8W matmul");
block_on(cpu_command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let mut reference = buffer_to_vec::<Cpu, bf16>(&cpu_buffers.y);
+ let mut reference = buffer_to_vec::<Cpu, bf16>(&cpu_context, &cpu_buffers.y);
for row in reference.chunks_exact_mut(n as usize) {
for (value, bias) in row.iter_mut().zip(&output_bias) {
*value = bf16::from_f32(value.to_f32() + bias.to_f32());
@@ -743,7 +781,7 @@ fn a8w_mxu_output_bias_parity_bf16(
.encode_with_gemm_engine(metal_arguments, GemmEngine::Mxu, &mut metal_command_buffer)
.expect("Metal A8W MXU matmul with output bias");
block_on(metal_command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let actual = buffer_to_vec::<Metal, bf16>(&metal_buffers.y);
+ let actual = buffer_to_vec::<Metal, bf16>(&context, &metal_buffers.y);
assert_parity::<bf16>(
&format!("A8W{bits} MXU output bias, output Hadamard={with_output_hadamard}"),
@@ -809,7 +847,7 @@ fn gemv_reads_mxu_tiled_layout_bf16(
};
cpu_matmul.encode(cpu_arguments, &mut cpu_command_buffer).expect("CPU matmul");
block_on(cpu_command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let reference = buffer_to_vec::<Cpu, bf16>(&cpu_buffers.y);
+ let reference = buffer_to_vec::<Cpu, bf16>(&cpu_context, &cpu_buffers.y);
let mut buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);
let metal_factors = crate::tests::helpers::create_buffer_with_data::<Metal, i32>(&context, &factors);
@@ -829,7 +867,7 @@ fn gemv_reads_mxu_tiled_layout_bf16(
};
matmul.encode(arguments, &mut command_buffer).expect("Metal matmul");
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let actual = buffer_to_vec::<Metal, bf16>(&buffers.y);
+ let actual = buffer_to_vec::<Metal, bf16>(&context, &buffers.y);
assert_parity::<bf16>(
&format!("MxuTiled GEMV k={k} n={n} gs={group_size} bits={bits} method={method:?} hadamard={output_hadamard}"),
@@ -880,7 +918,7 @@ fn gathered_gemv_reads_mxu_tiled_layout_bf16(
arguments.n = gathered_rows;
matmul.encode(arguments, &mut command_buffer).expect("gathered GEMV");
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let actual = buffer_to_vec::<Metal, bf16>(&buffers.y)[..gathered_rows as usize].to_vec();
+ let actual = buffer_to_vec::<Metal, bf16>(&context, &buffers.y)[..gathered_rows as usize].to_vec();
assert_parity::<bf16>(
&format!("gathered MxuTiled GEMV bits={bits} gs={group_size} method={method:?}"),
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs
index bbeeec47d..eac7a88d8 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs
@@ -91,7 +91,7 @@ fn decode_level(
(8 * field_sum + ((3 * (hash_byte & 15)) & 15)) as i32 - 54
}
-type MetalBuffer = <Metal as Backend>::GlobalBuffer;
+type MetalBuffer = <Metal as Backend>::GlobalGpuBuffer;
type MetalMatmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel;
const CODEBOOK: [f32; 5] = [0.0123, 0.3, -0.25, 0.125, -0.0625];
@@ -196,7 +196,7 @@ fn run_projection(
.chunks_exact(row_bytes)
.flat_map(|codes| (0..k).map(|column| decode_level(format, codes, k, column)))
.collect();
- let actual = buffer_to_vec::<Metal, u16>(&output);
+ let actual = buffer_to_vec::<Metal, u16>(context, &output);
let stride = n + PADDING;
for (index, &got) in actual.iter().enumerate() {
let token = index / stride;
diff --git a/crates/uzu-engine/unit/backends/webgpu/kernel/mod.rs b/crates/uzu-engine/unit/backends/webgpu/kernel/mod.rs
new file mode 100644
index 000000000..7eb024fb3
--- /dev/null
+++ b/crates/uzu-engine/unit/backends/webgpu/kernel/mod.rs
@@ -0,0 +1 @@
+mod test_kernel;
diff --git a/crates/uzu-engine/unit/backends/webgpu/kernel/test_kernel.rs b/crates/uzu-engine/unit/backends/webgpu/kernel/test_kernel.rs
new file mode 100644
index 000000000..6176dd2a6
--- /dev/null
+++ b/crates/uzu-engine/unit/backends/webgpu/kernel/test_kernel.rs
@@ -0,0 +1,399 @@
+use futures::executor::block_on;
+use uzu_engine_macros::uzu_test;
+
+use crate::{
+ backends::{
+ common::{
+ CommandBufferEncoding, Context,
+ gpu_types::{
+ activation_type::ActivationType, kv_cache_update::Copy, quantization::QuantizationMode,
+ ring::RingParams,
+ },
+ },
+ webgpu::{
+ WebGPU,
+ buffer::{binding_parts, dense::WebGPUDenseBufferGpu},
+ command_buffer::WebGPUCommandBufferEncoding,
+ context::WebGPUContext,
+ error::WebGPUError,
+ },
+ },
+ data_type::{DataType, DataTypeRepr},
+ tests::helpers::{buffer_to_vec, create_buffer_with_data, submit_command_buffer},
+};
+
+include!(concat!(env!("OUT_DIR"), "/webgpu/test_kernel.rs"));
+
+fn data<T: DataTypeRepr>(count: usize) -> Vec<T> {
+ (0..count).map(|i| T::from((i % 31) as f32 / 4.0 - 3.75).unwrap()).collect()
+}
+
+fn filled<T: DataTypeRepr>(
+ count: usize,
+ value: f32,
+) -> Vec<T> {
+ vec![T::from(value).unwrap(); count]
+}
+
+fn check<T: DataTypeRepr>(
+ context: &WebGPUContext,
+ initial: &[T],
+ expected: &[T],
+ tolerance: f32,
+ encode: impl FnOnce(&mut WebGPUDenseBufferGpu, &mut WebGPUCommandBufferEncoding),
+) {
+ let mut output = create_buffer_with_data::<WebGPU, T>(context, initial);
+ let mut commands = context.create_command_buffer(None, None).unwrap();
+ encode(&mut output, &mut commands);
+ submit_command_buffer(commands);
+ let actual = buffer_to_vec::<WebGPU, T>(context, &output);
+ assert_eq!(actual.len(), expected.len());
+ for (i, (actual, expected)) in actual.iter().zip(expected).enumerate() {
+ let actual = actual.to_f64().unwrap();
+ let expected = expected.to_f64().unwrap();
+ assert!((actual - expected).abs() <= tolerance as f64, "element {i}: expected {expected}, got {actual}");
+ }
+}
+
+fn dispatch_1d<T: DataTypeRepr>() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let group_thread = TestKernelGroupThreadWebGPUKernel::new(&context, T::data_type()).unwrap();
+ for size in [1usize, 255, 256, 257, 513] {
+ let initial = filled::<T>((size + 3).next_multiple_of(2), -100.0);
+ let a = data::<T>(initial.len());
+ let b = filled::<T>(initial.len(), 2.0);
+ let input_0 = create_buffer_with_data::<WebGPU, T>(&context, &a);
+ let input_1 = create_buffer_with_data::<WebGPU, T>(&context, &b);
+ let mut expected = initial.clone();
+ for (dst, src) in expected[..size].iter_mut().zip(&a) {
+ *dst = T::from(src.to_f32().unwrap() + 2.0).unwrap();
+ }
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ group_thread.encode(&input_0, &input_1, output, size as u32, commands);
+ });
+ for bs in [2, 4, 8] {
+ let kernel = TestKernelAxisWebGPUKernel::new(&context, T::data_type(), bs).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input_0, &input_1, output, size as u32, commands);
+ });
+ }
+ if T::data_type() == DataType::F32 {
+ let kernel = TestKernelAxisFloatWebGPUKernel::new(&context).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input_0, &input_1, output, size as u32, commands);
+ });
+ }
+ }
+}
+
+fn dispatch_2d<T: DataTypeRepr>() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let rows = 35;
+ let cols = 67;
+ let count = rows * cols;
+ let values = data::<T>(count + 3);
+ let input = create_buffer_with_data::<WebGPU, T>(&context, &values);
+ let initial = filled::<T>(values.len(), -100.0);
+ let mut expected = initial.clone();
+ expected[..count].copy_from_slice(&values[..count]);
+ let axis = TestKernelAxis2dWebGPUKernel::new(&context, T::data_type()).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ axis.encode(&input, output, rows as u32, cols as u32, commands);
+ });
+ let groups = TestKernelGroups2dWebGPUKernel::new(&context, T::data_type()).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ groups.encode(&input, output, rows as u32, cols as u32, commands);
+ });
+ for bm in [16, 32, 64] {
+ for bn in [16, 32, 64] {
+ let kernel = TestKernelConstraintWebGPUKernel::new(&context, T::data_type(), bm, bn);
+ if bm * bn > 1024 {
+ assert!(matches!(kernel, Err(WebGPUError::UnsupportedKernelVariant(_))));
+ } else {
+ let kernel = kernel.unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input, output, rows as u32, cols as u32, commands);
+ });
+ }
+ }
+ }
+}
+
+fn multispecialize<I: DataTypeRepr, O: DataTypeRepr>() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let values = data::<I>(260);
+ let input = create_buffer_with_data::<WebGPU, I>(&context, &values);
+ let initial = filled::<O>(values.len(), -100.0);
+ let mut expected = initial.clone();
+ for (dst, src) in expected[..257].iter_mut().zip(&values) {
+ *dst = O::from(src.to_f32().unwrap()).unwrap();
+ }
+ let kernel = TestKernelMultispecializeWebGPUKernel::new(&context, I::data_type(), O::data_type()).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input, output, 257, commands);
+ });
+}
+
+fn specialize_and_optional<T: DataTypeRepr>() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let values = data::<T>(260);
+ let input = create_buffer_with_data::<WebGPU, T>(&context, &values);
+ let bias = create_buffer_with_data::<WebGPU, T>(&context, &filled::<T>(260, 2.0));
+ let initial = filled::<T>(260, -100.0);
+ for in_place in [false, true] {
+ let mut expected = initial.clone();
+ for (dst, src) in expected[..257].iter_mut().zip(&values) {
+ *dst = if in_place {
+ T::from(-99.0).unwrap()
+ } else {
+ *src
+ };
+ }
+ let kernel = TestKernelSpecializeWebGPUKernel::new(&context, T::data_type(), in_place).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input, output, 257, commands);
+ });
+ }
+ for use_bias in [false, true] {
+ let size = if use_bias {
+ 129
+ } else {
+ 257
+ };
+ let mut expected = initial.clone();
+ for (dst, src) in expected[..size].iter_mut().zip(&values) {
+ *dst = T::from(
+ src.to_f32().unwrap()
+ + if use_bias {
+ 2.0
+ } else {
+ 0.0
+ },
+ )
+ .unwrap();
+ }
+ let kernel = TestKernelOptionalWebGPUKernel::new(&context, T::data_type(), use_bias).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input, use_bias.then_some(&bias), output, use_bias.then_some(size as u32), commands);
+ });
+ }
+}
+
+fn indirect<T: DataTypeRepr>() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let values = data::<T>(4 * 64);
+ let input = create_buffer_with_data::<WebGPU, T>(&context, &values);
+ let tile_map = create_buffer_with_data::<WebGPU, u32>(&context, &[3, 1, 0]);
+ let dispatch = create_buffer_with_data::<WebGPU, u32>(&context, &[2, 1, 1]);
+ let initial = filled::<T>(values.len(), -100.0);
+ let mut expected = initial.clone();
+ for tile in [3, 1] {
+ expected[tile * 64..(tile + 1) * 64].copy_from_slice(&values[tile * 64..(tile + 1) * 64]);
+ }
+ let kernel = TestKernelIndirectWebGPUKernel::new(&context, T::data_type()).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input, &tile_map, output, &dispatch, commands);
+ });
+}
+
+fn constant_array<T: DataTypeRepr>() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let values = data::<T>(260);
+ let input = create_buffer_with_data::<WebGPU, T>(&context, &values);
+ let factors = std::array::from_fn(|i| i as i32 - 8);
+ let initial = filled::<T>(values.len(), -100.0);
+ let mut expected = initial.clone();
+ for i in 0..257 {
+ expected[i] = T::from(values[i].to_f32().unwrap() * factors[i % 16] as f32).unwrap();
+ }
+ let kernel = TestKernelConstantArrayWebGPUKernel::new(&context, T::data_type()).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input, &factors, output, 257, commands);
+ });
+}
+
+fn groupshared<T: DataTypeRepr>() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let batch_size = 4;
+ let element_count = 259;
+ let values = data::<T>(batch_size * element_count);
+ let input = create_buffer_with_data::<WebGPU, T>(&context, &values);
+ let initial = filled::<T>(batch_size, -100.0);
+ let expected = values
+ .chunks_exact(element_count)
+ .map(|chunk| T::from(chunk.iter().map(|value| value.to_f32().unwrap()).sum::<f32>()).unwrap())
+ .collect::<Vec<_>>();
+ let kernel = TestKernelGroupsharedSizedWebGPUKernel::new(&context, T::data_type()).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input, output, batch_size as u32, element_count as u32, commands);
+ });
+
+ let element_count = 67;
+ let values = data::<T>(batch_size);
+ let input = create_buffer_with_data::<WebGPU, T>(&context, &values);
+ let initial = filled::<T>(batch_size * element_count, -100.0);
+ let expected = values.iter().flat_map(|value| std::iter::repeat_n(*value, element_count)).collect::<Vec<_>>();
+ let kernel = TestKernelGroupsharedRefWebGPUKernel::new(&context, T::data_type()).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input, output, batch_size as u32, element_count as u32, commands);
+ });
+}
+
+fn enums<T: DataTypeRepr>() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let values = data::<T>(260);
+ let input = create_buffer_with_data::<WebGPU, T>(&context, &values);
+ let initial = filled::<T>(values.len(), -100.0);
+ for act in [
+ ActivationType::SILU,
+ ActivationType::GELUApprox,
+ ActivationType::GELUExact,
+ ActivationType::IDENTITY,
+ ActivationType::SOFTPLUS,
+ ] {
+ let mut expected = initial.clone();
+ for (dst, src) in expected[..257].iter_mut().zip(&values) {
+ let x = src.to_f32().unwrap();
+ *dst = T::from(if act == ActivationType::GELUExact {
+ x
+ } else {
+ act.activate(x)
+ })
+ .unwrap();
+ }
+ let kernel = TestKernelEnumSpecializeWebGPUKernel::new(&context, T::data_type(), act).unwrap();
+ let tolerance = if T::data_type() == DataType::F16 {
+ 0.004
+ } else {
+ 1e-5
+ };
+ check(&context, &initial, &expected, tolerance, |output, commands| {
+ kernel.encode(&input, output, 257, commands);
+ });
+ }
+ let kernel = TestKernelEnumRuntimeWebGPUKernel::new(&context, T::data_type()).unwrap();
+ for (mode, scale) in [(QuantizationMode::U4, 15.0), (QuantizationMode::I8, 127.0), (QuantizationMode::U8, 255.0)] {
+ let mut expected = initial.clone();
+ for (dst, src) in expected[..257].iter_mut().zip(&values) {
+ *dst = T::from(src.to_f32().unwrap() * scale).unwrap();
+ }
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(&input, output, 257, mode, commands);
+ });
+ }
+}
+
+fn struct_constants<T: DataTypeRepr>() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let stride = 257;
+ let values = data::<T>(4 * stride);
+ let input = create_buffer_with_data::<WebGPU, T>(&context, &values);
+ let initial = filled::<T>(values.len(), -100.0);
+ let mut expected = initial.clone();
+ expected[stride..2 * stride].copy_from_slice(&values[2 * stride..3 * stride]);
+ let copy = Copy {
+ source: 2,
+ destination: 1,
+ };
+ let scalar = TestKernelStructScalarWebGPUKernel::new(&context, T::data_type()).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ scalar.encode(&input, output, copy, stride as u32, commands);
+ });
+ let mut copies = [Copy {
+ source: 0,
+ destination: 3,
+ }; 16];
+ copies[8] = copy;
+ let constant = TestKernelStructConstantWebGPUKernel::new(&context, T::data_type()).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ constant.encode(&input, output, &copies, stride as u32, commands);
+ });
+}
+
+#[uzu_test]
+fn struct_buffer() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let size = 257;
+ let ring = RingParams {
+ ring_offset: 19,
+ ring_length: 260,
+ };
+ let pairs = (0..size).flat_map(|i| [i * 3 + 1, i * 7 + 2]).collect::<Vec<u32>>();
+ let input = create_buffer_with_data::<WebGPU, u32>(&context, &pairs);
+ let initial = vec![u32::MAX; 2 * ring.ring_length as usize];
+ let mut expected_pairs = initial.clone();
+ let mut expected_indices = vec![u32::MAX; ring.ring_length as usize];
+ for i in 0..size as usize {
+ let dst = (i + ring.ring_offset as usize) % ring.ring_length as usize;
+ expected_pairs[2 * dst..2 * dst + 2].copy_from_slice(&pairs[2 * i..2 * i + 2]);
+ expected_indices[dst] = pairs[2 * i];
+ }
+ let mut indices = create_buffer_with_data::<WebGPU, u32>(&context, &vec![u32::MAX; ring.ring_length as usize]);
+ let kernel = TestKernelStructBufferWebGPUKernel::new(&context).unwrap();
+ check(&context, &initial, &expected_pairs, 0.0, |output, commands| {
+ kernel.encode(&input, output, &mut indices, ring, size, commands);
+ });
+ assert_eq!(buffer_to_vec::<WebGPU, u32>(&context, &indices), expected_indices);
+}
+
+#[uzu_test]
+fn thread_context() {
+ let context = block_on(WebGPUContext::new()).unwrap();
+ let initial = vec![u32::MAX; 260];
+ let mut expected = initial.clone();
+ expected[..257].fill(0);
+ let kernel = TestKernelThreadContextWebGPUKernel::new(&context).unwrap();
+ check(&context, &initial, &expected, 0.0, |output, commands| {
+ kernel.encode(output, 257, commands);
+ });
+}
+
+macro_rules! float_tests {
+ ($module:ident, $ty:ty, $($test:ident),+ $(,)?) => {
+ mod $module {
+ use super::*;
+
+ $(
+ #[uzu_test]
+ fn $test() {
+ super::$test::<$ty>();
+ }
+ )+
+
+ #[uzu_test]
+ fn multispecialize_to_f32() {
+ super::multispecialize::<$ty, f32>();
+ }
+
+ #[uzu_test]
+ fn multispecialize_to_f16() {
+ super::multispecialize::<$ty, half::f16>();
+ }
+ }
+ };
+}
+
+float_tests!(
+ f32,
+ f32,
+ dispatch_1d,
+ dispatch_2d,
+ specialize_and_optional,
+ indirect,
+ constant_array,
+ groupshared,
+ enums,
+ struct_constants
+);
+float_tests!(
+ f16,
+ half::f16,
+ dispatch_1d,
+ dispatch_2d,
+ specialize_and_optional,
+ indirect,
+ constant_array,
+ groupshared,
+ enums,
+ struct_constants
+);
diff --git a/crates/uzu-engine/unit/common/helpers.rs b/crates/uzu-engine/unit/common/helpers.rs
index d6b02843e..53acfa772 100644
--- a/crates/uzu-engine/unit/common/helpers.rs
+++ b/crates/uzu-engine/unit/common/helpers.rs
@@ -4,8 +4,8 @@ use futures::executor::block_on;
use crate::{
backends::common::{
- Backend, BufferCpuAccessible, BufferMut, BufferRef, CommandBufferEncoding, CommandBufferExecutable,
- CommandBufferPending, Context,
+ Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, CpuBuffer,
+ GlobalBufferCpuGpu,
},
data_type::DataTypeRepr,
};
@@ -13,13 +13,13 @@ use crate::{
/// Invokes `$body` once per available backend, with `$B` bound to each backend type.
macro_rules! for_each_backend {
(|$B:ident| $body:expr) => {{
+ #[cfg(backend = "metal")]
{
- type $B = crate::backends::cpu::Cpu;
+ type $B = crate::backends::metal::Metal;
$body
}
- #[cfg(backend = "metal")]
{
- type $B = crate::backends::metal::Metal;
+ type $B = crate::backends::cpu::Cpu;
$body
}
}};
@@ -50,30 +50,33 @@ pub fn buffer_size_bytes<T>(elements_count: usize) -> usize {
pub fn create_buffer<B: Backend, T>(
context: &B::Context,
elements_count: usize,
-) -> B::GlobalBuffer {
- context.create_buffer(buffer_size_bytes::<T>(elements_count)).expect("Failed to create buffer")
+) -> B::GlobalGpuBuffer {
+ context.create_buffer_gpu(buffer_size_bytes::<T>(elements_count)).expect("Failed to create buffer")
}
pub fn create_buffer_with_data<B: Backend, T: DataTypeRepr>(
context: &B::Context,
data: &[T],
-) -> B::GlobalBuffer {
- let mut buffer = context.create_buffer(buffer_size_bytes::<T>(data.len())).expect("Failed to create buffer");
+) -> B::GlobalGpuBuffer {
+ let mut buffer =
+ context.create_buffer_cpu_gpu(buffer_size_bytes::<T>(data.len())).expect("Failed to create buffer");
buffer.copyin(data);
- buffer
+ buffer.handoff()
}
pub fn buffer_to_vec<B: Backend, T: DataTypeRepr>(
- buffer: impl BufferRef<Backend = B, Buffer: BufferCpuAccessible>
+ context: &B::Context,
+ buffer: impl BufferRef<Backend = B, Buffer = B::GlobalGpuBuffer>,
) -> Vec<T> {
- buffer.copyout()
+ block_on(context.copyout(buffer)).expect("Failed to read buffer")
}
pub fn buffer_prefix_to_vec<B: Backend, T: DataTypeRepr>(
- buffer: impl BufferRef<Backend = B, Buffer: BufferCpuAccessible>,
+ context: &B::Context,
+ buffer: impl BufferRef<Backend = B, Buffer = B::GlobalGpuBuffer>,
elements_count: usize,
) -> Vec<T> {
- let mut values = buffer_to_vec::<B, T>(buffer);
+ let mut values = buffer_to_vec::<B, T>(context, buffer);
values.truncate(elements_count);
values
}
@@ -90,7 +93,7 @@ pub fn submit_command_buffer<E: CommandBufferEncoding>(command_buffer: E) {
pub fn buffer_readback<B: Backend>(
context: &B::Context,
buffer: impl BufferRef<Backend = B>,
-) -> B::GlobalBuffer {
+) -> B::GlobalGpuBuffer {
let mut output_buffer = create_buffer::<B, u8>(context, buffer.size());
let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
diff --git a/crates/uzu-engine/unit/common/matmul/bench.rs b/crates/uzu-engine/unit/common/matmul/bench.rs
index 0b410ebd8..9224a72ed 100644
--- a/crates/uzu-engine/unit/common/matmul/bench.rs
+++ b/crates/uzu-engine/unit/common/matmul/bench.rs
@@ -33,6 +33,6 @@ pub fn iter_encode_loop_named<B: Backend, F>(
encode(&mut command_buffer);
}
let completed = block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- completed.gpu_execution_time()
+ completed.gpu_execution_time().unwrap()
});
}
diff --git a/crates/uzu-engine/unit/common/matmul/harness.rs b/crates/uzu-engine/unit/common/matmul/harness.rs
index 398d7dd35..d8c48ee7f 100644
--- a/crates/uzu-engine/unit/common/matmul/harness.rs
+++ b/crates/uzu-engine/unit/common/matmul/harness.rs
@@ -108,7 +108,14 @@ pub fn run<B: Backend, T: DataTypeRepr + Float>(
input: &Input<T>,
encode: impl for<'a> FnOnce(
&mut <B::Kernels as Kernels>::MatmulKernel,
- MatmulArguments<'a, B, &'a B::GlobalBuffer, &'a B::GlobalBuffer, &'a mut B::GlobalBuffer, &'a B::GlobalBuffer>,
+ MatmulArguments<
+ 'a,
+ B,
+ &'a B::GlobalGpuBuffer,
+ &'a B::GlobalGpuBuffer,
+ &'a mut B::GlobalGpuBuffer,
+ &'a B::GlobalGpuBuffer,
+ >,
&mut <B::CommandBuffer as CommandBuffer>::Encoding,
),
) -> Vec<T> {
@@ -120,7 +127,7 @@ pub fn run<B: Backend, T: DataTypeRepr + Float>(
let b_buffer = create_buffer_with_data::<B, T>(context, &input.b);
let a_buffer = create_buffer_with_data::<B, T>(context, &input.a);
let mut d_buffer =
- context.create_buffer(m as usize * n as usize * std::mem::size_of::<T>()).expect("create d buffer");
+ context.create_buffer_gpu(m as usize * n as usize * std::mem::size_of::<T>()).expect("create d buffer");
let rht_buffer = input.rht_factors.as_ref().map(|factors| create_buffer_with_data::<B, i32>(context, factors));
let bias_buffer = input.bias.as_ref().map(|bias| create_buffer_with_data::<B, T>(context, bias));
@@ -153,7 +160,7 @@ pub fn run<B: Backend, T: DataTypeRepr + Float>(
&mut command_buffer,
);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<B, T>(&d_buffer)
+ buffer_to_vec::<B, T>(context, &d_buffer)
}
pub fn cpu_reference<T: DataTypeRepr + Float>(input: &Input<T>) -> Vec<T> {
diff --git a/crates/uzu-engine/unit/common/matmul/quant.rs b/crates/uzu-engine/unit/common/matmul/quant.rs
index 2879b357a..6b921832e 100644
--- a/crates/uzu-engine/unit/common/matmul/quant.rs
+++ b/crates/uzu-engine/unit/common/matmul/quant.rs
@@ -7,8 +7,7 @@ use rand::{RngExt, SeedableRng, rngs::SmallRng};
use crate::{
backends::{
common::{
- Backend, BufferMut, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending,
- Context,
+ Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,
gpu_types::{quantization::QuantizationMode, quantization_method::QuantizationMethod},
kernel::{
ActivationQuantization, ActivationTransform, Kernels,
@@ -258,9 +257,9 @@ impl<T: DataTypeRepr + Float> QuantInput<T> {
block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("CPU activation quantization");
self.prepared_a = Some(PreparedInt8A {
- values: buffer_to_vec(&values),
- scales: buffer_to_vec(&scales),
- group_sums: group_sums.map_or_else(Vec::new, |sums| buffer_to_vec(&sums)),
+ values: buffer_to_vec(&*context, &values),
+ scales: buffer_to_vec(&*context, &scales),
+ group_sums: group_sums.map_or_else(Vec::new, |sums| buffer_to_vec(&*context, &sums)),
quantization,
});
self
@@ -285,15 +284,15 @@ impl<T: DataTypeRepr + Float> QuantInput<T> {
}
pub struct QuantBuffers<B: Backend, T: DataTypeRepr + Float> {
- pub w: B::GlobalBuffer,
- pub scales: B::GlobalBuffer,
- pub zp: Option<B::GlobalBuffer>,
- pub bias: Option<B::GlobalBuffer>,
- pub x: B::GlobalBuffer,
- pub prepared_a: Option<B::GlobalBuffer>,
- pub prepared_a_scales: Option<B::GlobalBuffer>,
- pub prepared_a_group_sums: Option<B::GlobalBuffer>,
- pub y: B::GlobalBuffer,
+ pub w: B::GlobalGpuBuffer,
+ pub scales: B::GlobalGpuBuffer,
+ pub zp: Option<B::GlobalGpuBuffer>,
+ pub bias: Option<B::GlobalGpuBuffer>,
+ pub x: B::GlobalGpuBuffer,
+ pub prepared_a: Option<B::GlobalGpuBuffer>,
+ pub prepared_a_scales: Option<B::GlobalGpuBuffer>,
+ pub prepared_a_group_sums: Option<B::GlobalGpuBuffer>,
+ pub y: B::GlobalGpuBuffer,
pub weights_layout: WeightsLayout<B>,
_t: std::marker::PhantomData<T>,
}
@@ -308,17 +307,24 @@ impl<B: Backend, T: DataTypeRepr + Float> QuantBuffers<B, T> {
let params = QuantParams::new(params_layout, input.n, groups);
let metadata_elements = params.scale_shape().into_iter().product::<u32>() as usize;
let zero_point_bytes = params.zero_point_shape(input.mode).into_iter().product::<u32>() as usize;
- let mut buffers = Self {
+ let mut scales = pad(&input.scales, metadata_elements);
+ let mut zp = input.zero_points.as_ref().map(|values| pad(values, zero_point_bytes));
+ let mut bias = input.biases.as_ref().map(|values| pad(values, metadata_elements));
+ if params_layout == QuantParamsLayout::GroupOutput {
+ let value_bits = size_of::<T>() as u32 * u8::BITS;
+ transpose_metadata(bytemuck::cast_slice_mut(&mut scales), input.n, groups, value_bits);
+ if let Some(bias) = &mut bias {
+ transpose_metadata(bytemuck::cast_slice_mut(bias), input.n, groups, value_bits);
+ }
+ if let Some(zp) = &mut zp {
+ transpose_metadata(zp, input.n, groups, DataType::from(input.mode).size_in_bits() as u32);
+ }
+ }
+ Self {
w: create_buffer_with_data::<B, u32>(context, &input.weights_for_upload()),
- scales: create_buffer_with_data::<B, T>(context, &pad(&input.scales, metadata_elements)),
- zp: input
- .zero_points
- .as_ref()
- .map(|zero_points| create_buffer_with_data::<B, u8>(context, &pad(zero_points, zero_point_bytes))),
- bias: input
- .biases
- .as_ref()
- .map(|biases| create_buffer_with_data::<B, T>(context, &pad(biases, metadata_elements))),
+ scales: create_buffer_with_data::<B, T>(context, &scales),
+ zp: zp.as_ref().map(|values| create_buffer_with_data::<B, u8>(context, values)),
+ bias: bias.as_ref().map(|values| create_buffer_with_data::<B, T>(context, values)),
x: create_buffer_with_data::<B, T>(context, &input.x),
prepared_a: input
.prepared_a
@@ -336,17 +342,13 @@ impl<B: Backend, T: DataTypeRepr + Float> QuantBuffers<B, T> {
y: create_buffer::<B, T>(context, (input.m as usize) * (input.n as usize)),
weights_layout: Default::default(),
_t: std::marker::PhantomData,
- };
- if params_layout == QuantParamsLayout::GroupOutput {
- buffers.transpose_quant_params(input);
}
- buffers
}
pub fn matmul_b<'a>(
&'a self,
input: &QuantInput<T>,
- ) -> MatmulB<&'a B::GlobalBuffer> {
+ ) -> MatmulB<&'a B::GlobalGpuBuffer> {
quant_b_variant(
&self.w,
&self.scales,
@@ -357,36 +359,6 @@ impl<B: Backend, T: DataTypeRepr + Float> QuantBuffers<B, T> {
input,
)
}
-
- fn transpose_quant_params(
- &mut self,
- input: &QuantInput<T>,
- ) {
- let columns = input.n;
- let groups = input.k.div_ceil(input.group_size);
- let value_bits = size_of::<T>() as u32 * u8::BITS;
- transpose_metadata(self.scales.as_slice_mut(), columns, groups, value_bits);
- match input.quant_method {
- QuantizationMethod::ScaleBias => {
- transpose_metadata(
- self.bias.as_mut().expect("bias buffer").as_slice_mut(),
- columns,
- groups,
- value_bits,
- );
- },
- QuantizationMethod::ScaleZeroPoint => {
- let correction_bits = DataType::from(input.mode).size_in_bits() as u32;
- transpose_metadata(
- self.zp.as_mut().expect("zp buffer").as_slice_mut(),
- columns,
- groups,
- correction_bits,
- );
- },
- QuantizationMethod::ScaleSymmetric => {},
- }
- }
}
fn quant_b_variant<TB: BufferRef, T: DataTypeRepr + Float>(
@@ -419,7 +391,14 @@ fn quant_b_variant<TB: BufferRef, T: DataTypeRepr + Float>(
pub fn quant_arguments<'a, B: Backend, T: DataTypeRepr + Float>(
buffers: &'a mut QuantBuffers<B, T>,
input: &QuantInput<T>,
-) -> MatmulArguments<'a, B, &'a B::GlobalBuffer, &'a B::GlobalBuffer, &'a mut B::GlobalBuffer, &'a B::GlobalBuffer> {
+) -> MatmulArguments<
+ 'a,
+ B,
+ &'a B::GlobalGpuBuffer,
+ &'a B::GlobalGpuBuffer,
+ &'a mut B::GlobalGpuBuffer,
+ &'a B::GlobalGpuBuffer,
+> {
let QuantBuffers {
w,
scales,
@@ -475,5 +454,5 @@ pub fn run_quant_cpu<T: DataTypeRepr + Float>(input: &QuantInput<T>) -> Vec<T> {
let mut command_buffer = context.create_command_buffer(None, None).unwrap();
matmul.encode(quant_arguments(&mut buffers, input), &mut command_buffer).expect("encode cpu quant");
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- buffer_to_vec::<Cpu, T>(&buffers.y)
+ buffer_to_vec::<Cpu, T>(&context, &buffers.y)
}
diff --git a/crates/uzu-engine/unit/common/proptest.rs b/crates/uzu-engine/unit/common/proptest.rs
index 2ddc98c5f..7f2fcdbd8 100644
--- a/crates/uzu-engine/unit/common/proptest.rs
+++ b/crates/uzu-engine/unit/common/proptest.rs
@@ -18,41 +18,41 @@ pub fn kernel_data_type() -> impl Strategy<Value = DataType> {
}
pub struct TestContextes {
- pub cpu: Arc<<Cpu as Backend>::Context>,
#[cfg(backend = "metal")]
pub metal: Arc<<Metal as Backend>::Context>,
+ pub cpu: Arc<<Cpu as Backend>::Context>,
}
impl TestContextes {
pub fn new() -> TestContextes {
TestContextes {
- cpu: block_on(<Cpu as Backend>::Context::new()).expect("Failed to create Cpu context"),
#[cfg(backend = "metal")]
metal: block_on(<Metal as Backend>::Context::new()).expect("Failed to create Metal context"),
+ cpu: block_on(<Cpu as Backend>::Context::new()).expect("Failed to create Cpu context"),
}
}
}
pub struct TestResults<T> {
- pub cpu: T,
#[cfg(backend = "metal")]
pub metal: T,
+ pub cpu: T,
}
macro_rules! for_each_context {
($CONTEXTES:ident, |$CONTEXT_NAME:ident: $CONTEXT_TYPE:ident| $body:expr) => {
crate::tests::proptest::TestResults {
- cpu: ({
- type $CONTEXT_TYPE = <crate::backends::cpu::Cpu as crate::backends::common::Backend>::Context;
- let $CONTEXT_NAME = $CONTEXTES.cpu.as_ref();
- $body
- })?,
#[cfg(backend = "metal")]
metal: ({
type $CONTEXT_TYPE = <crate::backends::metal::Metal as crate::backends::common::Backend>::Context;
let $CONTEXT_NAME = $CONTEXTES.metal.as_ref();
$body
})?,
+ cpu: ({
+ type $CONTEXT_TYPE = <crate::backends::cpu::Cpu as crate::backends::common::Backend>::Context;
+ let $CONTEXT_NAME = $CONTEXTES.cpu.as_ref();
+ $body
+ })?,
}
};
}
diff --git a/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs b/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs
index 11bed3867..755e8223d 100644
--- a/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs
+++ b/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs
@@ -76,7 +76,7 @@ fn run_key_value_row_stride_test<B: Backend>() {
norm.encode_key_value(&mut key_value, BATCH_SIZE, &mut command_buffer);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).expect("failed to execute key/value norm");
- let output = buffer_to_vec::<B, f32>(&key_value);
+ let output = buffer_to_vec::<B, f32>(&context, &key_value);
assert_eq_float(&expected, &output, 1e-5, "key/value norm row stride mismatch");
}
diff --git a/crates/uzu-engine/unit/encodable_block/delta_net_tree_verify_bench.rs b/crates/uzu-engine/unit/encodable_block/delta_net_tree_verify_bench.rs
index 485d21534..64f1e239c 100644
--- a/crates/uzu-engine/unit/encodable_block/delta_net_tree_verify_bench.rs
+++ b/crates/uzu-engine/unit/encodable_block/delta_net_tree_verify_bench.rs
@@ -10,7 +10,7 @@ use uzu_engine_macros::uzu_bench;
use crate::{
backends::{
common::{
- Backend, BufferMut, CommandBufferEncoding, Context, Kernels,
+ Backend, CommandBufferEncoding, Context, CpuBuffer, Kernels,
kernel::delta_net_tree_verify::DeltaNetTreeVerify,
},
metal::Metal,
diff --git a/crates/uzu-engine/unit/encodable_block/sampling_test.rs b/crates/uzu-engine/unit/encodable_block/sampling_test.rs
index b555b205b..db5534c79 100644
--- a/crates/uzu-engine/unit/encodable_block/sampling_test.rs
+++ b/crates/uzu-engine/unit/encodable_block/sampling_test.rs
@@ -9,7 +9,7 @@ use uzu_engine_macros::uzu_test;
use crate::{
backends::common::{
- Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,
+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,
gpu_types::trie::TrieNode,
},
data_type::{DataType, DataTypeRepr},
@@ -65,8 +65,8 @@ fn do_sampling_backend<B: Backend, T: DataTypeRepr + Float>(
&logits_buffer,
seeds_buffer.as_ref(),
bitmask_buffer.as_ref(),
- None::<&B::GlobalBuffer>, // TODO
- None::<&B::ConstantBuffer>, // TODO
+ None::<&B::GlobalGpuBuffer>, // TODO
+ None::<&B::ConstantBuffer>, // TODO
&batch_topology,
(0..batch_size).into(),
method,
@@ -78,7 +78,7 @@ fn do_sampling_backend<B: Backend, T: DataTypeRepr + Float>(
drop(bitmask_buffer);
block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
- let sampled = sampled_buffer.copyout::<u32>();
+ let sampled = block_on(context.copyout::<u32>(&sampled_buffer)).unwrap();
Ok(SamplingTestResults(sampled))
}
diff --git a/crates/uzu-engine/unit/session/model_loading_bench.rs b/crates/uzu-engine/unit/session/model_loading_bench.rs
index 16d756f27..7fbca42d2 100644
--- a/crates/uzu-engine/unit/session/model_loading_bench.rs
+++ b/crates/uzu-engine/unit/session/model_loading_bench.rs
@@ -21,7 +21,7 @@ fn bench_model_loading(c: &mut Criterion) {
let model_path = get_test_model_path();
let engine = block_on(Engine::<B>::new()).unwrap();
// TODO: This should flush caches (maybe both cold/hot benchmarks?)
- engine.load_language_model(&model_path).unwrap();
+ block_on(engine.load_language_model(&model_path)).unwrap();
});
});
});
diff --git a/flake.nix b/flake.nix
index 36e7634e7..e7ab0df12 100644
--- a/flake.nix
+++ b/flake.nix
@@ -47,6 +47,50 @@
hash = "sha256-vpSn2ZVUo5tNRgJ89KMBCmPE4JFefP70DfCarVagniU=";
};
+ shader-slang-env = with pkgs; let
+ libenv =
+ {
+ darwin = "DYLD_FALLBACK_LIBRARY_PATH";
+ linux = "LD_LIBRARY_PATH";
+ }.${
+ stdenv.hostPlatform.parsed.kernel.name
+ };
+ in
+ makeSetupHook {
+ name = "shader-slang-env";
+ propagatedBuildInputs = [shader-slang];
+ }
+ (writeText "shader-slang-env.sh" ''
+ export SLANG_INCLUDE_DIR="${lib.getDev shader-slang}/include"
+ export SLANG_LIB_DIR="${lib.getLib shader-slang}/lib"
+ addToSearchPath ${libenv} "${lib.getLib shader-slang}/lib"
+ '');
+
+ bindgen-env = with pkgs;
+ makeSetupHook {name = "bindgen-env";}
+ (writeText "bindgen-env.sh" ''
+ export LIBCLANG_PATH="${lib.getLib libclang}/lib"
+ export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${lib.getDev glibc}/include"
+ '');
+
+ vulkan-env = with pkgs;
+ makeSetupHook {name = "vulkan-env";}
+ (writeText "vulkan-env.sh" ''
+ addToSearchPath LD_LIBRARY_PATH "${lib.getLib vulkan-loader}/lib"
+ export VK_ADD_LAYER_PATH="${vulkan-validation-layers}/share/vulkan/explicit_layer.d"
+ '');
+
+ playwright-env = with pkgs;
+ makeSetupHook {
+ name = "playwright-env";
+ propagatedBuildInputs = [playwright-driver playwright-driver.browsers-chromium];
+ }
+ (writeText "playwright-env.sh" ''
+ export PLAYWRIGHT_BROWSERS_PATH="${playwright-driver.browsers-chromium}"
+ export PLAYWRIGHT_DRIVER_PATH="${playwright-driver}"
+ export PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD="1"
+ '');
+
hostToolchainBuildInputs = with pkgs; (lib.optionals stdenv.hostPlatform.isLinux [alsa-lib]);
nixToolchainBuildInputs = hostToolchainBuildInputs ++ (with pkgs; lib.optionals stdenv.hostPlatform.isDarwin [apple-sdk_26]);
@@ -56,10 +100,13 @@
commonDevshellPackages = with pkgs;
[
nil
+ shader-slang-env
+ playwright-env
uv
maturin
nodejs_26
pnpm_12
+ wasm-bindgen-cli_0_2_129 # Keep in sync with Cargo.toml.
wasmtime_36
evcxr
cargo-deny
@@ -71,6 +118,7 @@
cargo-show-asm
critcmp
]
+ ++ (with pkgs; lib.optionals stdenv.hostPlatform.isLinux [bindgen-env vulkan-env vulkan-tools shaderc spirv-tools lldb])
++ (with pkgs; lib.optionals stdenv.hostPlatform.isDarwin [cargo-swift tuist]);
hostToolchainDevshellPackages = commonDevshellPackages ++ [rustShimHostCC];
nixToolchainDevshellPackages = commonDevshellPackages ++ [rustShimNixCC];