JHCodec: Generalized Ray Tracing Sampler
- JHCodec is a generalized ray tracing framework that reinterprets MCMC sampling by modeling parameter space as an optical medium with a refractive index tied to the likelihood.
- It enforces fair sampling through conservation of optical invariants, unifying methods such as HMC, Gibbs, and Metropolis under one geometric formalism.
- The method utilizes constant-speed ray propagation to mitigate stochastic gradient noise, enabling scalable sampling in high-dimensional settings like large neural networks.
Below is a focused technical summary of the paper’s generalized ray tracing framework for sampling.
1. Core idea: sampling by tracing rays in parameter space
The paper’s central idea is to reinterpret MCMC sampling geometrically:
- The parameter vector is a point in a -dimensional “optical medium.”
- The target density is represented by an unnormalized likelihood .
- One evolves trajectories not as particles under forces, but as light rays traveling through a medium whose refractive index depends on .
The key design principle is to choose the refractive index so that the geometric concentration of rays in space exactly matches the target density. The paper argues that in dimensions, optical refraction changes ray density by powers of , so fair sampling is obtained with
This is the basic ray tracing sampler. But the paper goes further: by allowing arbitrary sample weights and/or variable speed , the method becomes a generalized framework that includes several existing samplers as special cases.
So the contribution is not just “a new sampler”; it is a unifying geometric formalism in which many local MCMC methods correspond to different choices of:
- path geometry,
- refractive index ,
- speed 0,
- and sample weight 1.
2. Optical invariants that make the method work
2.1 Basic radiance
The paper derives that, in 2 dimensions, for refraction without reflection, the conserved optical quantity is
3
where 4 is the radiance, interpreted here as the geometric density of ray paths, i.e. the sampling density in position/direction space.
This is derived from power conservation across an interface plus Snell’s law. For incoming/outgoing bundles at indices 5,
6
and with differential Snell relations
7
one gets
8
Hence 9 is invariant.
2.2 Etendue
The paper also defines the conserved 0-dimensional optical phase-space quantity (analog of Liouville volume in Hamiltonian mechanics) as
1
This is the generalized etendue. Conservation of etendue explains how cross-sectional area and solid angle transform under ray propagation. The consequence for sampling is that the ray-bundle phase-space volume is compressed by a factor 2.
3. Fair sampling from likelihood via refractive index
The basic fair-sampling construction is:
3
Because radiance transforms as 4, this makes
5
So the geometric density of ray paths is directly proportional to the target likelihood. This is the stationarity mechanism.
The paper gives a local detailed-balance style derivation: emit rays isotropically from a differential volume around 6 with intensity proportional to 7,
8
with 9 independent of position and direction. Using conservation of etendue between 0 and 1, one gets that the power density arriving at 2 is
3
for the choice 4. Because ray paths are reversible, forward and reverse transitions satisfy detailed balance.
Resulting stationary distribution
For the unweighted constant-speed ray tracer, the stationary sampling density in parameter space is proportional to
5
In the generalized weighted case, the samples may carry nonuniform weights 6, but the effective weighted stationary measure remains the desired target 7.
4. Ray dynamics: constant-speed propagation
The standard ray equation used is
8
where 9 is path length. Rewriting yields the evolution of the unit direction vector:
0
This is important:
- only the gradient of 1 matters,
- only the component of 2 perpendicular to the direction of motion bends the ray.
If 3 is the angle between the direction of travel and 4, then
5
The paper integrates this exactly over one kick step to maintain reversibility:
6
Constant speed vs HMC
This is the paper’s main dynamical distinction from HMC.
- Ray tracing: rays move at constant speed through parameter space; the likelihood only bends the trajectory.
- HMC: a particle accelerates/decelerates under the potential 7; both direction and speed change because kinetic and potential energy exchange.
The paper emphasizes that constant speed means stochastic gradient errors perturb only the direction, not the kinetic energy. That is the basis for its robustness claims.
5. Acceptance rule and exactness with imperfect integrators
For an imperfect numerical integrator, the path will not preserve basic radiance exactly. The paper derives a local radiance boost for a direction update 8:
9
Accumulating this over a trajectory yields a predicted ratio 0. Then the Metropolis-like correction is
1
In the generalized weighted framework, this becomes
2
This is exactly the inverse ratio of excess basic radiance at the endpoint, and it restores exact sampling provided:
- the path map is reversible,
- the Metropolis correction is applied,
- the chain is ergodic.
6. Generalized ray tracing with weights and variable speed
The framework is generalized by allowing explicit sample weights 3 and path speed 4.
The paper states that the effective sample density scales as
5
To preserve fair sampling, this must equal the target likelihood:
6
Since 7, one obtains the generalized refractive index
8
This is the master equation of the generalized framework.
Interpretation:
- changing 9 changes path geometry,
- changing 0 changes how much time is spent along the path,
- changing 1 changes the weight assigned to visited points.
This separation is what lets the framework subsume HMC, microcanonical HMC, Gibbs, Metropolis, Monte Carlo integration, and tempered variants.
7. Ergodicity, scattering, barriers, and holes
Ergodicity
Ray propagation by itself is deterministic given initial direction. To guarantee exploration, the direction must be refreshed. The paper proposes periodic full or partial momentum refreshes.
Partial momentum refresh / scattering
A partial refresh is treated as a random rotation of direction, preserving Jacobian. The paper recommends performing it between completed integration steps. If no refresh occurs between Metropolis tests, failed proposals should reverse direction to maintain reversibility.
Crossing likelihood barriers
A major claim is that ray tracing can cross arbitrary likelihood barriers, unlike ordinary HMC at fixed energy.
Why:
- In basic ray tracing, the speed is fixed and only curvature changes.
- There is no fixed energy ceiling preventing access to low-likelihood regions.
- Rays can pass through regions of arbitrarily low likelihood; they are merely refracted according to 2.
This is contrasted with HMC, where a fixed total energy forbids entering regions with 3.
Crossing holes / disallowed regions
The paper further claims ray tracing can cross “holes” or disconnected allowed regions if boundaries are treated as blackbody radiators:
- boundaries absorb incoming rays,
- then re-emit them with Lambertian emissivity proportional to 4.
This gives a mechanism to move between disconnected components (“parameter space islands”), something standard Hamiltonian integration cannot do.
Conditions for correct sampling
Correct sampling requires:
- reversibility of the path integrator,
- detailed balance via conserved basic radiance or Metropolis correction,
- ergodicity via direction refresh/scattering,
- either connected support, or special blackbody-boundary handling for islands.
8. Why stochastic gradients affect ray tracing differently from HMC
The paper’s main practical claim is much stronger resilience to stochastic gradients.
HMC problem
Stochastic gradients inject energy into the trajectory, causing path heating. In SGHMC, this requires friction/diffusion terms tuned to the noise covariance.
Ray tracing claim
Because ray tracing keeps path speed fixed, stochastic gradient errors do not accumulate as kinetic-energy heating. They mainly perturb direction, which is actually similar to the deliberate scattering needed for ergodicity.
The residual issue is wrong acceptance probabilities due to noisy likelihood estimates, not runaway heating.
The paper proposes a stochastic acceptance correction:
5
where 6 is the variance of 7.
But the paper also notes that when stochastic likelihood noise dominates integration error, a Metropolis test can become meaningless; then threshold/masking strategies are more useful.
9. Relationship to prior methods under the generalized framework
This is one of the paper’s most interesting claims: many samplers are recovered by choosing 8, 9, and 0 appropriately.
9.1 Hamiltonian Monte Carlo as ray tracing
For HMC with potential 1, and specific kinetic energy 2, total energy conservation implies
3
Geometrically, the transverse component of velocity is conserved across potential jumps:
4
which has Snell-law form. Hence HMC paths are identical to ray paths with
5
and specifically
6
So HMC is a generalized ray-tracing method where:
- refractive index depends on energy through 7,
- speed is not constant,
- sample weighting is effectively inverse velocity.
At low likelihood where 8, 9, so HMC has an impassable barrier. This explains geometrically why ordinary HMC cannot cross arbitrary likelihood barriers.
The paper also notes Langevin methods follow because they can be written as single-step HMC.
9.2 Microcanonical HMC
The paper identifies microcanonical HMC as the choice
0
which leads to
1
This is close to standard ray tracing 2 in large 3, so the path dynamics are similar asymptotically. The paper’s distinction is that ray tracing decouples speed from likelihood, which improves stochastic-gradient robustness.
9.3 Gibbs sampling
In this framework, Gibbs sampling corresponds to
4
Since 5 is constant:
- rays are straight lines,
- 6,
- the phase-space Jacobian is trivial.
The weights 7 then enforce the conditional distribution along the chosen coordinate/subspace.
9.4 Metropolis(-Hastings)
A Metropolis step is described as:
- a single ray-tracing step,
- integrated by Euler,
- with 8,
- 9,
- and proposal length 0 drawn from the chosen proposal distribution (often Gaussian).
So again the path is straight, and the usual accept/reject rule is recovered as the weighted-sampling correction.
9.5 Monte Carlo integration
Monte Carlo integration appears as a limiting case of Gibbs sampling with masked samples:
- weights are zero everywhere along the path,
- except at ray endpoints / refresh points, where they are 1.
So raw Monte Carlo integration is a degenerate straight-ray weighted sampler.
9.6 Goodman–Weare stretch move
The paper also sketches an interpretation of the stretch move:
- 2 outside a narrow cone from target walker to current walker,
- inside the cone, weighting 3 for 4. This is less central than the other correspondences but supports the unification claim.
10. Tempering inside the generalized framework
Because path geometry and weighting are separated, one can define a tempered family while still sampling the original target correctly.
For effective temperature 5, the paper gives
6
So:
- increasing 7 flattens the refractive-index landscape,
- low-likelihood regions are traversed faster / with lower weight.
If 8 depends on 9, then
00
This preserves alignment with the 01 gradient direction up to a scalar.
11. Algorithmic implementation
Inputs
The pseudocode GRTSample takes roughly:
- initial point 02,
- dimension 03,
- number of integration steps 04,
- path step size 05,
- refresh parameter 06,
- target likelihood 07,
- optional weight function 08 (default 1).
Required gradient
Only the gradient of the log refractive index is needed. In the basic weighted constant-speed implementation:
09
So in practice one needs 10 (or gradient of loss / log posterior), not the Hessian.
Update scheme
The pseudocode uses a drift-kick-drift leapfrog structure:
- partial momentum refresh,
- half drift:
11
- kick using
UpdateV, - another half drift.
The velocity magnitude is irrelevant for the path because only 12 matters in drifting.
Partial refresh
The direction update is
13
with fresh Gaussian 14, i.e. Ornstein–Uhlenbeck-style partial refresh.
Direction update
Inside UpdateV, one computes:
- 15,
- 16,
- initial angle 17,
- final angle 18 via the exact reversible formula.
Then the new velocity is
19
where
20
The cumulative radiance change is tracked as
21
Metropolis test
At the end,
22
triggers rejection.
Numerical integrators
The paper discusses:
- KDK and DKD leapfrog,
- random alternation between KDK and DKD,
- Omelyan second-order,
- Forest–Ruth / Yoshida fourth-order.
It finds Omelyan best over a broad practical range in a 10,000D Gaussian test.
Complexity
Per integration step:
- one gradient of 23 (or loss) at a midpoint,
- 24 vector operations.
So computational cost is similar in order to HMC: dominated by gradient evaluations. The key gain is not lower per-step cost but better behavior under noisy gradients and large-model minibatching.
12. Practical recommendations for neural networks
Approximate likelihood from a loss
When no proper probabilistic likelihood is available, the paper proposes
25
where:
- 26 is the training loss,
- 27 is desired tolerance above optimum,
- 28 is an effective number of constrained parameters.
This is exact for Gaussian targets and suggested as a practical approximation for high-dimensional models.
Recipe
The paper’s recommended workflow:
- burn in with low-temperature ray tracing or Adam,
- choose likelihood scaling / 29,
- tune step size (start around 30),
- tune refresh rate,
- run many walkers,
- assess convergence in function space, not necessarily weight space.
High-dimensional caveats
- Neural-network posteriors in weight space are often filamentary and non-Gaussian.
- Convergence in weight space may be poor or absent even when function-space uncertainty is useful.
- The sampler is not generically separable; if subspaces have very different gradient scales, independent ray dynamics by subspace may help.
13. Experimental evidence relevant to the framework
13.1 Gaussian benchmarks
For a 10,000D Gaussian:
- with exact gradients, ray tracing and HMC have roughly similar performance when tuned well;
- Metropolis correction matters for imperfect integrators;
- Omelyan integrator performed best across a broad step-size range.
So the paper does not claim huge gains over exact-gradient HMC in benign settings.
13.2 Stochastic-gradient robustness
This is the headline empirical result.
For stochastic Gaussian gradients defined by
31
the paper finds:
- ray tracing remains accurate up to 32,
- HMC degrades by 33.
The median-log-likelihood error obeys
34
with empirical resilience
- HMC: 35,
- ray tracing: 36.
So ray tracing tolerated about 37 larger noise amplitude, or 38 larger variance, at comparable bias.
Scaling with step size:
- HMC robustness: 39,
- ray tracing robustness: 40.
This implies smaller minibatches can improve total efficiency for ray tracing, but not for HMC.
13.3 Neural-network applications
- MLP, 1433 params: both HMC and ray tracing work; similar posterior predictions, somewhat better autocorrelation for ray tracing.
- ResNet-34, 22M params: ray tracing feasible on one consumer GPU; HMC not attempted because minibatch stochasticity too high.
- GPT-2, 1.5B params: approximate posterior sampling on a single consumer GPU; stable validation loss around target; median autocorrelation time for sampled token probabilities around 41 tokens.
The GPT-2 experiment is presented as approximate rather than exact, but it supports the paper’s claim that the framework scales to very large neural networks under stochastic gradients.
14. Limitations and caveats
The paper is fairly candid about several limitations:
- 42: the basic formula
43
is undefined; the ray-tracing formulation is meaningful only for 44.
- Need for refresh/scattering: deterministic ray tracing alone is not ergodic.
- Disconnected support: requires special blackbody-boundary treatment for islands.
- Approximate likelihoods for neural nets: practical results depend on choosing 45 and loss scaling, often heuristically.
- Weight-space convergence may fail even when function-space uncertainty is useful.
- Very large models: reported GPT-2 sampling is approximate and affected by BF16 quantization spikes; the paper uses masking to skip bad samples.
- No universal speed advantage over exact-gradient HMC in clean, standard targets; the strongest advantage is specifically for stochastic-gradient settings.
15. Why the generalized framework matters
The significance of the framework is threefold.
(i) A new geometric route to correct sampling
Instead of preserving Hamiltonian energy, it preserves an optical invariant: 46 This gives a distinct acceptance rule and a natural fair-sampling construction.
(ii) A principled separation of geometry from weighting
The generalized formulation
47
separates:
- path geometry 48,
- traversal speed 49,
- sample weight 50.
That makes the approach a family of samplers, not just a single one.
(iii) Unification of prior samplers
Under this lens:
- HMC is ray tracing with 51,
- microcanonical HMC uses 52,
- Gibbs uses 53,
- Metropolis is a one-step straight-ray weighted update,
- Monte Carlo integration is masked Gibbs sampling.
So the framework provides a common language for comparing how different samplers trade off exploration of high-probability peaks versus low-probability tails.
16. Bottom-line summary
The paper proposes a sampling framework based on optical ray propagation in parameter space. The fair-sampling version chooses
54
so that conservation of optical radiance implies ray density 55. Ray paths evolve according to
56
or equivalently
57
with constant path speed and reversible angle update
58
Correctness is enforced through conservation of the “basic radiance”
59
with Metropolis correction
60
or in generalized form
61
The generalized framework introduces weights and speeds: 62 which lets many standard methods appear as special cases.
Its main practical claim is that constant-speed rays are vastly more robust than HMC to stochastic-gradient heating, which the experiments support strongly. That robustness is what enables approximate posterior sampling for very large neural networks, including GPT-2-scale models, on modest hardware.