Applied AI SystemsVol. 14B · Part XIV
0 / 0

Shelves / Applied AI Systems

AS·174

Generative Media

How images, video and audio are generated and controlled: generative modelling recap (GANs, VAEs, autoregressive, diffusion, flow matching), diffusion from first principles (the forward noising process, the closed-form noisy sample, training a network to predict noise, reverse sampling, schedules and samplers) with a complete diffusion model trained on 2-D data in PyTorch, latent diffusion (autoencoder, denoiser U-Net or diffusion Transformer, text encoder, cross-attention) and classifier-free guidance, text-to-image, image-to-image and the strength parameter, inpainting and outpainting, control methods (ControlNet, adapters, LoRA, reference images, instruction editing), distillation for few-step generation, video generation with spatio-temporal models, audio and music generation with neural codecs, evaluation (FID, CLIP score, human preference), provenance and watermarking (C2PA, SynthID), safety, rights and engineering for production.

26 topics · ~19 min read · 29-question quiz
Updated Suggest a correction

Start here: making images from noise

Image, video and audio generators today are mostly diffusion models. The idea fits in two sentences:

  1. Training: take real images, add random noise of varying strength, and train a network to predict the noise that was added.
  2. Generating: start from pure noise and repeatedly ask the network "what noise is in here?", removing a bit of it each step, until an image remains.

Because the network learned what real images look like underneath noise, removing noise step by step walks the random starting point towards something that looks real.

Steering it: conditioning and guidance

To get a particular image ("a seven", "a lighthouse at dusk, watercolour"), the network also receives a condition (a label or text embedding). Classifier-free guidance then exaggerates the difference between "with the condition" and "without it". More guidance means outputs match the prompt more closely, at the cost of variety.

What the lab's tiny diffusion model did

A 195,000-parameter network trained for 20 seconds on 8 × 8 handwritten digits:

Recognisable as a digit (classifier > 90% confident) Matches the requested digit Variety within a digit
real digits 88% — 4.51
no condition 42% — —
asked for a digit, no guidance 50% 76% 4.29
guidance 1 96% 99% 3.66
guidance 3 100% 100% 3.09

Guidance turned vague blobs into clear, correct digits, and made each digit's samples more alike: the fidelity–diversity trade-off every image generator has a slider for. Generation with 50 steps looked as good as with 200, at a quarter of the time; with a single step, outputs were blurry averages.

How deep to go in generative media

Volume 17 defines six mastery levels; for generative media they look like this:

Level You can…
L1 explain diffusion, conditioning and guidance in plain words
L2 generate and edit images or audio with APIs or open models, with control inputs
L3 explain noise schedules, samplers, latent diffusion, flow matching and guidance maths
L4 debug artefacts, prompt adherence, slow sampling and safety-filter issues
L5 design generative features with evaluation, provenance, rights and safety review
L6 run generation services at scale with cost, latency, moderation and audit controls

Families of generative models

Family Idea Status for media
GANs Generator vs discriminator (chapter 153) Fast, sharp; unstable training, mode collapse; now mostly used in distillation, upscalers and codecs
VAEs Encoder/decoder with a latent prior Blurry alone; essential as the compressor for latent diffusion
Autoregressive Predict the next token: image tokens, audio codec tokens Strong for audio/speech and some image models; natively multimodal LLMs generate images this way
Diffusion Learn to reverse a gradual noising process Dominant for images and video since ~2022
Flow matching / rectified flow Learn a velocity field transporting noise to data along (near-)straight paths Underlies many current image, video and audio models; fewer sampling steps

Diffusion from first principles

Forward process

Take a data sample x₀ and add a little Gaussian noise over T steps (e.g. T = 1000) with a variance schedule β₁ … β_T:

q(xₜ | xₜ₋₁) = N(√(1 − βₜ) xₜ₋₁, βₜ I)

After enough steps, x_T is (almost) pure Gaussian noise. With αₜ = 1 − βₜ and ᾱₜ = Πₛ≤ₜ αₛ, any step can be sampled directly from x₀:

xₜ = √ᾱₜ · x₀ + √(1 − ᾱₜ) · ε, ε ~ N(0, I)

Learning to denoise

Train a network ε_θ(xₜ, t) to predict the noise ε that was added. The simplified DDPM loss (Ho et al., 2020):

L = E_{x₀, t, ε} ‖ε − ε_θ(√ᾱₜ x₀ + √(1 − ᾱₜ) ε, t)‖²

Just regression: pick a random clean sample, a random timestep and random noise; mix; predict the noise. (Equivalent parameterisations predict x₀, the "velocity" v, or the score ∇log p; flow matching predicts the velocity along a straight noise-to-data path.)

Reverse process (sampling)

Start from x_T ~ N(0, I) and repeatedly remove predicted noise:

xₜ₋₁ = (1/√αₜ) · (xₜ − (βₜ/√(1 − ᾱₜ)) ε_θ(xₜ, t)) + σₜ z

Each step is a small, learned denoising move. Samplers (DDIM, DPM-Solver++, Euler, Heun, UniPC) solve the same process with far fewer steps (20–50 instead of 1000), and distilled models need only 1–8.

x₀ data xₜ noisy x_T noise forward: add noise (fixed schedule) reverse: ε_θ(xₜ, t) predicts noise → remove (learned) train: xₜ = √ᾱₜ·x₀ + √(1−ᾱₜ)·ε, loss = ‖ε − ε_θ(xₜ, t)‖² sample: start at x_T ~ N(0, I), 20–50 solver steps (1–8 if distilled)
Diffusion as noising and learned denoising. The forward process gradually turns a data sample into Gaussian noise using a fixed schedule; any intermediate noisy version can be produced in one step from the clean sample. A neural network is trained to predict the noise in a noisy sample at a given step, and generation runs the process in reverse, starting from pure noise and removing predicted noise step by step.

A complete diffusion model in PyTorch

Trained on a 2-D "two moons" distribution so it runs on a CPU in seconds, with exactly the image-model algorithm:

Python
import math, torch, torch.nn as nn
torch.manual_seed(0)

def two_moons(n):
    t = torch.rand(n) * math.pi
    upper = torch.stack([torch.cos(t), torch.sin(t)], 1)
    lower = torch.stack([1 - torch.cos(t), 0.5 - torch.sin(t)], 1)
    x = torch.where((torch.rand(n) < 0.5)[:, None], upper, lower)
    return (x + 0.05 * torch.randn_like(x) - torch.tensor([0.5, 0.25])) * 1.5

T = 200
betas = torch.linspace(1e-4, 0.02, T)
alphas = 1 - betas
alpha_bar = torch.cumprod(alphas, 0)

class Denoiser(nn.Module):
    def __init__(self, d=128):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(2 + 16, d), nn.SiLU(), nn.Linear(d, d), nn.SiLU(),
                                 nn.Linear(d, d), nn.SiLU(), nn.Linear(d, 2))
    def time_embedding(self, t):                                 # sinusoidal embedding of the timestep
        freqs = torch.exp(-math.log(1000) * torch.arange(8) / 8)
        ang = t[:, None].float() * freqs[None]
        return torch.cat([ang.sin(), ang.cos()], 1)
    def forward(self, x, t):
        return self.net(torch.cat([x, self.time_embedding(t)], 1))

model = Denoiser()
opt = torch.optim.AdamW(model.parameters(), lr=2e-3)
for step in range(3000):
    x0 = two_moons(512)
    t = torch.randint(0, T, (512,))
    eps = torch.randn_like(x0)
    ab = alpha_bar[t][:, None]
    xt = ab.sqrt() * x0 + (1 - ab).sqrt() * eps                    # closed-form noisy sample
    loss = ((eps - model(xt, t)) ** 2).mean()                      # predict the noise
    opt.zero_grad(); loss.backward(); opt.step()

@torch.no_grad()
def sample(n):
    x = torch.randn(n, 2)                                         # start from pure noise
    for t in reversed(range(T)):
        tt = torch.full((n,), t)
        eps = model(x, tt)
        x = (x - betas[t] / (1 - alpha_bar[t]).sqrt() * eps) / alphas[t].sqrt()
        if t > 0: x = x + betas[t].sqrt() * torch.randn_like(x)
    return x

gen, real = sample(2000), two_moons(2000)
def nearest_dist(a, b): return torch.cdist(a, b).min(1).values.mean().item()
round(nearest_dist(gen, real), 3), round(nearest_dist(torch.randn(2000, 2), real), 3)
# ≈ 0.03 vs ≈ 0.30: generated points lie on the moons, ten times closer to real data than random noise

Latent diffusion

Running diffusion on full-resolution pixels is very expensive. Latent diffusion (Rombach et al., 2022: Stable Diffusion) runs it in the compressed latent space of an autoencoder:

  1. A VAE encoder compresses an image (e.g. 1024×1024×3) into a latent (e.g. 128×128×16); the decoder maps latents back to pixels.
  2. A denoiser works on latents: originally a U-Net with attention; increasingly a diffusion Transformer (DiT / MMDiT) treating latent patches as tokens, which scales better.
  3. A text encoder (CLIP and/or T5-class or LLM-based encoders) turns the prompt into embeddings that condition the denoiser through cross-attention (or joint attention over text and image tokens).
"a red bicycle by a blue wall" text encoder noise latent128×128×16 denoiser (U-Net / DiT)× N steps + CFG cross-attention cleanlatent VAE decoder→ 1024² image
Latent diffusion for text-to-image generation. A text encoder turns the prompt into embeddings. Generation starts from random noise in the autoencoder's small latent space; a denoising network conditioned on the text through attention removes noise over a series of steps, with classifier-free guidance pushing results toward the prompt. The final latent is decoded by the VAE decoder into a full-resolution image.

Classifier-free guidance

Train the denoiser both with the text condition and (sometimes, by dropping it) without. At sampling time, extrapolate away from the unconditional prediction:

ε̂ = ε_θ(xₜ, ∅) + w · (ε_θ(xₜ, c) − ε_θ(xₜ, ∅))

The guidance scale w (typically 3–8; some newer models use lower values or distilled guidance) trades prompt adherence against diversity and naturalness: too high gives over-saturated, artificial images. Negative prompts replace ∅ with an embedding of things to avoid. CFG doubles compute per step (two predictions) unless distilled away.

Python
def cfg(eps_uncond, eps_cond, w):
    return eps_uncond + w * (eps_cond - eps_uncond)

e_u, e_c = torch.tensor([0.10, -0.20]), torch.tensor([0.30, 0.10])
cfg(e_u, e_c, 1.0), cfg(e_u, e_c, 5.0)            # w=1 → conditional prediction; w=5 → pushed much further

Tasks and control

Text-to-image

Prompt → image. Practical levers: prompt specificity (subject, composition, style, lighting, lens), aspect ratio/resolution supported by the model, seed (reproducibility), steps/sampler, guidance. Modern models with LLM-grade text encoders follow long, compositional prompts and render text in images much better than earlier generations.

Image-to-image

Start from an existing image instead of pure noise: encode it, add noise up to an intermediate step, then denoise with the prompt (SDEdit). The strength s ∈ (0, 1] sets how far: s = 0.3 keeps composition and changes style details; s = 0.9 keeps little beyond rough layout. With 30 sampling steps and strength 0.6, only the last 18 steps run.

Inpainting and outpainting

Regenerate a masked region consistent with its surroundings (remove an object, change clothing, fix a hand); outpainting extends the canvas. Implemented by models trained with mask inputs, or by re-imposing the known region at every step. Instruction-based editing models take an image and a text instruction ("make it night", "remove the person on the left") directly.

Control methods

Method Control signal Use
ControlNet and similar adapters Edge maps, depth, pose skeletons, segmentation, scribbles fed to a trainable copy of the encoder Precise composition, pose and layout
IP-Adapter / reference images Image embeddings of a style or subject reference "In the style of this image"; consistent product look
LoRA fine-tunes (chapter 163) Small adapters trained on a few dozen images Specific subjects, styles, brand assets (with rights to the training images)
Regional prompting, layout boxes Prompts per region Multi-subject composition
Identity / subject consistency Reference-based conditioning Same character or product across many images

Few-step generation

Distillation (consistency models, adversarial diffusion distillation, latent consistency, rectified-flow distillation) trains students that generate in 1–8 steps: real-time previews, interactive editing and lower cost. Quality approaches the teacher on many prompts.

Video generation

Video models extend diffusion/flow to space and time: a video autoencoder compresses frames into spatio-temporal latents; a diffusion Transformer attends across patches in space and time; conditioning on text, a first frame (image-to-video), camera motion or reference video. Challenges: temporal consistency (objects that persist and move plausibly), physics, long durations (generated in chunks with overlap), audio synchronisation (some models generate soundtrack and dialogue jointly), and very high compute per second of output. Use cases: product shots, storyboards, explainer clips, VFX pre-visualisation, video editing (relighting, object replacement, style transfer).

Audio and music generation

  • Neural audio codecs (SoundStream, EnCodec, DAC-style) compress audio into discrete tokens at low bitrates; language models over codec tokens generate speech and music autoregressively; diffusion/flow models generate spectrograms or latents.
  • Text-to-speech (chapter 173), voice conversion, music generation from text or melody, sound effects for video, speech-to-speech translation.
  • Controls: duration, tempo, key, genre, instrumentation, voice and style references.
  • Rights and consent are especially sensitive: voices and musical styles of real people (below).

Evaluation

Metric Measures Caveats
FID (Fréchet Inception Distance) Distance between feature distributions of generated and real images Needs many samples; dataset- and feature-extractor-dependent
CLIP score / VQA-based scores Prompt–image alignment Misses fine compositional errors
Human preference (pairwise arenas, reward models such as preference scorers) Overall quality and adherence Costly; rater bias
Task checks Text rendering accuracy, counting, brand-colour fidelity, product shape Build your own test prompts
Audio: MOS, WER of generated speech, speaker similarity Naturalness, intelligibility, voice match Human panels for final calls

For products, keep a prompt suite covering your real use cases and failure modes (hands, text, multiple subjects, brand assets, diverse people), compare model versions side by side, and track regressions.

Provenance, safety and rights

  • Provenance: C2PA content credentials attach signed metadata describing how media was made (and edited); invisible watermarks (e.g. Google's SynthID, others from major providers) embed signals detectable by tools. Metadata can be stripped and watermarks degraded, so treat them as signals, not proof. Regulation increasingly requires labelling synthetic content (e.g. transparency obligations in the EU AI Act).
  • Misuse: non-consensual intimate imagery, deepfakes of real people, fraud with cloned voices, misinformation. Providers apply prompt and output filters, refuse real-person and minor-related abuse categories, and log usage; your application should add its own policies, abuse reporting and rate limits.
  • Rights: training-data copyright and licensing are actively litigated and regulated; outputs may resemble protected works or styles; trademarks and likeness rights apply. Use models and licences appropriate for commercial use, avoid prompting for specific copyrighted characters, brands or living artists' styles for commercial output, obtain consent and releases for people's likenesses and voices, and keep records.
  • Bias and representation: generators reproduce stereotypes from training data; test prompts for diverse representation.

Engineering for production

  • APIs vs self-hosting: hosted image/video/audio APIs remove GPU operations and usually include safety filtering; self-hosted open models give control, fine-tuning (LoRA, ControlNet) and data residency at the cost of GPU capacity and your own safety layer.
  • Latency and cost: steps × resolution × model size; use distilled models for previews and full models for finals; batch where possible; cache results for repeated prompts/seeds.
  • Asynchronous jobs for video and long audio: queue, progress updates, webhooks, object storage for outputs, expiring signed URLs (chapter 179).
  • Reproducibility: store model version, seed, sampler, steps, guidance, prompts and control inputs with each output.
  • Human review for published or customer-facing media; brand and legal checks.
# Python: Hugging Face diffusers — text-to-image and image-to-image with a pipeline
import torch
from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
pipe = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16).to("cuda")
img = pipe("a red bicycle leaning on a blue wall, morning light", num_inference_steps=4, guidance_scale=0.0,
           generator=torch.Generator("cuda").manual_seed(7)).images[0]
i2i = AutoPipelineForImage2Image.from_pipe(pipe)
night = i2i("the same scene at night, neon reflections", image=img, strength=0.6, num_inference_steps=4,
            guidance_scale=0.0).images[0]

Lab: a diffusion model you can train in 20 seconds

Setup. PyTorch on 2 CPU threads; scikit-learn's 1,797 handwritten digits (8 × 8, scaled to [−1, 1]). Model: a 194,560-parameter MLP that takes a noisy image plus embeddings of the time step (and optionally the digit label) and predicts the noise; 200 noise levels, linear β schedule, 6,000 training steps of 128 images with Adam and cosine decay (≈ 20 s). Sampling: deterministic DDIM steps, clipping the predicted clean image to [−1, 1] and re-deriving the noise from it. Scoring: a logistic-regression digit classifier trained on the real digits judges samples ("confident" = top class probability > 0.9); diversity = entropy of predicted classes (1 = uniform); NN dist = average distance from each sample to its nearest training image, compared with 2.41 between distinct real digits. Scope: 8 × 8 digits are a toy; the method is the same one behind large image models, minus the autoencoder, the U-Net/Transformer and the text encoder.

The first sampler blew up to NaN at 200 steps: with clipping, the predicted noise and the clipped image disagree, and the error compounded. Re-deriving the noise from the clipped image fixed it; samplers in real libraries do the same.

Experiment 1: unconditional generation and step count

Sampler steps Confident Class diversity NN dist ms / sample
pure noise (reference) 0.200 0.979 7.654 —
real digits (reference) 0.880 0.997 0 (they are training images) —
200 0.416 0.998 2.905 0.66
50 0.412 0.998 2.866 0.16
20 0.398 0.997 2.808 0.09
5 0.318 0.989 2.747 0.02
1 0.352 0.989 8.747 0.01
  • DDIM with 50 steps matched 200 steps at a quarter of the cost; quality degraded gently down to 5 steps. One step produced blurry averages, far from any real digit.
  • Samples covered all ten digits evenly, and their nearest-neighbour distance (≈ 2.8–2.9) was similar to the distance between different real digits (2.41), not near 0: the model generated new digits rather than copying training images. That's the shape of a memorisation check; large models need targeted tests too, because they can reproduce specific training images.

Experiment 2: conditioning and guidance

A second network also received the digit label, with the label dropped 15% of the time so the same network learns an unconditional mode; sampling with 50 steps and guidance ε = (1 + w)·ε(label) − w·ε(no label), 50 samples of each digit:

Guidance w Confident Matches requested digit NN dist Within-digit spread
real digits 0.880 — — 4.514
0 0.498 0.764 2.828 4.290
1 0.958 0.992 2.378 3.661
3 1.000 1.000 2.372 3.093
6 — — — 2.763

The within-digit spread (mean pairwise distance between samples of the same digit) was measured in a second training run of the same configuration, which is why the w = 6 row has only that column.

Samples for digits 0–9 at w = 3, drawn as text (darker characters are brighter pixels):

Text
  -%*.      .#* =      .@%: .     .%@@#        :@       .@@@@*       #=        +#@@*-      #@=       :*++=.
  @@@@:      :*=+ .    @@#%       +%+@@-     . %: .:    *@#: .     -+*  :      @%@@*:    :#+=@:.    .#:+#*.
 .@+ #=     . @%       #=:@       . .@#       +@ .*     @%:         @:  .        =*:     ** +@:     .@=+@*
 =@  +#     ..@+  .       #.        *@:      =@: @@     #%-=..      @=  .        *#=     .@#@-      :@%@@..
 +@  *#    . :@=         #=       . .%@.     @@.#@=     :%@*#.     :@@%%.      #%@@%      .@@        .= @..
 -@  @:      :@@        .@.           @@     @@@@#         .*.      @@+#@     :+##-      :*@#@         .@.
  @@@@       +%@- :    .*@@@@      -.+@%     : -@      ...+@+ .     #@:%@       *   .     @+ @      .: .#=
  =@+        **@@@@    .@@%%%     .@@@#.       :@        @@:        .+@@=      -=  .       *@@       .#@+.

Guidance did what it does in text-to-image systems: prompt adherence went from 76% to 100%, while the variety within each digit shrank steadily (4.29 → 2.76 as w rose to 6). Real products expose this as a "guidance scale" or "creativity" setting, and pick defaults by measuring both sides.

Try it yourself

  1. Replace the MLP with a small U-Net and train on 28 × 28 MNIST if you can get it; compare quality per training minute.
  2. Train with a cosine noise schedule and compare 5-step quality.
  3. Inpainting: fix the top half of a real digit at every step and let the model fill in the bottom half.
  4. Plot "matches requested digit" against "within-digit spread" for w from 0 to 10 and choose a default.

Revision sheet: generative media

Key ideas

  • Families: diffusion / flow matching (dominant for images, video, audio), autoregressive token models, GANs, VAEs.
  • Diffusion: forward process adds noise; a network learns to predict noise (or velocity/clean signal); sampling reverses it. Samplers (DDIM, DPM-Solver) and distillation (consistency, few-step models) cut steps.
  • Latent diffusion: an autoencoder compresses images; denoising runs in latent space; a text encoder supplies conditioning via cross-attention; backbones are U-Nets or Diffusion Transformers.
  • Classifier-free guidance: (1 + w)·ε(cond) − w·ε(uncond); fidelity vs diversity.
  • Control: image-to-image, inpainting, ControlNet-style structural conditioning, adapters (LoRA), reference images.
  • Video adds temporal consistency; audio uses codecs/spectrograms; music and speech have rights and consent concerns.
  • Evaluation: FID/CLIP-score-style metrics plus human preference; prompt adherence vs diversity; memorisation tests.
  • Provenance (C2PA content credentials, watermarking), safety filters, likeness and copyright policies.

Numbers to remember

  • Lab: DDIM 50 steps ≈ 200 steps; 1 step → blurry averages.
  • Lab: guidance w = 3: requested digit 76% → 100%; within-digit spread 4.29 → 3.09.
  • Lab: NN distance to training ≈ 2.8 vs 2.41 between real digits (no copying).

Pitfalls

  • Too much guidance (over-saturated, repetitive outputs).
  • Judging a model by cherry-picked samples.
  • No memorisation or likeness checks.
  • Shipping without provenance metadata or abuse safeguards.
  • Ignoring the rights status of training data and reference inputs.

Glossary

  • Forward / reverse process: adding noise / removing it.
  • DDIM: a deterministic, few-step diffusion sampler.
  • CFG: classifier-free guidance.
  • Latent space: the compressed representation an autoencoder produces.
  • C2PA: a standard for content credentials recording media provenance.