Overfitting and Regularization Techniques

How overfitting shows up in GANs, VAEs, diffusion models and LLM fine-tunes, and the regularization techniques that keep generative models general.

Generative AI

A classifier that overfits gets wrong answers on new inputs, and your test accuracy tells you so. A generative model that overfits does something quieter: it gives back its training data. A fine-tuned image model draws the same five photos you trained it on with slightly different backgrounds. A chat model repeats a customer email word for word, name and phone number included. A GAN discriminator memorizes the real set and training falls apart. None of these show up as a single bad number unless you go looking.

This article covers what overfitting means for generative models, how to spot it in each model family, and the regularization techniques that work in practice: data, weight decay, dropout, early stopping, augmentation, label smoothing, and the parameter-efficient methods that dominate fine-tuning today. The previous article on evaluation metrics explained how to grade a generative model; this one is about training it so the grade holds on data it has never seen.

What overfitting means

A model is trained to reduce a loss on the training set, but you care about its behaviour on new data from the same distribution. The gap between the two is the generalization gap. Overfitting is when that gap grows: training loss keeps falling while held-out loss stops improving or starts to rise. The model has started fitting noise and specific examples rather than the patterns that carry over.

The opposite failure, underfitting, is when the model cannot fit even the training data well, usually because it is too small, trained too briefly, or regularized too hard. The model training and evaluation article introduces both for classic supervised learning. Generative models add three twists.

  • There is no label to get wrong. The failure is copying rather than mislabeling, so it can look like excellent output. A memorized image is, after all, a very realistic image.
  • Memorization is not uniform. A model can generalize well overall and still reproduce a handful of examples verbatim, typically ones that were duplicated many times in the training data. Average loss hides this.
  • Some architectures have internal overfitting. In a GAN, the discriminator can overfit to the real set even while the generator is far from it, which wrecks the training signal.

Capacity, data and the classic curve

The textbook picture is a U-shaped test error curve: as model capacity grows, test error falls, then rises once the model is big enough to memorize. Large neural networks complicate this. Nakkiran and colleagues (2019) showed “deep double descent”: test error can rise near the point where the model just barely fits the training set, then fall again as the model grows further. This is part of why very large language models, with far more parameters than a naive count says they should support, still generalize.

What has not changed is the role of data. Overfitting is a ratio problem: capacity relative to the amount of distinct information in the data. A billion-parameter model pretrained on trillions of tokens rarely sees the same token sequence twice and barely needs explicit regularization. The same model fine-tuned on 500 examples for ten epochs will memorize them.

flowchart LR
    A["Training loss falls"] --> B{"Validation loss?"}
    B -->|"Falls too"| C["Still learning"]
    B -->|"Flat"| D["Near the best point"]
    B -->|"Rises"| E["Overfitting"]
    E --> F["Stop early, add data or regularize"]
    D --> G["Keep the best checkpoint"]

How overfitting shows up in each model family

The symptoms differ enough by architecture that it is worth going through them one at a time.

GANs: the discriminator overfits

A GAN’s generator never sees the training images directly. It only gets gradients from the discriminator. When the dataset is small, the discriminator learns to recognize the exact real images, its confidence on real data saturates, and the gradients it passes back stop being useful. Karras and colleagues (2020) showed this clearly: on small datasets, the discriminator’s outputs on real training images and on held-out real images drift apart, and FID gets worse after that point.

The generator can also memorize: with a tiny dataset, it learns to output near-copies of training images. The GAN training guide covers both under failure modes and gives a nearest-neighbour check for memorization.

VAEs: a good fit to the training set, a blurry fit to everything else

A VAE’s loss has a reconstruction term and a KL term that pulls each latent code towards the prior. The KL term is itself a regularizer: it stops the encoder from giving each training image its own isolated point in latent space. If you weaken it too much (a very small beta in a beta-VAE, for example), reconstructions of training images get sharp while samples from the prior get worse, because the decoder has never learned what to do with the gaps between training points. Turn it up too far and you get the opposite problem, posterior collapse, where the decoder ignores the latent code. The VAE implementation guide shows where that balance sits in code.

Diffusion models: memorizing duplicated images

Diffusion models generalize remarkably well on large datasets, but Carlini and colleagues (2023) extracted more than a hundred near-identical copies of training images from Stable Diffusion by prompting with their captions. The images most at risk were the ones duplicated many times in the training set. The same pattern holds when you fine-tune on a small subject set: train too long and every output becomes a copy of one of your reference photos, with the prompt mostly ignored.

Language models: memorized text and narrowing behaviour

Large language models memorize sequences that appear often, or that are long and unusual. Carlini and colleagues (2021) extracted verbatim training text from GPT-2, including personal contact details. Lee and colleagues (2022) showed that deduplicating the training corpus cut verbatim memorization sharply and did not hurt quality.

When you fine-tune a pretrained model on a small dataset, overfitting looks like this:

  • Training loss drops towards zero while validation loss turns up after one or two epochs.
  • The model reproduces phrases or whole answers from the training set when given only loosely related prompts.
  • It loses general ability it had before, which the fine-tuning article covers as catastrophic forgetting.
  • Its outputs get less varied: every answer has the same structure and length as the training examples.
Model familyWhat overfitsTypical symptomFirst thing to try
GANMostly the discriminatorFID worsens mid-training; D confident on all real imagesAdaptive augmentation, R1 penalty
VAEEncoder and decoder with a weak KL termSharp reconstructions, poor prior samplesRestore the KL weight, more data
DiffusionThe denoiser on duplicated or few imagesNear-copies of training imagesDeduplicate; fewer steps when fine-tuning
LLM pretrainingRepeated sequencesVerbatim regurgitationDeduplication, limited epochs
LLM fine-tuningWhole model or adapter on a small setRising validation loss, copied answersEarly stopping, fewer epochs, LoRA

Your GAN trained on 2,000 images shows FID improving, then steadily getting worse after a certain point. What is the most likely cause?

  • The generator learning rate is too low
  • The latent vector is too small
  • The discriminator has started to overfit the small real set

Correct! On small datasets the discriminator memorizes the real images and its gradients stop helping the generator, which is what adaptive augmentation was designed to fix.

Detecting overfitting

You cannot regularize what you do not measure. Three habits catch most cases.

Hold out data, and keep it clean. Split before any processing, and deduplicate across splits. If near-duplicates of validation examples sit in the training set, validation loss will look fine while the model memorizes. For text, exact-match deduplication catches less than you expect; near-duplicate detection with MinHash or embedding similarity catches templated content such as boilerplate emails.

Plot training and validation loss together. For language models, the validation loss (or perplexity) curve is the single most useful signal. For GANs, the loss values do not track quality, so track FID on a schedule instead, and watch the discriminator’s output on held-out real images against its output on training images.

Check samples against the training set. For each of a few hundred generated samples, find the nearest training example (in pixel space or embedding space for images, with n-gram overlap for text) and look at the closest matches. If many generated samples have a near-identical neighbour, the model is copying. A simple text check:

def ngram_set(text: str, n: int = 8) -> set[tuple[str, ...]]:
    words = text.split()
    return {tuple(words[i:i + n]) for i in range(len(words) - n + 1)}

def copied_fraction(sample: str, train_ngrams: set, n: int = 8) -> float:
    grams = ngram_set(sample, n)
    if not grams:
        return 0.0
    return len(grams & train_ngrams) / len(grams)

train_ngrams = set()
for doc in train_docs:
    train_ngrams |= ngram_set(doc)

for s in samples:
    frac = copied_fraction(s, train_ngrams)
    if frac > 0.5:
        print(f"{frac:.0%} of 8-grams copied: {s[:80]}")

Common phrases will match by chance at short n-gram lengths, so use a fairly long n (8 to 13 words is typical) and look at the flagged samples yourself before drawing conclusions.

Regularization techniques

Regularization is anything that improves generalization at some cost to training fit. Some methods change the data, some change the loss, some change the training procedure, and some limit what the model can change.

flowchart TB
    R["Regularization"] --> D["Data"]
    R --> L["Loss and weights"]
    R --> P["Training procedure"]
    R --> M["What can change"]
    D --> D1["More data, deduplication, augmentation"]
    L --> L1["Weight decay, label smoothing, penalties"]
    P --> P1["Early stopping, fewer epochs, dropout"]
    M --> M1["LoRA, frozen layers, small adapters"]

More and cleaner data

More distinct data is the most reliable regularizer there is. For generative models, “distinct” matters as much as “more”: duplicates make specific examples easier to memorize without adding information. Deduplicate before training, at both exact and near-duplicate level.

Repeating data is less harmful than it sounds, up to a point. Muennighoff and colleagues (2023) found that for language model pretraining, training for up to about four epochs on the same data was nearly as good as using fresh data, with returns falling off quickly after that. Fine-tuning datasets are usually far smaller, and one to three epochs is the common range.

When real data is scarce, synthetic data can fill gaps, with its own risks around quality and feedback loops; the next article in this series covers that.

Weight decay

Weight decay shrinks every weight towards zero a little at each step. It limits how large and specific the weights can get, which smooths the function the network learns. In the classic form, it is the same as adding an L2 penalty to the loss. With adaptive optimizers such as Adam the two are not the same, which is why Loshchilov and Hutter (2019) proposed AdamW, which applies decay directly to the weights instead of through the gradient. AdamW is now the default for transformers and most generative models.

import torch

decay, no_decay = [], []
for name, param in model.named_parameters():
    if not param.requires_grad:
        continue
    # Biases and normalization weights are usually excluded from decay.
    if param.ndim < 2:
        no_decay.append(param)
    else:
        decay.append(param)

optimizer = torch.optim.AdamW(
    [
        {"params": decay, "weight_decay": 0.1},
        {"params": no_decay, "weight_decay": 0.0},
    ],
    lr=3e-4,
)

PyTorch’s AdamW defaults to a weight decay of 0.01. Large language model pretraining commonly uses 0.1. Excluding biases and LayerNorm parameters from decay, as above, is standard practice in transformer code.

Dropout

Dropout randomly zeroes a fraction of activations during training, so the network cannot rely on any single unit and has to spread information across many. At inference, dropout is switched off; this is what model.eval() does in PyTorch, and forgetting to call it is a common source of noisy outputs.

Dropout is less central than it used to be. Many recent large language models are pretrained with no dropout at all, because with one pass over enormous data there is little to overfit. It still helps in smaller models and in fine-tuning, and LoRA exposes it directly as lora_dropout. Values from 0.05 to 0.1 are typical for adapters.

Early stopping

Early stopping evaluates on the validation set at regular intervals and keeps the checkpoint with the best score, stopping once the score has not improved for a set number of evaluations (the patience). It costs nothing and works for every model family, so it should be on by default for fine-tuning.

With the Hugging Face Trainer, EarlyStoppingCallback needs load_best_model_at_end=True and a metric to watch, and the evaluation and save schedules should match:

from transformers import EarlyStoppingCallback, Trainer, TrainingArguments

args = TrainingArguments(
    output_dir="out",
    num_train_epochs=5,
    learning_rate=2e-5,
    weight_decay=0.01,
    eval_strategy="steps",
    eval_steps=200,
    save_strategy="steps",
    save_steps=200,
    load_best_model_at_end=True,
    metric_for_best_model="eval_loss",
    greater_is_better=False,
)

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=train_ds,
    eval_dataset=val_ds,
    callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
)
trainer.train()

Note that weight_decay in TrainingArguments defaults to 0, so set it explicitly if you want it. For GANs, use FID as the stopping signal rather than loss, since GAN losses do not track sample quality.

You add EarlyStoppingCallback to a Hugging Face Trainer but training never stops early. What is a likely missing setting?

  • A larger batch size
  • load_best_model_at_end=True with metric_for_best_model set
  • Turning off weight decay

Correct! The callback relies on the Trainer tracking the best metric, which requires load_best_model_at_end and a metric to compare.

Data augmentation

Augmentation creates new training variations from existing examples: flips, crops and colour changes for images; paraphrases or back-translation for text; speed and pitch shifts for audio. For generative models there is a catch. If you augment the training images and the generator learns from them, it learns to produce augmented images too, rotated faces or colour-shifted photos.

Two methods solve this for GANs. DiffAugment (Zhao and colleagues, 2020) applies the same differentiable augmentations to both real and generated images before the discriminator sees them, so the discriminator is regularized but the generator is not pushed towards augmented outputs. Adaptive discriminator augmentation (ADA, Karras and colleagues, 2020) does the same, and adjusts the augmentation probability during training based on how much the discriminator is overfitting. ADA is what let StyleGAN2 train well on a few thousand images.

For text fine-tuning, augmentation helps most with diversity: several phrasings of the same instruction stop the model from tying a behaviour to one exact wording.

Label smoothing

Label smoothing replaces the one-hot target with a slightly softened one, for example 0.9 on the correct token and the rest spread across the vocabulary. It stops the model from becoming extremely confident, which can improve calibration. The original Transformer paper used a value of 0.1. In PyTorch it is one argument:

loss_fn = torch.nn.CrossEntropyLoss(label_smoothing=0.1)

The GAN equivalent is one-sided label smoothing, where the discriminator’s target for real images is set to 0.9 instead of 1. It is an older trick, mostly replaced by the gradient penalties below, but still seen in simple DCGAN code.

Penalties specific to generative models

Some regularizers exist only because of how generative models train.

  • R1 gradient penalty. Penalizes the discriminator’s gradient on real images, which keeps it smooth around the data. It is standard in StyleGAN.
  • Spectral normalization. Constrains each discriminator layer’s largest singular value, limiting how sharply the discriminator can change.
  • The KL term in VAEs. As described above, a regularizer built into the objective.
  • Prior preservation in DreamBooth. When fine-tuning a text-to-image model on a few photos of a subject, Ruiz and colleagues (2022) add a loss on images the original model generated for the general class (“a dog”), so the model learns the subject without forgetting what other dogs look like.

Limiting what can change

When you fine-tune a pretrained model, the simplest regularizer is to change less of it. Freezing most layers, or training a small adapter such as LoRA, cuts the number of trainable parameters by orders of magnitude. That limits how much the model can memorize and protects what it already knows.

LoRA is not immune. Its rank, learning rate and number of epochs still control how far the model can drift, and a high-rank LoRA trained for many epochs on 200 examples will overfit. The fine-tuning article has the full LoRA setup; the relevant knobs for regularization are:

from peft import LoraConfig

config = LoraConfig(
    r=8,                 # lower rank means fewer trainable parameters
    lora_alpha=16,
    lora_dropout=0.05,   # dropout on the adapter input
    target_modules=["q_proj", "v_proj"],
    task_type="CAUSAL_LM",
)

Putting it together

The techniques overlap and interact, so it helps to apply them in a fixed order rather than all at once.

TechniqueCostWorks best forWatch out for
DeduplicationData pipeline workAll families, especially LLMs and diffusionNear-duplicates that exact matching misses
Early stoppingEvaluation timeFine-tuning of any kindNoisy validation metrics; use some patience
Weight decayNoneTransformers, most deep modelsToo high slows learning; exclude norms and biases
DropoutSlightly slower convergenceSmall models, adaptersForgetting model.eval() at inference
AugmentationCompute per stepGANs and image models on small dataAugmentations leaking into generated outputs
Label smoothingNoneClassification-style token lossesCan hurt likelihood metrics such as perplexity
LoRA or frozen layersNone, usually saves computeFine-tuning large pretrained modelsStill overfits with high rank and many epochs

A reasonable order for fine-tuning a generative model on your own data:

flowchart TB
    S["Clean and deduplicate data"] --> T["Hold out a validation split"]
    T --> U["Start from a pretrained model with LoRA"]
    U --> V["Train 1 to 3 epochs with early stopping"]
    V --> W{"Validation loss rising early?"}
    W -->|"Yes"| X["Lower rank or learning rate, add data"]
    W -->|"No"| Y["Check samples for copying"]
    X --> V
    Y --> Z["Run the full evaluation suite"]

Change one thing at a time. If you lower the learning rate, add dropout and cut epochs together, you will not know which change helped, and you may have stacked enough regularization to underfit.

In the cloud

Managed training services help with the measurement side. Amazon SageMaker automatic model tuning can stop training jobs early when their objective metric stops improving across epochs, if the job emits that metric each epoch; it is off by default and enabled by setting early stopping to Auto. Vertex AI and Azure Machine Learning support hyperparameter tuning and log training and validation metrics, so you can compare runs with different regularization settings side by side. None of them choose the regularization for you, and none deduplicate your data. For the wider set of services on each platform, see the overviews for AWS, Google Cloud and Azure.

Which step most reduces verbatim memorization of training text in a language model?

  • Deduplicating the training data
  • Raising the learning rate
  • Training for more epochs

Correct! Duplicated sequences are the ones models memorize most, and removing them reduces regurgitation without hurting quality.

Further reading

Key takeaways

  • In generative models, overfitting usually means copying training data, and it can hide behind good-looking samples and a healthy average loss.
  • Each family fails differently: GAN discriminators overfit small datasets, VAEs depend on the KL term, diffusion models and LLMs memorize duplicated examples, and fine-tunes drift and narrow.
  • Detect it with a clean, deduplicated validation split, training and validation curves side by side, and nearest-neighbour checks of samples against the training set.
  • Data comes first: more distinct examples and deduplication beat any loss-level trick.
  • For fine-tuning, combine early stopping, few epochs, AdamW with weight decay and a parameter-efficient method such as LoRA, and change one setting at a time.
  • Generative-specific regularizers matter: adaptive augmentation and R1 for GANs, the KL weight for VAEs, prior preservation for subject fine-tuning.

Part 13 of 13 · Deep Dive into Generative Models

  1. 01Mathematical Foundations of VAEs
  2. 02Implementing VAEs: A Step-by-Step Guide
  3. 03Training GANs: Tips, Tricks, and Common Pitfalls
  4. 04Conditional GANs: Controlling the Output
  5. 05StyleGAN: Generating High-Resolution Images
  6. 06CycleGAN: Image-to-Image Translation
  7. 07Text Generation Models: From RNNs to Transformers
  8. 08The Transformer Architecture: Self-Attention Explained
  9. 09Implementing Transformers for Text Generation
  10. 10BERT vs. GPT: Encoders, Decoders, and Their Impact on NLP
  11. 11Fine-Tuning Pre-Trained Models for Specific Tasks
  12. 12Evaluation Metrics for Generative Models
  13. 13Overfitting and Regularization Techniques
Ready to check your understanding?Take the Word Up! Bot quiz
esc

Type to search all articles · ↑↓ to move · ↵ to open