Course contents 21 / 34

21 / 34 · GANs

Beyond CycleGAN: multimodal, contrastive and semantic image synthesis

Other routes from an image or a label map to an image: a swappable style code, a contrastive loss in place of the cycle, label maps that modulate every layer, and super-resolution beyond the pixel loss.

On this page 6

An input image rarely determines every detail of a desired output. A useful translator must preserve some information, change something else and account for what the input never observed. The CycleGAN note showed how a return trip constrains a correspondence without identifying its meaning. If several outputs are valid, recovering one input through a return trip requires preserving the information that selects it.

The worked cases use explicit finite vectors. They let us verify information flow and losses exactly; they do not measure photographic quality or train the named networks.

MUNIT: one content space, a style space per domain#

MUNIT separates a shared content code from domain-specific style and translates by combining content from one image with a sampled or encoded target style (Huang et al., 2018). This names the intended roles of the variables. An unsupervised objective alone does not certify that the learned coordinates match a person’s idea of content or style.

Two autoencoders with a shared content code#

Let each encoder return a pair and each decoder consume it:

Ei(xi)=(ci,si),x~2=G2(c1,s2).\begin{aligned} E_i(x_i)&=(c_i,s_i),\\ \widetilde x_2&=G_2(c_1,s_2). \end{aligned}

For a completely specified example, choose content uniformly from two values and independently choose style uniformly from two others:

c∈{−1,2},s∈{−2,1},G1(c,s)=(c,s),G2(c,s)=(3c+s,c−2s).\begin{aligned} c&\in\{-1,2\},\\ s&\in\{-2,1\},\\ G_1(c,s)&=(c,s),\\ G_2(c,s)&=(3c+s,c-2s). \end{aligned}

The second domain contains exactly four points. Its inverse is ordinary linear algebra:

E2(a,b)=(2a+b7,a−3b7).E_2(a,b)=\left(\frac{2a+b}{7},\frac{a-3b}{7}\right).

Keep content at −1. The two target styles produce (−5,3) and (−2,−3). Decoding does not require guessing a missing style from the source: we supply one. Conversely, encoding either output recovers the same content and the chosen target style. The domains here are vector collections specified for this lesson, not a dataset of images.

Losses in image and latent space#

There are three distinct reconstruction checks. An image round trip asks whether its own content and style reconstruct it. A content round trip asks whether translation preserves the content code. A style round trip asks whether the decoder uses the supplied target style. For example:

rx=∥G1(E1(x1))−x1∥1,rc=∥E2c(G2(c1,s2))−c1∥1,rs=∥E2s(G2(c1,s2))−s2∥1.\begin{aligned} r_x&=\|G_1(E_1(x_1))-x_1\|_1,\\ r_c&=\|E_2^c(G_2(c_1,s_2))-c_1\|_1,\\ r_s&=\|E_2^s(G_2(c_1,s_2))-s_2\|_1. \end{aligned}

MUNIT combines both directions of these checks with adversarial distribution matching (Huang et al., 2018). Our eight combinations of source content, source style and target style have all three residuals zero. Each target point is generated twice, hence with probability one quarter. That verifies the target marginal directly, without a trained discriminator.

Reconstruction and marginal matching are complementary: an invertible but badly chosen coordinate transform may reconstruct perfectly while generating the wrong target frequencies; correct frequencies alone do not establish the desired pairing.

Why MUNIT has no cycle loss#

The main objective does not require a fresh random reverse translation to recover the input. MUNIT instead admits a cycle that retains the original style (Huang et al., 2018). Our example makes the distinction concrete. Translate source (−1,−2) using target style 1 to get (−2,−3). Recover content −1 and combine it with the saved source style −2: the result is the original input. Combining it with fresh style 1 instead gives (−1,1).

The saved variable carries information that would otherwise be lost. In this example, replacing the saved source style by an independent uniform draw succeeds only half the time. This is a statement about our explicit finite procedure, not an assertion that every stochastic cycle is impossible.

Where it breaks: diversity that is noise#

For content −1, the two valid outputs have an L1 distance of 9. A different procedure outputs (−20,−20) or (20,20), with distance 80. Its diversity is larger, but neither result is in the stipulated valid set. A distance between outputs measures variation; it does not establish whether that variation is acceptable. Here validity can be checked exactly because the set is known. In photographic evaluation it needs a separate, justified assessment.

Likewise, renaming the two content values consistently leaves every reconstruction equation true. Without extra evidence, zero loss identifies an internal code convention, not semantic names.

CUT: replacing the cycle with a contrastive loss#

Why drop the cycle?#

CUT uses one translation direction and a patchwise contrastive objective to encourage input/output correspondence. The generator’s encoder and a projection network provide features; corresponding locations are positives, while other locations in the same input supply negatives (Park et al., 2020). This avoids building a reverse translator solely for a reconstruction loss. It still requires a reason to trust the feature correspondence.

InfoNCE: pick the positive among negatives#

Suppose a query has similarities to three candidates, with candidate zero designated positive. Divide the similarities by a positive temperature, apply softmax, then penalize the negative log probability of the designated candidate:

pj=exp⁡(sj/τ)∑k=02exp⁡(sk/τ),ℓ=−log⁡p0.\begin{aligned} p_j&=\frac{\exp(s_j/\tau)}{\sum_{k=0}^{2}\exp(s_k/\tau)},\\ \ell&=-\log p_0. \end{aligned}

Use the three standard unit vectors as keys. A correct query gives similarities (1,0,0); a query shifted to the next key gives (0,1,0); identical query and key features everywhere give (1,1,1). No image network or random vectors are needed to compute the result:

TemperatureCorrect locationRotated locationIdentical features
10.5514451.5514451.098612
0.50.2395452.2395451.098612

These are losses in nats. At temperature 0.5 the correct location receives probability 0.786986. Lower temperature rewards the correct ranking more confidently and punishes the wrong ranking more confidently. Differentiating the log-sum-exp gives

∂ℓ∂sj=pj−1{j=0}τ.\frac{\partial\ell}{\partial s_j}=\frac{p_j-\mathbf 1\{j=0\}}{\tau}.

For identical features the loss is log three: no candidate is preferred. This does not mean every gradient through a shared feature network is useful; the features’ parameterization and Jacobian also matter.

PatchNCE: corresponding patches, negatives from the same image#

The classification calculation extends to several spatial locations and feature layers, averaging their losses. CUT uses normalized features and within-image negatives (Park et al., 2020). Correspondence is therefore encouraged at the selected representation levels, not enforced as literal pixel equality.

For the standard InfoNCE mutual-information bound, consider independent joint pairs, with negatives drawn from the appropriate marginal independently of the query. Under that sampling contract, for K candidates (Poole et al., 2019):

I(X;Y)≥log⁡K−Eℓ.I(X;Y)\geq\log K-\mathbb E\ell.

This is an expectation bound, not a certificate from one observed loss. It is at most log K and need not be tight. Correlated patches inside one image do not automatically satisfy the independent-negative contract. The classification objective remains well-defined even when that particular theorem cannot be invoked.

The objective, and FastCUT#

Writing the source and optional target-domain contrastive terms separately avoids confusing an identity regularizer with a reverse generator:

L=Ladv+λXLNCE,X+λYLNCE,Y.L=L_{\mathrm{adv}}+\lambda_XL_{\mathrm{NCE},X}+\lambda_YL_{\mathrm{NCE},Y}.

The reported CUT setting uses both coefficients equal to 1; FastCUT uses source coefficient 10 and target coefficient 0 (Park et al., 2020). These describe the paper’s settings, not universally optimal values or a speed guarantee for arbitrary implementations.

Where it breaks: matching the statistics of the target#

Our unit-vector case also exposes a shortcut. Suppose a feature extractor returns the first unit vector at the first location, the second at the second, and so on, regardless of image content. Input and output then get the low “correct location” loss even if every translated image is constant. The extractor has identified coordinates, not preserved useful content. This is a constructed counterexample with positional access, not a claim that CUT necessarily learns this extractor.

A distribution-level discriminator supplies an additional constraint, but still does not label the intended input/output relation. Evaluate correspondence and output quality separately; neither a single contrastive value nor a marginal realism score answers both questions.

Semantic image synthesis from a label map#

A label map states which category belongs at each location. It supplies spatial information rather than leaving all correspondence to an unpaired objective. Training pairs and the meaning of their labels must be defined consistently; the map does not specify every color or texture.

pix2pixHD: multi-scale discriminators and feature matching#

pix2pixHD combines a coarse-to-fine generator with discriminators at several image scales. It also compares discriminator features for real and generated images conditioned on the same map (Wang et al., 2018). For fixed discriminator parameters, an L1 discrepancy between intermediate features gives the generator a richer target than the final real/fake score alone. Gradients still flow through those features to the generated image; holding discriminator parameters fixed is not the same as detaching the generated features.

Downsampling changes what a local discriminator can observe. A fine-scale view can penalize a local artifact while a coarse-scale view sees a larger arrangement. Neither guarantees that every structure or small object will be represented correctly.

How normalization washes out the label map#

Consider one channel with six activations:

h=(1,3,1,3,1,3),μ=2,v=1,ϵ=14.\begin{aligned} h&=(1,3,1,3,1,3),\\ \mu&=2,\\ v&=1,\\ \epsilon&=\frac14. \end{aligned}

Normalize over these six positions:

h^j=hj−μv+ϵ.\widehat h_j=\frac{h_j-\mu}{\sqrt{v+\epsilon}}.

Every low value becomes −2 divided by the square root of five, every high value the positive counterpart. Now add 7 to every input activation. Its mean also increases by 7, its variance is unchanged, and the normalized output is exactly the same. Any category encoded only by that offset has disappeared. This explicit example concerns information loss in centering; a real network may retain information through other channels or paths.

The variance after normalization is 4/5, not exactly 1, because epsilon is positive. The example uses a deliberately visible epsilon to make that distinction easy to check.

SPADE: per-pixel scale and shift from the mask#

SPADE supplies spatially varying modulation from the label map after normalization (Park et al., 2019). Including the sample index explicitly, the operation has the form

yn,c,u,v=γn,c,u,v(mn)h^n,c,u,v+βn,c,u,v(mn).\begin{aligned} y_{n,c,u,v}&=\gamma_{n,c,u,v}(m_n)\widehat h_{n,c,u,v}\\ &\quad+\beta_{n,c,u,v}(m_n). \end{aligned}

The chosen normalization statistics must also be specified; our single-channel case uses the six positions above. Give those positions labels A,A,B,B,C,C and use the following stipulated lookup values, rather than a trained convolution:

LabelScaleShift
A1−1
B20
C0.52

The outputs are approximately −1.894427, −0.105573, −1.788854, 1.788854, 1.552786 and 2.447214. Labels now affect the result after the operation that erased the shared offset. The lookup illustrates the modulation arithmetic; it is not the learned mask-processing network from the paper.

Figure

Normalization loses an offset; the mask restores control

Six sites with three labelsInput alternates 1 and 3, and a second input 8 and 10. Normalized values alternate −0.8944 and 0.8944. Labels A,A,B,B,C,C select scales 1,1,2,2,0.5,0.5 and shifts −1,−1,0,0,2,2.Label mAABBCCh131313h + 7810810810Norm. h−0.890.89−0.890.89−0.890.89γ(m)11220.500.50β(m)-1-10022Output−1.89−0.11−1.791.791.552.45Output = γ(m) · normalized h + β(m)Six sites with three labelsInput alternates 1 and 3, and a second input 8 and 10. Normalized values alternate −0.8944 and 0.8944. Labels A,A,B,B,C,C select scales 1,1,2,2,0.5,0.5 and shifts −1,−1,0,0,2,2.Label mAABBCCh131313h + 7810810810Norm. h−0.890.89−0.890.89−0.890.89γ(m)11220.500.50β(m)-1-10022Output−1.89−0.11−1.791.791.552.45Output = γ(m) · normalized h + β(m)
Two different inputs give the same normalized values. Labels A/B/C then select different γ and β. This is an explicit coefficient lookup, not a trained SPADE network. Values are rounded; ε = 1/4, and normalized h has variance 4/5.

This pathway permits spatial control, but the loss and training data must teach the generator to use it. A misaligned or unseen label map can still produce a poor result.

Super-resolution: why the average looks blurry#

Super-resolution starts with a measurement that can discard detail. Define a four-entry high-resolution vector and obtain two low-resolution entries by averaging adjacent pairs. Three possible originals all produce the same observation (2,2):

OriginalFour entriesConditional probability
a(0,4,1,3)1/5
b(2,2,3,1)1/2
c(3,1,0,4)3/10

The probabilities are part of our specified problem, not inferred from a model. The observation cannot tell which original occurred. Artificially degrading photographs can create training pairs. The degradation must match the intended application: a model trained to undo one reduction process need not recover details lost by another.

The MSE optimum is the conditional mean#

For a fixed observation with finite conditional second moment, let the conditional mean be m. Expanding a square and using the zero-mean residual yields, for every deterministic prediction g:

E[∥X−g∥2∣L]=E[∥X−m∥2∣L]+∥g−m∥2.\mathbb E[\|X-g\|^2\mid L] =\mathbb E[\|X-m\|^2\mid L]+\|g-m\|^2.

Thus the mean minimizes squared error. In our four-entry case it is

m=(19/10,21/10,17/10,23/10).m=(19/10,21/10,17/10,23/10).

Divide squared errors by four to obtain per-entry MSE. The mean has risk 29/20. Always outputting b has risk 23/10; its excess is 17/20, exactly its squared distance from the mean divided by four. The optimal mean is not one of the three possible originals.

Now independently draw another original from the same conditional distribution. The two residuals have zero cross expectation, so the expected squared distance is twice the conditional variance. Enumerating the nine pairs gives sample risk 29/10. Conditional independence and the correct conditional law are essential; a deterministic GAN output is not automatically such a sample.

Figure

One reduced signal admits different details

Three possible signals, their mean and risksSignals a=(0,4,1,3), b=(2,2,3,1), c=(3,1,0,4), probabilities 1/5, 1/2, 3/10. Mean (1.9,2.1,1.7,2.3). MSE: mean 29/20, independent sample 29/10, fixed b 23/10.a: p = 1/50413b: p = 1/22231c: p = 3/103104Conditional mean1.92.11.72.3Reconstruction ruleExpected MSEMean29/20Independent sample29/10Always candidate b23/10MSE is averaged over four entriesThree possible signals, their mean and risksSignals a=(0,4,1,3), b=(2,2,3,1), c=(3,1,0,4), probabilities 1/5, 1/2, 3/10. Mean (1.9,2.1,1.7,2.3). MSE: mean 29/20, independent sample 29/10, fixed b 23/10.a: p = 1/50413b: p = 1/22231c: p = 3/103104Conditional mean1.92.11.72.3Reconstruction ruleExpected MSEMean29/20Independent sample29/10Always candidate b23/10MSE is averaged over four entries
All three signals become (2, 2) after averaging adjacent pairs. The mean minimizes conditional MSE. An independent sample from the stated distribution doubles expected MSE; a fixed candidate b follows a different formula. This is a finite problem, not a generator quality measurement.

With peak value 4, define a score from the aggregate MSE:

PSNRaggregate=10log⁡1016MSE.\mathrm{PSNR}_{\mathrm{aggregate}}=10\log_{10}\frac{16}{\mathrm{MSE}}.

This score is 10.427520 dB for the mean and 7.417220 dB for the independent sample. Their difference is approximately 3.010300 dB. This is not the average of each pair’s PSNR: the independent sample equals the truth with probability 19/50, giving zero error and infinite per-pair PSNR under the uncapped definition. Averaging before or after the logarithm changes the quantity. There is no universal three-decibel penalty for every perceptual model or evaluation protocol.

SRGAN: a VGG content loss and an adversarial loss#

SRGAN combines a feature-space content loss from a fixed VGG network with an adversarial generator objective (Ledig et al., 2017). The feature map changes which discrepancies are expensive. It does not observe the missing detail in the particular input. In our case, choosing a plausible original can preserve a possible high-frequency pattern while disagreeing with the hidden truth. That is why visual plausibility and reconstruction error need separate interpretation.

A fixed feature network still participates in differentiation with respect to the generated image. Its parameters need not be optimized. We do not load a VGG checkpoint here: framework code, pretrained weights and training images have separate provenance.

ESRGAN: RRDB, a relativistic discriminator and features before activation#

ESRGAN uses residual-in-residual dense blocks without batch normalization, a relativistic-average discriminator, and feature comparisons before activation. Its generator objective also retains a pixel L1 term (Wang et al., 2018). With critic scores, the relativistic real score compares a real example against the mean fake score; the fake score uses the opposite reference group. The generator therefore receives gradients through the fake group even in the real-example term.

Comparing pre-activation features avoids one particular information loss: distinct negative activations become the same zero after ReLU. That observation does not establish that any selected layer is an adequate perceptual metric for every domain.

The paper also interpolates corresponding parameters between an initial reconstruction model and its adversarially fine-tuned continuation (Wang et al., 2018). A shared architecture and aligned parameterization matter. Interpolated weights do not generally yield linearly interpolated outputs or monotonically improving metrics. Treat intermediate models as candidates to evaluate, not a theorem about quality.

What changed#

We have replaced one constraint with several more specific choices. A saved style variable makes a multimodal return trip possible. Local contrastive classification tests a chosen representation. Spatial modulation supplies labels after normalization. Reconstruction from a lossy measurement requires deciding how to score uncertainty. Each mechanism answers a different question about information.

What you should remember#

Specify what remains fixed, what is sampled and what the observation cannot reveal. Check marginal validity separately from correspondence and diversity. State the negative-sampling contract before interpreting a contrastive loss as an information bound. Distinguish a conditional mean, a fixed plausible output and an independent conditional sample. When reporting PSNR, state its peak, error normalization and aggregation order.

Code#

This small standard-library program independently enumerates the reconstruction risks. It requires no network, dataset or random sampling.

from fractions import Fraction as F

rows = [(0, 4, 1, 3), (2, 2, 3, 1), (3, 1, 0, 4)]
p = [F(1, 5), F(1, 2), F(3, 10)]
m = [sum(w * x[j] for w, x in zip(p, rows)) for j in range(4)]
def mse(x, y):
    return sum((F(a) - F(b)) ** 2 for a, b in zip(x, y)) / 4
mean_risk = sum(w * mse(x, m) for w, x in zip(p, rows))
sample_risk = sum(p[i] * p[j] * mse(x, y)
                  for i, x in enumerate(rows) for j, y in enumerate(rows))
print("mean:", " ".join(map(str, m)))
print("risks:", mean_risk, sample_risk)
assert sample_risk == 2 * mean_risk
mean: 19/10 21/10 17/10 23/10
risks: 29/20 29/10

The companion executable verifies all eight multimodal round trips, the contrastive losses and their gradients, the six modulation outputs and the full reconstruction table. Its saved results drive the figures. These are finite calculation checks, not training or benchmark results.

Next#

These translators do not generally offer an efficiently evaluated normalized density. The normalizing-flows note changes that contract: an invertible map and a normalized base distribution permit density evaluation through a Jacobian. That benefit comes with its own restrictions on the map.

Where to see the images#

The primary papers linked below show the authors’ photographic experiments. They are external references, not redistributed image collections or assets required for this lesson. Our two figures show only the explicit numerical cases described here.

References#

  1. Xun Huang, Ming-Yu Liu, Serge Belongie, Jan Kautz. Multimodal Unsupervised Image-to-Image Translation, 2018, sections 3–4.
  2. Taesung Park, Alexei A. Efros, Richard Zhang, Jun-Yan Zhu. Contrastive Learning for Unpaired Image-to-Image Translation, 2020, section 3.
  3. Ben Poole, Sherjil Ozair, Aaron van den Oord, Alexander A. Alemi, George Tucker. On Variational Bounds of Mutual Information, 2019, section 2.3, equation 10.
  4. Ting-Chun Wang, Ming-Yu Liu, Jun-Yan Zhu, Andrew Tao, Jan Kautz, Bryan Catanzaro. High-Resolution Image Synthesis and Semantic Manipulation with Conditional GANs, 2018, section 3.2.
  5. Taesung Park, Ming-Yu Liu, Ting-Chun Wang, Jun-Yan Zhu. Semantic Image Synthesis with Spatially-Adaptive Normalization, 2019, section 3.
  6. Christian Ledig, Lucas Theis, Ferenc Huszár, Jose Caballero, Andrew Cunningham, Alejandro Acosta, Andrew Aitken, Alykhan Tejani, Johannes Totz, Zehan Wang, Wenzhe Shi. Photo-Realistic Single Image Super-Resolution Using a Generative Adversarial Network, 2017, section 2.2.
  7. Xintao Wang, Ke Yu, Shixiang Wu, Jinjin Gu, Yihao Liu, Chao Dong, Chen Change Loy, Yu Qiao, Xiaoou Tang. ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks, 2018, sections 3.1–3.4.