Skip to main content
Case Study / 06

NeRF Turntable — 2D to 3D Neural View Synthesis

From-scratch PyTorch Neural Radiance Field synthesizing 360° novel views from circular photographs

01 / Summary

Executive Summary & Facts

Problem: Reconstructing 3D physical objects from sparse circular photographs traditionally requires explicit polygonal meshes or discrete voxel grids. These classical representations scale cubically in memory, fail to capture fine geometric details and semi-transparency, and completely miss view-dependent lighting phenomena such as specular reflection and glossy sheen.

Result: Engineered a from-scratch PyTorch implementation of Neural Radiance Fields (NeRF) (Mildenhall et al., ECCV 2020) that optimizes a continuous 5D neural radiance function without third-party 3D graphics libraries. The system maps spatial coordinates and viewing angles through harmonic positional encoding into an 8-layer deep MLP with softplus volume density and directional color heads. Trained on 20 turntable photographs across 30,000 gradient steps, it synthesizes photorealistic novel views and smooth 60-frame 360° orbiting animations on a consumer GPU (NVIDIA RTX 3050, 4GB VRAM), wrapped in a full-stack FastAPI and React 19 web application.

Role: Computer Vision & Deep Learning Engineer; formulated the mathematical ray marcher, harmonic coordinate expansion, volumetric quadrature renderer, CUDA training loop, and asynchronous FastAPI background rendering engine.

Role & OwnershipComputer Vision & Deep Learning Engineer
Timeframe & StatusNov 2024 – Jan 2025 · Open-Source Implementation & Web App
Core Stack
PyTorch · CUDA · FastAPI · React 19 · Tailwind CSS · SQLAlchemy · NumPy · Docker
Artifacts & References
02 / Problem

Problem & Theoretical Constraints

Novel view synthesis requires bridging the gap between discrete 2D sensor observations and continuous 3D reality:

The Limits of Explicit 3D Geometry

Classical photogrammetry techniques rely on explicit surface reconstructions—such as Structure-from-Motion (SfM) point clouds or Multi-View Stereo (MVS) triangle meshes. Meshes require defining fixed surface topology, causing catastrophic artifacts when modeling thin structures (e.g., wires, foliage, fur) or semi-transparent volumes. Furthermore, explicit voxel grids scale cubically O(N³) with resolution; representing a modest 512³ grid consumes gigabytes of memory before accounting for color and directional radiance.

Spectral Bias in Neural Approximators

Standard deep Multi-Layer Perceptrons exhibit a well-documented spectral bias (Rahaman et al., 2019): they inherently prioritize low-frequency approximations. Feeding raw spatial coordinates (x, y, z) directly into neural layers results in blurry, over-smoothed renderings that completely fail to capture high-frequency surface textures and sharp object boundaries.

Audited Engineering & Hardware Constraints:
• Zero Third-Party 3D Frameworks: Built completely from first principles in raw PyTorch without relying on high-level frameworks (Nerfstudio, Instant-NGP, Tiny-CUDA-NN).
• Consumer VRAM Ceiling: Must train and render strictly within the 4GB VRAM boundary of a mobile workstation GPU (NVIDIA GeForce RTX 3050 Laptop GPU).
• Continuous Turntable Pose Ingestion: Formulate a deterministic spherical camera model (radius R = 4.0, elevation θ = 30°) to compute consistent look-at rotation matrices from sequential uncalibrated mobile photos.
• Asynchronous Production Serving: Render jobs take ~75 seconds for a 60-frame 360° rotation; the web service must employ decoupled background task queues with persistent job status tracking rather than blocking HTTP sockets.
03 / Architecture

Mathematical Formulation & Pipeline Architecture

The system represents a 3D scene as a continuous function parameterized by a neural network F_Θ: (x, d) → (c, σ), mapping spatial position x = (x, y, z) and viewing unit direction d = (θ, φ) to volume density σ and emitted RGB radiance c:

NeRF Volumetric Rendering PipelinePyTorch · Harmonic Positional Encoding · Ray Marching
CAMERA POSEr(t) = o + t·dCircular TurntableRAY MARCHINGStratified SamplesN = 96 samples / rayNear: 2.0 · Far: 6.0HARMONICPos Encoding γx: 3D → 63D (L=10)d: 3D → 27D (L=4)8-LAYER MLPHidden: 256Skip @ Layer 5Density σ (Softplus)Color c (Sigmoid)VOLUMEINTEGRALC = Σ T·α·cRGB Pixel
Figure 4: NeRF mathematical architecture. From camera pose rays to stratified spatial sampling, harmonic sinusoidal coordinate expansion, an 8-layer deep MLP with skip connections, and numerical quadrature volumetric integration.

1. Turntable Camera Geometry & Ray Generation

Camera poses for M = 20 turntable photographs are computed along a circular orbit at radius R = 4.0 with elevation angle θ = 30°:

camera_pos = [R · cos(elevation) · cos(φ), R · cos(elevation) · sin(φ), R · sin(elevation)]

For each pixel (i, j) in an image with focal length f = W, a ray r(t) = o + t·d is projected into world space using the camera-to-world transformation matrix [R | T].

2. Stratified Ray Sampling with Jitter

Rather than evaluating points on a fixed uniform grid (which leads to discrete banding artifacts), N = 96 sampling intervals are partitioned along each ray between near plane t_n = 2.0 and far plane t_f = 6.0. During training, uniform random jitter is added within each interval:

t_i ~ U[t_n + (i-1)/N · (t_f - t_n), t_n + i/N · (t_f - t_n)]

This forces the network to learn a smooth, continuous field over space rather than memorizing discrete evaluation coordinates.

3. Harmonic Sinusoidal Positional Encoding

To circumvent spectral bias and capture crisp surface boundaries, coordinates are projected into higher-dimensional sinusoidal bases:

γ(p) = [p, sin(2⁰πp), cos(2⁰πp), ..., sin(2^(L-1)πp), cos(2^(L-1)πp)]

Spatial coordinates x are encoded with L = 10 frequency bands (3 × (1 + 20) = 63 dimensions); viewing directions d are encoded with L = 4 frequency bands (3 × (1 + 8) = 27 dimensions).

4. 8-Layer Deep MLP Network Architecture

The network is structured to enforce view-consistent geometry:

  • Geometry Trunk: 8 fully connected layers (hidden dim 256) with ReLU activations. A skip connection at layer 5 concatenates the original input spatial encoding γ(x), preserving high-frequency spatial priors.
  • Density Output: Volume density σ is predicted strictly from spatial features independent of viewing direction: σ = Softplus(W_σ · h). Softplus ensures density remains strictly non-negative (σ ≥ 0) while avoiding zero-gradient death.
  • View-Dependent Radiance: A 256-dimensional feature vector is extracted and concatenated with directional encoding γ(d). Two additional linear layers with Sigmoid activation predict emitted RGB color c ∈ [0, 1]³, capturing specular highlights that shift as the observer moves around the turntable.

5. Classical Numerical Quadrature Volumetric Rendering

The continuous volume rendering integral is evaluated numerically along each ray:

Ĉ(r) = Σ [i=1 to N] T_i · (1 - exp(-σ_i · δ_i)) · c_i

where T_i = exp(-Σ [j=1 to i-1] σ_j · δ_j) represents accumulated transmittance (the probability that the ray traverses from t_n to t_i without encountering an occluder), and δ_i = t_{i+1} - t_i represents the distance between adjacent samples. White background compositing is applied for transparent empty space: C_final = Ĉ + (1 - Σ w_i).

04 / Key Decisions

Engineering Decisions & Defenses

Decision: Implementation: Pure PyTorch from First Principles over Pre-Packaged Libraries
Selected Approach:From-scratch PyTorch implementation of NeRF (NeRF.py)
Alternatives Evaluated:Nerfstudio, Instant-NGP bindings, PyTorch3D, Luma AI API
Engineering Rationale:

Pre-packaged NeRF frameworks abstract away ray-marching primitives, camera coordinate conversions, and volume rendering quadrature behind opaque C++/CUDA extensions. Writing from scratch guaranteed full control over memory footprint, exact algorithmic verification, educational transparency, and zero external binary dependencies.

Decision: Activation Function: Softplus for Density σ over Standard ReLU
Selected Approach:density = F.softplus(self.density_layer(h))
Alternatives Evaluated:Standard ReLU, LeakyReLU, Exponential activation
Engineering Rationale:

Mildenhall et al. originally used ReLU for density. However, standard ReLU produces exact zero gradients for inactive units, leading to 'dead rays' where empty space fails to receive optimization updates. Softplus guarantees strictly positive density (σ ≥ 0) while maintaining smooth, non-zero derivatives everywhere, dramatically stabilizing early training convergence.

Decision: Ray Sampling: Stratified Jittered Sampling over Fixed Uniform Grid
Selected Approach:z_vals = z_vals + torch.rand_like(z_vals) * delta / N during training
Alternatives Evaluated:Fixed uniform sampling, purely random sampling, importance sampling alone
Engineering Rationale:

Sampling points at identical static depth positions across iterations causes the MLP to learn discrete planar slice artifacts. Adding stratified random jitter across the ray interval acts as continuous stochastic regularization, forcing the network to represent a continuous 3D field.

Decision: Service Architecture: Asynchronous FastAPI Worker Queue over Blocking REST
Selected Approach:SQLAlchemy RenderJob model with background threading worker and polling API
Alternatives Evaluated:Synchronous blocking HTTP /render endpoint, Celery + Redis, WebSocket pipeline
Engineering Rationale:

Generating a full 60-frame 360° orbiting animation requires ~75 seconds of continuous GPU ray-marching. A synchronous HTTP request would trigger browser socket timeouts and drop connections. An asynchronous database-backed job queue with SQLite/PostgreSQL allows clients to submit requests instantly, track percentage progress, and retrieve output media durably.

05 / Evaluation

Training Diagnostics & Convergence Audit

The pipeline was evaluated across both synthetic procedural geometry and real circular photograph datasets:

Hyperparameter / MetricAudit Setting / ValueEngineering Justification
Training Iterations30,000 Gradient StepsAchieves full photometric convergence without overfitting
Ray Batch Size2,048 Rays / BatchSaturates GPU tensor cores while preserving 4GB VRAM ceiling
Samples per Ray (N)96 Samples / RayOptimal trade-off between spatial resolution and forward-pass FLOPs
Optimizer & Learning RateAdam (lr = 5e-4)Standard exponential decay stabilizing MLP weight updates
Loss FunctionPhotometric MSE LossMean squared error across sampled ray batches
Peak GPU Memory~2.1 GB VRAMLeaves 1.9 GB headroom on mobile RTX 3050 hardware
Benchmarked on Python 3.11, PyTorch 2.x, CUDA 12.x on NVIDIA GeForce RTX 3050 Laptop GPU (4GB VRAM).
06 / Cost & Latency

Compute, VRAM & Inference Benchmarks

Training Duration~35 Minutes30,000 iterations @ 300×300 px on mobile RTX 3050 GPU
Peak VRAM Utilization2.1 GB / 4.0 GBChunked ray batching prevents CUDA Out-Of-Memory crashes
360° Animation Synthesis~75 SecondsRenders 60 continuous orbiting frames into GIF / MP4
07 / Deployment

Full-Stack Web Architecture & Asynchronous Job Pipeline

The project includes a self-contained web platform allowing users to launch 3D render jobs through an intuitive browser interface:

•FastAPI REST Server (main.py): Exposes endpoints for queueing turntable render jobs (/render), polling progress (/render/status), and serving compiled static frontend assets.
•Asynchronous Worker Thread (generate_gif.py): Executes GPU ray-marching routines in a separate thread, incrementally updating job status in SQLite/PostgreSQL to prevent blocking the event loop.
•React 19 + Tailwind CSS Frontend: Modern single-page application providing real-time job status monitoring, interactive animation playback, and video download controls.
08 / Retrospective

Engineering Retrospective: What Failed, Solved & Next Steps

Failure 1: High-Frequency Blurring without Positional Encoding

Initial experiments passed raw (x, y, z) coordinates directly into the MLP without sinusoidal expansion. The network converged to a monolithic, blurry blob unable to resolve edges or texture patterns. Resolution: Implemented harmonic positional encoding with L = 10 frequency octaves for spatial positions, allowing the MLP to fit high-frequency visual features.

Failure 2: Dying ReLUs Causing Empty Render Volumes

Using standard ReLU for predicting volume density σ caused large regions of rays to receive zero gradients early in training, trapping the model in local minima where entire sections of the object disappeared. Resolution: Replaced ReLU with Softplus, guaranteeing continuous positive density and providing gradient flow across transparent regions.

Failure 3: CUDA Out-of-Memory on Full-Frame Ray Marching

Evaluating all rays for a full 300 × 300 frame simultaneously requires 90,000 × 96 = 8,640,000 points, exceeding the 4GB VRAM ceiling and crashing the CUDA driver. Resolution: Implemented chunked ray batching, splitting image frames into sub-batches of 2,048 rays during both training and novel-view synthesis.

Next Steps & Future Work

  • Incorporate Instant-NGP style multi-resolution hash encodings (Müller et al., 2022) to accelerate training from 35 minutes down to under 1 minute.
  • Implement 3D Gaussian Splatting (3DGS) rasterization as an alternative real-time rendering backend.
  • Add automated camera calibration via COLMAP integration for unconstrained casual photo collections.