Card: standardized form
Browse files5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971 unmodified line1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442455 unmodified lines# pathtracer-diffA differentiable Monte Carlo path tracer as one kernel, loadable through`kernels`. The forward pass is a megakernel unidirectional path tracer:Lambertian diffuse, GGX conductor (VNDF-sampled, height-correlated Smith),smooth dielectric, rough plastic, and rough dielectric materials; arealights with per-texel emission and an importance-sampled equirectangularenvironment map; an optional homogeneous participating medium; multipleimportance sampling (balance heuristic) by default; per-texel albedo withbilinear filtering; a binned-SAH BVH built in vectorized torch infractions of a second at a million triangles. The backward pass replaysthe identical paths with the identical counter-based random draws andemits analytic gradients to albedo texels, emission texels, environmenttexels, and medium coefficients; a companion pass differentiates thedirect-lighting image with respect to vertex positions, including shadowand camera silhouettes. Inverse rendering runs as a bare torch loop aroundthe kernel, with no rendering framework in the loop: render, compare,`backward()`, step.<video src="https://huggingface.co/kernels/phanerozoic/pathtracer-diff/resolve/main/media/inverse.mp4" autoplay loop muted playsinline controls width="100%"><img src="https://huggingface.co/kernels/phanerozoic/pathtracer-diff/resolve/main/media/inverse.gif" alt="THE DRAGON'S HALL: one continuous inverse-rendering shot; a dark marble hall with a gold-trimmed pedestal, glowing rune band, warm sconces, and a levitating crystal Stanford dragon that slides onto its pedestal while fog fills the room, converging to the fixed target inset"></video>*THE DRAGON'S HALL (`media/make_hero.py`): one continuous shot, everygradient, optimized live through the kernel against the fixed TARGETinset, 30 fps with a progress bar. From a flat gray start, Adam through`render()` recovers the 128x128 marble floor albedo (49,152 unknowns),the gold trim's conductor tint, the pedestal's plastic albedo, thebraziers' warm emission (max err 1.75 of 14), and a 16x64 per-texelemissive rune band (3,072 unknowns, mean err 0.15), around a smoothglass slab and the rough-dielectric crystal dragon. Mid-shot,`geometry_grad()` alone takes over the dragon's position: 5,205 verticesslide 4.60 scene units onto the pedestal by shadow and silhouette alone,final offset 0.004. In the last phase the participating medium rolls in:sigma_a and sigma_s recover from the hazy target to extinction error0.014. Image loss falls 8.5e-1 to 1.9e-1 at spp 8; the dim-hall floorand trim retain residual texel error where the scene barely observesthem, reported as measured. Stanford dragon courtesy of the StanfordComputer Graphics Laboratory.*## Usage4 unmodified linesptd = get_kernel("phanerozoic/pathtracer-diff", version=1, trust_remote_code=True)wall_tex = torch.full((256, 256, 3), 0.5, device="cuda", requires_grad=True)panel_emi = torch.full((16, 32, 3), 5.0, device="cuda", requires_grad=True)scene = ptd.Scene(vertices, faces, material_ids,albedo=[torch.tensor([0.73] * 3), # constants are 1x1 textureswall_tex, # [H, W, 3] per-texel albedotorch.tensor([0.9, 0.6, 0.3])],emission=[torch.zeros(3), torch.zeros(3), panel_emi],uvs=uvs,material_types=[ptd.DIFFUSE, ptd.DIFFUSE, ptd.PLASTIC],roughness=[0.3, 0.3, 0.2])cam = ptd.Camera(position=(2.78, 2.73, -8.0), look_at=(2.78, 2.73, 2.8),vfov_deg=39.0)img = ptd.render(scene, cam, 512, 512, spp=64, max_bounces=4) # [H, W, 3] linearloss = (img - target).square().mean()loss.backward() # gradients on wall_tex and panel_emigrad_verts = ptd.geometry_grad(scene, cam, dloss_dimage) # [V, 3] vertex grads````version` selects the release branch; `trust_remote_code` is required by`kernels` for publishers without the trusted-publisher mark.A fixed `seed` renders the same paths every call, so the Monte Carloobjective is a deterministic function of the parameters and gradientdescent sees a smooth landscape at any spp; that is the configuration aninverse-rendering loop wants. `estimator` selects `"mis"` (default),`"nee"`, or `"brdf"`.## API| Symbol | Purpose ||---|---|| `Scene(vertices, faces, material_ids, albedo, emission, uvs, material_types, roughness, ior, env, medium)` | triangle-mesh scene; BVH, light list, and the detached environment CDF / medium rate are built at construction; `albedo` and `emission` are `[M, 3]` constants or lists of `[Hm, Wm, 3]` textures; `env` is an optional `[Eh, Ew, 3]` equirect map; `medium=(sigma_a, sigma_s)` fills the scene with a homogeneous absorbing/scattering medium (mutually exclusive with `env`); texture/env shapes are fixed at construction || `Camera(position, look_at, up, vfov_deg)` | pinhole camera || `render(scene, camera, height, width, spp, max_bounces, estimator, seed)` | differentiable render to `[H, W, 3]` f32 linear radiance; autograd to albedo texels, emission texels, env texels, and medium sigmas || `geometry_grad(scene, camera, grad_image, spp, edge_samples, seed)` | d(loss)/d(vertex positions) `[V, 3]` for the direct-lighting transport term: dual-number interior derivative + edge-sampled shadow-silhouette and camera-silhouette boundary terms || `DIFFUSE`, `CONDUCTOR`, `DIELECTRIC`, `PLASTIC`, `ROUGH_DIELECTRIC` | material type constants || `ops.pt_forward` / `ops.pt_backward` / `ops.pt_geometry_grad` | raw kernel launches |## How it worksOne thread owns one pixel and accumulates its spp samples serially, so theimage is bitwise deterministic with no atomics in the forward pass.Diffuse vertices sample the cosine hemisphere (the throughput multiplieris then exactly the albedo); conductors sample the GGX visible-normaldistribution (Heitz 2018) with the height-correlated Smith term, so thecontinuation weight is `F * G2/G1`; smooth dielectrics branch on theFresnel term; rough plastic mixes a diffuse base with a GGX coat(F0 = 0.04) under a 50/50 lobe-mixture pdf; rough dielectrics sample GGXtransmission. With a medium, propagation distances are drawn from adetached exponential rate frozen at Scene construction, and each segmentcarries the transmittance ratio `exp(-sigma_t d) / exp(-sbar d)`. Directlight is estimated at every NEE-capable vertex (and at medium scatteringvertices) by area sampling over the emissive faces and, when anenvironment map is present, by sampling a detached mixture of itsluminance CDF and the uniform sphere; BSDF-sampled hits on emitters andenvironment misses are combined with the balance heuristic, so all threeestimators agree in expectation at any bounce budget.The backward pass is exact path replay. Sampling distributions depend onlyon geometry, frozen material parameters (roughness, ior), theconstruction-time environment CDF and medium rate, and the counter-basedPhilox stream keyed by `(seed, pixel, sample)`, never on thedifferentiable parameters, so the backward kernel re-traces identicalpaths with identical draws and no stored path state. Every radiance termis a product of per-bounce factors, each affine in its vertex's albedotexels (Schlick Fresnel is affine in F0; dielectric factors are constant),times a linear emission or environment texel; the replay differentiatesthe product in closed form with prefix/suffix exclusion products (nodivision, so zero albedos are safe) and scatters each factor's gradientinto the four texels of its bilinear footprint with the sampling weights,the exact adjoint of the fetch. Medium sigma-gradients are the closed-formlog-derivatives `-(D_total + d_term)` for `sigma_a`, plus`N_scatter/sigma_s` for `sigma_s`. Albedo gradients up to 2048 texels andemission gradients up to 512 texels accumulate in per-block shared memoryand flush once; larger textures and environment gradients use directglobal atomics.Geometry gradients are a separate pass over the direct-lighting transportterm. The interior (smooth) part re-traces camera rays and light samplesunder detached sampling and pushes forward-mode dual numbers through thereceiver hit, the shading geometry, and the light-area measure, one passper perturbed vertex coordinate. The boundary (visibility) part isredner-style edge sampling: shadow silhouettes are sampled as (edge point,light point) pairs, projected to the receiver, tested for a cleanlit/blocked crossing, and accumulated with the exact projective sweepvelocity, the edge-to-curve arc stretch, and the receiver-area-to-pixelmeasure; camera silhouettes are sampled on the image plane, where theprojected edge sweeps front-minus-background direct radiance acrosspixels.## CorrectnessMeasured on RTX 6000 Ada (sm89) from a source build; the published `v1`variants additionally pass the full 22-test suite through `get_kernel` ona GeForce RTX 3070 Ti (Ampere sm86, Linux):- **Analytic furnace, zero variance.** Closed uniform diffuse box underBRDF sampling: every path returns exactly `E * sum a^k`; the analyticvalue 0.498046875 is met with worst pixel deviation 3.4e-3. A diffuseplane under a constant environment reproduces `albedo * c` the same way.- **Fresnel slabs.** A smooth glass slab (ior 1.5) at normal incidencetransmits the internal-bounce series `(1-R)/(1+R)`: measured 0.923141against 0.923077 analytic (0.007%). A rough-dielectric slab atalpha = 0.02 transmits the same series within 0.05%.- **Beer-Lambert.** A purely absorbing medium attenuates a uniform emitterto `E * exp(-sigma_a d)` within 0.035%; with scattering on, MIS andBRDF-only means agree on a foggy Cornell box.- **Estimator agreement.** MIS, NEE-only, and BRDF-only means agree withinMonte Carlo tolerance on a Cornell box; MIS vs BRDF-only agree for a GGXconductor under an environment map and for rough plastic, which jointlyexercises the VNDF weight, the GGX pdf, the mixed-lobe pdf, and theenvironment pdf.- **Gradients match finite differences along the same paths.** Constants2.2e-4 max relative error over nine entries; wall-texture texels 2.6e-3;conductor F0 through GGX sampling and MIS 9.9e-4; plastic albedo throughboth lobes 2.8e-4; environment texels 2.1e-4 (detached CDF); emissiontexels linear-exact; medium sigmas 2e-2 gates. Texels no path can seeget exactly zero from both the replay and the differences.- **Geometry gradients match seed-averaged finite differences.** Interior:translating an area light matches central differences of the directimage within 15%. Boundary: each occluder vertex's gradient (shadowsweep + its own image silhouette) matches an 8-seed-averaged FD within0.23 worst-case (6-8% on three of four vertices; a single-seed FD of avisibility discontinuity is flip noise at these scales).- **Constants are 1x1 textures.** Both albedo forms render equal images tofloat rounding and receive matching gradients.- **Inverse rendering.** A wall color (3 unknowns) recovers to max error0.004 in 80 Adam steps; an 8x8 wall texture (192 unknowns) drives theimage loss from 1.8e-4 to 7.2e-14; a 4x8 emissive panel texture recoversfrom the room it lights; all through the kernel alone.- **Deterministic.** Repeated forward renders are bitwise identical;gradient buffers accumulate through float atomics and are deterministicin expectation but not bitwise.## MeasuredRTX 6000 Ada, 512x512, MIS, 4 bounces. The terrain scenes are displacedgrids with a 256x256 checker albedo texture, a GGX conductor block, and aconstant environment map; the SAH build is the vectorized torch builder.| scene | build | forward | backward (replay) ||---|---|---|---|1 unmodified line| terrain, 522,254 tris, 16 spp | 0.2 s | 18.3 ms (229 Mpaths/s) | 39.0 ms (2.1x) || terrain, 1,045,470 tris, 16 spp | 0.3 s | 20.3 ms (207 Mpaths/s) | 40.8 ms (2.0x) |## Requirements and limits- NVIDIA GPU with compute capability 8.0+; float32 throughout.- Materials: Lambertian diffuse, GGX conductor, smooth dielectric, roughplastic (F0 = 0.04 coat), rough dielectric (BSDF-sampled only; GGXroughness clamped to >= 0.01); per-texel emission; pinhole camera; atmost 64 materials and 16 bounces; two-sided surfaces; no Russianroulette (fixed bounce budget keeps the replay exact).- `render()` differentiates albedo texels/constants (all material types;conductor F0 tint), emission texels, environment texels, and mediumsigmas. Camera, UVs, roughness, and ior are frozen.- `geometry_grad()` differentiates vertex positions for thedirect-lighting term only: diffuse receivers and emitters carry theradiance jumps, indirect bounces are not differentiated, and uv motionacross textures is not differentiated. Boundary terms cover shadowsilhouettes and camera silhouettes.- The medium is homogeneous (isotropic phase), fills the scene, and ismutually exclusive with an environment map; its sampling rate isdetached at Scene construction (`scene.med_sbar`).- The environment sampling CDF is detached at Scene construction (a 0.5uniform-sphere mixture keeps every direction reachable, so optimizing anenv map from an arbitrary initialization stays unbiased); rebuild theScene to re-importance-sample a changed map.- Texture and env shapes are fixed at Scene construction; UVs wrap.- Published variants are Linux x86_64; on Windows `load_local.py`JIT-builds the same source and exposes the identical API.## ReferencesKajiya, "The Rendering Equation" (SIGGRAPH 1986); Vicini, Speierer, Jakob,"Path Replay Backpropagation" (SIGGRAPH 2021); Nimier-David, Speierer,Ruiz, Jakob, "Radiative Backpropagation" (SIGGRAPH 2020); Li, Aittala,Durand, Lehtinen, "Differentiable Monte Carlo Ray Tracing through EdgeSampling" (SIGGRAPH Asia 2018); Heitz, "Sampling the GGX Distribution ofVisible Normals" (JCGT 2018); Heitz, "Understanding the Masking-ShadowingFunction" (JCGT 2014); Walter et al., "Microfacet Models for Refractionthrough Rough Surfaces" (EGSR 2007); Veach and Guibas, "OptimallyCombining Sampling Techniques" (SIGGRAPH 1995); Möller and Trumbore,"Fast, Minimum Storage Ray-Triangle Intersection" (1997); Duff et al.,"Building an Orthonormal Basis, Revisited" (JCGT 2017); Wald, "On fastConstruction of SAH-based Bounding Volume Hierarchies" (2007).## License5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434 unmodified lines484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151 unmodified line1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701715 unmodified lines# pathtracer-diffA differentiable Monte Carlo path tracer as one kernel, loadable through`kernels`. The forward pass is a megakernel unidirectional path tracer withfive materials, area lights, an importance-sampled environment map, anoptional homogeneous medium, and multiple importance sampling; the backwardpass replays the identical paths with identical counter-based draws andemits analytic gradients. The reference standards are analytic transportresults and finite differences along the same paths.Rendering is a simulation of light, and making it differentiable turns itinto an instrument: give it a photograph and unknown scene parameters, andgradient descent recovers the materials, the lights, the fog, and thegeometry that produced the image. That normally requires a researchframework; here it is one loadable kernel, and inverse rendering is a baretorch loop: render, compare, `backward()`, step.<video src="https://huggingface.co/kernels/phanerozoic/pathtracer-diff/resolve/main/media/inverse.mp4" autoplay loop muted playsinline controls width="100%"><img src="https://huggingface.co/kernels/phanerozoic/pathtracer-diff/resolve/main/media/inverse.gif" alt="THE DRAGON'S HALL: one continuous inverse-rendering shot; a dark marble hall with a gold-trimmed pedestal, glowing rune band, warm sconces, and a levitating crystal Stanford dragon that slides onto its pedestal while fog fills the room, converging to the fixed target inset"></video>*THE DRAGON'S HALL (`media/make_hero.py`): one continuous shot, everygradient, optimized live through the kernel against the fixed TARGET inset.From a flat gray start, Adam through `render()` recovers the 128x128 marblefloor albedo (49,152 unknowns), the gold trim's conductor tint, thepedestal's plastic albedo, the braziers' warm emission (max err 1.75 of 14),and a 16x64 per-texel emissive rune band (3,072 unknowns, mean err 0.15),around a smooth glass slab and the rough-dielectric crystal dragon.Mid-shot, `geometry_grad()` alone takes over the dragon's position: 5,205vertices slide 4.60 scene units onto the pedestal by shadow and silhouettealone, final offset 0.004. In the last phase the participating medium rollsin: sigma_a and sigma_s recover from the hazy target to extinction error0.014. Image loss falls 8.5e-1 to 1.9e-1 at spp 8; the dim-hall floor andtrim retain residual texel error where the scene barely observes them.Stanford dragon courtesy of the Stanford Computer Graphics Laboratory.*## Usage4 unmodified linesptd = get_kernel("phanerozoic/pathtracer-diff", version=1, trust_remote_code=True)wall_tex = torch.full((256, 256, 3), 0.5, device="cuda", requires_grad=True)scene = ptd.Scene(vertices, faces, material_ids,albedo=[torch.tensor([0.73] * 3), wall_tex],emission=[torch.zeros(3), torch.zeros(3)],uvs=uvs, material_types=[ptd.DIFFUSE, ptd.DIFFUSE],roughness=[0.3, 0.3])cam = ptd.Camera(position=(2.78, 2.73, -8.0), look_at=(2.78, 2.73, 2.8),vfov_deg=39.0)img = ptd.render(scene, cam, 512, 512, spp=64, max_bounces=4)loss = (img - target).square().mean()loss.backward() # gradients on wall_texgrad_verts = ptd.geometry_grad(scene, cam, dloss_dimage)````version` selects the release branch; `trust_remote_code` is required by`kernels` for publishers without the trusted-publisher mark. A fixed `seed`renders the same paths every call, so the Monte Carlo objective is adeterministic function of the parameters and gradient descent sees a smoothlandscape at any spp.## API| Symbol | Purpose ||---|---|| `Scene(vertices, faces, material_ids, albedo, emission, uvs, material_types, roughness, ior, env, medium)` | triangle-mesh scene; BVH, light list, and the detached environment CDF / medium rate built at construction || `Camera(position, look_at, up, vfov_deg)` | pinhole camera || `render(scene, camera, height, width, spp, max_bounces, estimator, seed)` | differentiable render to `[H, W, 3]` f32 linear; autograd to albedo, emission, environment texels, and medium sigmas || `geometry_grad(scene, camera, grad_image, spp, edge_samples, seed)` | d(loss)/d(vertex positions) for the direct-lighting term: dual-number interior + edge-sampled shadow and camera silhouettes || `DIFFUSE`, `CONDUCTOR`, `DIELECTRIC`, `PLASTIC`, `ROUGH_DIELECTRIC` | material type constants || `ops.pt_forward` / `ops.pt_backward` / `ops.pt_geometry_grad` | raw kernel launches |## MethodOne thread owns one pixel and accumulates its spp samples serially, so theimage is bitwise deterministic with no atomics in the forward pass. Diffusevertices sample the cosine hemisphere; conductors sample the GGXvisible-normal distribution with the height-correlated Smith term; smoothdielectrics branch on Fresnel; rough plastic mixes a diffuse base with a GGXcoat under a 50/50 lobe-mixture pdf; rough dielectrics sample GGXtransmission. Direct light is estimated at every NEE-capable vertex by areasampling over emissive faces and, with an environment map, by a detachedmixture of its luminance CDF and the uniform sphere; BSDF-sampled hitscombine by the balance heuristic.The backward pass is exact path replay: sampling distributions depend onlyon geometry, frozen parameters, and the counter-based Philox stream, neveron the differentiable parameters, so the backward kernel re-traces identicalpaths with no stored path state. Every radiance term is a product ofper-bounce factors, each affine in its vertex's albedo texels, times alinear emission or environment texel; the replay differentiates the productin closed form with prefix/suffix exclusion products and scatters eachfactor's gradient into the four texels of its bilinear footprint. Geometrygradients run a separate pass over the direct-lighting term: forward-modeduals for the smooth part, redner-style edge sampling for shadow and camerasilhouettes.## MeasuredRTX 6000 Ada, 512x512, MIS, 4 bounces; terrain scenes are displaced gridswith a 256x256 checker albedo, a GGX conductor block, and a constantenvironment, built by the vectorized torch SAH builder:| scene | build | forward | backward (replay) ||---|---|---|---|1 unmodified line| terrain, 522,254 tris, 16 spp | 0.2 s | 18.3 ms (229 Mpaths/s) | 39.0 ms (2.1x) || terrain, 1,045,470 tris, 16 spp | 0.3 s | 20.3 ms (207 Mpaths/s) | 40.8 ms (2.0x) |## CorrectnessMeasured on RTX 6000 Ada from source; the published `v1` variants pass thefull 22-test suite through `get_kernel` on a GeForce RTX 3070 Ti (sm86):- Analytic furnace, zero variance: a closed uniform diffuse box returnsexactly `E * sum a^k` per path; the analytic 0.498046875 is met with worstpixel deviation 3.4e-3.- Fresnel slabs: a smooth glass slab at normal incidence transmits theinternal-bounce series `(1-R)/(1+R)`, measured 0.923141 against 0.923077(0.007%); a rough-dielectric slab at alpha 0.02 within 0.05%.- Beer-Lambert: a purely absorbing medium attenuates a uniform emitter to`E * exp(-sigma_a d)` within 0.035%.- Estimator agreement: MIS, NEE-only, and BRDF-only means agree within MonteCarlo tolerance across Cornell, GGX-under-environment, and rough-plasticscenes.- Gradients match finite differences along the same paths: constants 2.2e-4max relative over nine entries; wall texels 2.6e-3; conductor F0 throughGGX and MIS 9.9e-4; environment texels 2.1e-4; emission linear-exact;medium sigmas within 2e-2 gates. Texels no path can see get exactly zerofrom both sides.- Geometry gradients match seed-averaged finite differences: lighttranslation within 15%; occluder vertices within 0.23 worst case.- Inverse rendering: a wall color recovers to max error 0.004 in 80 Adamsteps; an 8x8 texture drives the loss from 1.8e-4 to 7.2e-14.- Deterministic: repeated forward renders are bitwise identical; gradientbuffers accumulate through float atomics and are deterministic inexpectation but not bitwise.## Requirements and limits- NVIDIA GPU with compute capability 8.0+; float32 throughout.- At most 64 materials and 16 bounces; two-sided surfaces; no Russianroulette (the fixed bounce budget keeps the replay exact); pinhole camera.- `render()` differentiates albedo, emission, environment texels, and mediumsigmas; camera, UVs, roughness, and ior are frozen. `geometry_grad()`covers the direct-lighting term only.- The medium is homogeneous, fills the scene, and is mutually exclusive withan environment map; the environment CDF is detached at Scene construction.- Published variants are Linux x86_64; on Windows `load_local.py` JIT-buildsthe same source.## ReferencesKajiya (1986); Vicini et al., "Path Replay Backpropagation" (2021);Nimier-David et al., "Radiative Backpropagation" (2020); Li et al.,"Differentiable Monte Carlo Ray Tracing through Edge Sampling" (2018);Heitz (2014, 2018) on GGX and VNDF; Walter et al. (2007); Veach and Guibas(1995); Möller and Trumbore (1997); Wald (2007) on SAH construction.## License
5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971 unmodified line1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442455 unmodified lines# pathtracer-diffA differentiable Monte Carlo path tracer as one kernel, loadable through`kernels`. The forward pass is a megakernel unidirectional path tracer:Lambertian diffuse, GGX conductor (VNDF-sampled, height-correlated Smith),smooth dielectric, rough plastic, and rough dielectric materials; arealights with per-texel emission and an importance-sampled equirectangularenvironment map; an optional homogeneous participating medium; multipleimportance sampling (balance heuristic) by default; per-texel albedo withbilinear filtering; a binned-SAH BVH built in vectorized torch infractions of a second at a million triangles. The backward pass replaysthe identical paths with the identical counter-based random draws andemits analytic gradients to albedo texels, emission texels, environmenttexels, and medium coefficients; a companion pass differentiates thedirect-lighting image with respect to vertex positions, including shadowand camera silhouettes. Inverse rendering runs as a bare torch loop aroundthe kernel, with no rendering framework in the loop: render, compare,`backward()`, step.<video src="https://huggingface.co/kernels/phanerozoic/pathtracer-diff/resolve/main/media/inverse.mp4" autoplay loop muted playsinline controls width="100%"><img src="https://huggingface.co/kernels/phanerozoic/pathtracer-diff/resolve/main/media/inverse.gif" alt="THE DRAGON'S HALL: one continuous inverse-rendering shot; a dark marble hall with a gold-trimmed pedestal, glowing rune band, warm sconces, and a levitating crystal Stanford dragon that slides onto its pedestal while fog fills the room, converging to the fixed target inset"></video>*THE DRAGON'S HALL (`media/make_hero.py`): one continuous shot, everygradient, optimized live through the kernel against the fixed TARGETinset, 30 fps with a progress bar. From a flat gray start, Adam through`render()` recovers the 128x128 marble floor albedo (49,152 unknowns),the gold trim's conductor tint, the pedestal's plastic albedo, thebraziers' warm emission (max err 1.75 of 14), and a 16x64 per-texelemissive rune band (3,072 unknowns, mean err 0.15), around a smoothglass slab and the rough-dielectric crystal dragon. Mid-shot,`geometry_grad()` alone takes over the dragon's position: 5,205 verticesslide 4.60 scene units onto the pedestal by shadow and silhouette alone,final offset 0.004. In the last phase the participating medium rolls in:sigma_a and sigma_s recover from the hazy target to extinction error0.014. Image loss falls 8.5e-1 to 1.9e-1 at spp 8; the dim-hall floorand trim retain residual texel error where the scene barely observesthem, reported as measured. Stanford dragon courtesy of the StanfordComputer Graphics Laboratory.*## Usage4 unmodified linesptd = get_kernel("phanerozoic/pathtracer-diff", version=1, trust_remote_code=True)wall_tex = torch.full((256, 256, 3), 0.5, device="cuda", requires_grad=True)panel_emi = torch.full((16, 32, 3), 5.0, device="cuda", requires_grad=True)scene = ptd.Scene(vertices, faces, material_ids,albedo=[torch.tensor([0.73] * 3), # constants are 1x1 textureswall_tex, # [H, W, 3] per-texel albedotorch.tensor([0.9, 0.6, 0.3])],emission=[torch.zeros(3), torch.zeros(3), panel_emi],uvs=uvs,material_types=[ptd.DIFFUSE, ptd.DIFFUSE, ptd.PLASTIC],roughness=[0.3, 0.3, 0.2])cam = ptd.Camera(position=(2.78, 2.73, -8.0), look_at=(2.78, 2.73, 2.8),vfov_deg=39.0)img = ptd.render(scene, cam, 512, 512, spp=64, max_bounces=4) # [H, W, 3] linearloss = (img - target).square().mean()loss.backward() # gradients on wall_tex and panel_emigrad_verts = ptd.geometry_grad(scene, cam, dloss_dimage) # [V, 3] vertex grads````version` selects the release branch; `trust_remote_code` is required by`kernels` for publishers without the trusted-publisher mark.A fixed `seed` renders the same paths every call, so the Monte Carloobjective is a deterministic function of the parameters and gradientdescent sees a smooth landscape at any spp; that is the configuration aninverse-rendering loop wants. `estimator` selects `"mis"` (default),`"nee"`, or `"brdf"`.## API| Symbol | Purpose ||---|---|| `Scene(vertices, faces, material_ids, albedo, emission, uvs, material_types, roughness, ior, env, medium)` | triangle-mesh scene; BVH, light list, and the detached environment CDF / medium rate are built at construction; `albedo` and `emission` are `[M, 3]` constants or lists of `[Hm, Wm, 3]` textures; `env` is an optional `[Eh, Ew, 3]` equirect map; `medium=(sigma_a, sigma_s)` fills the scene with a homogeneous absorbing/scattering medium (mutually exclusive with `env`); texture/env shapes are fixed at construction || `Camera(position, look_at, up, vfov_deg)` | pinhole camera || `render(scene, camera, height, width, spp, max_bounces, estimator, seed)` | differentiable render to `[H, W, 3]` f32 linear radiance; autograd to albedo texels, emission texels, env texels, and medium sigmas || `geometry_grad(scene, camera, grad_image, spp, edge_samples, seed)` | d(loss)/d(vertex positions) `[V, 3]` for the direct-lighting transport term: dual-number interior derivative + edge-sampled shadow-silhouette and camera-silhouette boundary terms || `DIFFUSE`, `CONDUCTOR`, `DIELECTRIC`, `PLASTIC`, `ROUGH_DIELECTRIC` | material type constants || `ops.pt_forward` / `ops.pt_backward` / `ops.pt_geometry_grad` | raw kernel launches |## How it worksOne thread owns one pixel and accumulates its spp samples serially, so theimage is bitwise deterministic with no atomics in the forward pass.Diffuse vertices sample the cosine hemisphere (the throughput multiplieris then exactly the albedo); conductors sample the GGX visible-normaldistribution (Heitz 2018) with the height-correlated Smith term, so thecontinuation weight is `F * G2/G1`; smooth dielectrics branch on theFresnel term; rough plastic mixes a diffuse base with a GGX coat(F0 = 0.04) under a 50/50 lobe-mixture pdf; rough dielectrics sample GGXtransmission. With a medium, propagation distances are drawn from adetached exponential rate frozen at Scene construction, and each segmentcarries the transmittance ratio `exp(-sigma_t d) / exp(-sbar d)`. Directlight is estimated at every NEE-capable vertex (and at medium scatteringvertices) by area sampling over the emissive faces and, when anenvironment map is present, by sampling a detached mixture of itsluminance CDF and the uniform sphere; BSDF-sampled hits on emitters andenvironment misses are combined with the balance heuristic, so all threeestimators agree in expectation at any bounce budget.The backward pass is exact path replay. Sampling distributions depend onlyon geometry, frozen material parameters (roughness, ior), theconstruction-time environment CDF and medium rate, and the counter-basedPhilox stream keyed by `(seed, pixel, sample)`, never on thedifferentiable parameters, so the backward kernel re-traces identicalpaths with identical draws and no stored path state. Every radiance termis a product of per-bounce factors, each affine in its vertex's albedotexels (Schlick Fresnel is affine in F0; dielectric factors are constant),times a linear emission or environment texel; the replay differentiatesthe product in closed form with prefix/suffix exclusion products (nodivision, so zero albedos are safe) and scatters each factor's gradientinto the four texels of its bilinear footprint with the sampling weights,the exact adjoint of the fetch. Medium sigma-gradients are the closed-formlog-derivatives `-(D_total + d_term)` for `sigma_a`, plus`N_scatter/sigma_s` for `sigma_s`. Albedo gradients up to 2048 texels andemission gradients up to 512 texels accumulate in per-block shared memoryand flush once; larger textures and environment gradients use directglobal atomics.Geometry gradients are a separate pass over the direct-lighting transportterm. The interior (smooth) part re-traces camera rays and light samplesunder detached sampling and pushes forward-mode dual numbers through thereceiver hit, the shading geometry, and the light-area measure, one passper perturbed vertex coordinate. The boundary (visibility) part isredner-style edge sampling: shadow silhouettes are sampled as (edge point,light point) pairs, projected to the receiver, tested for a cleanlit/blocked crossing, and accumulated with the exact projective sweepvelocity, the edge-to-curve arc stretch, and the receiver-area-to-pixelmeasure; camera silhouettes are sampled on the image plane, where theprojected edge sweeps front-minus-background direct radiance acrosspixels.## CorrectnessMeasured on RTX 6000 Ada (sm89) from a source build; the published `v1`variants additionally pass the full 22-test suite through `get_kernel` ona GeForce RTX 3070 Ti (Ampere sm86, Linux):- **Analytic furnace, zero variance.** Closed uniform diffuse box underBRDF sampling: every path returns exactly `E * sum a^k`; the analyticvalue 0.498046875 is met with worst pixel deviation 3.4e-3. A diffuseplane under a constant environment reproduces `albedo * c` the same way.- **Fresnel slabs.** A smooth glass slab (ior 1.5) at normal incidencetransmits the internal-bounce series `(1-R)/(1+R)`: measured 0.923141against 0.923077 analytic (0.007%). A rough-dielectric slab atalpha = 0.02 transmits the same series within 0.05%.- **Beer-Lambert.** A purely absorbing medium attenuates a uniform emitterto `E * exp(-sigma_a d)` within 0.035%; with scattering on, MIS andBRDF-only means agree on a foggy Cornell box.- **Estimator agreement.** MIS, NEE-only, and BRDF-only means agree withinMonte Carlo tolerance on a Cornell box; MIS vs BRDF-only agree for a GGXconductor under an environment map and for rough plastic, which jointlyexercises the VNDF weight, the GGX pdf, the mixed-lobe pdf, and theenvironment pdf.- **Gradients match finite differences along the same paths.** Constants2.2e-4 max relative error over nine entries; wall-texture texels 2.6e-3;conductor F0 through GGX sampling and MIS 9.9e-4; plastic albedo throughboth lobes 2.8e-4; environment texels 2.1e-4 (detached CDF); emissiontexels linear-exact; medium sigmas 2e-2 gates. Texels no path can seeget exactly zero from both the replay and the differences.- **Geometry gradients match seed-averaged finite differences.** Interior:translating an area light matches central differences of the directimage within 15%. Boundary: each occluder vertex's gradient (shadowsweep + its own image silhouette) matches an 8-seed-averaged FD within0.23 worst-case (6-8% on three of four vertices; a single-seed FD of avisibility discontinuity is flip noise at these scales).- **Constants are 1x1 textures.** Both albedo forms render equal images tofloat rounding and receive matching gradients.- **Inverse rendering.** A wall color (3 unknowns) recovers to max error0.004 in 80 Adam steps; an 8x8 wall texture (192 unknowns) drives theimage loss from 1.8e-4 to 7.2e-14; a 4x8 emissive panel texture recoversfrom the room it lights; all through the kernel alone.- **Deterministic.** Repeated forward renders are bitwise identical;gradient buffers accumulate through float atomics and are deterministicin expectation but not bitwise.## MeasuredRTX 6000 Ada, 512x512, MIS, 4 bounces. The terrain scenes are displacedgrids with a 256x256 checker albedo texture, a GGX conductor block, and aconstant environment map; the SAH build is the vectorized torch builder.| scene | build | forward | backward (replay) ||---|---|---|---|1 unmodified line| terrain, 522,254 tris, 16 spp | 0.2 s | 18.3 ms (229 Mpaths/s) | 39.0 ms (2.1x) || terrain, 1,045,470 tris, 16 spp | 0.3 s | 20.3 ms (207 Mpaths/s) | 40.8 ms (2.0x) |## Requirements and limits- NVIDIA GPU with compute capability 8.0+; float32 throughout.- Materials: Lambertian diffuse, GGX conductor, smooth dielectric, roughplastic (F0 = 0.04 coat), rough dielectric (BSDF-sampled only; GGXroughness clamped to >= 0.01); per-texel emission; pinhole camera; atmost 64 materials and 16 bounces; two-sided surfaces; no Russianroulette (fixed bounce budget keeps the replay exact).- `render()` differentiates albedo texels/constants (all material types;conductor F0 tint), emission texels, environment texels, and mediumsigmas. Camera, UVs, roughness, and ior are frozen.- `geometry_grad()` differentiates vertex positions for thedirect-lighting term only: diffuse receivers and emitters carry theradiance jumps, indirect bounces are not differentiated, and uv motionacross textures is not differentiated. Boundary terms cover shadowsilhouettes and camera silhouettes.- The medium is homogeneous (isotropic phase), fills the scene, and ismutually exclusive with an environment map; its sampling rate isdetached at Scene construction (`scene.med_sbar`).- The environment sampling CDF is detached at Scene construction (a 0.5uniform-sphere mixture keeps every direction reachable, so optimizing anenv map from an arbitrary initialization stays unbiased); rebuild theScene to re-importance-sample a changed map.- Texture and env shapes are fixed at Scene construction; UVs wrap.- Published variants are Linux x86_64; on Windows `load_local.py`JIT-builds the same source and exposes the identical API.## ReferencesKajiya, "The Rendering Equation" (SIGGRAPH 1986); Vicini, Speierer, Jakob,"Path Replay Backpropagation" (SIGGRAPH 2021); Nimier-David, Speierer,Ruiz, Jakob, "Radiative Backpropagation" (SIGGRAPH 2020); Li, Aittala,Durand, Lehtinen, "Differentiable Monte Carlo Ray Tracing through EdgeSampling" (SIGGRAPH Asia 2018); Heitz, "Sampling the GGX Distribution ofVisible Normals" (JCGT 2018); Heitz, "Understanding the Masking-ShadowingFunction" (JCGT 2014); Walter et al., "Microfacet Models for Refractionthrough Rough Surfaces" (EGSR 2007); Veach and Guibas, "OptimallyCombining Sampling Techniques" (SIGGRAPH 1995); Möller and Trumbore,"Fast, Minimum Storage Ray-Triangle Intersection" (1997); Duff et al.,"Building an Orthonormal Basis, Revisited" (JCGT 2017); Wald, "On fastConstruction of SAH-based Bounding Volume Hierarchies" (2007).## License5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434 unmodified lines484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151 unmodified line1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701715 unmodified lines# pathtracer-diffA differentiable Monte Carlo path tracer as one kernel, loadable through`kernels`. The forward pass is a megakernel unidirectional path tracer withfive materials, area lights, an importance-sampled environment map, anoptional homogeneous medium, and multiple importance sampling; the backwardpass replays the identical paths with identical counter-based draws andemits analytic gradients. The reference standards are analytic transportresults and finite differences along the same paths.Rendering is a simulation of light, and making it differentiable turns itinto an instrument: give it a photograph and unknown scene parameters, andgradient descent recovers the materials, the lights, the fog, and thegeometry that produced the image. That normally requires a researchframework; here it is one loadable kernel, and inverse rendering is a baretorch loop: render, compare, `backward()`, step.<video src="https://huggingface.co/kernels/phanerozoic/pathtracer-diff/resolve/main/media/inverse.mp4" autoplay loop muted playsinline controls width="100%"><img src="https://huggingface.co/kernels/phanerozoic/pathtracer-diff/resolve/main/media/inverse.gif" alt="THE DRAGON'S HALL: one continuous inverse-rendering shot; a dark marble hall with a gold-trimmed pedestal, glowing rune band, warm sconces, and a levitating crystal Stanford dragon that slides onto its pedestal while fog fills the room, converging to the fixed target inset"></video>*THE DRAGON'S HALL (`media/make_hero.py`): one continuous shot, everygradient, optimized live through the kernel against the fixed TARGET inset.From a flat gray start, Adam through `render()` recovers the 128x128 marblefloor albedo (49,152 unknowns), the gold trim's conductor tint, thepedestal's plastic albedo, the braziers' warm emission (max err 1.75 of 14),and a 16x64 per-texel emissive rune band (3,072 unknowns, mean err 0.15),around a smooth glass slab and the rough-dielectric crystal dragon.Mid-shot, `geometry_grad()` alone takes over the dragon's position: 5,205vertices slide 4.60 scene units onto the pedestal by shadow and silhouettealone, final offset 0.004. In the last phase the participating medium rollsin: sigma_a and sigma_s recover from the hazy target to extinction error0.014. Image loss falls 8.5e-1 to 1.9e-1 at spp 8; the dim-hall floor andtrim retain residual texel error where the scene barely observes them.Stanford dragon courtesy of the Stanford Computer Graphics Laboratory.*## Usage4 unmodified linesptd = get_kernel("phanerozoic/pathtracer-diff", version=1, trust_remote_code=True)wall_tex = torch.full((256, 256, 3), 0.5, device="cuda", requires_grad=True)scene = ptd.Scene(vertices, faces, material_ids,albedo=[torch.tensor([0.73] * 3), wall_tex],emission=[torch.zeros(3), torch.zeros(3)],uvs=uvs, material_types=[ptd.DIFFUSE, ptd.DIFFUSE],roughness=[0.3, 0.3])cam = ptd.Camera(position=(2.78, 2.73, -8.0), look_at=(2.78, 2.73, 2.8),vfov_deg=39.0)img = ptd.render(scene, cam, 512, 512, spp=64, max_bounces=4)loss = (img - target).square().mean()loss.backward() # gradients on wall_texgrad_verts = ptd.geometry_grad(scene, cam, dloss_dimage)````version` selects the release branch; `trust_remote_code` is required by`kernels` for publishers without the trusted-publisher mark. A fixed `seed`renders the same paths every call, so the Monte Carlo objective is adeterministic function of the parameters and gradient descent sees a smoothlandscape at any spp.## API| Symbol | Purpose ||---|---|| `Scene(vertices, faces, material_ids, albedo, emission, uvs, material_types, roughness, ior, env, medium)` | triangle-mesh scene; BVH, light list, and the detached environment CDF / medium rate built at construction || `Camera(position, look_at, up, vfov_deg)` | pinhole camera || `render(scene, camera, height, width, spp, max_bounces, estimator, seed)` | differentiable render to `[H, W, 3]` f32 linear; autograd to albedo, emission, environment texels, and medium sigmas || `geometry_grad(scene, camera, grad_image, spp, edge_samples, seed)` | d(loss)/d(vertex positions) for the direct-lighting term: dual-number interior + edge-sampled shadow and camera silhouettes || `DIFFUSE`, `CONDUCTOR`, `DIELECTRIC`, `PLASTIC`, `ROUGH_DIELECTRIC` | material type constants || `ops.pt_forward` / `ops.pt_backward` / `ops.pt_geometry_grad` | raw kernel launches |## MethodOne thread owns one pixel and accumulates its spp samples serially, so theimage is bitwise deterministic with no atomics in the forward pass. Diffusevertices sample the cosine hemisphere; conductors sample the GGXvisible-normal distribution with the height-correlated Smith term; smoothdielectrics branch on Fresnel; rough plastic mixes a diffuse base with a GGXcoat under a 50/50 lobe-mixture pdf; rough dielectrics sample GGXtransmission. Direct light is estimated at every NEE-capable vertex by areasampling over emissive faces and, with an environment map, by a detachedmixture of its luminance CDF and the uniform sphere; BSDF-sampled hitscombine by the balance heuristic.The backward pass is exact path replay: sampling distributions depend onlyon geometry, frozen parameters, and the counter-based Philox stream, neveron the differentiable parameters, so the backward kernel re-traces identicalpaths with no stored path state. Every radiance term is a product ofper-bounce factors, each affine in its vertex's albedo texels, times alinear emission or environment texel; the replay differentiates the productin closed form with prefix/suffix exclusion products and scatters eachfactor's gradient into the four texels of its bilinear footprint. Geometrygradients run a separate pass over the direct-lighting term: forward-modeduals for the smooth part, redner-style edge sampling for shadow and camerasilhouettes.## MeasuredRTX 6000 Ada, 512x512, MIS, 4 bounces; terrain scenes are displaced gridswith a 256x256 checker albedo, a GGX conductor block, and a constantenvironment, built by the vectorized torch SAH builder:| scene | build | forward | backward (replay) ||---|---|---|---|1 unmodified line| terrain, 522,254 tris, 16 spp | 0.2 s | 18.3 ms (229 Mpaths/s) | 39.0 ms (2.1x) || terrain, 1,045,470 tris, 16 spp | 0.3 s | 20.3 ms (207 Mpaths/s) | 40.8 ms (2.0x) |## CorrectnessMeasured on RTX 6000 Ada from source; the published `v1` variants pass thefull 22-test suite through `get_kernel` on a GeForce RTX 3070 Ti (sm86):- Analytic furnace, zero variance: a closed uniform diffuse box returnsexactly `E * sum a^k` per path; the analytic 0.498046875 is met with worstpixel deviation 3.4e-3.- Fresnel slabs: a smooth glass slab at normal incidence transmits theinternal-bounce series `(1-R)/(1+R)`, measured 0.923141 against 0.923077(0.007%); a rough-dielectric slab at alpha 0.02 within 0.05%.- Beer-Lambert: a purely absorbing medium attenuates a uniform emitter to`E * exp(-sigma_a d)` within 0.035%.- Estimator agreement: MIS, NEE-only, and BRDF-only means agree within MonteCarlo tolerance across Cornell, GGX-under-environment, and rough-plasticscenes.- Gradients match finite differences along the same paths: constants 2.2e-4max relative over nine entries; wall texels 2.6e-3; conductor F0 throughGGX and MIS 9.9e-4; environment texels 2.1e-4; emission linear-exact;medium sigmas within 2e-2 gates. Texels no path can see get exactly zerofrom both sides.- Geometry gradients match seed-averaged finite differences: lighttranslation within 15%; occluder vertices within 0.23 worst case.- Inverse rendering: a wall color recovers to max error 0.004 in 80 Adamsteps; an 8x8 texture drives the loss from 1.8e-4 to 7.2e-14.- Deterministic: repeated forward renders are bitwise identical; gradientbuffers accumulate through float atomics and are deterministic inexpectation but not bitwise.## Requirements and limits- NVIDIA GPU with compute capability 8.0+; float32 throughout.- At most 64 materials and 16 bounces; two-sided surfaces; no Russianroulette (the fixed bounce budget keeps the replay exact); pinhole camera.- `render()` differentiates albedo, emission, environment texels, and mediumsigmas; camera, UVs, roughness, and ior are frozen. `geometry_grad()`covers the direct-lighting term only.- The medium is homogeneous, fills the scene, and is mutually exclusive withan environment map; the environment CDF is detached at Scene construction.- Published variants are Linux x86_64; on Windows `load_local.py` JIT-buildsthe same source.## ReferencesKajiya (1986); Vicini et al., "Path Replay Backpropagation" (2021);Nimier-David et al., "Radiative Backpropagation" (2020); Li et al.,"Differentiable Monte Carlo Ray Tracing through Edge Sampling" (2018);Heitz (2014, 2018) on GGX and VNDF; Walter et al. (2007); Veach and Guibas(1995); Möller and Trumbore (1997); Wald (2007) on SAH construction.## License
CARD.md+108-182
README.md+108-182