AI Wiki中文/EN

Neural radiance fields: turn posed photographs into a viewable scene

神经辐射场

Derive visibility, inverse-CDF sampling and full gradients; train two small radiance networks and evaluate unseen camera poses.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Walk around an object that was only photographed

You have four photographs of a small object. Moving a virtual camera between them should reveal a new view: the near side covers part of the far side, and a shiny patch may change brightness. Cross-fading photographs cannot, in general, produce that geometry. A neural radiance field, or NeRF, instead fits a function of spatial position and viewing direction, then renders the function along camera rays. The original method optimizes a separate representation for each scene from posed images. It is not a text-to-image model and does not infer a new object’s shape from a single photo by default. Paper, §§3–5

Imagine transparent colored layers along a ray. A front layer contributes some color and lets the rest of the light through. A rear layer is visible only through what the front layers transmit. NeRF predicts the ingredients for these layers at continuous query locations. Their composite must match an observed pixel. The training signal is the image mismatch; the model is not handed the correct density at every three-dimensional point.

This separation makes two questions worth asking before training: Where are the cameras? What can the photographs actually constrain? A pleasing training image does not prove accurate hidden geometry. If every photograph sees only the front of an object, many different backs can explain those observations.

Our example learns two synthetic colored density blobs from four known camera poses. Two other poses are reserved for evaluation. Both small networks are trained, including their density and color branches, with handwritten NumPy gradients. You can inspect every computation without downloading a dataset or using a GPU. The experiment establishes that this teaching pipeline works on its stated task; it does not reproduce the original paper’s architecture, data or scores.

Actual synthetic target and prediction at a held-out pose; the curve shows stochastic training loss. Compositing weights come from the two-layer calculation.
Actual synthetic target and prediction at a held-out pose; the curve shows stochastic training loss. Compositing weights come from the two-layer calculation.

A pixel is an ordered integral

Coordinates, density and directional color

Write the camera ray and its unit viewing direction as:

r(t)=o+td,d^=d/∥d∥,d≠0.\mathbf r(t)=\mathbf o+t\mathbf d,\qquad \widehat{\mathbf d}=\mathbf d/\|\mathbf d\|,\quad \mathbf d\ne\mathbf0.

The origin and direction use the same world frame as the field. Camera intrinsics determine which ray belongs to which pixel. The code constructs look-at rays directly, with image rows increasing downward; it does not import a COLMAP or OpenGL matrix. When importing poses, convert world-to-camera versus camera-to-world and axis conventions explicitly. Otherwise an optimizer can spend its effort fitting the wrong rays. See structure from motion for pose and scale ambiguities.

The field outputs density from position alone and RGB color from position and direction:

Fθ(x,d^)=(σθ(x),cθ(x,d^)),σ≥0.F_\theta(\mathbf x,\widehat{\mathbf d})= \bigl(\sigma_\theta(\mathbf x),\mathbf c_\theta(\mathbf x,\widehat{\mathbf d})\bigr), \qquad \sigma\ge0.

Density has inverse-length units in the chosen coordinate scale; it is not an opacity probability bounded by one. Color may vary with direction, allowing a representation of view-dependent appearance. This factorization encourages shared geometry but does not enforce a physically complete material or lighting model. Paper, §3

For the following integral, assume a unit-length ray direction, so that t measures distance. With a finite interval and a background color, our rendering model is:

T(t)=exp⁡ ⁣[−∫tntσ(r(s)) ds],C=∫tntfT(t)σ(r(t))c(r(t),d^) dt+T(tf)cbg.T(t)=\exp\!\left[-\int_{t_n}^{t}\sigma(\mathbf r(s))\,ds\right],\qquad \mathbf C=\int_{t_n}^{t_f}T(t)\sigma(\mathbf r(t))\mathbf c(\mathbf r(t),\widehat{\mathbf d})\,dt +T(t_f)\mathbf c_{\rm bg}.

T is the fraction that survives all earlier density. The explicit background term accounts for rays that traverse the whole finite interval. The paper’s displayed integral gives the volume contribution; the finite background convention here is part of our teaching model. If a direction is not unit length, multiply parameter intervals by its norm before computing attenuation. Paper, §4; renderer’s distance conversion Pinned rendering code

From density to an actual pixel

Approximate the field as constant in each ordered cell, with physical width delta. Integrating constant density in a cell gives:

τi=σiδi,αi=1−e−τi,Ti=e−∑j<iτj,wi=Tiαi.\tau_i=\sigma_i\delta_i,\qquad \alpha_i=1-e^{-\tau_i},\qquad T_i=e^{-\sum_{j<i}\tau_j},\qquad w_i=T_i\alpha_i.

Alpha is a cell opacity; sigma is a density. Doubling a cell’s width without changing its density increases its opacity. The composite and its conservation identity are:

C^=∑i=1Nwici+Tendcbg,Tend=e−∑iτi,∑iwi+Tend=1.\widehat{\mathbf C}=\sum_{i=1}^{N}w_i\mathbf c_i+T_{\rm end}\mathbf c_{\rm bg}, \qquad T_{\rm end}=e^{-\sum_i\tau_i},\qquad \sum_i w_i+T_{\rm end}=1.

The identity follows by telescoping: each weight is the transmission immediately before a cell minus the transmission immediately after it. It holds for nonnegative optical thickness, up to floating-point error in code. Our implementation uses -expm1(-tau) to avoid losing tiny opacity to subtraction. It handles an opaque first cell without dividing by the remaining transmission.

For a red front cell and a blue back cell, each with opacity 1/2, the weights are 1/2 and 1/4. A white background receives the remaining 1/4, producing RGB (0.75, 0.25, 0.50). Swapping the cells produces (0.50, 0.25, 0.75). Addition of colors is commutative; visibility along a ray is not. Alpha quadrature: paper, Eq. 3

Why encode coordinates?

Our network receives raw coordinates plus sinusoidal features. For one scalar coordinate:

γ~L(p)=[p,sin⁡(πp),cos⁡(πp),…,sin⁡(2L−1πp),cos⁡(2L−1πp)].\widetilde\gamma_L(p)= [p,\sin(\pi p),\cos(\pi p),\ldots, \sin(2^{L-1}\pi p),\cos(2^{L-1}\pi p)].

The three-coordinate vector therefore has dimension 3+6L. Sinusoids provide rapidly changing input features; they do not add observations or guarantee that a hidden surface is correct. Their meaning depends on coordinate scale. The original paper writes frequencies with pi and omits the raw coordinate in its displayed encoding. The pinned implementation includes the raw input and uses powers of two without pi. Our convention is stated above, so the example is not a numerical reproduction of either representation. Paper, §5.1 Embedding code

The two shared hidden layers in our field have width 12. We use tanh activations, softplus density and sigmoid RGB. Density cannot access the encoded direction. The color head concatenates the shared spatial features and direction encoding. With position L=2 and direction L=1, one network has:

(15⋅12+12)+(12⋅12+12)+(12+1)+((12+9)⋅3+3)=427(15\cdot12+12)+(12\cdot12+12)+(12+1)+((12+9)\cdot3+3)=427

trainable scalars. There are two independent networks, so their combined parameter count is 854. The original model uses a much larger ReLU network; its pinned color branch has one hidden layer. None of those large-model settings should be inferred from this small example. Paper, §3 Network construction

Coarse samples suggest where fine samples should go

Take one random query in each of N uniform bins during training. Evaluation uses bin midpoints. For our finite integration rule, place cell boundaries halfway between neighboring sorted queries and close the interval at the near and far bounds:

e0=tn,eN=tf,ei=(ti+ti+1)/2 (1≤i<N),δi=(ei−ei−1)∥d∥.e_0=t_n,\quad e_N=t_f,\quad e_i=(t_i+t_{i+1})/2\ (1\le i<N), \qquad \delta_i=(e_i-e_{i-1})\|\mathbf d\|.

This covers the entire interval. It differs from the pinned original renderer, which uses adjacent sample distances and a final interval of 1e10. Mixing these rules changes boundary behavior. In particular, a very long terminal interval can make even a small positive terminal density nearly opaque. Pinned renderer

Coarse opacity weights define a proposal over cells. Our smoothed bin masses and cumulative masses are:

pi=wi+ε∑j(wj+ε),qi=∑j≤ipj,ε=10−5,q0=0.p_i=\frac{w_i+\varepsilon}{\sum_j(w_j+\varepsilon)},\qquad q_i=\sum_{j\le i}p_j,\qquad \varepsilon=10^{-5},\quad q_0=0.

Here p is probability mass per bin, not density per unit distance. Within the selected bin, invert the linear CDF:

t=ei−1+u−qi−1qi−qi−1(ei−ei−1),qi−1≤u<qi.t=e_{i-1}+\frac{u-q_{i-1}}{q_i-q_{i-1}}(e_i-e_{i-1}), \qquad q_{i-1}\le u<q_i.

Our deterministic u values are midpoint quantiles. All-zero weights produce equal bin masses; unequal-width bins therefore do not yield uniform physical distance. The original helper uses endpoint-inclusive quantiles in deterministic mode, and its caller excludes the endpoint weights. Our full-cell proposal makes a different, explicit boundary choice. Hierarchical sampling: paper, §5.2 Proposal code Caller

Merge 12 coarse queries and 12 new queries, sort all 24, and evaluate the fine network at their union. This is nonuniform quadrature, not an independent importance estimate requiring a 1/p multiplier for every color. Coarse and fine networks each receive an image loss:

L=13B∑r=1B(∥C^c(r)−C(r)∥22+∥C^f(r)−C(r)∥22).\mathcal L=\frac{1}{3B}\sum_{r=1}^{B} \left(\|\widehat{\mathbf C}_c(r)-\mathbf C(r)\|_2^2+ \|\widehat{\mathbf C}_f(r)-\mathbf C(r)\|_2^2\right).

The mean convention differs by a constant from the paper’s sum. During backpropagation we hold the proposed positions fixed. The fine loss does not differentiate through the inverse CDF into the coarse network; the coarse network learns from its own RGB loss. The original caller also stops proposal gradients. Paper, §§5.2–5.3 Caller

A stable derivative through visibility

Let S after a cell denote the color of everything behind it, including the background, with no attenuation from earlier cells. It can be computed backward:

SN+1=cbg,Si=αici+(1−αi)Si+1.\mathbf S_{N+1}=\mathbf c_{\rm bg},\qquad \mathbf S_i=\alpha_i\mathbf c_i+(1-\alpha_i)\mathbf S_{i+1}.

For an upstream RGB gradient g, changing a cell’s opacity trades its own color against its entire suffix. Thus:

∂L∂αi=Ti gT(ci−Si+1),∂L∂σi=δie−τi∂L∂αi,∂L∂ci=wig.\frac{\partial\mathcal L}{\partial\alpha_i} =T_i\,\mathbf g^T(\mathbf c_i-\mathbf S_{i+1}),\qquad \frac{\partial\mathcal L}{\partial\sigma_i} =\delta_i e^{-\tau_i}\frac{\partial\mathcal L}{\partial\alpha_i},\qquad \frac{\partial\mathcal L}{\partial\mathbf c_i}=w_i\mathbf g.

This derivative explains why density need not always increase: making a cell more opaque helps only if replacing the suffix color improves the pixel. It also avoids division by 1-alpha at an opaque sample. The field’s chain rule then updates both hidden layers and both output branches; see backpropagation.

Train the whole small field

Save the following complete program as nerf.py. It runs with Python 3.12 and NumPy 1.26.4. It generates target images by integrating an analytic two-blob field with 256 samples per ray. Training receives only the resulting RGB pixels and camera rays, not the analytic density or color labels at query points. The target generator and learner share a tested compositing routine, so this is a controlled implementation exercise rather than an independent physical renderer comparison.

Each view contains 6×6 pixels. Training camera angles are 0, 1.7, 3.4 and 5.1 radians; held-out angles are 0.8 and 4.2. Camera height, radius, near/far bounds and white background remain fixed. The 180 Adam updates use 48 training rays per step, learning rate 0.01, beta values 0.9 and 0.999, and epsilon 1e-8. Seeds are fixed in the program. No camera optimization or scene normalization is performed.

Let H denote hidden width, Dₓ the position-encoding dimension and D_d the direction-encoding dimension. For B rays, a query network costs O(H²+DₓH+(H+D_d)·3) per sample for these two hidden layers. Hierarchical evaluation uses B·N_c coarse queries and B·(N_c+N_f) fine queries, plus O(B(N_c+N_f) log(N_c+N_f)) sorting. Stored backward activations grow with query count and hidden width. Rendering a large image still requires many queries even though the scene representation is compact. Chunking reduces peak memory without reducing the total query count.

"""Original tiny NeRF-style scene learner with complete NumPy gradients.

Two small networks, unit-direction color conditioning, finite ray intervals,
stratified coarse samples, inverse-CDF fine samples with stopped proposal
feedback. Midpoint cell boundaries cover the full near/far interval; this differs
from the original NeRF implementation's terminal 1e10 interval. Not a benchmark.
"""
import json
import numpy as np


def finite(value,shape=None):
    a=np.asarray(value,dtype=float)
    if not np.isfinite(a).all() or (shape is not None and a.shape!=shape):
        raise ValueError('Finite values with matching shapes required')
    return a


def integer(n,minimum=1,maximum=10000):
    if isinstance(n,(bool,np.bool_)) or not isinstance(n,(int,np.integer)) or not minimum<=n<=maximum:
        raise ValueError('Integer count outside the supported range')
    return int(n)


def sigmoid(x):
    z=np.exp(-np.abs(x));return np.where(x>=0,1/(1+z),z/(1+z))


def unit_vectors(d):
    d=finite(d)
    if d.ndim!=2 or d.shape[1]!=3:raise ValueError('N by 3 directions required')
    length=np.linalg.norm(d,axis=1,keepdims=True)
    if not np.isfinite(length).all() or np.any(length<1e-12):raise ValueError('Finite nonzero direction lengths required')
    return d/length,length


def encode(x,levels):
    x=finite(x);levels=integer(levels,0,12)
    if x.ndim!=2 or x.shape[1]!=3:raise ValueError('N by 3 coordinates required')
    frequencies=np.pi*2.**np.arange(levels)
    output=[x]
    for f in frequencies:output.extend([np.sin(f*x),np.cos(f*x)])
    return np.concatenate(output,axis=1),(x,frequencies)


def encode_vjp(upstream,cache):
    x,frequencies=cache;upstream=finite(upstream,(len(x),3+6*len(frequencies)));dx=upstream[:,:3].copy()
    for i,f in enumerate(frequencies):
        start=3+6*i;dx+=f*(upstream[:,start:start+3]*np.cos(f*x)-upstream[:,start+3:start+6]*np.sin(f*x))
    return dx


def initialize(hidden=12,position_levels=2,direction_levels=1,seed=1):
    h=integer(hidden,1,128);lx=integer(position_levels,0,12);ld=integer(direction_levels,0,12);rng=np.random.default_rng(seed)
    return {'w1':rng.normal(0,.3,(3+6*lx,h)),'b1':np.zeros(h),'w2':rng.normal(0,.3,(h,h)),'b2':np.zeros(h),
            'ws':rng.normal(0,.15,h),'bs':np.array(-.7),'wc':rng.normal(0,.2,(h+3+6*ld,3)),'bc':np.zeros(3)}


def field(x,d,p):
    x=finite(x);direction,norm=unit_vectors(d)
    if x.shape!=direction.shape or not len(x):raise ValueError('Matching nonempty coordinates and directions required')
    if set(p)!={'w1','b1','w2','b2','ws','bs','wc','bc'}:raise ValueError('All model arrays required')
    if np.ndim(p['b1'])!=1 or not len(p['b1']) or np.ndim(p['w1'])!=2 or np.ndim(p['wc'])!=2:raise ValueError('Positive hidden dimension and matrix weights required')
    h=len(p['b1']);lx=(np.shape(p['w1'])[0]-3)//6;ld=(np.shape(p['wc'])[0]-h-3)//6
    shapes={'w1':(3+6*lx,h),'b1':(h,),'w2':(h,h),'b2':(h,),'ws':(h,),'bs':(),'wc':(h+3+6*ld,3),'bc':(3,)}
    for key,shape in shapes.items():finite(p[key],shape)
    ex,cx=encode(x,lx);ed,cd=encode(direction,ld)
    a=np.tanh(ex@p['w1']+p['b1']);b=np.tanh(a@p['w2']+p['b2'])
    raw=b@p['ws']+p['bs'];sigma=np.logaddexp(0,raw);features=np.c_[b,ed];rgb=sigmoid(features@p['wc']+p['bc'])
    return sigma,rgb,(p,ex,cx,cd,direction,norm,a,b,raw,features,rgb)


def field_vjp(ds,dc,cache):
    p,ex,cx,cd,direction,norm,a,b,raw,features,rgb=cache
    ds=finite(ds,(len(a),));dc=finite(dc,rgb.shape);dr=ds*sigmoid(raw);dz=dc*rgb*(1-rgb)
    grad={'ws':b.T@dr,'bs':np.array(dr.sum()),'wc':features.T@dz,'bc':dz.sum(axis=0)}
    df=dz@p['wc'].T;db=dr[:,None]*p['ws']+df[:,:b.shape[1]];db*=1-b*b
    grad.update(w2=a.T@db,b2=db.sum(axis=0));da=(db@p['w2'].T)*(1-a*a)
    grad.update(w1=ex.T@da,b1=da.sum(axis=0))
    dx=encode_vjp(da@p['w1'].T,cx);dd=encode_vjp(df[:,b.shape[1]:],cd)
    dd=(dd-direction*np.sum(dd*direction,axis=1,keepdims=True))/norm
    return grad,dx,dd


def composite(sigma,color,distance,background):
    sigma=finite(sigma);color=finite(color);distance=finite(distance,sigma.shape);background=finite(background,(3,))
    if sigma.ndim!=2 or not sigma.size or color.shape!=sigma.shape+(3,) or np.any(sigma<0) or np.any(distance<0):
        raise ValueError('Nonempty ray samples, nonnegative density and distance required')
    with np.errstate(over='ignore'):tau=sigma*distance
    if not np.isfinite(tau).all():raise ValueError('Optical thickness overflow')
    transmission=np.exp(-np.c_[np.zeros(len(tau)),np.cumsum(tau,axis=1)[:,:-1]])
    remainder=np.exp(-tau.sum(axis=1));attenuation=np.exp(-tau);alpha=-np.expm1(-tau);weights=transmission*alpha
    output=np.sum(weights[:,:,None]*color,axis=1)+remainder[:,None]*background
    return output,weights,(sigma,color,distance,background,transmission,attenuation,alpha,remainder,weights)


def composite_vjp(upstream,cache):
    sigma,color,distance,background,transmission,attenuation,alpha,remainder,weights=cache
    upstream=finite(upstream,(len(sigma),3));tail=np.broadcast_to(background,upstream.shape).copy();dtau=np.zeros_like(sigma)
    for i in range(sigma.shape[1]-1,-1,-1):
        da=transmission[:,i]*np.sum(upstream*(color[:,i]-tail),axis=1)
        dtau[:,i]=da*attenuation[:,i]
        tail=alpha[:,i,None]*color[:,i]+attenuation[:,i,None]*tail
    return dtau*distance,weights[:,:,None]*upstream[:,None,:],dtau*sigma,np.sum(remainder[:,None]*upstream,axis=0)


def cells(samples,near,far):
    samples=finite(samples)
    if samples.ndim!=2 or not samples.size or not np.isfinite([near,far]).all() or not near<far:
        raise ValueError('Ordered finite ray interval required')
    if np.any(np.diff(samples,axis=1)<0) or np.any(samples<near) or np.any(samples>far):raise ValueError('Samples must be ordered inside bounds')
    # Voronoi-like cell boundaries, including both finite domain boundaries.
    edges=np.c_[np.full(len(samples),near),.5*(samples[:,1:]+samples[:,:-1]),np.full(len(samples),far)]
    return edges,np.diff(edges,axis=1)


def stratified(rays,n,near,far,rng=None):
    rays=integer(rays);n=integer(n)
    if not np.isfinite([near,far]).all() or near>=far:raise ValueError('Valid near/far bounds required')
    u=np.full((rays,n),.5) if rng is None else rng.random((rays,n))
    return near+(np.arange(n)+u)*(far-near)/n


def sample_pdf(edges,weights,n,rng=None):
    weights=finite(weights);edges=finite(edges);n=integer(n)
    if weights.ndim!=2 or not weights.size or edges.shape!=(len(weights),weights.shape[1]+1) or np.any(np.diff(edges,axis=1)<=0) or np.any(weights<0):
        raise ValueError('Strict bin edges and nonnegative weights required')
    mass=weights+1e-5;mass/=mass.max(axis=1,keepdims=True);mass/=mass.sum(axis=1,keepdims=True);cdf=np.c_[np.zeros(len(weights)),np.cumsum(mass,axis=1)];cdf[:,-1]=1
    u=np.broadcast_to((np.arange(n)+.5)/n,(len(weights),n)) if rng is None else rng.random((len(weights),n))
    result=np.empty_like(u)
    for row in range(len(weights)):
        index=np.minimum(np.searchsorted(cdf[row],u[row],side='right')-1,weights.shape[1]-1)
        fraction=(u[row]-cdf[row,index])/(cdf[row,index+1]-cdf[row,index])
        result[row]=edges[row,index]+fraction*(edges[row,index+1]-edges[row,index])
    return result


def render(origins,directions,samples,p,near,far,background):
    origins=finite(origins);directions=finite(directions);direction,length=unit_vectors(directions);samples=finite(samples)
    if origins.shape!=direction.shape or samples.ndim!=2 or samples.shape[0]!=len(origins):raise ValueError('Matching ray and sample batches required')
    edges,width=cells(samples,near,far)
    # t is a ray parameter; multiply intervals by |directions| to get lengths.
    locations=origins[:,None]+directions[:,None]*samples[:,:,None]
    dirs=np.broadcast_to(direction[:,None],locations.shape)
    sigma,color,network=field(locations.reshape(-1,3),dirs.reshape(-1,3),p)
    output,weights,volume=composite(sigma.reshape(samples.shape),color.reshape(samples.shape+(3,)),width*length,background)
    return output,weights,edges,(network,volume)


def ray_loss(target,cache,prediction):
    target=finite(target,prediction.shape);error=prediction-target;loss=float(np.mean(error**2));network,volume=cache
    ds,dc,_,_=composite_vjp(2*error/error.size,volume)
    grad,_,_=field_vjp(ds.ravel(),dc.reshape(-1,3),network)
    return loss,grad


def camera_rays(angle,size=6):
    size=integer(size,2,64);origin=np.array([2.2*np.cos(angle),.25,2.2*np.sin(angle)])
    forward=-origin/np.linalg.norm(origin);right=np.cross(forward,[0.,1,0]);right/=np.linalg.norm(right);up=np.cross(right,forward)
    yy,xx=np.mgrid[:size,:size];u=(xx-(size-1)/2)/(size*1.2);v=-(yy-(size-1)/2)/(size*1.2)
    directions=forward+u[:,:,None]*right+v[:,:,None]*up
    directions,_=unit_vectors(directions.reshape(-1,3))
    return np.broadcast_to(origin,directions.shape).copy(),directions


def truth_field(x,d):
    a=3.0*np.exp(-np.sum(((x-[-.23,0,0])/[.28,.35,.3])**2,axis=1)/2)
    b=2.5*np.exp(-np.sum(((x-[.28,.08,.03])/[.23,.25,.38])**2,axis=1)/2)
    sigma=a+b;rgb=(a[:,None]*[.8,.18,.1]+b[:,None]*[.1,.3,.8])/(sigma[:,None]+1e-30)
    rgb+=.06*(d[:,1,None]+1);return sigma,np.clip(rgb,0,1)


def dataset(angles,near=.7,far=3.8):
    origins=[];directions=[]
    for angle in angles:
        o,d=camera_rays(angle);origins.append(o);directions.append(d)
    o=np.concatenate(origins);d=np.concatenate(directions);t=stratified(len(o),256,near,far);_,width=cells(t,near,far)
    x=o[:,None]+d[:,None]*t[:,:,None];v=np.broadcast_to(d[:,None],x.shape)
    sigma,c=truth_field(x.reshape(-1,3),v.reshape(-1,3))
    target,_,_=composite(sigma.reshape(t.shape),c.reshape(t.shape+(3,)),width,np.ones(3))
    return o,d,target


def hierarchical(o,d,coarse,fine,near=.7,far=3.8,nc=12,nf=12,rng=None):
    t=stratified(len(o),nc,near,far,rng);rgbc,w,edges,cc=render(o,d,t,coarse,near,far,np.ones(3))
    proposal=sample_pdf(edges,w,nf,rng);merged=np.sort(np.c_[t,proposal],axis=1)
    rgbf,_,_,cf=render(o,d,merged,fine,near,far,np.ones(3))
    return rgbc,rgbf,cc,cf,merged


def train(steps=180,rate=.01):
    steps=integer(steps);rng=np.random.default_rng(13);data=dataset([0,1.7,3.4,5.1]);o,d,target=data
    models=[initialize(seed=1),initialize(seed=2)];moments=[({k:np.zeros_like(v) for k,v in p.items()},{k:np.zeros_like(v) for k,v in p.items()}) for p in models];history=[]
    if not np.isfinite(rate) or rate<=0:raise ValueError('Positive finite learning rate required')
    initial=hierarchical(o,d,*models);initial_loss=float(np.mean((initial[1]-target)**2))
    for step in range(1,steps+1):
        ids=rng.choice(len(o),48,replace=False);a,b,ca,cb,_=hierarchical(o[ids],d[ids],*models,rng=rng)
        lc,gc=ray_loss(target[ids],ca,a);lf,gf=ray_loss(target[ids],cb,b);history.append(lc+lf)
        # Separate losses: no gradient through coarse proposal positions into fine loss.
        for p,grad,(first,second) in zip(models,[gc,gf],moments):
            for key in p:
                first[key]=.9*first[key]+.1*grad[key];second[key]=.999*second[key]+.001*grad[key]**2
                p[key]-=rate*(first[key]/(1-.9**step))/(np.sqrt(second[key]/(1-.999**step))+1e-8)
    return models,data,initial_loss,history


def demo():
    models,data,initial,history=train();o,d,target=data;train_rgb=hierarchical(o,d,*models)[1]
    ot,dt,test=dataset([.8,4.2]);pred=hierarchical(ot,dt,*models)[1];baseline=np.broadcast_to(target.mean(axis=0),test.shape)
    mse=float(np.mean((pred-test)**2))
    return {'train_views':4,'test_views':2,'pixels_per_view':36,'coarse_samples':12,'fine_total_samples':24,
            'parameters_per_network':sum(v.size for v in models[0].values()),'initial_train_fine_mse':initial,
            'final_train_fine_mse':float(np.mean((train_rgb-target)**2)),'heldout_fine_mse':mse,'heldout_psnr':float(-10*np.log10(mse)),
            'training_mean_rgb_baseline_mse':float(np.mean((baseline-test)**2)),
            'first_training_loss':history[0],'last_training_loss':history[-1]}


if __name__=='__main__':print(json.dumps(demo(),indent=2))

The output below was actually produced by the program. Minor final-digit differences may occur across numerical libraries; comparisons use justified tolerances rather than requiring identical floating-point strings.

{
  "train_views": 4,
  "test_views": 2,
  "pixels_per_view": 36,
  "coarse_samples": 12,
  "fine_total_samples": 24,
  "parameters_per_network": 427,
  "initial_train_fine_mse": 0.0657482222433728,
  "final_train_fine_mse": 0.0004018653082918753,
  "heldout_fine_mse": 0.0022016666011150194,
  "heldout_psnr": 26.572484456996474,
  "training_mean_rgb_baseline_mse": 0.03703027092339929,
  "first_training_loss": 0.13174346638033724,
  "last_training_loss": 0.0008293850993072794
}

Training fine-image MSE falls from about 0.06575 to 0.000402. At the held-out poses, MSE is about 0.00220, versus 0.03703 for a constant RGB baseline computed solely from training pixels. PSNR uses a peak value of one: −10 log10(MSE), giving about 26.57 dB. These numbers refer only to this synthetic scene and split. The baseline is deliberately simple; it is not a comparison with an image-based renderer or another NeRF implementation.

The first and last logged training losses use different random minibatches and jittered samples. They are not the same measurement as full-training fine-image MSE evaluated with deterministic sampling. Compare like with like before interpreting a curve.

The companion preflight suite checks all 85 parameters of a reduced field by central differences, repeats those parameter checks through image loss at fixed samples, checks input and compositing derivatives, and exercises transparent/opaque cells, zero-weight sampling, ray rescaling and held-out evaluation. These are derivative and behavior checks of the teaching program, not evidence for the original paper’s benchmark claims.

A good pixel fit can hide a bad scene

  • Incomplete observations. RGB loss constrains rendered rays, not a unique three-dimensional explanation. Sparse views, occlusion and inaccurate poses can leave ambiguous density or view-dependent color. Add coverage and inspect novel views; a low training error alone is insufficient.
  • Sampling and scale. Thin structure can be missed by coarse queries; added proposal samples cannot guarantee recovery of every missed feature. Coordinate scaling changes the effective encoding frequencies, and changing ray lengths without converting density or intervals changes opacity.
  • Appearance and motion. Directional color is not a full decomposition of illumination, material and shape. This static model does not account for independently moving objects or changing exposure. Such violations should be addressed in data or in a different model.
  • Geometry and speed. A density field is not automatically a clean mesh or a metric depth map. Rendering cost depends on pixels, samples, network and hardware. This CPU exercise makes no real-time or real-scene quality claim.

A textured mesh can be a useful alternative when reliable surfaces are available. An explicit Gaussian representation uses a different rendering and optimization pipeline, discussed in the separate Gaussian-splatting topic. Choose by the required editability, geometry, capture conditions and rendering budget; “implicit” is not itself a quality metric.

Four checks before believing a reconstruction

  1. Hand calculation. A single constant-density cell has sigma=log(2), width 2, red RGB and a white background. What is the pixel?

    Answer: Optical thickness is 2 log(2), so transmission is 1/4 and opacity is 3/4. The result is (1, 1/4, 1/4). Treating sigma as alpha would give a different answer and would also ignore width.

  2. Sampling counterexample. All proposal weights are zero and the bin edges are 0, 1 and 3. Where do four deterministic midpoint quantiles land in this implementation?

    Answer: Smoothing gives each bin mass 1/2. Quantiles 1/8 and 3/8 map to 0.25 and 0.75; quantiles 5/8 and 7/8 map to 1.5 and 2.5. Uniform sampling over physical length would instead produce 0.375, 1.125, 1.875 and 2.625. Equal bin mass and equal spatial density differ when widths differ.

  3. Reparameterization. Replace every ray direction by four times itself, divide t and both bounds by four, and leave the field unchanged. Should the pixel change?

    Answer: No. Query positions o+td stay the same; normalized viewing directions stay the same; parameter widths are divided by four while direction norms are multiplied by four. Physical widths and all optical thicknesses are unchanged. Omitting the norm conversion breaks this invariance. This is a ray parameter change, not a rescaling of the entire world.

  4. Experimental judgment. Training MSE improves after you repeatedly tune settings using the two held-out views. Can the final held-out score still be called an untouched test result?

    Answer: No. Those views have become validation data through model selection. Reserve new poses for a final test, describe the selection process, and compare against a baseline trained without those views. Also inspect geometry or additional views if the intended claim concerns reconstruction rather than RGB interpolation.

Read the method and the executable conventions together

The first arXiv submission was on 19 March 2020 at 17:57:23 UTC; the v2 used here followed on 3 August. Submission, conference presentation and formal publication are distinct dates. Official submission history

Mildenhall and colleagues introduced NeRF as a per-scene radiance-field optimization method. The cited v2 paper’s §§3–5 explain the coordinate network, alpha quadrature, encoding, two-stage sampling and image loss. Our source review covers physical PDF pages 3–9; it does not certify the complete supplement, benchmark tables or later variants. Paper

The pinned official implementation is useful because several details are more specific than the paper’s equations: raw input inclusion, frequency convention, terminal interval, interior proposal weights and stopped sample gradients. We inspected those portions rather than executing its TensorFlow training pipeline. The repository’s MIT license was read; this article’s NumPy implementation and teaching calculations are original. Helpers Renderer

Follow-up reading should separate representation, sampling, anti-aliasing, acceleration and data assumptions. Improving one does not automatically solve the others. This article establishes the original mechanism and a complete small training exercise; it does not substitute for individual treatments of subsequent radiance-field methods.

Make a prediction, then check

All proposal weights are zero and two bins have different lengths. After adding the same epsilon to each weight, is sampling uniform in physical distance?

Choose one answer

Learning objectives

  • Separate density, opacity, transmission and direction-dependent color.
  • Derive finite-ray alpha compositing and its stable backward pass.
  • Explain hierarchical sampling, stopped proposal gradients and coordinate conventions.
  • Train both small fields and assess disjoint camera views against a training-only baseline.

Prerequisites & connections

Explore related knowledge →

References

  1. NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis (v2)
    Ben Mildenhall; Pratul P. Srinivasan; Matthew Tancik; Jonathan T. Barron; Ravi Ramamoorthi; Ren Ng · 2020
  2. bmild/nerf — run_nerf_helpers.py
    bmild/nerf contributors
  3. bmild/nerf — run_nerf.py
    bmild/nerf contributors
  4. NeRF official arXiv submission history
    Ben Mildenhall and colleagues · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: scoped original paper and pinned official code; complete NumPy coarse/fine training, 13 matching display equations, four explained bilingual exercises, actual outputs and held-out evaluation. Formal suite executes production MDX; final static-site checks recorded separately. Original figures checked in an isolated responsive harness with four fonts. Not human peer review or an original NeRF benchmark reproduction.

  • Compared both complete manuscripts section by section: coordinate frames and density units, finite background and telescoping weights, frequency conventions, proposal boundaries and stopped gradients, stable suffix derivatives, model size, data split, loss definitions, limitations and four worked answers. Thirteen display formulas and the 218-line Python program match. AI author check, not independent human review.
  • Formal production-MDX suite contains 20 core numerical checks plus nine publication checks. The written-stage run passed 28 and explicitly skipped final freeze; rerun all 29 after binding. Finite differences cover every parameter of an 85-parameter reduced field and inputs, including the composed image loss; the training example has 427 parameters per network.
  • Rechecked 33 compositing derivatives, constant-medium closed form, transparent and opaque limits, tiny opacity, order sensitivity, nonunit-ray invariance, zero-weight bin mass, proposal stopping and held-out baseline. MSE 0.0022016666 versus training-mean 0.0370302709 concerns only the synthetic scene; target and learner share a tested compositor.
  • Four original SVGs and numerical data come from actual training and two-layer compositing. Isolated picture harness passes 390/768/1536 widths and four font families after fixing two English mobile lines. Full article interactions, rendering and search require the final publication validation record.
  • Official arXiv v1 history re-read: 2020-03-19 17:57:23 UTC. Kept submission distinct from presentation/publication; adopted no benchmark scores. Read paper scope, code convention differences and original teaching choices remain explicit.
  • Final static-link and browser validation exposed unrendered Chinese emphasis delimiters. Seven explicit spans were converted to strong tags; exact reversal reproduces the frozen Chinese draft. Wording, code, equations, outputs, English and figures are unchanged; corrected build is checked separately.

Source locations checked:

  • NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis (v2) · Physical PDF pages 3–9 read as extracted text; methods in §§3–5 rechecked. Not full supplement, benchmark tables or visual inspection. SHA-256 c7fc70b38f84cb2e42890a69a7c9b9c26ded464b221e0355031004f24fb8e727.
  • bmild/nerf — run_nerf_helpers.py · Pinned commit 14c55567a6d0fbd75d3fd12b0411f98160ba3237; read line ranges [[20, 66], [80, 119], [183, 227]]. Not executed. MIT license read; teaching code original, no upstream code copied.
  • bmild/nerf — run_nerf.py · Pinned commit 14c55567a6d0fbd75d3fd12b0411f98160ba3237; read line ranges [[93, 158], [208, 233]]. Not executed. MIT license read; teaching code original, no upstream code copied.
  • NeRF official arXiv submission history · Official page lines 8–29 read with web tool: first submission 2020-03-19 17:57:23 UTC; v2 2020-08-03. This is an arXiv submission date, not conference presentation or evidence of benchmark replication.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.