diff --git a/ecs/.claude/rules/ecs/component._.ts.md b/ecs/.claude/rules/ecs/component._.ts.md index 6d72b572..a6251463 100644 --- a/ecs/.claude/rules/ecs/component._.ts.md +++ b/ecs/.claude/rules/ecs/component._.ts.md @@ -9,3 +9,10 @@ paths: - A key is a top-level `Symbol()` with no description, its traits declared beside it: `declare module "@adobe/ecs" { interface Components { [title]: { type: string } } }`. - An entity reference is a component of its own, `type: Entity` with `reference: "owner"` or `"weak"`, never a field of a struct. A DOM object is `thread: "main"`. - A derived component, `derived: true`, is defined in its own file by `Component.derive(key, { from, not })`: it's on exactly the entities some derivation of it matches, and nothing else adds or removes it. +- Shape components by how systems use their fields. A component is one array per archetype, each row's fields side by side; separate components are separate arrays. A system loads every byte of each component it reads, and kernels run four rows a vector where each field meets the same operation or a component is one value; fields combined with each other are transposed into lanes first, which costs about 2×. + - One tuple or struct for fields every system treats alike, such as a vector or color moved by `position + velocity * dt`: a tight `Vec2`, `Vec3` or `Vec4` runs at memory speed. + - Separate scalar components for fields systems compare or combine with each other (`hp` against `maxhp`, a status), or that only some systems use: health as three components ran 0.35 ns a row against 0.61 as one struct, and reading one `I32` of a 40-byte struct 0.42 against 0.17 as its own component. + - Separate components for fields written at different times: `changed`, stamps and persistence track whole components, so writing one field marks the rest changed. + - A value of each row that every field of a vector uses, such as a mass or scale, as its own scalar component, which a kernel spreads across the vector's lanes. +- Use the narrowest type that holds the value: `F32` unless the precision is needed, `I32` or `U32` for integers. Kernels compute at storage precision, so `F32` runs four lanes a vector and `number`, an f64, two, moving twice the bytes: integrating a vec3 took 0.27 ns a row in `F32` and 0.52 in `number`. Keep `F32` and `number` fields in separate components; a kernel mixing them computes the `number` ones a row at a time. +- Use a padded layout, `storage` or `vertex`, only for components the GPU reads: a vec3 padded to 16 bytes moves a third more. diff --git a/ecs/.github/instructions/ecs/component._.ts.instructions.md b/ecs/.github/instructions/ecs/component._.ts.instructions.md index a18dea42..88fce59c 100644 --- a/ecs/.github/instructions/ecs/component._.ts.instructions.md +++ b/ecs/.github/instructions/ecs/component._.ts.instructions.md @@ -8,3 +8,10 @@ applyTo: "**/component.*.ts" - A key is a top-level `Symbol()` with no description, its traits declared beside it: `declare module "@adobe/ecs" { interface Components { [title]: { type: string } } }`. - An entity reference is a component of its own, `type: Entity` with `reference: "owner"` or `"weak"`, never a field of a struct. A DOM object is `thread: "main"`. - A derived component, `derived: true`, is defined in its own file by `Component.derive(key, { from, not })`: it's on exactly the entities some derivation of it matches, and nothing else adds or removes it. +- Shape components by how systems use their fields. A component is one array per archetype, each row's fields side by side; separate components are separate arrays. A system loads every byte of each component it reads, and kernels run four rows a vector where each field meets the same operation or a component is one value; fields combined with each other are transposed into lanes first, which costs about 2×. + - One tuple or struct for fields every system treats alike, such as a vector or color moved by `position + velocity * dt`: a tight `Vec2`, `Vec3` or `Vec4` runs at memory speed. + - Separate scalar components for fields systems compare or combine with each other (`hp` against `maxhp`, a status), or that only some systems use: health as three components ran 0.35 ns a row against 0.61 as one struct, and reading one `I32` of a 40-byte struct 0.42 against 0.17 as its own component. + - Separate components for fields written at different times: `changed`, stamps and persistence track whole components, so writing one field marks the rest changed. + - A value of each row that every field of a vector uses, such as a mass or scale, as its own scalar component, which a kernel spreads across the vector's lanes. +- Use the narrowest type that holds the value: `F32` unless the precision is needed, `I32` or `U32` for integers. Kernels compute at storage precision, so `F32` runs four lanes a vector and `number`, an f64, two, moving twice the bytes: integrating a vec3 took 0.27 ns a row in `F32` and 0.52 in `number`. Keep `F32` and `number` fields in separate components; a kernel mixing them computes the `number` ones a row at a time. +- Use a padded layout, `storage` or `vertex`, only for components the GPU reads: a vec3 padded to 16 bytes moves a third more. diff --git a/ecs/packages/ecs-architecture/package.json b/ecs/packages/ecs-architecture/package.json index 827ecc12..97f9bb43 100644 --- a/ecs/packages/ecs-architecture/package.json +++ b/ecs/packages/ecs-architecture/package.json @@ -1,6 +1,6 @@ { "name": "@adobe/ecs-architecture", - "version": "0.6.0", + "version": "0.6.1", "description": "The architecture standard for @adobe/ecs applications: its checker and the agent rules for it", "license": "MIT", "type": "module", diff --git a/ecs/packages/ecs-architecture/standard.md b/ecs/packages/ecs-architecture/standard.md index 3b85db8d..44c3b35b 100644 --- a/ecs/packages/ecs-architecture/standard.md +++ b/ecs/packages/ecs-architecture/standard.md @@ -196,6 +196,9 @@ feature, and of its sub-features, import them, and they add no systems to an app aim is to stay semantically immutable and gain its speed underneath, as compiled systems do, assigning new tuples in source and allocating none. - **Hot paths allocate nothing per frame,** and have a benchmark. +- **Model components for the systems that use them,** as `@adobe/ecs`'s component rules say: a tuple for fields every + system treats alike, scalar components for fields combined with each other or used apart, `F32` unless the precision + is needed. - **Prefer WebGPU for drawing,** through `@adobe/ecs-gpu` and render systems, to WebGL and other older APIs: a render system draws from the GPU copy of the components it names, which the world uploads straight from storage as rows change, with no copy of its own. diff --git a/ecs/packages/ecs/design.md b/ecs/packages/ecs/design.md index 2d57ee6f..e83c3074 100644 --- a/ecs/packages/ecs/design.md +++ b/ecs/packages/ecs/design.md @@ -266,7 +266,9 @@ Rule: anything that doesn't affect the API or correctness belongs in phase 2+. 1. **Kernel subset.** Kernels compile to efficient JS or WASM. Main-thread systems run as normal JS with every feature available. - **Parser:** the bundler's own (`this.parse`, ESTree, in both Vite and Rolldown); the compiler validates the subset on that tree, and an ESLint rule can share the validator since ESLint also produces ESTree. A second JS parser would only add size and upkeep. - **Closed world:** every input comes from the ECS (query rows, resources). - - **Precision:** a CPU kernel compiled without `kernel: true` computes as its body as written does, in f64, rounding only where it stores, in JS and WASM alike, so compiling it never changes a result: every value bit for bit, and NaN wherever the body gives NaN, its sign and payload the platform's (x86's differ from ARM's, in JavaScript as in WASM). A kernel the declaration asks for may compute at storage precision, as WASM's f32 SIMD lanes do, rounding each step: about 4.4 times faster for `move` and `chain` than one row at a time in f64, and not bit-exact with the body as written. At storage precision, arithmetic on fields declared `I32` or `U32`, and on locals only ever given such results, wraps at 32 bits as the integers they're stored as do (sums, differences, products, remainders by a literal, `I32` negations); a value JS operators make 32-bit, as `>>> 0` does, computes as written, and a `U8` promotes, as a C integer does. Its JS kernel computes as written. In every kernel an integer field declared with a `minimum` and `maximum` (`Schema.Type<{ type: "integer"; minimum: 0; maximum: 1000 }>`) bounds what the compiler proves of its arithmetic, so sums it can't overflow stay in i32; a value outside its declared range is unspecified. GPU kernels compute in f32. + - **Precision:** every CPU kernel's WASM computes at storage precision, whether or not the declaration asks for a kernel: kernels exist to run many rows fast, and SIMD lanes of the type the values are stored in are the fastest way to. Arithmetic on values of `F32` fields, on constants and the same for every row (resources, the input, shared values, literals), which convert to f32, and on its own results rounds each step to f32, as f32 lanes do, and a comparison of a row's such values compares f32s; in lanes and a row at a time alike, a row at a time in f32 instructions on f32 loads and stores, each such value the same for every row converted once a call, so every row computes the same whether or not it falls in a whole group of lanes (`wasm-kernels.test.ts`: a 120-frame simulation is bit-identical with SIMD and without). When every float field a kernel touches is an `f64` (`number`), lanes are f64x2, loaded and stored as they're stored, and compute as the body does. `integrate`, the guide's `Vec3.add(p, Vec3.scale(v, mass * delta))` with no `kernel` flag, runs 0.95 → 0.27 ns a row on an M4 Max, within 1.22× of its memory bound, and `integrate f64` 0.79 → 0.52. At storage precision, arithmetic on fields declared `I32` or `U32`, and on locals only ever given such results, wraps at 32 bits as the integers they're stored as do (sums, differences, products, remainders by a literal, `I32` negations); a value JS operators make 32-bit, as `>>> 0` does, computes as written, and a `U8` promotes, as a C integer does. Its JS kernel computes as written. In every kernel an integer field declared with a `minimum` and `maximum` (`Schema.Type<{ type: "integer"; minimum: 0; maximum: 1000 }>`) bounds what the compiler proves of its arithmetic, so sums it can't overflow stay in i32; a value outside its declared range is unspecified. NaN's sign and payload are the platform's (x86's differ from ARM's, in JavaScript as in WASM). GPU kernels compute in f32. + - **Lanes across rows:** before choosing a SIMD loop, the generator writes each local assigned once into its one read when nothing between changes what it reads, and each constant into every read (`forward-locals.ts`), so the temporaries of inlined calls leave each store its whole value. Stores to a component's leaves whose values match lane for lane then run four rows' elements as `4 × stride / 16` whole vectors (`elementsLoop`): leaves of other components of the same stride load lane for lane; values the same for every row splat; a value of each row, such as a scalar component, or a local assigned one, computes four rows at a time and is shuffled across each element's leaves (`spread`); and lanes no store writes, a leaf the body leaves or a padded vec3's padding, are stored back as loaded (`bitselect`). + - **Filtered rows in lanes:** with change filters, rows run across rows too, inside each run of passing blocks. At each eight rows aligned to eight, four f64x2 comparisons of each filter's row ticks against `lastRun` give the rows that pass; eight none of which pass are skipped whole, and the rest run as groups of a vector's rows (dense columns) or four rows' elements, branch-free, under those rows' mask: stores blend with what's there, a row's mask spread across its element's leaves as per-row values are, and row ticks stamp per lane. A group lies in one block, so a block and its chunk are stamped once its groups are done, where one stamped a row: the same ticks a row at a time gives (`wasm.test.ts`, filtered rows, bit for bit with SIMD and without over scattered, dense, alternating and clustered changes). Rows before the first aligned eight and after the last run one at a time. A branch on each row's tick mispredicts on scattered changes, about 3.7 ns a row at a random half; the masks take 0.42 for a vec3, 0.53 for a vec4 and 0.22 for an f32, whatever changed. - **Imported functions:** kernels call pure functions and use constants from any module the build resolves to a file, the kernel's own module included: user TypeScript or JavaScript, other packages' ESM, and the package's math types. The plugin reads each module a kernel reaches, with types stripped, follows its imports and re-exports, and inlines each call compiled in its own module's scope, so tuples are scalarized and never allocate, on JS, WASM and the GPU alike. A function outside the subset fails the build at the kernel's call, with a frame naming the file and line of each inlined function down to the failure. Recursion fails, also across modules. A module's constants must be known at build time: a `let`, or a mutation at runtime, isn't seen. Editing an inlined file compiles its kernels again, in dev too. - **Math types:** the package exports math types that are also namespaces of functions: `Vec2`, `Vec3`, `Vec4` (each `F32`, with `I32` and `U32` nested beside it), `Quat`, `Mat4x4`, and the scalars `F32`, `I32`, `U32`, each with a `schema`. They follow WGSL's semantics, and where WGSL leaves a result indeterminate they do what is fastest: integer vectors wrap, `round` rounds halfway values to even, `mod` is `x - m * floor(x / m)`, and `normalize` of a zero vector is NaN. Integer functions are defined for integers in range, and `pow` for a positive base; other inputs give indeterminate results, which may differ between the CPU and the GPU. The few that throw (`Mat4x4.inverse`, `Mat4x4.perspective`, `Mat4x4.lookAt`) can't be used in kernels. - **WGSL builtins:** a math function whose WGSL builtin matches it declares that explicitly, in its own file (`intrinsic({ wgsl: "normalize", parameters: ["vec3f"], result: "vec3f" }, implementation)`). In a GPU kernel a call to it becomes an intrinsic region holding its operands and its inlined body: WGSL emits the builtin on vector and matrix types, nesting calls as builtins do, and JS and WASM run the body, so CPU output is unchanged. Locals keep their JS names in WGSL, and a region's result is named after its function. diff --git a/ecs/packages/ecs/followups.md b/ecs/packages/ecs/followups.md index 7b41ce5a..c01d3a43 100644 --- a/ecs/packages/ecs/followups.md +++ b/ecs/packages/ecs/followups.md @@ -103,6 +103,12 @@ correctness, then optimization. Remove an item once it's decided or done. ## Optimization +- **The interleaved loop's cost gate** (`work.spent > 0.7 × 4 × statements` in `interleavedGroups`) was tuned before + lanes across whole elements existed; measure it against one row at a time over 1M rows for bodies that mix leaves, + such as `Vec3.cross`, and loosen it where lanes still win. +- **The JS kernel computes as written,** not at storage precision, so where WASM can't run a kernel's last bits differ + from WASM's. Rounding each f32 step there with `Math.fround` would make them agree, at its cost in the fallback. + - **Owner references in bulk spawns:** `spawn tables 1M owner` takes 53 ms against 10 ms for `spawn tables 1M`, and `spawn owned 1M` 64 ms. What's left is per row: `commands.spawnTables` places every entity of the tables and finds each row's owner among them (about 25 ms at 1M), and the sync point links each holder to its target (about 20 ms), diff --git a/ecs/packages/ecs/package.json b/ecs/packages/ecs/package.json index 572d552d..1bca610c 100644 --- a/ecs/packages/ecs/package.json +++ b/ecs/packages/ecs/package.json @@ -1,6 +1,6 @@ { "name": "@adobe/ecs", - "version": "0.6.0", + "version": "0.7.0", "description": "Adobe ECS", "license": "MIT", "type": "module", diff --git a/ecs/packages/ecs/rules/component.x.ts.md b/ecs/packages/ecs/rules/component.x.ts.md index 40294e60..2669e895 100644 --- a/ecs/packages/ecs/rules/component.x.ts.md +++ b/ecs/packages/ecs/rules/component.x.ts.md @@ -4,3 +4,10 @@ glob: "**/component.*.ts" - A key is a top-level `Symbol()` with no description, its traits declared beside it: `declare module "@adobe/ecs" { interface Components { [title]: { type: string } } }`. - An entity reference is a component of its own, `type: Entity` with `reference: "owner"` or `"weak"`, never a field of a struct. A DOM object is `thread: "main"`. - A derived component, `derived: true`, is defined in its own file by `Component.derive(key, { from, not })`: it's on exactly the entities some derivation of it matches, and nothing else adds or removes it. +- Shape components by how systems use their fields. A component is one array per archetype, each row's fields side by side; separate components are separate arrays. A system loads every byte of each component it reads, and kernels run four rows a vector where each field meets the same operation or a component is one value; fields combined with each other are transposed into lanes first, which costs about 2×. + - One tuple or struct for fields every system treats alike, such as a vector or color moved by `position + velocity * dt`: a tight `Vec2`, `Vec3` or `Vec4` runs at memory speed. + - Separate scalar components for fields systems compare or combine with each other (`hp` against `maxhp`, a status), or that only some systems use: health as three components ran 0.35 ns a row against 0.61 as one struct, and reading one `I32` of a 40-byte struct 0.42 against 0.17 as its own component. + - Separate components for fields written at different times: `changed`, stamps and persistence track whole components, so writing one field marks the rest changed. + - A value of each row that every field of a vector uses, such as a mass or scale, as its own scalar component, which a kernel spreads across the vector's lanes. +- Use the narrowest type that holds the value: `F32` unless the precision is needed, `I32` or `U32` for integers. Kernels compute at storage precision, so `F32` runs four lanes a vector and `number`, an f64, two, moving twice the bytes: integrating a vec3 took 0.27 ns a row in `F32` and 0.52 in `number`. Keep `F32` and `number` fields in separate components; a kernel mixing them computes the `number` ones a row at a time. +- Use a padded layout, `storage` or `vertex`, only for components the GPU reads: a vec3 padded to 16 bytes moves a third more. diff --git a/ecs/packages/ecs/src/guide/14-kernels.md b/ecs/packages/ecs/src/guide/14-kernels.md index 46774855..c9669b1b 100644 --- a/ecs/packages/ecs/src/guide/14-kernels.md +++ b/ecs/packages/ecs/src/guide/14-kernels.md @@ -1,13 +1,14 @@ # Kernels A *kernel* is a body the build compiles to run once per row, each row on its own, so the world can split the rows -across workers and run them as WASM, with results the same as the body as written. +across workers and run them as WASM. As WASM it computes at the precision its values are stored in: arithmetic on `F32` +values rounds each step to 32 bits, as SIMD lanes do, and on `I32` and `U32` values wraps at 32 bits, so a result can +differ in its last bits from the body as written. `number` values compute in 64 bits. The build makes a kernel of any row system whose body reads and writes only data, calls math, and touches no module state, without being asked: [`move`](14-kernels.ts#L21-L23) is one. Two flags change that: -- `kernel: true` asserts it. The build fails, saying why, if [the body](14-kernels.ts#L25-L27) can't be one. It also - computes `F32` values at 32 bits, which is faster on dense rows. +- `kernel: true` asserts it. The build fails, saying why, if [the body](14-kernels.ts#L25-L27) can't be one. - `kernel: false` runs [the body as written](14-kernels.ts#L29-L31), on its thread: to step through it in a debugger, say. diff --git a/ecs/packages/ecs/src/implementation/compiler/compile-kernel.ts b/ecs/packages/ecs/src/implementation/compiler/compile-kernel.ts index 16f0b3f5..0d4f0b18 100644 --- a/ecs/packages/ecs/src/implementation/compiler/compile-kernel.ts +++ b/ecs/packages/ecs/src/implementation/compiler/compile-kernel.ts @@ -64,7 +64,6 @@ export type KernelExplanation = { readonly columns: readonly string[]; readonly upColumns: readonly string[]; readonly signature: Signature; - readonly storagePrecision: boolean; /** Each accumulator's operator, in its description's `reductions` order. */ readonly operators: readonly Reduction[]; }; @@ -183,7 +182,6 @@ export const compileKernel = (declaration: ObjectExpression, body: Node, module: columns: [...unit.columnIndex.keys()], upColumns: [...unit.upColumnIndex.keys()], signature: unit.signature, - storagePrecision: !unit.tried, operators: unit.accumulators.map(entry => unit.signature.reduced[entry.reduced]?.operator ?? fail(declaration, "unknown reduction")), }); return { @@ -206,7 +204,6 @@ export const compileKernel = (declaration: ObjectExpression, body: Node, module: `url: ${url},`, `program: ${serialize(program)},`, `reducedShapes: [${[...unit.reducedShapes].join(", ")}],`, - ...unit.tried ? [] : ["storagePrecision: true,"], `reductions: [${unit.accumulators.map(entry => { const { resource, operator } = reduced[entry.reduced] ?? fail(declaration, "unknown reduction"); return `{ resource: ${resource}, operator: ${JSON.stringify(operator)}, path: ${JSON.stringify(entry.path)} }`; diff --git a/ecs/packages/ecs/src/implementation/compiler/describe.test.ts b/ecs/packages/ecs/src/implementation/compiler/describe.test.ts index d37135f7..c5b52046 100644 --- a/ecs/packages/ecs/src/implementation/compiler/describe.test.ts +++ b/ecs/packages/ecs/src/implementation/compiler/describe.test.ts @@ -82,21 +82,20 @@ describe("a module's systems described", () => { expect([...systems.keys()]).toEqual(["automatic", "asserted", "shaded", "spawn", "observe", "named", "optional", "unflagged", "draw", "filtered", "looked", "summed", "inputs", "hypotenuse", null]); }); - it("gives an automatic kernel's JS, its WASM at the body's precision, and the shader it would be as a GPU kernel", () => { + it("gives an automatic kernel's JS, its WASM in f32 lanes at storage precision, and the shader it would be as a GPU kernel", () => { const system = described("automatic"); expect(system).toMatchObject({ kind: "row", kernel: null, js: { kind: "compiled" }, wasm: { kind: "compiled" }, wgsl: { kind: "eligible", reason: expect.stringContaining("With `kernel: \"gpu\"`") } }); expect(codeOf(system.js)).toContain("export const create = (booleans"); expect(codeOf(system.js)).toContain("\n\t\trows: for ("); expect(codeOf(system.wasm)).toContain("(func $run (type 0) (param $start i32) (param $end i32) (param $tick f64) (param $lastRun f64) (param $c0 i32)"); - expect(codeOf(system.wasm)).toContain("(local $x1_7 f64)"); - expect(codeOf(system.wasm)).toContain("f64.promote_f32"); + expect(codeOf(system.wasm)).toContain("f32x4.mul"); expect(codeOf(system.wgsl)).toContain("@compute @workgroup_size(64)"); - expect(system.runs).toMatch(/^WASM on the kernel pool's workers, (a row at a time|two f64 lanes at a time, bit-exact with the body as written); the JS kernel/); + expect(system.runs).toMatch(/^WASM on the kernel pool's workers, four f32 lanes at a time; the JS kernel/); }); it("gives a kernel: true kernel's WASM in f32 lanes at storage precision", () => { const system = described("asserted"); - expect(system).toMatchObject({ kernel: true, wasm: { kind: "compiled" }, runs: expect.stringContaining("four f32 lanes at a time, rounding each step to storage precision") }); + expect(system).toMatchObject({ kernel: true, wasm: { kind: "compiled" }, runs: expect.stringContaining("four f32 lanes at a time") }); expect(codeOf(system.wasm)).toContain("f32x4.add"); }); diff --git a/ecs/packages/ecs/src/implementation/compiler/describe.ts b/ecs/packages/ecs/src/implementation/compiler/describe.ts index 13522b57..74c38317 100644 --- a/ecs/packages/ecs/src/implementation/compiler/describe.ts +++ b/ecs/packages/ecs/src/implementation/compiler/describe.ts @@ -351,11 +351,13 @@ export const describeSystems = async (sites: TransformedSites, format: (code: st // An `up` kernel's runner passes only the rows that pass its filters. const filters = signature.up !== null ? 0 : listLength(declaration, ["components", "added"], count) + listLength(declaration, ["components", "changed"], count); const generated = generateWasmOrReason(explanation.program, placed.columns, placed.scalarType, true, filters, placed.lookups, placed.upColumns, - explanation.operators, [], [], explanation.storagePrecision, arraysOf(explanation), true); + explanation.operators, [], [], true, arraysOf(explanation), true); if (typeof generated === "string") return { backend: { kind: "none", reason: generated }, lanes: null }; const printed = printWat(generated.bytes); if ("failure" in printed) return { backend: { kind: "none", reason: `its WASM can't be printed: ${printed.failure}` }, lanes: null }; - const lanes = !generated.vectorized ? "a row at a time" : explanation.storagePrecision ? "four f32 lanes at a time, rounding each step to storage precision" : "two f64 lanes at a time, bit-exact with the body as written"; + const lanes = generated.lanes === null ? "a row at a time" + : generated.lanes === "interleaved" ? "four rows at a time, interleaved into a vector a field" + : generated.lanes === "f32" ? "four f32 lanes at a time" : "two f64 lanes at a time"; return { backend: { kind: "compiled", code: printed.wat }, lanes }; }; diff --git a/ecs/packages/ecs/src/implementation/compiler/wat.test.ts b/ecs/packages/ecs/src/implementation/compiler/wat.test.ts index b4b9289e..36264b73 100644 --- a/ecs/packages/ecs/src/implementation/compiler/wat.test.ts +++ b/ecs/packages/ecs/src/implementation/compiler/wat.test.ts @@ -82,6 +82,7 @@ const simdInstruction = (subopcode: number): number[] => { if (subopcode === 91) return [0xfd, subopcode, 3, 8, 1]; if (subopcode === 13) return [0xfd, subopcode, ...[0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23]]; if (subopcode === 27 || subopcode === 28 || subopcode === 31 || subopcode === 32) return [0xfd, subopcode, 3]; + if (subopcode === 34) return [0xfd, subopcode, 1]; return [0xfd, ...unsigned(subopcode)]; }; diff --git a/ecs/packages/ecs/src/implementation/compiler/wat.ts b/ecs/packages/ecs/src/implementation/compiler/wat.ts index f2d50a1d..b2b1ab7a 100644 --- a/ecs/packages/ecs/src/implementation/compiler/wat.ts +++ b/ecs/packages/ecs/src/implementation/compiler/wat.ts @@ -44,7 +44,7 @@ const simd: { readonly [subopcode: number]: { readonly name: string; readonly al 0: { name: "v128.load", align: 4 }, 11: { name: "v128.store", align: 4 }, 12: { name: "v128.const" }, 13: { name: "i8x16.shuffle", lanes: 16 }, 15: { name: "i8x16.splat" }, 16: { name: "i16x8.splat" }, 17: { name: "i32x4.splat" }, 18: { name: "i64x2.splat" }, 19: { name: "f32x4.splat" }, 20: { name: "f64x2.splat" }, 27: { name: "i32x4.extract_lane", lanes: 1 }, 28: { name: "i32x4.replace_lane", lanes: 1 }, - 31: { name: "f32x4.extract_lane", lanes: 1 }, 32: { name: "f32x4.replace_lane", lanes: 1 }, + 31: { name: "f32x4.extract_lane", lanes: 1 }, 32: { name: "f32x4.replace_lane", lanes: 1 }, 34: { name: "f64x2.replace_lane", lanes: 1 }, 55: { name: "i32x4.eq" }, 56: { name: "i32x4.ne" }, 57: { name: "i32x4.lt_s" }, 58: { name: "i32x4.lt_u" }, 59: { name: "i32x4.gt_s" }, 60: { name: "i32x4.gt_u" }, 61: { name: "i32x4.le_s" }, 62: { name: "i32x4.le_u" }, 63: { name: "i32x4.ge_s" }, 64: { name: "i32x4.ge_u" }, 65: { name: "f32x4.eq" }, 66: { name: "f32x4.ne" }, 67: { name: "f32x4.lt" }, 68: { name: "f32x4.gt" }, 69: { name: "f32x4.le" }, 70: { name: "f32x4.ge" }, diff --git a/ecs/packages/ecs/src/implementation/world/builtins.test.ts b/ecs/packages/ecs/src/implementation/world/builtins.test.ts index fe2f0166..0238e3a7 100644 --- a/ecs/packages/ecs/src/implementation/world/builtins.test.ts +++ b/ecs/packages/ecs/src/implementation/world/builtins.test.ts @@ -67,8 +67,9 @@ describe("math in kernels", () => { await world.run(transform); const read = await readEach(world, await select(world, { required: [position] }), position); const want = Array.from({ length: 64 }, (_, i) => expected([i, i % 5, -i], [1, 0.5 * (i % 3), 0.25])); - // Stored as f32, so compared at f32 precision. - expect(read.map(value => value?.map(Math.fround))).toEqual(want.map(value => value.map(Math.fround))); + // Stored as f32, so compared at f32 precision; WASM's f32 lanes also round each step. + if (!wasm) expect(read.map(value => value?.map(Math.fround))).toEqual(want.map(value => value.map(Math.fround))); + else read.forEach((value, i) => value?.forEach((leaf, k) => expect(Math.abs(leaf - (want[i]?.[k] ?? NaN))).toBeLessThanOrEqual(1e-6 * Math.max(1, Math.abs(want[i]?.[k] ?? 0))))); await world.dispose(); }); } diff --git a/ecs/packages/ecs/src/implementation/world/forward-locals.test.ts b/ecs/packages/ecs/src/implementation/world/forward-locals.test.ts new file mode 100644 index 00000000..59169801 --- /dev/null +++ b/ecs/packages/ecs/src/implementation/world/forward-locals.test.ts @@ -0,0 +1,57 @@ +// © 2026 Adobe. MIT License. See /LICENSE for details. +import { describe, expect, it } from "vitest"; +import { forwardLocals } from "./forward-locals.js"; +import type { Program } from "./kernel.js"; + +type Expression = Program.Expression; +type Statement = Program.Statement; + +const column = (index: number): Expression => ({ kind: "column", column: index }); +const local = (index: number): Expression => ({ kind: "local", local: index }); +const number = (value: number): Expression => ({ kind: "number", value }); +const resource: Expression = { kind: "resource", index: 0, path: [] }; +const times = (left: Expression, right: Expression): Expression => ({ kind: "binary", operator: "*", left, right }); +const plus = (left: Expression, right: Expression): Expression => ({ kind: "binary", operator: "+", left, right }); +const set = (index: number, value: Expression): Statement => ({ kind: "set", local: index, value }); +const store = (index: number, value: Expression): Statement => ({ kind: "store", column: index, value }); +/** Columns 0 to 2 are one component's leaves, 3 to 5 another's; 6 holds the same bytes as 0. */ +const aliases = (a: number, b: number): boolean => a === b || (Math.min(a, b) === 0 && Math.max(a, b) === 6); +const forward = (body: readonly Statement[], reductions?: readonly number[]): readonly Statement[] => + forwardLocals({ locals: 8, body, ...reductions === undefined ? {} : { reductions } }, aliases).body; + +describe("forwardLocals", () => { + it("writes each temporary of an inlined call into the store reading it, so stores hold whole values", () => { + // p = add(p, scale(v, d)), leaf by leaf, through snapshots and the scaled temporaries. + const body = [ + set(0, column(3)), set(1, column(4)), set(2, resource), + set(3, times(local(0), local(2))), set(4, times(local(1), local(2))), + store(0, plus(column(0), local(3))), store(1, plus(column(1), local(4))), + ]; + expect(forward(body)).toEqual([ + store(0, plus(column(0), times(column(3), resource))), + store(1, plus(column(1), times(column(4), resource))), + ]); + }); + + it("keeps a value whose column a store between changes, and one read twice", () => { + expect(forward([set(0, column(0)), store(6, number(1)), store(1, local(0))])).toEqual([set(0, column(0)), store(6, number(1)), store(1, local(0))]); + expect(forward([set(0, column(0)), store(1, number(1)), store(2, local(0))])).toEqual([store(1, number(1)), store(2, column(0))]); + expect(forward([set(0, times(column(0), column(1))), store(2, plus(local(0), local(0)))])).toEqual([set(0, times(column(0), column(1))), store(2, plus(local(0), local(0)))]); + }); + + it("writes a constant into every read, in nested statements too, and keeps accumulators' assignments", () => { + const branch: Statement = { kind: "if", test: { kind: "binary", operator: ">", left: column(0), right: local(0) }, consequent: [store(1, local(0))], alternate: [] }; + expect(forward([set(0, resource), branch, store(2, local(0))])).toEqual([ + { kind: "if", test: { kind: "binary", operator: ">", left: column(0), right: resource }, consequent: [store(1, resource)], alternate: [] }, + store(2, resource), + ]); + expect(forward([set(0, number(0)), store(1, local(0))], [0])).toEqual([set(0, number(0)), store(1, local(0))]); + }); + + it("doesn't move a value into a statement nested in a later one, nor past what it can't see through", () => { + const nested: Statement = { kind: "if", test: column(1), consequent: [store(2, local(0))], alternate: [] }; + expect(forward([set(0, column(0)), nested])).toEqual([set(0, column(0)), nested]); + const lookup: Statement = { kind: "find", handle: 0, lookup: 0, entity: column(5) }; + expect(forward([set(0, column(0)), lookup, store(2, local(0))])).toEqual([set(0, column(0)), lookup, store(2, local(0))]); + }); +}); diff --git a/ecs/packages/ecs/src/implementation/world/forward-locals.ts b/ecs/packages/ecs/src/implementation/world/forward-locals.ts new file mode 100644 index 00000000..e6492ca2 --- /dev/null +++ b/ecs/packages/ecs/src/implementation/world/forward-locals.ts @@ -0,0 +1,172 @@ +// © 2026 Adobe. MIT License. See /LICENSE for details. +import type { Program } from './kernel.js'; + +type Expression = Program.Expression; +type Statement = Program.Statement; + +/** Whether a value is the same wherever it's read in a run: a literal, or a leaf of a resource, the input or a shared value. */ +const constant = (expression: Expression): boolean => + expression.kind === "number" || expression.kind === "boolean" || expression.kind === "resource" || expression.kind === "args" || expression.kind === "shared"; + +/** Whether a value only reads locals, row columns and constants, adding them to `locals` and `columns`. */ +const readsOnly = (expression: Expression, locals: Set, columns: Set): boolean => { + switch (expression.kind) { + case "number": case "boolean": case "resource": case "args": case "shared": return true; + case "local": locals.add(expression.local); return true; + case "column": columns.add(expression.column); return true; + case "unary": return readsOnly(expression.operand, locals, columns); + case "binary": case "logical": return readsOnly(expression.left, locals, columns) && readsOnly(expression.right, locals, columns); + case "conditional": return readsOnly(expression.test, locals, columns) && readsOnly(expression.consequent, locals, columns) && readsOnly(expression.alternate, locals, columns); + case "math": return expression.arguments.every(argument => readsOnly(argument, locals, columns)); + default: return false; + } +}; + +/** An expression with each read of `local` replaced by `value`, and how many it replaced, in `count`. */ +const replaceIn = (expression: Expression, local: number, value: Expression, count: { n: number }): Expression => { + const replace = (inner: Expression): Expression => replaceIn(inner, local, value, count); + switch (expression.kind) { + case "local": + if (expression.local !== local) return expression; + count.n++; + return value; + case "unary": return { ...expression, operand: replace(expression.operand) }; + case "binary": case "logical": return { ...expression, left: replace(expression.left), right: replace(expression.right) }; + case "conditional": return { ...expression, test: replace(expression.test), consequent: replace(expression.consequent), alternate: replace(expression.alternate) }; + case "math": return { ...expression, arguments: expression.arguments.map(replace) }; + case "lane": return { ...expression, value: replace(expression.value) }; + case "resourceElement": return { ...expression, element: replace(expression.element) }; + default: return expression; + } +}; + +/** Statements with each read of `local` replaced by `value`, nested ones too. */ +const replaceInStatements = (statements: readonly Statement[], local: number, value: Expression, count: { n: number }): Statement[] => statements.map(statement => { + const expression = (inner: Expression): Expression => replaceIn(inner, local, value, count); + const nested = (inner: readonly Statement[]): Statement[] => replaceInStatements(inner, local, value, count); + switch (statement.kind) { + case "set": case "store": return { ...statement, value: expression(statement.value) }; + case "resourceStore": return { ...statement, element: expression(statement.element), value: expression(statement.value) }; + case "if": return { ...statement, test: expression(statement.test), consequent: nested(statement.consequent), alternate: nested(statement.alternate) }; + case "block": case "loop": return { ...statement, body: nested(statement.body) }; + case "branchIf": return { ...statement, test: expression(statement.test) }; + case "find": return { ...statement, entity: expression(statement.entity) }; + case "probe": return { ...statement, values: statement.values.map(expression) }; + case "listRow": return { ...statement, index: expression(statement.index) }; + case "intrinsic": return { ...statement, operands: statement.operands.map(lanes => lanes.map(expression)), body: nested(statement.body) }; + default: return statement; + } +}); + +/** A statement's own expressions with each read of `local` replaced, not those of statements nested in it. */ +const replaceInOwn = (statement: Statement, local: number, value: Expression, count: { n: number }): Statement | null => { + const expression = (inner: Expression): Expression => replaceIn(inner, local, value, count); + switch (statement.kind) { + case "set": case "store": return { ...statement, value: expression(statement.value) }; + case "if": return { ...statement, test: expression(statement.test) }; + default: return null; + } +}; + +const countUses = (statements: readonly Statement[], sets: Map, reads: Map): void => { + for (const statement of statements) { + if (statement.kind === "set") sets.set(statement.local, (sets.get(statement.local) ?? 0) + 1); + const visit = (expression: Expression): void => { + switch (expression.kind) { + case "local": reads.set(expression.local, (reads.get(expression.local) ?? 0) + 1); return; + case "unary": return visit(expression.operand); + case "binary": case "logical": visit(expression.left); return visit(expression.right); + case "conditional": visit(expression.test); visit(expression.consequent); return visit(expression.alternate); + case "math": return expression.arguments.forEach(visit); + case "lane": return visit(expression.value); + case "resourceElement": return visit(expression.element); + default: return; + } + }; + switch (statement.kind) { + case "set": case "store": visit(statement.value); break; + case "resourceStore": visit(statement.element); visit(statement.value); break; + case "if": visit(statement.test); countUses(statement.consequent, sets, reads); countUses(statement.alternate, sets, reads); break; + case "block": case "loop": countUses(statement.body, sets, reads); break; + case "branchIf": visit(statement.test); break; + case "find": visit(statement.entity); break; + case "probe": statement.values.forEach(visit); break; + case "listRow": visit(statement.index); break; + case "intrinsic": statement.operands.forEach(lanes => lanes.forEach(visit)); countUses(statement.body, sets, reads); break; + default: break; + } + } +}; + +/** + * The program with values written into the reads of the locals holding them, so each store holds its whole value, as + * nested calls inlined into temporaries don't: a local assigned once a constant, into every read after it; and one + * assigned once a value of row columns, constants and locals and read once, into its read in a later statement of the + * same list when nothing between changes what the value reads. `aliases` is whether two columns hold the same bytes. + * Accumulators keep their assignments. + */ +export const forwardLocals = (program: Program, aliases: (a: number, b: number) => boolean): Program => { + const accumulators = new Set(program.reductions ?? []); + const changes = (between: readonly Statement[], locals: ReadonlySet, columns: ReadonlySet): boolean => between.some(statement => { + switch (statement.kind) { + case "set": return locals.has(statement.local); + case "store": return [...columns].some(column => aliases(column, statement.column)); + case "stamp": return false; + default: return true; + } + }); + let body = program.body; + for (let pass = 0; pass < 64; pass++) { + const sets = new Map(); + const reads = new Map(); + countUses(body, sets, reads); + let changed = false; + const visit = (statements: readonly Statement[]): Statement[] => { + const list: Statement[] = statements.map((statement): Statement => { + switch (statement.kind) { + case "if": return { ...statement, consequent: visit(statement.consequent), alternate: visit(statement.alternate) }; + case "block": case "loop": return { ...statement, body: visit(statement.body) }; + default: return statement; + } + }); + for (let index = 0; index < list.length; index++) { + const statement = list[index]; + if (statement === undefined || statement.kind !== "set" || sets.get(statement.local) !== 1 || accumulators.has(statement.local)) continue; + const { local, value } = statement; + const total = reads.get(local) ?? 0; + if (total === 0) continue; + const later = list.slice(index + 1); + if (constant(value)) { + const count = { n: 0 }; + const replaced = replaceInStatements(later, local, value, count); + if (count.n !== total) continue; + list.splice(index, list.length - index, ...replaced); + changed = true; + index--; + continue; + } + const locals = new Set(); + const columns = new Set(); + if (total !== 1 || locals.has(local) || !readsOnly(value, locals, columns)) continue; + const reader = later.findIndex(next => { + const count = { n: 0 }; + replaceInStatements([next], local, value, count); + return count.n > 0; + }); + const target = later[reader]; + if (target === undefined || changes(later.slice(0, reader), locals, columns)) continue; + const count = { n: 0 }; + const replaced = replaceInOwn(target, local, value, count); + if (replaced === null || count.n !== 1) continue; + list.splice(index + 1 + reader, 1, replaced); + list.splice(index, 1); + changed = true; + index--; + } + return list; + }; + body = visit(body); + if (!changed) break; + } + return { ...program, body }; +}; diff --git a/ecs/packages/ecs/src/implementation/world/fusion.ts b/ecs/packages/ecs/src/implementation/world/fusion.ts index 8440d839..4d044736 100644 --- a/ecs/packages/ecs/src/implementation/world/fusion.ts +++ b/ecs/packages/ecs/src/implementation/world/fusion.ts @@ -159,17 +159,14 @@ export const fuseSchedule = (state: State, schedule: Schedule, runnerOf: (leaf: return { leaf, runner, tier: t, uses: usesOf(state, runner, leaf), reads: readsOf(runner), group: null }; })); const groups: Placed[][] = []; - const storagePrecisionOf = (entry: Placed): boolean => entry.runner.kernel?.description.storagePrecision === true; for (let t = 1; t < placed.length; t++) { for (const later of placed[t]) { if (!fusible(later.runner, later.leaf)) continue; const readsFrom = (earlier: Placed): boolean => earlier.runner.touches.some(id => later.reads.has(id)); const shares = (group: Placed[]): boolean => group.some(readsFrom); - // A fused kernel computes in one arithmetic: an explicit kernel's, 32 bits for I32 and U32, or as JS does. - const precision = storagePrecisionOf(later); const candidate = groups.find(group => { const last = group[group.length - 1]; - if (last === undefined || last.tier >= t || !shares(group) || group.some(member => storagePrecisionOf(member) !== precision)) return false; + if (last === undefined || last.tier >= t || !shares(group)) return false; for (let s = group[0]?.tier ?? t; s < t; s++) if (schedule.syncs[s] !== null) return false; // What runs in the tiers it moves over, and beside it, mustn't conflict with what moves. for (let s = (group[0]?.tier ?? t) + 1; s <= t; s++) { @@ -186,7 +183,7 @@ export const fuseSchedule = (state: State, schedule: Schedule, runnerOf: (leaf: continue; } const earlier = placed.slice(0, t).flat().find(other => other.group === null && fusible(other.runner, other.leaf) - && readsFrom(other) && storagePrecisionOf(other) === precision + && readsFrom(other) && placed.slice(other.tier + 1, t + 1).every(tier => tier.every(next => next === later || !conflict(other.uses, next.uses))) && schedule.syncs.slice(other.tier, t).every(sync => sync === null)); if (earlier === undefined) continue; @@ -334,7 +331,7 @@ const compileGroup = async (state: State, group: FusedGroup): Promise => { if (parts.some(part => part === undefined || part.loaded === null) || kernels.some(kernel => kernel?.wasm === null || kernel?.description.program === null)) return; const fusion = parts.flatMap(part => part === undefined ? [] : [part]); const merged = fuseMembers(fusion, kernels.flatMap(kernel => kernel?.description.program ?? []), kernels.map(kernel => (kernel?.description.resources ?? []).flatMap(key => typeof key === "symbol" ? [key] : []))); - const wasm = generateWasm(merged.program, merged.columns, merged.scalarType, state.simd, 0, [], [], [], [], [], kernels.every(kernel => kernel?.description.storagePrecision === true), merged.arrays); + const wasm = generateWasm(merged.program, merged.columns, merged.scalarType, state.simd, 0, [], [], [], [], [], true, merged.arrays); group.loadedFrom = fusion.map(part => part.loaded).join("|"); if (wasm === null || (!wasm.vectorized && kernels.some(kernel => kernel?.wasm?.vectorized === true))) { group.refused = true; diff --git a/ecs/packages/ecs/src/implementation/world/interleaved-arms.test.ts b/ecs/packages/ecs/src/implementation/world/interleaved-arms.test.ts new file mode 100644 index 00000000..9d89567f --- /dev/null +++ b/ecs/packages/ecs/src/implementation/world/interleaved-arms.test.ts @@ -0,0 +1,79 @@ +// © 2026 Adobe. MIT License. See /LICENSE for details. +import { expect, it } from "vitest"; +import type { F32, I32, U32 } from "../../interface/math/index.js"; +import { definitionOf } from "../../interface/registry/index.js"; +import { workers } from "../../interface/resources/workers.js"; +import { System } from "../../interface/system/system.js"; +import { kernelOf } from "./attach-kernel.js"; +import { createWorld } from "./create.js"; +import { bindKernel } from "./kernels.js"; +import { readEach, select } from "./reads.test-helper.js"; +import { createState } from "./state.js"; + +const state = Symbol("interleavedArmsTest/state"); +const direction = Symbol("interleavedArmsTest/direction"); +declare module "@adobe/ecs" { + export interface Components { + [state]: { type: { readonly step: I32; readonly rng: readonly [U32, U32, U32, U32] } }; + [direction]: { type: { readonly x: F32; readonly y: F32 } }; + } +} + +type Random = readonly [U32, U32, U32, U32]; +/** xoshiro128**, as the ecs_benchmark suite's systems draw numbers. */ +const next = (s: Random): { readonly value: U32; readonly state: Random } => { + const scrambled = Math.imul(s[1], 5); + const t = s[1] << 9, t2 = s[2] ^ s[0], t3 = s[3] ^ s[1]; + return { value: Math.imul((scrambled << 7) | (scrambled >>> 25), 9) >>> 0, state: [(s[0] ^ t3) >>> 0, (s[1] ^ t2) >>> 0, (t2 ^ t) >>> 0, ((t3 << 11) | (t3 >>> 21)) >>> 0] }; +}; +const range = (s: Random, low: number, high: number): { readonly value: U32; readonly state: Random } => { + const step = next(s); + return { value: (step.value % (high - low + 1)) + low, state: step.state }; +}; + +const spawn = System.create({}, ({ commands }, input: { readonly pattern: number }) => { + for (let i = 0; i < 1001; i++) { + const taken = input.pattern === 0 ? true : input.pattern === 1 ? false : ((Math.imul(i, 0x9e3779b1) >>> 16) & 3) === 0; + commands.spawn([state, direction])({ [state]: { step: taken ? 10 * i : 10 * i + 1, rng: [i + 1, 2 * i + 3, 0x9e3779b9 ^ i, 7] }, [direction]: { x: 0, y: 0 } }); + } +}); + +/** Two draws in each arm, more than the interleaved loop runs for every group, taken by rows whose step is a tenth. */ +const steer = System.create({ kernel: true, components: { with: [state, direction] } }, row => { + const value = row[state]; + if (value.step % 10 === 0) { + if (value.rng[0] > value.rng[1]) { + const x = range(value.rng, 3, 19); + const y = range(x.state, 0, 5); + row[direction] = { x: x.value - 10, y: y.value }; + row[state] = { step: value.step, rng: y.state }; + } + else { + const x = range(value.rng, 0, 5); + const y = range(x.state, 3, 19); + row[direction] = { x: x.value, y: y.value - 10 }; + row[state] = { step: value.step, rng: y.state }; + } + } +}); + +it("runs large arms four rows at a time, skipped where no row of a group takes them, as one row at a time does", async () => { + const definition = definitionOf(steer); + const description = kernelOf(steer); + if (definition === undefined || definition.kind === "composite" || description === undefined) throw new Error("not a compiled leaf"); + expect(bindKernel(createState(), definition, description).wasm?.lanes).toBe("interleaved"); + for (const pattern of [0, 1, 2]) { + const results = []; + for (const simd of [false, true]) { + await using world = createWorld({ [workers]: 0 }, { simd }); + await world.run(spawn, { pattern }); + await world.run(steer); + await world.run(steer); + const entities = await select(world, { required: [state] }); + results.push([await readEach(world, entities, state), await readEach(world, entities, direction)]); + } + expect([pattern, results[1]]).toEqual([pattern, results[0]]); + const moved = (results[0]?.[1] ?? []).filter(value => JSON.stringify(value) !== '{"x":0,"y":0}').length; + expect([pattern, pattern === 0 ? moved > 900 : pattern === 1 ? moved === 0 : moved > 100 && moved < 500]).toEqual([pattern, true]); + } +}); diff --git a/ecs/packages/ecs/src/implementation/world/kernel.ts b/ecs/packages/ecs/src/implementation/world/kernel.ts index 7ec3d898..3c2c6f20 100644 --- a/ecs/packages/ecs/src/implementation/world/kernel.ts +++ b/ecs/packages/ecs/src/implementation/world/kernel.ts @@ -267,11 +267,6 @@ export type KernelDescription = { readonly reductions: readonly Reduced[]; /** The leaves of each value contributed whole, by resource. Registration checks they are all of the schema's leaves. */ readonly reducedShapes: readonly Shape[]; - /** - * Whether its arithmetic may round each step to storage precision, as SIMD lanes do: only for a kernel the - * declaration asks for. A body compiled unflagged computes as the body as written does. - */ - readonly storagePrecision?: true; }; /** What a kernel module at `KernelDescription.url` exports. */ diff --git a/ecs/packages/ecs/src/implementation/world/kernels.ts b/ecs/packages/ecs/src/implementation/world/kernels.ts index 9bc848da..0f2e939e 100644 --- a/ecs/packages/ecs/src/implementation/world/kernels.ts +++ b/ecs/packages/ecs/src/implementation/world/kernels.ts @@ -339,7 +339,7 @@ export const bindKernel = (state: State, leaf: Leaf, description: KernelDescript const generate = (muted: readonly boolean[]): WasmKernel | null => useWasm && description.program !== null ? generateWasm(description.program, wasmColumns.map((column, k) => muted[k] ? { ...column, muted: true } : column), scalarType, state.simd, filterCount, wasmLookups, upWasmColumns, description.reductions.map(reduction => reduction.operator), indexes.map(bound => bound?.wasm ?? null), (description.probes ?? []).map(probe => probe.lookup), - description.storagePrecision === true, arrays) + true, arrays) : null; let muted = mutedNow(); let index = state.kernelIndexes.get(description.url); diff --git a/ecs/packages/ecs/src/implementation/world/perf.md b/ecs/packages/ecs/src/implementation/world/perf.md index 79822587..40f89b8c 100644 --- a/ecs/packages/ecs/src/implementation/world/perf.md +++ b/ecs/packages/ecs/src/implementation/world/perf.md @@ -400,9 +400,74 @@ move, chromium, by worker count and entity count (a quarter of the entities move - **Even shares wait for the slowest core.** The default pool is `hardwareConcurrency − 1`, which is 9 here. Past 7 workers, shares land on efficiency cores or share a core with the main thread, so 1M more than doubles. Browsers expose no core types or thread placement, so claimed splits fix this instead: with them, 1M takes 0.030 ms at 7, 8 and the default 9 workers. Pieces per worker (4, 8 or 16) made no measurable difference. - **At 10M the work is memory bound.** 2.5M rows read 24 bytes and write 12, about 90 MB per run; 0.5 ms is about 180 GB/s, near the chip's CPU bandwidth. It stops improving after 4 to 6 workers, and more entities would not change that. - **Single-threaded move matches the adobe/data ECS** (0.095 ms against 0.09 ms): four tight vec3 rows are three full vectors, as its separate x, y and z arrays are. +- **Lanes across rows for every kernel, at storage precision** (`design.md`, Precision and Lanes across rows), M4 Max, ns a row, before → after: `integrate` 0.951 → 0.273, against a 0.224 memory bound; `integrate f64` 0.791 → 0.522, against 0.426; `with 100K kernel` 0.303 → 0.183; `shared read 100K kernel` 0.228 → 0.128; `column read 100K kernel` 0.250 → 0.159; `chain` 0.203 → 0.174; `move` 0.226 both, as it already ran in lanes. The generated `integrate` loop runs within 2% of a hand-written one. +- **f32 arithmetic a row at a time in f32 instructions,** where it rounded each f64 step to f32: the guide's `move` without SIMD 1.95 → 0.61 ns a row (below). +- **Filtered rows in lanes, eight rows' masks at a time** (`design.md`, Filtered rows in lanes), M4 Max: `integrate changed half` 1.11 → 0.49 ns a row; `changed all 100K kernels` 64.5 → 26.5 µs a system; `sparse changed` 0.177 → 0.155 ns a row, `sparse changed clustered` 0.0141 → 0.0083; `changed one` and `changed few 100K kernels` within noise. Over 1M rows, a vec3 kernel took 0.42 ns a row for every row changed or a random half, against 0.96 and 3.84 a row at a time within lanes, and 0.70 at a random tenth, against 1.63. + +## The guide's move on one thread + +`row[position] = Vec3.add(row[position], Vec3.scale(row[velocity], resources[delta]))` over 1M rows of f32 vec3s, +one thread (`workers: 0`), M4 Max, fastest run: + +| Runs as | ns a row | 1M rows | +| --- | --- | --- | +| The body as written (`kernel: false`) | 129 | 135 ms | +| JS kernel (where WASM can't run) | 2.45 | 2.57 ms | +| WASM a row at a time (no SIMD) | 0.61 | 0.64 ms | +| WASM, f32x4 across rows | 0.227 | 0.24 ms | + +- **The SIMD kernel runs at one core's memory throughput.** Each row moves 36 bytes (24 read, 12 written). A + hand-written loop with the same loads and stores and one `v128.or` in place of the arithmetic takes the same time at + every size, so the arithmetic is free: + + | Rows | Working set | `move` | Loads and stores alone | `move`'s rate | + | --- | --- | --- | --- | --- | + | 1K | 0.02 MB | 0.150 | 0.144 | 239 GB/s | + | 16K | 0.38 MB | 0.231 | 0.225 | 156 GB/s | + | 1M | 24 MB | 0.238 | 0.235 | 152 GB/s | + | 16M | 384 MB | 0.234 | 0.236 | 154 GB/s | + + The rate is flat at about 155 GB/s from L2 to DRAM; only a working set in L1 goes faster. The benchmarks' **Best** + assumes the peak in-cache copy rate (0.195 for `move`), which one core can't sustain past L1. More rows a second + take more cores: `move workers` 0.051 ns a row across nine. +- **The JS kernel** inlines the calls into scalar arithmetic on the columns' typed arrays, about 55× the body as + written, which builds tuples and reads each row through its row object; WASM without SIMD is 4× the JS kernel. + +- **Interleaved arms skipped by groups no row takes them,** each span only such an arm uses loaded and stored back in it, + where an arm over `armsBudget` made the kernel run a row at a time: the ecs_benchmark suite's `MoreComplexSystem`, + whose rows all take its arm one frame in ten, 0.95 → 0.76 ns a row at 1M; its 7-system frame 4.20 → 4.08. Loading + every span up front, the arm skipped, took 1.13. + +## Modeling components + +The component rules (`rules/component.x.ts.md`) rest on these, WASM, one thread, 1M rows, M4 Max: + +- **Fields combined with each other:** `HealthSystem` of the ecs_benchmark suite, `{ hp, maxhp, status }` as one struct + 0.61 ns a row, as three components 0.35. The struct's kernel transposes four rows into a vector a field and back, 16 + shuffles a group; the same logic over separate arrays, hand-written, 0.30, near its memory floor of about 0.18. A + hand-written transpose of the struct with fewer, irregular shuffles was slower, 1.00: the generated one is about the + best the struct's layout allows. +- **One field of a wide struct:** reading the `I32` `thingy` of the suite's 40-byte `DataComponent`, 0.42 ns a row; as + its own component, 0.17. A row loads its components' every byte. +- **Width:** `integrate` 0.27 ns a row in `F32`, `integrate f64` 0.52. +- **The suite's frame by system** (`BM_ComplexSystemsUpdate`, 1M): `MovementSystem` 0.20 at its floor of about 0.16; + `DataSystem` 1.11 against 0.50; `MoreComplexSystem` 0.76 against 0.26 (below); `HealthSystem` 0.65 against 0.16; `DamageSystem` 0.39 against 0.21; + `SpriteSystem` 0.53 against 0.26; `RenderSystem` 0.37 against 0.08, scattered writes to its frame buffer. The suite + ports its structs as the C++ declares them, so they stay structs there. ## Tried and not kept +- **Filtered groups of four without the eight-row skip,** every group's arithmetic run under its mask: `changed all 100K + kernels` 32.6 µs and a random tenth 0.38 ns a row, but `sparse changed` 0.35 ns, against 0.155 with the skip. Skipping + before the groups with the old eight-row check loaded and compared the ticks twice: `changed all 100K kernels` 45 µs. + Skipping a group of four whose mask is empty: 38.2 µs and `sparse changed` 0.26. The eight rows' masks shared by the + skip and the groups beat all three but at a random tenth, where the skip's branch mispredicts; worth revisiting with + a skip that turns off in a run where it rarely skips. + +- **Eight rows a pass in the across-elements loop,** two groups of four unrolled: a hand-written f32x4 `move` over 1M + rows took 0.246 ns a row both ways on an M4 Max, the loop already bound by memory. Worth revisiting for bodies with + more arithmetic a row, where the loop's own instructions are a larger share. + - **Finding a sync point's pairs by scanning up to eight before using the map,** since `Map.prototype.clear` allocates a new table: `sync point one spawn` 669 bytes and 0.40–0.42 µs mean before and after, `spawn singles` 0.57–0.59 µs both. The allocations a sync point keeps, about 670 bytes with the benchmark's own, are its closures and records in diff --git a/ecs/packages/ecs/src/implementation/world/plan.md b/ecs/packages/ecs/src/implementation/world/plan.md index b6ea0fe1..41f031e9 100644 --- a/ecs/packages/ecs/src/implementation/world/plan.md +++ b/ecs/packages/ecs/src/implementation/world/plan.md @@ -68,13 +68,14 @@ All of the runtime lives here. The only export is `create`, which moves here fro - **Layout:** a linear component is one interleaved column per archetype, in its schema's layout: `storage` (WGSL storage-buffer rules), `vertex` (tight, 4-byte aligned), or by default tight for the CPU. A GPU layout is checked at registration. Kernels address a field as `row * stride + offset`. - **The compiler lowers each kernel once** and prints both the JS kernel and a `Program` IR from it. The IR is `null` for kernels with commands or lookups, which keep the JS kernel. -- **Registration generates WASM** from the IR and the schemas' storage types: f64 arithmetic with typed-array store conversion, so scalar WASM is bit-identical to JS. It compiles once, and every worker instantiates the module against the shared `Memory`. -- **SIMD**, in f32 lanes at storage precision: - - *Across rows*, four at a time, when every column is a dense f32 scalar. - - *Across rows of whole elements*, four at a time as `stride / 4` full vectors, when every store fuses into whole-element writes of components that read only same-stride components lane for lane (`p = p + v` on tight vec2 or vec3). The per-row loop takes the tail. +- **Registration generates WASM** from the IR and the schemas' storage types, at storage precision: arithmetic on f32 values rounds each step to f32, a row at a time as in lanes, and f64 values compute as JS does. It compiles once, and every worker instantiates the module against the shared `Memory`. +- **SIMD**, in f32 lanes, or f64x2 when every float field is an f64: + - *Across rows*, a vector's lanes at a time, when every column is a dense float scalar. + - *Across rows of whole elements*, four at a time as `4 × stride / 16` full vectors, when every store fuses into element writes of components that read same-stride components lane for lane, values the same for every row, and values of each row spread across its element's leaves (`p = p + v * (mass * delta)` on tight or padded vec2, vec3 or vec4); lanes no store writes are kept. The per-row loop takes the tail. + - *Filtered rows* run across rows the same way, eight rows' masks of passing rows at a time, branch-free within them, inside each run of passing blocks. - *Within a row* otherwise: consecutive snapshot loads of a component's leaves become one vector load, and stores to its leaves whose values match lane for lane become one f32x4 operation and store. Loads and stores cover only the element's lanes. - Anything else runs as scalar WASM, in the same row. -- **Tests:** scalar WASM is bit-identical to JS; SIMD is within storage precision of JS; 0 and N workers stay identical with SIMD, since chunks start on 16-row boundaries. +- **Tests:** WASM is bit-identical with SIMD and without, and to the body rounding each f32 step; the JS kernel to the body as written; 0 and N workers stay identical with SIMD, since chunks start on 16-row boundaries. ## Deferred diff --git a/ecs/packages/ecs/src/implementation/world/precision.test.ts b/ecs/packages/ecs/src/implementation/world/precision.test.ts index d2a1239c..e43427a3 100644 --- a/ecs/packages/ecs/src/implementation/world/precision.test.ts +++ b/ecs/packages/ecs/src/implementation/world/precision.test.ts @@ -55,12 +55,11 @@ const differenceAfter = async (system: typeof tried, wasm: boolean): Promise { +it("computes a kernel in WASM at storage precision, rounding each step to f32, and in its JS kernel as the body as written does", async () => { expect(kernelOf(tried)).toBeDefined(); - const expected = await differenceAfter(written, true); - expect(expected).toBe(Math.fround(2 ** -46)); - expect(await differenceAfter(tried, true)).toBe(expected); - expect(await differenceAfter(tried, false)).toBe(expected); + expect(await differenceAfter(written, true)).toBe(Math.fround(2 ** -46)); + expect(await differenceAfter(tried, true)).toBe(0); + expect(await differenceAfter(tried, false)).toBe(Math.fround(2 ** -46)); }); /** Values where f32 arithmetic loses what f64 keeps: cancellation, rounding at each step, NaN, infinities and -0. */ @@ -73,23 +72,29 @@ const seedMany = System.create(({ commands }) => { const touch = System.create({ kernel: false, components: { with: [c] } }, row => { if (row.entity % 3 === 0) row[c] = row[c] * 3; }); +/** Each kernel, the body as written, and the body rounding each step of f32 arithmetic to f32, as its WASM does in lanes and a row at a time. */ const pairs = [ [ System.create({ components: { with: [a, c, difference] } }, row => { row[difference] = Math.sqrt(Math.abs(row[a])) / row[c] + Math.min(row[a], 0.75) * Math.fround(row[c]) - Math.floor(row[a]); }), System.create({ kernel: false, components: { with: [a, c, difference] } }, row => { row[difference] = Math.sqrt(Math.abs(row[a])) / row[c] + Math.min(row[a], 0.75) * Math.fround(row[c]) - Math.floor(row[a]); }), + System.create({ kernel: false, components: { with: [a, c, difference] } }, row => { row[difference] = Math.fround(Math.fround(Math.fround(Math.sqrt(Math.abs(row[a]))) / row[c]) + Math.fround(Math.min(row[a], 0.75) * row[c])) - Math.floor(row[a]); }), ], [ System.create({ components: { with: [velocity, position] } }, row => { row[position] = [row[position][0] * row[velocity][0] - row[velocity][0] * 0.75, row[position][1] * row[velocity][1] - row[velocity][1] * 0.75, row[position][2] * row[velocity][2] - row[velocity][2] * 0.75]; }), System.create({ kernel: false, components: { with: [velocity, position] } }, row => { row[position] = [row[position][0] * row[velocity][0] - row[velocity][0] * 0.75, row[position][1] * row[velocity][1] - row[velocity][1] * 0.75, row[position][2] * row[velocity][2] - row[velocity][2] * 0.75]; }), + System.create({ kernel: false, components: { with: [velocity, position] } }, row => { row[position] = [Math.fround(row[position][0] * row[velocity][0]) - Math.fround(row[velocity][0] * 0.75), Math.fround(row[position][1] * row[velocity][1]) - Math.fround(row[velocity][1] * 0.75), Math.fround(row[position][2] * row[velocity][2]) - Math.fround(row[velocity][2] * 0.75)]; }), ], // Remainders by integer literals: of integers and of everything else, NaN, infinities and -0 among them. + // Remainders run a row at a time; a product of f32s rounds to f32 there too. [ System.create({ components: { with: [a, c, difference] } }, row => { row[difference] = row[a] < 0 ? Math.trunc(row[a] * -1e6) % 5 + row[c] % 2 : row[a] === 0 ? Math.trunc(row[a]) % 4 : row[a] % 3 + Math.floor(row[c] * 4096) % 7; }), System.create({ kernel: false, components: { with: [a, c, difference] } }, row => { row[difference] = row[a] < 0 ? Math.trunc(row[a] * -1e6) % 5 + row[c] % 2 : row[a] === 0 ? Math.trunc(row[a]) % 4 : row[a] % 3 + Math.floor(row[c] * 4096) % 7; }), + System.create({ kernel: false, components: { with: [a, c, difference] } }, row => { row[difference] = row[a] < 0 ? Math.trunc(Math.fround(row[a] * -1e6)) % 5 + row[c] % 2 : row[a] === 0 ? Math.trunc(row[a]) % 4 : row[a] % 3 + Math.floor(Math.fround(row[c] * 4096)) % 7; }), ], [ System.create({ components: { with: [a, c, difference], changed: [c] } }, row => { row[difference] = row[a] * row[a] - row[c]; }), System.create({ kernel: false, components: { with: [a, c, difference], changed: [c] } }, row => { row[difference] = row[a] * row[a] - row[c]; }), + System.create({ kernel: false, components: { with: [a, c, difference], changed: [c] } }, row => { row[difference] = Math.fround(row[a] * row[a]) - row[c]; }), ], ] as const; const values: number[] = []; @@ -126,12 +131,11 @@ const bitsAfter = async (system: (typeof pairs)[number][number], wasm: boolean): } }; -it("gives an unflagged kernel's results bit for bit as written, for dense columns, whole elements and change filters", async () => { - for (const [index, [tried, written]] of pairs.entries()) { +it("gives a kernel's results bit for bit rounding each step to f32 in WASM and as written in JS, for dense columns, whole elements and change filters", async () => { + for (const [index, [tried, written, stepped]] of pairs.entries()) { expect([index, kernelOf(tried) !== undefined]).toEqual([index, true]); - const expected = await bitsAfter(written, true); - expect([index, "wasm", await bitsAfter(tried, true)]).toEqual([index, "wasm", expected]); - expect([index, "js", await bitsAfter(tried, false)]).toEqual([index, "js", expected]); + expect([index, "wasm", await bitsAfter(tried, true)]).toEqual([index, "wasm", await bitsAfter(stepped, true)]); + expect([index, "js", await bitsAfter(tried, false)]).toEqual([index, "js", await bitsAfter(written, true)]); } }); diff --git a/ecs/packages/ecs/src/implementation/world/shared-kernels.test.ts b/ecs/packages/ecs/src/implementation/world/shared-kernels.test.ts index 674f53ed..165e664a 100644 --- a/ecs/packages/ecs/src/implementation/world/shared-kernels.test.ts +++ b/ecs/packages/ecs/src/implementation/world/shared-kernels.test.ts @@ -48,6 +48,12 @@ const written = System.create({ kernel: false, components: { with: [scale, cell, row[out] = row[value] * row[scale] + x / 3 + (row[flag] ? 1 : 0); row[steps] = x * 1000 + y; }); +/** The body rounding each step of its f32 arithmetic to f32, as WASM computes it. */ +const stepped = System.create({ kernel: false, components: { with: [scale, cell, flag, value, out, steps] } }, row => { + const [x, y] = row[cell]; + row[out] = Math.fround(Math.fround(row[value] * row[scale]) + Math.fround(x / 3)) + (row[flag] ? 1 : 0); + row[steps] = x * 1000 + y; +}); /** Moving rows to another scale, which only a system run as written does: tried as a kernel, it runs as written. */ const moving = System.create({ components: { with: [value] } }, (row, { commands }) => { @@ -74,11 +80,11 @@ describe("a kernel reading a shared component", () => { expect(description?.program).not.toBeNull(); }); for (const wasm of [false, true]) { - it(`gives the body's results, bit for bit, in ${wasm ? "WASM" : "JS"}`, async () => { + it(`gives the body's results, bit for bit, in ${wasm ? "WASM, rounding each step of f32 arithmetic" : "JS, as written"}`, async () => { const expected = await (async () => { await using world = createWorld({ [workers]: 0 }, { wasm }); await world.run(spawn); - await world.run(written); + await world.run(wasm ? stepped : written); return results(world); })(); await using world = createWorld({ [workers]: 0 }, { wasm }); diff --git a/ecs/packages/ecs/src/implementation/world/shared-workers.cases.ts b/ecs/packages/ecs/src/implementation/world/shared-workers.cases.ts index da8c7b2d..dcb85948 100644 --- a/ecs/packages/ecs/src/implementation/world/shared-workers.cases.ts +++ b/ecs/packages/ecs/src/implementation/world/shared-workers.cases.ts @@ -5,7 +5,7 @@ import type * as Fixture from "./shared-workers.fixture.js"; /** Shared components in kernels on workers: the cases, over the fixture built for node. */ export const sharedWorkersCases = (load: () => Promise) => describe("shared components in kernels on workers", () => { for (const wasm of [false, true]) { - it(`take each call's archetype's values, giving the body's results bit for bit (${wasm ? "WASM" : "JS"})`, async () => { + it(`take each call's archetype's values, giving the body's results bit for bit (${wasm ? "WASM, rounding each step of f32 arithmetic" : "JS"})`, async () => { const fixture = await load(); const { kernel, written } = await fixture.computedOnWorkers(wasm); expect(kernel).toEqual(written); diff --git a/ecs/packages/ecs/src/implementation/world/shared-workers.fixture.ts b/ecs/packages/ecs/src/implementation/world/shared-workers.fixture.ts index 4cfe82f7..be120d83 100644 --- a/ecs/packages/ecs/src/implementation/world/shared-workers.fixture.ts +++ b/ecs/packages/ecs/src/implementation/world/shared-workers.fixture.ts @@ -27,7 +27,7 @@ const spawn = System.create(({ commands }) => { commands.spawn([scale, cell, value, out, steps], { [scale]: [0.1, 1.5, -3.25][k % 3] ?? 0, [cell]: [k % 2, -7] })({ [value]: k * 0.7, [out]: 0, [steps]: 0 }); } }); -// Tried as a kernel, and as written: the kernel's results are the body's. +// Tried as a kernel, as written, and rounding each step of f32 arithmetic: JS kernels give the body's results, WASM the stepped ones. const compute = System.create({ components: { with: [scale, cell, value, out, steps] } }, row => { const [x, y] = row[cell]; row[out] = row[value] * row[scale] + x / 3; @@ -38,6 +38,11 @@ const written = System.create({ kernel: false, components: { with: [scale, cell, row[out] = row[value] * row[scale] + x / 3; row[steps] = x * 1000 + y; }); +const stepped = System.create({ kernel: false, components: { with: [scale, cell, value, out, steps] } }, row => { + const [x, y] = row[cell]; + row[out] = Math.fround(row[value] * row[scale]) + Math.fround(x / 3); + row[steps] = x * 1000 + y; +}); const read: [number, string][] = []; const results = System.create({ readonly: true, components: { with: [value, out, steps] } }, row => { read.push([row[value], `${row[out]} ${row[steps]}`]); }); @@ -50,9 +55,9 @@ const outcome = async (system: typeof compute, wasm: boolean): Promise a[0] - b[0]).map(([, text]) => text); }; -/** Each row's results, by a kernel on workers and by the body as written. */ +/** Each row's results, by a kernel on workers and by the body: as written for JS, rounding each f32 step for WASM. */ export const computedOnWorkers = async (wasm: boolean): Promise<{ readonly kernel: readonly string[]; readonly written: readonly string[] }> => - ({ kernel: await outcome(compute, wasm), written: await outcome(written, wasm) }); + ({ kernel: await outcome(compute, wasm), written: await outcome(wasm ? stepped : written, wasm) }); // With `where`, workers only ever run the archetypes that pass. const negative = System.create({ components: { with: [value, out], where: { [scale]: value => value < 0 } } }, row => { diff --git a/ecs/packages/ecs/src/implementation/world/wasm-kernels.test.ts b/ecs/packages/ecs/src/implementation/world/wasm-kernels.test.ts index b4ee166d..b3aa37f0 100644 --- a/ecs/packages/ecs/src/implementation/world/wasm-kernels.test.ts +++ b/ecs/packages/ecs/src/implementation/world/wasm-kernels.test.ts @@ -295,7 +295,7 @@ describe("WASM kernels", () => { if (description === undefined) throw new Error("not compiled"); return bindKernel(createState(), definition, description).wasm; }; - expect([integrate, bounce, tally, scale, drift].map(system => wasmOf(system)?.vectorized)).toEqual([false, false, false, false, true]); + expect([integrate, bounce, tally, scale, drift].map(system => wasmOf(system)?.vectorized)).toEqual([false, false, false, true, true]); expect(wasmOf(chase)).not.toBeNull(); }); @@ -364,10 +364,10 @@ describe("WASM kernels", () => { expect(scores).toEqual([[0.25, 0.25, 0.25], [0.25, 0.25, 0.25]]); }); - it("give bit-identical results to the JS kernels without SIMD", async () => { - const javascript = await simulate(false); - expect(javascript.some(values => JSON.stringify(values).includes("true"))).toBe(true); - expect(await simulate(true)).toEqual(javascript); + it("give bit-identical results with SIMD and without, rounding each step of f32 arithmetic alike", async () => { + const scalar = await simulate(true); + expect(scalar.some(values => JSON.stringify(values).includes("true"))).toBe(true); + expect(await simulate(true, true)).toEqual(scalar); }); it("stay within storage precision of the JS kernels with SIMD", async () => { diff --git a/ecs/packages/ecs/src/implementation/world/wasm.test.ts b/ecs/packages/ecs/src/implementation/world/wasm.test.ts index 2556913c..c484aacd 100644 --- a/ecs/packages/ecs/src/implementation/world/wasm.test.ts +++ b/ecs/packages/ecs/src/implementation/world/wasm.test.ts @@ -327,7 +327,7 @@ describe("generateWasm with change filters", () => { run(0, rows, 10, 5, 0, 16384, 32768, 65536, 66560); const written = [...output].flatMap((value, row) => value === -1 ? [] : [row]); // Rows 1100 and 2050 have new ticks, but their block or chunk says nothing in it changed, so they're skipped by design. - expect([simd, kernel.vectorized, written]).toEqual([simd, false, [1030, 1500, 2047]]); + expect([simd, kernel.vectorized, written]).toEqual([simd, simd, [1030, 1500, 2047]]); // From a start inside a block, that block's tick is still checked. output.fill(-1); run(1029, 1040, 10, 5, 0, 16384, 32768, 65536, 66560); @@ -548,14 +548,14 @@ describe("generateWasm with f64 lanes, as kernels computing at the body's precis expect(both(program, columns, ([a, b]) => { for (let i = 0; i < 1024; i++) { a[i] = hard(i); b[i] = hard(i + 3); } }, 5, 133)).toEqual({ vectorized: true, same: true }); }); - // A padded vec3's elements aren't whole vectors, and f64 lanes don't fuse within a row, so it runs a row at a time. - for (const [name, stride, leaves, vectorized] of [["vec2", 8, 2, true], ["tight vec3", 12, 3, true], ["padded vec3", 16, 3, false]] as const) { - it(`computes ${name} elements ${vectorized ? "in f64 lanes" : "a row at a time"}, as the body does`, () => { + // A padded vec3's padding lane is stored back as it was loaded. + for (const [name, stride, leaves] of [["vec2", 8, 2], ["tight vec3", 12, 3], ["padded vec3", 16, 3]] as const) { + it(`computes ${name} elements in f64 lanes, as the body does`, () => { // p = p * v - v * args, leaf by leaf, with p.x and v.x reading cancelling values. const all = Array.from({ length: leaves }, (_, leaf) => leaf); const program: Program = { locals: 0, body: all.map(leaf => ({ kind: "store", column: leaf, value: binary("-", binary("*", read(leaf), read(leaves + leaf)), binary("*", read(leaves + leaf), { kind: "args", path: [] })) })) }; const columns = [...all.map(leaf => column(0, stride, 4 * leaf)), ...all.map(leaf => column(1, stride, 4 * leaf))]; - expect(both(program, columns, ([p, v]) => { for (let i = 0; i < 1024; i++) { p[i] = hard(i); v[i] = hard(i + 1); } }, 1, 63)).toEqual({ vectorized, same: true }); + expect(both(program, columns, ([p, v]) => { for (let i = 0; i < 1024; i++) { p[i] = hard(i); v[i] = hard(i + 1); } }, 1, 63)).toEqual({ vectorized: true, same: true }); }); } @@ -931,9 +931,9 @@ describe("generateWasm integers through locals", () => { body: [ { kind: "set", local: 0, value: binary("%", column(0), number(17)) }, { kind: "store", column: 1, value: binary("-", local(0), number(10)) }, - // A u32 and 1 reach 2^32. + // A u32 and 1 reach 2^32; read twice, so it stays a local. { kind: "set", local: 1, value: binary("+", column(0), number(1)) }, - { kind: "store", column: 2, value: binary("/", local(1), local(0)) }, + { kind: "store", column: 2, value: binary("/", local(1), binary("+", local(1), local(0))) }, ], }; const rangeColumns: WasmColumn[] = [{ view: "u32", stride: 4, offset: 0, boolean: false, component: 0 }, { view: "i32", stride: 4, offset: 0, boolean: false, component: 1 }, dense("f64", 2)]; @@ -947,7 +947,7 @@ describe("generateWasm integers through locals", () => { const run = new WebAssembly.Instance(new WebAssembly.Module(kernel.bytes), { env: { memory }, math: importsOf(kernel.imports) }).exports.run; if (typeof run !== "function") throw new Error("no run export"); run(0, values.length, 0, -1, 0, 1024, 2048); - expect([[...differences], [...inverses]]).toEqual([values.map(x => (x % 17) - 10), values.map(x => (x + 1) / (x % 17))]); + expect([[...differences], [...inverses]]).toEqual([values.map(x => (x % 17) - 10), values.map(x => (x + 1) / (x + 1 + (x % 17)))]); const wat = printWat(kernel.bytes); if ("failure" in wat) throw new Error(wat.failure); const named = generateWasmOrReason(range, rangeColumns, () => "number", true, 0, [], [], [], [], [], false, () => null, true); @@ -1226,9 +1226,9 @@ describe("generateWasm interleaved rows", () => { expect(vector).toEqual(scalar); }); - it("runs an if beside lanes of a row without branching, choosing what its arms store, as row by row does", () => { - // p += v over an f32 pair in 8-byte elements, in lanes of a row; then, where an i32 is even, a long mix of it, - // past what four rows at a time take, and a choice by comparing p's fields. + it("runs an if with a long arm four rows at a time beside the lanes of whole elements, as row by row does", () => { + // p += v over an f32 pair in 8-byte elements; then, where an i32 is even, a long mix of it, more than an arm runs + // for every group, so skipped by groups no row of takes it, and a choice by comparing p's fields. const columns: WasmColumn[] = [ { view: "f32", stride: 8, offset: 0, boolean: false, component: 0 }, { view: "f32", stride: 8, offset: 4, boolean: false, component: 0 }, { view: "f32", stride: 8, offset: 0, boolean: false, component: 1 }, { view: "f32", stride: 8, offset: 4, boolean: false, component: 1 }, @@ -1252,8 +1252,8 @@ describe("generateWasm interleaved rows", () => { }; const { vector, scalar, wat } = bothWays(program, columns, 1, 4 * 40 + 3); expect(wat).toContain("f32x4.add"); - expect(wat).not.toContain("i32x4"); - expect(wat).toContain("select"); + expect(wat).toContain("i32x4"); + expect(wat).toContain("v128.any_true"); expect(vector).toEqual(scalar); }); @@ -1765,3 +1765,281 @@ describe("generateWasm remainders by a literal", () => { expect(signedMagic(7)).toEqual({ multiplier: -1840700269, shift: 2 }); }); }); + +describe("generateWasm across whole elements", () => { + type Columns = readonly (WasmColumn & { readonly base: number })[]; + const field = (view: "f32" | "f64", component: number, stride: number, offset: number): WasmColumn & { readonly base: number } => + ({ view, stride, offset, boolean: false, component, base: 8192 * (component + 1) }); + const read = (k: number): Expression => ({ kind: "column", column: k }); + const local = (k: number): Expression => ({ kind: "local", local: k }); + const args: Expression = { kind: "args", path: [] }; + const binary = (operator: "+" | "-" | "*", left: Expression, right: Expression): Expression => ({ kind: "binary", operator, left, right }); + /** Runs a kernel at storage precision over rows `start` to `end`, `args` 0.1, on memory `fill` sets; returns whether it vectorized, and the memory. */ + const run = (program: Program, columns: Columns, fill: (memory: WebAssembly.Memory) => void, start: number, end: number) => { + const kernel = generateWasm(program, columns, () => "number", true, 0, [], [], [], [], [], true); + if (kernel === null) throw new Error("expected a kernel"); + const memory = new WebAssembly.Memory({ initial: 2, maximum: 65536, shared: true }); + fill(memory); + const runKernel: unknown = new WebAssembly.Instance(new WebAssembly.Module(kernel.bytes), { env: { memory }, math: importsOf(kernel.imports) }).exports.run; + if (typeof runKernel !== "function") throw new Error("no run export"); + runKernel(start, end, 7, -1, ...columns.map(column => column.base), 0.1); + return { kernel, memory }; + }; + const f32 = Math.fround; + const rows = 40; + const ranges = [[0, rows], [3, 22], [1, 2]] as const; + + it("spreads a per-row f32 value over each element's leaves: a dense column loaded, a leaf of a wider one gathered", () => { + // p = p + v * (m * args), leaf by leaf; m is a dense f32 column, or the second leaf of an 8-byte element. + for (const [stride, offset] of [[4, 0], [8, 4]] as const) { + const columns = [field("f32", 0, 12, 0), field("f32", 0, 12, 4), field("f32", 0, 12, 8), field("f32", 1, 12, 0), field("f32", 1, 12, 4), field("f32", 1, 12, 8), field("f32", 2, stride, offset)]; + const program: Program = { locals: 0, body: [0, 1, 2].map(leaf => ({ kind: "store", column: leaf, value: binary("+", read(leaf), binary("*", read(3 + leaf), binary("*", read(6), args))) })) }; + for (const [start, end] of ranges) { + const { kernel, memory } = run(program, columns, memory => { + const floats = new Float32Array(memory.buffer); + for (let i = 0; i < 3 * rows; i++) { floats[8192 / 4 + i] = i * 1.25; floats[16384 / 4 + i] = 7 - i * 0.375; } + for (let i = 0; i < rows; i++) floats[24576 / 4 + i * stride / 4 + offset / 4] = 1 + i * 0.1; + }, start, end); + const p = new Float32Array(memory.buffer, 8192, 3 * rows); + const expected = Array.from({ length: 3 * rows }, (_, i) => { + const row = Math.floor(i / 3); + if (row < start || row >= end) return f32(i * 1.25); + return f32(f32(i * 1.25) + f32(f32(7 - i * 0.375) * f32(f32(1 + row * 0.1) * f32(0.1)))); + }); + expect([stride, start, end, kernel.lanes, [...p]]).toEqual([stride, start, end, "f32", expected]); + } + } + }); + + it("computes a local of each row's values four rows at a time, then spreads it", () => { + // s = m * args; p = p + v * s. + const columns = [field("f32", 0, 8, 0), field("f32", 0, 8, 4), field("f32", 1, 8, 0), field("f32", 1, 8, 4), field("f32", 2, 4, 0)]; + const program: Program = { + locals: 1, + body: [ + { kind: "set", local: 0, value: binary("*", read(4), args) }, + ...[0, 1].map((leaf): Program.Statement => ({ kind: "store", column: leaf, value: binary("+", read(leaf), binary("*", read(2 + leaf), local(0))) })), + { kind: "store", column: 4, value: binary("+", read(4), local(0)) }, + ], + }; + const s = (row: number): number => f32(f32(2 + row) * f32(0.1)); + // Rows outside whole groups of four, a row at a time, round as the lanes do. + for (const [start, end] of ranges) { + const { kernel, memory } = run(program, columns, memory => { + const floats = new Float32Array(memory.buffer); + for (let i = 0; i < 2 * rows; i++) { floats[8192 / 4 + i] = i; floats[16384 / 4 + i] = i + 0.5; } + for (let i = 0; i < rows; i++) floats[24576 / 4 + i] = 2 + i; + }, start, end); + const within = (row: number): boolean => row >= start && row < end; + expect([start, end, kernel.lanes, [...new Float32Array(memory.buffer, 8192, 2 * rows)], [...new Float32Array(memory.buffer, 24576, rows)]]).toEqual([ + start, end, "f32", + Array.from({ length: 2 * rows }, (_, i) => within(Math.floor(i / 2)) ? f32(i + f32(f32(i + 0.5) * s(Math.floor(i / 2)))) : i), + Array.from({ length: rows }, (_, row) => within(row) ? f32(2 + row + s(row)) : 2 + row), + ]); + } + }); + + it("loads, computes and stores f64 elements in f64 lanes, as the body computes, spreading a per-row f64", () => { + // p = p + v * (m * args) over f64 vec3s and a dense f64 m. + const columns = [field("f64", 0, 24, 0), field("f64", 0, 24, 8), field("f64", 0, 24, 16), field("f64", 1, 24, 0), field("f64", 1, 24, 8), field("f64", 1, 24, 16), field("f64", 2, 8, 0)]; + const program: Program = { locals: 0, body: [0, 1, 2].map(leaf => ({ kind: "store", column: leaf, value: binary("+", read(leaf), binary("*", read(3 + leaf), binary("*", read(6), args))) })) }; + for (const [start, end] of ranges) { + const { kernel, memory } = run(program, columns, memory => { + const doubles = new Float64Array(memory.buffer); + for (let i = 0; i < 3 * rows; i++) { doubles[8192 / 8 + i] = i / 3; doubles[16384 / 8 + i] = 1 / (i + 1); } + for (let i = 0; i < rows; i++) doubles[24576 / 8 + i] = Math.PI + i; + }, start, end); + const expected = Array.from({ length: 3 * rows }, (_, i) => { + const row = Math.floor(i / 3); + return row < start || row >= end ? i / 3 : i / 3 + 1 / (i + 1) * ((Math.PI + row) * 0.1); + }); + expect([start, end, kernel.lanes, [...new Float64Array(memory.buffer, 8192, 3 * rows)]]).toEqual([start, end, "f64", expected]); + } + }); + + it("runs dense f64 columns two rows at a time", () => { + const columns = [field("f64", 0, 8, 0), field("f64", 1, 8, 0)]; + const { kernel, memory } = run({ locals: 0, body: [{ kind: "store", column: 0, value: binary("-", binary("*", read(0), read(1)), args) }] }, columns, memory => { + const doubles = new Float64Array(memory.buffer); + for (let i = 0; i < rows; i++) { doubles[8192 / 8 + i] = i / 7; doubles[16384 / 8 + i] = 1e300 * i; } + }, 3, 22); + expect([kernel.lanes, [...new Float64Array(memory.buffer, 8192, rows)]]).toEqual(["f64", Array.from({ length: rows }, (_, i) => i >= 3 && i < 22 ? i / 7 * (1e300 * i) - 0.1 : i / 7)]); + }); + + it("keeps what no store writes: leaves the body leaves, and a padded vec3's padding", () => { + // p.x and p.z of a tight vec3; then x, y and z of a padded one. + for (const [stride, stored] of [[12, [0, 2]], [16, [0, 1, 2]]] as const) { + const columns = [0, 1, 2].flatMap(leaf => [field("f32", 0, stride, 4 * leaf)]); + const program: Program = { locals: 0, body: stored.map(leaf => ({ kind: "store", column: leaf, value: binary("*", read(leaf), args) })) }; + const { kernel, memory } = run(program, columns, memory => { + const floats = new Float32Array(memory.buffer, 8192, stride / 4 * rows); + for (let i = 0; i < floats.length; i++) floats[i] = i % (stride / 4) === 1 && stored.length === 2 ? NaN : i; + }, 1, 30); + const words = stride / 4; + const expected = Array.from({ length: words * rows }, (_, i) => { + const row = Math.floor(i / words), leaf = i % words; + const before = leaf === 1 && stored.length === 2 ? NaN : i; + return row >= 1 && row < 30 && (stored as readonly number[]).includes(leaf) ? f32(before * f32(0.1)) : before; + }); + expect([stride, kernel.lanes, [...new Float32Array(memory.buffer, 8192, words * rows)]]).toEqual([stride, "f32", expected]); + } + }); + + it("compares a row's f32 value with a constant as f32s, in lanes and a row at a time alike", () => { + // out = in > 0.1 ? 1 : 2, where in is f32(0.1), which is greater than 0.1 but not than f32(0.1). + const test: Expression = { kind: "binary", operator: ">", left: read(0), right: { kind: "number", value: 0.1 } }; + const program: Program = { locals: 0, body: [{ kind: "store", column: 1, value: { kind: "conditional", test, consequent: { kind: "number", value: 1 }, alternate: { kind: "number", value: 2 } } }] }; + const { kernel, memory } = run(program, [field("f32", 0, 4, 0), field("f32", 1, 4, 0)], memory => { + new Float32Array(memory.buffer, 8192, rows).fill(0.1); + }, 3, 22); + expect([kernel.lanes, [...new Float32Array(memory.buffer, 16384, rows)]]).toEqual(["f32", Array.from({ length: rows }, (_, row) => row >= 3 && row < 22 ? 2 : 0)]); + }); + + it("spreads a component's leaf after an earlier group stored it, as each row reads it", () => { + // v = v * args; p = p + v.x. + const columns = [field("f32", 0, 8, 0), field("f32", 0, 8, 4), field("f32", 1, 8, 0), field("f32", 1, 8, 4)]; + const program: Program = { + locals: 0, + body: [ + ...[0, 1].map((leaf): Program.Statement => ({ kind: "store", column: leaf, value: binary("*", read(leaf), args) })), + ...[2, 3].map((leaf): Program.Statement => ({ kind: "store", column: leaf, value: binary("+", read(leaf), read(0)) })), + ], + }; + const { kernel, memory } = run(program, columns, memory => { + const floats = new Float32Array(memory.buffer); + for (let i = 0; i < 2 * rows; i++) { floats[8192 / 4 + i] = i + 1; floats[16384 / 4 + i] = 100 * i; } + }, 0, rows); + const vx = (row: number): number => f32(f32(2 * row + 1) * f32(0.1)); + expect([kernel.lanes, [...new Float32Array(memory.buffer, 16384, 2 * rows)]]).toEqual(["f32", Array.from({ length: 2 * rows }, (_, i) => f32(100 * i + vx(Math.floor(i / 2))))]); + }); +}); + +describe("generateWasm filtered rows, with SIMD and without", () => { + const rows = 2600; + /** Each filter's row ticks, then chunk and block ticks; then the stamped column's; then the components'. */ + const tickBytes = 8 * rows + 64; + const field = (view: "f32" | "f64", component: number, stride: number, offset: number): WasmColumn => ({ view, stride, offset, boolean: false, component }); + const ticks = (component: number): WasmColumn => ({ view: "f64", stride: 8, offset: 0, boolean: false, component }); + const read = (k: number): Expression => ({ kind: "column", column: k }); + const args: Expression = { kind: "args", path: [] }; + const binary = (operator: "+" | "-" | "*" | ">", left: Expression, right: Expression): Expression => ({ kind: "binary", operator, left, right }); + const hash = (i: number): number => { + let x = (i + 0x9e3779b9) | 0; + x = Math.imul(x ^ (x >>> 16), 0x85ebca6b); + x = Math.imul(x ^ (x >>> 13), 0xc2b2ae35); + return (x ^ (x >>> 16)) >>> 0; + }; + /** Which rows each pattern marks changed. */ + const patterns: readonly (readonly [string, (row: number) => boolean])[] = [ + ["all", () => true], + ["none", () => false], + ["alternate", row => row % 2 === 0], + ["random half", row => hash(row) % 2 === 0], + ["random tenth", row => hash(row) % 10 === 0], + ["runs of 64", row => hash(row >> 6) % 2 === 0], + ["single rows", row => row === 1031 || row === 2047 || row === 5], + ]; + /** + * Runs a program with `filters` change filters over `rows` rows, the first filter marking rows by `changed` and + * the second, if any, the rows after each it marks, from `start` to `end`; returns the kernel and every byte it may + * have written, as words. + */ + const runFiltered = (program: Program, columns: readonly WasmColumn[], simd: boolean, filters: number, changed: (row: number) => boolean, start: number, end: number) => { + const kernel = generateWasm(program, columns, () => "number", simd, filters, [], [], [], [], [], true); + if (kernel === null) throw new Error("expected a kernel"); + const memory = new WebAssembly.Memory({ initial: 16, maximum: 65536, shared: true }); + let next = 64; + const allocate = (bytes: number): number => { const at = next; next += bytes + 64; return at; }; + // Each filter's ticks: a row's 9 where marked, else 1; its block and chunk 9 where a row in it is. + const filterArrays = Array.from({ length: filters }, (_, filter) => { + const marked = (row: number): boolean => filter === 0 ? changed(row) : row > 0 && changed(row - 1); + const rowTicks = allocate(tickBytes), chunks = allocate(8 * 8), blocks = allocate(8 * 64); + const view = new Float64Array(memory.buffer); + for (let row = 0; row < rows; row++) { + const tick = marked(row) ? 9 : 1; + view[rowTicks / 8 + row] = tick; + view[chunks / 8 + (row >> 10)] = Math.max(view[chunks / 8 + (row >> 10)] ?? 0, tick); + view[blocks / 8 + (row >> 6)] = Math.max(view[blocks / 8 + (row >> 6)] ?? 0, tick); + } + return { rowTicks, chunks, blocks }; + }); + // Columns: ticks of the stamped component as 3, a chunk's and block's as 0; components filled with distinct values. + const bases = new Map(); + const addresses = columns.map(column => { + const key = column.component; + let base = bases.get(key); + if (base === undefined) { + base = allocate(Math.max(column.stride, 8) * rows + 64); + bases.set(key, base); + const length = (Math.max(column.stride, 8) * rows + 64) / 4; + if (key >= 0) { + if (column.view === "f64") { const view = new Float64Array(memory.buffer, base, length / 2); for (let k = 0; k < view.length; k++) view[k] = (k % 97) * 0.37 - 11; } + else { const view = new Float32Array(memory.buffer, base, length); for (let k = 0; k < view.length; k++) view[k] = (k % 97) * 0.37 - 11; } + } + else new Float64Array(memory.buffer, base, length / 2).fill(key === -1 ? 3 : 0); + } + return base; + }); + const run: unknown = new WebAssembly.Instance(new WebAssembly.Module(kernel.bytes), { env: { memory }, math: importsOf(kernel.imports) }).exports.run; + if (typeof run !== "function") throw new Error("no run export"); + run(start, end, 7, 5, ...addresses, ...filterArrays.map(arrays => arrays.rowTicks), ...filterArrays.map(arrays => arrays.chunks), ...filterArrays.map(arrays => arrays.blocks), 0.1); + return { kernel, memory, addresses, words: [...new Uint32Array(memory.buffer, 0, next / 4)] }; + }; + /** Checks a program gives the same bits with SIMD and without, for every pattern and range, and how SIMD runs it. */ + const same = (program: Program, columns: readonly WasmColumn[], lanes: "f32" | "f64" | null, filters = 1) => { + for (const [name, changed] of patterns) { + for (const [start, end] of [[0, rows], [3, 2050], [1029, 1040], [700, 701]] as const) { + const scalar = runFiltered(program, columns, false, filters, changed, start, end); + const vector = runFiltered(program, columns, true, filters, changed, start, end); + const differing = scalar.words.flatMap((word, k) => word === vector.words[k] ? [] : [k]); + expect([name, start, end, vector.kernel.lanes, differing.slice(0, 5)]).toEqual([name, start, end, lanes, []]); + } + } + }; + const stamp = (column: number): Program.Statement => ({ kind: "stamp", column, chunks: column + 1, blocks: column + 2 }); + + it("runs a dense f32 column's changed rows: their values, ticks, chunks and blocks", () => { + const columns = [field("f32", 0, 4, 0), field("f32", 1, 4, 0), ticks(-1), ticks(-2), ticks(-3)]; + const program: Program = { locals: 0, body: [{ kind: "store", column: 0, value: binary("+", read(0), binary("*", read(1), args)) }, stamp(2)] }; + same(program, columns, "f32"); + same(program, columns, "f32", 2); + // Directly: rows marked run, rounding each step to f32, and stamp their ticks; the rest keep both. + const changed = (row: number): boolean => hash(row) % 3 === 0; + const { memory, addresses } = runFiltered(program, columns, true, 1, changed, 0, rows); + const f32 = Math.fround; + const initial = (k: number): number => f32((k % 97) * 0.37 - 11); + const values = new Float32Array(memory.buffer, addresses[0], rows); + const rowTicks = new Float64Array(memory.buffer, addresses[2], rows); + expect([...values]).toEqual(Array.from({ length: rows }, (_, row) => changed(row) ? f32(initial(row) + f32(initial(row) * f32(0.1))) : initial(row))); + expect([...rowTicks]).toEqual(Array.from({ length: rows }, (_, row) => changed(row) ? 7 : 3)); + }); + + it("runs changed rows of whole vec3 and vec4 elements, spreading a per-row value", () => { + for (const leaves of [3, 4]) { + const stride = 4 * leaves; + const all = Array.from({ length: leaves }, (_, leaf) => leaf); + // p = p + v * (m * args), leaf by leaf. + const columns = [...all.map(leaf => field("f32", 0, stride, 4 * leaf)), ...all.map(leaf => field("f32", 1, stride, 4 * leaf)), field("f32", 2, 4, 0), ticks(-1), ticks(-2), ticks(-3)]; + const m = 2 * leaves; + const program: Program = { locals: 0, body: [...all.map((leaf): Program.Statement => ({ kind: "store", column: leaf, value: binary("+", read(leaf), binary("*", read(leaves + leaf), binary("*", read(m), args))) })), stamp(m + 1)] }; + same(program, columns, "f32"); + } + }); + + it("runs changed rows' partial stores and stores under an if, keeping what they leave", () => { + const columns = [field("f32", 0, 12, 0), field("f32", 0, 12, 4), field("f32", 0, 12, 8), field("f32", 1, 12, 0), field("f32", 1, 12, 8), ticks(-1), ticks(-2), ticks(-3)]; + // p.x and p.z less v times args; p.y kept. + const partial: Program = { locals: 0, body: [0, 2].map((leaf, k): Program.Statement => ({ kind: "store", column: leaf, value: binary("-", read(leaf), binary("*", read(3 + k), args)) })).concat(stamp(5)) }; + same(partial, columns, "f32"); + // Dense columns: where a > b, a = a + args, stamped. + const dense = [field("f32", 0, 4, 0), field("f32", 1, 4, 0), ticks(-1), ticks(-2), ticks(-3)]; + const branched: Program = { locals: 0, body: [{ kind: "if", test: binary(">", read(0), read(1)), consequent: [{ kind: "store", column: 0, value: binary("+", read(0), args) }, stamp(2)], alternate: [] }] }; + same(branched, dense, "f32"); + }); + + it("runs changed rows of f64 elements in f64 lanes", () => { + const columns = [field("f64", 0, 24, 0), field("f64", 0, 24, 8), field("f64", 0, 24, 16), field("f64", 1, 24, 0), field("f64", 1, 24, 8), field("f64", 1, 24, 16), ticks(-1), ticks(-2), ticks(-3)]; + const program: Program = { locals: 0, body: [...[0, 1, 2].map((leaf): Program.Statement => ({ kind: "store", column: leaf, value: binary("+", read(leaf), binary("*", read(3 + leaf), args)) })), stamp(6)] }; + same(program, columns, "f64"); + }); +}); diff --git a/ecs/packages/ecs/src/implementation/world/wasm.ts b/ecs/packages/ecs/src/implementation/world/wasm.ts index b843b266..89d552dc 100644 --- a/ecs/packages/ecs/src/implementation/world/wasm.ts +++ b/ecs/packages/ecs/src/implementation/world/wasm.ts @@ -3,6 +3,7 @@ import { blockShift, chunkShift, type Program } from './kernel.js'; import type { Reduction } from '../../interface/resource/reduction.js'; import { bytesOf, type View } from '../../interface/registry/layout.js'; import type { TypedArrays } from '../../interface/schema/schema.js'; +import { forwardLocals } from './forward-locals.js'; import { withoutIntrinsics } from './intrinsics.js'; type Expression = Program.Expression; @@ -95,6 +96,11 @@ export type WasmKernel = { readonly imports: readonly string[]; /** Whether it runs rows several at a time with SIMD: in f32 at storage precision, or in f64 as the body computes. */ readonly vectorized: boolean; + /** + * How its SIMD lanes run: four f32s or two f64s a vector; `interleaved`, four rows transposed into a vector a field; + * null when it runs a row at a time. + */ + readonly lanes: "f32" | "f64" | "interleaved" | null; }; /** Math functions with exact native equivalents; the rest are imported from JS so results match bit for bit. */ @@ -159,7 +165,7 @@ const op = { f64Abs: 0x99, f64Neg: 0x9a, f64Ceil: 0x9b, f64Floor: 0x9c, f64Trunc: 0x9d, f64Sqrt: 0x9f, f64Add: 0xa0, f64Sub: 0xa1, f64Mul: 0xa2, f64Div: 0xa3, f64Min: 0xa4, f64Max: 0xa5, i64Add: 0x7c, i64Sub: 0x7d, i64Mul: 0x7e, i64ExtendI32S: 0xac, i64ExtendI32U: 0xad, i32RemS: 0x6f, i32RemU: 0x70, - i32WrapI64: 0xa7, i32GeU: 0x4f, i32Ne: 0x47, i64Const: 0x42, i64ShrS: 0x87, i64ShrU: 0x88, i64RemS: 0x81, f64ConvertI64S: 0xb9, f64Copysign: 0xa6, f32DemoteF64: 0xb6, f64ConvertI32S: 0xb7, f64ConvertI32U: 0xb8, f64PromoteF32: 0xbb, + i32WrapI64: 0xa7, i32GeU: 0x4f, i32Ne: 0x47, i64Const: 0x42, i64ShrS: 0x87, i64ShrU: 0x88, i64RemS: 0x81, f64ConvertI64S: 0xb9, f64Copysign: 0xa6, f32DemoteF64: 0xb6, f32Const: 0x43, f32Neg: 0x8c, f32Add: 0x92, f32Sub: 0x93, f32Mul: 0x94, f32Div: 0x95, f64ConvertI32S: 0xb7, f64ConvertI32U: 0xb8, f64PromoteF32: 0xbb, } as const; const f64Type = 0x7c; const i32Type = 0x7f; @@ -340,7 +346,9 @@ export const generateWasmOrReason = ( arrays: (resource: number) => WasmArray | null = () => null, named = false, ): WasmKernel | string => { - const program = withoutIntrinsics(source); + // Columns of one component at one offset hold the same bytes. + const program = forwardLocals(withoutIntrinsics(source), (a, b) => a === b + || (columns[a] !== undefined && columns[b] !== undefined && columns[a].component >= 0 && columns[a].component === columns[b].component && columns[a].offset === columns[b].offset)); const scalars: WasmScalar[] = []; const scalarIndex = new Map(); const imports: string[] = []; @@ -1400,8 +1408,9 @@ export const generateWasmOrReason = ( return; } if (!strict || (leftType === rightType && leftType !== "mixed")) { - emit(expression.left); - emit(expression.right); + const f32 = comparesF32(expression); + (f32 ? emitF32 : emit)(expression.left); + (f32 ? emitF32 : emit)(expression.right); code.push(comparisons[expression.operator as keyof typeof comparisons]); return; } @@ -1659,6 +1668,17 @@ export const generateWasmOrReason = ( code.push(operator === ">>>" ? op.f64ConvertI32U : op.f64ConvertI32S); return; } + if (operator in arithmetic && f32Step(expression)) { + emitF32Value(expression); + code.push(op.f64PromoteF32); + return; + } + if (operator in comparisons && comparesF32(expression)) { + emitF32(left); + emitF32(right); + code.push(comparisons[operator as keyof typeof comparisons], op.f64ConvertI32U); + return; + } emit(left); emit(right); if (operator in arithmetic) { @@ -1668,6 +1688,100 @@ export const generateWasmOrReason = ( code.push(comparisons[operator as keyof typeof comparisons], op.f64ConvertI32U); }; + /** Each local assigned once, by its value. */ + const singleValues = new Map(); + { + const counts = new Map(); + const visit = (statements: readonly Statement[]): void => { + for (const statement of statements) { + if (statement.kind === "set") { + counts.set(statement.local, (counts.get(statement.local) ?? 0) + 1); + singleValues.set(statement.local, statement.value); + } + else if (statement.kind === "if") { visit(statement.consequent); visit(statement.alternate); } + else if (statement.kind === "block" || statement.kind === "loop") visit(statement.body); + } + }; + visit(program.body); + for (const [local, count] of counts) if (count !== 1) singleValues.delete(local); + } + /** + * Whether a value is an operand of f32 arithmetic at storage precision, as f32 lanes compute: an f32, a number the + * same for every row, which converts to f32, a local assigned one once, or such arithmetic's result. + */ + const f32Operand = (expression: Expression, depth = 0): boolean => { + if (depth > 64) return false; + switch (expression.kind) { + case "number": return true; + case "resource": case "args": case "shared": return typeOf(expression) === "number"; + case "local": { + const value = singleValues.get(expression.local); + return floatExact(expression) || (value !== undefined && f32Operand(value, depth + 1)); + } + case "unary": return (expression.operator === "-" || expression.operator === "+") && f32Operand(expression.operand, depth + 1); + case "binary": return floatExact(expression) || f32Step(expression, depth + 1); + default: return floatExact(expression); + } + }; + /** + * Whether arithmetic computes in f32, rounding its result, as f32 lanes do: at storage precision, with float fields + * stored as f32, on f32 operands, every row alike, whether it runs in lanes or one row at a time. + */ + const f32Step = (expression: Extract, depth = 0): boolean => + storagePrecision && !wide && expression.operator in arithmetic && wrappedKind(expression) == null + && f32Operand(expression.left, depth) && f32Operand(expression.right, depth); + /** Whether a comparison is of a row's f32 values, which compare as f32s, as f32 lanes compare them. */ + const comparesF32 = ({ left, right }: Extract): boolean => + storagePrecision && !wide && !(rowIndependent(left) && rowIndependent(right)) + && typeOf(left) === "number" && typeOf(right) === "number" && f32Operand(left) && f32Operand(right); + const f32Arithmetic = { "+": op.f32Add, "-": op.f32Sub, "*": op.f32Mul, "/": op.f32Div } as const; + /** By scalar parameter, the f32 local it's converted into once a call, for f32 arithmetic; and where that goes. */ + const f32Scalars = new Map(); + let f32ScalarsAt = 0; + /** + * A value as an f32: f32 arithmetic in f32 instructions, an f32 field loaded as one, a literal as its f32; anything + * else computed as an f64 and converted. + */ + const emitF32Value = (expression: Expression): void => { + if (!hoisted.has(expression)) { + if (expression.kind === "binary" && expression.operator in f32Arithmetic && f32Step(expression)) { + emitF32Value(expression.left); + emitF32Value(expression.right); + code.push(f32Arithmetic[expression.operator as keyof typeof f32Arithmetic]); + return; + } + if (expression.kind === "column" && columns[expression.column].view === "f32" && !columns[expression.column].boolean + && !registers.has(expression.column) && (lane === null || !vectorRegisters.has(expression.column))) { + address(expression.column); + code.push(op.f32Load, 2, ...unsigned(columnOffset(expression.column))); + return; + } + if (expression.kind === "number") { + code.push(op.f32Const, ...float32(expression.value)); + return; + } + if ((expression.kind === "resource" || expression.kind === "args" || expression.kind === "shared") && typeOf(expression) === "number") { + const parameter = scalarParameter(scalarOf(scalarOfExpression(expression))); + let converted = f32Scalars.get(parameter); + if (converted === undefined) f32Scalars.set(parameter, converted = { parameter, local: scratch(f32Type) }); + code.push(op.localGet, ...unsigned(converted.local)); + return; + } + if (expression.kind === "unary" && expression.operator === "-" && f32Operand(expression.operand)) { + emitF32Value(expression.operand); + code.push(op.f32Neg); + return; + } + } + emit(expression); + code.push(op.f32DemoteF64); + }; + /** An f32 operand, converted to f32 where it isn't one already. */ + const emitF32 = (expression: Expression): void => { + emit(expression); + if (!floatExact(expression)) code.push(op.f32DemoteF64, op.f64PromoteF32); + }; + // ---- Typed array resources, read and written in place at their elements. ---- /** Each typed array's loads and stores by its elements' type, with their alignment's log2. */ @@ -1842,10 +1956,11 @@ export const generateWasmOrReason = ( if (integer) emitToInt32(); } else if (integer) emitInteger(value); + else if (view === "f32") emitF32Value(value); else emit(value); const memory = (align: number): number[] => [align, ...unsigned(offset)]; switch (view) { - case "f32": code.push(op.f32DemoteF64, op.f32Store, ...memory(2)); return; + case "f32": code.push(op.f32Store, ...memory(2)); return; case "i32": case "u32": code.push(op.i32Store, ...memory(2)); return; case "u8": code.push(op.i32Store8, ...memory(0)); return; default: code.push(op.f64Store, ...memory(3)); return; @@ -2662,7 +2777,7 @@ export const generateWasmOrReason = ( const vop = { load: 0, store: 11, const: 12, shuffle: 13, i32Splat: 17, f32Splat: 19, f64Splat: 20, i32ExtractLane: 27, i32ReplaceLane: 28, i32Eq: 55, i32Ne: 56, i32LtS: 57, i32LtU: 58, i32GtS: 59, i32GtU: 60, i32LeS: 61, i32LeU: 62, i32GeS: 63, i32GeU: 64, xor: 81, - f32ExtractLane: 31, f32ReplaceLane: 32, i32TruncSatF32S: 248, f32ConvertI32S: 250, f32ConvertI32U: 251, + f32ExtractLane: 31, f32ReplaceLane: 32, f64ReplaceLane: 34, i32TruncSatF32S: 248, f32ConvertI32S: 250, f32ConvertI32U: 251, i32Neg: 161, i32Shl: 171, i32ShrS: 172, i32ShrU: 173, i32Add: 174, i32Sub: 177, i32Mul: 181, i32MinS: 182, i32MinU: 183, i32MaxS: 184, i32MaxU: 185, i64x2ExtmulLowI32x4S: 220, i64x2ExtmulHighI32x4S: 221, i64x2ExtmulLowI32x4U: 222, i64x2ExtmulHighI32x4U: 223, f32Eq: 65, f32Ne: 66, f32Lt: 67, f32Gt: 68, f32Le: 69, f32Ge: 70, @@ -2673,10 +2788,21 @@ export const generateWasmOrReason = ( f32Abs: 224, f32Neg: 225, f32Sqrt: 227, f32Add: 228, f32Sub: 229, f32Mul: 230, f32Div: 231, f32Min: 232, f32Max: 233, f64Abs: 236, f64Neg: 237, f64Sqrt: 239, f64Add: 240, f64Sub: 241, f64Mul: 242, f64Div: 243, f64Min: 244, f64Max: 245, } as const; + /** + * The float leaves lanes hold: f64 when every float field is an f64, which lanes then load, compute and store as + * they're stored; otherwise f32. + */ + const fields = columns.filter(column => column.component >= 0 && !column.boolean && (column.view === "f32" || column.view === "f64")); + const storageView: "f32" | "f64" = fields.length > 0 && fields.every(column => column.view === "f64") ? "f64" : "f32"; + const storage64 = storageView === "f64"; + /** Bytes of one stored float leaf. */ + const leafBytes = storage64 ? 8 : 4; /** f64 lanes: each vector holds two values, each operation the f64 one, so lanes compute as the scalar path does. */ - const wide = !storagePrecision; - /** Bytes of f32 storage one vector covers: four lanes, or two promoted to f64. */ - const laneBytes = wide ? 8 : 16; + const wide = !storagePrecision || storage64; + /** Values one vector holds. */ + const vectorLanes = wide ? 2 : 4; + /** Bytes of storage one vector covers: four f32 lanes, two f32s promoted to f64, or two f64s. */ + const laneBytes = vectorLanes * leafBytes; const float32 = (value: number): number[] => [...new Uint8Array(new Float32Array([value]).buffer)]; const vectorConstant = (values: readonly number[]): number[] => wide ? [...simd(vop.const), ...[0, 1].flatMap(lane => float64(values[lane] ?? 0))] @@ -2694,12 +2820,14 @@ export const generateWasmOrReason = ( : { "<": vop.f32Lt, ">": vop.f32Gt, "<=": vop.f32Le, ">=": vop.f32Ge, "==": vop.f32Eq, "!=": vop.f32Ne, "===": vop.f32Eq, "!==": vop.f32Ne }; /** Loads the vector of f32 storage at the address on the stack plus `offset`, as lanes. */ const loadLanes = (offset: number): void => { - if (wide) code.push(...simd(vop.load64Zero), 2, ...unsigned(offset), ...simd(vop.f64PromoteLowF32)); + if (storage64) code.push(...simd(vop.load), 3, ...unsigned(offset)); + else if (wide) code.push(...simd(vop.load64Zero), 2, ...unsigned(offset), ...simd(vop.f64PromoteLowF32)); else code.push(...simd(vop.load), 2, ...unsigned(offset)); }; /** Stores lanes, on the stack after the address, to f32 storage at that address plus `offset`. */ const storeLanes = (offset: number): void => { - if (wide) code.push(...simd(vop.f32DemoteF64Zero), ...simd(vop.store64Lane), 2, ...unsigned(offset), 0); + if (storage64) code.push(...simd(vop.store), 3, ...unsigned(offset)); + else if (wide) code.push(...simd(vop.f32DemoteF64Zero), ...simd(vop.store64Lane), 2, ...unsigned(offset), 0); else code.push(...simd(vop.store), 2, ...unsigned(offset)); }; @@ -2732,6 +2860,53 @@ export const generateWasmOrReason = ( /** The mask of the enclosing `if`s, or null outside any. */ let mask: number | null = null; + /** With f64 lanes over four rows, the mask of the last two, `mask` holding the first two's; null otherwise. */ + let maskHigh: number | null = null; + /** + * In a filtered kernel's groups of rows: by block and chunk column, an i32 local set where a group of the current + * block stamped a row, stamped once its groups are done; null outside them. + */ + let filtered: { readonly pending: Map } | null = null; + /** + * Eight rows' masks from the row local, where any filter's row tick is newer than `lastRun`, as f64x2 vectors of two + * rows each; then an `if` that runs what follows only where one of them passes, which the caller ends. + */ + const filterEight = (): number[] => { + const halves = [0, 1, 2, 3].map(half => { + for (let filter = 0; filter < filters; filter++) { + code.push(op.localGet, ...unsigned(filterRowParameter(filter)), op.localGet, ...unsigned(rowLocal), op.i32Const, 3, op.i32Shl, op.i32Add); + code.push(...simd(vop.load), 3, ...unsigned(16 * half), op.localGet, 3, ...simd(vop.f64Splat), ...simd(vop.f64Gt)); + if (filter > 0) code.push(...simd(vop.or)); + } + const vector = scratch(v128Type); + code.push(op.localSet, ...unsigned(vector)); + return vector; + }); + // Eight rows none of passes are skipped whole: a branch rows mostly take the same way, where changes are dense or sparse. + code.push(op.localGet, ...unsigned(halves[0])); + for (const half of halves.slice(1)) code.push(op.localGet, ...unsigned(half), ...simd(vop.or)); + code.push(...simd(vop.anyTrue), op.if, 0x40); + return halves; + }; + /** The masks of `count` rows from the `first` of eight, as vectors of rows: f32 lanes' four rows in one, f64 lanes' two rows a vector. */ + const groupMasks = (halves: readonly number[], first: number, count: number): number[] => { + const own = halves.slice(first / 2, (first + count) / 2); + if (wide) return own; + // Each row's 64-bit lane to a 32-bit one. + const rows = scratch(v128Type); + code.push(op.localGet, ...unsigned(own[0]), op.localGet, ...unsigned(own[1]), ...simd(vop.shuffle), 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27, op.localSet, ...unsigned(rows)); + return [rows]; + }; + /** Eight rows from the row local, a group of `count` at a time by `group`, under the masks of the rows that pass. */ + const filteredEight = (count: number, group: (masks: readonly number[]) => void): void => { + const halves = filterEight(); + for (let first = 0; first < 8; first += count) { + if (first > 0) code.push(op.localGet, ...unsigned(rowLocal), op.i32Const, count, op.i32Add, op.localSet, ...unsigned(rowLocal)); + group(groupMasks(halves, first, count)); + } + code.push(op.localGet, ...unsigned(rowLocal), op.i32Const, ...signed(-(8 - count)), op.i32Add, op.localSet, ...unsigned(rowLocal)); + code.push(op.end); + }; const rowsLocals: number[] = []; const rowsLocal = (index: number): number => rowsLocals[index] ??= scratch(v128Type); /** Rows a pass of the across-rows loops runs at once, which stamps cover. */ @@ -2739,8 +2914,8 @@ export const generateWasmOrReason = ( const denseAddress = (column: number): void => { const { view, stride, boolean, component } = columns[column]; - if (view !== "f32" || stride !== 4 || boolean || component < 0) throw notVectorizable; - code.push(op.localGet, ...unsigned(columnParameter(column)), op.localGet, ...unsigned(rowLocal), op.i32Const, 4, op.i32Mul, op.i32Add); + if (view !== storageView || stride !== leafBytes || boolean || component < 0) throw notVectorizable; + code.push(op.localGet, ...unsigned(columnParameter(column)), op.localGet, ...unsigned(rowLocal), op.i32Const, leafBytes, op.i32Mul, op.i32Add); }; const vectorTruthy = (type: Type): void => { @@ -2875,13 +3050,27 @@ export const generateWasmOrReason = ( if (mask !== null) { address(); code.push(...simd(vop.load), 3, ...unsigned(16 * half)); - code.push(op.localGet, ...unsigned(mask)); - if (!wide) code.push(...simd(half === 0 ? vop.i64ExtendLowS : vop.i64ExtendHighS)); + // f64 lanes' masks are a lane per row, the second two rows' in `maskHigh`; f32 lanes' are extended. + if (wide) code.push(op.localGet, ...unsigned(half === 1 && maskHigh !== null ? maskHigh : mask)); + else code.push(op.localGet, ...unsigned(mask), ...simd(half === 0 ? vop.i64ExtendLowS : vop.i64ExtendHighS)); code.push(...simd(vop.bitselect)); } code.push(...simd(vop.store), 3, ...unsigned(16 * half)); } } + // Under a filter, groups lie in one block, whose block and chunk are stamped once the block's groups are + // done, if any lane stamped. + if (filtered !== null && mask !== null) { + for (const [dense, shift] of [[current.blocks, blockShift], [current.chunks, chunkShift]] as const) { + if (columns[dense].muted === true) continue; + let pending = filtered.pending.get(dense); + if (pending === undefined) filtered.pending.set(dense, pending = { local: scratch(i32Type), shift }); + code.push(op.localGet, ...unsigned(pending.local), op.localGet, ...unsigned(mask)); + if (maskHigh !== null) code.push(op.localGet, ...unsigned(maskHigh), ...simd(vop.or)); + code.push(...simd(vop.anyTrue), op.i32Or, op.localSet, ...unsigned(pending.local)); + } + return; + } // The group may straddle two chunks or blocks. Under a mask this can stamp one no lane changed, which only costs a scan. stampDense(current.blocks, blockShift, 0); stampDense(current.blocks, blockShift, groupRows - 1); @@ -2920,16 +3109,20 @@ export const generateWasmOrReason = ( /** Rows from `start` in groups of a vector's lanes, up to the last whole group; leaves the row local at the first row not done. */ const rowsLoop = (): void => { - groupRows = laneBytes / 4; + groupRows = vectorLanes; const vectorEnd = scratch(i32Type); code.push(op.localGet, 1, op.localGet, 0, op.i32Sub, op.i32Const, ...signed(-groupRows), op.i32And, op.localGet, 0, op.i32Add, op.localSet, ...unsigned(vectorEnd)); code.push(op.block, 0x40, op.loop, 0x40); code.push(op.localGet, ...unsigned(rowLocal), op.localGet, ...unsigned(vectorEnd), op.i32GeS, op.brIf, 1); mask = null; - for (const current of program.body) rowsStatement(current); + rowsGroup(); code.push(op.localGet, ...unsigned(rowLocal), op.i32Const, ...signed(groupRows), op.i32Add, op.localSet, ...unsigned(rowLocal), op.br, 0); code.push(op.end, op.end); }; + /** One group of a vector's lanes of rows, from the row local, under `mask` if any. */ + const rowsGroup = (): void => { + for (const current of program.body) rowsStatement(current); + }; // ---- Interleaved: four rows at a time, for programs over components of any layout. The 32-bit integer leaves a ---- // component holds within 16 bytes are a span: each row's are one load, transposed into a vector per leaf, and back. @@ -3730,10 +3923,22 @@ export const generateWasmOrReason = ( if (negate) code.push(...simd(vop.not)); } else code.push(op.localGet, ...unsigned(outer), op.localGet, ...unsigned(test), ...simd(negate ? vop.andNot : vop.and)); - // Arms are few operations, so each runs for every group: branching to skip one no row takes mispredicts on mixed rows. code.push(op.localSet, ...unsigned(inner)); mask = inner; + // A few operations run for every group, as branching to skip them mispredicts on mixed rows; an arm + // of more is skipped where no row of the group takes it, as rows taking one way together do. + const skippable = statementsSize(statements) > armsBudget; + const registered = new Set(vectorRegisters.keys()); + if (skippable) code.push(op.localGet, ...unsigned(inner), ...simd(vop.anyTrue), op.if, 0x40); + const own = skippable ? armSpans?.get(statements) : undefined; + for (const load of own?.load ?? []) load(); for (const statement of statements) interleavedStatement(statement); + for (const store of own?.store ?? []) store(); + if (skippable) { + code.push(op.end); + // A register first set in the arm holds nothing where the arm was skipped. + for (const column of [...vectorRegisters.keys()]) if (!registered.has(column)) vectorRegisters.delete(column); + } mask = outer; }; withFacts(current.test, () => branch(current.consequent, false)); @@ -3766,13 +3971,8 @@ export const generateWasmOrReason = ( } }); - /** - * The operations of the `if` arms a group's masks run, every arm some row of it takes: past a few, rows a row at a - * time run only their own and skip the rest, as a rarely taken arm is. - */ + /** The operations an `if` arm of the interleaved loop runs for every group, past which it's skipped where no row takes it. */ const armsBudget = 40; - const armsSize = (statements: readonly Statement[]): number => statements.reduce((total, statement) => - statement.kind === "if" ? total + statementsSize(statement.consequent) + statementsSize(statement.alternate) : total, 0); /** * Rows from `start` in groups of four, up to the last whole group, interleaved; leaves the row local at the first row @@ -3795,7 +3995,7 @@ export const generateWasmOrReason = ( } }; const interleavedGroups = (): void => { - if (!interleavableStatements(program.body) || armsSize(program.body) > armsBudget) throw notVectorizable; + if (!interleavableStatements(program.body)) throw notVectorizable; const used = columnsUsed(program.body, new Set()); const stored = storedColumns(program.body, new Set()); const spans = planSpans(used, stored); @@ -3869,7 +4069,7 @@ export const generateWasmOrReason = ( code.push(op.localSet, ...unsigned(own)); } for (const [column, own] of addresses) rowAddresses.set(column, own); - spans.forEach((span, s) => { + const loadSpan = (span: Span, s: number): void => { const { rows, leaves } = spanVectors[s]; const own = addresses.get(span.owner) ?? 0; if (span.packed) { @@ -3888,7 +4088,20 @@ export const generateWasmOrReason = ( vectorRegisters.set(column, leaves[leaf]); spanned.add(column); } + }; + // A span only a skippable arm uses is loaded, and stored back, in the arm, which groups no row of takes skip. + const homes = spans.map(span => spanHome([...span.lanes.keys()])); + spans.forEach((span, s) => { if (homes[s] === null) loadSpan(span, s); }); + const inArms = new Map void)[]; readonly store: (() => void)[] }>(); + spans.forEach((span, s) => { + const home = homes[s]; + if (home === null || home === undefined) return; + const entry = inArms.get(home) ?? { load: [], store: [] }; + entry.load.push(() => loadSpan(span, s)); + entry.store.push(() => storeSpan(span, s)); + inArms.set(home, entry); }); + armSpans = inArms; mask = null; // Each span's four loads and eight shuffles, and back, or a store a lane for each leaf stored; a packed span's // loads, a vector each, and the shuffles picking its leaves, and back. @@ -3900,7 +4113,14 @@ export const generateWasmOrReason = ( } // Four rows one at a time, as the scalar loop runs them, must cost clearly more. if (work.spent > 0.7 * 4 * statementsSize(program.body)) throw notVectorizable; - spans.forEach((span, s) => { + spans.forEach((span, s) => { if (homes[s] === null) storeSpan(span, s); }); + armSpans = null; + code.push(op.localGet, ...unsigned(rowLocal), op.i32Const, 4, op.i32Add, op.localSet, ...unsigned(rowLocal), op.br, 0); + code.push(op.end, op.end); + code.splice(invariants.at, 0, ...invariants.code); + invariants = null; + /** Stores a span's stored leaves back from their vectors: up front's after the body, an arm's as it closes. */ + function storeSpan(span: Span, s: number): void { const { rows, leaves } = spanVectors[s]; const own = addresses.get(span.owner) ?? 0; const written = [...span.lanes].filter(([column]) => stored.has(column)); @@ -3937,11 +4157,37 @@ export const generateWasmOrReason = ( for (const [column, leaf] of written) { for (let k = 0; k < 4; k++) code.push(op.localGet, ...unsigned(own), op.localGet, ...unsigned(leaves[leaf]), ...simd(vop.store32Lane), 2, ...unsigned(columns[column].offset + k * span.stride), k); } - }); - code.push(op.localGet, ...unsigned(rowLocal), op.i32Const, 4, op.i32Add, op.localSet, ...unsigned(rowLocal), op.br, 0); - code.push(op.end, op.end); - code.splice(invariants.at, 0, ...invariants.code); - invariants = null; + } + }; + /** By skippable arm, what loads its spans at its start and stores them back at its end; null outside the interleaved loop. */ + let armSpans: ReadonlyMap void)[]; readonly store: readonly (() => void)[] }> | null = null; + /** + * The innermost skippable arm holding every use of `leaves` outside an `if` test, which a span of them is loaded in; + * null for one used outside every skippable arm. + */ + const spanHome = (leaves: readonly number[]): readonly Statement[] | null => { + let common: (readonly Statement[])[] | undefined; + const use = (chain: readonly (readonly Statement[])[]): void => { + if (common === undefined) common = [...chain]; + else { + let k = 0; + while (k < common.length && k < chain.length && common[k] === chain[k]) k++; + common.length = k; + } + }; + const reads = (statements: readonly Statement[]): boolean => [...columnsUsed(statements, new Set())].some(column => leaves.includes(column)); + const visit = (statements: readonly Statement[], chain: readonly (readonly Statement[])[]): void => { + for (const statement of statements) { + if (statement.kind !== "if") { + if (reads([statement])) use(chain); + continue; + } + if (reads([{ kind: "if", test: statement.test, consequent: [], alternate: [] }])) use(chain); + for (const arm of [statement.consequent, statement.alternate]) visit(arm, statementsSize(arm) > armsBudget ? [...chain, arm] : chain); + } + }; + visit(program.body, []); + return common === undefined || common.length === 0 ? null : common[common.length - 1] ?? null; }; // ---- Within a row (SLP): statements over a component's leaves that match lane for lane become one f32x4 operation. ---- @@ -3957,19 +4203,20 @@ export const generateWasmOrReason = ( | { readonly kind: "math"; readonly name: string; readonly arguments: readonly VectorExpression[] }; /** Snapshot locals that hold a component's leaves, loaded as one vector at the first of their `set`s. */ type Pack = { readonly first: number; readonly column: number; readonly window: Window; readonly lanes: Map; used: boolean; local: number }; - type Group = { readonly length: number; readonly column: number; readonly window: Window; readonly value: VectorExpression }; + /** Consecutive stores fused into one vector expression; `stored` has each lane of `window` a store writes, the rest kept. */ + type Group = { readonly length: number; readonly column: number; readonly window: Window; readonly value: VectorExpression; readonly stored: readonly boolean[] }; /** f32 leaves of one component, as consecutive lanes from the lowest offset; null if they can't be. */ const windowOf = (laneColumns: readonly number[]): Window | null => { const infos = laneColumns.map(column => columns[column]); const first = infos[0]; - if (first === undefined || infos.some(info => info.view !== "f32" || info.boolean || info.component !== first.component || info.component < 0)) return null; + if (first === undefined || infos.some(info => info.view !== storageView || info.boolean || info.component !== first.component || info.component < 0)) return null; const base = Math.min(...infos.map(info => info.offset)); - const lanes = infos.map(info => (info.offset - base) / 4); + const lanes = infos.map(info => (info.offset - base) / leafBytes); if (lanes.some(lane => lane > 3) || new Set(lanes).size !== lanes.length) return null; return { component: first.component, base, lanes: Math.max(...lanes) + 1 }; }; - const laneIn = (window: Window, column: number): number => (columns[column].offset - window.base) / 4; + const laneIn = (window: Window, column: number): number => (columns[column].offset - window.base) / leafBytes; const elementAddress = (column: number): void => { code.push(op.localGet, ...unsigned(columnParameter(column)), op.localGet, ...unsigned(rowLocal), op.i32Const, ...signed(columns[column].stride), op.i32Mul, op.i32Add); @@ -3995,7 +4242,11 @@ export const generateWasmOrReason = ( }; /** Plans the fusion of top-level statements. Statement index to group, and which `set`s only feed groups. */ - const planLanes = (): { readonly groups: ReadonlyMap; readonly packs: ReadonlyMap; readonly skipped: ReadonlySet } => { + /** + * With `whole`, for the across-elements loop, a group's window is its stores' component's whole element, and lanes + * no store writes are kept. + */ + const planLanes = (whole = false): { readonly groups: ReadonlyMap; readonly packs: ReadonlyMap; readonly skipped: ReadonlySet } => { const body = program.body; const assignments = new Map(); const uses = new Map(); @@ -4044,7 +4295,7 @@ export const generateWasmOrReason = ( body.forEach((statement, index) => { if (statement.kind === "set" && statement.value.kind === "column" && assignments.get(statement.local) === 1) { const info = columns[statement.value.column]; - if (info.view === "f32" && !info.boolean && info.component >= 0) { + if (info.view === storageView && !info.boolean && info.component >= 0) { const pending = open.get(info.component) ?? { first: index, columns: [], locals: [] }; open.set(info.component, pending); pending.columns.push(statement.value.column); @@ -4079,44 +4330,56 @@ export const generateWasmOrReason = ( }; const groupUses = new Map(); /** Matches one expression per lane; null if they don't line up. */ - const match = (lanes: readonly Expression[]): VectorExpression | null => { - const first = lanes[0]; - if (lanes.every(lane => JSON.stringify(lane) === JSON.stringify(first))) return { kind: "splat", expression: first }; - if (lanes.every(lane => lane.kind === "number")) return { kind: "constant", values: lanes.map(lane => lane.kind === "number" ? lane.value : 0) }; + /** Matches one expression per lane, a lane no store writes undefined; null if they don't line up. */ + const match = (lanes: readonly (Expression | undefined)[]): VectorExpression | null => { + const defined = lanes.flatMap((lane, i) => lane === undefined ? [] : [{ lane, i }]); + const first = defined[0]?.lane; + if (first === undefined) return null; + /** Each lane's part by `part`, undefined where the lane is or where `part` gives undefined; null if any defined lane has none. */ + const parts = (part: (lane: Expression) => Expression | undefined): (Expression | undefined)[] | null => { + const result = lanes.map(lane => lane === undefined ? undefined : part(lane)); + return defined.every(({ i }) => result[i] !== undefined) ? result : null; + }; + if (defined.every(({ lane }) => JSON.stringify(lane) === JSON.stringify(first))) return { kind: "splat", expression: first }; + if (defined.every(({ lane }) => lane.kind === "number")) return { kind: "constant", values: lanes.map(lane => lane?.kind === "number" ? lane.value : 0) }; if (first.kind === "local") { const pack = packOfLocal.get(first.local); - if (pack !== undefined && lanes.every((lane, i) => lane.kind === "local" && packOfLocal.get(lane.local) === pack && pack.lanes.get(lane.local) === i)) { - for (const lane of lanes) if (lane.kind === "local") groupUses.set(lane.local, (groupUses.get(lane.local) ?? 0) + 1); + if (pack !== undefined && defined.every(({ lane, i }) => lane.kind === "local" && packOfLocal.get(lane.local) === pack && pack.lanes.get(lane.local) === i)) { + for (const { lane } of defined) if (lane.kind === "local") groupUses.set(lane.local, (groupUses.get(lane.local) ?? 0) + 1); return { kind: "pack", pack }; } return null; } if (first.kind === "column") { - const laneColumns = lanes.flatMap(lane => lane.kind === "column" ? [lane.column] : []); - const window = laneColumns.length === lanes.length ? windowOf(laneColumns) : null; - return window !== null && laneColumns.every((column, i) => laneIn(window, column) === i) ? { kind: "load", column: laneColumns[0], window } : null; + const laneColumns = defined.flatMap(({ lane }) => lane.kind === "column" ? [lane.column] : []); + const window = laneColumns.length === defined.length ? windowOf(laneColumns) : null; + if (window === null) return null; + // The window starts where its lane 0 is, whether or not a store reads it. + const base = columns[laneColumns[0]].offset - (defined[0]?.i ?? 0) * leafBytes; + const placed: Window = { component: window.component, base, lanes: Math.max(window.lanes, lanes.length) }; + return base >= 0 && laneColumns.every((column, k) => laneIn(placed, column) === defined[k]?.i) ? { kind: "load", column: laneColumns[0], window: placed } : null; } if (first.kind === "binary" && isArithmetic(first.operator)) { const { operator } = first; - const pairs = lanes.flatMap(lane => lane.kind === "binary" && lane.operator === operator ? [lane] : []); - if (pairs.length !== lanes.length) return null; - const left = match(pairs.map(pair => pair.left)); - const right = left === null ? null : match(pairs.map(pair => pair.right)); + const lefts = parts(lane => lane.kind === "binary" && lane.operator === operator ? lane.left : undefined); + const rights = parts(lane => lane.kind === "binary" && lane.operator === operator ? lane.right : undefined); + if (lefts === null || rights === null) return null; + const left = match(lefts); + const right = left === null ? null : match(rights); return left === null || right === null ? null : { kind: "binary", operator, left, right }; } if (first.kind === "unary" && (first.operator === "-" || first.operator === "+")) { const operator = first.operator; - const operands = lanes.flatMap(lane => lane.kind === "unary" && lane.operator === operator ? [lane.operand] : []); - if (operands.length !== lanes.length) return null; + const operands = parts(lane => lane.kind === "unary" && lane.operator === operator ? lane.operand : undefined); + if (operands === null) return null; const operand = match(operands); return operand === null ? null : operator === "-" ? { kind: "negate", operand } : operand; } if (first.kind === "math" && vectorMath(first.name, first.arguments.length)) { - const calls = lanes.flatMap(lane => lane.kind === "math" && lane.name === first.name && lane.arguments.length === first.arguments.length ? [lane] : []); - if (calls.length !== lanes.length) return null; const parameters: VectorExpression[] = []; for (let i = 0; i < first.arguments.length; i++) { - const parameter = match(calls.map(call => call.arguments[i])); + const lanesOfParameter = parts(lane => lane.kind === "math" && lane.name === first.name && lane.arguments.length === first.arguments.length ? lane.arguments[i] : undefined); + const parameter = lanesOfParameter === null ? null : match(lanesOfParameter); if (parameter === null) return null; parameters.push(parameter); } @@ -4144,13 +4407,17 @@ export const generateWasmOrReason = ( end++; } const stores = body.slice(index, end).flatMap(store => store.kind === "store" ? [store] : []); - const window = stores.length >= 2 ? windowOf(stores.map(store => store.column)) : null; - const lanes: Expression[] = []; - if (window !== null && window.lanes === stores.length) for (const store of stores) lanes[laneIn(window, store.column)] = store.value; + const found = stores.length >= (whole ? 1 : 2) ? windowOf(stores.map(store => store.column)) : null; + const stride = columns[statement.column].stride; + const window: Window | null = found === null ? null + : !whole ? (found.lanes === stores.length ? found : null) + : stride % leafBytes === 0 && found.base + found.lanes * leafBytes <= stride ? { component: found.component, base: 0, lanes: stride / leafBytes } : null; + const lanes: (Expression | undefined)[] = Array.from({ length: window?.lanes ?? 0 }, () => undefined); + if (window !== null) for (const store of stores) lanes[laneIn(window, store.column)] = store.value; const before = new Map(groupUses); - const value = window !== null && window.lanes === stores.length && !readsEarlierStore(stores) ? match(lanes) : null; + const value = window !== null && !readsEarlierStore(stores) ? match(lanes) : null; if (window !== null && value !== null) { - groups.set(index, { length: stores.length, column: stores[0].column, window, value }); + groups.set(index, { length: stores.length, column: stores[0].column, window, value, stored: lanes.map(lane => lane !== undefined) }); const markUsed = (expression: VectorExpression): void => { if (expression.kind === "pack") expression.pack.used = true; else if (expression.kind === "binary") { markUsed(expression.left); markUsed(expression.right); } @@ -4304,14 +4571,24 @@ export const generateWasmOrReason = ( * same leaf in every operand. Snapshot sets must be skipped, and stamps run as in the across-rows loop. */ const acrossElements = ({ groups, skipped }: LanePlan): boolean => { - if (filters > 0 || groups.size === 0) return false; + if (groups.size === 0) return false; const whole = (column: number, window: Window, stride: number): boolean => window.base === 0 && columns[column].stride === stride; + const assignments = new Map(); + const countSets = (statements: readonly Statement[]): void => { + for (const statement of statements) { + if (statement.kind === "set") assignments.set(statement.local, (assignments.get(statement.local) ?? 0) + 1); + else if (statement.kind === "if") { countSets(statement.consequent); countSets(statement.alternate); } + else if (statement.kind === "block" || statement.kind === "loop") countSets(statement.body); + } + }; + countSets(program.body); + const rowLocals = new Set(); const fits = (expression: VectorExpression, stride: number): boolean => { switch (expression.kind) { case "pack": return whole(expression.pack.column, expression.pack.window, stride); case "load": return whole(expression.column, expression.window, stride); case "constant": return true; - case "splat": return rowIndependent(expression.expression); + case "splat": return rowIndependent(expression.expression) || spreadable(expression.expression, rowLocals); case "binary": return fits(expression.left, stride) && fits(expression.right, stride); case "negate": return fits(expression.operand, stride); case "math": return expression.arguments.every(parameter => fits(parameter, stride)); @@ -4322,14 +4599,125 @@ export const generateWasmOrReason = ( const group = groups.get(index); if (group !== undefined) { const { stride } = columns[group.column]; - if (group.window.base !== 0 || group.window.lanes * 4 !== stride || !fits(group.value, stride)) return false; + if (group.window.base !== 0 || group.window.lanes * leafBytes !== stride || !fits(group.value, stride)) return false; index += group.length - 1; + continue; + } + const statement = body[index]; + if (skipped.has(index) || statement.kind === "stamp") continue; + // A local assigned once a value of the row, computed four rows at a time. + if (statement.kind === "set" && assignments.get(statement.local) === 1 && spreadable(statement.value, rowLocals)) { + rowLocals.add(statement.local); + continue; } - else if (!skipped.has(index) && body[index].kind !== "stamp") return false; + return false; } return true; }; + /** + * Whether a value of one row computes four rows at a time, as vectors of rows: arithmetic on float leaves of row + * columns, constants and locals in `rowLocals`. + */ + const spreadable = (expression: Expression, rowLocals: ReadonlySet): boolean => { + switch (expression.kind) { + case "number": case "resource": case "args": case "shared": return true; + case "local": return rowLocals.has(expression.local); + case "column": { + const { view, boolean, component } = columns[expression.column]; + return view === storageView && !boolean && component >= 0; + } + case "unary": return (expression.operator === "-" || expression.operator === "+") && spreadable(expression.operand, rowLocals); + case "binary": return isArithmetic(expression.operator) && spreadable(expression.left, rowLocals) && spreadable(expression.right, rowLocals); + case "math": return vectorMath(expression.name, expression.arguments.length) && expression.arguments.every(argument => spreadable(argument, rowLocals)); + default: return false; + } + }; + /** Vectors of the four rows' values of per-row locals the across-elements loop computed, by local: one, or two of f64 lanes. */ + const rowVectors = new Map(); + /** Rows `vectorLanes * part` on of the group's four, the value of each in a lane. */ + const emitRows = (expression: Expression, part: number): void => { + switch (expression.kind) { + case "number": case "resource": case "args": case "shared": return emitSplat(expression); + case "local": { + const vectors = rowVectors.get(expression.local); + if (vectors === undefined) throw new Error("A per-row local is read before it's computed."); + code.push(op.localGet, ...unsigned(vectors[part])); + return; + } + case "column": { + const { stride, offset } = columns[expression.column]; + const first = vectorLanes * part; + if (stride === leafBytes) { + elementAddress(expression.column); + loadLanes(offset + first * leafBytes); + return; + } + for (let lane = 0; lane < vectorLanes; lane++) { + elementAddress(expression.column); + const at = unsigned(offset + (first + lane) * stride); + if (storage64) code.push(op.f64Load, 3, ...at); + else code.push(op.f32Load, 2, ...at); + if (wide && !storage64) code.push(op.f64PromoteF32); + if (lane === 0) code.push(...simd(wide ? vop.f64Splat : vop.f32Splat)); + else code.push(...simd(wide ? vop.f64ReplaceLane : vop.f32ReplaceLane), lane); + } + return; + } + case "unary": + emitRows(expression.operand, part); + if (expression.operator === "-") code.push(...simd(negateVector)); + return; + case "binary": + if (!isArithmetic(expression.operator)) throw notVectorizable; + emitRows(expression.left, part); + emitRows(expression.right, part); + code.push(...simd(arithmeticVector[expression.operator])); + return; + case "math": + for (const argument of expression.arguments) emitRows(argument, part); + emitVectorMath(expression.name, expression.arguments.length); + return; + default: throw notVectorizable; + } + }; + /** The group's four rows of a value, in a local per vector of rows. */ + const rowsOf = (expression: Expression): number[] => Array.from({ length: 4 / vectorLanes }, (_, part) => { + emitRows(expression, part); + const vector = scratch(v128Type); + code.push(op.localSet, ...unsigned(vector)); + return vector; + }); + /** + * Vector `vector` of `stride`-byte elements whose every leaf is its row's value in `rows`: each lane the value of the + * row its leaf is in, shuffled from the one or two vectors of rows holding them. + */ + const spread = (rows: readonly number[], vector: number, stride: number): void => { + const leaves = stride / leafBytes; + const laneSize = 16 / vectorLanes; + const sources = Array.from({ length: vectorLanes }, (_, lane) => Math.floor((vector * vectorLanes + lane) / leaves)); + const first = Math.floor(sources[0] / vectorLanes); + const pattern = sources.flatMap(row => { + const base = (Math.floor(row / vectorLanes) === first ? 0 : 16) + (row % vectorLanes) * laneSize; + return Array.from({ length: laneSize }, (_, byte) => base + byte); + }); + code.push(op.localGet, ...unsigned(rows[first]), op.localGet, ...unsigned(rows[Math.min(first + 1, rows.length - 1)]), ...simd(vop.shuffle), ...pattern); + }; + /** By the value it spreads, in the group being emitted, its vectors of rows. */ + const spreads = new Map(); + /** Computes the rows of each row-dependent value a group's vector expression spreads, before its stores. */ + const prepareSpreads = (expression: VectorExpression): void => { + switch (expression.kind) { + case "splat": + if (!rowIndependent(expression.expression) && !spreads.has(JSON.stringify(expression.expression))) spreads.set(JSON.stringify(expression.expression), rowsOf(expression.expression)); + return; + case "binary": prepareSpreads(expression.left); return prepareSpreads(expression.right); + case "negate": return prepareSpreads(expression.operand); + case "math": return expression.arguments.forEach(prepareSpreads); + default: return; + } + }; + /** Vector `vector` of an expression over four rows of `stride`-byte elements; packs are in `packVectors`. */ const emitElementExpression = (expression: VectorExpression, vector: number, stride: number, packVectors: ReadonlyMap): void => { switch (expression.kind) { @@ -4344,8 +4732,12 @@ export const generateWasmOrReason = ( elementAddress(expression.column); loadLanes(laneBytes * vector); return; - case "constant": code.push(...vectorConstant([0, 1, 2, 3].map(lane => expression.values[((laneBytes * vector + 4 * lane) % stride) / 4] ?? 0))); return; - case "splat": return emitSplat(expression.expression); + case "constant": code.push(...vectorConstant([0, 1, 2, 3].map(lane => expression.values[((laneBytes * vector + leafBytes * lane) % stride) / leafBytes] ?? 0))); return; + case "splat": { + const rows = spreads.get(JSON.stringify(expression.expression)); + if (rows === undefined) return emitSplat(expression.expression); + return spread(rows, vector, stride); + } case "binary": emitElementExpression(expression.left, vector, stride, packVectors); emitElementExpression(expression.right, vector, stride, packVectors); @@ -4367,14 +4759,23 @@ export const generateWasmOrReason = ( * operations and stores; leaves the row local at the first row not done. Vectors stay inside the four rows' elements, * and each vector's store only touches bytes no other vector reads. */ - const elementsLoop = ({ groups, packs }: LanePlan): void => { + const elementsLoop = ({ groups, packs, skipped: skippedSets }: LanePlan): void => { groupRows = 4; - const vectors = (stride: number): number => 4 * stride / laneBytes; const vectorEnd = scratch(i32Type); code.push(op.localGet, 1, op.localGet, 0, op.i32Sub, op.i32Const, ...signed(-4), op.i32And, op.localGet, 0, op.i32Add, op.localSet, ...unsigned(vectorEnd)); code.push(op.block, 0x40, op.loop, 0x40); code.push(op.localGet, ...unsigned(rowLocal), op.localGet, ...unsigned(vectorEnd), op.i32GeS, op.brIf, 1); mask = null; + elementsGroup({ groups, packs, skipped: skippedSets }, null); + code.push(op.localGet, ...unsigned(rowLocal), op.i32Const, 4, op.i32Add, op.localSet, ...unsigned(rowLocal), op.br, 0); + code.push(op.end, op.end); + }; + /** + * Four rows' elements from the row local. `rows` is the rows' mask, in vectors of rows as `rowsOf` gives values: + * where set, the row's leaves are stored and its stamps set; elsewhere they keep what they hold. + */ + const elementsGroup = ({ groups, packs, skipped: skippedSets }: LanePlan, rows: readonly number[] | null): void => { + const vectors = (stride: number): number => 4 * stride / laneBytes; const packVectors = new Map(); const body = program.body; for (let index = 0; index < body.length; index++) { @@ -4392,20 +4793,43 @@ export const generateWasmOrReason = ( const group = groups.get(index); if (group !== undefined) { const { stride } = columns[group.column]; + spreads.clear(); + prepareSpreads(group.value); for (let vector = 0; vector < vectors(stride); vector++) { + // By lane, whether a store writes its leaf. + const written = Array.from({ length: vectorLanes }, (_, lane) => group.stored[((laneBytes * vector + leafBytes * lane) % stride) / leafBytes] === true); + if (!written.includes(true)) continue; const value = scratch(v128Type); emitElementExpression(group.value, vector, stride, packVectors); + if (written.includes(false) || rows !== null) { + elementAddress(group.column); + loadLanes(laneBytes * vector); + if (written.includes(false)) code.push(...simd(vop.const), ...written.flatMap(lane => new Array(16 / vectorLanes).fill(lane ? 0xff : 0))); + if (rows !== null) { + spread(rows, vector, stride); + if (written.includes(false)) code.push(...simd(vop.and)); + } + code.push(...simd(vop.bitselect)); + } code.push(op.localSet, ...unsigned(value)); elementAddress(group.column); code.push(op.localGet, ...unsigned(value)); storeLanes(laneBytes * vector); } index += group.length - 1; + continue; + } + const statement = body[index]; + if (statement.kind === "stamp") { + groupRows = 4; + mask = rows?.[0] ?? null; + maskHigh = rows?.[1] ?? null; + rowsStatement(statement); + mask = maskHigh = null; } - else if (body[index].kind === "stamp") rowsStatement(body[index]); + else if (statement.kind === "set" && !skippedSets.has(index)) rowVectors.set(statement.local, rowsOf(statement.value)); } - code.push(op.localGet, ...unsigned(rowLocal), op.i32Const, 4, op.i32Add, op.localSet, ...unsigned(rowLocal), op.br, 0); - code.push(op.end, op.end); + rowVectors.clear(); }; try { @@ -4521,6 +4945,8 @@ export const generateWasmOrReason = ( localBase = partialsParameter + (accumulators.length > 0 ? 1 : 0); rowLocal = scratch(i32Type); code.push(op.localGet, 0, op.localSet, ...unsigned(rowLocal)); + f32Scalars.clear(); + f32ScalarsAt = code.length; hoisted.clear(); hoist(program.body); convertArrayParameters(); @@ -4545,13 +4971,19 @@ export const generateWasmOrReason = ( if (indexParameters > 0) convertIndexParameters(); stampRangeChunks(); if (filters > 0) startChunksAndBlocks(); - if (mode === "rows") rowsLoop(); + /** With change filters, emits one group of rows from the row local, where a run of passing blocks holds one. */ + let filteredGroup: { readonly rows: number; readonly emit: () => void } | null = null; + if (mode === "rows") { + if (filters > 0) filteredGroup = { rows: 8, emit: () => filteredEight(vectorLanes, masks => { groupRows = vectorLanes; mask = masks[0] ?? null; rowsGroup(); mask = null; }) }; + else rowsLoop(); + } if (mode === "interleaved") interleavedLoop(); let across = false; if (mode === "lanes") { - const plan = planLanes(); + const plan = planLanes(true); across = acrossElements(plan); - if (across) elementsLoop(plan); + if (across && filters > 0) filteredGroup = { rows: 8, emit: () => filteredEight(4, masks => elementsGroup(plan, masks)) }; + else if (across) elementsLoop(plan); else if (acrossOnly) throw notVectorizable; } // for (; row < end; row++) { block next { body } }, where with `up` the row and its parent's are rows[n] and parents[n]. @@ -4602,7 +5034,30 @@ export const generateWasmOrReason = ( code.push(op.localGet, ...unsigned(upParameter(0)), op.localGet, ...unsigned(slot), op.i32Const, 2, op.i32Shl, op.i32Add, op.i32Load, 2, 0, op.localSet, ...unsigned(rowLocal)); code.push(op.localGet, ...unsigned(upParameter(1)), op.localGet, ...unsigned(slot), op.i32Const, 2, op.i32Shl, op.i32Add, op.i32Load, 2, 0, op.localSet, ...unsigned(parentLocal)); } - if (filters > 0 && simdEnabled && !upMode) skipEights(); + if (filters > 0 && simdEnabled && !upMode && filteredGroup === null) skipEights(); + // At a row a whole group starts from, aligned so a group lies in one block, the group runs under the + // rows' mask of passing filters, branch-free; other rows run one at a time. + if (filters > 0 && filteredGroup !== null) { + const { rows: count } = filteredGroup; + filtered = { pending: new Map() }; + code.push(...get(rowLocal), op.i32Const, count - 1, op.i32And, op.i32Eqz); + code.push(...get(rowLocal), op.i32Const, count, op.i32Add, ...get(blockEnd), op.i32LeS, op.i32And, op.if, 0x40); + filteredGroup.emit(); + code.push(...get(rowLocal), op.i32Const, count, op.i32Add, op.localSet, ...unsigned(rowLocal)); + // Once its block's groups are done, a block and its chunk are stamped where a group stamped a row. + if (filtered.pending.size > 0) { + code.push(...get(rowLocal), op.i32Const, ...signed(2 ** blockShift - 1), op.i32And, op.i32Eqz); + code.push(...get(rowLocal), op.i32Const, count, op.i32Add, ...get(blockEnd), op.i32GtS, op.i32Or, op.if, 0x40); + for (const [dense, { local: pending, shift }] of filtered.pending) { + code.push(...get(pending), op.if, 0x40); + code.push(op.localGet, ...unsigned(columnParameter(dense)), ...get(rowLocal), op.i32Const, 1, op.i32Sub, op.i32Const, ...signed(shift), op.i32ShrU, op.i32Const, 3, op.i32Shl, op.i32Add, op.localGet, 2, op.f64Store, 3, 0); + code.push(op.i32Const, 0, op.localSet, ...unsigned(pending), op.end); + } + code.push(op.end); + } + filtered = null; + code.push(op.br, 1, op.end); + } code.push(op.block, 0x40); // A row that no filter passes goes to the next. if (filters > 0) { @@ -4616,7 +5071,7 @@ export const generateWasmOrReason = ( if (!scalarRows) { setAddresses(); for (const { column, own } of addressLocals) rowAddresses.set(column, own); - fused = emitLaneBody(); + fused = emitLaneBody() || across; rowAddresses.clear(); } else { @@ -4658,6 +5113,8 @@ export const generateWasmOrReason = ( accumulators.forEach((accumulator, k) => { code.push(op.localGet, ...unsigned(partialsParameter), op.localGet, ...unsigned(local(accumulator)), op.f64Store, 3, ...unsigned(8 * k)); }); + // Each value the same for every row that f32 arithmetic reads, converted once a call, before the rows. + code.splice(f32ScalarsAt, 0, ...[...f32Scalars.values()].flatMap(({ parameter, local: own }) => [op.localGet, ...unsigned(parameter), op.f32DemoteF64, op.localSet, ...unsigned(own)])); // The function's end. code.push(op.end); }; @@ -4666,10 +5123,13 @@ export const generateWasmOrReason = ( // Listed rows aren't consecutive, so `up` programs run one row at a time. // Within a row, f64 lanes would split a component's leaves across vectors, so filtered kernels at the body's // precision run one row at a time. - let mode: Mode = !simdEnabled || accumulators.length > 0 || upMode || (wide && filters > 0) ? "scalar" : filters > 0 ? "lanes" : "rows"; + let mode: Mode = !simdEnabled || accumulators.length > 0 || upMode ? "scalar" : "rows"; // A SIMD mode throws `notVectorizable` for a program it can't run, and the next is tried. // Whole elements across rows, where the plan covers the body, outrun interleaved rows, which outrun fusing within rows. - const candidates: readonly (readonly [Mode, boolean])[] = mode === "rows" ? [["rows", false], ["lanes", true], ["interleaved", false], ["lanes", false]] : [[mode, false]]; + // Filtered rows run across rows under the mask of those passing, or fuse within each row. + const candidates: readonly (readonly [Mode, boolean])[] = mode === "scalar" ? [[mode, false]] + : filters > 0 ? [["rows", false], ["lanes", true], ["lanes", false]] + : [["rows", false], ["lanes", true], ["interleaved", false], ["lanes", false]]; for (let k = 0; k < candidates.length; k++) { [mode, acrossOnly] = candidates[k] ?? ["scalar", false]; try { @@ -4737,7 +5197,7 @@ export const generateWasmOrReason = ( ...section(10, vector([[...unsigned(body.length), ...body]])), ...named ? nameSection() : [], ]); - return { bytes, scalars, imports, vectorized }; + return { bytes, scalars, imports, vectorized, lanes: !vectorized ? null : mode === "interleaved" ? "interleaved" : wide ? "f64" : "f32" }; } catch (error) { const reason = typeof error === "object" && error !== null ? reasons.get(error) : undefined; diff --git a/ecs/packages/ecs/src/interface/system/declaration.ts b/ecs/packages/ecs/src/interface/system/declaration.ts index 1b7a1fc8..104cc4a2 100644 --- a/ecs/packages/ecs/src/interface/system/declaration.ts +++ b/ecs/packages/ecs/src/interface/system/declaration.ts @@ -16,13 +16,14 @@ import type { OwnTrait } from './sync-system-declaration.js'; export type Declaration = { /** * Whether its body compiles to a kernel, a function the build compiles to run on every matched row, in parallel, on - * the kernel pool. Values in `components` and `lookup` must be structs and resources read-only. + * the kernel pool. Values in `components` and `lookup` must be structs and resources read-only. As WASM, a kernel + * computes at storage precision: arithmetic on values of fields declared `F32` rounds each step to f32, as SIMD lanes + * do, and on values of fields declared `I32` or `U32` wraps at 32 bits, as the integers they're stored as do, so its + * results may differ from the body as written; `number` fields compute in f64. Its JS kernel, which runs where WASM + * can't, computes as written. * - Without it, a system with components compiles when its body is in the kernel subset and its declaration allows - * it, and otherwise runs as written, computing as the body as written does. A system without components runs once, - * as written. - * - `true`: compiles, or the build fails saying why. Its arithmetic may round each step to storage precision, as - * WASM's f32 SIMD lanes do, and wraps at 32 bits on values of fields declared `I32` or `U32`, as the integers - * they're stored as do, so its results may differ from the body as written. + * it, and otherwise runs as written. A system without components runs once, as written. + * - `true`: compiles, or the build fails saying why. * - `false`: runs as written, on its thread. * - `"gpu"`: also has no lookups, change filters, commands or loops, and only 4-byte scalar values, its `up` * included. It runs as a compute shader in a world with a GPU, and as a kernel on the pool in one without. Every diff --git a/ecs/packages/ecs/src/perftest/benchmarks.ts b/ecs/packages/ecs/src/perftest/benchmarks.ts index b0824c30..90e28772 100644 --- a/ecs/packages/ecs/src/perftest/benchmarks.ts +++ b/ecs/packages/ecs/src/perftest/benchmarks.ts @@ -3,7 +3,7 @@ import type { Component } from "../interface/component/component.js"; import type { Entity } from "../interface/entity/entity.js"; import { World } from "../interface/world/world.js"; import { enabled as flatEnabled, spawnFlat, spawnFlatDynamic, visible as flatVisible } from "./flat.js"; -import { enabled, fastest as particlesFastest, move, position as particlePosition, spawn, visible } from "./particles.js"; +import { enabled, fastest as particlesFastest, integrate, integrate64, integrateChanged, move, nudgeHalf, position as particlePosition, spawn, spawn64, visible } from "./particles.js"; import { forest, local as hierarchyLocal, nudge, parent as hierarchyParent, propagate, propagateChanged, reparent, sprout, turnover, under } from "./hierarchy.js"; import * as structural from "./structural.js"; import { chain, churn, emit, failing, fastest, follow, highest, hits, idle, idles, idleObserver, index, indexSum, observe, poke, pokeCluster, reduce, retag, seeded, small, smalls, spawnOne, tag, totalOf } from "./suite.js"; @@ -339,6 +339,52 @@ export const benchmarks: readonly Benchmark[] = [ return minimum; }, }, + { + name: "integrate", + operation: "A kernel adding each row's velocity, scaled by its mass and the time step, to its position, through nested vec3 calls and without `kernel: true`: Euler integration.", + per: "matched rows", + n: 250_000, + typical: [1_000, 1_000_000], + best: { bytes: 40, basis: "Each row reads 12 bytes of velocity and 4 of mass, and reads and writes 12 bytes of position." }, + run: async () => { + const world = inline(); + await world.run(spawn, { count: 1_000_000 }); + const { minimum } = await particlesFastest(() => world.run(integrate, { delta: 1 / 60 })); + await world.dispose(); + return minimum; + }, + }, + { + name: "integrate changed half", + operation: "`integrate` filtered on `changed` velocity, after a scattered half of the rows changed: per-row updates reacting to edits no branch predicts.", + per: "matched rows", + n: 250_000, + typical: [1_000, 1_000_000], + best: { bytes: 48, basis: "Each row reads its 8-byte velocity tick, 12 bytes of velocity and 4 of mass, and reads and writes 12 bytes of position." }, + run: async () => { + const world = inline(); + await world.run(spawn, { count: 1_000_000 }); + let round = 0; + const minimum = await after(() => world.run(nudgeHalf, { z: round++ % 2 }), () => world.run(integrateChanged)); + await world.dispose(); + return minimum; + }, + }, + { + name: "integrate f64", + operation: "`integrate` over f64 position, velocity and mass, which compute in f64.", + per: "matched rows", + n: 250_000, + typical: [1_000, 1_000_000], + best: { bytes: 80, basis: "Each row reads 24 bytes of velocity and 8 of mass, and reads and writes 24 bytes of position." }, + run: async () => { + const world = inline(); + await world.run(spawn64, { count: 250_000 }); + const { minimum } = await particlesFastest(() => world.run(integrate64, { delta: 1 / 60 })); + await world.dispose(); + return minimum; + }, + }, { name: "move watched", operation: "`move` with a changes system watching position, told each run that rows wrote it: what a coarse signal of row writes costs a per-row update.", diff --git a/ecs/packages/ecs/src/perftest/particles.ts b/ecs/packages/ecs/src/perftest/particles.ts index 7b00ceae..08b0f3d6 100644 --- a/ecs/packages/ecs/src/perftest/particles.ts +++ b/ecs/packages/ecs/src/perftest/particles.ts @@ -1,12 +1,11 @@ // © 2026 Adobe. MIT License. See /LICENSE for details. import type { Schema } from "../interface/schema/schema.js"; import { System } from "../interface/system/system.js"; -import type { F32, U32 } from "../interface/math/index.js"; +import { Vec3, type F32, type U32 } from "../interface/math/index.js"; // Mirrors adobe/data's ecs1/ecs2 perftests (packages/data/src/perftest): 1M particles split evenly across // 4 archetypes by visible/enabled; move adds velocity to position for the visible and enabled quarter. -type Vec3 = readonly [number, number, number]; const vec3 = { type: "array", items: { type: "number", precision: 1 }, minItems: 3, maxItems: 3 } as const satisfies Schema; const color = Symbol("perf/color"); @@ -15,6 +14,10 @@ export const position = Symbol("perf/position"); const velocity = Symbol("perf/velocity"); export const visible = Symbol("perf/visible"); export const enabled = Symbol("perf/enabled"); +const position64 = Symbol("perf/position64"); +const velocity64 = Symbol("perf/velocity64"); +const mass64 = Symbol("perf/mass64"); +const step = Symbol("perf/step"); declare module "@adobe/ecs" { export interface Components { @@ -24,6 +27,12 @@ declare module "@adobe/ecs" { [velocity]: { type: Schema.Type<{ type: "array"; items: { type: "number"; precision: 1 }; minItems: 3; maxItems: 3 }> }; [visible]: { type: true }; [enabled]: { type: true }; + [position64]: { type: [number, number, number] }; + [velocity64]: { type: [number, number, number] }; + [mass64]: { type: number }; + } + export interface Resources { + [step]: { type: number; default: 0.016 }; } } @@ -53,6 +62,47 @@ export const move = System.create({ row[position] = [px + vx, py + vy, pz + vz]; }); +/** + * Euler integration as the guide writes it, with no `kernel` flag: velocity scaled by each row's mass and the step, added + * to position, through nested calls. + */ +export const integrate = System.create({ + components: { with: [velocity, position, mass, visible, enabled] }, +}, (row, _context, input: { readonly delta: number }) => { + row[position] = Vec3.add(row[position], Vec3.scale(row[velocity], row[mass] * input.delta)); +}); + +/** `integrate` for the rows whose velocity changed since it last ran. */ +export const integrateChanged = System.create({ + components: { with: [velocity, position, mass, visible, enabled], changed: [velocity] }, +}, (row, { resources }) => { + row[position] = Vec3.add(row[position], Vec3.scale(row[velocity], row[mass] * resources[step])); +}); + +/** Writes the velocity of a scattered half of the rows, by a hash of each entity: changes no branch predicts. */ +export const nudgeHalf = System.create({ + kernel: true, + components: { with: [velocity, visible, enabled] }, +}, (row, _context, input: { readonly z: number }) => { + const hashed = Math.imul(row.entity ^ (row.entity >>> 16), 0x45d9f3b); + if (((hashed ^ (hashed >>> 16)) & 1) === 0) row[velocity] = [row[velocity][0], row[velocity][1], input.z]; +}); + +/** Particles of f64 position, velocity and mass. */ +export const spawn64 = System.create({}, ({ commands }, input: { readonly count: number }) => { + for (let i = 0; i < input.count; i++) commands.spawn([position64, velocity64, mass64])({ [position64]: [i + 1, i + 1, i + 1], [velocity64]: [-i, -i, -i], [mass64]: 10 }); +}); + +/** `integrate` over f64 components. */ +export const integrate64 = System.create({ + components: { with: [velocity64, position64, mass64] }, +}, (row, _context, input: { readonly delta: number }) => { + const [px, py, pz] = row[position64]; + const [vx, vy, vz] = row[velocity64]; + const step = row[mass64] * input.delta; + row[position64] = [px + vx * step, py + vy * step, pz + vz * step]; +}); + /** Fastest of repeated runs within a time budget, like the adobe/data harness. */ export const fastest = async (run: () => Promise, budget = 1000): Promise<{ readonly minimum: number; readonly passes: number }> => { for (let warm = 0; warm < 20; warm++) await run();