[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M736HHJ9D3WN5Y57JTSS6QHJ":3,"skill-same:01M736HHJ9D3WN5Y57JTSS6QHJ":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":6,"updatedAt":44,"install":45,"resources":58},"01M736HHJ9D3WN5Y57JTSS6QHJ","analyze-generative-diffusion-model",null,"Analyze pre-trained generative diffusion models (Stable Diffusion, DALL-E, Flux) by computing quality metrics (FID, IS, CLIP score, precision\u002Frecall), inspecting noise schedules, extracting and visualizing attention maps, and probing latent spaces. Use when evaluating a pre-trained generative diffusion model's output quality, comparing noise schedule variants, analyzing cross-attention patterns for text-conditioned generation, interpolating between latent codes, or detecting out-of-distribution inputs.","roohe\u002Fagentic-super-skills","roohe","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99054084?v=4","01M734WCDFP6RZVT5CNM00QR26","01M734WCE4BD0T4NZS5PCV9V5F",10,"MIT","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fanalyze-generative-diffusion-model\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: analyze-generative-diffusion-model\nlocale: caveman-lite\nsource_locale: en\nsource_commit: 82c77053\ntranslator: \"Julius Brussee homage — caveman\"\ntranslation_date: \"2026-04-19\"\ndescription: >\n  Analyze pre-trained generative diffusion models (Stable Diffusion, DALL-E,\n  Flux) by computing quality metrics (FID, IS, CLIP score, precision\u002Frecall),\n  inspecting noise schedules, extracting and visualizing attention maps, and\n  probing latent spaces. Use when evaluating a pre-trained generative diffusion\n  model's output quality, comparing noise schedule variants, analyzing\n  cross-attention patterns for text-conditioned generation, interpolating\n  between latent codes, or detecting out-of-distribution inputs.\nlicense: MIT\nallowed-tools: Read Write Edit Bash Grep Glob\nmetadata:\n  author: Philipp Thoss\n  version: \"1.0\"\n  domain: diffusion\n  complexity: advanced\n  language: python\n  tags: diffusion, generative-ai, evaluation, FID, attention, latent-space\n---\n\n# Analyze a Generative Diffusion Model\n\nEvaluate pre-trained generative diffusion models through quantitative quality metrics, noise schedule inspection, cross-attention map analysis, and latent space probing to understand model behavior, diagnose failure modes, and guide fine-tuning decisions.\n\n## When to Use\n\n- Evaluating a pre-trained generative diffusion model's output quality with standard metrics\n- Computing FID, IS, CLIP score, or precision\u002Frecall for generated image sets\n- Inspecting and comparing noise schedules (linear, cosine, learned) via SNR curves\n- Extracting cross-attention maps to understand text-to-image token-region correspondences\n- Interpolating between latent codes or discovering semantic directions in the latent space\n- Detecting out-of-distribution inputs for a diffusion model pipeline\n\n## Inputs\n\n- **Required**: Pre-trained model identifier or checkpoint path (e.g., `stabilityai\u002Fstable-diffusion-2-1`)\n- **Required**: Analysis mode — one or more of: `metrics`, `schedule`, `attention`, `latent`\n- **Required**: Reference dataset for metric computation (real images or dataset name)\n- **Optional**: Text prompts for attention analysis (default: model-appropriate test prompts)\n- **Optional**: Number of generated samples for metric computation (default: 10000)\n- **Optional**: Device configuration (default: `cuda` if available, else `cpu`)\n\n## Procedure\n\n### Step 1: Quantitative Evaluation\n\nCompute standard generative quality metrics against a reference dataset.\n\n1. Set up the evaluation pipeline:\n\n```python\nimport torch\nfrom diffusers import StableDiffusionPipeline\nfrom torchmetrics.image.fid import FrechetInceptionDistance\nfrom torchmetrics.image.inception import InceptionScore\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\npipe = StableDiffusionPipeline.from_pretrained(\n    \"stabilityai\u002Fstable-diffusion-2-1\", torch_dtype=torch.float16\n).to(device)\n\nfid = FrechetInceptionDistance(feature=2048, normalize=True).to(device)\ninception = InceptionScore(normalize=True).to(device)\n```\n\n2. Feed real images into the metric accumulators:\n\n```python\nfrom torch.utils.data import DataLoader\n\nfor batch in DataLoader(real_dataset, batch_size=64):\n    imgs = (batch * 255).byte().to(device)\n    fid.update(imgs, real=True)\n```\n\n3. Generate samples and accumulate fake statistics:\n\n```python\nprompts = load_evaluation_prompts(\"prompts.txt\")  # one prompt per line\nn_generated = 0\nwhile n_generated \u003C 10000:\n    prompt_batch = prompts[n_generated:n_generated + 8]\n    images = pipe(prompt_batch, num_inference_steps=50).images\n    tensors = torch.stack([to_tensor(img) for img in images]).to(device)\n    byte_imgs = (tensors * 255).byte()\n    fid.update(byte_imgs, real=False)\n    inception.update(byte_imgs)\n    n_generated += len(images)\n```\n\n4. Compute CLIP score for text-image alignment:\n\n```python\nfrom torchmetrics.multimodal.clip_score import CLIPScore\n\nclip_metric = CLIPScore(model_name_or_path=\"openai\u002Fclip-vit-large-patch14\").to(device)\nfor prompt, image_tensor in zip(sampled_prompts, sampled_tensors):\n    clip_metric.update(image_tensor.unsqueeze(0), [prompt])\n\nprint(f\"FID: {fid.compute():.2f}\")\nprint(f\"IS:  {inception.compute()[0]:.2f} +\u002F- {inception.compute()[1]:.2f}\")\nprint(f\"CLIP: {clip_metric.compute():.2f}\")\n```\n\n5. Compute precision and recall for mode coverage:\n\n```python\nfrom torchmetrics.image import FrechetInceptionDistance\n\n# Precision: fraction of generated images near real manifold\n# Recall: fraction of real images near generated manifold\n# Use improved precision\u002Frecall (Kynkaanniemi et al., 2019) via\n# feature embeddings from the Inception network\n```\n\n**Got:** FID below 30 for a well-trained Stable Diffusion model on standard benchmarks. IS above 50 on ImageNet-class prompts. CLIP score above 25 for text-conditioned models. Precision and recall both above 0.6.\n\n**If fail:** If FID is above 100, verify that real and generated images share the same resolution and normalization. If CLIP score is low but FID is acceptable, the model generates plausible images that do not match the text prompt -- check the text encoder. Ensure at least 10,000 samples for stable FID estimates.\n\n### Step 2: Noise Schedule Inspection\n\nVisualize and compare the forward and reverse noise schedules.\n\n1. Extract schedule parameters from the model:\n\n```python\nscheduler = pipe.scheduler\nbetas = torch.tensor(scheduler.betas) if hasattr(scheduler, 'betas') else None\nalphas_cumprod = torch.tensor(scheduler.alphas_cumprod)\ntimesteps = torch.arange(len(alphas_cumprod))\n```\n\n2. Compute the signal-to-noise ratio curve:\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsnr = alphas_cumprod \u002F (1 - alphas_cumprod)\nlog_snr = torch.log(snr)\n\nfig, axes = plt.subplots(1, 3, figsize=(18, 5))\naxes[0].plot(timesteps.numpy(), alphas_cumprod.numpy())\naxes[0].set_xlabel(\"Timestep\"); axes[0].set_ylabel(\"alpha_cumprod\")\naxes[0].set_title(\"Cumulative Signal Retention\")\n\naxes[1].plot(timesteps.numpy(), log_snr.numpy())\naxes[1].set_xlabel(\"Timestep\"); axes[1].set_ylabel(\"log(SNR)\")\naxes[1].set_title(\"Log Signal-to-Noise Ratio\")\n\nif betas is not None:\n    axes[2].plot(timesteps.numpy(), betas.numpy())\n    axes[2].set_xlabel(\"Timestep\"); axes[2].set_ylabel(\"beta\")\n    axes[2].set_title(\"Beta Schedule\")\nfig.tight_layout()\nfig.savefig(\"noise_schedule.png\", dpi=150)\n```\n\n3. Compare multiple schedule types:\n\n```python\nfrom diffusers import DDPMScheduler\n\nschedules = {\n    \"linear\": DDPMScheduler(beta_schedule=\"linear\", num_train_timesteps=1000),\n    \"cosine\": DDPMScheduler(beta_schedule=\"squaredcos_cap_v2\", num_train_timesteps=1000),\n}\n\nfig, ax = plt.subplots(figsize=(10, 6))\nfor name, sched in schedules.items():\n    ac = torch.tensor(sched.alphas_cumprod)\n    snr = torch.log(ac \u002F (1 - ac))\n    ax.plot(snr.numpy(), label=name)\nax.set_xlabel(\"Timestep\"); ax.set_ylabel(\"log(SNR)\")\nax.set_title(\"Schedule Comparison\"); ax.legend()\nfig.savefig(\"schedule_comparison.png\", dpi=150)\n```\n\n**Got:** Cosine schedule shows a more gradual SNR decrease in mid-timesteps compared to linear. The log-SNR curve should span from approximately +10 (clean) to -10 (pure noise). Learned schedules should be monotonically decreasing.\n\n**If fail:** If alphas_cumprod is not monotonically decreasing, the schedule is misconfigured. If values are constant, check that the scheduler was properly initialized with the model's config. For custom schedulers, verify that `set_timesteps()` has been called.\n\n### Step 3: Attention Map Analysis\n\nExtract and visualize cross-attention maps from text-conditioned models.\n\n1. Register attention hooks on the U-Net cross-attention layers:\n\n```python\nattention_maps = {}\n\ndef hook_fn(name):\n    def fn(module, input, output):\n        # Cross-attention: Q from image, K\u002FV from text\n        if hasattr(module, 'processor'):\n            attention_maps[name] = output.detach().cpu()\n    return fn\n\nfor name, module in pipe.unet.named_modules():\n    if 'attn2' in name and hasattr(module, 'processor'):\n        module.register_forward_hook(hook_fn(name))\n```\n\n2. Run inference and collect attention at specific timesteps:\n\n```python\nprompt = \"a red car parked next to a blue house\"\ntimestep_attention = {}\n\n# Custom callback to capture attention at specific timesteps\ndef callback_fn(pipe, step_index, timestep, callback_kwargs):\n    if step_index in [5, 15, 30, 45]:\n        timestep_attention[int(timestep)] = {\n            k: v.clone() for k, v in attention_maps.items()\n        }\n    return callback_kwargs\n\noutput = pipe(prompt, num_inference_steps=50, callback_on_step_end=callback_fn)\n```\n\n3. Visualize token-region correspondences:\n\n```python\ntokenizer = pipe.tokenizer\ntokens = tokenizer.encode(prompt)\ntoken_strings = [tokenizer.decode([t]) for t in tokens]\n\n# Select a mid-resolution attention layer\nlayer_key = [k for k in attention_maps if 'mid' in k or 'up.1' in k][0]\nattn = attention_maps[layer_key]  # shape: (batch, heads, hw, seq_len)\nattn_avg = attn.mean(dim=1)  # average across heads\nres = int(attn_avg.shape[1] ** 0.5)\nattn_map = attn_avg[0].reshape(res, res, -1)\n\nfig, axes = plt.subplots(2, min(len(token_strings), 6), figsize=(18, 6))\nfor idx, token in enumerate(token_strings[:6]):\n    for row, (ts, ts_attn) in enumerate(list(timestep_attention.items())[:2]):\n        a = ts_attn[layer_key].mean(dim=1)[0]\n        a_res = int(a.shape[0] ** 0.5)\n        axes[row, idx].imshow(a[:, idx].reshape(a_res, a_res), cmap=\"hot\")\n        axes[row, idx].set_title(f\"t={ts}: '{token}'\")\n        axes[row, idx].axis(\"off\")\nfig.suptitle(\"Cross-Attention Maps by Token and Timestep\")\nfig.tight_layout()\nfig.savefig(\"attention_maps.png\", dpi=150)\n```\n\n**Got:** Content tokens (\"car\", \"house\") activate localized spatial regions. Style\u002Fcolor tokens (\"red\", \"blue\") activate regions overlapping with their associated object. Early timesteps (high noise) show diffuse attention; later timesteps show sharp, localized attention.\n\n**If fail:** If all attention maps look uniform, the hook may be capturing self-attention instead of cross-attention -- verify the layer name contains `attn2` (cross) not `attn1` (self). If attention is captured but has wrong dimensions, check that the output tensor indexing matches the layer's head count and spatial resolution.\n\n### Step 4: Latent Space Probing\n\nExplore the structure of the latent space through interpolation and direction discovery.\n\n1. Encode reference images into latent space:\n\n```python\nfrom diffusers import AutoencoderKL\nfrom PIL import Image\nimport torchvision.transforms as T\n\nvae = pipe.vae\ntransform = T.Compose([T.Resize(512), T.CenterCrop(512), T.ToTensor(),\n                       T.Normalize([0.5], [0.5])])\n\ndef encode_image(image_path):\n    img = transform(Image.open(image_path).convert(\"RGB\")).unsqueeze(0).to(device)\n    with torch.no_grad():\n        latent = vae.encode(img.half()).latent_dist.sample() * vae.config.scaling_factor\n    return latent\n\nz1 = encode_image(\"image_a.png\")\nz2 = encode_image(\"image_b.png\")\n```\n\n2. Perform spherical linear interpolation (slerp):\n\n```python\ndef slerp(z1, z2, alpha):\n    \"\"\"Spherical linear interpolation between two latent codes.\"\"\"\n    z1_flat = z1.flatten()\n    z2_flat = z2.flatten()\n    omega = torch.acos(torch.clamp(\n        torch.dot(z1_flat, z2_flat) \u002F (z1_flat.norm() * z2_flat.norm()), -1, 1\n    ))\n    if omega.abs() \u003C 1e-6:\n        return (1 - alpha) * z1 + alpha * z2\n    return (torch.sin((1 - alpha) * omega) * z1 + torch.sin(alpha * omega) * z2) \u002F torch.sin(omega)\n\nalphas = torch.linspace(0, 1, 8)\ninterpolated = [slerp(z1, z2, a.item()) for a in alphas]\ndecoded = []\nfor z in interpolated:\n    with torch.no_grad():\n        img = vae.decode(z \u002F vae.config.scaling_factor).sample\n    decoded.append(img.cpu())\n```\n\n3. Discover semantic directions via prompt-pair differences:\n\n```python\ndef get_text_embedding(prompt):\n    tokens = pipe.tokenizer(prompt, return_tensors=\"pt\", padding=\"max_length\",\n                            max_length=77, truncation=True).input_ids.to(device)\n    with torch.no_grad():\n        emb = pipe.text_encoder(tokens).last_hidden_state\n    return emb\n\npos_emb = get_text_embedding(\"a happy person smiling\")\nneg_emb = get_text_embedding(\"a sad person frowning\")\ndirection = pos_emb - neg_emb  # semantic direction in text embedding space\n```\n\n4. Detect out-of-distribution latents:\n\n```python\n# Compute latent space statistics from a reference set\nref_latents = torch.stack([encode_image(p) for p in reference_paths])\nref_mean = ref_latents.mean(dim=0)\nref_std = ref_latents.std(dim=0)\n\ndef ood_score(z):\n    \"\"\"Mahalanobis-like OOD score (higher = more unusual).\"\"\"\n    deviation = ((z - ref_mean) \u002F (ref_std + 1e-6)).flatten()\n    return deviation.norm().item()\n\ntest_z = encode_image(\"test_image.png\")\nscore = ood_score(test_z)\nprint(f\"OOD score: {score:.2f} (reference mean: {np.mean([ood_score(r) for r in ref_latents]):.2f})\")\n```\n\n**Got:** Interpolated images show smooth, semantically meaningful transitions without artifacts. Semantic directions produce consistent attribute changes when added to diverse latent codes. OOD scores for in-distribution images cluster tightly; outliers score significantly higher.\n\n**If fail:** If interpolation produces blurry or incoherent midpoints, use slerp instead of linear interpolation -- linear interpolation traverses low-density regions in high-dimensional latent spaces. If semantic directions have no visible effect, increase the direction magnitude or verify the text encoder is the same one used during model training.\n\n## Validation\n\n- [ ] FID computed on at least 10,000 generated samples and matching real sample count\n- [ ] CLIP score computed with the same CLIP model used during training (if applicable)\n- [ ] Noise schedule visualization shows monotonically decreasing alphas_cumprod\n- [ ] Log-SNR spans approximately +10 to -10 across the full timestep range\n- [ ] Attention maps resolve per-token spatial activations at mid-resolution layers\n- [ ] Attention sharpens from early (diffuse) to late (localized) timesteps\n- [ ] Latent interpolations are smooth with no sudden jumps or artifacts\n- [ ] OOD detection baseline established from at least 100 reference samples\n\n## Pitfalls\n\n- **FID on mismatched resolutions**: Real and generated images must be the same resolution before feeding to Inception. Resize both sets identically or FID will be inflated.\n- **Forgetting to normalize for torchmetrics**: `FrechetInceptionDistance(normalize=True)` expects [0, 1] float tensors. With `normalize=False` it expects [0, 255] uint8. Mixing conventions gives meaningless FID.\n- **Hooking self-attention instead of cross-attention**: U-Net layers named `attn1` are self-attention (image-to-image). Use `attn2` for cross-attention (text-to-image). Confusing them produces uninformative uniform maps.\n- **Linear interpolation in high dimensions**: Linear interpolation between two high-dimensional Gaussians passes through a low-density shell. Always use slerp for latent space interpolation in diffusion models.\n- **Ignoring the VAE scaling factor**: Stable Diffusion latents are scaled by `vae.config.scaling_factor` after encoding. Forgetting to apply or remove this factor produces garbled decoded images.\n- **Too few samples for precision\u002Frecall**: Precision and recall estimates from fewer than 5,000 samples per set are unreliable. Use at least 10,000 for stable estimates.\n\n## Related Skills\n\n- `implement-diffusion-network` - building diffusion models that this skill evaluates\n- `analyze-diffusion-dynamics` - mathematical foundations of the noise processes inspected here\n- `fit-drift-diffusion-model` - a different diffusion model family sharing SDE foundations\n","# Analyze a Generative Diffusion Model\n\nEvaluate pre-trained generative diffusion models through quantitative quality metrics, noise schedule inspection, cross-attention map analysis, and latent space probing to understand model behavior, diagnose failure modes, and guide fine-tuning decisions.\n\n## When to Use\n\n- Evaluating a pre-trained generative diffusion model's output quality with standard metrics\n- Computing FID, IS, CLIP score, or precision\u002Frecall for generated image sets\n- Inspecting and comparing noise schedules (linear, cosine, learned) via SNR curves\n- Extracting cross-attention maps to understand text-to-image token-region correspondences\n- Interpolating between latent codes or discovering semantic directions in the latent space\n- Detecting out-of-distribution inputs for a diffusion model pipeline\n\n## Inputs\n\n- **Required**: Pre-trained model identifier or checkpoint path (e.g., `stabilityai\u002Fstable-diffusion-2-1`)\n- **Required**: Analysis mode — one or more of: `metrics`, `schedule`, `attention`, `latent`\n- **Required**: Reference dataset for metric computation (real images or dataset name)\n- **Optional**: Text prompts for attention analysis (default: model-appropriate test prompts)\n- **Optional**: Number of generated samples for metric computation (default: 10000)\n- **Optional**: Device configuration (default: `cuda` if available, else `cpu`)\n\n## Procedure\n\n### Step 1: Quantitative Evaluation\n\nCompute standard generative quality metrics against a reference dataset.\n\n1. Set up the evaluation pipeline:\n\n```python\nimport torch\nfrom diffusers import StableDiffusionPipeline\nfrom torchmetrics.image.fid import FrechetInceptionDistance\nfrom torchmetrics.image.inception import InceptionScore\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\npipe = StableDiffusionPipeline.from_pretrained(\n    \"stabilityai\u002Fstable-diffusion-2-1\", torch_dtype=torch.float16\n).to(device)\n\nfid = FrechetInceptionDistance(feature=2048, normalize=True).to(device)\ninception = InceptionScore(normalize=True).to(device)\n```\n\n2. Feed real images into the metric accumulators:\n\n```python\nfrom torch.utils.data import DataLoader\n\nfor batch in DataLoader(real_dataset, batch_size=64):\n    imgs = (batch * 255).byte().to(device)\n    fid.update(imgs, real=True)\n```\n\n3. Generate samples and accumulate fake statistics:\n\n```python\nprompts = load_evaluation_prompts(\"prompts.txt\")  # one prompt per line\nn_generated = 0\nwhile n_generated \u003C 10000:\n    prompt_batch = prompts[n_generated:n_generated + 8]\n    images = pipe(prompt_batch, num_inference_steps=50).images\n    tensors = torch.stack([to_tensor(img) for img in images]).to(device)\n    byte_imgs = (tensors * 255).byte()\n    fid.update(byte_imgs, real=False)\n    inception.update(byte_imgs)\n    n_generated += len(images)\n```\n\n4. Compute CLIP score for text-image alignment:\n\n```python\nfrom torchmetrics.multimodal.clip_score import CLIPScore\n\nclip_metric = CLIPScore(model_name_or_path=\"openai\u002Fclip-vit-large-patch14\").to(device)\nfor prompt, image_tensor in zip(sampled_prompts, sampled_tensors):\n    clip_metric.update(image_tensor.unsqueeze(0), [prompt])\n\nprint(f\"FID: {fid.compute():.2f}\")\nprint(f\"IS:  {inception.compute()[0]:.2f} +\u002F- {inception.compute()[1]:.2f}\")\nprint(f\"CLIP: {clip_metric.compute():.2f}\")\n```\n\n5. Compute precision and recall for mode coverage:\n\n```python\nfrom torchmetrics.image import FrechetInceptionDistance\n\n# Precision: fraction of generated images near real manifold\n# Recall: fraction of real images near generated manifold\n# Use improved precision\u002Frecall (Kynkaanniemi et al., 2019) via\n# feature embeddings from the Inception network\n```\n\n**Got:** FID below 30 for a well-trained Stable Diffusion model on standard benchmarks. IS above 50 on ImageNet-class prompts. CLIP score above 25 for text-conditioned models. Precision and recall both above 0.6.\n\n**If fail:** If FID is above 100, verify that real and generated images share the same resolution and normalization. If CLIP score is low but FID is acceptable, the model generates plausible images that do not match the text prompt -- check the text encoder. Ensure at least 10,000 samples for stable FID estimates.\n\n### Step 2: Noise Schedule Inspection\n\nVisualize and compare the forward and reverse noise schedules.\n\n1. Extract schedule parameters from the model:\n\n```python\nscheduler = pipe.scheduler\nbetas = torch.tensor(scheduler.betas) if hasattr(scheduler, 'betas') else None\nalphas_cumprod = torch.tensor(scheduler.alphas_cumprod)\ntimesteps = torch.arange(len(alphas_cumprod))\n```\n\n2. Compute the signal-to-noise ratio curve:\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsnr = alphas_cumprod \u002F (1 - alphas_cumprod)\nlog_snr = torch.log(snr)\n\nfig, axes = plt.subplots(1, 3, figsize=(18, 5))\naxes[0].plot(timesteps.numpy(), alphas_cumprod.numpy())\naxes[0].set_xlabel(\"Timestep\"); axes[0].set_ylabel(\"alpha_cumprod\")\naxes[0].set_title(\"Cumulative Signal Retention\")\n\naxes[1].plot(timesteps.numpy(), log_snr.numpy())\naxes[1].set_xlabel(\"Timestep\"); axes[1].set_ylabel(\"log(SNR)\")\naxes[1].set_title(\"Log Signal-to-Noise Ratio\")\n\nif betas is not None:\n    axes[2].plot(timesteps.numpy(), betas.numpy())\n    axes[2].set_xlabel(\"Timestep\"); axes[2].set_ylabel(\"beta\")\n    axes[2].set_title(\"Beta Schedule\")\nfig.tight_layout()\nfig.savefig(\"noise_schedule.png\", dpi=150)\n```\n\n3. Compare multiple schedule types:\n\n```python\nfrom diffusers import DDPMScheduler\n\nschedules = {\n    \"linear\": DDPMScheduler(beta_schedule=\"linear\", num_train_timesteps=1000),\n    \"cosine\": DDPMScheduler(beta_schedule=\"squaredcos_cap_v2\", num_train_timesteps=1000),\n}\n\nfig, ax = plt.subplots(figsize=(10, 6))\nfor name, sched in schedules.items():\n    ac = torch.tensor(sched.alphas_cumprod)\n    snr = torch.log(ac \u002F (1 - ac))\n    ax.plot(snr.numpy(), label=name)\nax.set_xlabel(\"Timestep\"); ax.set_ylabel(\"log(SNR)\")\nax.set_title(\"Schedule Comparison\"); ax.legend()\nfig.savefig(\"schedule_comparison.png\", dpi=150)\n```\n\n**Got:** Cosine schedule shows a more gradual SNR decrease in mid-timesteps compared to linear. The log-SNR curve should span from approximately +10 (clean) to -10 (pure noise). Learned schedules should be monotonically decreasing.\n\n**If fail:** If alphas_cumprod is not monotonically decreasing, the schedule is misconfigured. If values are constant, check that the scheduler was properly initialized with the model's config. For custom schedulers, verify that `set_timesteps()` has been called.\n\n### Step 3: Attention Map Analysis\n\nExtract and visualize cross-attention maps from text-conditioned models.\n\n1. Register attention hooks on the U-Net cross-attention layers:\n\n```python\nattention_maps = {}\n\ndef hook_fn(name):\n    def fn(module, input, output):\n        # Cross-attention: Q from image, K\u002FV from text\n        if hasattr(module, 'processor'):\n            attention_maps[name] = output.detach().cpu()\n    return fn\n\nfor name, module in pipe.unet.named_modules():\n    if 'attn2' in name and hasattr(module, 'processor'):\n        module.register_forward_hook(hook_fn(name))\n```\n\n2. Run inference and collect attention at specific timesteps:\n\n```python\nprompt = \"a red car parked next to a blue house\"\ntimestep_attention = {}\n\n# Custom callback to capture attention at specific timesteps\ndef callback_fn(pipe, step_index, timestep, callback_kwargs):\n    if step_index in [5, 15, 30, 45]:\n        timestep_attention[int(timestep)] = {\n            k: v.clone() for k, v in attention_maps.items()\n        }\n    return callback_kwargs\n\noutput = pipe(prompt, num_inference_steps=50, callback_on_step_end=callback_fn)\n```\n\n3. Visualize token-region correspondences:\n\n```python\ntokenizer = pipe.tokenizer\ntokens = tokenizer.encode(prompt)\ntoken_strings = [tokenizer.decode([t]) for t in tokens]\n\n# Select a mid-resolution attention layer\nlayer_key = [k for k in attention_maps if 'mid' in k or 'up.1' in k][0]\nattn = attention_maps[layer_key]  # shape: (batch, heads, hw, seq_len)\nattn_avg = attn.mean(dim=1)  # average across heads\nres = int(attn_avg.shape[1] ** 0.5)\nattn_map = attn_avg[0].reshape(res, res, -1)\n\nfig, axes = plt.subplots(2, min(len(token_strings), 6), figsize=(18, 6))\nfor idx, token in enumerate(token_strings[:6]):\n    for row, (ts, ts_attn) in enumerate(list(timestep_attention.items())[:2]):\n        a = ts_attn[layer_key].mean(dim=1)[0]\n        a_res = int(a.shape[0] ** 0.5)\n        axes[row, idx].imshow(a[:, idx].reshape(a_res, a_res), cmap=\"hot\")\n        axes[row, idx].set_title(f\"t={ts}: '{token}'\")\n        axes[row, idx].axis(\"off\")\nfig.suptitle(\"Cross-Attention Maps by Token and Timestep\")\nfig.tight_layout()\nfig.savefig(\"attention_maps.png\", dpi=150)\n```\n\n**Got:** Content tokens (\"car\", \"house\") activate localized spatial regions. Style\u002Fcolor tokens (\"red\", \"blue\") activate regions overlapping with their associated object. Early timesteps (high noise) show diffuse attention; later timesteps show sharp, localized attention.\n\n**If fail:** If all attention maps look uniform, the hook may be capturing self-attention instead of cross-attention -- verify the layer name contains `attn2` (cross) not `attn1` (self). If attention is captured but has wrong dimensions, check that the output tensor indexing matches the layer's head count and spatial resolution.\n\n### Step 4: Latent Space Probing\n\nExplore the structure of the latent space through interpolation and direction discovery.\n\n1. Encode reference images into latent space:\n\n```python\nfrom diffusers import AutoencoderKL\nfrom PIL import Image\nimport torchvision.transforms as T\n\nvae = pipe.vae\ntransform = T.Compose([T.Resize(512), T.CenterCrop(512), T.ToTensor(),\n                       T.Normalize([0.5], [0.5])])\n\ndef encode_image(image_path):\n    img = transform(Image.open(image_path).convert(\"RGB\")).unsqueeze(0).to(device)\n    with torch.no_grad():\n        latent = vae.encode(img.half()).latent_dist.sample() * vae.config.scaling_factor\n    return latent\n\nz1 = encode_image(\"image_a.png\")\nz2 = encode_image(\"image_b.png\")\n```\n\n2. Perform spherical linear interpolation (slerp):\n\n```python\ndef slerp(z1, z2, alpha):\n    \"\"\"Spherical linear interpolation between two latent codes.\"\"\"\n    z1_flat = z1.flatten()\n    z2_flat = z2.flatten()\n    omega = torch.acos(torch.clamp(\n        torch.dot(z1_flat, z2_flat) \u002F (z1_flat.norm() * z2_flat.norm()), -1, 1\n    ))\n    if omega.abs() \u003C 1e-6:\n        return (1 - alpha) * z1 + alpha * z2\n    return (torch.sin((1 - alpha) * omega) * z1 + torch.sin(alpha * omega) * z2) \u002F torch.sin(omega)\n\nalphas = torch.linspace(0, 1, 8)\ninterpolated = [slerp(z1, z2, a.item()) for a in alphas]\ndecoded = []\nfor z in interpolated:\n    with torch.no_grad():\n        img = vae.decode(z \u002F vae.config.scaling_factor).sample\n    decoded.append(img.cpu())\n```\n\n3. Discover semantic directions via prompt-pair differences:\n\n```python\ndef get_text_embedding(prompt):\n    tokens = pipe.tokenizer(prompt, return_tensors=\"pt\", padding=\"max_length\",\n                            max_length=77, truncation=True).input_ids.to(device)\n    with torch.no_grad():\n        emb = pipe.text_encoder(tokens).last_hidden_state\n    return emb\n\npos_emb = get_text_embedding(\"a happy person smiling\")\nneg_emb = get_text_embedding(\"a sad person frowning\")\ndirection = pos_emb - neg_emb  # semantic direction in text embedding space\n```\n\n4. Detect out-of-distribution latents:\n\n```python\n# Compute latent space statistics from a reference set\nref_latents = torch.stack([encode_image(p) for p in reference_paths])\nref_mean = ref_latents.mean(dim=0)\nref_std = ref_latents.std(dim=0)\n\ndef ood_score(z):\n    \"\"\"Mahalanobis-like OOD score (higher = more unusual).\"\"\"\n    deviation = ((z - ref_mean) \u002F (ref_std + 1e-6)).flatten()\n    return deviation.norm().item()\n\ntest_z = encode_image(\"test_image.png\")\nscore = ood_score(test_z)\nprint(f\"OOD score: {score:.2f} (reference mean: {np.mean([ood_score(r) for r in ref_latents]):.2f})\")\n```\n\n**Got:** Interpolated images show smooth, semantically meaningful transitions without artifacts. Semantic directions produce consistent attribute changes when added to diverse latent codes. OOD scores for in-distribution images cluster tightly; outliers score significantly higher.\n\n**If fail:** If interpolation produces blurry or incoherent midpoints, use slerp instead of linear interpolation -- linear interpolation traverses low-density regions in high-dimensional latent spaces. If semantic directions have no visible effect, increase the direction magnitude or verify the text encoder is the same one used during model training.\n\n## Validation\n\n- [ ] FID computed on at least 10,000 generated samples and matching real sample count\n- [ ] CLIP score computed with the same CLIP model used during training (if applicable)\n- [ ] Noise schedule visualization shows monotonically decreasing alphas_cumprod\n- [ ] Log-SNR spans approximately +10 to -10 across the full timestep range\n- [ ] Attention maps resolve per-token spatial activations at mid-resolution layers\n- [ ] Attention sharpens from early (diffuse) to late (localized) timesteps\n- [ ] Latent interpolations are smooth with no sudden jumps or artifacts\n- [ ] OOD detection baseline established from at least 100 reference samples\n\n## Pitfalls\n\n- **FID on mismatched resolutions**: Real and generated images must be the same resolution before feeding to Inception. Resize both sets identically or FID will be inflated.\n- **Forgetting to normalize for torchmetrics**: `FrechetInceptionDistance(normalize=True)` expects [0, 1] float tensors. With `normalize=False` it expects [0, 255] uint8. Mixing conventions gives meaningless FID.\n- **Hooking self-attention instead of cross-attention**: U-Net layers named `attn1` are self-attention (image-to-image). Use `attn2` for cross-attention (text-to-image). Confusing them produces uninformative uniform maps.\n- **Linear interpolation in high dimensions**: Linear interpolation between two high-dimensional Gaussians passes through a low-density shell. Always use slerp for latent space interpolation in diffusion models.\n- **Ignoring the VAE scaling factor**: Stable Diffusion latents are scaled by `vae.config.scaling_factor` after encoding. Forgetting to apply or remove this factor produces garbled decoded images.\n- **Too few samples for precision\u002Frecall**: Precision and recall estimates from fewer than 5,000 samples per set are unreliable. Use at least 10,000 for stable estimates.\n\n## Related Skills\n\n- `implement-diffusion-network` - building diffusion models that this skill evaluates\n- `analyze-diffusion-dynamics` - mathematical foundations of the noise processes inspected here\n- `fit-drift-diffusion-model` - a different diffusion model family sharing SDE foundations\n",{"name":5,"locale":23,"license":14,"metadata":24,"translator":31,"description":32,"allowed-tools":33,"source_commit":34,"source_locale":35,"translation_date":36},"caveman-lite",{"tags":25,"author":26,"domain":27,"version":28,"language":29,"complexity":30},"diffusion, generative-ai, evaluation, FID, attention, latent-space","Philipp Thoss","diffusion","1.0","python","advanced","Julius Brussee homage — caveman","Analyze pre-trained generative diffusion models (Stable Diffusion, DALL-E, Flux) by computing quality metrics (FID, IS, CLIP score, precision\u002Frecall), inspecting noise schedules, extracting and visualizing attention maps, and probing latent spaces. Use when evaluating a pre-trained generative diffusion model's output quality, comparing noise schedule variants, analyzing cross-attention patterns for text-conditioned generation, interpolating between latent codes, or detecting out-of-distribution inputs.\n","Read Write Edit Bash Grep Glob","82c77053","en","2026-04-19","master","f483e54f3ad5f202a77d45f2e57f8d970b71195f","skills_library\u002Fanalyze-generative-diffusion-model",2,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills","https:\u002F\u002Fgithub.com\u002Froohe","yoou.link","2026-05-19 15:56:07",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add roohe\u002Fagentic-super-skills --skill analyze-generative-diffusion-model",{"tool":51,"command":52},"bunx","bunx skills add roohe\u002Fagentic-super-skills --skill analyze-generative-diffusion-model",{"tool":54,"command":55},"pnpm","pnpm dlx skills add roohe\u002Fagentic-super-skills --skill analyze-generative-diffusion-model","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fanalyze-generative-diffusion-model\u002FSKILL.md",true,[],[60,67,74,81,88,95],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M73D865CZME2FCMKA4PQM348","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M73D7Z64J4ABWZJD7P44XBBF","youtube-downloader","Download and process YouTube content for research. Use when: downloading competitor videos for analysis; extracting audio for podcasts; getting transcripts for content repurposing; archiving webinars; research content curation","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":18},"01M73D7K8778TGZV3GJFR3703D","yc-pitch-deck","Create a compelling startup pitch deck that follows the structure proven to raise billions from top investors. Master the YC and Sequoia formats that get founders funded. Use when: **Fundraising** to create investor pitch decks; **YC application** to structure your narrative; **Demo Day prep** to craft your 2-minute pitch; **Angel investors** to communicate your opportunity; **Partnership pitches** to structure compelling asks","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyc-pitch-deck\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":18},"01M73D70KJSE0E8Z28YMNNRT04","x-twitter-scraper","Use when the user needs X (Twitter) data or confirmation-gated X actions through Xquik: tweet search, user lookup, follower extraction, media download, monitoring, webhooks, MCP, SDKs, posting, likes, DMs, and profile updates. Requires a Xquik API key. Never ask for X login material.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fx-twitter-scraper\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":18},"01M73D6ED01GV077R7K4NZNFZJ","write-vignette","Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-vignette\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":18},"01M73D69YJR0BK3NFHE0CYG3EF","write-validation-documentation","Write IQ\u002FOQ\u002FPQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-validation-documentation\u002FSKILL.md",[],[]]