Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Measure the native tracer against Cycles 5.3 on lit-interior (#892)

Nguyen Xuan Anba41ac8f82dc
diff --git a/bench/cycles-parity/compare.py b/bench/cycles-parity/compare.py
new file mode 100644
index 00000000..3ceae2c0
--- /dev/null
+++ b/bench/cycles-parity/compare.py
@@ -0,0 +1,373 @@
+"""Compare linear RGB float renders (.npy or .exr) and summarize M0 sample ladders and T_eq."""
+import json
+import math
+import os
+import statistics
+import sys
+
+import numpy
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+REL_MSE_EPSILON = 1e-2
+TILE_GRID_SIZE = 8
+TILE_ELIGIBLE_MEAN_THRESHOLD = 0.01
+TILE_RATIO_TOLERANCE = 0.05
+
+
+def load_linear_rgb_image(image_path):
+ lower_path = image_path.lower()
+ if lower_path.endswith(".npy"):
+ array = numpy.load(image_path)
+ return array.astype(numpy.float64)
+ if lower_path.endswith(".exr"):
+ import OpenEXR
+ with OpenEXR.File(image_path) as exr_file:
+ channels = exr_file.channels()
+ if "RGB" in channels:
+ pixels = channels["RGB"].pixels
+ elif "RGBA" in channels:
+ pixels = channels["RGBA"].pixels[..., :3]
+ else:
+ pixels = numpy.stack([channels[name].pixels for name in ("R", "G", "B")], axis=-1)
+ return pixels.astype(numpy.float64)
+ raise ValueError(f"Unsupported image extension for '{image_path}'. Pass a .npy or .exr file.")
+
+
+def compute_relative_mse(reference_rgb, candidate_rgb):
+ denominator = reference_rgb ** 2 + REL_MSE_EPSILON
+ squared_relative = ((candidate_rgb - reference_rgb) ** 2) / denominator
+ per_pixel = squared_relative.mean(axis=-1).ravel()
+ keep_count = max(1, int(per_pixel.size * 0.9999))
+ trimmed = numpy.partition(per_pixel, keep_count - 1)[:keep_count]
+ clipped_reference = numpy.clip(reference_rgb, 0.0, 1000.0)
+ clipped_candidate = numpy.clip(candidate_rgb, 0.0, 1000.0)
+ clipped_error = ((clipped_candidate - clipped_reference) ** 2) / (clipped_reference ** 2 + REL_MSE_EPSILON)
+ return {
+ "relMse": float(per_pixel.mean()),
+ "relMseClipped1000": float(clipped_error.mean()),
+ "relMseTrimmed": float(trimmed.mean()),
+ }
+
+
+def compute_tile_grid_ratios(reference_rgb, candidate_rgb):
+ row_strips_ref = numpy.array_split(reference_rgb, TILE_GRID_SIZE, axis=0)
+ row_strips_cand = numpy.array_split(candidate_rgb, TILE_GRID_SIZE, axis=0)
+ grid_ratios = []
+ eligible_entries = []
+ for row_index in range(TILE_GRID_SIZE):
+ cols_ref = numpy.array_split(row_strips_ref[row_index], TILE_GRID_SIZE, axis=1)
+ cols_cand = numpy.array_split(row_strips_cand[row_index], TILE_GRID_SIZE, axis=1)
+ row_values = []
+ for column_index in range(TILE_GRID_SIZE):
+ ref_tile = cols_ref[column_index]
+ cand_tile = cols_cand[column_index]
+ ref_mean = float(ref_tile.mean())
+ cand_mean = float(cand_tile.mean())
+ ratio = cand_mean / ref_mean if ref_mean > 0.0 else None
+ row_values.append(round(ratio, 4) if ratio is not None else None)
+ if ref_mean > TILE_ELIGIBLE_MEAN_THRESHOLD and ratio is not None:
+ ref_channels = ref_tile.reshape(-1, 3).mean(axis=0)
+ cand_channels = cand_tile.reshape(-1, 3).mean(axis=0)
+ channel_ratios = [round(float(cand_channels[ch] / max(ref_channels[ch], 1e-9)), 4) for ch in range(3)]
+ eligible_entries.append({
+ "row": row_index,
+ "column": column_index,
+ "ratio": round(ratio, 4),
+ "absDeviation": abs(ratio - 1.0),
+ "referenceMean": round(ref_mean, 5),
+ "candidateMean": round(cand_mean, 5),
+ "channelRatios": channel_ratios,
+ })
+ grid_ratios.append(row_values)
+ ratios_only = [entry["ratio"] for entry in eligible_entries]
+ within_tolerance = [entry for entry in eligible_entries if entry["absDeviation"] <= TILE_RATIO_TOLERANCE]
+ worst_tiles = sorted(eligible_entries, key=lambda entry: entry["absDeviation"], reverse=True)[:8]
+ for entry in worst_tiles:
+ entry.pop("absDeviation", None)
+ return {
+ "gridShape": [TILE_GRID_SIZE, TILE_GRID_SIZE],
+ "eligibleMeanThreshold": TILE_ELIGIBLE_MEAN_THRESHOLD,
+ "eligibleTileCount": len(eligible_entries),
+ "withinFivePercentCount": len(within_tolerance),
+ "outsideFivePercentCount": len(eligible_entries) - len(within_tolerance),
+ "minRatio": round(min(ratios_only), 4) if ratios_only else None,
+ "medianRatio": round(float(statistics.median(ratios_only)), 4) if ratios_only else None,
+ "maxRatio": round(max(ratios_only), 4) if ratios_only else None,
+ "gridRatios": grid_ratios,
+ "worstTiles": worst_tiles,
+ }
+
+
+def compute_part_breakdown(reference_rgb, candidate_rgb, parts_prefix):
+ part_indices = numpy.load(f"{parts_prefix}-parts.npy")
+ with open(f"{parts_prefix}-parts.json", encoding="utf-8") as handle:
+ part_names = json.load(handle)
+ breakdown = []
+ denominator = reference_rgb ** 2 + REL_MSE_EPSILON
+ pixel_rel_mse = (((candidate_rgb - reference_rgb) ** 2) / denominator).mean(axis=-1)
+ for index, part_name in enumerate(part_names, start=1):
+ mask = part_indices == index
+ pixel_count = int(mask.sum())
+ if pixel_count == 0:
+ continue
+ ref_pixels = reference_rgb[mask]
+ cand_pixels = candidate_rgb[mask]
+ ref_mean = ref_pixels.mean(axis=0)
+ cand_mean = cand_pixels.mean(axis=0)
+ ratios = [round(float(cand_mean[ch] / max(ref_mean[ch], 1e-9)), 4) for ch in range(3)]
+ scalar_ratio = float(cand_pixels.mean() / max(ref_pixels.mean(), 1e-9))
+ breakdown.append({
+ "part": part_name,
+ "pixelCount": pixel_count,
+ "relMse": round(float(pixel_rel_mse[mask].mean()), 6),
+ "scalarMeanRatio": round(scalar_ratio, 4),
+ "channelMeanRatio": ratios,
+ "referenceMeanRgb": [round(float(value), 5) for value in ref_mean],
+ "candidateMeanRgb": [round(float(value), 5) for value in cand_mean],
+ })
+ breakdown.sort(key=lambda item: item["relMse"], reverse=True)
+ return breakdown
+
+
+def compare_image_pair(reference_rgb, candidate_rgb, parts_prefix=None):
+ error_metrics = compute_relative_mse(reference_rgb, candidate_rgb)
+ abs_diff = numpy.abs(candidate_rgb - reference_rgb)
+ differing_mask = abs_diff.max(axis=-1) > 0.0
+ ref_mean_channels = reference_rgb.reshape(-1, 3).mean(axis=0)
+ cand_mean_channels = candidate_rgb.reshape(-1, 3).mean(axis=0)
+ channel_ratios = [round(float(cand_mean_channels[ch] / max(ref_mean_channels[ch], 1e-12)), 4) for ch in range(3)]
+ result = {
+ **error_metrics,
+ "differingPixelCount": int(differing_mask.sum()),
+ "totalPixelCount": int(reference_rgb.shape[0] * reference_rgb.shape[1]),
+ "maxAbsDiff": float(abs_diff.max()),
+ "meanAbsDiff": float(abs_diff.mean()),
+ "referenceChannelMean": [round(float(val), 6) for val in ref_mean_channels],
+ "candidateChannelMean": [round(float(val), 6) for val in cand_mean_channels],
+ "channelMeanRatio": channel_ratios,
+ "scalarMeanRatio": round(float(cand_mean_channels.mean() / max(ref_mean_channels.mean(), 1e-12)), 4),
+ "tileGrid8x8": compute_tile_grid_ratios(reference_rgb, candidate_rgb),
+ }
+ if parts_prefix is not None:
+ result["partBreakdown"] = compute_part_breakdown(reference_rgb, candidate_rgb, parts_prefix)
+ return result
+
+
+def fit_asymptotic_bias_model(ladder_points):
+ inverse_samples = numpy.array([1.0 / point["samples"] for point in ladder_points], dtype=numpy.float64)
+ errors = numpy.array([point["relMse"] for point in ladder_points], dtype=numpy.float64)
+ design_matrix = numpy.column_stack([numpy.ones_like(inverse_samples), inverse_samples])
+ coefficients, _, _, _ = numpy.linalg.lstsq(design_matrix, errors, rcond=None)
+ asymptotic_bias = float(coefficients[0])
+ variance_slope = float(coefficients[1])
+ predicted = asymptotic_bias + variance_slope * inverse_samples
+ residual_rmse = float(numpy.sqrt(numpy.mean((errors - predicted) ** 2)))
+ total_ss = float(numpy.sum((errors - errors.mean()) ** 2))
+ r_squared = 1.0 - float(numpy.sum((errors - predicted) ** 2)) / total_ss if total_ss > 0.0 else 1.0
+ return {
+ "asymptoticBiasRelMse": round(asymptotic_bias, 6),
+ "varianceSlopePerSample": round(variance_slope, 6),
+ "fitResidualRmse": round(residual_rmse, 6),
+ "fitRSquared": round(r_squared, 6),
+ }
+
+
+def interpolate_equal_error_time(target_rel_mse, native_points, time_key):
+ ordered = sorted(native_points, key=lambda item: item["samples"])
+ for index in range(len(ordered) - 1):
+ first = ordered[index]
+ second = ordered[index + 1]
+ if first["relMse"] >= target_rel_mse >= second["relMse"] and first["relMse"] > second["relMse"]:
+ log_error_first = math.log(first["relMse"])
+ log_error_second = math.log(second["relMse"])
+ log_target = math.log(target_rel_mse)
+ fraction = (log_target - log_error_first) / (log_error_second - log_error_first)
+ log_time = math.log(first[time_key]) + fraction * (math.log(second[time_key]) - math.log(first[time_key]))
+ log_samples = math.log(first["samples"]) + fraction * (math.log(second["samples"]) - math.log(first["samples"]))
+ return {
+ "reachable": True,
+ "interpolatedSeconds": round(math.exp(log_time), 6),
+ "interpolatedSamples": round(math.exp(log_samples), 2),
+ "bracketSamples": [first["samples"], second["samples"]],
+ }
+ best_point = min(ordered, key=lambda item: item["relMse"])
+ return {
+ "reachable": False,
+ "interpolatedSeconds": None,
+ "interpolatedSamples": None,
+ "bestAchievedRelMse": round(best_point["relMse"], 6),
+ "bestAchievedAtSamples": best_point["samples"],
+ "targetRelMse": round(target_rel_mse, 6),
+ }
+
+
+def run_pair_cli(argument_list):
+ parts_prefix = None
+ filtered = []
+ index = 0
+ while index < len(argument_list):
+ if argument_list[index] == "--parts":
+ parts_prefix = argument_list[index + 1]
+ index += 2
+ continue
+ filtered.append(argument_list[index])
+ index += 1
+ if len(filtered) < 2:
+ raise ValueError("Usage: compare.py [pair] [--parts <partsPrefix>] <referenceImage> <candidateImage> [<candidateImage>...]")
+ reference_rgb = load_linear_rgb_image(filtered[0])
+ for candidate_path in filtered[1:]:
+ candidate_rgb = load_linear_rgb_image(candidate_path)
+ if candidate_rgb.shape != reference_rgb.shape:
+ raise ValueError(f"Resolution mismatch for '{candidate_path}': {candidate_rgb.shape} vs {reference_rgb.shape}.")
+ comparison = compare_image_pair(reference_rgb, candidate_rgb, parts_prefix=parts_prefix)
+ comparison["image"] = candidate_path
+ print(json.dumps(comparison))
+
+
+def summarize_repeated_runs(records):
+ by_samples = {}
+ for record in records:
+ by_samples.setdefault(record["samples"], []).append(record)
+ summary_rows = []
+ for samples in sorted(by_samples.keys()):
+ group = by_samples[samples]
+ wall_values = [item["wallSeconds"] for item in group]
+ setup_values = [item["setupSeconds"] for item in group]
+ sampling_values = [item["samplingSeconds"] for item in group]
+ total_trace_values = [item["totalTraceSeconds"] for item in group]
+ ram_values = [item["peakRamMegabytes"] for item in group]
+ vram_delta_values = [item["peakVramDeltaMegabytes"] for item in group]
+ vram_peak_values = [item["peakCardVramMegabytes"] for item in group]
+ rel_mse_values = [item["relMse"] for item in group]
+ cycles_peak_values = [item["cyclesPeakMemoryMegabytes"] for item in group if item.get("cyclesPeakMemoryMegabytes") is not None]
+ representative = group[0]
+ row = {
+ "samples": samples,
+ "runCount": len(group),
+ "gpuExclusiveAllRuns": all(item["gpuExclusive"] for item in group),
+ "relMse": round(float(statistics.median(rel_mse_values)), 6),
+ "relMseClipped1000": representative["relMseClipped1000"],
+ "relMseTrimmed": representative["relMseTrimmed"],
+ "channelMeanRatio": representative["channelMeanRatio"],
+ "scalarMeanRatio": representative["scalarMeanRatio"],
+ "setupSecondsMedian": round(float(statistics.median(setup_values)), 4),
+ "setupSecondsSpread": [round(min(setup_values), 4), round(max(setup_values), 4)],
+ "samplingSecondsMedian": round(float(statistics.median(sampling_values)), 4),
+ "samplingSecondsSpread": [round(min(sampling_values), 4), round(max(sampling_values), 4)],
+ "totalTraceSecondsMedian": round(float(statistics.median(total_trace_values)), 4),
+ "totalTraceSecondsSpread": [round(min(total_trace_values), 4), round(max(total_trace_values), 4)],
+ "wallSecondsMedian": round(float(statistics.median(wall_values)), 4),
+ "wallSecondsSpread": [round(min(wall_values), 4), round(max(wall_values), 4)],
+ "peakRamMegabytesMedian": round(float(statistics.median(ram_values)), 2),
+ "peakRamMegabytesSpread": [round(min(ram_values), 2), round(max(ram_values), 2)],
+ "peakVramDeltaMegabytesMedian": round(float(statistics.median(vram_delta_values)), 2),
+ "peakVramDeltaMegabytesSpread": [round(min(vram_delta_values), 2), round(max(vram_delta_values), 2)],
+ "peakCardVramMegabytesMedian": round(float(statistics.median(vram_peak_values)), 2),
+ "cyclesPeakMemoryMegabytesMedian": round(float(statistics.median(cycles_peak_values)), 2) if cycles_peak_values else None,
+ }
+ summary_rows.append(row)
+ return summary_rows
+
+
+def load_run_record(prefix_path, reference_rgb):
+ with open(f"{prefix_path}.json", encoding="utf-8") as handle:
+ trace_info = json.load(handle)
+ with open(f"{prefix_path}.metrics.json", encoding="utf-8") as handle:
+ metrics_info = json.load(handle)
+ candidate_rgb = load_linear_rgb_image(f"{prefix_path}.npy")
+ pair_metrics = compare_image_pair(reference_rgb, candidate_rgb)
+ return {
+ "prefix": prefix_path,
+ "engine": trace_info["engine"],
+ "samples": trace_info["samples"],
+ "seed": trace_info["seed"],
+ "setupSeconds": trace_info["setupSeconds"],
+ "samplingSeconds": trace_info["samplingSeconds"],
+ "totalTraceSeconds": trace_info["totalTraceSeconds"],
+ "cyclesPeakMemoryMegabytes": trace_info.get("cyclesPeakMemoryMegabytes"),
+ "wallSeconds": metrics_info["wallSeconds"],
+ "peakRamMegabytes": metrics_info["peakRamMegabytes"],
+ "peakVramDeltaMegabytes": metrics_info["peakVramDeltaMegabytes"],
+ "peakCardVramMegabytes": metrics_info["peakCardVramMegabytes"],
+ "gpuExclusive": metrics_info["gpuExclusive"],
+ "relMse": pair_metrics["relMse"],
+ "relMseClipped1000": round(pair_metrics["relMseClipped1000"], 6),
+ "relMseTrimmed": round(pair_metrics["relMseTrimmed"], 6),
+ "channelMeanRatio": pair_metrics["channelMeanRatio"],
+ "scalarMeanRatio": pair_metrics["scalarMeanRatio"],
+ }
+
+
+def run_suite_cli(argument_list):
+ if not argument_list:
+ raise ValueError("Usage: compare.py suite <manifestJsonPath>")
+ manifest_path = os.path.abspath(argument_list[0])
+ with open(manifest_path, encoding="utf-8") as handle:
+ manifest = json.load(handle)
+ seed_a_rgb = load_linear_rgb_image(f"{manifest['referenceSeedAPrefix']}.npy")
+ seed_b_rgb = load_linear_rgb_image(f"{manifest['referenceSeedBPrefix']}.npy")
+ noise_floor = compare_image_pair(seed_a_rgb, seed_b_rgb)
+ cycles_records = [load_run_record(prefix, seed_a_rgb) for prefix in manifest["cyclesLadderPrefixes"]]
+ native_records = [load_run_record(prefix, seed_a_rgb) for prefix in manifest["nativeLadderPrefixes"]]
+ cycles_ladder = summarize_repeated_runs(cycles_records)
+ native_ladder = summarize_repeated_runs(native_records)
+ cycles_256 = next(row for row in cycles_ladder if row["samples"] == 256)
+ native_256 = next(row for row in native_ladder if row["samples"] == 256)
+ native_high_prefix = manifest["nativeDetailPrefix"]
+ parts_prefix = manifest.get("partsPrefix")
+ native_detail = compare_image_pair(seed_a_rgb, load_linear_rgb_image(f"{native_high_prefix}.npy"), parts_prefix=parts_prefix)
+ bias_fit_native = fit_asymptotic_bias_model(native_ladder)
+ bias_fit_cycles = fit_asymptotic_bias_model(cycles_ladder)
+ teq_sampling = interpolate_equal_error_time(cycles_256["relMse"], native_ladder, "samplingSecondsMedian")
+ teq_total = interpolate_equal_error_time(cycles_256["relMse"], native_ladder, "totalTraceSecondsMedian")
+ teq_wall = interpolate_equal_error_time(cycles_256["relMse"], native_ladder, "wallSecondsMedian")
+ summary = {
+ "sceneId": manifest["sceneId"],
+ "noiseFloorSeedAVsSeedB": noise_floor,
+ "cyclesLadder": cycles_ladder,
+ "nativeLadder": native_ladder,
+ "cyclesBiasModelFit": bias_fit_cycles,
+ "nativeBiasModelFit": bias_fit_native,
+ "equalSpp256Comparison": {
+ "cyclesRelMse": cycles_256["relMse"],
+ "nativeRelMse": native_256["relMse"],
+ "relMseRatioNativeOverCycles": round(native_256["relMse"] / cycles_256["relMse"], 4),
+ "samplingTimeRatioNativeOverCycles": round(native_256["samplingSecondsMedian"] / max(cycles_256["samplingSecondsMedian"], 1e-9), 4),
+ "totalTraceTimeRatioNativeOverCycles": round(native_256["totalTraceSecondsMedian"] / max(cycles_256["totalTraceSecondsMedian"], 1e-9), 4),
+ "wallTimeRatioNativeOverCycles": round(native_256["wallSecondsMedian"] / max(cycles_256["wallSecondsMedian"], 1e-9), 4),
+ "setupTimeRatioNativeOverCycles": round(native_256["setupSecondsMedian"] / max(cycles_256["setupSecondsMedian"], 1e-9), 4),
+ },
+ "equalErrorTargetCycles256": {
+ "targetRelMse": cycles_256["relMse"],
+ "cyclesSamplingSeconds": cycles_256["samplingSecondsMedian"],
+ "cyclesTotalTraceSeconds": cycles_256["totalTraceSecondsMedian"],
+ "cyclesWallSeconds": cycles_256["wallSecondsMedian"],
+ "nativeSamplingCurve": teq_sampling,
+ "nativeTotalTraceCurve": teq_total,
+ "nativeWallCurve": teq_wall,
+ },
+ "nativeDetailedComparison": native_detail,
+ }
+ output_path = manifest.get("outputSummaryPath")
+ if output_path:
+ with open(output_path, "w", encoding="utf-8") as handle:
+ json.dump(summary, handle, indent=2)
+ print(json.dumps(summary, indent=2))
+
+
+def main():
+ arguments = sys.argv[1:]
+ if not arguments:
+ raise ValueError("Usage: compare.py [pair|suite] ...")
+ if arguments[0] == "suite":
+ run_suite_cli(arguments[1:])
+ return
+ if arguments[0] == "pair":
+ run_pair_cli(arguments[1:])
+ return
+ run_pair_cli(arguments)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/cycles-parity/export-scene.mjs b/bench/cycles-parity/export-scene.mjs
new file mode 100644
index 00000000..b1acff79
--- /dev/null
+++ b/bench/cycles-parity/export-scene.mjs
@@ -0,0 +1,89 @@
+// Exports a 67js reference scene to JSON for Cycles parity runs and verifies lossless round-trip packing.
+// node bench/cycles-parity/export-scene.mjs <outputDirectory> [--scene lit-interior]
+import { mkdir, writeFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { createCamera } from '../../src/path-tracer.js';
+import * as packModule from '../../src/path-tracer-gpu-pack.js';
+import { buildTraceScene } from '../../src/path-tracer-scene.js';
+import { buildNativeInput } from '../../packages/render-native/pack-input.mjs';
+import { loadReferenceScene, reconstructTraceSceneSource, serializeSceneDescription } from './scene-bridge.mjs';
+
+const TABLE_NAMES = ['triangles', 'materials', 'lights', 'atlas', 'environmentColors', 'environmentTables', 'parameters'];
+
+function readFlagValue(argumentList, flagName, fallbackValue) {
+ const flagIndex = argumentList.indexOf(flagName);
+ if (flagIndex === -1) {
+ return fallbackValue;
+ }
+ const nextValue = argumentList[flagIndex + 1];
+ if (nextValue === undefined || nextValue.startsWith('--')) {
+ throw new RangeError(`Flag ${flagName} requires a value.`);
+ }
+ return nextValue;
+}
+
+function viewAsBytes(typedArray) {
+ return Buffer.from(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
+}
+
+function buildPackedTables(traceSource) {
+ const options = {
+ width: 960,
+ height: 540,
+ bounces: 8,
+ seed: 1,
+ fireflyClamp: 1e9,
+ noiseThreshold: 0,
+ };
+ const traceScene = buildTraceScene(traceSource.parts, traceSource.environment);
+ const camera = createCamera(traceSource.camera, options.width, options.height);
+ return buildNativeInput(traceScene, camera, options, packModule);
+}
+
+function assertIdenticalPackedInputs(directInput, roundTripInput, sceneId) {
+ if (directInput.triangleCount !== roundTripInput.triangleCount) {
+ throw new Error(`Scene "${sceneId}" round-trip triangleCount mismatch: ${directInput.triangleCount} vs ${roundTripInput.triangleCount}.`);
+ }
+ for (const tableName of TABLE_NAMES) {
+ const directBytes = viewAsBytes(directInput[tableName]);
+ const roundTripBytes = viewAsBytes(roundTripInput[tableName]);
+ if (!directBytes.equals(roundTripBytes)) {
+ throw new Error(`Scene "${sceneId}" round-trip mismatch in native table "${tableName}" (${directBytes.length} vs ${roundTripBytes.length} bytes).`);
+ }
+ }
+}
+
+async function runCli() {
+ const argumentList = process.argv.slice(2);
+ if (argumentList.length === 0 || argumentList[0].startsWith('--')) {
+ throw new RangeError('Usage: node bench/cycles-parity/export-scene.mjs <outputDirectory> [--scene lit-interior]');
+ }
+ const outputDirectory = resolve(argumentList[0]);
+ const sceneId = readFlagValue(argumentList, '--scene', 'lit-interior');
+ const loaded = await loadReferenceScene(sceneId);
+ const description = await serializeSceneDescription(sceneId, loaded.rawScene);
+ const jsonText = JSON.stringify(description);
+ const parsedDescription = JSON.parse(jsonText);
+ const reconstructedSource = await reconstructTraceSceneSource(parsedDescription);
+ const directInput = buildPackedTables(loaded.traceSource);
+ const roundTripInput = buildPackedTables(reconstructedSource);
+ assertIdenticalPackedInputs(directInput, roundTripInput, sceneId);
+ const scenesDirectory = join(outputDirectory, 'scenes');
+ await mkdir(scenesDirectory, { recursive: true });
+ const outputPath = join(scenesDirectory, `${sceneId}.json`);
+ await writeFile(outputPath, jsonText);
+ const summary = {
+ sceneId,
+ outputPath,
+ partCount: description.parts.length,
+ materialCount: description.materials.length,
+ triangleCount: directInput.triangleCount,
+ pointLightCount: (description.environment.pointLights ?? []).length,
+ spotLightCount: (description.environment.spotLights ?? []).length,
+ areaLightCount: (description.environment.areaLights ?? []).length,
+ roundTripVerified: true,
+ };
+ console.log(JSON.stringify(summary));
+}
+
+await runCli();
diff --git a/bench/cycles-parity/measure-gpu-run.py b/bench/cycles-parity/measure-gpu-run.py
new file mode 100644
index 00000000..28976df2
--- /dev/null
+++ b/bench/cycles-parity/measure-gpu-run.py
@@ -0,0 +1,260 @@
+"""Execute one GPU benchmark command while recording wall time, peak process-tree RAM, and 50 ms polled VRAM."""
+import json
+import os
+import re
+import subprocess
+import sys
+import threading
+import time
+
+import psutil
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+RAM_POLL_INTERVAL_SECONDS = 0.025
+VRAM_POLL_INTERVAL_MILLISECONDS = 50
+BLENDER_PEAK_PATTERN = re.compile(r"Peak\s+([0-9.]+)([KMGTP]?)", re.IGNORECASE)
+BLENDER_FRA_PATTERN = re.compile(r"Fra:\d+.*\|\s*Time:(\d+):(\d+\.\d+)\s*\|\s*(.+)")
+DESKTOP_SHELL_BINARIES = {
+ "applicationframehost.exe",
+ "cloudflare warp.exe",
+ "discord.exe",
+ "explorer.exe",
+ "logioptionsplus_agent.exe",
+ "msedgewebview2.exe",
+ "oh-snap.exe",
+ "powertoys.colorpickerui.exe",
+ "powertoys.fancyzones.exe",
+ "searchhost.exe",
+ "shellexperiencehost.exe",
+ "shellhost.exe",
+ "startmenuexperiencehost.exe",
+ "systemsettings.exe",
+ "textinputhost.exe",
+ "zalo.exe",
+ "zalocall.exe",
+}
+
+
+def is_desktop_shell_process(process_name):
+ basename = os.path.basename(process_name).lower()
+ return basename in DESKTOP_SHELL_BINARIES
+
+
+def parse_cli_arguments():
+ if "--" not in sys.argv or len(sys.argv) < 4:
+ raise ValueError("Usage: measure-gpu-run.py <metricsJsonPath> -- <command> [arguments...]")
+ separator_index = sys.argv.index("--")
+ metrics_path = os.path.abspath(sys.argv[1])
+ command = sys.argv[separator_index + 1:]
+ if not command:
+ raise ValueError("Missing command after '--'.")
+ return metrics_path, command
+
+
+def query_gpu_snapshot():
+ result = subprocess.run(
+ ["nvidia-smi", "--query-gpu=name,memory.used,memory.total,utilization.gpu", "--format=csv,noheader,nounits"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ first_line = next((line.strip() for line in result.stdout.splitlines() if line.strip()), "")
+ fields = [field.strip() for field in first_line.split(",")]
+ if len(fields) < 4:
+ return {
+ "gpuName": "unknown",
+ "usedMegabytes": 0.0,
+ "totalMegabytes": 0.0,
+ "utilizationPercent": 0.0,
+ }
+ return {
+ "gpuName": fields[0],
+ "usedMegabytes": float(fields[1]),
+ "totalMegabytes": float(fields[2]),
+ "utilizationPercent": float(fields[3]),
+ }
+
+
+def query_compute_processes():
+ result = subprocess.run(
+ ["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader,nounits"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ entries = []
+ for raw_line in result.stdout.splitlines():
+ fields = [field.strip() for field in raw_line.split(",")]
+ if len(fields) >= 2 and fields[0].isdigit():
+ used_megabytes = float(fields[2]) if len(fields) >= 3 and fields[2].replace(".", "", 1).isdigit() else None
+ entries.append({
+ "pid": int(fields[0]),
+ "processName": fields[1],
+ "usedMegabytes": used_megabytes,
+ })
+ return entries
+
+
+def start_vram_stream():
+ stream_process = subprocess.Popen(
+ [
+ "nvidia-smi",
+ "--query-gpu=memory.used,utilization.gpu",
+ "--format=csv,noheader,nounits",
+ "-lms",
+ str(VRAM_POLL_INTERVAL_MILLISECONDS),
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ text=True,
+ bufsize=1,
+ )
+ samples = []
+ first_sample_ready = threading.Event()
+
+ def read_samples():
+ assert stream_process.stdout is not None
+ for raw_line in stream_process.stdout:
+ fields = [field.strip() for field in raw_line.split(",")]
+ if len(fields) >= 2:
+ try:
+ used_value = float(fields[0])
+ utilization_value = float(fields[1])
+ samples.append((time.perf_counter(), used_value, utilization_value))
+ first_sample_ready.set()
+ except ValueError:
+ continue
+
+ reader_thread = threading.Thread(target=read_samples, daemon=True)
+ reader_thread.start()
+ first_sample_ready.wait(timeout=2.0)
+ return stream_process, samples
+
+
+def collect_process_tree(root_process):
+ try:
+ return [root_process] + root_process.children(recursive=True)
+ except psutil.Error:
+ return []
+
+
+def parse_blender_stdout_metrics(output_lines):
+ peak_megabytes = None
+ first_render_time = None
+ finished_time = None
+ scale_by_unit = {"K": 1.0 / 1024.0, "M": 1.0, "": 1.0, "G": 1024.0, "T": 1024.0 * 1024.0}
+ for line in output_lines:
+ peak_match = BLENDER_PEAK_PATTERN.search(line)
+ if peak_match:
+ megabytes = float(peak_match.group(1)) * scale_by_unit.get(peak_match.group(2).upper(), 1.0)
+ peak_megabytes = megabytes if peak_megabytes is None else max(peak_megabytes, megabytes)
+ fra_match = BLENDER_FRA_PATTERN.search(line)
+ if fra_match:
+ minutes = int(fra_match.group(1))
+ seconds = float(fra_match.group(2))
+ stamp_seconds = minutes * 60.0 + seconds
+ status_tail = fra_match.group(3)
+ if "Rendering " in status_tail and first_render_time is None:
+ first_render_time = stamp_seconds
+ if "Finished" in status_tail or "Rendering " in status_tail:
+ finished_time = stamp_seconds
+ return {
+ "stdoutPeakMegabytes": round(peak_megabytes, 2) if peak_megabytes is not None else None,
+ "stdoutFirstRenderSeconds": round(first_render_time, 4) if first_render_time is not None else None,
+ "stdoutFinishedSeconds": round(finished_time, 4) if finished_time is not None else None,
+ }
+
+
+def main():
+ metrics_path, command = parse_cli_arguments()
+ os.makedirs(os.path.dirname(metrics_path), exist_ok=True)
+ pre_snapshot = query_gpu_snapshot()
+ pre_compute_apps = query_compute_processes()
+ smi_process, vram_samples = start_vram_stream()
+ creation_flags = subprocess.BELOW_NORMAL_PRIORITY_CLASS if os.name == "nt" else 0
+ captured_lines = []
+ run_started = time.perf_counter()
+ child_process = subprocess.Popen(
+ command,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ bufsize=1,
+ creationflags=creation_flags,
+ )
+
+ def forward_output():
+ assert child_process.stdout is not None
+ for line in child_process.stdout:
+ captured_lines.append(line.rstrip("\r\n"))
+ sys.stdout.write(line)
+ sys.stdout.flush()
+
+ output_thread = threading.Thread(target=forward_output, daemon=True)
+ output_thread.start()
+ psutil_root = psutil.Process(child_process.pid)
+ peak_ram_bytes = 0
+ tracked_pids = {child_process.pid}
+ while child_process.poll() is None:
+ members = collect_process_tree(psutil_root)
+ tree_rss_bytes = 0
+ for member in members:
+ tracked_pids.add(member.pid)
+ try:
+ tree_rss_bytes += member.memory_info().rss
+ except psutil.Error:
+ continue
+ peak_ram_bytes = max(peak_ram_bytes, tree_rss_bytes)
+ time.sleep(RAM_POLL_INTERVAL_SECONDS)
+ output_thread.join(timeout=5.0)
+ wall_seconds = time.perf_counter() - run_started
+ post_snapshot = query_gpu_snapshot()
+ smi_process.terminate()
+ try:
+ smi_process.wait(timeout=2.0)
+ except subprocess.TimeoutExpired:
+ smi_process.kill()
+ post_compute_apps = query_compute_processes()
+ window_samples = [(used_mb, util_pct) for stamp, used_mb, util_pct in vram_samples if stamp >= run_started]
+ if not window_samples:
+ window_samples = [(post_snapshot["usedMegabytes"], post_snapshot["utilizationPercent"])]
+ peak_card_vram_mb = max(sample[0] for sample in window_samples)
+ peak_gpu_utilization = max(sample[1] for sample in window_samples)
+ baseline_vram_mb = pre_snapshot["usedMegabytes"]
+ foreign_apps = [
+ entry for entry in (pre_compute_apps + post_compute_apps)
+ if entry["pid"] not in tracked_pids and not is_desktop_shell_process(entry["processName"])
+ ]
+ unique_foreign = {entry["pid"]: entry for entry in foreign_apps}
+ gpu_exclusive = len(unique_foreign) == 0 and pre_snapshot["utilizationPercent"] < 15.0
+ blender_stdout = parse_blender_stdout_metrics(captured_lines)
+ report = {
+ "command": command,
+ "exitCode": child_process.returncode,
+ "gpuName": pre_snapshot["gpuName"],
+ "totalCardVramMegabytes": pre_snapshot["totalMegabytes"],
+ "preRunGpuUtilizationPercent": pre_snapshot["utilizationPercent"],
+ "postRunGpuUtilizationPercent": post_snapshot["utilizationPercent"],
+ "wallSeconds": round(wall_seconds, 6),
+ "peakRamMegabytes": round(peak_ram_bytes / (1024.0 * 1024.0), 2),
+ "peakRamGigabytes": round(peak_ram_bytes / 1e9, 3),
+ "baselineCardVramMegabytes": round(baseline_vram_mb, 2),
+ "peakCardVramMegabytes": round(peak_card_vram_mb, 2),
+ "peakVramDeltaMegabytes": round(max(0.0, peak_card_vram_mb - baseline_vram_mb), 2),
+ "peakGpuUtilizationPercent": round(peak_gpu_utilization, 1),
+ "vramSampleCount": len(window_samples),
+ "gpuExclusive": gpu_exclusive,
+ "foreignComputeProcesses": list(unique_foreign.values()),
+ **blender_stdout,
+ }
+ with open(metrics_path, "w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=2)
+ print("GPU_RUN_METRICS " + json.dumps(report))
+ sys.exit(child_process.returncode)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/cycles-parity/npy.mjs b/bench/cycles-parity/npy.mjs
new file mode 100644
index 00000000..300bbb8b
--- /dev/null
+++ b/bench/cycles-parity/npy.mjs
@@ -0,0 +1,37 @@
+import { writeFile } from 'node:fs/promises';
+
+const NPY_MAGIC_PREFIX = Buffer.from([0x93, 0x4e, 0x55, 0x4d, 0x50, 0x59, 0x01, 0x00]);
+const HEADER_ALIGNMENT_BYTES = 64;
+
+function validateFloat32Shape(pixels, shape) {
+ if (!(pixels instanceof Float32Array)) {
+ throw new TypeError('writeFloat32Npy requires pixels to be a Float32Array.');
+ }
+ if (!Array.isArray(shape) || shape.length === 0 || shape.some((dimension) => !Number.isInteger(dimension) || dimension <= 0)) {
+ throw new RangeError('writeFloat32Npy requires shape to be a non-empty array of positive integers.');
+ }
+ const expectedLength = shape.reduce((product, dimension) => product * dimension, 1);
+ if (pixels.length !== expectedLength) {
+ throw new RangeError(`writeFloat32Npy expected ${expectedLength} float32 values for shape (${shape.join(', ')}), got ${pixels.length}.`);
+ }
+}
+
+function buildNpyHeader(shape) {
+ const shapeTuple = shape.length === 1 ? `${shape[0]},` : shape.join(', ');
+ const dictionary = `{'descr': '<f4', 'fortran_order': False, 'shape': (${shapeTuple}), }`;
+ const unpaddedLength = NPY_MAGIC_PREFIX.length + 2 + dictionary.length + 1;
+ const remainder = unpaddedLength % HEADER_ALIGNMENT_BYTES;
+ const paddingCount = remainder === 0 ? 0 : HEADER_ALIGNMENT_BYTES - remainder;
+ const headerText = `${dictionary}${' '.repeat(paddingCount)}\n`;
+ const headerBytes = Buffer.from(headerText, 'ascii');
+ const lengthBytes = Buffer.alloc(2);
+ lengthBytes.writeUInt16LE(headerBytes.length, 0);
+ return Buffer.concat([NPY_MAGIC_PREFIX, lengthBytes, headerBytes]);
+}
+
+export async function writeFloat32Npy(filePath, pixels, shape) {
+ validateFloat32Shape(pixels, shape);
+ const header = buildNpyHeader(shape);
+ const body = Buffer.from(pixels.buffer, pixels.byteOffset, pixels.byteLength);
+ await writeFile(filePath, Buffer.concat([header, body]));
+}
diff --git a/bench/cycles-parity/render-cycles.py b/bench/cycles-parity/render-cycles.py
new file mode 100644
index 00000000..d1f4603f
--- /dev/null
+++ b/bench/cycles-parity/render-cycles.py
@@ -0,0 +1,563 @@
+"""Render an exported 67js scene JSON in Blender Cycles OptiX with matched parity settings."""
+import base64
+import json
+import math
+import os
+import re
+import sys
+import time
+
+import bpy
+import numpy
+from mathutils import Matrix, Vector
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+WATTS_PER_POINT_INTENSITY = 4.0 * math.pi
+WATTS_PER_AREA_INTENSITY = math.pi
+SUN_ANGULAR_DIAMETER = math.radians(1.0)
+ENVIRONMENT_ROTATION_Z = -math.pi / 2.0
+PART_ID_STEPS = 64
+Y_UP_TO_Z_UP = Matrix((
+ (1.0, 0.0, 0.0, 0.0),
+ (0.0, 0.0, -1.0, 0.0),
+ (0.0, 1.0, 0.0, 0.0),
+ (0.0, 0.0, 0.0, 1.0),
+))
+NUMPY_DTYPES = {
+ "Float32Array": numpy.float32,
+ "Uint32Array": numpy.uint32,
+ "Uint16Array": numpy.uint16,
+ "Uint8Array": numpy.uint8,
+ "Uint8ClampedArray": numpy.uint8,
+}
+PEAK_MEMORY_PATTERN = re.compile(r"(?:Peak|Mem)[:\s]+([0-9.]+)\s*([KMGT]?)(?:i?B)?", re.IGNORECASE)
+
+
+def read_flag_value(argument_list, flag_name, fallback_value):
+ if flag_name not in argument_list:
+ return fallback_value
+ flag_index = argument_list.index(flag_name)
+ if flag_index + 1 >= len(argument_list):
+ raise ValueError(f"Flag {flag_name} requires a value.")
+ return argument_list[flag_index + 1]
+
+
+def parse_cli_arguments():
+ if "--" not in sys.argv:
+ raise ValueError("Pass script arguments after '--': <sceneJsonPath> <outputPrefix> [options].")
+ argument_list = sys.argv[sys.argv.index("--") + 1:]
+ if len(argument_list) < 2 or argument_list[0].startswith("--") or argument_list[1].startswith("--"):
+ raise ValueError("Usage: blender -b --factory-startup --python bench/cycles-parity/render-cycles.py -- <sceneJsonPath> <outputPrefix> [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--keep-exr] [--part-ids]")
+ return {
+ "scene_json_path": os.path.abspath(argument_list[0]),
+ "output_prefix": os.path.abspath(argument_list[1]),
+ "samples": int(read_flag_value(argument_list, "--samples", "256")),
+ "bounces": int(read_flag_value(argument_list, "--bounces", "8")),
+ "seed": int(read_flag_value(argument_list, "--seed", "1")),
+ "width": int(read_flag_value(argument_list, "--width", "960")),
+ "height": int(read_flag_value(argument_list, "--height", "540")),
+ "keep_exr": "--keep-exr" in argument_list,
+ "part_ids": "--part-ids" in argument_list,
+ }
+
+
+def decode_typed_array(encoded_entry):
+ if encoded_entry is None:
+ return None
+ raw_bytes = base64.b64decode(encoded_entry["base64"])
+ dtype = NUMPY_DTYPES[encoded_entry["type"]]
+ return numpy.frombuffer(raw_bytes, dtype=dtype)
+
+
+def convert_position_to_blender(position):
+ return (position[0], -position[2], position[1])
+
+
+def set_linear_rgba_socket(socket, rgb_color):
+ socket.default_value = (rgb_color[0], rgb_color[1], rgb_color[2], 1.0)
+
+
+def build_blender_mesh(mesh_name, geometry_entry):
+ positions = decode_typed_array(geometry_entry["positions"]).reshape(-1, 3)
+ normals = decode_typed_array(geometry_entry["normals"]).reshape(-1, 3)
+ triangles = decode_typed_array(geometry_entry["indices"]).reshape(-1, 3)
+ degenerate_mask = (triangles[:, 0] == triangles[:, 1]) | (triangles[:, 1] == triangles[:, 2]) | (triangles[:, 0] == triangles[:, 2])
+ valid_triangles = triangles[~degenerate_mask]
+ mesh = bpy.data.meshes.new(mesh_name)
+ mesh.from_pydata(positions.tolist(), [], valid_triangles.tolist())
+ mesh.validate()
+ mesh.normals_split_custom_set_from_vertices(normals.tolist())
+ uv_values = decode_typed_array(geometry_entry.get("uvs"))
+ if uv_values is not None:
+ uv_pairs = uv_values.reshape(-1, 2)
+ uv_layer = mesh.uv_layers.new(name="UVMap")
+ corner_uvs = uv_pairs[valid_triangles.reshape(-1)].copy()
+ corner_uvs[:, 1] = 1.0 - corner_uvs[:, 1]
+ uv_layer.data.foreach_set("uv", corner_uvs.reshape(-1))
+ vertex_colors = decode_typed_array(geometry_entry.get("colors"))
+ if vertex_colors is not None:
+ color_attribute = mesh.color_attributes.new("Col", "FLOAT_COLOR", "POINT")
+ rgb_values = vertex_colors.reshape(-1, 3)
+ alpha_column = numpy.ones((len(rgb_values), 1), dtype=numpy.float32)
+ rgba_values = numpy.concatenate([rgb_values, alpha_column], axis=1)
+ color_attribute.data.foreach_set("color", rgba_values.reshape(-1))
+ mesh.update()
+ return mesh
+
+
+def unpack_shared_image(image_name, texture_descriptor, image_entries, built_images):
+ image_identifier = texture_descriptor["image"]["imageId"]
+ if image_identifier in built_images:
+ return built_images[image_identifier]
+ source_entry = image_entries[image_identifier]
+ raw_pixels = decode_typed_array(source_entry["data"])
+ width = source_entry["width"]
+ height = source_entry["height"]
+ blender_image = bpy.data.images.new(image_name, width, height, alpha=True)
+ flipped_pixels = raw_pixels.reshape(height, width, 4)[::-1].astype(numpy.float32) / 255.0
+ blender_image.pixels.foreach_set(flipped_pixels.reshape(-1))
+ blender_image.pack()
+ built_images[image_identifier] = blender_image
+ return blender_image
+
+
+def connect_base_color_texture(material, principled_node, material_entry, has_vertex_colors, image_entries, built_images):
+ nodes = material.node_tree.nodes
+ links = material.node_tree.links
+ texture_node = nodes.new("ShaderNodeTexImage")
+ texture_node.image = unpack_shared_image(f"{material.name}-map", material_entry["map"], image_entries, built_images)
+ multiply_node = nodes.new("ShaderNodeMixRGB")
+ multiply_node.blend_type = "MULTIPLY"
+ multiply_node.inputs[0].default_value = 1.0
+ set_linear_rgba_socket(multiply_node.inputs[2], material_entry["color"])
+ links.new(texture_node.outputs["Color"], multiply_node.inputs[1])
+ if has_vertex_colors:
+ vertex_color_node = nodes.new("ShaderNodeVertexColor")
+ vertex_color_node.layer_name = "Col"
+ vertex_multiply_node = nodes.new("ShaderNodeMixRGB")
+ vertex_multiply_node.blend_type = "MULTIPLY"
+ vertex_multiply_node.inputs[0].default_value = 1.0
+ links.new(multiply_node.outputs["Color"], vertex_multiply_node.inputs[1])
+ links.new(vertex_color_node.outputs["Color"], vertex_multiply_node.inputs[2])
+ links.new(vertex_multiply_node.outputs["Color"], principled_node.inputs["Base Color"])
+ else:
+ links.new(multiply_node.outputs["Color"], principled_node.inputs["Base Color"])
+ if material_entry.get("alphaMode") == "mask":
+ cutoff_node = nodes.new("ShaderNodeMath")
+ cutoff_node.operation = "GREATER_THAN"
+ cutoff_node.inputs[1].default_value = material_entry.get("alphaCutoff", 0.5)
+ links.new(texture_node.outputs["Alpha"], cutoff_node.inputs[0])
+ links.new(cutoff_node.outputs[0], principled_node.inputs["Alpha"])
+
+
+def connect_vertex_colors(material, principled_node, material_entry):
+ nodes = material.node_tree.nodes
+ links = material.node_tree.links
+ vertex_color_node = nodes.new("ShaderNodeVertexColor")
+ vertex_color_node.layer_name = "Col"
+ multiply_node = nodes.new("ShaderNodeMixRGB")
+ multiply_node.blend_type = "MULTIPLY"
+ multiply_node.inputs[0].default_value = 1.0
+ set_linear_rgba_socket(multiply_node.inputs[2], material_entry["color"])
+ links.new(vertex_color_node.outputs["Color"], multiply_node.inputs[1])
+ links.new(multiply_node.outputs["Color"], principled_node.inputs["Base Color"])
+
+
+def configure_principled_layers(material, principled_node, material_entry):
+ principled_node.inputs["Coat Weight"].default_value = material_entry.get("clearcoat", 0.0)
+ principled_node.inputs["Coat Roughness"].default_value = material_entry.get("clearcoatRoughness", 0.0)
+ default_transmission = principled_node.inputs["Transmission Weight"].default_value
+ principled_node.inputs["Transmission Weight"].default_value = material_entry.get("transmission", default_transmission)
+ default_ior = principled_node.inputs["IOR"].default_value
+ principled_node.inputs["IOR"].default_value = material_entry.get("ior", default_ior)
+ principled_node.inputs["Specular IOR Level"].default_value = 0.5 * material_entry.get("specular", 1.0)
+ set_linear_rgba_socket(principled_node.inputs["Specular Tint"], material_entry.get("specularColor", [1.0, 1.0, 1.0]))
+ attenuation_distance = material_entry.get("attenuationDistance")
+ if attenuation_distance:
+ absorption_node = material.node_tree.nodes.new("ShaderNodeVolumeAbsorption")
+ attenuation_color = material_entry.get("attenuationColor", [1.0, 1.0, 1.0])
+ set_linear_rgba_socket(absorption_node.inputs["Color"], attenuation_color)
+ mean_log_color = sum(math.log(max(channel, 0.001)) for channel in attenuation_color) / 3.0
+ absorption_node.inputs["Density"].default_value = -mean_log_color / attenuation_distance
+ output_node = material.node_tree.nodes["Material Output"]
+ material.node_tree.links.new(absorption_node.outputs["Volume"], output_node.inputs["Volume"])
+
+
+def build_blender_material(material_name, material_entry, has_vertex_colors, image_entries, built_images):
+ material = bpy.data.materials.new(material_name)
+ principled_node = material.node_tree.nodes["Principled BSDF"]
+ set_linear_rgba_socket(principled_node.inputs["Base Color"], material_entry["color"])
+ principled_node.inputs["Metallic"].default_value = material_entry.get("metallic", 0.0)
+ principled_node.inputs["Roughness"].default_value = material_entry.get("roughness", 0.5)
+ if material_entry.get("tag") == "liquid":
+ principled_node.inputs["Transmission Weight"].default_value = 1.0
+ principled_node.inputs["IOR"].default_value = material_entry["liquid"]["ior"]
+ configure_principled_layers(material, principled_node, material_entry)
+ if material_entry.get("emission", 0.0) > 0.0:
+ emission_color = material_entry.get("emissiveColor", material_entry["color"])
+ set_linear_rgba_socket(principled_node.inputs["Emission Color"], emission_color)
+ principled_node.inputs["Emission Strength"].default_value = material_entry["emission"]
+ if "map" in material_entry:
+ connect_base_color_texture(material, principled_node, material_entry, has_vertex_colors, image_entries, built_images)
+ elif has_vertex_colors:
+ connect_vertex_colors(material, principled_node, material_entry)
+ return material
+
+
+def build_scene_objects(scene, description):
+ built_meshes = {}
+ built_materials = {}
+ built_images = {}
+ image_entries = description.get("images", [])
+ for part_entry in description["parts"]:
+ geometry_index = part_entry["geometry"]
+ geometry_entry = description["geometries"][geometry_index]
+ has_vertex_colors = geometry_entry.get("colors") is not None
+ if geometry_index not in built_meshes:
+ mesh = build_blender_mesh(f"geometry-{geometry_index}", geometry_entry)
+ mesh.materials.append(None)
+ built_meshes[geometry_index] = mesh
+ material_key = (part_entry["material"], has_vertex_colors)
+ if material_key not in built_materials:
+ material_entry = description["materials"][part_entry["material"]]
+ material_name = f"material-{part_entry['material']}"
+ built_materials[material_key] = build_blender_material(material_name, material_entry, has_vertex_colors, image_entries, built_images)
+ mesh_object = bpy.data.objects.new(part_entry["name"], built_meshes[geometry_index])
+ mesh_object.material_slots[0].link = "OBJECT"
+ mesh_object.material_slots[0].material = built_materials[material_key]
+ column_major = part_entry["matrix"]
+ local_matrix = Matrix([[column_major[column * 4 + row] for column in range(4)] for row in range(4)])
+ mesh_object.matrix_world = Y_UP_TO_Z_UP @ local_matrix
+ scene.collection.objects.link(mesh_object)
+
+
+def build_world_shader(scene, world_description, repository_root):
+ world = bpy.data.worlds.new("World")
+ scene.world = world
+ nodes = world.node_tree.nodes
+ links = world.node_tree.links
+ background_node = nodes["Background"]
+ if world_description["type"] == "constant":
+ constant_value = world_description["value"]
+ background_node.inputs[0].default_value = (constant_value, constant_value, constant_value, 1.0)
+ background_node.inputs[1].default_value = 1.0
+ return
+ if world_description["type"] == "hdri":
+ coordinate_node = nodes.new("ShaderNodeTexCoord")
+ mapping_node = nodes.new("ShaderNodeMapping")
+ mapping_node.inputs["Rotation"].default_value = (0.0, 0.0, ENVIRONMENT_ROTATION_Z)
+ environment_node = nodes.new("ShaderNodeTexEnvironment")
+ environment_node.image = bpy.data.images.load(os.path.join(repository_root, world_description["file"]))
+ links.new(coordinate_node.outputs["Generated"], mapping_node.inputs["Vector"])
+ links.new(mapping_node.outputs["Vector"], environment_node.inputs["Vector"])
+ cap_node = nodes.new("ShaderNodeVectorMath")
+ cap_node.operation = "MINIMUM"
+ radiance_limit = world_description["radianceLimit"]
+ cap_node.inputs[1].default_value = (radiance_limit, radiance_limit, radiance_limit)
+ links.new(environment_node.outputs["Color"], cap_node.inputs[0])
+ links.new(cap_node.outputs["Vector"], background_node.inputs[0])
+ background_node.inputs[1].default_value = world_description["intensity"]
+ return
+ raise ValueError(f"Unsupported world description type '{world_description['type']}'.")
+
+
+def attach_light_receivers(light_object, receiver_names):
+ if receiver_names is None:
+ return
+ receiver_collection = bpy.data.collections.new(f"{light_object.name}-receivers")
+ for object_name in receiver_names:
+ receiver_collection.objects.link(bpy.data.objects[object_name])
+ light_object.light_linking.receiver_collection = receiver_collection
+
+
+def add_spot_light(scene, light_index, spot_entry):
+ light_data = bpy.data.lights.new(f"Spot-{light_index}", "SPOT")
+ light_data.energy = spot_entry["intensity"] * WATTS_PER_POINT_INTENSITY
+ light_data.color = spot_entry["color"]
+ light_data.shadow_soft_size = spot_entry["radius"]
+ light_data.spot_size = 2.0 * spot_entry["angle"]
+ light_data.spot_blend = spot_entry["penumbra"]
+ spot_object = bpy.data.objects.new(f"Spot-{light_index}", light_data)
+ spot_object.location = convert_position_to_blender(spot_entry["position"])
+ spot_object.rotation_mode = "QUATERNION"
+ aim_direction = Vector(convert_position_to_blender(spot_entry["direction"])).normalized()
+ spot_object.rotation_quaternion = aim_direction.to_track_quat("-Z", "Y")
+ scene.collection.objects.link(spot_object)
+ attach_light_receivers(spot_object, spot_entry.get("affects"))
+
+
+def add_area_light(scene, light_index, area_entry):
+ light_data = bpy.data.lights.new(f"Area-{light_index}", "AREA")
+ light_data.energy = area_entry["intensity"] * WATTS_PER_AREA_INTENSITY
+ light_data.color = area_entry["color"]
+ light_data.shape = "RECTANGLE"
+ light_data.size = area_entry["width"]
+ light_data.size_y = area_entry["height"]
+ area_object = bpy.data.objects.new(f"Area-{light_index}", light_data)
+ area_object.location = convert_position_to_blender(area_entry["position"])
+ normal_vector = Vector(convert_position_to_blender(area_entry["direction"])).normalized()
+ up_vector = Vector(convert_position_to_blender(area_entry.get("up", [0.0, 1.0, 0.0]))).normalized()
+ width_axis = up_vector.cross(normal_vector)
+ if width_axis.length < 1e-3:
+ width_axis = Vector((1.0, 0.0, 0.0))
+ width_axis.normalize()
+ height_axis = width_axis.cross(normal_vector)
+ rotation_matrix = Matrix((width_axis, height_axis, -normal_vector)).transposed()
+ area_object.rotation_mode = "QUATERNION"
+ area_object.rotation_quaternion = rotation_matrix.to_quaternion()
+ scene.collection.objects.link(area_object)
+ attach_light_receivers(area_object, area_entry.get("affects"))
+
+
+def build_scene_lights(scene, environment_entry):
+ key_color = environment_entry["keyColor"]
+ if max(key_color) > 0.0:
+ sun_strength = max(key_color)
+ sun_data = bpy.data.lights.new("Sun", "SUN")
+ sun_data.energy = sun_strength
+ sun_data.color = [channel / sun_strength for channel in key_color]
+ sun_data.angle = SUN_ANGULAR_DIAMETER
+ sun_object = bpy.data.objects.new("Sun", sun_data)
+ toward_light = Vector(convert_position_to_blender(environment_entry["lightDirection"])).normalized()
+ sun_object.rotation_mode = "QUATERNION"
+ sun_object.rotation_quaternion = toward_light.to_track_quat("Z", "Y")
+ scene.collection.objects.link(sun_object)
+ attach_light_receivers(sun_object, environment_entry.get("keyAffects"))
+ for light_index, point_entry in enumerate(environment_entry.get("pointLights", [])):
+ point_data = bpy.data.lights.new(f"Point-{light_index}", "POINT")
+ point_data.energy = point_entry["intensity"] * WATTS_PER_POINT_INTENSITY
+ point_data.color = point_entry["color"]
+ point_data.shadow_soft_size = point_entry["radius"]
+ point_object = bpy.data.objects.new(f"Point-{light_index}", point_data)
+ point_object.location = convert_position_to_blender(point_entry["position"])
+ scene.collection.objects.link(point_object)
+ attach_light_receivers(point_object, point_entry.get("affects"))
+ for light_index, spot_entry in enumerate(environment_entry.get("spotLights", [])):
+ add_spot_light(scene, light_index, spot_entry)
+ for light_index, area_entry in enumerate(environment_entry.get("areaLights", [])):
+ add_area_light(scene, light_index, area_entry)
+
+
+def build_camera_object(scene, camera_entry):
+ camera_data = bpy.data.cameras.new("Camera")
+ camera_data.sensor_fit = "VERTICAL"
+ camera_data.angle_y = math.radians(camera_entry["fov"])
+ camera_data.clip_start = camera_entry["near"]
+ camera_data.clip_end = camera_entry["far"]
+ camera_object = bpy.data.objects.new("Camera", camera_data)
+ eye_vector = Vector(convert_position_to_blender(camera_entry["eye"]))
+ target_vector = Vector(convert_position_to_blender(camera_entry["target"]))
+ camera_object.location = eye_vector
+ camera_object.rotation_mode = "QUATERNION"
+ camera_object.rotation_quaternion = (target_vector - eye_vector).to_track_quat("-Z", "Y")
+ scene.collection.objects.link(camera_object)
+ scene.camera = camera_object
+
+
+def configure_linear_exr_output(scene, width, height):
+ scene.render.resolution_x = width
+ scene.render.resolution_y = height
+ scene.render.resolution_percentage = 100
+ scene.render.image_settings.file_format = "OPEN_EXR"
+ scene.render.image_settings.color_depth = "32"
+ scene.render.image_settings.color_mode = "RGB"
+ scene.render.image_settings.exr_codec = "ZIP"
+ scene.view_settings.view_transform = "Raw"
+ scene.view_settings.look = "None"
+
+
+def configure_cycles_parity(scene, options):
+ scene.render.engine = "CYCLES"
+ preferences = bpy.context.preferences.addons["cycles"].preferences
+ preferences.compute_device_type = "OPTIX"
+ preferences.get_devices()
+ used_devices = []
+ for device in preferences.devices:
+ device.use = device.type == "OPTIX"
+ if device.use:
+ used_devices.append(device.name)
+ if not used_devices:
+ raise RuntimeError("No OptiX GPU device was found in Blender Cycles preferences.")
+ scene.cycles.device = "GPU"
+ scene.cycles.samples = options["samples"]
+ scene.cycles.seed = options["seed"]
+ scene.cycles.use_denoising = False
+ scene.cycles.use_adaptive_sampling = False
+ scene.cycles.pixel_filter_type = "BOX"
+ scene.cycles.filter_width = 1.0
+ scene.cycles.sample_clamp_direct = 0.0
+ scene.cycles.sample_clamp_indirect = 0.0
+ scene.cycles.caustics_reflective = True
+ scene.cycles.caustics_refractive = True
+ bounces = options["bounces"]
+ scene.cycles.max_bounces = bounces
+ scene.cycles.diffuse_bounces = bounces
+ scene.cycles.glossy_bounces = bounces
+ scene.cycles.transmission_bounces = bounces
+ scene.cycles.volume_bounces = bounces
+ scene.cycles.transparent_max_bounces = bounces
+ return used_devices
+
+
+def parse_megabytes_from_stats(stats_text):
+ matches = PEAK_MEMORY_PATTERN.findall(stats_text)
+ if not matches:
+ return None
+ scale_by_unit = {"K": 1.0 / 1024.0, "M": 1.0, "": 1.0, "G": 1024.0, "T": 1024.0 * 1024.0}
+ values = [float(number_text) * scale_by_unit.get(unit_text.upper(), 1.0) for number_text, unit_text in matches]
+ return max(values)
+
+
+def load_exr_into_npy(exr_path, npy_path, width, height, keep_exr):
+ loaded_image = bpy.data.images.load(exr_path)
+ rgba_pixels = numpy.empty(width * height * 4, dtype=numpy.float32)
+ loaded_image.pixels.foreach_get(rgba_pixels)
+ linear_rgb = rgba_pixels.reshape(height, width, 4)[::-1, :, :3].copy()
+ numpy.save(npy_path, linear_rgb)
+ bpy.data.images.remove(loaded_image)
+ if not keep_exr:
+ os.remove(exr_path)
+
+
+def render_part_identifier_map(scene, output_prefix, width, height):
+ mesh_objects = sorted([item for item in scene.objects if item.type == "MESH"], key=lambda item: item.name)
+ part_names = [item.name for item in mesh_objects]
+ for part_index, mesh_object in enumerate(mesh_objects, start=1):
+ part_material = bpy.data.materials.new(f"part-id-{part_index}")
+ part_material.diffuse_color = (part_index / PART_ID_STEPS, 0.0, 0.0, 1.0)
+ mesh_object.material_slots[0].material = part_material
+ scene.render.engine = "BLENDER_WORKBENCH"
+ scene.display.shading.light = "FLAT"
+ scene.display.shading.color_type = "MATERIAL"
+ scene.display.render_aa = "OFF"
+ scene.view_settings.view_transform = "Raw"
+ scene.world.color = (0.0, 0.0, 0.0)
+ temporary_exr = f"{output_prefix}-part-levels.exr"
+ temporary_npy = f"{output_prefix}-part-levels.npy"
+ scene.render.filepath = temporary_exr
+ bpy.ops.render.render(write_still=True)
+ load_exr_into_npy(temporary_exr, temporary_npy, width, height, False)
+ red_levels = numpy.load(temporary_npy)[:, :, 0]
+ os.remove(temporary_npy)
+ part_indices = numpy.rint(red_levels * PART_ID_STEPS).astype(numpy.int16)
+ numpy.save(f"{output_prefix}-parts.npy", part_indices)
+ with open(f"{output_prefix}-parts.json", "w", encoding="utf-8") as handle:
+ json.dump(part_names, handle, indent=2)
+ print("PART_IDS " + json.dumps({"parts": part_names, "outputPrefix": output_prefix}))
+
+
+def execute_timed_cycles_render(scene, exr_path):
+ scene.render.filepath = exr_path
+ stats_events = []
+ render_started = time.perf_counter()
+
+ def record_stats(*callback_arguments):
+ elapsed = time.perf_counter() - render_started
+ joined_text = " ".join(str(item) for item in callback_arguments if item is not None)
+ stats_events.append((elapsed, joined_text))
+
+ bpy.app.handlers.render_stats.append(record_stats)
+ try:
+ bpy.ops.render.render(write_still=True)
+ finally:
+ bpy.app.handlers.render_stats.remove(record_stats)
+ render_call_seconds = time.perf_counter() - render_started
+ first_sample_seconds = None
+ last_sample_seconds = None
+ peak_stats_megabytes = 0.0
+ for event_seconds, stats_text in stats_events:
+ parsed_peak = parse_megabytes_from_stats(stats_text)
+ if parsed_peak is not None:
+ peak_stats_megabytes = max(peak_stats_megabytes, parsed_peak)
+ if "Rendering " in stats_text or "Sample " in stats_text:
+ if first_sample_seconds is None:
+ first_sample_seconds = event_seconds
+ last_sample_seconds = event_seconds
+ if first_sample_seconds is None:
+ cycles_sync_seconds = render_call_seconds
+ sampling_seconds = 0.0
+ else:
+ cycles_sync_seconds = first_sample_seconds
+ end_seconds = last_sample_seconds if last_sample_seconds is not None and last_sample_seconds > first_sample_seconds else render_call_seconds
+ sampling_seconds = max(0.0, end_seconds - first_sample_seconds)
+ return {
+ "render_call_seconds": render_call_seconds,
+ "cycles_sync_seconds": cycles_sync_seconds,
+ "sampling_seconds": sampling_seconds,
+ "peak_stats_megabytes": peak_stats_megabytes,
+ "stats_event_count": len(stats_events),
+ "last_stats_text": stats_events[-1][1] if stats_events else "",
+ }
+
+
+def main():
+ options = parse_cli_arguments()
+ os.makedirs(os.path.dirname(options["output_prefix"]), exist_ok=True)
+ with open(options["scene_json_path"], encoding="utf-8") as handle:
+ description = json.load(handle)
+ repository_root = os.getcwd()
+ build_started = time.perf_counter()
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ scene = bpy.context.scene
+ build_scene_objects(scene, description)
+ build_world_shader(scene, description["world"], repository_root)
+ build_scene_lights(scene, description["environment"])
+ build_camera_object(scene, description["camera"])
+ configure_linear_exr_output(scene, options["width"], options["height"])
+ if options["part_ids"]:
+ render_part_identifier_map(scene, options["output_prefix"], options["width"], options["height"])
+ return
+ used_devices = configure_cycles_parity(scene, options)
+ scene_build_seconds = time.perf_counter() - build_started
+ exr_path = f"{options['output_prefix']}.exr"
+ npy_path = f"{options['output_prefix']}.npy"
+ timing = execute_timed_cycles_render(scene, exr_path)
+ load_exr_into_npy(exr_path, npy_path, options["width"], options["height"], options["keep_exr"])
+ setup_seconds = scene_build_seconds + timing["cycles_sync_seconds"]
+ total_trace_seconds = scene_build_seconds + timing["render_call_seconds"]
+ report = {
+ "engine": "cycles-optix",
+ "blenderVersion": bpy.app.version_string,
+ "devices": used_devices,
+ "sceneId": description["id"],
+ "npyPath": npy_path,
+ "exrPath": exr_path if options["keep_exr"] else None,
+ "width": options["width"],
+ "height": options["height"],
+ "samples": scene.cycles.samples,
+ "seed": scene.cycles.seed,
+ "bounces": scene.cycles.max_bounces,
+ "diffuseBounces": scene.cycles.diffuse_bounces,
+ "glossyBounces": scene.cycles.glossy_bounces,
+ "transmissionBounces": scene.cycles.transmission_bounces,
+ "volumeBounces": scene.cycles.volume_bounces,
+ "transparentMaxBounces": scene.cycles.transparent_max_bounces,
+ "useDenoising": scene.cycles.use_denoising,
+ "useAdaptiveSampling": scene.cycles.use_adaptive_sampling,
+ "pixelFilterType": scene.cycles.pixel_filter_type,
+ "filterWidth": scene.cycles.filter_width,
+ "sampleClampDirect": scene.cycles.sample_clamp_direct,
+ "sampleClampIndirect": scene.cycles.sample_clamp_indirect,
+ "causticsReflective": scene.cycles.caustics_reflective,
+ "causticsRefractive": scene.cycles.caustics_refractive,
+ "useLightTree": getattr(scene.cycles, "use_light_tree", None),
+ "viewTransform": scene.view_settings.view_transform,
+ "look": scene.view_settings.look,
+ "sceneBuildSeconds": round(scene_build_seconds, 6),
+ "cyclesSyncSeconds": round(timing["cycles_sync_seconds"], 6),
+ "setupSeconds": round(setup_seconds, 6),
+ "samplingSeconds": round(timing["sampling_seconds"], 6),
+ "renderCallSeconds": round(timing["render_call_seconds"], 6),
+ "totalTraceSeconds": round(total_trace_seconds, 6),
+ "cyclesPeakMemoryMegabytes": round(timing["peak_stats_megabytes"], 2),
+ "statsEventCount": timing["stats_event_count"],
+ "lastStatsText": timing["last_stats_text"],
+ }
+ with open(f"{options['output_prefix']}.json", "w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=2)
+ print("CYCLES_TRACE " + json.dumps(report))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/cycles-parity/root-loader.mjs b/bench/cycles-parity/root-loader.mjs
new file mode 100644
index 00000000..41c13e46
--- /dev/null
+++ b/bench/cycles-parity/root-loader.mjs
@@ -0,0 +1,15 @@
+// Resolves root-relative imports (/src/*, /bench/*, /packages/*) from the repository root so Node can load reference scenes directly.
+const REPOSITORY_ROOT_URL = new URL('../../', import.meta.url);
+const ROOT_PREFIXES = ['/src/', '/bench/', '/packages/', '/scripts/'];
+
+function hasRepositoryRootPrefix(specifier) {
+ return ROOT_PREFIXES.some((prefix) => specifier.startsWith(prefix));
+}
+
+export async function resolve(specifier, context, nextResolve) {
+ if (hasRepositoryRootPrefix(specifier)) {
+ const resolvedUrl = new URL(specifier.slice(1), REPOSITORY_ROOT_URL).href;
+ return nextResolve(resolvedUrl, context);
+ }
+ return nextResolve(specifier, context);
+}
diff --git a/bench/cycles-parity/run-m0-suite.py b/bench/cycles-parity/run-m0-suite.py
new file mode 100644
index 00000000..ff924ea7
--- /dev/null
+++ b/bench/cycles-parity/run-m0-suite.py
@@ -0,0 +1,219 @@
+"""Run the M0 Cycles 5.3 vs 67js native parity benchmark suite."""
+import json
+import os
+import subprocess
+import sys
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+DEFAULT_BLENDER_BINARY = r"C:\Program Files\Blender Foundation\Blender 5.3\blender.exe"
+DEFAULT_LADDER_SAMPLES = [16, 32, 64, 128, 256, 512, 1024]
+DEFAULT_EXTENDED_NATIVE_SAMPLES = [2048, 4096]
+
+
+def read_flag_value(argument_list, flag_name, fallback_value):
+ if flag_name not in argument_list:
+ return fallback_value
+ flag_index = argument_list.index(flag_name)
+ if flag_index + 1 >= len(argument_list):
+ raise ValueError(f"Flag {flag_name} requires a value.")
+ return argument_list[flag_index + 1]
+
+
+def parse_suite_arguments():
+ argument_list = sys.argv[1:]
+ if not argument_list or argument_list[0].startswith("--"):
+ raise ValueError("Usage: run-m0-suite.py <outputDirectory> [--scene lit-interior] [--repeats 3] [--bounces 8] [--mode all|references|ladder|compare]")
+ blender_binary = read_flag_value(argument_list, "--blender-bin", os.environ.get("BLENDER_BIN", DEFAULT_BLENDER_BINARY))
+ ladder_text = read_flag_value(argument_list, "--samples", ",".join(str(item) for item in DEFAULT_LADDER_SAMPLES))
+ extra_text = read_flag_value(argument_list, "--native-extra-samples", ",".join(str(item) for item in DEFAULT_EXTENDED_NATIVE_SAMPLES))
+ ladder_samples = [int(token) for token in ladder_text.split(",") if token.strip()]
+ extra_samples = [int(token) for token in extra_text.split(",") if token.strip()]
+ return {
+ "output_directory": os.path.abspath(argument_list[0]),
+ "scene_id": read_flag_value(argument_list, "--scene", "lit-interior"),
+ "repeats": int(read_flag_value(argument_list, "--repeats", "3")),
+ "bounces": int(read_flag_value(argument_list, "--bounces", "8")),
+ "reference_samples": int(read_flag_value(argument_list, "--reference-samples", "4096")),
+ "seed_a": int(read_flag_value(argument_list, "--seed-a", "1")),
+ "seed_b": int(read_flag_value(argument_list, "--seed-b", "2")),
+ "mode": read_flag_value(argument_list, "--mode", "all"),
+ "blender_binary": blender_binary,
+ "node_binary": read_flag_value(argument_list, "--node-bin", "node"),
+ "ladder_samples": ladder_samples,
+ "native_extra_samples": extra_samples,
+ "skip_existing": "--skip-existing" in argument_list,
+ }
+
+
+def run_checked_command(command):
+ completed = subprocess.run(command, check=False)
+ if completed.returncode != 0:
+ raise RuntimeError(f"Command failed with exit code {completed.returncode}: {' '.join(command)}")
+
+
+def wrap_with_gpu_lock(inner_command):
+ bash_binary = os.environ.get("GIT_BASH_BIN")
+ gpu_lock_script = os.environ.get("GPU_LOCK_SCRIPT")
+ if bash_binary and gpu_lock_script:
+ return [bash_binary, gpu_lock_script, *inner_command]
+ return inner_command
+
+
+def run_measured_gpu_step(prefix_path, render_command, skip_existing):
+ npy_file = f"{prefix_path}.npy"
+ json_file = f"{prefix_path}.json"
+ metrics_file = f"{prefix_path}.metrics.json"
+ if skip_existing and os.path.exists(npy_file) and os.path.exists(json_file) and os.path.exists(metrics_file):
+ return
+ measure_command = [
+ "uv",
+ "run",
+ "--no-project",
+ "--with",
+ "psutil",
+ "python",
+ "bench/cycles-parity/measure-gpu-run.py",
+ metrics_file,
+ "--",
+ *render_command,
+ ]
+ run_checked_command(wrap_with_gpu_lock(measure_command))
+
+
+def build_cycles_command(options, scene_json_path, prefix_path, samples, seed, keep_exr):
+ command = [
+ options["blender_binary"],
+ "-b",
+ "--factory-startup",
+ "--python",
+ "bench/cycles-parity/render-cycles.py",
+ "--",
+ scene_json_path,
+ prefix_path,
+ "--samples",
+ str(samples),
+ "--bounces",
+ str(options["bounces"]),
+ "--seed",
+ str(seed),
+ ]
+ if keep_exr:
+ command.append("--keep-exr")
+ return command
+
+
+def build_native_command(options, scene_json_path, prefix_path, samples, seed):
+ return [
+ options["node_binary"],
+ "bench/cycles-parity/trace-native.mjs",
+ scene_json_path,
+ prefix_path,
+ "--samples",
+ str(samples),
+ "--bounces",
+ str(options["bounces"]),
+ "--seed",
+ str(seed),
+ "--firefly-clamp",
+ "1000000000",
+ "--noise-threshold",
+ "0",
+ ]
+
+
+def ensure_scene_and_parts(options, scene_json_path, parts_prefix):
+ if not os.path.exists(scene_json_path):
+ run_checked_command([
+ options["node_binary"],
+ "bench/cycles-parity/export-scene.mjs",
+ options["output_directory"],
+ "--scene",
+ options["scene_id"],
+ ])
+ if not os.path.exists(f"{parts_prefix}-parts.npy"):
+ part_command = [
+ options["blender_binary"],
+ "-b",
+ "--factory-startup",
+ "--python",
+ "bench/cycles-parity/render-cycles.py",
+ "--",
+ scene_json_path,
+ parts_prefix,
+ "--part-ids",
+ ]
+ run_checked_command(wrap_with_gpu_lock(part_command))
+
+
+def main():
+ options = parse_suite_arguments()
+ scene_id = options["scene_id"]
+ out_dir = options["output_directory"]
+ scene_json_path = os.path.join(out_dir, "scenes", f"{scene_id}.json")
+ parts_prefix = os.path.join(out_dir, "scenes", scene_id)
+ ensure_scene_and_parts(options, scene_json_path, parts_prefix)
+ ref_dir = os.path.join(out_dir, "reference")
+ ladder_dir = os.path.join(out_dir, "ladder")
+ os.makedirs(ref_dir, exist_ok=True)
+ os.makedirs(ladder_dir, exist_ok=True)
+ ref_seed_a = os.path.join(ref_dir, f"{scene_id}-cycles-{options['reference_samples']}-seed{options['seed_a']}")
+ ref_seed_b = os.path.join(ref_dir, f"{scene_id}-cycles-{options['reference_samples']}-seed{options['seed_b']}")
+ mode = options["mode"]
+ if mode in ("all", "references"):
+ cmd_a = build_cycles_command(options, scene_json_path, ref_seed_a, options["reference_samples"], options["seed_a"], True)
+ run_measured_gpu_step(ref_seed_a, cmd_a, options["skip_existing"])
+ cmd_b = build_cycles_command(options, scene_json_path, ref_seed_b, options["reference_samples"], options["seed_b"], True)
+ run_measured_gpu_step(ref_seed_b, cmd_b, options["skip_existing"])
+ cycles_prefixes = []
+ native_prefixes = []
+ for sample_count in options["ladder_samples"]:
+ for repeat_index in range(1, options["repeats"] + 1):
+ cycles_prefix = os.path.join(ladder_dir, f"{scene_id}-cycles-s{sample_count}-r{repeat_index}")
+ native_prefix = os.path.join(ladder_dir, f"{scene_id}-native-s{sample_count}-r{repeat_index}")
+ cycles_prefixes.append(cycles_prefix)
+ native_prefixes.append(native_prefix)
+ if mode in ("all", "ladder"):
+ cycles_cmd = build_cycles_command(options, scene_json_path, cycles_prefix, sample_count, options["seed_a"], False)
+ run_measured_gpu_step(cycles_prefix, cycles_cmd, options["skip_existing"])
+ native_cmd = build_native_command(options, scene_json_path, native_prefix, sample_count, options["seed_a"])
+ run_measured_gpu_step(native_prefix, native_cmd, options["skip_existing"])
+ for extra_sample_count in options["native_extra_samples"]:
+ for repeat_index in range(1, options["repeats"] + 1):
+ extra_prefix = os.path.join(ladder_dir, f"{scene_id}-native-s{extra_sample_count}-r{repeat_index}")
+ native_prefixes.append(extra_prefix)
+ if mode in ("all", "ladder"):
+ extra_cmd = build_native_command(options, scene_json_path, extra_prefix, extra_sample_count, options["seed_a"])
+ run_measured_gpu_step(extra_prefix, extra_cmd, options["skip_existing"])
+ highest_native_samples = max(options["ladder_samples"] + options["native_extra_samples"])
+ detail_prefix = os.path.join(ladder_dir, f"{scene_id}-native-s{highest_native_samples}-r1")
+ manifest_path = os.path.join(out_dir, f"{scene_id}-manifest.json")
+ summary_path = os.path.join(out_dir, f"{scene_id}-summary.json")
+ manifest = {
+ "sceneId": scene_id,
+ "referenceSeedAPrefix": ref_seed_a,
+ "referenceSeedBPrefix": ref_seed_b,
+ "cyclesLadderPrefixes": cycles_prefixes,
+ "nativeLadderPrefixes": native_prefixes,
+ "nativeDetailPrefix": detail_prefix,
+ "partsPrefix": parts_prefix,
+ "outputSummaryPath": summary_path,
+ }
+ with open(manifest_path, "w", encoding="utf-8") as handle:
+ json.dump(manifest, handle, indent=2)
+ if mode in ("all", "compare"):
+ run_checked_command([
+ "uv",
+ "run",
+ "--no-project",
+ "--with",
+ "numpy",
+ "python",
+ "bench/cycles-parity/compare.py",
+ "suite",
+ manifest_path,
+ ])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/cycles-parity/scene-bridge.mjs b/bench/cycles-parity/scene-bridge.mjs
new file mode 100644
index 00000000..0ee76e6f
--- /dev/null
+++ b/bench/cycles-parity/scene-bridge.mjs
@@ -0,0 +1,279 @@
+import { readFile } from 'node:fs/promises';
+import { register } from 'node:module';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+register('./root-loader.mjs', import.meta.url);
+
+const REPOSITORY_ROOT_PATH = fileURLToPath(new URL('../../', import.meta.url));
+const TYPED_ARRAY_CONSTRUCTORS = {
+ Float32Array,
+ Uint32Array,
+ Uint16Array,
+ Uint8Array,
+ Uint8ClampedArray,
+};
+
+function encodeTypedArray(typedArray) {
+ const byteView = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
+ return {
+ type: typedArray.constructor.name,
+ base64: Buffer.from(byteView).toString('base64'),
+ };
+}
+
+function decodeTypedArray(encodedEntry) {
+ if (encodedEntry === null || encodedEntry === undefined) {
+ return undefined;
+ }
+ const Constructor = TYPED_ARRAY_CONSTRUCTORS[encodedEntry.type];
+ if (!Constructor) {
+ throw new TypeError(`Unsupported typed array entry type "${encodedEntry.type}".`);
+ }
+ const rawBuffer = Buffer.from(encodedEntry.base64, 'base64');
+ const alignedBytes = new Uint8Array(rawBuffer.byteLength);
+ alignedBytes.set(rawBuffer);
+ return new Constructor(alignedBytes.buffer, 0, alignedBytes.byteLength / Constructor.BYTES_PER_ELEMENT);
+}
+
+function isImageDataLike(value) {
+ if (!value || typeof value !== 'object') {
+ return false;
+ }
+ const hasDimensions = Number.isInteger(value.width) && Number.isInteger(value.height);
+ const hasByteArray = value.data instanceof Uint8ClampedArray || value.data instanceof Uint8Array;
+ return hasDimensions && hasByteArray && Object.keys(value).length <= 4;
+}
+
+function serializePlainValue(value, imageTable) {
+ if (ArrayBuffer.isView(value)) {
+ return encodeTypedArray(value);
+ }
+ if (isImageDataLike(value)) {
+ if (!imageTable) {
+ return {
+ width: value.width,
+ height: value.height,
+ data: encodeTypedArray(value.data),
+ };
+ }
+ if (!imageTable.identifiers.has(value)) {
+ const nextIdentifier = imageTable.entries.length;
+ imageTable.identifiers.set(value, nextIdentifier);
+ imageTable.entries.push({
+ width: value.width,
+ height: value.height,
+ data: encodeTypedArray(value.data),
+ });
+ }
+ return { imageId: imageTable.identifiers.get(value) };
+ }
+ if (Array.isArray(value)) {
+ return value.map((entry) => serializePlainValue(entry, imageTable));
+ }
+ if (value && typeof value === 'object') {
+ const serializedObject = {};
+ for (const [key, entry] of Object.entries(value)) {
+ if (typeof entry !== 'function') {
+ serializedObject[key] = serializePlainValue(entry, imageTable);
+ }
+ }
+ return serializedObject;
+ }
+ return value;
+}
+
+function createMaterialTable() {
+ const imageTable = {
+ identifiers: new Map(),
+ entries: [],
+ };
+ const materials = [];
+ const indexByJson = new Map();
+ function indexOf(material) {
+ const serializedMaterial = serializePlainValue(material, imageTable);
+ const key = JSON.stringify(serializedMaterial);
+ if (!indexByJson.has(key)) {
+ indexByJson.set(key, materials.length);
+ materials.push(serializedMaterial);
+ }
+ return indexByJson.get(key);
+ }
+ return {
+ indexOf,
+ materials,
+ images: imageTable.entries,
+ };
+}
+
+async function resolvePartGeometry(part, boxProjectedCache) {
+ if (part.skin) {
+ const { skinnedGeometry } = await import('../../src/path-tracer-scene.js');
+ return skinnedGeometry(part);
+ }
+ const boxMapScale = part.material.boxMapScale;
+ if (!(boxMapScale > 0) || part.geometry.uvs) {
+ return part.geometry;
+ }
+ const { boxProjectedGeometry } = await import('../../src/export-box-uv.js');
+ const { matrix } = part;
+ const partScale = [0, 1, 2].map((column) => Math.hypot(matrix[column * 4], matrix[column * 4 + 1], matrix[column * 4 + 2]));
+ const cacheKey = `${partScale.join(',')}|${boxMapScale}|${part.material.boxMapAxis ?? 1}`;
+ if (!boxProjectedCache.has(part.geometry)) {
+ boxProjectedCache.set(part.geometry, new Map());
+ }
+ const byScale = boxProjectedCache.get(part.geometry);
+ if (!byScale.has(cacheKey)) {
+ const projected = boxProjectedGeometry(part.geometry, partScale, boxMapScale, part.material.boxMapAxis ?? 1);
+ byScale.set(cacheKey, projected);
+ }
+ return byScale.get(cacheKey);
+}
+
+export async function loadReferenceScene(sceneId) {
+ const [{ REFERENCE_SCENES }, { applyLightLinks }] = await Promise.all([
+ import('../../bench/reference/scenes.js'),
+ import('../../src/light-linking.js'),
+ ]);
+ const sceneFactory = REFERENCE_SCENES[sceneId];
+ if (!sceneFactory) {
+ const availableIds = Object.keys(REFERENCE_SCENES).join(', ');
+ throw new RangeError(`Unknown reference scene "${sceneId}". Pass one of: ${availableIds}.`);
+ }
+ const rawScene = await sceneFactory();
+ const linkedParts = applyLightLinks(rawScene.parts, rawScene.environment);
+ return {
+ rawScene,
+ traceSource: {
+ parts: linkedParts,
+ environment: rawScene.environment,
+ camera: rawScene.camera,
+ },
+ };
+}
+
+export async function serializeSceneDescription(sceneId, rawScene) {
+ const { map: _ignoredEnvironmentMap, ...serializableEnvironment } = rawScene.environment;
+ const geometryIndices = new Map();
+ const boxProjectedCache = new Map();
+ const materialTable = createMaterialTable();
+ const serializedParts = [];
+ for (const part of rawScene.parts) {
+ const geometry = await resolvePartGeometry(part, boxProjectedCache);
+ if (!geometryIndices.has(geometry)) {
+ geometryIndices.set(geometry, geometryIndices.size);
+ }
+ serializedParts.push({
+ name: part.name,
+ geometry: geometryIndices.get(geometry),
+ matrix: [...part.matrix],
+ material: materialTable.indexOf(part.material),
+ });
+ }
+ const serializedGeometries = [...geometryIndices.keys()].map((geometry) => serializePlainValue({
+ positions: geometry.positions,
+ normals: geometry.normals,
+ uvs: geometry.uvs,
+ colors: geometry.colors,
+ indices: geometry.indices,
+ }, null));
+ return {
+ id: sceneId,
+ camera: rawScene.camera,
+ environment: serializableEnvironment,
+ world: rawScene.blenderWorld,
+ blenderCloth: rawScene.blenderCloth,
+ brightRegion: rawScene.brightRegion,
+ materials: materialTable.materials,
+ images: materialTable.images,
+ parts: serializedParts,
+ geometries: serializedGeometries,
+ };
+}
+
+function restorePlainValue(value, decodedImages) {
+ if (!value || typeof value !== 'object') {
+ return value;
+ }
+ if (typeof value.type === 'string' && typeof value.base64 === 'string' && Object.keys(value).length === 2) {
+ return decodeTypedArray(value);
+ }
+ if (Number.isInteger(value.imageId) && Object.keys(value).length === 1) {
+ return decodedImages[value.imageId];
+ }
+ if (Array.isArray(value)) {
+ return value.map((entry) => restorePlainValue(entry, decodedImages));
+ }
+ const restored = {};
+ for (const [key, entry] of Object.entries(value)) {
+ restored[key] = restorePlainValue(entry, decodedImages);
+ }
+ return restored;
+}
+
+async function rebuildEnvironmentMap(worldDescription, repositoryRootPath = REPOSITORY_ROOT_PATH) {
+ const { createEnvironmentMap, parseRadianceHdr } = await import('../../src/hdri.js');
+ if (worldDescription.type === 'constant') {
+ const constantData = new Float32Array(8 * 4 * 3).fill(worldDescription.value);
+ return createEnvironmentMap({
+ width: 8,
+ height: 4,
+ data: constantData,
+ showBackground: true,
+ });
+ }
+ if (worldDescription.type === 'hdri') {
+ const hdriBytes = await readFile(join(repositoryRootPath, worldDescription.file));
+ const parsedHdri = parseRadianceHdr(hdriBytes.buffer.slice(hdriBytes.byteOffset, hdriBytes.byteOffset + hdriBytes.byteLength));
+ const cappedData = parsedHdri.data.map((radiance) => Math.min(radiance, worldDescription.radianceLimit));
+ return createEnvironmentMap({
+ ...parsedHdri,
+ data: cappedData,
+ intensity: worldDescription.intensity,
+ showBackground: true,
+ });
+ }
+ throw new RangeError(`Unsupported world description type "${worldDescription.type}".`);
+}
+
+export async function reconstructTraceSceneSource(description, repositoryRootPath = REPOSITORY_ROOT_PATH) {
+ const { applyLightLinks } = await import('../../src/light-linking.js');
+ const decodedImages = (description.images ?? []).map((imageEntry) => ({
+ width: imageEntry.width,
+ height: imageEntry.height,
+ data: decodeTypedArray(imageEntry.data),
+ }));
+ const decodedGeometries = description.geometries.map((geometryEntry) => {
+ const restoredGeometry = {
+ positions: decodeTypedArray(geometryEntry.positions),
+ normals: decodeTypedArray(geometryEntry.normals),
+ indices: decodeTypedArray(geometryEntry.indices),
+ };
+ const uvs = decodeTypedArray(geometryEntry.uvs);
+ if (uvs) {
+ restoredGeometry.uvs = uvs;
+ }
+ const colors = decodeTypedArray(geometryEntry.colors);
+ if (colors) {
+ restoredGeometry.colors = colors;
+ }
+ return restoredGeometry;
+ });
+ const decodedMaterials = description.materials.map((materialEntry) => restorePlainValue(materialEntry, decodedImages));
+ const rawParts = description.parts.map((partEntry) => ({
+ name: partEntry.name,
+ geometry: decodedGeometries[partEntry.geometry],
+ matrix: new Float32Array(partEntry.matrix),
+ material: decodedMaterials[partEntry.material],
+ }));
+ const environmentMap = await rebuildEnvironmentMap(description.world, repositoryRootPath);
+ const fullEnvironment = {
+ ...description.environment,
+ map: environmentMap,
+ };
+ return {
+ parts: applyLightLinks(rawParts, fullEnvironment),
+ environment: fullEnvironment,
+ camera: description.camera,
+ };
+}
diff --git a/bench/cycles-parity/trace-native.mjs b/bench/cycles-parity/trace-native.mjs
new file mode 100644
index 00000000..4bf77ee4
--- /dev/null
+++ b/bench/cycles-parity/trace-native.mjs
@@ -0,0 +1,129 @@
+// Traces an exported scene JSON on packages/render-native and writes linear RGB float32 (.npy) plus timing JSON.
+// node bench/cycles-parity/trace-native.mjs <sceneJsonPath> <outputPrefix> [--samples 256] [--bounces 8] [--seed 1]
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { dirname, resolve } from 'node:path';
+import { createCamera } from '../../src/path-tracer.js';
+import * as packModule from '../../src/path-tracer-gpu-pack.js';
+import { buildTraceScene } from '../../src/path-tracer-scene.js';
+import { buildNativeInput, findNativeAddon, traceNative } from '../../packages/render-native/index.mjs';
+import { writeFloat32Npy } from './npy.mjs';
+import { reconstructTraceSceneSource } from './scene-bridge.mjs';
+
+function readFlagValue(argumentList, flagName, fallbackValue) {
+ const flagIndex = argumentList.indexOf(flagName);
+ if (flagIndex === -1) {
+ return fallbackValue;
+ }
+ const nextValue = argumentList[flagIndex + 1];
+ if (nextValue === undefined || nextValue.startsWith('--')) {
+ throw new RangeError(`Flag ${flagName} requires a value.`);
+ }
+ return nextValue;
+}
+
+function parseIntegerOption(argumentList, flagName, fallbackValue, minimumValue) {
+ const parsed = Number(readFlagValue(argumentList, flagName, fallbackValue));
+ if (!Number.isInteger(parsed) || parsed < minimumValue) {
+ throw new RangeError(`Option ${flagName} must be an integer >= ${minimumValue}, got ${parsed}.`);
+ }
+ return parsed;
+}
+
+function parseNumberOption(argumentList, flagName, fallbackValue, minimumValue) {
+ const parsed = Number(readFlagValue(argumentList, flagName, fallbackValue));
+ if (!Number.isFinite(parsed) || parsed < minimumValue) {
+ throw new RangeError(`Option ${flagName} must be a finite number >= ${minimumValue}, got ${parsed}.`);
+ }
+ return parsed;
+}
+
+function parseTraceArguments(argumentList) {
+ if (argumentList.length < 2 || argumentList[0].startsWith('--') || argumentList[1].startsWith('--')) {
+ throw new RangeError('Usage: node bench/cycles-parity/trace-native.mjs <sceneJsonPath> <outputPrefix> [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--firefly-clamp 1e9] [--noise-threshold 0]');
+ }
+ return {
+ sceneJsonPath: resolve(argumentList[0]),
+ outputPrefix: resolve(argumentList[1]),
+ width: parseIntegerOption(argumentList, '--width', 960, 16),
+ height: parseIntegerOption(argumentList, '--height', 540, 16),
+ samples: parseIntegerOption(argumentList, '--samples', 256, 1),
+ bounces: parseIntegerOption(argumentList, '--bounces', 8, 0),
+ seed: parseIntegerOption(argumentList, '--seed', 1, 0),
+ fireflyClamp: parseNumberOption(argumentList, '--firefly-clamp', 1e9, 0),
+ noiseThreshold: parseNumberOption(argumentList, '--noise-threshold', 0, 0),
+ maxSeconds: parseNumberOption(argumentList, '--max-seconds', 1800, 1),
+ };
+}
+
+function extractLinearRgb(rgbaPixels, pixelCount) {
+ const linearRgb = new Float32Array(pixelCount * 3);
+ for (let pixelIndex = 0; pixelIndex < pixelCount; pixelIndex++) {
+ const sourceOffset = pixelIndex * 4;
+ const targetOffset = pixelIndex * 3;
+ linearRgb[targetOffset] = rgbaPixels[sourceOffset];
+ linearRgb[targetOffset + 1] = rgbaPixels[sourceOffset + 1];
+ linearRgb[targetOffset + 2] = rgbaPixels[sourceOffset + 2];
+ }
+ return linearRgb;
+}
+
+async function runCli() {
+ setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+ const options = parseTraceArguments(process.argv.slice(2));
+ if (!findNativeAddon()) {
+ throw new Error('The render-native addon is missing. Build packages/render-native before running trace-native.mjs.');
+ }
+ const description = JSON.parse(await readFile(options.sceneJsonPath, 'utf8'));
+ await mkdir(dirname(options.outputPrefix), { recursive: true });
+ const totalStarted = performance.now();
+ const buildStarted = performance.now();
+ const traceSource = await reconstructTraceSceneSource(description);
+ const traceScene = buildTraceScene(traceSource.parts, traceSource.environment);
+ const camera = createCamera(traceSource.camera, options.width, options.height);
+ const nativeInput = buildNativeInput(traceScene, camera, options, packModule);
+ const sceneBuildSeconds = (performance.now() - buildStarted) / 1000;
+ const traced = traceNative(nativeInput, {
+ width: options.width,
+ height: options.height,
+ samples: options.samples,
+ maxSeconds: options.maxSeconds,
+ });
+ const totalTraceSeconds = (performance.now() - totalStarted) / 1000;
+ const postTraceRssMegabytes = process.memoryUsage().rss / (1024 * 1024);
+ const pixelCount = options.width * options.height;
+ const linearRgb = extractLinearRgb(traced.rgba, pixelCount);
+ const npyPath = `${options.outputPrefix}.npy`;
+ await writeFloat32Npy(npyPath, linearRgb, [options.height, options.width, 3]);
+ const setupSeconds = sceneBuildSeconds + traced.setupSeconds + traced.compileSeconds + traced.uploadSeconds + traced.accelerationBuildSeconds;
+ const report = {
+ engine: '67js-render-native',
+ sceneId: description.id,
+ npyPath,
+ width: options.width,
+ height: options.height,
+ samples: options.samples,
+ averageSamples: traced.averageSamples,
+ bounces: options.bounces,
+ seed: options.seed,
+ fireflyClamp: options.fireflyClamp,
+ noiseThreshold: options.noiseThreshold,
+ triangleCount: nativeInput.triangleCount,
+ adapter: traced.adapter,
+ backend: traced.backend,
+ features: traced.features,
+ sceneBuildSeconds: Number(sceneBuildSeconds.toFixed(6)),
+ deviceSetupSeconds: Number(traced.setupSeconds.toFixed(6)),
+ compileSeconds: Number(traced.compileSeconds.toFixed(6)),
+ uploadSeconds: Number(traced.uploadSeconds.toFixed(6)),
+ accelerationBuildSeconds: Number(traced.accelerationBuildSeconds.toFixed(6)),
+ setupSeconds: Number(setupSeconds.toFixed(6)),
+ samplingSeconds: Number(traced.tracedSeconds.toFixed(6)),
+ totalTraceSeconds: Number(totalTraceSeconds.toFixed(6)),
+ nodeRssMegabytes: Number(postTraceRssMegabytes.toFixed(2)),
+ };
+ await writeFile(`${options.outputPrefix}.json`, `${JSON.stringify(report, null, 2)}\n`);
+ console.log(`NATIVE_TRACE ${JSON.stringify(report)}`);
+}
+
+await runCli();
diff --git a/docs/cycles-parity.md b/docs/cycles-parity.md
new file mode 100644
index 00000000..34e9e088
--- /dev/null
+++ b/docs/cycles-parity.md
@@ -0,0 +1,234 @@
+# Cycles 5.3 Parity Baseline (M0)
+
+Milestone M0 measures today's native path tracer ([`packages/render-native`](../packages/render-native/README.md), legacy `kernel.wgsl` on `wgpu 30.0.1` Vulkan `EXPERIMENTAL_RAY_QUERY`) against **Blender 5.3.0 Cycles OptiX** under matched unbiased settings on a single reference scene before any Cycles-kernel port changes land.
+
+All claims below are tagged `[measured]` (from benchmark artifacts produced by [`bench/cycles-parity/`](../bench/cycles-parity/run-m0-suite.py)), `[source]` (verified in 67js or Blender 5.3 source), or `[inferred]`.
+
+## Summary Verdict
+
+- **Per-sample speed vs equal-error speed (`T_eq`) `[measured]`**: On `lit-interior` (`960 × 540`, `8` bounces, unclamped, undenoised), 67js `render-native` traces `256` samples in **`2.101 s`** median sampling time (`2.381 s` total trace) vs **`11.371 s`** (`13.456 s` total trace) in Cycles 5.3 OptiX — **`5.41×` faster per sample (`0.185×` time)**. However, at `256` samples 67js has **`6.33×` higher `relMSE`** (`0.019762` vs `0.003121`) and still has not reached Cycles' 256-spp error at `1024` samples (`0.005135`). Extending the 67js ladder to `2048` (`0.002679`) and `4096` (`0.001453`) samples brackets Cycles' 256-spp `relMSE` at **`1,740.5` samples (`6.80×` as many samples)**, giving **`T_eq = 10.331 s` sampling (`T_eq / T_cycles = 0.909×`)** and **`12.886 s` total trace (`0.958×`)**. Nearly the entire `5.4×` raw ray-tracing speed lead on this 3,072-triangle room is consumed by higher Monte Carlo variance (no light tree on bounces, white-noise PCG instead of Sobol + blue noise).
+- **Setup latency (`T_sync`), RAM, and VRAM `[measured]`**: Warm per-call setup is **`0.244 s`** median in 67js (`0.026 s` JS pack + `0.164 s` Vulkan adapter/device + `0.005 s` WGSL compile + `0.009 s` upload + `0.002 s` BLAS/TLAS) vs **`2.012 s`** in headless Blender/Cycles (`~1.80 s` Python/mesh build + `~0.21 s` Cycles OptiX sync), even though 67js recreates its `wgpu` device, pipeline, and acceleration structures on every call. Peak process-tree RSS is **`287.0 MiB`** in 67js vs **`590.2 MiB`** in Blender (`0.49×`). Cycles reports **`Mem: 351.0 MiB`** peak render memory; uncontended 67js runs at `2048–4096` spp measure **`211–433 MiB`** card VRAM delta (`769–998 MiB` total card VRAM above a `558–565 MiB` desktop baseline).
+- **Radiometric bias (`[measured]`)**: At `4096` samples against Cycles `4096` spp (`Seed 1`, whose `Seed 1` vs `Seed 2` noise floor is `relMSE = 0.000285`), 67js global per-channel mean ratios are **`R = 1.0104, G = 1.0090, B = 1.0068`** (`+1.04% R, +0.90% G, +0.68% B`, scalar `1.0092`), and **all `64 / 64` tiles** in an `8 × 8` grid lie within `1 ± 0.05` (`min = 0.9849`, `median = 1.0034`, `max = 1.0280`). Fitting `relMSE(N) = B_bias + V / N` across `16..4096` spp isolates a systematic bias plateau **`B_bias = 0.000542`** (`~1.9×` the 4096-spp reference noise floor) driven by sphere point-light falloff near the ceiling (`+2.8%`) and missing multiscatter GGX + light-sphere reflections on the glossy table (`-2.1%`).
+
+---
+
+## Scene, Hardware, and Matched Settings
+
+### Scene: `lit-interior`
+
+Exported losslessly from [`bench/reference/scenes.js`](../bench/reference/scenes.js) via [`bench/cycles-parity/export-scene.mjs`](../bench/cycles-parity/export-scene.mjs), which verifies byte-for-byte identity across all seven packed `NativeTraceInput` buffers (`triangles`, `materials`, `lights`, `atlas`, `environmentColors`, `environmentTables`, `parameters`) before and after JSON serialization `[measured]`:
+
+- **Geometry**: `9` parts (`room-floor`, `room-ceiling`, `room-back`, `room-left`, `room-right`, `table`, `table-leg`, `vase`, `block`), `8` dielectric materials (`roughness` `0.2` to `0.9`, `metallic = 0`), `3,072` triangles (`roundTripVerified = true`).
+- **Lighting**: `3` spherical point lights (`radius = 0.05 m`): overhead warm key (`[0, 2.6, -0.5]`, `color = [1.0, 0.9, 0.75]`, `intensity = 8`, `100.53 W` in Cycles), left warm fill (`[-2.5, 1.5, 1.5]`, `[1.0, 0.6, 0.4]`, `intensity = 2`, `25.13 W`), right cool fill (`[2.5, 1.5, 1.5]`, `[0.5, 0.7, 1.0]`, `intensity = 2`, `25.13 W`), plus a constant `0.02` world background (`emitterCount = 4` in 67js).
+- **Camera**: `eye = [0, 1.5, 3.9]`, `target = [0, 1.0, -1.0]`, vertical `fov = 50°`, `960 × 540` (`518,400` pixels).
+
+### Hardware & Contention Disclosure
+
+- **Machine `[measured]`**: NVIDIA GeForce RTX 3060 (`12,288 MiB` VRAM), Windows, Node.js `v24.19.0`, Blender `5.3.0` (`CYCLES` `OPTIX`), `packages/render-native` (`wgpu 30.0.1`, Vulkan `EXPERIMENTAL_RAY_QUERY`).
+- **GPU scheduling & exclusivity `[measured]`**: Every GPU command ran at `BelowNormal` priority under the machine-wide `gpu-lock` wrapper and [`bench/cycles-parity/measure-gpu-run.py`](../bench/cycles-parity/measure-gpu-run.py) (`50 ms` `nvidia-smi` stream + `25 ms` process-tree RSS polling). During the `4096`-spp references and the `16..1024`-spp ladder, another session's light-slot Blender/Node workload shared the RTX 3060 (`gpuExclusive = false`, pre-run card VRAM `6,812–7,650 MiB`). To prevent drift from skewing engine comparisons, every ladder point ran **3 interleaved back-to-back pairs** (`Cycles` immediately followed by `67js` for `r1`, `r2`, `r3`). During the extended `2048` and `4096` spp 67js runs (`s2048-r1`, `s4096-r1`), the foreign render exited (`baselineCardVramMegabytes = 558–565 MiB`, `preRunGpuUtilizationPercent = 11%–14%`, only idle desktop Chrome attached), providing uncontended card VRAM delta measurements alongside Cycles' internal `Mem:` counter.
+
+### Strictly Matched Parity Configuration
+
+| Parameter | Cycles 5.3 OptiX ([`render-cycles.py`](../bench/cycles-parity/render-cycles.py)) | 67js `render-native` ([`trace-native.mjs`](../bench/cycles-parity/trace-native.mjs)) | Why override default |
+| --- | --- | --- | --- |
+| Resolution | `960 × 540` (`100%`) | `width: 960, height: 540` | Same pixel grid (`518,400` pixels) |
+| Bounces | `max_bounces = 8`, `diffuse = glossy = transmission = volume = transparent_max = 8` | `bounces: 8` | Cycles defaults to `diffuse = 4, glossy = 4, max = 12`; 67js uses one shared limit |
+| Caustics | `caustics_reflective = True`, `caustics_refractive = True` | Always traced | Match glossy-to-diffuse indirect transport |
+| Radiance clamping | `sample_clamp_direct = 0.0`, `sample_clamp_indirect = 0.0` (`FLT_MAX`) | `fireflyClamp: 1e9` | Cycles default `indirect = 10` clamps at `30` (`×3`); 67js default clamps peak channel to `20` at `depth > 0` |
+| Denoising | `use_denoising = False` | Raw `traced.rgba` (no wavelet/OIDN) | Measure raw Monte Carlo estimator |
+| Adaptive sampling | `use_adaptive_sampling = False` | `noiseThreshold: 0` | Draw exact `N` samples at every pixel |
+| Pixel filter | `pixel_filter_type = 'BOX'`, `filter_width = 1.0` | Uniform jitter in `[0, 1)^2` | Cycles default Blackman-Harris `1.5 px` blurs/rings across pixel boundaries |
+| Color space | `OPEN_EXR` `32`-bit float RGB, `view_transform = 'Raw'`, `look = 'None'` | Linear `Float32Array` RGB `.npy` | Scene-referred linear float32 with no tone map |
+
+### Bounce-Count Semantics Verification
+
+- **Source semantics `[source]`**:
+ - In **Cycles** (`intern/cycles/scene/integrator.cpp:227`, `kernel/integrator/path_state.h:146`, `shade_surface.h:840-867`), setting `max_bounces = B` stores `kintegrator->max_bounce = B + 1`. Camera hits start at `path.bounce = 0`. Surface direct-light NEE (`integrate_surface_direct_light`) executes at `path.bounce = 0, 1, ..., B` (`B + 1` surface vertices). After sampling the BSDF at `bounce = B`, `bounce` increments to `B + 1 == max_bounce`, which sets `PATH_RAY_TERMINATE_AFTER_TRANSPARENT`: ray `B + 1` is traced **only** to accumulate emission/background MIS if it hits a light or escapes, and terminates immediately on any opaque surface without shading.
+ - In **67js** ([`packages/render-native/src/kernel.wgsl`](../packages/render-native/src/kernel.wgsl) lines `609-618`, `808-832`, `963-1048`), `tracePath` loops `for (var depth = 0; depth <= bounces; depth++)`, evaluating `addLights` (NEE) at `depth = 0, 1, ..., B` (`B + 1` surface vertices) and exiting after `depth = B` **without** tracing continuation ray `B + 1`.
+ - **Subtle sky-MIS consequence `[source]` + `[measured]`**: For analytical lights (`point`, `spot`, `area`, `sun`), 67js uses pure NEE (`directWeight = 1 / selectionProbability`), so `bounces = B` matches Cycles `max_bounces = B` vertex-for-vertex (`B + 1` NEE evaluations). For the environment map (`weightMode = 1`), 67js multiplies NEE at `depth = B` by the MIS weight `p_env^2 / (p_env^2 + p_bsdf^2)` (`kernel.wgsl:609-613`) expecting `depth = B + 1` to add the complementary BSDF escape weight `p_bsdf^2 / (p_env^2 + p_bsdf^2)` in `addEscape`, which never runs on the final bounce `depth == B`.
+- **Empirical white-furnace sphere check (`color = [0.8, 0.8, 0.8]`, `roughness = 1.0`, `specular = 0.0`, constant `1.0` sky, `128 × 128`, `256` spp) `[measured]`**:
+ - `B = 0`: Cycles center patch mean = **`0.79971`** (exact `0.8`, because ray `B + 1` completes background MIS) vs 67js = **`0.13334`** (`ratio = 0.16674 ≈ 1/6`, confirming analytically that $(1/4\pi)^2 / ((1/4\pi)^2 + (\cos\theta/\pi)^2)$ integrated over the cosine hemisphere equals `1/6`, so `0.8 / 6 = 0.13333` when ray `B + 1` is omitted).
+ - `B = 1` and `B = 8`: Cycles = **`0.79971`** vs 67js = **`0.79923`** (**`ratio = 0.9994`**, within `0.06%`), because every ray from the convex sphere escapes at `depth = 1` and completes vertex `0`'s MIS pair.
+- **Empirical `B = 0` check on `lit-interior` `[measured]`**: Because `lit-interior` is an enclosed room lit by point lights, `B = 0` (`64` spp) matches between Cycles (`max_bounces = 0`) and 67js (`bounces = 0`) to **`relMSE = 0.000106`**, `channelMeanRatio = [1.0082, 1.0079, 1.0064]`, and `64 / 64` tiles within `±5%` (`medianRatio = 0.9965`).
+
+---
+
+## 1. Cycles 4096-Sample Reference & Seed Noise Floor
+
+Rendered at `4096` samples in Cycles 5.3 OptiX with `seed = 1` (Seed A) and `seed = 2` (Seed B), using error metric:
+
+$$\text{relMSE}(x, r) = \text{mean}\!\left(\frac{(x - r)^2}{r^2 + 10^{-2}}\right)$$
+
+| Metric (`Cycles 4096 Seed 1` vs `Seed 2`) | Value `[measured]` |
+| --- | --- |
+| Differing pixels | **`518,400 / 518,400` (`100.0%`)** |
+| Noise floor `relMSE` | **`0.00028509`** (`2.851 × 10⁻⁴`) |
+| `relMSE` clipped at `1000` / `99.99%` trimmed | `0.00028509` / `0.00028431` |
+| Mean / max absolute channel difference | `0.002363` / `0.039031` |
+| Channel means (`Seed 1` vs `Seed 2`) | `[0.251260, 0.178773, 0.126399]` vs `[0.251265, 0.178782, 0.126405]` |
+| Per-channel mean ratio (`Seed 2 / Seed 1`) | **`[1.0000, 1.0000, 1.0000]`** (scalar `1.0000`) |
+| `8 × 8` tile ratios (`mean > 0.01`, `64 / 64` eligible) | `min = 0.9993`, `median = 1.0001`, `max = 1.0011` (`64 / 64` within `±5%`) |
+| Seed 1 timing & memory | `1.659 s` setup (`1.392 s` build + `0.266 s` OptiX sync), `261.269 s` sampling, `604.83 MiB` RSS, `351.0 MiB` Cycles `Mem:` |
+
+---
+
+## 2. Sample Ladder (`16` to `1024` spp, Extended to `4096` spp for 67js)
+
+Every row below reports the **median** and `[min, max]` spread across **3 interleaved back-to-back runs** (`seed = 1`), evaluated against the `Cycles 4096 Seed 1` reference `[measured]`.
+
+### Cycles 5.3 OptiX Sample Ladder
+
+| Samples | `relMSE` vs Ref | Setup `T_sync` (s) | Sampling (s) | Total Trace (s) | Process Wall (s) | Peak RAM (MiB) | Cycles `Mem:` (MiB) | Card VRAM Δ (MiB, shared) |
+| --- | --- | --- | --- | --- | --- | --- | --- | --- |
+| `16` | `0.069997` | `2.089` `[1.501, 3.731]` | `0.488` `[0.475, 0.748]` | `43.233` `[2.860, 53.581]`¹ | `50.495` `[5.497, 95.955]`¹ | `601.55` `[591.6, 615.8]` | `351.0` | `725.0` `[725, 979]` |
+| `32` | `0.031804` | `3.404` `[1.769, 3.856]` | `0.938` `[0.932, 0.946]` | `4.580` `[2.842, 4.871]` | `8.580` `[6.774, 8.882]` | `589.51` `[588.7, 592.9]` | `351.0` | `943.0` `[109, 943]` |
+| `64` | `0.014797` | `1.617` `[1.596, 2.280]` | `3.261` `[1.823, 3.358]` | `5.081` `[3.479, 5.809]` | `6.878` `[5.878, 7.504]` | `590.89` `[589.9, 591.2]` | `351.0` | `1667.0` `[0, 2096]` |
+| `128` | `0.006862` | `1.885` `[1.800, 2.711]` | `5.889` `[5.877, 6.812]` | `9.108` `[7.821, 9.176]` | `10.721` `[9.463, 10.968]` | `590.95` `[589.4, 595.2]` | `351.0` | `2096.0` `[2096, 2138]` |
+| **`256`** | **`0.003121`** | **`2.012`** `[1.728, 2.012]` | **`11.371`** `[10.277, 11.885]` | **`13.456`** `[12.406, 14.371]` | **`15.113`** `[14.269, 15.988]` | **`590.20`** `[590.0, 599.1]` | **`351.0`** | `1804.0` `[1667, 2279]` |
+| `512` | `0.001519` | `2.082` `[1.771, 2.168]` | `20.489` `[18.871, 20.797]` | `22.621` `[21.154, 22.690]` | `24.644` `[23.166, 24.828]` | `592.22` `[591.7, 593.1]` | `351.0` | `1667.0` `[834, 1668]` |
+| `1024` | `0.000770` | `6.173` `[3.616, 9.780]` | `83.307` `[54.446, 141.786]` | `93.176` `[58.331, 148.029]` | `100.003` `[60.800, 172.032]` | `584.98` `[579.6, 590.1]` | `351.0` | `1723.0` `[841, 8403]` |
+
+¹ *On `s16-r2` and `s16-r3`, Blender's post-render EXR ZIP write (`Saving: 00:48.97`) stalled on concurrent disk I/O while `render_stats` cleanly isolated actual OptiX path-tracing `samplingSeconds` (`0.488 s` median).*
+
+### 67js `packages/render-native` (Legacy Kernel) Sample Ladder
+
+| Samples | `relMSE` vs Ref | Mean Ratio `(R, G, B)` | Setup `T_sync` (s) | Sampling (s) | Total Trace (s) | Process Wall (s) | Peak RAM (MiB) | Card VRAM Δ (MiB) | Peak Card VRAM (MiB) |
+| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
+| `16` | `0.307783` | `[1.0103, 1.0094, 1.0072]` | `0.234` `[0.209, 0.311]` | `0.104` `[0.090, 0.406]` | `0.370` `[0.366, 0.763]` | `1.389` `[1.116, 2.054]` | `274.32` `[269.0, 290.5]` | `943.0` `[237, 1070]` | `7755.0` (shared) |
+| `32` | `0.155303` | `[1.0102, 1.0090, 1.0069]` | `0.253` `[0.230, 0.258]` | `0.173` `[0.164, 0.448]` | `0.466` `[0.434, 0.761]` | `0.972` `[0.678, 7.718]` | `288.32` `[269.2, 311.0]` | `236.0` `[0, 237]` | `7410.0` (shared) |
+| `64` | `0.077857` | `[1.0099, 1.0087, 1.0065]` | `0.213` `[0.204, 0.218]` | `0.516` `[0.297, 1.124]` | `0.773` `[0.566, 1.360]` | `0.999` `[0.837, 1.884]` | `271.43` `[269.4, 273.2]` | `1070.0` `[666, 1179]` | `7882.0` (shared) |
+| `128` | `0.039273` | `[1.0103, 1.0090, 1.0067]` | `0.189` `[0.188, 0.219]` | `0.565` `[0.564, 0.572]` | `0.784` `[0.783, 0.820]` | `1.208` `[1.040, 1.301]` | `269.40` `[268.9, 302.9]` | `575.0` `[237, 666]` | `7049.0` (shared) |
+| **`256`** | **`0.019762`** | **`[1.0104, 1.0091, 1.0069]`** | **`0.244`** `[0.206, 0.270]` | **`2.101`** `[1.160, 2.313]` | **`2.381`** `[1.465, 2.568]` | **`2.913`** `[2.120, 3.443]` | **`286.96`** `[268.4, 311.7]` | `1608.0` `[1541, 1650]` | `7992.0` (shared) |
+| `512` | `0.010005` | `[1.0106, 1.0092, 1.0069]` | `0.306` `[0.232, 0.400]` | `3.428` `[2.895, 3.648]` | `4.209` `[3.275, 4.317]` | `4.637` `[3.555, 9.658]` | `371.43` `[302.5, 372.0]` | `346.0` `[261, 1179]` | `7995.0` (shared) |
+| `1024` | `0.005135` | `[1.0105, 1.0091, 1.0068]` | `0.810` `[0.541, 1.016]` | `12.330` `[8.675, 12.739]` | `15.371` `[9.999, 16.628]` | `17.084` `[12.550, 19.309]` | `298.25` `[294.1, 329.8]` | **`352.0`** `[346, 377]` | **`909.0`** (uncontended r2–r3) |
+| `2048` | `0.002679` | `[1.0105, 1.0091, 1.0068]` | `1.044` `[0.318, 1.051]` | `9.786` `[8.642, 16.037]` | `12.208` `[9.966, 17.575]` | `13.591` `[10.256, 20.280]` | `389.77` `[270.1, 425.7]` | **`432.0`** `[211, 5808]` | **`997.0`** (`769.0` on r1) |
+| `4096` | `0.001453` | `[1.0104, 1.0090, 1.0068]` | `0.377` `[0.349, 0.415]` | `19.035` `[18.284, 24.398]` | `19.608` `[18.700, 24.878]` | `19.962` `[19.006, 25.724]` | `394.41` `[281.9, 409.8]` | **`433.0`** `[366, 7765]` | **`998.0`** (uncontended r1–r2) |
+
+### Setup (`T_sync`) Sub-Phase Breakdown (`256` spp Representative Run `r1`)
+
+- **67js `render-native` (`0.2056 s` total warm setup `[measured]`)**:
+ - JS scene flatten & pack (`buildTraceScene` + `buildNativeInput`): `0.0261 s`
+ - `wgpu` Vulkan instance/adapter/device init (`deviceSetupSeconds`): `0.1637 s` (`79.6%` of warm setup; a cold driver-cache init on first boot measured `7.83 s`)
+ - WGSL `kernel.wgsl` compile & pipeline creation (`compileSeconds`): `0.0048 s`
+ - Storage buffer upload (`uploadSeconds`): `0.0087 s`
+ - Vulkan BLAS + TLAS build (`accelerationBuildSeconds`, `3,072` triangles): `0.0023 s`
+- **Cycles 5.3 OptiX (`2.0116 s` total setup `[measured]`)**:
+ - Headless Blender factory reset + Python mesh/material/light creation (`sceneBuildSeconds`): `1.7977 s`
+ - Cycles scene sync + OptiX BVH build before sample 1 (`cyclesSyncSeconds`): `0.2139 s`
+
+---
+
+## 3. Radiometric Bias, `8 × 8` Tile Grid, and Visible Differences
+
+Evaluated between **`67js 4096 spp` (`lit-interior-native-s4096-r1`)** and **`Cycles 4096 spp Seed 1`** (`relMSE = 0.001453`, `relMSETrimmed = 0.001441`, `meanAbsDiff = 0.006631`, `maxAbsDiff = 0.728733`) `[measured]`:
+
+- **Per-channel mean radiance**:
+ - Cycles `4096` spp: `R = 0.251260, G = 0.178773, B = 0.126399`
+ - 67js `4096` spp: `R = 0.253883, G = 0.180387, B = 0.127258`
+ - **Per-channel mean ratio (`67js / Cycles`)**: **`R = 1.0104 (+1.04%), G = 1.0090 (+0.90%), B = 1.0068 (+0.68%)`**, scalar ratio **`1.0092`** (already passes M1's `1 ± 0.02` global channel gate on this scene).
+- **`8 × 8` tile mean ratio summary (`120 × 67.5 px` tiles, threshold `mean > 0.01`)**:
+ - Eligible tiles: **`64 / 64`**
+ - Tiles within `1 ± 0.05`: **`64 / 64` (`0` tiles outside `±5%`)**
+ - Distribution: **`min = 0.9849`** (tile `(7, 4)`, foreground floor/table shadow), **`median = 1.0034`**, **`max = 1.0280`** (tile `(0, 4)`, ceiling directly above the overhead key light)
+
+```text
+Row 0 (ceiling): [1.0165, 1.0214, 1.0184, 1.0276, 1.0280, 1.0192, 1.0200, 1.0145]
+Row 1 (upper): [1.0047, 1.0088, 1.0084, 1.0072, 1.0071, 1.0071, 1.0071, 1.0029]
+Row 2: [1.0062, 1.0054, 1.0037, 1.0025, 1.0034, 1.0021, 1.0039, 1.0033]
+Row 3: [1.0051, 1.0054, 1.0036, 1.0041, 1.0084, 1.0035, 1.0028, 1.0040]
+Row 4 (mid): [1.0052, 1.0077, 1.0030, 0.9961, 0.9985, 1.0004, 1.0047, 1.0039]
+Row 5 (table): [1.0018, 0.9978, 0.9940, 0.9878, 0.9863, 0.9917, 0.9980, 0.9988]
+Row 6: [0.9968, 1.0004, 1.0015, 0.9986, 0.9999, 1.0000, 0.9994, 0.9960]
+Row 7 (floor): [1.0033, 1.0033, 0.9975, 0.9856, 0.9849, 0.9965, 1.0034, 1.0031]
+```
+
+### Per-Part Breakdown (`67js 4096 spp` vs `Cycles 4096 spp Seed 1`)
+
+| Part | Pixels | Material (`roughness`) | `relMSE` `[measured]` | Scalar Ratio | Channel Ratio `[R, G, B]` |
+| --- | --- | --- | --- | --- | --- |
+| `block` | `3,367` | Yellow dielectric (`0.5`) | `0.001745` | `1.0217` | `[1.0236, 1.0215, 1.0134]` |
+| `table` | `9,146` | Brown dielectric (`0.4`) | `0.001672` | **`0.9794`** | **`[0.9808, 0.9785, 0.9764]`** |
+| `room-back` | `115,710` | Plaster wall (`0.9`) | `0.001607` | `1.0031` | `[1.0049, 1.0026, 1.0005]` |
+| `vase` | `3,933` | Teal glossy sphere (`0.2`) | `0.001568` | `1.0074` | `[0.9998, 1.0104, 1.0091]` |
+| `room-floor` | `193,854` | Wood floor (`0.6`) | `0.001564` | `0.9972` | `[1.0011, 0.9959, 0.9890]` |
+| `room-ceiling` | `81,806` | Plaster ceiling (`0.9`) | `0.001352` | **`1.0253`** | **`[1.0262, 1.0253, 1.0236]`** |
+| `room-right` | `54,104` | Blue wall (`0.9`) | `0.001211` | `1.0035` | `[1.0000, 1.0043, 1.0051]` |
+| `room-left` | `54,104` | Red wall (`0.9`) | `0.001099` | `1.0058` | `[1.0093, 1.0011, 0.9978]` |
+| `table-leg` | `2,376` | Dark support (`0.5`) | `0.000432` | `1.0207` | `[1.0253, 1.0194, 1.0133]` |
+
+### Visible Differences and Causes from the Gap Table
+
+1. **Ceiling hotspot `+2.80%` (`room-ceiling` `1.0253`, tiles `(0, 3)..(0, 4)` at `1.0276–1.0280`) `[measured]` → Sphere point-light sampling mismatch `[source]`**:
+ - In [`packages/render-native/src/kernel.wgsl`](../packages/render-native/src/kernel.wgsl) (`randomOnSphere` + `pointLightFalloff`, lines `724-739`, `776-789`), 67js jitters a point uniformly over the entire `r = 0.05 m` sphere (including the back hemisphere) and evaluates `1 / max(d^2, r^2)` without solid-angle subtended-cone sampling. Cycles (`kernel/light/point.h`) samples the visible spherical cap uniformly in solid angle. At `0.40 m` vertical separation from the overhead key light (`y = 2.6` to `y = 3.0`), full-sphere jitter shifts the mean inverse-square kernel upward by `~2–3%`.
+2. **Darker glossy tabletop `-2.06%` (`table` `0.9794`, tiles `(5, 3)..(5, 4)` at `0.9863–0.9878`, and `maxAbsDiff = 0.729` on specular highlights) `[measured]` → Two Principled/light gaps `[source]`**:
+ - **Principled v2 multiscatter GGX & dielectric Fresnel albedo** (`kernel.wgsl:441-582` vs Cycles `bsdf_microfacet.h` / `svm/closure.h`): 67js `principled-lite` uses single-scatter GGX with a polynomial directional-albedo approximation to weight the diffuse lobe under specular, losing energy at medium roughness (`roughness = 0.4` on `table`, `0.6` on `room-floor`).
+ - **Light visibility & MIS on finite-radius lights** ([`docs/path-tracer.md`](path-tracer.md) line `37`): 67js point lights (`radius = 0.05 m`) are sampled by NEE only and cannot be intersected by camera or glossy BSDF rays (no MIS), whereas Cycles intersects and MIS-weights the `5 cm` sphere lights in glossy reflections on `table` (`roughness = 0.4`) and `vase` (`roughness = 0.2`).
+3. **`4.4×–6.3×` higher grain across walls and shadows at equal sample count `[measured]` → Missing native Light Tree + white-noise PCG sampler `[source]`**:
+ - On bounces `depth >= 1` (`kernel.wgsl:808-821`), 67js picks **one emitter uniformly at random** out of `emitterCount = 4` (`selectionProbability = 0.25`), spending `25%` of bounce shadow rays on the nearly black `0.02` constant world (which cannot even illuminate interior points!) and giving equal `25%` probability to the `intensity = 2` side lights and the `intensity = 8` overhead key light. Cycles (`use_light_tree = True`) weights emitters by energy and geometric bound.
+ - 67js draws independent stateless PCG white noise (`kernel.wgsl:54-75`), converging strictly as `1 / N`, whereas Cycles uses **Tabulated Sobol** with blue-noise scrambling (`sample/sobol_burley.h`), whose quasi-Monte Carlo stratification widens the `relMSE` gap from `4.40×` at `16` spp to `6.33×` at `256` spp and `6.67×` at `1024` spp.
+4. **Warm channel tilt (`+1.04% R` vs `+0.68% B`) `[measured]` → Multi-bounce albedo compounding `[inferred]`**:
+ - Because the `intensity = 8` key light (`[1.0, 0.9, 0.75]`), wood floor (`[0.45, 0.32, 0.22]`), and red wall (`[0.55, 0.25, 0.20]`) are red-dominant, the `+2.5%` ceiling excess re-radiates more strongly in `R` than `B` across `8` diffuse/glossy bounces.
+
+---
+
+## 4. Equal-Error Time `T_eq` and Convergence Decomposition
+
+### Equal-Sample (`256` spp) vs Equal-Error (`relMSE = 0.003121`) Comparison
+
+| Comparison Metric | Cycles 5.3 OptiX (`256` spp) | 67js `render-native` (`256` spp) | 67js Equal-Error (`~1,740.5` spp) | Ratio (`67js / Cycles`) |
+| --- | --- | --- | --- | --- |
+| Samples per pixel | `256` | `256` (`1.00×`) | **`1,740.51`** (bracket `[1024, 2048]`) | **`6.80×` samples** for equal `relMSE` |
+| `relMSE` vs Cycles `4096` Seed 1 | **`0.003121`** | `0.019762` (`6.33×` higher error) | **`0.003121`** (matched) | `6.33×` at `256` spp / `1.00×` at `T_eq` |
+| Warm setup `T_sync` (s) | `2.0116` | `0.2444` | `~0.9` (interpolated bracket) | **`0.122×`** at `256` spp (`8.2×` faster) |
+| Sampling time (s) | `11.3708` | `2.1010` (`0.185×` / `5.41×` faster) | **`10.3311`** (`T_eq` sampling) | **`0.909×`** (`1.10×` faster at `T_eq`) |
+| Total trace time (s) | `13.4559` | `2.3806` (`0.177×` / `5.65×` faster) | **`12.8859`** (`T_eq` total trace) | **`0.958×`** (`1.04×` faster at `T_eq`) |
+| Process wall time (s) | `15.1132` | `2.9132` (`0.193×` / `5.19×` faster) | **`14.3404`** (`T_eq` wall) | **`0.949×`** (`1.05×` faster at `T_eq`) |
+
+### Asymptotic Bias vs Variance Fit
+
+Least-squares fit of $\text{relMSE}(N) = B_{\text{bias}} + \frac{V}{N}$ across the measured ladders (`[measured]`):
+
+- **67js `render-native` (`16..4096` spp)**:
+ - $B_{\text{bias}} = \mathbf{0.000542}$ (`5.42 × 10⁻⁴`), $V_{\text{native}} = \mathbf{4.9246}$, $R^2 = \mathbf{0.999982}$ (residual RMSE `0.000406`).
+ - Subtracting the reference's own finite-sample noise floor (`0.000285` at `4096` spp) leaves a true expected-image bias of $\Delta B \approx 0.000542 - 0.000285 = \mathbf{0.000257}$ (`2.57 × 10⁻⁴`).
+ - Because $B_{\text{bias}} = 0.000542 < 0.003121$, 67js's bias floor does **not** prevent reaching Cycles' `256`-spp `relMSE` on `lit-interior` (`1,740.5` spp reaches `0.003121` cleanly). However, $B_{\text{bias}} = 0.000542$ **does** sit near Cycles' `1024`-spp `relMSE` (`0.000770`), proving quantitatively that past `~1,000` Cycles samples 67js hits an irreducible radiometric bias ceiling until M1 closes the sphere-light and Principled-BSDF gaps.
+- **Cycles 5.3 OptiX (`16..1024` spp)**:
+ - $V_{\text{cycles}} = \mathbf{1.1247}$ ($R^2 = 0.9977$, slight super-`1/N` curvature from Tabulated Sobol + blue noise causing a small negative linear intercept `-0.001518` when fit against `1/N`).
+
+---
+
+## Reproducible Commands
+
+Run from the repository root in PowerShell. Set `$env:BLENDER_BIN` if Blender 5.3 is installed outside `C:\Program Files\Blender Foundation\Blender 5.3\blender.exe`, and pass an untracked `<out-dir>` (such as `artifacts/cycles-parity`) so binary `.exr` and `.npy` files stay out of Git:
+
+```powershell
+# 1. Lower priority so child Node / Blender processes do not starve interactive work
+([System.Diagnostics.Process]::GetCurrentProcess()).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::BelowNormal
+if (-not $env:BLENDER_BIN) {
+ $env:BLENDER_BIN = "C:\Program Files\Blender Foundation\Blender 5.3\blender.exe"
+}
+$OutDir = "artifacts/cycles-parity"
+
+# 2. Build packages/render-native if build/render-native.node is not present yet
+node packages/render-native/build.mjs
+
+# 3. Export lit-interior scene JSON and verify byte-identical NativeTraceInput round-trip
+node bench/cycles-parity/export-scene.mjs $OutDir --scene lit-interior
+
+# 4. Run a single matched pair (Cycles 5.3 OptiX vs 67js render-native) through gpu-lock
+& "C:\Program Files\Git\bin\bash.exe" $env:GPU_LOCK_SCRIPT `
+ uv run --no-project --with psutil python bench/cycles-parity/measure-gpu-run.py "$OutDir/single/cycles-256.metrics.json" -- `
+ $env:BLENDER_BIN -b --factory-startup --python bench/cycles-parity/render-cycles.py -- `
+ "$OutDir/scenes/lit-interior.json" "$OutDir/single/cycles-256" --samples 256 --bounces 8 --seed 1
+
+& "C:\Program Files\Git\bin\bash.exe" $env:GPU_LOCK_SCRIPT `
+ uv run --no-project --with psutil python bench/cycles-parity/measure-gpu-run.py "$OutDir/single/native-256.metrics.json" -- `
+ node bench/cycles-parity/trace-native.mjs `
+ "$OutDir/scenes/lit-interior.json" "$OutDir/single/native-256" --samples 256 --bounces 8 --seed 1 --firefly-clamp 1000000000 --noise-threshold 0
+
+uv run --no-project --with numpy python bench/cycles-parity/compare.py pair "$OutDir/single/cycles-256.npy" "$OutDir/single/native-256.npy"
+
+# 5. Run or re-score the full M0 reference + 3x back-to-back ladder suite (writes <out-dir>/lit-interior-summary.json)
+# Set GIT_BASH_BIN="C:\Program Files\Git\bin\bash.exe" and GPU_LOCK_SCRIPT="<path-to-gpu-lock.sh>" to wrap every GPU step automatically.
+uv run --no-project --with numpy --with psutil python bench/cycles-parity/run-m0-suite.py $OutDir --scene lit-interior --repeats 3 --bounces 8 --mode all
+```