Simple Algorithm
Deep Learning · Emergence · 26 min

Conditional GANs & Image-to-Image Translation

pix2pix, CycleGAN and turning one kind of image into another.

Turn a sketch into a shoe, a map into a satellite photo, a summer landscape into winter, a horse into a zebra. Each is a generative model conditioned on an entire image, and each raises the same two questions: how does the condition enter the networks, and what forces the output to stay faithful to the input rather than merely look real?

What you’ll learn

  • Explain how conditional GANs inject a label, and derive the projection discriminator's form from a log-linear model of class posteriors.
  • Derive why pixelwise L1 and L2 losses blur, and explain pix2pix's combination of L1, a U-Net generator and a PatchGAN discriminator.
  • Explain CycleGAN's cycle-consistency loss, why it under-determines the mapping, and how a generator can satisfy it by hiding information.
  • Describe SPADE, perceptual losses for super-resolution, the perception–distortion trade-off, and the diffusion-era successors of image translation.

Conditioning a GAN

A conditional GAN (Mirza & Osindero, 2014) models p(x∣y)p(\mathbf x\mid y) by giving the condition to both players: the generator samples G(z,y)G(\mathbf z,y) and the discriminator judges pairs D(x,y)D(\mathbf x,y):

min⁡Gmax⁡D E(x,y)∼pdata[log⁡D(x,y)]+Ez, y∼p(y)[log⁡(1−D(G(z,y),y))].\min_G\max_D\ \E_{(\mathbf x,y)\sim p_{\text{data}}}\big[\log D(\mathbf x,y)\big]+\E_{\mathbf z,\,y\sim p(y)}\big[\log\big(1-D(G(\mathbf z,y),y)\big)\big].

The derivation of the optimal discriminator carries over pair by pair, D∗(x,y)=pdata(x,y)/(pdata(x,y)+pg(x,y))D^*(\mathbf x,y)=p_{\text{data}}(\mathbf x,y)/\big(p_{\text{data}}(\mathbf x,y)+p_g(\mathbf x,y)\big), so a generator that ignores yy is caught: a perfectly realistic cat labeled "dog" is a fake pair.

How yy enters matters in practice. Mirza & Osindero simply concatenated a one-hot label to the inputs of both networks. AC-GAN (Odena, Olah & Shlens, 2017) instead had the discriminator also predict the class through an auxiliary classifier. The most effective design for class-conditional discriminators came from asking what the optimal discriminator's logit looks like.

DerivationProof
  1. f∗(x,y)=log⁡q(x,y)p(x,y)=log⁡q(y∣x)p(y∣x)+log⁡q(x)p(x)f^*(\mathbf x,y)=\log\frac{q(\mathbf x,y)}{p(\mathbf x,y)}=\log\frac{q(y\mid\mathbf x)}{p(y\mid\mathbf x)}+\log\frac{q(\mathbf x)}{p(\mathbf x)}

    The optimal logit is the log density ratio of the two joints. Split each joint into a class posterior times a marginal:

  2. f∗(x,y=c)=(vcq−vcp)⊤ϕ(x)  −log⁡Zq(ϕ)+log⁡Zp(ϕ)+log⁡q(x)p(x)⏟ψ(ϕ(x))f^*(\mathbf x,y=c)=(\mathbf v^q_c-\mathbf v^p_c)^\top\boldsymbol\phi(\mathbf x)\;\underbrace{-\log Z^q(\boldsymbol\phi)+\log Z^p(\boldsymbol\phi)+\log\frac{q(\mathbf x)}{p(\mathbf x)}}_{\psi(\boldsymbol\phi(\mathbf x))}

    Insert the log-linear posteriors with normalizers Zq(ϕ)Z^q(\boldsymbol\phi) and Zp(ϕ)Z^p(\boldsymbol\phi). The class-dependent part is linear in the one-hot label; everything else depends on x\mathbf x only:

  3. So a discriminator built as an unconditional score ψ\psi plus an inner product between a learned class embedding and the features, a "projection", can represent the optimal logit exactly. Concatenating the label to the input imposes no such structure. Miyato & Koyama's version, with spectral normalization, much improved class-conditional ImageNet generation, and BigGAN adopted it together with class-conditional batch normalization in the generator.

Check your understanding

In a projection discriminator, how does the class label enter the score?

  1. It is concatenated to the input image as extra channels
  2. As the inner product between a learned embedding of the class and the discriminator's features, added to a class-independent score
  3. Through a separate classifier whose loss is added to the discriminator's
  4. It does not: the label only enters the generator
Show the answer

B. As the inner product between a learned embedding of the class and the discriminator's features, added to a class-independent score

f(x,y)=y⊤Vϕ(x)+ψ(ϕ(x))f(\mathbf x,y)=\mathbf y^\top V\boldsymbol\phi(\mathbf x)+\psi(\boldsymbol\phi(\mathbf x)). The derivation shows this form is exactly what the optimal logit looks like when class posteriors are log-linear in the features.

Paired translation: pix2pix

In image-to-image translation the condition is a whole image x\mathbf x, and with paired training data (x,y)(\mathbf x,\mathbf y) the obvious approach is regression: train a network to output y\mathbf y and penalize the pixel error. It produces blur, for a reason worth stating precisely.

pix2pix (Isola, Zhu, Zhou & Efros, 2017) keeps an L1 term, which gets low frequencies right and blurs less than L2, and adds a conditional discriminator that judges the pair (x,y)(\mathbf x,\mathbf y), so that outputs must look real and match their inputs:

G∗=arg⁡min⁡Gmax⁡D LcGAN(G,D)+λ E∥y−G(x,z)∥1,λ=100.G^*=\arg\min_G\max_D\ \loss_{\text{cGAN}}(G,D)+\lambda\,\E\norm{\mathbf y-G(\mathbf x,\mathbf z)}_1,\qquad\lambda=100.

Three design choices made it work:

  • A U-Net generator: an encoder–decoder with skip connections that concatenate layer ii with layer n−in-i, so low-level information such as the positions of edges can bypass the bottleneck; input and output share structure.
  • A PatchGAN discriminator that classifies each N×NN\times N patch as real or fake and averages the answers. Most experiments used 70×7070\times70 patches. Since the L1 term handles low frequencies, the discriminator only needs to judge local texture and sharpness; it assumes independence beyond the patch size, like a Markov random field, acts as a learned texture loss, has fewer parameters, and runs on images of any size.
  • Noise via dropout. Feeding z\mathbf z explicitly did not help: the generator learned to ignore it. Dropout at both training and test time gave only slight stochasticity, so pix2pix is nearly deterministic, an acknowledged limitation.

The same recipe handled labels to street scenes, aerial photos to maps and back, edges to photos, black-and-white to color, and day to night. An unconditional discriminator, by contrast, let the generator produce nearly the same realistic output whatever the input.

Predict before you look

In the reference implementation, the 70×7070\times70 PatchGAN stacks five 4×44\times4 convolutions with strides 2,2,2,1,12,2,2,1,1. Using rℓ=rℓ−1+(kℓ−1)∏i<ℓsir_\ell=r_{\ell-1}+(k_\ell-1)\prod_{i<\ell}s_i with r0=1r_0=1, how many input pixels across does each output unit see?

Show the answer

70 pixels

r=1+3⋅1+3⋅2+3⋅4+3⋅8+3⋅8=1+3+6+12+24+24=70r=1+3\cdot1+3\cdot2+3\cdot4+3\cdot8+3\cdot8=1+3+6+12+24+24=70. Each output judges one 70×7070\times70 patch, and the patches overlap; averaging their verdicts gives the discriminator's score for the image.

Unpaired translation: CycleGAN

Paired data is rare: nobody has photos of the same horse as a zebra. CycleGAN (Zhu, Park, Isola & Efros, 2017) learns from two unpaired collections, XX and YY, with two generators G:X→YG:X\to Y and F:Y→XF:Y\to X and a discriminator for each domain. Adversarial losses alone only ask that G(x)G(\mathbf x) look like some member of YY; any mapping that turns the distribution of XX into that of YY is optimal, and nothing ties an output to its input. CycleGAN adds cycle consistency: translating there and back should return the original,

Lcyc(G,F)=Ex∥F(G(x))−x∥1+Ey∥G(F(y))−y∥1,\loss_{\text{cyc}}(G,F)=\E_{\mathbf x}\norm{F(G(\mathbf x))-\mathbf x}_1+\E_{\mathbf y}\norm{G(F(\mathbf y))-\mathbf y}_1,

weighted by λ=10\lambda=10 against the two adversarial losses, which use a least-squares form for stability. Practical details: generators built from residual blocks with instance normalization, 70×7070\times70 PatchGAN discriminators, a buffer of the last 50 generated images for updating the discriminators (to damp oscillation), and, for paintings to photos, an identity loss that keeps colors from drifting.

The failure modes follow. CycleGAN changes color and texture well (horses to zebras, summer to winter, photos to the styles of painters) but fails at geometric changes: dog-to-cat translations make only minimal edits, and a horse-to-zebra model trained without riders stripes the rider too. And when one domain carries less information than the other, cycle consistency is satisfied by cheating. Chu, Zhmoginov & Sandler (2017) showed that a CycleGAN between aerial photographs and maps hides information about the photo in a nearly imperceptible, high-frequency signal inside the generated map, which the reverse generator decodes to reconstruct details that the map itself does not show. The generator becomes an encoder of adversarial-example-like perturbations.

Later unpaired methods relax the cycle. CUT (Park, Efros, Zhang & Zhu, 2020) trains a single direction and keeps input and output corresponding with a patchwise contrastive loss: each output patch must be closer, in a learned feature space, to the input patch at the same location than to other patches of the same image.

Check your understanding

A photo-to-map CycleGAN reaches nearly zero cycle loss, and its reconstructed photos show rooftop colors that appear nowhere in the intermediate maps. What is the most likely explanation?

  1. The reverse generator memorized the training photos
  2. The maps really contain the colors, but the human eye cannot see them
  3. The cycle loss was computed incorrectly
  4. The photo-to-map generator hides information about the photo in an imperceptible signal inside the map, which the reverse generator decodes
Show the answer

D. The photo-to-map generator hides information about the photo in an imperceptible signal inside the map, which the reverse generator decodes

A map carries far less information than a photo, so a faithful map cannot be inverted. Cycle consistency rewards inverting it anyway, and the generators find a channel: low-amplitude, high-frequency perturbations that look like nothing but encode the details (Chu, Zhmoginov & Sandler, 2017).

Layouts, resolution and perceptual losses

Semantic layouts. To synthesize a photo from a segmentation map, earlier generators fed the map through ordinary normalized layers. Park, Liu, Wang & Zhu (2019) noticed that normalization washes away exactly that information: a region of uniform label has uniform activations, which normalization maps to zero, so a map that is a single class produces the same output whichever class it is. SPADE (spatially-adaptive denormalization) normalizes activations per channel as usual, then modulates them with scale and bias maps computed from the layout by small convolutional networks:

hc,y,x′=γc,y,x(m) hc,y,x−μcσc+βc,y,x(m).h'_{c,y,x}=\gamma_{c,y,x}(\mathbf m)\,\frac{h_{c,y,x}-\mu_c}{\sigma_c}+\beta_{c,y,x}(\mathbf m).

The layout re-enters at every layer instead of being normalized away. With spatially constant γ\gamma and β\beta computed from a style image, and a batch of one (where batch normalization becomes instance normalization), SPADE reduces to AdaIN.

Super-resolution. Upsampling a low-resolution image is the extreme case of a one-to-many map: many sharp images downsample to the same small one. Johnson, Alahi & Fei-Fei (2016) replaced pixel losses with perceptual losses, distances between the activations of a pretrained classification network, and SRGAN (Ledig et al., 2017) added an adversarial term (content loss on VGG features plus 10−310^{-3} times the adversarial loss) for 4×4\times upscaling. Its outputs had lower PSNR than MSE-trained networks but were rated much higher by human observers. That tension is a theorem.

Diffusion-era successors. As of the mid-2020s most image translation is done with pretrained diffusion models, which supply a strong prior over images:

  • SDEdit (Meng et al., 2022) translates without any task-specific training: add noise to the input (a stroke painting, a sketch, another domain's image) up to an intermediate time t0t_0, then run the reverse process. Larger t0t_0 gives more realistic but less faithful results, a single knob for the realism–faithfulness trade-off.
  • ControlNet (Zhang, Rao & Agrawala, 2023) adds spatial conditions (edges, depth, human pose, segmentation) to a frozen text-to-image model by training a copy of its encoder blocks, connected back through zero-initialized 1×11\times1 convolutions, so training starts exactly from the unchanged model.
  • Image-conditional diffusion trained on paired data, such as Palette (Saharia et al., 2022), handles colorization, inpainting, uncropping and JPEG restoration with one framework and no adversarial loss.

Key takeaways

  • Conditional GANs give the condition to both players; the optimal discriminator compares joint densities, so ignoring the condition is punished. Under log-linear class posteriors its logit is y⊤Vϕ(x)+ψ(ϕ(x))\mathbf y^\top V\boldsymbol\phi(\mathbf x)+\psi(\boldsymbol\phi(\mathbf x)), the projection discriminator.
  • Squared and absolute errors predict a per-pixel mean or median and blur multimodal outputs; pix2pix combines L1 for low frequencies with a conditional 70×7070\times70 PatchGAN for local realism and a U-Net generator.
  • CycleGAN learns unpaired translation with two generators and the cycle loss ∥F(G(x))−x∥1+∥G(F(y))−y∥1\norm{F(G(\mathbf x))-\mathbf x}_1+\norm{G(F(\mathbf y))-\mathbf y}_1, which does not identify the mapping and can be satisfied by hiding information in imperceptible signals.
  • SPADE re-injects layouts that normalization would erase; perceptual and adversarial losses trade distortion for realism along the perception–distortion frontier; diffusion methods (SDEdit, ControlNet, Palette) now do most image translation.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why does pix2pix add an adversarial term to its L1 reconstruction loss?

  1. L1 alone decides each pixel separately, giving a per-pixel median that blurs uncertain regions; the conditional discriminator rewards outputs that look like real images as a whole and match their inputs
  2. L1 cannot be minimized by gradient descent
  3. The adversarial term makes the output exactly equal to the target
  4. L1 ignores the input image
Show the answer

A. L1 alone decides each pixel separately, giving a per-pixel median that blurs uncertain regions; the conditional discriminator rewards outputs that look like real images as a whole and match their inputs

Absolute error is minimized by a median and squared error by a mean, pixel by pixel. Where several outputs are plausible, these hedge, and nothing makes neighboring pixels agree. The discriminator judges joint realism, while L1 keeps the low frequencies faithful.

Question 2

A CycleGAN reaches zero cycle loss and fools both discriminators. What can you conclude?

  1. Its translation is the intended one, since the inverse mapping recovers every input
  2. It has memorized the training set
  3. Only that GG and FF are mutual inverses mapping each distribution onto the other; composing GG with any symmetry of the target distribution would score equally well, and hidden signals can also achieve it
  4. The two domains must have identical distributions
Show the answer

C. Only that GG and FF are mutual inverses mapping each distribution onto the other; composing GG with any symmetry of the target distribution would score equally well, and hidden signals can also achieve it

If TT preserves pYp_Y, then T∘GT\circ G and G−1∘T−1G^{-1}\circ T^{-1} are just as optimal. The objective does not single out a correspondence; architecture and training do, and steganographic shortcuts are also optimal.

Question 3

Why did SPADE re-inject the segmentation layout at every normalization layer?

  1. Ordinary normalization maps a region of uniform activations to zero, washing away the label information that a flat layout region carries
  2. To make the generator faster
  3. To remove the need for a discriminator
  4. Because segmentation maps cannot be fed to a convolutional network directly
Show the answer

A. Ordinary normalization maps a region of uniform activations to zero, washing away the label information that a flat layout region carries

A uniform region has zero spatial variation, and normalization subtracts the mean, so a single-class layout produces the same normalized activations whatever the class. SPADE's spatially varying γ(m)\gamma(\mathbf m) and β(m)\beta(\mathbf m) put the layout back after each normalization.

Further reading

  • T. Miyato & M. Koyama, "cGANs with projection discriminator," ICLR (2018).
  • P. Isola, J.-Y. Zhu, T. Zhou & A. A. Efros, "Image-to-image translation with conditional adversarial networks," CVPR (2017).
  • J.-Y. Zhu, T. Park, P. Isola & A. A. Efros, "Unpaired image-to-image translation using cycle-consistent adversarial networks," ICCV (2017).
  • T. Park, M.-Y. Liu, T.-C. Wang & J.-Y. Zhu, "Semantic image synthesis with spatially-adaptive normalization," CVPR (2019).
  • Y. Blau & T. Michaeli, "The perception-distortion tradeoff," CVPR (2018).