Skip to content

Image understanding, generation, and 3D reconstruction · Monocular depth and dense prediction · VIS016 · Architecture

Dense Prediction Transformer (DPT)

DPT adapts transformer representations to dense prediction by reassembling tokens into spatial feature maps and fusing information across depths. It supports monocular depth and semantic segmentation;

Explained here Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

Documented in the Academy only. There's no Set up button.

Availability
Explained here
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

DPT adapts transformer representations to dense prediction by reassembling tokens into spatial feature maps and fusing information across depths. It supports monocular depth and semantic segmentation; it is an architecture, whereas MiDaS separately describes a mixed-dataset depth-learning approach that can use a DPT backbone.

Question / hypotheses

Can reassembled transformer features support accurate spatially aligned depth or semantic predictions? This is a modeling/evaluation question, not a formal null-hypothesis test.

Architecture / computational structure

A transformer or hybrid backbone supplies features from multiple layers. Reassembly operations project token channels, restore spatial layout and resample to a multiscale hierarchy. Convolutional fusion blocks progressively combine scales before a task-specific dense head.

Assumptions

Token order must map correctly to image coordinates. Monocular depth remains ambiguous without metric supervision or calibration; a dense architecture alone does not establish physical depth scale. Training-image content, aspect ratio and camera intrinsics can shift predictions.

Formula / computational definition

Fl=Resample⁡l(Reshape⁡(TlWl))F_l=\operatorname{Resample}_l(\operatorname{Reshape}(T_lW_l)) and Ul=Fuse⁡l(Fl,Upsample⁡(Ul+1))U_l=\operatorname{Fuse}_l(F_l,\operatorname{Upsample}(U_{l+1})). The output head maps fused features to depth/disparity or class logits; the loss depends on the chosen target and training protocol.

Parameters and notation

Notation: Here T_l is a selected transformer token matrix, W_l its channel projection, F_l a reassembled/resampled spatial feature map and U_l a fusion state. Reshape requires the patch-grid dimensions and correct token order; the classification/readout token is handled separately.

Learned or estimated: Backbone attention/feedforward parameters, token projections/readout handling, fusion convolutions and the dense output head.

Hyperparameters and effects: Backbone, selected layers, patch size, resampling scales, feature width, output convention and task loss. A finer patch grid improves localization at higher cost; positional embeddings and resolution changes require the implementation’s prescribed handling.

Fitting, fine-tuning, and adaptation

For a new dense task, fit reassembly/fusion/head layers with the backbone frozen, then unfreeze later transformer blocks at smaller rates. Use an appropriate pixel-level loss and target-unit convention; do not transfer depth-head interpretations blindly between checkpoints. Validate source-task retention, boundary behavior and resolution changes.

How to use and calibrate

Split by independent image source, scene, subject or capture sequence before augmentation; keep near-duplicate frames and crops in the same split. Measure depth error under explicitly declared metric or scale-aligned protocols, or class IoU for segmentation. Report spatial artifacts, latency/memory and comparisons at matched backbone pretraining and input size.

Example application

Predict a dense relative-depth map from a single image with transformer features. This is a proposed use case, not a claim of validated performance on supplied real data.

Interpretation / pitfalls

Watch out

A training loss, confidence score or attention map is not a p-value or causal explanation. Confidence calibration, annotation quality and distribution-shift performance need separate assessment. A correct component calculation does not validate the full architecture, checkpoint or deployment pipeline.

Python and R code examples

Scope: DPT token reassembly into a spatial grid and fusion with a coarser feature map; readout-token handling, convolutions and the transformer are omitted. Use the shared setup. Dependencies: NumPy / base R. Validation: Python executed; R unexecuted.

Full-model route: Python: official DPT implementation. R: native torch reassembly/fusion components or bridge. The example verifies token-to-grid reconstruction and cross-scale fusion, not pretrained depth inference.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — DPT token reassembly into a spatial grid and fusion with a coarser feature map; readout-token handling, convolutions and the transformer are omitted. Use the shared setup.

Shared setup for this chapter
import numpy as np
from itertools import permutations
def softmax(x):
    x=np.asarray(x,dtype=float)
    e=np.exp(x-x.max(axis=-1,keepdims=True))
    return e/e.sum(axis=-1,keepdims=True)
def bilinear(a,y,x):
    y=float(np.clip(y,0,a.shape[0]-1)); x=float(np.clip(x,0,a.shape[1]-1))
    y0=int(np.floor(y)); x0=int(np.floor(x))
    y1=min(y0+1,a.shape[0]-1); x1=min(x0+1,a.shape[1]-1)
    dy=y-y0; dx=x-x0
    return (1-dy)*((1-dx)*a[y0,x0]+dx*a[y0,x1])+dy*((1-dx)*a[y1,x0]+dx*a[y1,x1])
tokens=np.arange(12,dtype=float).reshape(4,3)/10 # row-major 2x2 grid
projection=np.array([.2,.3,.5])
grid=(tokens@projection).reshape(2,2)
coarse=np.array([[.4]])
up=np.repeat(np.repeat(coarse,2,axis=0),2,axis=1)
fused=np.maximum(grid+up,0)
assert np.isclose(grid[1,0],tokens[2]@projection) and fused.shape==(2,2)
print('reassembled:',grid,'fused:',fused)
R

Component demo, not a trained model — DPT token reassembly into a spatial grid and fusion with a coarser feature map; readout-token handling, convolutions and the transformer are omitted. Use the shared setup.

Shared setup for this chapter
softmax <- function(x) {
  if(is.null(dim(x))) {e<-exp(x-max(x)); return(e/sum(e))}
  t(apply(x,1,function(v) {e<-exp(v-max(v)); e/sum(e)}))
}
bilinear <- function(a,y,x) {
  y<-min(max(y,0),nrow(a)-1); x<-min(max(x,0),ncol(a)-1)
  y0<-floor(y); x0<-floor(x); y1<-min(y0+1,nrow(a)-1); x1<-min(x0+1,ncol(a)-1)
  dy<-y-y0; dx<-x-x0
  (1-dy)*((1-dx)*a[y0+1,x0+1]+dx*a[y0+1,x1+1])+dy*((1-dx)*a[y1+1,x0+1]+dx*a[y1+1,x1+1])
}
tokens<-matrix(0:11,4,byrow=TRUE)/10 # row-major 2x2 grid
projection<-c(.2,.3,.5)
grid<-matrix(as.vector(tokens%*%projection),2,byrow=TRUE)
coarse<-matrix(.4,1,1); up<-coarse[rep(1,2),rep(1,2)]
fused<-pmax(grid+up,0)
stopifnot(abs(grid[2,1]-sum(tokens[3,]*projection))<1e-12,all(dim(fused)==c(2,2)))
print(list(reassembled=grid,fused=fused))

Sources

From the CodeSplash reference, entry VIS016.