Skip to main content

Adding a method

A method is a pipeline plus its training settings. If the blocks you need already exist, skip to step 6.

Some changes fit the contracts directly. Others need the kernels or the training code changed. Check which kind yours is before starting.

What a change touches
Supported by the contracts

A different alpha for each pixel, still built from a 2D position and covariance. Kernels are unchanged.

render/blocks/response/<name>.mojoWrite newImplement Response and LoadedResponse, as in the walkthrough below.
render/pipelines.mojoEditAdd a struct with a new ID, or add the pipeline struct next to your test.
tests/render/test_block_gradients.mojoEditFinite-difference check of every backward. A generic block that nothing instantiates is not even compiled.
Your programEditTrainer[MyPipeline](...) or rast.forward[MyPipeline](...). tools/train and tools/eval pick one through --method, which needs a Method that names it.
render/preprocess.mojo, blend*.mojo, instances.mojoNo changeUnchanged; they are instantiated with your block.
Select a change. Everything here reflects the current code; none of it is a plan.

Walkthrough: a new footprint​

Suppose you want a footprint with its own per-Gaussian parameter, say a Beta-kernel falloff with a learned exponent b. This walkthrough uses a simplified version of it; the full block is BetaFootprint in render/blocks/response/beta.mojo, used by the beta-splatting method. The smallest working example to copy from is ScaledGaussian in tests/render/test_pipeline_seams.mojo: a Gaussian2D with alpha scaled by a value from its own column, tested from the column through blend and back to the column's gradient.

1. Decide where each value lives​

WhatWhereLimit
Position, shape, opacity for the tile test and blendThe record, your six floats6 floats
A per-Gaussian value blend needs (here b)Its own Splats column, copied per slot into EXTRA16 floats, in a separate array
Values each lane needs per pixelThe slab, sized by SLABIn shared memory, per lane
What the backward sums per slotGRAD lanes returned by gradient16 lanes

2. Write the two structs​

render/blocks/response/<name>.mojo holds both. Start with the constants:

struct MyFootprint(ImplicitlyCopyable, Movable, Response):
comptime Loaded = LoadedMyFootprint
comptime TILE_ARGS = 6 # lanes of tile_args in use
comptime SLAB = 12 # floats per Gaussian in the blend slab
comptime GRAD = 7 # Gaussian2D's 6, plus one for b
comptime EXTRA = 1 # b, copied per slot
comptime NUM_COLUMNS = 1
comptime MIN_OPACITY = MIN_ALPHA
comptime STOP_BEFORE_LAST = False

Response is what preprocess builds from the projected 2D Gaussian (it also gets the Gaussian in world space and the camera, for responses evaluated along rays). LoadedResponse is what the two blend kernels evaluate at pixels, built from the slab or the record. Its eval returns a Hit: lane 0 is alpha, and the other seven lanes belong to the block. The backward kernel passes that Hit back to add, so a block needs no hidden per-pixel state.

Then the methods. Each exists because a specific kernel calls it:

You writeCalled fromPurpose
__init__(mean2d, cov2d, geom, cam), valid, extent, record, tile_args, touches_tilepreprocess, instancesForward, culling, the tile test
extra(opacity, cols, g)preprocessRead your column and return b for this slot
store_slab, channel, skip_fragmentblendLay out the slab
Loaded(src), Loaded(), Loaded(rec, extra)blend, blend backwardUnpack from slab or record
eval, add, gradientblend, blend backwardPixel value, gradient sums
backward, opacity_gradientpreprocess backwardBack to the mean and shape, and the opacity logit
densificationpreprocess backwardThe densification statistic of one view
write_gradients, zero_gradients, grad_indexpreprocess backwardWrite the column's gradient; slot layout
columns()TrainerDeclare your column as a ColumnSpec with its initial value and learning rate
note

A footprint evaluated in 2D computes a ScreenGrad, the gradients with respect to the screen position and the 2D covariance, and returns through_placement(screen, place, shape, cam) from backward: Placement.backward takes it to the mean and shape, and the screen-position gradient becomes 3DGS's densification statistic. A response evaluated along rays (GaussianRay3D, 3DGUT) computes the 3D gradient itself and defines its own statistic.

3. Name it in a pipeline​

struct MyPipeline(Pipeline):
comptime ID = 1
comptime TILE_H = DEFAULT_TILE_H # tiles are 16 wide; 3DGUT uses 16 x 16
comptime Place = PinholeEWA[DType.float32]
comptime Resp = MyFootprint
comptime Appear = SphericalHarmonics

ID must differ from other pipelines: it is how Rasterizer.backward detects a state from another pipeline's forward.

4. Test it​

Add the block to tests/render/test_block_gradients.mojo, which checks each backward against finite differences, one output at a time. Mojo only checks a generic function when something instantiates it, so an unused block may not compile at all. Tests in test_pipeline_seams.mojo show the two checks worth copying: that the extra column really reaches the image, and that its gradient reaches the column.

5. Use it from your own program​

Name it where a program picks a pipeline:

var trainer = Trainer[MyPipeline](ctx, ds^, config) # training
rast.render[MyPipeline](splats.view(), camera, background, image, sh_degree)

Trainer then handles the rest: it adds your column from columns(), gives it the learning rate in its ColumnSpec, and Splats.gather keeps it through densification. The column saves in PLY as extra_<name>_<i> properties.

6. Make it a method​

A Method in mojosplat/methods/ gives the pipeline a name, a densification strategy and its settings. The settings are a struct of the method's own: the shared TrainConfig, the strategy's config, and any settings only this method has. Every field becomes a command-line option, so a method shows only the options it uses. A method that starts differently from 3DGS also returns an InitConfig from initialization(), as MCMCConfig (random points) and ThreeDGUTConfig (camera distance scales, random rotations) do, and one with other schedules returns a ScheduleConfig from schedules(), as SphericalVoronoiConfig (only the colors train at the end) and ThreeDGUTConfig (schedules advance after the optimizer step) do.

struct MyMethodConfig(MethodConfig):
comptime Strategy = ClassicDensification

@__annotation(Arg("Training"))
var train: TrainConfig

@__annotation(Arg("Densification"))
var densify: DensifyConfig

def __init__(out self):
self.train = TrainConfig()
self.train.initial_opacity = 0.5
self.densify = DensifyConfig()

def training(self) -> TrainConfig:
return self.train.copy()

def densification(self) -> DensifyConfig:
return self.densify.copy()


struct MyMethod(Method):
comptime Pipe = MyPipeline
comptime Config = MyMethodConfig

@staticmethod
def name() -> String:
return "my-method"

@staticmethod
def config(scene: String) -> MyMethodConfig:
return MyMethodConfig()

config receives the scene's directory name, for settings that differ per scene. Export the struct from methods/__init__.mojo and add a branch for it in main in tools/train.mojo and tools/eval.mojo. Then run it:

pixi run train path/to/scene --method my-method

Flags on the command line override the method's settings, and pixi run train --method my-method --help lists them. Each run writes run.json next to the model, with the method, scene, MojoSplat commit (and whether it had uncommitted changes), GPU, resolved settings and results.

In a repository of your own​

The whole train and eval programs are library functions, train[M] and evaluate[M] in mojosplat.apps. A paper can live in its own repository that uses MojoSplat, with a main of a few lines:

from mojosplat.apps import train

def main() raises:
train[MyMethod]()

Blocks, strategies and methods defined there work the same as the ones in MojoSplat.

Limits at a glance​

LimitWhere
Splats always creates sh0 and sh_rest, as columns 4 and 5model/splats.mojo, constructor and Attr
Six extra column pointers in kernels; two are taken by SHcore/splats.mojo, NUM_EXTRA_COLUMNS
At most 16 columns for Adamtrain/adam.mojo
Record is 32 bytes: 6 floats plus the rectanglerender/record.mojo, REC
Up to 16 extra per-slot floats and 16 gradient lanesExtra and SlotGrad in the contract
Tiles are 16 pixels wide; a pipeline sets their heightPipeline.TILE_H
Blending is three channelsrender/rasterizer.mojo CDIM, render/blend.mojo assert
Placement.depth is also the sort key, so it must order Gaussians front to backrender/blocks/contracts.mojo
Shape is always QuatScalerender/blocks/contracts.mojo, kernels
tools/train and tools/eval get their method from --method, from the methods registered in their maintools/train.mojo, tools/eval.mojo
The viewer, tools/render and tools/bench always use Standard3DGSViewer, tools/render, tools/bench

Data and state explains why the record and the slab are laid out as they are, and the design document in the repository lists the portability rules that apply to code running in a kernel.