code wiki / _hdl_build / nx_image_fidelity.nx

nx_image_fidelity.nx source

↩ module page · 54 lines · 2689 B

1// SUPERSEDED-FOR-GENERATION (Critic, Blau-Michaeli): this measures DISTORTION only (MSE/PSNR), 2// which is correct for lossless RECONSTRUCTION but MISLEADING for generative quality -- a blurry 3// posterior-mean scores high PSNR yet looks fake. For generation, pair this with the PERCEPTION 4// axis in nx_rd_perception (distribution divergence). Distortion and perception trade off; never 5// judge a generative output by PSNR alone. 6// 7// nx_image_fidelity.nx -- "rebuild it EXACTLY": the measurement gate for image reconstruction, 8// bits-up. You cannot claim a rebuild is exact without measuring exactness; the precision research 9// flagged measurement as the weak link. This is the sovereign metric layer the generation stack 10// (our nx_qmatvec/nx_qlayer kernels -> VAE -> DiT) is judged by: how close is the rebuilt image to 11// the reference? MSE (exact integer), max-abs-error (the worst pixel -- catches local failures an 12// average hides), and PSNR in dB (the rate-distortion quality measure). Verdict: LOSSLESS (bit- 13// exact) / NEAR-LOSSLESS / LOSSY. Pixels are 0..255 per channel, stored one per slot. 14// license_tier: ORIGINAL Refs: PSNR/MSE (rate-distortion fidelity); SSIM lineage. 15 16import "nx_syscalls.nx" 17const IMG_MAGIC_65025: i64 = 65025 18 19const IMG_LOSSLESS: i64 = 0 // bit-exact rebuild (max-err 0) 20const IMG_NEAR: i64 = 1 // PSNR >= 40 dB, imperceptible 21const IMG_LOSSY: i64 = 2 // below the near-lossless bar 22 23// floor(log2 v) 24func img_ilog2(v: i64) -> i64 { var x: i64 = v; var n: i64 = 0; while x > 1 { x = x >> 1; n = n + 1 } return n } 25 26// mean squared error over n pixels (exact integer mean). 27func img_mse(ref: *i64, got: *i64, n: i64) -> i64 { 28 if n <= 0 { return 0 } 29 var s: i64 = 0; var i: i64 = 0 30 while i < n { let d: i64 = ref[i] - got[i]; s = s + d * d; i = i + 1 } 31 return s / n 32} 33 34// worst single-pixel error -- an average MSE can look fine while one region is wrecked. 35func img_max_abs_err(ref: *i64, got: *i64, n: i64) -> i64 { 36 var mx: i64 = 0; var i: i64 = 0 37 while i < n { var d: i64 = ref[i] - got[i]; if d < 0 { d = 0 - d } if d > mx { mx = d } i = i + 1 } 38 return mx 39} 40 41// PSNR in dB (coarse integer): 10*log10(255^2/MSE) ~= 3 * log2(65025/MSE). MSE 0 -> capped 99 (exact). 42func img_psnr_db(mse: i64) -> i64 { 43 if mse <= 0 { return 99 } 44 let ratio: i64 = IMG_MAGIC_65025 / mse 45 if ratio <= 1 { return 0 } 46 return 3 * img_ilog2(ratio) 47} 48 49// the fidelity verdict for a rebuild. 50func img_verdict(ref: *i64, got: *i64, n: i64) -> i64 { 51 if img_max_abs_err(ref, got, n) == 0 { return IMG_LOSSLESS } 52 if img_psnr_db(img_mse(ref, got, n)) >= 40 { return IMG_NEAR } 53 return IMG_LOSSY 54}