AI Architectures

U-Net

The shape that learned to label every pixel — born in cell microscopy, later adapted for segmentation and diffusion denoising.

Prerequisites: A convolution slides a filter over an image + Pooling shrinks a feature map. That’s it.
10
Chapters
9+
Simulations
0
Assumed Knowledge

Chapter 0: A Label for Every Pixel

A normal image classifier answers one question about a whole image: “cat or dog?” One label for millions of pixels. But a huge class of problems needs something far more demanding: a label for every single pixel. Which pixels are tumor and which are healthy tissue? Which pixels are road, car, pedestrian, sky? This is semantic segmentation, and it's where U-Net was born — in 2015, for segmenting cells in biomedical microscopy images.

A classifier's final head usually reduces spatial features to one prediction. That output cannot tell you which pixels belong to a cell. Its convolutional features can still be useful: replace the classification head with a dense-prediction decoder, train against pixel labels, and you have the beginnings of a segmenter.

Segmentation needs both context (the surrounding evidence that distinguishes a cell from an artifact) and spatial precision (the exact boundary). U-Net builds features at several resolutions, then combines the broad view with detailed features from earlier layers. Downsampling is an efficient way to gather context, but dilated convolutions, deeper full-resolution stacks, and attention are other routes.

The one-sentence version. U-Net contracts to gather context, expands to make a dense prediction, and carries encoder features directly across to matching decoder stages. Those skip connections give the decoder access to detail that may be difficult to preserve through the deepest path.

What the output looks like

A segmenter produces class scores at many spatial positions. For binary segmentation, a one-channel logit map can become foreground probabilities through a sigmoid, then a binary mask through a threshold. A multi-class model commonly uses one channel per class and a per-pixel softmax. A same-padding U-Net can produce an output the same size as its input; the original architecture predicted a smaller central region, as Chapter 4 explains. Dense output alone does not require a U-shaped architecture.

See it: classifier vs. segmenter

The widget shows the same input two ways. A classifier pools the image down to a single label — watch the spatial grid collapse to one box. A segmenter must instead produce a full per-pixel mask — every cell gets its own prediction. Toggle to compare the output tasks; the underlying feature extractor can be adapted.

One Label vs. A Label Per Pixel

A classification head gives one label. A segmentation head gives a label at each output location. Toggle to see the fundamentally different output shapes.

Common misconception. “A wide view requires pooling.” For a fixed shallow stack of small filters, removing downsampling reduces the receptive field. But downsampling is not mathematically required for context: dilation, larger filters, more layers, or attention can also enlarge it. U-Net offers a practical balance of context, compute, and localization.
Why can't a standard image classifier be directly used for pixel-level segmentation?

Chapter 1: The Encoder–Decoder — Down, Then Up

The first half of U-Net's idea is the encoder–decoder shape. It has two paths. The encoder (or contracting path) progressively shrinks the image — convolve, then downsample, again and again — squeezing a big detailed picture into a small stack of abstract features. The decoder (or expanding path) reverses the change in spatial scale — upsample, then convolve — growing those abstract features back into a dense output. Upsampling is not an inverse of the encoder.

Why go down first

Downsampling reduces the number of spatial locations processed by later layers. It also increases the spacing, measured in input pixels, between neighboring features. Subsequent convolutions therefore gather context over a larger input region. For example, a 3×3 convolution increases the receptive-field width by 2 pixels at stride 1, but by 8 input pixels after two factor-of-two reductions. This is efficient receptive-field growth, not a guarantee that learned features understand an object.

Resolution down, channels up. This lesson uses an illustrative same-padding design: 256×256×64 features become 128×128×128, then 64×64×256, 32×32×512, and 16×16×1024. Convolutions choose the channel counts; pooling itself does not add channels. The wider channel dimension can retain information even as spatial resolution shrinks.

Why go up after

The decoder reverses the journey. It takes the small, semantically-rich feature map at the bottom and progressively upsamples it — doubling the spatial size each step, applying convolutions to refine — until it reaches the desired output resolution. Now the output can carry a prediction at each desired location; same-padding variants can match the input size. The encoder built up meaning by shrinking; the decoder rebuilds spatial precision by growing. Together they form the two strokes of the letter U — down the left side, up the right.

The data flow, traced

input
256×256, 3 ch
↓ encode
128×128, 128ch
conv + downsample
↓
bottleneck
16×16, 1024ch — lowest spatial resolution
↑ decode
128×128, 128ch
upsample + conv
↑
output
256×256 mask

For a stride-1 3×3 convolution, padding 1 preserves size; padding 0 removes one pixel at each border. The Conv2d shape formula makes this explicit.

See it: the resolution pyramid

The widget shows feature-map sizes through a plain encoder–decoder. Step through: watch the spatial size halve on the way down (and channels grow), reach the tiny bottleneck, then double back up to full resolution. This down-then-up profile is the skeleton of U-Net — the next chapter examines why a narrow deep path can make boundary reconstruction harder.

The Encoder–Decoder Resolution Pyramid

Each block is a feature map; width = spatial size, color intensity = channel richness. Step down (shrink, enrich) to the bottleneck, then up (grow) back to full size.

Stage (encode, then decode) 4

Common misconception. “The decoder exactly undoes the encoder.” Both paths form one network trained end-to-end, but learned upsampling is not mathematical inversion. Skip features must have matching spatial dimensions when concatenated; this can require cropping or padding, particularly in the original valid-convolution architecture.
What does downsampling in the encoder accomplish beyond making feature maps smaller?

Chapter 2: The Blur — What a Bottleneck Can Lose

A decoder without long skips receives its information through the deepest feature map. If the encoder has discarded boundary details, enlarging that map cannot recover those details uniquely. Predictions may then miss thin structures or localize boundaries poorly. This is a motivation for U-Net skips, not a theorem that every plain encoder–decoder must blur.

What pooling actually loses

Take two 2×2 patches: one has a bright top-left pixel; the other has a bright bottom-right pixel. Both have maximum 1 and average 0.25. Max pooling or average pooling on that single channel cannot distinguish them. These operations are non-injective: different inputs can produce the same output. A decoder given only that pooled value cannot know which patch it came from.

Count channels as well as spatial positions. A 16×16×1024 tensor contains 262,144 values. Its 256 spatial positions alone do not prove it cannot carry detail from a 256×256 image. Learned features can encode spatial relationships in channels before downsampling. The practical question is which information this encoder preserves, not whether a small spatial grid is automatically incapable of localization.

The tension, made sharp

The encoder develops a broad view, while the decoder needs local evidence. Long skips provide a direct route for earlier, higher-resolution features, reducing reliance on the deepest representation. Those features are learned responses, not a separate set of perfect edge labels. A trained decoder must learn how to use both streams.

See it: reconstruction from the bottleneck alone

The widget performs a specific, deliberately simple operation: average a 24×24 synthetic mask into a smaller grid, then bilinearly resize it. Smaller grids retain less of this mask’s detail. This demonstrates information loss and interpolation, not the output of a trained encoder–decoder.

Toy Pool-and-Resize Reconstruction

Left: synthetic binary mask. Right: average pooling followed by bilinear resizing. No network is trained or run in this demonstration.

Bottleneck size (smaller = more pooling) 6

Common misconception. “Skips are the only way to preserve detail.” More channels, a larger bottleneck, alternative downsampling operators, and different architectures can help. Each changes memory, compute, or learning behavior. U-Net makes higher-resolution features directly available instead of asking the deepest path to carry every useful signal.
Why can the toy pooled mask fail to reconstruct a sharp boundary?

Chapter 3: Skip Connections — The One Big Idea

U-Net gives the decoder a second source of information: feature maps saved from the encoder before each downsampling stage. It copies those maps across to the corresponding decoder stage and fuses them with upsampled deeper features. These long skip connections are the cross-bars of the U. They help localization by making local evidence accessible; they do not guarantee a perfect boundary.

How a skip connection works

At each level of the decoder, just before refining, you have two feature maps at the same spatial size: the upsampled one coming up from below (rich in context, but coarse), and the copied one skipping across from the matching encoder level (rich in fine detail, high-resolution). U-Net concatenates them — stacks them along the channel dimension — then runs convolutions over the combined stack. Now the decoder's refinement step can use both the high-level meaning and the precise spatial detail at once. Context from below, detail from the side, fused.

Context from below, detail from the side. Deep features typically have larger receptive fields; shallow features typically retain finer spatial structure. Both can contain semantic and spatial information. The useful distinction is their scale and route through the network, not a strict division in which one stream knows only “what” and the other only “where.”

Worked example: concatenation

At decoder level 2, suppose the upsampled feature map from below is 128×128 with 256 channels (carrying context), and the encoder's level-2 feature map — copied across the skip — is also 128×128 but with 128 channels (carrying fine detail). Concatenating along channels gives a 128×128 map with 256 + 128 = 384 channels. The next convolution sees all 384 channels together, so a single output pixel can be computed from both the “this region is a cell” signal and the “the edge is exactly here” signal. The spatial dimensions must match for concatenation to work — so implementations explicitly align the grids by design, cropping, or padding.

From scratch: the skip in code

python
# Schematic: NCHW tensors; same-padding blocks and matching spatial sizes.
def unet_forward(x):
    # encoder — SAVE each feature map before downsampling
    e1 = enc_block1(x);        s1 = e1;  e1 = down(e1)   # save s1 (high-res)
    e2 = enc_block2(e1);       s2 = e2;  e2 = down(e2)   # save s2
    b  = bottleneck(e2)                                  # deepest, lowest-res
    # decoder — CONCATENATE the saved skip at each level
    d2 = up(b)
    d2 = dec_block2(torch.cat([d2, s2], dim=1))   # ← skip: context + detail
    d1 = up(d2)
    d1 = dec_block1(torch.cat([d1, s1], dim=1))   # ← skip again
    return final_conv(d1)                            # per-pixel logits; apply sigmoid/softmax afterward

The whole U-Net difference is those two torch.cat([..., s], dim=1) calls. The encoder saves its feature maps (s1, s2) before downsampling; the decoder concatenates them back in at the matching resolution. Without those lines you have a plain encoder–decoder with no long skips. With them, you have U-Net.

See it: skip on vs. off

This toy comparison starts with the same synthetic mask as Chapter 2. The no-skip view shows pooling plus interpolation. The skip-on view directly copies the original mask to illustrate access to a high-resolution route. A real U-Net concatenates learned features and learns a decoder; it does not copy the ground-truth mask or become accurate just because a switch is enabled.

Skip Connections: Off vs. On

Left: synthetic mask. Right: a scripted comparison of coarse reconstruction and direct detail access. The perfect copy is illustrative, not measured model performance.

Concatenation versus addition. A classic U-Net skip concatenates along channels: 256 channels plus 128 channels gives 384. An additive residual skip adds aligned tensors elementwise and keeps the channel count; a projection can align channels first. These describe operations, not exclusive model families: modern U-Nets can also contain residual blocks and other skip designs.
What does a classic U-Net skip contribute to the decoder?

Chapter 4: The Full U — Watch It Flow

Trace an illustrative same-padding U-Net: input at top-left, contracting encoder, bottleneck, expanding decoder, and prediction at top-right. The horizontal rungs carry encoder features to matching decoder scales. The two bottom boxes depict the entrance and exit of one bottleneck stage, not two separately skipped stages. Channel counts and exact operator choices remain implementation decisions.

Press Run to trace the deep path, then toggle the skips. The output thumbnails are schematic indicators of detail access, not network predictions or evidence of an accuracy improvement. The architectural question is whether each decoder stage can use both its deeper input and the corresponding encoder features.

Live U-Net Data Flow

Down the encoder, across the bottleneck, up the decoder. Skip connections (rungs) carry detail across. The flow and output thumbnails illustrate routing; no model inference is performed.

The original U-Net used valid convolutions. In the 2015 paper, Figure 1, two unpadded 3×3 convolutions per block shrink the grid. A 572×572 input gives a 388×388 output, with encoder skips cropped before concatenation. A final 1×1 convolution maps features to class scores. The 256×256 diagrams in this lesson instead assume same padding. Keep those conventions separate when implementing or tracing shapes.
Depth is a design choice. More downsampling stages can gather wider context at coarser resolution, but change compute, memory, and the handling of small structures. Choose depth and patch size for the image scale and task, then validate the result. More levels are not automatically better, and diffusion backbones need not retain this U-shaped architecture.

No quiz — trace both routes into a decoder block, explain what concatenation changes, and distinguish this same-padding diagram from the original cropped-skip design.

Chapter 5: Upsampling — How the Decoder Grows

We've talked about the decoder “upsampling” — growing a small feature map back to a larger one. But how do you actually add spatial resolution? You're conjuring more pixels than you started with, so something must fill in the gaps. There are two main approaches, and the choice has real consequences for the output's quality.

Method 1: interpolation + convolution

The simple approach: blow the feature map up with plain image resizing — nearest-neighbor (copy each value into a 2×2 block) or bilinear (smoothly interpolate between values) — then run a normal convolution to refine. The resize adds the resolution (dumbly), and the convolution learns to refine the resized features. It is a common alternative to learned strided upsampling.

Method 2: transposed convolution

A transposed convolution applies the transpose of the matrix describing a convolutional linear map. Operationally, each input value contributes a learned kernel to the output; overlapping contributions are summed. With stride greater than 1 it can increase spatial size. It is sometimes called “deconvolution,” but it is not generally an inverse that reconstructs the original signal. See the PyTorch operator definition.

Uneven overlap is a risk. With dilation 1, a kernel size not divisible by the stride can cover neighboring output positions different numbers of times. This can create periodic patterns, especially with repeated layers. Learned weights can reduce or amplify the pattern, and even-overlap kernels can still learn artifacts. Resize followed by convolution reduces this particular risk, but is not a guarantee against every artifact. Distill’s analysis explains the distinction.

Worked example: why the checkerboard appears

For a one-dimensional all-ones input and all-ones kernel of size 3, stride 2, interior overlap counts alternate between 1 and 2. In two dimensions those counts multiply: interior positions receive 1, 2, or 4 contributions. This is a concrete arithmetic example, not a universal brightness rule for learned filters. Size 4, stride 2 removes this interior count imbalance; output boundaries still have fewer contributions.

See it: interpolation and overlap

The first two modes resize a 4×4 feature map to 16×16 using nearest-neighbor or bilinear interpolation. The other two compute actual all-ones transposed-convolution overlap counts at stride 2, with kernel size 4 or 3. They isolate coverage, not learned image quality. Border effects remain visible in both count maps.

Upsampling Methods Compared

Nearest and bilinear resize a varying source map. The transposed-convolution modes use all-ones inputs and filters to show exact contribution counts, with kernel size 4 or 3 and stride 2.

More positions do not mean recovered information. Upsampling enlarges the grid; learned refinement determines its useful content. For dilation 1, the transposed-convolution size is (input size − 1) × stride − 2 × padding + kernel size + output padding. Thus a 4×4 input with stride 2, no padding, and kernel 3 produces 9×9, while kernel 4 produces 10×10. The overlap modes show those exact sizes.
Which mechanism can cause checkerboard artifacts in transposed-convolution upsampling?

Chapter 6: Training a U-Net — The Loss Matters

A U-Net outputs a per-pixel prediction, so the obvious loss is per-pixel cross-entropy: classify each pixel (tumor or not) and average the loss over all pixels. It works — but in segmentation there's a vicious trap that makes this loss alone dangerous: class imbalance.

The imbalance trap

A foreground region might occupy 2% of the pixels. Predicting background everywhere then gives 98% pixel accuracy while missing the whole region. This does not imply low cross-entropy: CE uses probabilities, and a confident false negative has a large penalty. Averaging over many background pixels can make class balance matter, but accuracy and CE are different quantities.

Accuracy can hide the error you care about. In a 100-pixel image with four foreground pixels, an all-background mask is 96% accurate. To judge localization, inspect class-wise overlap and boundary errors as well. No single metric describes every failure, and a segmentation metric alone does not establish clinical usefulness.

Measuring overlap: Dice

For a binary foreground mask, Dice is twice the intersection divided by the sum of predicted and true foreground sizes: 2TP / (2TP + FP + FN). It ignores true negatives, but false-positive foreground predictions increase the denominator and reduce the score. When the true foreground is nonempty, an all-background prediction scores 0. If both masks are empty, the ratio is 0/0; implementations must specify an empty-mask convention or smoothing.

Worked example: scores versus losses

For the 100-pixel example, an empty predicted foreground has Dice 0 and pixel accuracy 96%. If the model assigns foreground probability 0.01 everywhere, mean binary CE is −[0.04 log(0.01) + 0.96 log(0.99)] ≈ 0.194. Decreasing that probability toward zero makes the missed foreground more confidently wrong and increases its penalty. For training, a soft Dice loss replaces hard masks with probabilities; its smoothing and reduction across images/classes must be chosen explicitly. Combining CE and soft Dice is one common option, not a guarantee of good segmentation.

See it: accuracy vs. Dice as the tumor shrinks

A model that always predicts “background.” Shrink the true tumor and watch pixel accuracy soar toward 100% (it's right about all the background) while Dice stays pinned at 0 (it never overlaps the tumor). The gap between the two is the imbalance trap made visible — and the reason accuracy should not be the only evaluation metric. Accuracy is also not a differentiable training objective.

Pixel Accuracy vs. Dice (a do-nothing model)

The model predicts all-background. As the tumor shrinks, pixel accuracy climbs toward 100% while Dice stays at 0 — revealing why accuracy is a dangerous metric for imbalanced segmentation.

Tumor size (% of image) 8%

The original training recipe was weighted cross-entropy. U-Net’s 2015 paper used per-pixel softmax and cross-entropy with weights for class frequency and the separating borders between touching cells. Strong augmentation, especially elastic deformations, helped use limited annotations. Dice-based training appeared in later segmentation work such as V-Net; it was not the original U-Net loss.
What does foreground Dice reveal that pixel accuracy can hide?

Chapter 7: U-Net as the Diffusion Backbone

U-Net became an important backbone beyond segmentation. The DDPM paper used a U-Net-like network to model denoising, while latent diffusion adapted this idea to compressed image representations. The transferable feature is multiscale, spatially aligned prediction. Diffusion is a process; U-Net is one possible neural architecture inside it.

What diffusion asks the network to do

In the noise-prediction parameterization, training constructs xt = √ᾱt x0 + √(1 − ᾱt) ε, where ε is sampled Gaussian noise and ᾱt sets the signal level. The network estimates ε from xt, timestep t, and any conditioning. The sampler then uses that prediction with schedule-dependent coefficients, and sometimes fresh noise, to produce the next state. It does not simply subtract the raw prediction. Other parameterizations predict the clean sample x0 or a velocity-like target v.

Match the prediction grid, not necessarily RGB. A denoiser needs both local and wider-scale evidence. U-Net provides those through its contracting path, expanding path, and skips. In pixel diffusion, the denoiser works on image-space tensors. In latent diffusion, it works on a lower-resolution latent grid; a separate autoencoder decoder maps the final latent to RGB. Skips provide features from the noisy input, not hidden access to the clean answer.

Two additions: time and text

Time conditioning tells the denoiser the current noise level, often through an embedding injected into residual blocks. A text-conditioned latent diffusion model can also use cross-attention: spatial features query an encoded prompt. Conditioning can instead be class labels, another image, or be absent. Exact block layouts vary; time and text do not make every diffusion architecture an unchanged segmentation U-Net.

The bridge to DiT

The DiT paper explored transformers over patches of a latent representation as an alternative diffusion backbone. Its experiments studied scaling model size and compute. This shows that denoising does not require a convolutional U-shaped hierarchy. U-Nets, transformers, and hybrids are design choices; no architecture is a universal successor or winner for every task.

See it: denoising with a U-Net

The widget is a visual analogy for noise giving way to structure. It linearly blends a fixed random grid with a known synthetic target over eight steps. It runs no denoising network, has no diffusion noise schedule, and does not demonstrate generation quality. Use it to picture repeated refinement while keeping the actual training target and sampler distinct.

Noise-to-Structure Illustration (scripted blend)

A known target fades into a fixed random grid. This eight-step blend illustrates a visual idea; it is not U-Net inference or a diffusion sampler.

Keep three choices separate. The architecture computes a prediction; the parameterization determines whether that prediction represents noise, a clean sample, or another target; the sampler converts it into a state update. A U-Net does not specify the whole diffusion algorithm, and a diffusion algorithm does not require a U-Net.
Why is U-Net a natural fit for the noise-prediction step in diffusion models?

Chapter 8: The U-Net Family

U-Net's skeleton — contract, bottleneck, expand, with skip connections — turned out to be so good that it spawned a whole family of variants, each adapting the template to a new domain or fixing a limitation. Knowing them shows just how general the core idea is.

The major variants

A family resemblance, not an identical blueprint. These models share multiscale encoding, decoding, and routes that fuse features across stages. They can differ in padding, normalization, channel counts, downsampling, attention, and loss. An architecture name alone does not determine the preprocessing or training recipe that makes it work.

See it: what each variant changes

Select a variant to highlight its main architectural emphasis. The transformer view marks a hybrid encoder stage rather than claiming that all blocks become transformers. These are schematic comparisons; consult each paper for its full implementation.

One Skeleton, Many Variants

Pick a variant; the modified part of the U lights up. The contract–bottleneck–expand shape with skips is shared by all of them.

Validate the full pipeline. A more elaborate architecture is not automatically better. nnU-Net demonstrates the importance of data preprocessing, patch selection, augmentation, training, and inference configuration. Compare candidates with the same dataset split and relevant metrics; reported benchmark wins do not establish a universal ranking.
What broad design idea connects the U-Net family?

Chapter 9: Connections & Cheat Sheet

U-Net makes a practical bet: dense prediction benefits from combining features computed at several spatial scales. The deep route gathers context; long skips make earlier features available to the decoder. That is a useful template for segmentation and denoising, with performance determined by data, representation, optimization, and implementation details as well as the diagram.

The cheat sheet

Shape:  contracting encoder → bottleneck → expanding decoder (the letter U)
Encoder:  conv + downsample; resolution ↓, channels ↑, receptive field ↑ (context)
Decoder:  upsample + conv; resolution ↑ back to full size (precision)
The blur problem:  pooling can lose detail; spatial size alone does not prove information loss
Skip connections:  concatenate encoder feature maps into the decoder at matching resolution
Upsampling:  resize+conv or transposed conv; inspect overlap, boundaries, and learned artifacts
Training:  original: weighted cross-entropy; later options include soft Dice + CE; evaluate class-wise
Beyond segmentation:  a possible diffusion denoiser; predictions may live on pixel or latent grids

A decision guide

Need a dense spatial output?
Consider U-Net for segmentation, denoising, depth, or image translation.
↓
Boundaries coming out blurry?
Check labels, alignment, input resolution, loss, decoder, and skip features.
↓
Small/imbalanced target (medical)?
Compare foreground overlap, false positives, and false negatives; validate the training recipe.
↓
Seeing checkerboard artifacts?
Inspect overlap and learned filters; compare resize + convolution under the same conditions.

Where this connects

The one thing to remember. U-Net answers a question every dense-prediction task asks: how do I produce a sharp, full-resolution output while still understanding the big picture? Its answer — go down for context, up for resolution, and carry the fine detail across on skip connections — proved useful beyond its origin in cell microscopy, including in diffusion denoisers. The U is one of the most reused shapes in all of deep learning.
You're building a model that takes a photo and outputs a same-size depth map (a value per pixel). What architecture and what to watch for?

“To see clearly, you must first step back to take in the whole — then return to attend to every detail.” That round trip, with memory carried across, is the U.