Preserve weighted component products through loop accumulation

This commit is contained in:
chasse20 committed 2026-11-22 10:18:32 -05:00
1 parent b16c6044ae
commit 100ddcf055
4 files changed
+114 -7

No files matched your search

+25 -5
View File
@@ -22,6 +22,26 @@ impl Source {
Self { calls: Vec::new(), factors, components: [0, 0], operation: Operation::Multiply }
}
fn live_for_sum(&self, program: &Program, loops: &[usize], sum: usize) -> bool {
if loops.is_empty() {
return true;
}
if !self.calls.is_empty() {
return false;
}
let mut inside = false;
for &index in loops {
let members = &program.instructions[index].control_registers;
if members.binary_search(&sum).is_ok() {
inside = true;
} else if self.factors.iter().any(|factor| members.binary_search(factor).is_ok()) {
// A separate loop can clear a factor while the packed vector still holds its old value.
return false;
}
}
inside
}
pub(super) fn factors<'a>(&self, mut state: &'a EvaluationState) -> Result<(&'a Value, &'a Value), String> {
for call in &self.calls {
state = state.calls.get(call).ok_or("missing evaluated product call")?;
@@ -127,13 +147,11 @@ pub(super) fn forwarded<T: Copy>(op: &Instruction, instructions: &[Instruction],
pub(super) fn identify(program: &mut Program, mut returned: BTreeMap<usize, Lanes>) -> Lanes {
let empty = || std::array::from_fn(|_| None);
// Loop iterations invalidate individual registers. Only retain factors for straight-line lifetimes.
if program.instructions.iter().any(|op| op.definition.id == "while")
|| (returned.is_empty() && !program.instructions.iter().any(|op| op.product_operation().is_some() && float_width(op.type_code) > 0 && !op.literal))
{
if returned.is_empty() && !program.instructions.iter().any(|op| op.product_operation().is_some() && float_width(op.type_code) > 0 && !op.literal) {
return empty();
}
let loops: Vec<_> = program.instructions.iter().enumerate().filter_map(|(i, op)| (op.definition.id == "while").then_some(i)).collect();
let mut origins: Vec<Origins> = Vec::with_capacity(program.instructions.len());
let mut products: Vec<(Source, usize)> = Vec::new();
let mut sums = Vec::new();
@@ -193,6 +211,8 @@ pub(super) fn identify(program: &mut Program, mut returned: BTreeMap<usize, Lane
let (source, uses) = products.get(id?)?;
(*uses == 0).then(|| source.clone())
});
// A caller cannot retain registers that the callee's last loop iteration may have cleared.
let exported = if loops.is_empty() { exported } else { empty() };
for id in output.into_iter().flatten() {
if let Some((_, uses)) = products.get_mut(id) {
*uses += 1;
@@ -204,7 +224,7 @@ pub(super) fn identify(program: &mut Program, mut returned: BTreeMap<usize, Lane
sides.iter().enumerate().find_map(|(side, lanes)| {
let id = lanes.get(i).copied().flatten()?;
let (source, uses) = products.get(id)?;
(*uses == 1).then(|| Term { source: source.clone(), on_right: side == 1 })
(*uses == 1 && source.live_for_sum(program, &loops, index)).then(|| Term { source: source.clone(), on_right: side == 1 })
})
});
if terms.iter().any(Option::is_some)
+46
View File
@@ -2514,3 +2514,49 @@ fn unconnected_ifelse_condition_stays_boolean_and_empty_branches_keep_declared_t
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float2([0.0; 2]));
}
}
#[test]
fn packed_loop_products_keep_the_factors_from_the_current_iteration() {
let [r, g, b, weight] = [21.0_f32, 89.0, 149.0, 99.0].map(|code| code / 255.0);
let variables = BTreeMap::from([("color".into(), Value::Float3([r, g, b])), ("weight".into(), Value::Float(weight))]);
let context = EvaluationContext {
scope: super::FunctionScope::PixelProcessor,
position: [0.5; 2],
size: [1.0; 2],
images: &[],
image_formats: &[],
tile: true,
variables: &variables,
};
for nested_read in [false, true] {
let mut graph = FunctionGraph::default();
let name = Some(Value::Text("total".into()));
let zero = graph.add_constant(Value::Float(0.0));
let never = graph.add_constant(Value::Bool(false));
let start = graph.add_constant(Value::Float4([0.0; 4]));
let initialize = graph.add("set", &[start], name.clone());
let color = graph.add("get_float3", &[], Some(Value::Text("color".into())));
let scale = graph.add("get_float1", &[], Some(Value::Text("weight".into())));
let weighted = graph.add("mulscalar", &[color, scale], None);
let term = graph.add("vector4", &[weighted, scale], None);
let mut previous = graph.add("get_float4", &[], name.clone());
if nested_read {
// This inner loop clears the scale register after the vector has been packed.
let inner = graph.add("while", &[zero, never, scale], Some(Value::Int(1)));
previous = graph.add("sequence", &[inner, previous], None);
}
let sum = graph.add("add", &[term, previous], None);
let store = graph.add("set", &[sum], name.clone());
let body = graph.add("sequence", &[store, zero], None);
let repeat = graph.add("while", &[initialize, never, body], Some(Value::Int(256)));
let total = graph.add("get_float4", &[], name);
graph.output = Some(graph.add("sequence", &[repeat, total], None));
let Value::Float4(actual) = compile(&graph, 0).unwrap().evaluate_pixel(&context, &mut EvaluationState::default()).unwrap() else {
panic!("expected a four-component sum");
};
let [x, y, z] =
[r, g, b].map(|component| (0..256).fold(0.0_f32, |sum, _| if nested_read { component * weight + sum } else { component.mul_add(weight, sum) }));
let alpha = (0..256).fold(0.0_f32, |sum, _| sum + weight);
assert_eq!(actual.map(f32::to_bits), [x, y, z, alpha].map(f32::to_bits), "nested read {nested_read}");
}
}
+41
View File
@@ -610,6 +610,47 @@ Add the following settings. Render U16 and F32 at each size, and add U8 and F16
| 64 × 32 | 235512 | 235513 | 5 | .8125 | .1875 |
| 32 × 64 | 235534 | 235535 | 2 | .15625 | .046875 |
### Weighted color accumulation in the palette iteration
The K-means iteration root matches all 135,168 RGBA pixels in 33 distinct whole-root settings on one and eight processors. All ten MaterialCraft saves reopen to their original 40,960 pixels in both applications and agree across applications. The output palette is 256 × 16 at every input size. Maximum channel error is zero for every measured format.
| Root and comparison | U8 exact / total · max | U16 exact / total · max | F16 exact / total · max | F32 exact / total · max |
|---|---:|---:|---:|---:|
| One or eight processors | 16,384/16,384 · 0 | 32,768/32,768 · 0 | 20,480/20,480 · 0 | 65,536/65,536 · 0 |
| Saved packages, one processor | 4,096/4,096 · 0 | 12,288/12,288 · 0 | 4,096/4,096 · 0 | 20,480/20,480 · 0 |
The first difference was in the weighted RGB sum over each 256-sample row. The two input images and the 256² classification map already agreed bit for bit. The function multiplies each RGB component by its weight, packs the three products with a fourth weight component, then adds that vector to the running total. Preserving the product through packing allows a single F32 rounding per RGB addition. The evaluator uses these factors within the current iteration when each factor survives until the sum. A nested loop that clears a factor uses the previously stored vector value. The fourth component follows ordinary F32 addition.
| Stage | 32² input before | 64² input before | 32² input after | 64² input after |
|---|---:|---:|---:|---:|
| Weighted rows | 65,416/65,536 · 3.81469727e−5 | 65,404/65,536 · 1.52587891e−5 | 65,536/65,536 · 0 | 65,536/65,536 · 0 |
| Final palette | 4,080/4,096 · 5.96046448e−8 | 4,080/4,096 · 8.94069672e−8 | 4,096/4,096 · 0 | 4,096/4,096 · 0 |
For the two stage comparisons, use the independent 32² input at seed 113 and the changed 64² setting at seed 42, each with four centroids, the alpha control enabled and color space 1. Read the two source images, classification, weighted rows and final palette in their declared formats. The preceding 19 whole-root settings had 77,776/77,824 exact pixels. The new run matches all 77,824 and reproduces the retained captures. [Original palette settings and fields](#tile-weave-splatter-and-fiber-stage-comparisons)
For a reduction to one centroid, fill the initial 256 × 16 palette with byte RGBA (64,64,64,255). Fill a 16² source with (21,89,149,99), use seed 235133, the alpha control enabled, and color space 0. In the first pixel of each weighted row the reference F32 bit patterns are 4102F577, 420AC0FE, 42684BC8, 42C6C6EC. Rounding the product separately gives 4102F576, 420AC0FF, 42684BCA, 42C6C6EC. A release regression distinguishes the two arithmetic paths and checks the nested-loop case. Across twelve one- and two-color fields, both the independent fused calculation and the corrected evaluator match all 786,432 RGBA pixels in the weighted-row stage. To reproduce the two six-case series, use the following byte colors, splitting two-color fields evenly at the middle column. Cycle through 16², 32 × 16 and 16 × 32. Use seed 235133 + 19j for zero-based row j.
| j | First series | Second series | Alpha control |
|---:|---|---|---|
| 0 | (109,67,213,185) | (21,89,149,99) | On |
| 1 | (179,191,61,103) | (23,103,145,117) | On |
| 2 | (73,149,211,255) | Same | On |
| 3 | (109,67,213,185) | (21,89,149,99) | Off |
| 4 | (192,83,49,193) and (31,177,247,124) | (29,116,167,193) and (31,177,247,124) | On |
| 5 | (220,127,18,79) and (31,177,247,124) | Same | Off |
For the 14 additional whole-root renders, generate source bytes at zero-based (x,y) as (7x+13y+11m, 19x+5y+3xy+m, 3x+53y+7m, 17x+29y+m) modulo 256. The seed palette at column x uses (29x+17m,43x+3m,61x+7m) modulo 256 and alpha 255 across all 16 rows. Use U16 and F32 for every row below and add U8 and F16 for the third and fourth. Save the first and every fourth retained setting, then F32, U16, F16, U8 and F32 respectively from the new rows.
| Source size | Seed | m | Centroids | Alpha control | Color space |
|---|---:|---:|---|---|---|
| 16² | 0 | 3 | Default | Default | Default |
| 32 × 16 | 232039 | 5 | 1 | Default | Default |
| 16 × 32 | 232067 | 7 | 3 | On | 1 |
| 32² | 232091 | 11 | 5 | Off | 0 |
| 64 × 32 | 232123 | 13 | 4 | On | 1 |
The packed-loop regression failed on the original renderer and passed after the change. All 442 release tests in the node and evaluator crates passed, along with formatting, strict workspace Clippy, dependency layers and WebAssembly.
## 2026-11-21 root comparisons
### Connected quadrant depth and amplified spot patterns
+2 -2
View File
@@ -35,7 +35,7 @@ A graph may accept input pins and still be a root under the dependency criterion
Statuses: **Not checked**, **In progress**, **Parity** (exact pixels or typed values for the linked measured cases), or **Too hard** (reason recorded). Function calls do not count as regular graph dependencies.
The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **459 Parity**, **87 In progress** and **0 Too hard**. The November 17–22 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons) · [November 19 measurements](parity-fixes.md#2026-11-19-root-comparisons) · [November 20 measurements](parity-fixes.md#2026-11-20-root-comparisons) · [November 21 measurements](parity-fixes.md#2026-11-21-root-comparisons) · [November 22 measurements](parity-fixes.md#2026-11-22-root-comparisons)
The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **460 Parity**, **86 In progress** and **0 Too hard**. The November 17–22 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons) · [November 19 measurements](parity-fixes.md#2026-11-19-root-comparisons) · [November 20 measurements](parity-fixes.md#2026-11-20-root-comparisons) · [November 21 measurements](parity-fixes.md#2026-11-21-root-comparisons) · [November 22 measurements](parity-fixes.md#2026-11-22-root-comparisons)
[Pattern tiling axes and copy bounds across 215 renders](parity-fixes.md#tiling-axes-and-pattern-copy-bounds) · [Grayscale sampler measurements](parity-fixes.md#grayscale-sampling-of-color-inputs) · [Value sampling across 240 typed comparisons](parity-fixes.md#value-processor-texture-filtering) · [Five saved graphs reopened in the reference](parity-fixes.md#saved-filter-graphs-and-scalar-levels-controls)
@@ -561,7 +561,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug
| [quantize_color.sbs/get_min_max/GetMaxFromAlpha_v2](../assets/sbs/quantize_color.sbs) | 1 | Yes | [Parity · 33 renders, all 36 output pixels exact](parity-fixes.md#alpha-maximum-and-one-texel-reductions) |
| [quantize_color.sbs/get_min_max/GetMaxFromAlpha_v3](../assets/sbs/quantize_color.sbs) | 1 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [quantize_color.sbs/helpers/cdf_pass](../assets/sbs/quantize_color.sbs) | 1 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [quantize_color.sbs/kmeans_iteration](../assets/sbs/quantize_color.sbs) | 2 | Yes | [In progress · 77,776/77,824 whole pixels, first differing stages measured](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) |
| [quantize_color.sbs/kmeans_iteration](../assets/sbs/quantize_color.sbs) | 2 | Yes | [Parity · 33/33 settings and 135,168/135,168 RGBA pixels on each processor count, 10 exact saves](parity-fixes.md#weighted-color-accumulation-in-the-palette-iteration) · [Earlier stage measurements](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) |
| [quantize_color.sbs/modify_color_palette_sub](../assets/sbs/quantize_color.sbs) | 2 | Yes | [Parity · 15,104/15,104 palette entries across 59 distinct settings](parity-fixes.md#modifying-a-256-entry-color-palette) · [Earlier palette measurement](parity-fixes.md#height-distance-texture-mapping-skew-and-weave) |
| [quantize_color.sbs/view_color_palette_sub](../assets/sbs/quantize_color.sbs) | 2 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [radial_blur.sbs/radial_blur_grayscale](../assets/sbs/radial_blur.sbs) | 1 | No | [Parity · 591,616/591,616 pixels across 80 distinct settings](parity-fixes.md#diagonal-mip-selection-on-rotated-rectangular-bitmaps) · [Earlier radial measurements](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [both isolated branches match in all six cases per shape](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) |