[GH-ISSUE #7341] Density functions: fuse pure-arithmetic subgraphs into flat op-list samplers #3214

Open
opened 2026-11-03 04:06:43 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @socksprox on GitHub (Nov 2, 2026).
Original GitHub issue: https://github.com/horizon-rust/horizon/issues/7341

Originally assigned to: @socksprox on GitHub.

🤖 Filed by socksprox's AI agent (Devin, SWE-2 High), not by socksprox personally.

Fused evaluation path for compiled density functions — design for review

DensityCompiler::compile_raw (crates/horizon-core/src/density/graph/compiler.rs) lowers each GraphNode to an Arc<dyn DensitySampler> node. At generation time the hot path is bulk: final_density.sample_volume(context, density, volume) in crates/horizon-world/src/worldgen/terrain.rs (and the same pattern in generator.rs, climate.rs, aquifer/noise_based.rs, material_condition/density.rs). Every interior node in that tree costs a virtual call, a full pass over the volume buffer, and usually a SamplerContext::with_buffer scratch buffer for its sibling operand. Vanilla overworld trees stack many arithmetic nodes above each noise/cache leaf, so most of the bulk-eval time is buffer traffic and dispatch, not arithmetic.

Proposal: after optimize()/prepare(), flatten maximal runs of pure-arithmetic compiled samplers into one FusedSampler that evaluates a small op list. This is a design-level change; filing to align before implementing.

Fusible set

Pointwise arithmetic only: UnarySampler (all UnaryOp), BinarySampler (BinaryOp), PowerSampler, RoundSampler (with and without multiple), LerpSampler (incl. DensityValue::Constant endpoints), RangeChoiceSampler, ConstantSampler. Possibly IntervalSelectSampler (bulk evaluates every branch eagerly, so it can fuse if all branches do).

Leaves / boundaries: NoiseSampler, ShiftedNoiseSampler, GradientSampler, DistanceToPointSampler, offset/blended/end-islands/world-field samplers, SliceSampler, SplineSampler, CachingDensitySampler (bound cache entries), InterpolatedSampler, FindTopSurfaceSampler, BlendDensitySampler. Their sample_volume fills an operand slot that the op list consumes.

Bit-exactness constraints found while reading the code

These are why this needs a design pass rather than a mechanical rewrite:

  • Scalar vs bulk semantics differ per node. sample_value uses java_min/java_max (NaN and signed-zero rules); the bulk paths use plain comparisons (arithmetic.rs). A fused region must keep both semantics: bulk ops in the volume loop, java ops in sample_value.
  • Scalar short-circuits are observable. BinarySampler::sample_value skips the right child on left == 0.0 (mul/div) and on the baked min/max bounds; LerpSampler skips a branch on alpha 0/1; RangeChoice/IntervalSelect evaluate only the selected branch scalar-side but all branches bulk-side. Skipping suppresses child errors (ZeroGradientPeriod, RecursiveCache) and cache-cell population — observable, not just perf.
  • Buffer contract differs per node. check_buffer (≥) vs check_exact_buffer (==). In-place spine nodes propagate the caller's buffer contract; the fused sampler's requirement is the strictest along the output spine (e.g. Unary(Binary) → exact).
  • Tail behavior is observable. UnaryOp::apply_bulk runs over the whole caller buffer including cells past volume.size(); BinaryOp::apply_bulk zips against a volume-sized scratch and leaves the tail untouched; ConstantSampler::sample_volume fills the tail. The parity corpus already probes oversized buffers (tools/test_density_parity.py volume queries with iteration % 3), so this is checked.
  • Leaf evaluation order must be preserved (post-order, matching the tree — including RangeChoice's in-range→input→outside bulk order) so error ordering and context side effects (cache cells, plane retention) stay identical.
  • Standard float rules: jmath calls stay (log, pow), no FMA, no reassociation, evaluation order fixed at compile time.

Sketch

Fusion runs as a post-pass on the Arc<dyn DensitySampler> tree produced by compile_raw — at get_sampler output and at prepare's per-cache compilation — so DensityGraph interning/equality is untouched. Each FusedSampler holds leaves: Vec<Arc<dyn DensitySampler>> plus a post-order Vec<FusedOp> (Leaf(i), Const(f32), Unary(UnaryOp), Binary(BinaryOp), Power, Round{..}, Lerp, RangeChoice{..}), a buffer-contract flag, and per-op notes on whether the op applies to the full caller buffer or only volume.size() cells. Only regions of ≥2 ops fuse; smaller runs keep the existing nodes.

For sample_value, two options: (a) delegate to the retained subtree (simplest, keeps lazy semantics for free), or (b) evaluate the op list with per-node subtree-span records so short-circuits jump past skipped operand programs. I'd start with (a) — the documented win is bulk — unless you'd rather have one mechanism for both.

The existing tree stays intact underneath: fused samplers wrap, never replace, so a debug/env escape hatch and incremental rollout are trivial.

Verification

  • crates/horizon-core/src/bin/density_parity.rs + tools/test_density_parity.py is the oracle — bit-for-bit over the corpus (all node kinds, scalar + bulk + oversized buffers). Extend with fused-region-heavy graphs if coverage needs it.
  • A Rust unit test evaluating identical random graphs through tree vs fused for signal between harness runs.
  • worldgen_parity/datapack_worldgen_parity end-to-end; a before/after chunk-gen timing to confirm the win (which bench driver do you prefer for this?).

Questions for the maintainer

  1. Fuse inside compile_raw/get_sampler as sketched, or do you want it modeled as a GraphNode/rewrite pass instead (changes interning surface, seems unnecessary)?
  2. Scalar path: delegate to the subtree (option a) OK for v1?
  3. Should fusion be unconditional, or behind a DensityCompiler flag while it beds in?
Originally created by @socksprox on GitHub (Nov 2, 2026). Original GitHub issue: https://github.com/horizon-rust/horizon/issues/7341 Originally assigned to: @socksprox on GitHub. > 🤖 Filed by socksprox's AI agent (Devin, SWE-2 High), not by socksprox personally. ## Fused evaluation path for compiled density functions — design for review `DensityCompiler::compile_raw` (`crates/horizon-core/src/density/graph/compiler.rs`) lowers each `GraphNode` to an `Arc<dyn DensitySampler>` node. At generation time the hot path is bulk: `final_density.sample_volume(context, density, volume)` in `crates/horizon-world/src/worldgen/terrain.rs` (and the same pattern in `generator.rs`, `climate.rs`, `aquifer/noise_based.rs`, `material_condition/density.rs`). Every interior node in that tree costs a virtual call, a full pass over the volume buffer, and usually a `SamplerContext::with_buffer` scratch buffer for its sibling operand. Vanilla overworld trees stack many arithmetic nodes above each noise/cache leaf, so most of the bulk-eval time is buffer traffic and dispatch, not arithmetic. Proposal: after `optimize()`/`prepare()`, flatten maximal runs of pure-arithmetic compiled samplers into one `FusedSampler` that evaluates a small op list. This is a design-level change; filing to align before implementing. ### Fusible set Pointwise arithmetic only: `UnarySampler` (all `UnaryOp`), `BinarySampler` (`BinaryOp`), `PowerSampler`, `RoundSampler` (with and without multiple), `LerpSampler` (incl. `DensityValue::Constant` endpoints), `RangeChoiceSampler`, `ConstantSampler`. Possibly `IntervalSelectSampler` (bulk evaluates every branch eagerly, so it can fuse if all branches do). Leaves / boundaries: `NoiseSampler`, `ShiftedNoiseSampler`, `GradientSampler`, `DistanceToPointSampler`, offset/blended/end-islands/world-field samplers, `SliceSampler`, `SplineSampler`, `CachingDensitySampler` (bound cache entries), `InterpolatedSampler`, `FindTopSurfaceSampler`, `BlendDensitySampler`. Their `sample_volume` fills an operand slot that the op list consumes. ### Bit-exactness constraints found while reading the code These are why this needs a design pass rather than a mechanical rewrite: - **Scalar vs bulk semantics differ per node.** `sample_value` uses `java_min`/`java_max` (NaN and signed-zero rules); the bulk paths use plain comparisons (`arithmetic.rs`). A fused region must keep both semantics: bulk ops in the volume loop, java ops in `sample_value`. - **Scalar short-circuits are observable.** `BinarySampler::sample_value` skips the right child on `left == 0.0` (mul/div) and on the baked min/max bounds; `LerpSampler` skips a branch on alpha 0/1; `RangeChoice`/`IntervalSelect` evaluate only the selected branch scalar-side but all branches bulk-side. Skipping suppresses child errors (`ZeroGradientPeriod`, `RecursiveCache`) and cache-cell population — observable, not just perf. - **Buffer contract differs per node.** `check_buffer` (≥) vs `check_exact_buffer` (==). In-place spine nodes propagate the caller's buffer contract; the fused sampler's requirement is the strictest along the output spine (e.g. `Unary(Binary)` → exact). - **Tail behavior is observable.** `UnaryOp::apply_bulk` runs over the *whole* caller buffer including cells past `volume.size()`; `BinaryOp::apply_bulk` zips against a volume-sized scratch and leaves the tail untouched; `ConstantSampler::sample_volume` fills the tail. The parity corpus already probes oversized buffers (`tools/test_density_parity.py` volume queries with `iteration % 3`), so this is checked. - **Leaf evaluation order must be preserved** (post-order, matching the tree — including `RangeChoice`'s in-range→input→outside bulk order) so error ordering and context side effects (cache cells, plane retention) stay identical. - Standard float rules: `jmath` calls stay (`log`, `pow`), no FMA, no reassociation, evaluation order fixed at compile time. ### Sketch Fusion runs as a post-pass on the `Arc<dyn DensitySampler>` tree produced by `compile_raw` — at `get_sampler` output and at `prepare`'s per-cache compilation — so `DensityGraph` interning/equality is untouched. Each `FusedSampler` holds `leaves: Vec<Arc<dyn DensitySampler>>` plus a post-order `Vec<FusedOp>` (`Leaf(i)`, `Const(f32)`, `Unary(UnaryOp)`, `Binary(BinaryOp)`, `Power`, `Round{..}`, `Lerp`, `RangeChoice{..}`), a buffer-contract flag, and per-op notes on whether the op applies to the full caller buffer or only `volume.size()` cells. Only regions of ≥2 ops fuse; smaller runs keep the existing nodes. For `sample_value`, two options: (a) delegate to the retained subtree (simplest, keeps lazy semantics for free), or (b) evaluate the op list with per-node subtree-span records so short-circuits jump past skipped operand programs. I'd start with (a) — the documented win is bulk — unless you'd rather have one mechanism for both. The existing tree stays intact underneath: fused samplers wrap, never replace, so a debug/env escape hatch and incremental rollout are trivial. ### Verification - `crates/horizon-core/src/bin/density_parity.rs` + `tools/test_density_parity.py` is the oracle — bit-for-bit over the corpus (all node kinds, scalar + bulk + oversized buffers). Extend with fused-region-heavy graphs if coverage needs it. - A Rust unit test evaluating identical random graphs through tree vs fused for signal between harness runs. - `worldgen_parity`/`datapack_worldgen_parity` end-to-end; a before/after chunk-gen timing to confirm the win (which bench driver do you prefer for this?). ### Questions for the maintainer 1. Fuse inside `compile_raw`/`get_sampler` as sketched, or do you want it modeled as a `GraphNode`/rewrite pass instead (changes interning surface, seems unnecessary)? 2. Scalar path: delegate to the subtree (option a) OK for v1? 3. Should fusion be unconditional, or behind a `DensityCompiler` flag while it beds in?
Author
Owner

@socksprox commented on GitHub (Nov 2, 2026):

🤖 Agent: /claim

<!-- gh-comment-id:6579927571 --> @socksprox commented on GitHub (Nov 2, 2026): 🤖 Agent: /claim
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
horizon-rust/horizon#3214
No description provided.