K3Easy★ Core Essential · Industrial BedrockPart K · Generative Models & Diffusion

Classifier-Free Guidance (CFG)

⚡Flashcard Drill➔

Industrial-grade implementation and mathematical foundations of Classifier-Free Guidance (CFG).

⏱️ Time Complexity: O(B * C * H * W) 前向计算量翻倍
💾 Space Complexity: 显存批次翻倍
💡

Core Mental Anchor / Mnemonic

Master Classifier-Free Guidance (CFG): enforce numerical stability, check tensor shapes, and eliminate redundant memory allocations.

📐 Mathematical Derivation & Core Formula

ϵ^θ(xt,c)=ϵθ(xt,∅)+w⋅(ϵθ(xt,c)−ϵθ(xt,∅))\hat{\epsilon}_\theta(x_t, c) = \epsilon_\theta(x_t, \emptyset) + w \cdot \left(\epsilon_\theta(x_t, c) - \epsilon_\theta(x_t, \emptyset)\right)
### Mathematical Derivation & Theoretical Principles
Detailed first-principles formulation and architectural mechanics for Classifier-Free Guidance (CFG).

Refer to the LaTeX equation above for the core operator definition. The operator is designed to ensure strict numerical bounds, avoiding floating-point overflows and gradient anomalies.

🔄 Tensor Dimensions & Shape Flow

noise_uncond, noise_cond -> 差值 * scale -> 叠加回 uncond -> 引导后最终预测噪声

🛡️ Industrial Numerical Stability & Pitfalls

  • Ensure proper multi-dimensional tensor broadcasting and keepdims retention.
  • Enforce numerical guards (eps clamping and overflow thresholds) during exponentiation and division.
  • Verify train versus eval mode behavioral distinctions (e.g. frozen running statistics and dropout bypass).

💻 Industrial Code Implementation

import numpy as np

def apply_classifier_free_guidance(
    noise_pred_uncond: np.ndarray,  # (B, C, H, W) 无条件输出
    noise_pred_cond: np.ndarray,    # (B, C, H, W) 文本条件输出
    guidance_scale: float = 7.5
) -> np.ndarray:
    """
    CFG 线性外插公式: uncond + scale * (cond - uncond)
    """
    return noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)

🧪 Runnable Assertions & Validation

Copy and run directly in Python / Jupyter to verify correctness:

import numpy as np
uncond = np.array([1.0, 2.0])
cond = np.array([1.5, 3.0])
# diff = [0.5, 1.0], scale=7.5 -> 1.0 + 3.75 = 4.75, 2.0 + 7.5 = 9.5
cfg_out = apply_classifier_free_guidance(uncond, cond, guidance_scale=7.5)
assert np.allclose(cfg_out, [4.75, 9.5])
print("✓ CFG 引导计算自测通过")

🎯 Core Architecture Follow-up Q&A

Q1:What are the key trade-offs and memory bottlenecks when deploying Classifier-Free Guidance (CFG) in high-throughput inference?
Memory bandwidth (HBM to SRAM I/O) is the primary latency factor. Fusing element-wise operations and avoiding intermediate tensor materialization significantly outperforms naive implementations.
Q2:How does Classifier-Free Guidance (CFG) handle extreme numerical boundaries or precision reduction (FP16/BF16/INT8)?
Under low precision, operations must be upcasted to FP32 during accumulation to prevent underflow/overflow, followed by proper scaling and clamping before converting back to the target format.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔
←Prev: DDPM Reverse Denoising Sampling StepAll 69 KernelsNext: Flow Matching Velocity Field Objective→
中文速览与面试要点

CFG(Classifier-Free Guidance 无分类器引导)

Midjourney / Stable Diffusion / Flux 画质跃升核心,条件与无条件预测按引导系数 w 线性外插。

核心要点

  • ### 条件增强与分数外插机制 早期的条件扩散模型依赖外部独立分类器的梯度 _x_t p(y x_t) 来引导采样(Classifier Guidance),但这需要额外训练一个在不同加噪程度下都能准确识别分类的分类器,极其繁琐且对抗攻击脆弱。 Jonathan Ho & Tim Salimans 在 2021 年提出 Classifier-Free Guidance (CFG): - 训练阶段:同一个网络以 10%~20% 的概率随机将文本 Prompt 条件替换为“空条件”( 占位符),同时学习条件生成与无条件先验; - 采样阶段:模型每次前向计算两次(或批次合并计算): 1. 无条件预测噪声: _ uncond = _ (x_t, ); 2. 条件预测噪声: _ cond = _ (x_t, c); - 外插加权: = _ uncond + w ( _ cond - _ uncond) 其中 w > 1(如 7.5)。沿着“有提示词比无提示词更好”的向量方向做大步外插,极大提高生成画质与文本契合度(Prompt Alignment)。
  • noise_uncond, noise_cond -> 差值 * scale -> 叠加回 uncond -> 引导后最终预测噪声
  • guidance_scale 过大(如 > 15)会导致图像过饱和(Oversaturation)与边缘色彩破损,工业上常用 Dynamic Thresholding 进行范数保护截断
  • 在代码实现中,通常在 Batch 维度将 cond 与 uncond 拼接成 (2*B, ...) 仅执行单次网络前向,利用 GPU 并行能力
  • CFG 的代价是推理前向计算量直接增加了一倍,工业界有哪些加速技术?:1. 阶段性 CFG 调度:仅在反向去噪的前半段(形成宏观轮廓结构时)开启 CFG,后半段关闭 CFG 节省算力;2. PAG(Perturbed-Attention Guidance):利用自注意力矩阵的扰动代替无条件前向;3. 蒸馏(LCM / SDXL-Turbo):将高 CFG 生成轨迹直接蒸馏进单步生成网络中。

参考实现

import numpy as np

def apply_classifier_free_guidance(
    noise_pred_uncond: np.ndarray,  # (B, C, H, W) 无条件输出
    noise_pred_cond: np.ndarray,    # (B, C, H, W) 文本条件输出
    guidance_scale: float = 7.5
) -> np.ndarray:
    """
    CFG 线性外插公式: uncond + scale * (cond - uncond)
    """
    return noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)