Skip to content

idol: BiRefNet background removal and preprocessing on Metal, so tf-idol-generate takes a raw photo (stacked on #1780) - #1787

Open
jayleaton wants to merge 15 commits into
ashhart:mainfrom
jayleaton:idol-birefnet
Open

jayleaton wants to merge 15 commits into
ashhart:mainfrom
jayleaton:idol-birefnet

Conversation

@jayleaton

@jayleaton jayleaton commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #1780 (and through it #1773, #1774, #1775, #1766). Its own change is the last two commits (ee8343a4a, b0642cb1d). Review after #1780.

What this changes

Idol's background removal (BiRefNet) and its image preprocessing natively on Metal, so tf-idol-generate takes a raw photo. For #1757: with this, the whole IdolPipeline runs natively on M5 Metal, from a photo to a 3DGS PLY. Details: the "Background removal and preprocessing" part of docs/recipes/idol.md.

  • BiRefNet (Swin-L backbone with window attention and relative position bias, ASPP with deformable convolution, the decoder) in zig/kernels/metal/idol_birefnet.metal and birefnet*.zig, with tf-idol-birefnet and an idol_birefnet_case.py case. These are Idol's own kernels; no shared kernel changes.

  • Preprocessing on the host (preprocess.zig, photo.zig), as idol/preprocess.py does it:

    • Pillow LANCZOS on the short side;
    • BiRefNet's alpha, unless the photo has real alpha;
    • MinFilter(3) erosion;
    • the square crop at the mode's margin, LANCZOS to 1,024, pasted on black.

    Pillow's fixed-point LANCZOS is matched byte for byte. Photos are decoded by core/picture. No EXIF orientation is applied, matching the SDK.

Weights and licence

birefnet.safetensors in the speridlabs/idol snapshot (Apache 2.0, ungated). It is ZhengPeng7/BiRefNet at e2bf8e4460fc8fa32bba5ea4d94b3233d367b0e4 (MIT, ungated) in fp16: all 742 of its tensors equal the upstream checkpoint's byte for byte, and it leaves out 12 side-output tensors (decoder.conv_ms_spvn_*) that only training uses.

CLI additions to tf-idol-generate (#1780)

Additive only: every existing argument, flag, default and output is unchanged, and a safetensors PICTURE gives the same JSON keys as before.

  • PICTURE may be a .png, .jpg, .jpeg or .webp photo (any case of extension), preprocessed natively; BiRefNet's weights come from SNAPSHOT_DIR/birefnet.safetensors, which the snapshot already holds.
  • --mode synthetic|real: the SDK's mode; default synthetic (crop margin 1.2), real is 1.7.
  • --crop-margin X overrides the mode's margin.
  • A photo also writes OUT_DIR/preprocessed.png, the 1,024 x 1,024 RGB the encoders saw.
  • A photo's tf-idol-generate.json adds preprocess_s and birefnet_s; for a photo, load_s includes BiRefNet's load. stderr gains a preprocess: line.

Precision

The SDK runs BiRefNet in fp16. This port computes in fp32 on the fp16 weights. br_conv adds its sums in blocks of 256 terms: one running sum over the squeeze's 51,840 terms put it at twice torch's distance. BiRefNet's input matches torch's CPU bilinear fma(t0, w0, t1 * w1) per axis, so it is byte-identical to the SDK's. Attention keeps fp32 scores and sums and rounds P itself before P V (#1772).

Kernel contract

zig/tests/contract/metal_idol_birefnet*.zig: 24 kernels, 21 controls.

SUMMARY 24 kernels: 24 pass gates 1-4, 0 fail, 0 known findings; 21 controls: 21 red as planted, 0 missed; 0 limit problems

All of Idol's together (--only "metal idol"):

SUMMARY 81 kernels: 81 pass gates 1-4, 0 fail, 0 known findings; 78 controls: 78 red as planted, 0 missed; 0 limit problems

Two limits:

  • br_window, br_gate and br_head take gate 4's stated-reason path. Simulated fp16 sums would miss by only 61x, 84x and 3x, so gate 4 does not itself prove that those three need fp32 sums.
  • The contract's harness checks that every output value is written, so it cannot cover strided outputs (br_conv's yoff/row0, br_norm's and br_resize's ldy/yoff). The end-to-end gates exercise them.

Receipt

  • Environment: Mac Studio M5 Ultra 256 GB, macOS 27; this branch on idol: tf-idol-generate, one picture to a 3DGS PLY end to end on Metal (stacked on #1773, #1774, #1775) #1780's 192c4e902; idol-sdk 4702a7f0 on torch 2.13.0 (MPS).

  • Photos: the avocado input, a WebP, and an opaque photo in synthetic and real mode (BiRefNet runs), plus an RGBA photo with real alpha (BiRefNet skipped).

  • Exactness:

    • Host steps: the resized photo, BiRefNet's input, and the alpha from the SDK's own logits are byte-identical to the SDK's on every photo. The picture built from the SDK's alpha is byte-identical too.
    • BiRefNet's logits against a float64 ruler, worst row ours / torch: avocado 3.84e-6 / 4.15e-6; WebP 8.15e-6 / 1.14e-5; opaque 1.90e-5 / 1.65e-5. 1 - cos is about 1e-12 for both. The gate is twice torch's distance, worst row and cosine.
    • Each of 24 stages on torch's own input passes, at 0.2 to 1.13 times torch's worst row.
    • The uint8 alpha against the ruler's: 13 / 5 / 6 pixels off for ours, against torch's 11 / 6 / 5, each by 1.
    • The preprocessed picture from our alpha against the SDK's: 0 to 3 pixels off, at most 2 levels. The gate allows twice torch's own maximum here, because one alpha level moves a resized pixel by up to 2, and the SDK's own opaque picture is 2 off the ruler's.
    • Repeats are byte-identical. Planted mismatches fail the unit tests.
  • End to end from the raw photo (seed 42, 50 steps, 262,144 Gaussians), against the SDK's IdolPipeline from the same photo:

    stage ours, opaque SDK, opaque ours, WebP SDK, WebP
    load 1.36 s 2.10 s 1.35 s 2.16 s
    preprocess, BiRefNet included 0.295 s 0.519 s 0.264 s 0.481 s
    DINOv3 0.155 s 0.276 s 0.156 s 0.271 s
    VAE 0.244 s 0.117 s 0.244 s 0.107 s
    denoise 27.49 s 93.94 s 27.51 s 93.92 s
    octree 0.139 s 0.750 s 0.142 s 0.600 s
    Gaussian decoder 0.222 s 0.491 s 0.223 s 0.492 s
    total 30.07 s 101.27 s 30.04 s 100.69 s
    peak footprint 2.77 GB 12.88 GB 2.76 GB 12.92 GB
  • Tests: zig build test test-golden -Dcpu=apple_m1: 585 of 585 steps, 8,968 of 9,021 tests pass, 53 skipped, 0 fail; goldens 55 of 55 and 322 of 335 equal, 0 unexpected differences. zig fmt --check build.zig zig: clean. lean_check.py: 424, the same as main.

  • Not run: CUDA (none in this PR); Metal M1 to M4. JPEG: see below.

JPEG

core/picture decodes JPEG only through libjpeg-turbo at exactly the pinned 3.1.4.1. To measure JPEG input I built that release from its official tarball (sha256 ecae8008…a022, equal to GitHub's digest for the release asset) into a private prefix, and pointed only TensorFold's runs at it with TENSORFOLD_LIBTURBOJPEG. The build reports libjpeg-turbo version 3.1.4.1, with the arm64 NEON SIMD path. The system's and Homebrew's libraries were not touched.

The test photo is the opaque avocado photo saved by Pillow as a quality-92 JPEG, 1,280 x 960. The SDK decodes it with Pillow 13.0.0, whose bundled libjpeg-turbo is 3.2.0.

  • tf-idol-birefnet: all gates pass.
    • The resized photo and BiRefNet's input are byte-identical to the SDK's (0 values differ), so our 3.1.4.1 decode equals Pillow's 3.2.0 decode on this photo.
    • Logits worst row 8.44e-6 (torch 1.20e-5), 1 - cos 9.0e-13 (torch 1.3e-12).
    • The alpha and the preprocessed picture are byte-identical to the SDK's. Against the ruler, 11 and 22 pixels are off, by at most 1 and 2, the same counts as torch's.
    • Three more forwards give identical bytes.
  • tf-idol-generate from the JPEG, against the SDK's IdolPipeline from the same file:
    • 29.90 s total against 100.62 s: preprocess 0.257 s (BiRefNet 0.213 s) against 0.477 s, denoise 27.48 s against 93.86 s;
    • peak footprint 2.76 GB against 12.93 GB;
    • preprocessed.png equal to the SDK's input picture, 0 pixels different;
    • with the SDK's VAE and starting noise injected: sampled NN 0.00935 (baseline 0.00911), full-cloud 0.00177, sample cosine 0.99868, camera yaw/pitch 1.6866/0.4974 against 1.6888/0.4930;
    • with native noise the PLYs differ, as idol: tf-idol-generate, one picture to a 3DGS PLY end to end on Metal (stacked on #1773, #1774, #1775) #1780 explains.
  • core/picture's own goldens test ("every picture 0.6.6 decoded ...") ran its JPEG pixel cases with the library and passed. Without the library it prints that they were skipped.
  • zig build test test-golden -Dcpu=apple_m1 with the variable set: 585 of 585 steps; goldens 55 of 55 and 322 of 335 equal, 0 unexpected differences.

A question for review, about the pin: the check refuses any libjpeg-turbo whose built-in version string is not exactly 3.1.4.1. Homebrew's current 3.2.1 is refused by name, so a stock Mac decodes no JPEG until someone builds 3.1.4.1 by hand. On this photo, 3.1.4.1 gave the same pixels as Pillow 13's bundled 3.2.0. Should the pin stay an exact match, or accept a set of releases whose decode is verified against the goldens (for example 3.1.4.1 and 3.2.x)? I have not changed the pin.

Checklist

  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off. (No token path.)
  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo. (n/a.)
  • No precision traded for speed. If the bits change, the description says which sums change and why.
  • A new or changed GPU kernel is registered with the kernel contract (docs/kernel-contract.md); each backend's SUMMARY line is in the receipt.
  • Prompt processing is no slower than the last release. (Not touched.)
  • The description says which platforms I ran, Metal M1 to M5 and CUDA, and which I could not.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency.
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths. No AI attribution lines.

@ashhart

ashhart commented Nov 4, 2026

Copy link
Copy Markdown
Owner

Thanks @jayleaton. The Pillow-exact LANCZOS and the byte-identical BiRefNet input are good to see. On the pin: let's keep the exact 3.1.4.1 match in this PR. Accepting a verified set of releases would be its own small PR, with the picture goldens run on each version it admits. This one waits on #1780; please rebase after it lands.

@AIFlowML

Copy link
Copy Markdown
Contributor

I found a compile blocker on exact head a03d468f (M5 Max, Zig 0.17.0). This reproduces without model weights:

zig build tf-idol-generate tf-idol-birefnet tf-kernel-contract -Dcpu=apple_m1 -j7 --summary all

The first failures are missing tf.idol.preprocess and tf.idol.birefnet_kernels. The files are present. Restoring the public imports for preprocess, photo, birefnet, birefnet_kernels, birefnet_reference, birefnet_decoder and birefnet_weights in zig/src/families/idol/idol.zig got all three targets building in scratch. That same build with test-picture-host and libjpeg-turbo 3.1.4.1 passed 31/31 tests. ./zig-out/bin/tf-kernel-contract --only 'idol birefnet' passed all 24 kernel gates, with 21/21 planted controls caught and zero limit problems.

I also ran tf-idol-generate with a 128×96 RGBA .PNG containing one opaque rectangle on a transparent background. The real-alpha shortcut wrote 1024×1024 RGB preprocessed.png before opening the deliberately absent encoder weights. The default and --mode real --crop-margin 1.2 produced byte-identical output. --mode real used 1.7 and visibly reduced the rectangle's size. This covers the alpha shortcut and crop options. The full checkpoint-to-PLY run is still open.

The trial merge into 328a566e hits the same nine files as parent #1780. The missing exports reproduce independently on this PR head.

Igor Lessio - AIFLOW LABS

jayleaton pushed a commit to jayleaton/TensorFold that referenced this pull request Nov 20, 2026
@jayleaton

Copy link
Copy Markdown
Contributor Author

Rebased onto #1780's new head at 19a94a015, as asked. It includes the picture-layout fix from @AIFlowML's report on #1780: a raw photo still goes through BiRefNet's preprocessing, and a safetensors picture now goes through picture.layouts.

Host checks (Linux): zig fmt, git diff --check, lean 0 new against main, pr_check 0 errors, and test-kernel-contract 247 of 247. The second pr_check warning, an IPv4-like string in idol-birefnet.md:61, was already in the recipe before the rebase. Not run here, for lack of a Mac: the Metal build and the BiRefNet and photo runs.

ashhart added a commit to jayleaton/TensorFold that referenced this pull request Nov 21, 2026
@AIFlowML

Copy link
Copy Markdown
Contributor

The updated ccfe66e3 head fixes the missing exports from the earlier build. On the published head, M5 Max and Zig 0.17.0 built all three targets in 71/71 steps. The focused BiRefNet Metal run passed 24 kernels, caught 21/21 planted controls, and reported zero limit problems.

zig build tf-idol-generate tf-idol-birefnet tf-kernel-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all
./zig-out/bin/tf-kernel-contract --only birefnet

Against main 25586070b, Git still reports six overlaps in the combined Idol documentation, exports, Metal build and contract wiring. The device result above is from this exact published head. The raw-photo-to-PLY run with model weights remains separate.

Igor Lessio - AIFLOW LABS

…oders, the denoiser and the decoders to a PLY

Each stage is timed and each model freed after it. The starting noise is torch's CPU-seeded randn, reimplemented;
the VAE's posterior noise and the starting noise can be given for parity with the SDK's MPS draws. The recipe's
End to end section has the stage timings, memory and PLY comparison against the SDK's own IdolPipeline run.
…as AIFlowML found

picture() checked only the element count, so `pixels` as float32
[1024, 1024, 3] (HWC) passed and was then read as CHW: a scrambled image
reached both encoders. families/idol/picture.zig now requires `pixels`
to be exactly float32 [3, 1024, 1024] and `image` exactly
[1024, 1024, 3], and its host test plants the HWC `pixels`, a flat
tensor, a bf16 one and a CHW `image`, each refused.
… idol.md under 600 lines; the picture's layouts
jayleaton pushed a commit to jayleaton/TensorFold that referenced this pull request Nov 22, 2026
@jayleaton

Copy link
Copy Markdown
Contributor Author

Thanks @AIFlowML for retesting Ash's ccfe66e on the M5 Max: 71/71 steps, and BiRefNet's 24 kernels with 21/21 controls and no limit problems.

Rebased onto the rebased #1780 (6e4d936, on main c35d9f7). The new head is 6527531, and Ash's four commits are kept on top of mine. Of the six overlaps, only docs/recipes/idol.md needed a hand-edit: main's encoder sentence now also names BiRefNet's preprocessing, linking to idol-birefnet.md after Ash's split. The exports (idol.zig), the Metal build, idol_records.zig (birefnet added beside the denoiser, decoder and VAE records) and the contract wiring merged cleanly. kernel-contract.md's Idol paragraph now ends with BiRefNet's 21 controls.

Host checks on 6527531:

  • fmt, git diff --check and lean (0 new) are clean. pr_check --pr 1787 gives 0 errors and two advisory warnings that were already there: no Unreleased bullet names this PR, and the libjpeg-turbo version "3.1.4.1" reads as an IPv4 address.
  • test-kernel-contract passes 273/273.
  • tf-idol-generate, tf-idol-birefnet and tf-kernel-contract compile for -Dtarget=aarch64-macos -Dcpu=apple_m1. The link needs the macOS SDK, so the device run remains yours. The raw-photo-to-PLY run with weights is still separate.

@AIFlowML

Copy link
Copy Markdown
Contributor

The rebase cleared the six overlaps I reported. 65275310bebc0a12de3d53085846787ae0c92fe7 contains the published #1780 head, merges cleanly into c35d9f73c, and passes git diff --cached --check.

On M5 Max with Zig 0.17.0:

zig build tf-idol-generate tf-idol-birefnet tf-kernel-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j2 --summary all
./zig-out/bin/tf-kernel-contract --only birefnet

The build passed 71/71 steps. Metal passed 24 BiRefNet kernels and caught all 21 planted controls, with zero limit problems. A synthetic RGBA PNG through tf-idol-generate took the real-alpha preprocessing path and reached weight loading. The model-backed background-removal and raw-photo-to-PLY runs remain separate.

Igor Lessio - AIFLOW LABS

@ashhart

ashhart commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Thanks @jayleaton. The raw-photo and generation paths are well structured and covered. One receipt/refusal fix is needed: a --noise file can supply latent and camera without a noise tensor. The encoder then generates native posterior noise, while the JSON reports vae_noise: "given". Please either require noise for --noise, or report the actual native/given choice so the run record matches the inputs that produced the PLY.

  • Synthena

jayleaton and others added 8 commits November 24, 2026 00:20
tf-idol-generate's torch CPU generator moves to idol/torch_rng.zig, so its
test runs without Metal. It checks the [8192, 16] then [5] draw for seed 42
against torch 2.5.1+cpu's values, produced with ATEN_CPU_CAPABILITY=default
(the scalar normal_fill_16 the Mac runs): the camera's 5 values bit for bit,
the latent's ends within 3 ulps and its sum, since torch's float logf, cosf
and sinf are the platform's libm.
BiRefNet (Swin-L, ASPP-deformable decoder) in fp32 on Metal from the Idol
snapshot's birefnet.safetensors, the SDK's preprocess on the host byte for
byte (Pillow LANCZOS, erosion, crop, paste; torch's CPU bilinear input), the
tf-idol-birefnet gate tool, its case tool tools/zig/idol_birefnet_case.py
and the kernel contract for every idol_birefnet.metal kernel.
PICTURE may be a .png, .jpg, .jpeg or .webp photo, preprocessed natively
with BiRefNet; --mode synthetic|real and --crop-margin X; a photo writes
OUT_DIR/preprocessed.png and adds preprocess_s and birefnet_s to the JSON.
Recipe section and CHANGELOG line.
Rebase adaptation: expose the supplied preprocessing, photo and BiRefNet modules through the public Idol namespace, and retain their import tests.
…s review asks

A --noise file with `latent` and `camera` but no `noise` tensor left the VAE
posterior's noise native while the run record said "given". The record now
takes the choice encode made (idol/run_noise.zig): native, given, or unused
when --features skips the encoders; a host test covers the noise-less file.
@jayleaton

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Pushed a556f29 (with a lease), rebased onto #1780's new head 8c28d5f. Ash's four commits are kept; the only conflict was the idol.zig exports, where I kept both sides.

I chose to report the posterior noise that actually ran, rather than require a noise tensor. The SDK draws the posterior's noise itself, so a file with only latent and camera remains a valid way to pin just the starting noise.

  • tf-idol-generate.json's vae_noise now comes from the choice encode made, through idol/run_noise.zig: native, given, or unused when --features skips the encoders. Before, it reported given whenever --noise was passed.
  • A host test covers the case from the review: a --noise file without noise now reports native.
  • The usage text and idol-generate.md now say that a file without noise leaves the noise native, and that vae_noise records which one ran.

Checks: fmt, git diff --check and lean (0 new) are clean. pr_check --pr 1787 gives 0 errors and the two existing advisory warnings. test-kernel-contract passes 273/273, and the torch_rng and run_noise host tests pass. tf-idol-generate, tf-idol-birefnet and tf-kernel-contract compile for aarch64-macos -Dcpu=apple_m1, but linking needs the macOS SDK.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @jayleaton for the quick fix.

What's confirmed:

  • The noise record. tf-idol-generate.json now reports the posterior noise that actually ran: native, given or unused. A --noise file without a noise tensor reports native, and the host test covers it.
  • The libjpeg-turbo pin. The exact 3.1.4.1 pin stands, as discussed.
  • The generator move. Moving the torch CPU generator into torch_rng.zig changes no arithmetic.
  • No change for existing inputs. A safetensors picture takes the same path as before, and the new options are additive.

One thing still needed: the LANCZOS resize in zig/src/families/idol/preprocess.zig.

  • Why it matters: its comments name Pillow's Resample.c and its internal functions, and it follows them step for step. Our rule is that a library's code doesn't land, even with a notice, and we don't read Pillow's source to compare.
  • There's already a shared resampler: main has a Pillow-exact Lanczos-3 resize in zig/src/core/picture/resample.zig.
  • The ask: could the photo preprocessing use that one, extending it to four channels if the RGBA photos need it? Then there's one Lanczos resampler. If you'd rather keep yours, please tell us how it was written, from Pillow's documented behaviour and outputs or from its source.

Ours, nothing needed from you: the conflicts with main are all mechanical. Main has since landed #1780's files, and we'll handle them.

  • Synthena

…as review asks

The photo's LANCZOS resizes go through resample.zig's Pillow-exact
Lanczos-3 instead of preprocess.zig's own resampler, which is removed.
The shared View gains a channel count (3 by default) so RGBA photos resize
there too, each channel alike; its other callers are unchanged.

Its bytes equal the old resampler's on every case tried and Pillow 13.0.0's
on the SDK's resizes (the first to a 1,024 short side, RGB and RGBA, and
the crop's to 1,024), so BiRefNet's input is unchanged. A host test pins an
RGBA shrink and enlarge to Pillow 13's bytes.
@jayleaton

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I pushed 7a2faf0 as a fast-forward on top of a556f29 and didn't rebase. The conflicts with main are yours, as agreed.

  • One resampler: preprocess.zig's own LANCZOS resampler is deleted, along with its comments naming library internals. preprocess.resample now calls core/picture/resample.zig's resizeWith(.pillow, .lanczos, …). I also reworded the premultiply and paste helpers and the recipe so they describe the arithmetic rather than naming library macros.
  • Four channels: resample.View gains channels, which defaults to 3, so every existing caller is unchanged. View.ofChannels adds 4-channel (RGBA) rows, with each channel resized the same way. intoWith and resizeWith read the channel count from the view, and bicubicPlanes asserts RGB.
  • Golden: the BiRefNet input is unchanged. In a scratch harness I compared the shared resampler, our deleted one and Pillow 13.0.0's Image.resize(LANCZOS).
    • The shared and deleted resamplers gave identical bytes on all 13 cases, RGB and RGBA.
    • Both matched Pillow byte for byte on the SDK's resizes. These were the first resize to a 1,024 short side (1280×960, 960×1280 RGBA, 4032×3024, 640×480 RGBA enlarging), the crop's resize to 1,024 (1365×1024 RGBA, 1000×1000), and small odd sizes.
    • The BiRefNet input is computed from the resized photo by our own bilinear step, which this change doesn't touch.
    • I couldn't rerun the Mac golden (tf-idol-birefnet against the SDK case) from Linux, so a rerun on the M5 would close it.
  • Pin: a new host test in preprocess.zig pins an RGBA shrink (9×7 to 5×4) and enlarge (to 12×9) to Pillow 13.0.0's bytes. Swapping the filter makes it fail.
  • One difference, not on Idol's path: when one axis shrinks while the other enlarges (733×1211 to 1024×1024), Pillow's bytes match resizing height first. Both our deleted resampler and the shared one resize width first, so they differ there. Each axis on its own matches. Idol's resizes scale both axes by one factor, so they never hit this, and I left the shared order alone because other families rely on it.

Checks: fmt, git diff --check and lean (0 new) are clean. pr_check --pr 1787 gives 0 errors and the two earlier advisory warnings. The resample, torch_rng, run_noise and preprocess host tests pass, and test-kernel-contract passes 242/242. tf-idol-generate, tf-idol-birefnet and tf-kernel-contract compile for aarch64-macos -Dcpu=apple_m1, but they need the macOS SDK to link. After that run, the only change was shortening one header comment to the 120-column rule.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @jayleaton. The shared Lanczos call and RGBA goldens close the duplicate-resampler request. The noise record and exact JPEG pin remain correct.

One crash needs fixing: --crop-margin 1e300 passes the positive-value check, then overflows the crop’s integer conversion. Please check finite values and derived crop/allocation bounds, returning an error, with a focused host regression.

Please also clarify the origin of br_erf, labeled as musl’s erff. If it came from library source, the same no-library-code rule applies. The integration conflicts remain on our side; the current Mac preprocessing golden is still outstanding.

  • Synthena

…ed, as review asks

--crop-margin 1e300 passed the positive check and then overflowed the
crop box's integer conversion. preprocess.checkMargin now refuses a margin
that is not finite and above 0, and finish refuses a crop whose side would
pass 16,384 (1 GiB of RGBA) before converting or allocating anything; a
case's own crop_margin goes through the same checks.

tf-idol-generate's other numeric flags parse through idol/run_flags.zig:
--steps 1 to 1,000 (steps + 1 overflowed at the largest usize), --cfg
finite, --gaussians in the decoders' range at parse time rather than after
the encoders and denoiser ran, --seed a u64. Host tests cover 1e300, inf,
nan, 0 and negative margins, a crop past the allocation bound, one past the
picture's edges, and each flag's refusals.
… review asks

br_erf was musl's erff. It is now our own: the Maclaurin series' terms to
n = 10 below 1 (coefficients 2 / sqrt(pi) (-1)^n / (n! (2n + 1)), with
x kept exact), and 1 - exp(-x^2) R(1 / x) from 1 to 4, R a degree-10
least-squares fit to erfc(x) exp(x^2) (relative error 2.3e-9 in float64);
1 past 4. idol/birefnet_erf.zig runs the same fp32 steps on the host: within
1.52 ulp of float64's erf over every positive fp32 to 6 (musl's was 0.76),
well inside the GELU contract's 8 ulps.
@jayleaton

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I pushed 4b0acd5 on top of 7a2faf0 as two commits and didn't rebase. The conflicts with main are yours, as agreed.

Crop crash (5f1d806)

  • preprocess.checkMargin refuses a margin unless it is finite and greater than 0.
  • finish refuses a crop whose side would exceed 16,384 (1 GiB of RGBA), and it does so before any integer conversion or allocation. Both cases return an error.
  • A case's own crop_margin goes through the same checks.
  • Host regression in preprocess.zig:
    • 1e300, inf, -inf, nan, 0 and -1 are refused.
    • Margin 6000 is refused because it would push the crop past the allocation bound.
    • Margin 6, whose crop extends past the picture, pads with black.
    • With the new bound removed, the 1e300 case reproduces the panic ("integer part of floating point value out of bounds").
  • The other numeric flags in tf-idol-generate now go through idol/run_flags.zig, each with host tests:
    • --steps must be 1 to 1,000. At the largest usize, steps + 1 overflowed.
    • --cfg must be finite.
    • --gaussians is checked against the decoders' range when the flag is parsed. Before, that check only ran after the encoders and the denoiser had finished.
    • --seed must be a u64.
    • tf-idol-birefnet takes no numeric flags. Its margin comes from the case JSON and goes through finish's checks.

br_erf (4b0acd5)

  • It was ported from musl's erff, so I replaced it with an erf I wrote from the math:
    • Below 1, it uses the Maclaurin series' terms up to n = 10, with coefficients 2/√π·(−1)ⁿ/(n!(2n+1)) and x kept exact.
    • From 1 to 4, it computes 1 − e^(−x²)·R(1/x), where R is my own degree-10 least-squares fit to erfc(x)·e^(x²). Its relative error is 2.3e-9 in float64.
    • Past 4, it returns ±1.
  • idol/birefnet_erf.zig runs the same fp32 steps on the host. Over every positive fp32 up to 6, it is within 1.52 ulp of float64's erf (musl's was 0.76). That is well inside the GELU contract's 8 ulps. The recipe no longer mentions musl.

Still outstanding: the Mac goldens. I couldn't run the BiRefNet goldens (tf-idol-birefnet against the SDK case, which includes the GELU change's logits within the existing tolerance) or the Mac preprocessing golden from Linux. Both need a rerun on an M5.

Checks

  • fmt, git diff --check and lean (0 new) are clean.
  • pr_check --pr 1787 reports 0 errors and the two earlier advisory warnings.
  • The preprocess, run_flags, resample, torch_rng, run_noise and birefnet_erf host tests pass, and test-kernel-contract passes 242/242.
  • The three tools compile for aarch64-macos -Dcpu=apple_m1, but they need the macOS SDK to link.
  • After that run, the only change was collapsing the erf's Metal comment to one line, as the lean rule requires.

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thanks @jayleaton. The crop bounds fix the crash, the numeric flag checks are present, and the library-derived erf has been replaced with the math-based implementation. The shared-resampler and noise-record fixes remain credited.

The changed GELU now needs its exact native serial comparison and the current Mac background-removal and preprocessing goldens. The host ULP bound and older Metal results do not qualify the new arithmetic; the existing tolerance cannot replace exact output checks.

The current-main composition remains ours.

  • Synthena

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants