Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
K's min, max and clamp take their bounds plus a zero the GPU compiler can't prove (#82)
shinyobjectz9b9dd9e7809a
diff --git a/systems/k/src/lib.rs b/systems/k/src/lib.rsindex d4c08385..11d006ef 100644--- a/systems/k/src/lib.rs+++ b/systems/k/src/lib.rs@@ -256,6 +256,18 @@ impl Gpu {mod tests {use super::*;+ /// `n` xorshift words from `s`+ fn noise(n: usize, mut s: u64) -> Vec<u32> {+ (0..n)+ .map(|_| {+ s ^= s << 13;+ s ^= s >> 7;+ s ^= s << 17;+ s as u32+ })+ .collect()+ }+/// look_ham.k (every pair of frames' Hamming distance: sum, pop, xor and word over a buffer) on the GPU equals the/// interpreter (skipped without a GPU).#[test]@@ -265,15 +277,7 @@ mod tests {}let gpu = Gpu::new().unwrap();let frames = 37usize;- let mut s = 0x2545_f491_4f6c_dd1du64;- let words: Vec<u32> = (0..frames * 64)- .map(|_| {- s ^= s << 13;- s ^= s >> 7;- s ^= s << 17;- s as u32- })- .collect();+ let words = noise(frames * 64, 0x2545_f491_4f6c_dd1d);let scalars: HashMap<&str, i32> = [("n", frames as i32)].into();let k = raea_core_k::parse(include_str!("../../../core/k/kernels/look_ham.k")).unwrap();let cpu = raea_core_k::Cpu { buffers: [("H", &words[..])].into(), scalars: scalars.clone() };@@ -301,4 +305,37 @@ mod tests {let c = gpu.compile(&k, &["F"], &HashMap::new(), &["w"]).unwrap();assert_eq!(gpu.run(&c, &[&words], 256).unwrap().0.remove(0), want);}++ /// A byte from clamp (or min and max), shifted and or'd into a word, as nv12buf.k packs four luma bytes: the Adreno+ /// X1-85's Vulkan compiler fused the three into a pack that wrote 0xff into the top two bytes of half the words+ /// (#82, found by its reporter: 128,319 of 262,144 wrong) until the bounds took a zero it can't prove (kz); on+ /// random pixels, the GPU equals the interpreter.+ #[test]+ fn a_clamped_byte_packs_as_the_interpreter_packs_it() {+ let luma = |c: &str, at: &str| format!("{c}:word[F;(4*i)+{at}]\ny{c}:clamp[16+shr[(47*and[{c};255])+(157*and[shr[{c};8];255])+(16*and[shr[{c};16];255])+128;8];0;255]\nz{c}:0|255&16+shr[(47*and[{c};255])+(157*and[shr[{c};8];255])+(16*and[shr[{c};16];255])+128;8]\n");+ let src = format!(+ "{}{}{}{}yw:or[or[ya;shl[yb;8]];or[shl[yc;16];shl[yd;24]]]\nzw:or[or[za;shl[zb;8]];or[shl[zc;16];shl[zd;24]]]",+ luma("a", "0"),+ luma("b", "1"),+ luma("c", "2"),+ luma("d", "3")+ );+ let k = raea_core_k::parse(&src).unwrap();+ let wgsl = wgsl_tex(&k, &["F"], &[], &HashMap::new(), &["yw", "zw"]).unwrap();+ assert!(wgsl.contains("(0) + kz, (255) + kz)") && wgsl.contains("let kz: i32 = i32(shape.n >> 31u);"), "{wgsl}");+ if !Gpu::available() {+ return;+ }+ let n = 65_536usize;+ let words = noise(4 * n, 0x9e37_79b9_7f4a_7c15);+ let cpu = raea_core_k::Cpu { buffers: [("F", &words[..])].into(), scalars: HashMap::new() };+ let want = cpu.run(&k, n, &["yw", "zw"]).unwrap();+ let gpu = Gpu::new().unwrap();+ let c = gpu.compile(&k, &["F"], &HashMap::new(), &["yw", "zw"]).unwrap();+ let got = gpu.run(&c, &[&words], n).unwrap().0;+ for (o, (g, w)) in ["yw", "zw"].iter().zip(got.iter().zip(&want)) {+ let wrong = g.iter().zip(w).filter(|(a, b)| a != b).count();+ assert_eq!(wrong, 0, "{o}: {wrong} of {n} words differ from the interpreter");+ }+ }}diff --git a/systems/k/src/wgsl.rs b/systems/k/src/wgsl.rsindex fdb4bb11..4f78e5ec 100644--- a/systems/k/src/wgsl.rs+++ b/systems/k/src/wgsl.rs@@ -40,8 +40,11 @@ impl Gen<'_> {// K's % divides (WGSL's % is the remainder, K's !)'%' => format!("({x} / {y})"),'!' => format!("({x} % {y})"),- '&' => format!("min({x}, {y})"),- '|' => format!("max({x}, {y})"),+ // min, max and clamp take their bounds plus kz, a zero the compiler can't prove (read from the+ // shape uniform): knowing a value is a byte, the Adreno X1-85's Vulkan compiler fused clamp, shl and or+ // into a pack that set the top two bytes of half the NV12 luma words, striping bright video (#82)+ '&' => format!("min({x}, {y} + kz)"),+ '|' => format!("max({x}, {y} + kz)"),'<' | '>' => format!("select(0, 1, {x} {op} {y})"),_ => format!("select(0, 1, {x} == {y})"),}@@ -74,12 +77,11 @@ impl Gen<'_> {"xor" => format!("({} ^ {})", self.e(&a[0])?, self.e(&a[1])?),"or" => format!("({} | {})", self.e(&a[0])?, self.e(&a[1])?),"and" => format!("({} & {})", self.e(&a[0])?, self.e(&a[1])?),- // shifted as u32: a byte shifted into the sign bit (an NV12 word's top byte >= 128) is an- // overflow some drivers' compilers treat as undefined; on a Windows on ARM GPU it striped every- // bright 4 pixels of a video (#82). Same bits as the interpreter's wrapping_shl.+ // shifted as u32: a byte shifted into the sign bit (an NV12 word's top byte >= 128) overflows an i32+ // shift, which WGSL leaves to the compiler. Same bits as the interpreter's wrapping_shl."shl" => format!("bitcast<i32>(u32({}) << (u32({}) & 31u))", self.e(&a[0])?, self.e(&a[1])?),"shr" => format!("({} >> (u32({}) & 31u))", self.e(&a[0])?, self.e(&a[1])?),- "clamp" => format!("clamp({}, {}, {})", self.e(&a[0])?, self.e(&a[1])?, self.e(&a[2])?),+ "clamp" => format!("clamp({}, {} + kz, {} + kz)", self.e(&a[0])?, self.e(&a[1])?, self.e(&a[2])?),"sel" => {let (c, x, y) = (self.e(&a[0])?, self.e(&a[1])?, self.e(&a[2])?);format!("select({y}, {x}, {c} != 0)")@@ -103,7 +105,7 @@ impl Gen<'_> {self.pre.push(format!("var s_{id}: i32 = {init};\n for (var kl_{k}: i32 = 0; kl_{k} < {n}; kl_{k} = kl_{k} + 1) {{ {} s_{id} = {}; }}",inner.join(" "),- if fold.is_empty() { format!("s_{id} + {body}") } else { format!("{fold}(s_{id}, {body})") }+ if fold.is_empty() { format!("s_{id} + {body}") } else { format!("{fold}(s_{id}, {body} + kz)") }));format!("s_{id}")}@@ -175,7 +177,7 @@ pub fn wgsl_tex(k: &Kernel, buffers: &[&str], textures: &[&str], scalars: &HashMs.push_str("struct Shape { n: u32, stride: u32 }\n");s.push_str(&format!("@group(0) @binding({}) var<uniform> shape: Shape;\n", base + outputs.len()));s.push_str("@compute @workgroup_size(256)\nfn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n");- s.push_str(" let ii = gid.x + gid.y * shape.stride;\n if (ii >= shape.n) { return; }\n let k_i: i32 = i32(ii);\n");+ s.push_str(" let ii = gid.x + gid.y * shape.stride;\n if (ii >= shape.n) { return; }\n let k_i: i32 = i32(ii);\n let kz: i32 = i32(shape.n >> 31u);\n");s.push_str(&body);for name in outputs {s.push_str(&format!(" o_{name}[ii] = bitcast<u32>(k_{name});\n"));