skip to content
← Scientific Spaces English

Directly Using FID as a Loss: From Gradient Calculation to Streaming Training

Readers following visual generative models know that FID has always been one of the key evaluation metrics; lower values typically indicate more realistic generation. A natural question then arises: why not simply use FID directly as the loss function to train generative models? Could it be because FID is non-differentiable? Far from it. FID is actually differentiable, and there is no theoretical problem with using it as a loss; in practice, however, one encounters computational difficulties.

Recently, the paper 《Representation Fréchet Loss for Visual Generation》made some attempts to overcome these difficulties, successfully applying FID to generative model fine-tuning and noticeably improving the quality of single-step generation. In this post, I will briefly explore the underlying mathematical principles and implementation techniques.

Generative Metrics #

FID stands for "Fréchet Inception Distance", which we can understand by dividing it into two parts: "Fréchet Distance (FD)" and "Inception (I)".

Suppose there are two distributions and , representing real and generated samples, respectively. We pass their respective samples through a pretrained encoder to encode them into feature vectors , and estimate their respective mean vectors and covariance matrices . Then, assuming that the encoded results follow multivariate normal distributions, we can measure the discrepancy between them using a divergence function for normal distributions. Fréchet Distance (FD) chooses the Wasserstein distance:

Substituting the mean vectors and covariance matrices of the respective encoded representations into the equation above yields what is called the "Fréchet Distance (FD)". As for the derivation of the equation above, interested readers can refer to "KL Divergence, Bhattacharyya Distance, and Wasserstein Distance Between Two Multivariate Normal Distributions".

If we select the encoder to be InceptionV3 (I), then the corresponding result is called the "Fréchet Inception Distance", or FID. This evaluation metric was first proposed in the 2017 paper 《GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium》, which in some sense is already a product of the "ancient era".

Of course, whether for training or evaluation, using InceptionV3 is no longer strictly necessary nowadays; we can use other more advanced feature models, such as SigLIP, or compute the Fréchet Distance once for each of several different encoders and sum them up, and so on. We collectively refer to these approaches as "FD Loss".

Related Literature #

Although FID looks complex, it involves no non-differentiable operations, so using it as a loss is a very natural idea. As early as several years ago, there were already attempts in this direction, such as 《Image Generation Via Minimizing Fréchet Distance in Discriminator Feature Space》 and 《Backpropagating through Fréchet Inception Distance》.

However, early attempts did not produce particularly impressive results, with the fundamental reason being batch size. A standard loss function computes an individual loss for each single sample and then averages over all samples, whereas FID first computes the mean and covariance across all samples, and then substitutes them into Equation to perform nonlinear computations. This causes the FID estimated from small batches to be biased, and this bias cannot be eliminated through continued training—it can only be mitigated by increasing the batch size, making the training cost quite painful.

"Requiring nonlinear operations across samples", "requiring a large batch size"—do these phrases sound familiar? In fact, "contrastive learning" in vision usually shares these two characteristics as well. Due to nonlinear operations across samples, we cannot achieve the effect of increasing batch size via gradient accumulation either, but this is not completely unsolvable—for example, "Can Contrastive Learning Use Gradient Accumulation?". As we will see later, the method FID uses to resolve the batch size issue is actually quite similar.

Furthermore, from the perspective of "using a pretrained model to extract features to construct a loss function", another related work is Perceptual Loss, but this is used as a per-sample reconstruction loss, typically for training models such as VAEs, and does not involve cross-sample statistical operations, so there is no real computational difficulty.

Gradient Computation #

Now let us derive things step by step to see what difficulties are actually encountered when using FD as a loss. The first issue to resolve is the gradient computation. represents the real distribution, whose are fixed, so we only need to take gradients with respect to . has a relatively simple gradient:

While has the gradient

Here we use the second line of Eq. , which looks more complicated, but it has one advantage: the matrix is symmetric positive-definite, which can be used to simplify the computation. Let the singular value decomposition—that is, the eigenvalue decomposition—of be , then , and so

For the derivatives of eigenvalues, one can refer to "Derivatives of SVD". The final result is analogous to how the derivative of is ; it looks very intuitive, but it is non-trivial: if is not a symmetric positive-definite matrix, this generally does not hold. Finally, by the chain rule, we have

Combining these yields

This form may seem complicated, but can be precomputed, and we only need to compute the square root and inverse square root of the symmetric positive-definite matrix to calculate FID and its gradient. This can be accomplished via the eigh function, or by using the Newton-Schulz iteration schemes introduced in "Efficient Computation of Matrix Square Roots and Inverse Square Roots" and "Efficient Computation of Matrix r-th Roots and Inverse r-th Roots".

Ultra-Large Batches #

Introducing the notation:

Then

Note that usually has thousands of dimensions (2048 for InceptionV3), so tens of thousands of samples are typically required for accurate estimation. The real distribution is fixed, and its can be computed in advance, which is not an issue; however, the generative distribution changes in real time. If tens of thousands of samples are used at every step, that means the batch size would have to reach tens of thousands, which is quite prohibitive in many cases.

On the other hand, from the gradient formula , we can also see the necessity of a large batch. If the batch size is very small, then the estimated will not even be full rank, and thus will not be full rank either. At this point, cannot be inverted at all (we would face ). Therefore, using FD as a loss imposes requirements on the training batch size, which is likely the central difficulty in practice.

Constrained by compute, we can only try to simulate the effect of a large batch size using a small batch size, which is similar to the requirement in 'contrastive learning + gradient accumulation'.

Equivalent Loss #

Suppose that with a batch size of , the corresponding are sufficiently accurate, but we can only run a small batch size each time, so we need to run a total of times to simulate the effect of a large batch size. The results produced each time are , , ..., , so we have the relationship

We want to find an ideal equivalent loss such that the total gradient is equivalent to the sum of the gradients from each small batch, achieving an unbiased estimate. To this end, taking Eq. and differentiating both sides yields

What this equality means is that we can run forward passes sequentially in small batches to obtain , average them to obtain sufficiently accurate , and then for each batch compute the gradient using the loss

, and finally accumulate these gradients. This gradient is equivalent to the gradient with batch size , where is the stop-gradient operator. Of course, we could also consider not accumulating gradients, but instead using each step's gradient to perform an update and reducing the learning rate slightly accordingly; the effect is similar.

Filling the Gap with History #

Although the above scheme is theoretically feasible, because it requires forward steps to compute accurate , and only then turn around to compute the gradient at each step, the entire process feels rather un-'smooth'. The bottleneck here is that we must know the global before we can find a way to compute an unbiased local gradient.

A natural idea is: for , could we do some approximation? Considering that the learning rate is relatively small and parameter updates are slow, then should also change slowly. After introducing the current batch of data, the new should merely be a slight adjustment on top of the old ones. We consider using an exponential moving average (EMA) to approximate this operation:

This roughly maintains an averaging window of size , which is roughly equivalent to expanding the statistical batch size of by a factor of . In this way, at each step we can compute gradients according to the following loss to update

The extra cost is having to cache , which is very inexpensive. This operation of "making up for an insufficient batch size with history" is actually also an embodiment of the "streaming" philosophy in "Streaming Power Iteration". In addition, the paper discusses a queue approach, which maintains a queue of historical batches, incorporates them with the current batch according to Eq. to compute gradients, and evicts the oldest batch. This approach is actually quite naive, occupies much more space than EMA, and in practice performs worse than EMA.

Experimental Highlights #

The paper's experiments focus primarily on the post-training of generative models, aiming to improve the performance of original single-step generative models or fine-tune original multi-step generative models into single-step generative models via FD loss training. When mixing multiple different encoders to compute the FD loss, the paper uses a loss normalization trick to balance losses of different magnitudes:

We also discussed this trick in "Discussions on Multi-Task Learning (1): In the Name of Loss".

The paper's crowning achievement is pushing the performance (FID) of single-step generation to a brand-new height, surpassing all other single-step and multi-step generative models; this result appears to have reached the ceiling. Some charts are shown below:

FD loss improves single-step generation performance

FD loss improves single-step generation performance

Comprehensive comparison of FD loss

Comprehensive comparison of FD loss

Summary #

This article primarily analyzed from a theoretical perspective the difficulties of using FID as a loss function for generative models, and how to derive the corresponding techniques to overcome these difficulties from the derivation process.

Table 2, Figure 5 from Representation Fréchet Loss for Visual Generation (2604.28190v1); matching English original retained. Source attribution.

Table 4 from Representation Fréchet Loss for Visual Generation (2604.28190v1); matching English original retained. Source attribution.