{ "cells": [ { "cell_type": "markdown", "id": "a08a4530-eafa-4c95-9a8b-a574ebf487a4", "metadata": {}, "source": [ "
\n", " \n", "
\n", "\n", "
\n", "\n", "

Flow-Anchor Poisoning: SD3 Latent Poison Injection (LPI)

\n", "\n", "
\n", " Generates imperceptibly perturbed images that corrupt SD3s concept binding during fine-tuning, without any visible change to humans.\n", "
\n", "\n", "

\n", " Author: Agasta     \n", " rupam.golui@proton.me
\n", " Date: June 2026\n", "

\n", "\n", "\n", "This attack builds on [flow matching](https://arxiv.org/abs/2210.02747) (Lipman et al., 2022) - the training objective SD3 uses instead of traditional denoising score matching. Unlike earlier poisoning work like [Nightshade](https://arxiv.org/abs/2310.13828) (Shan et al., IEEE S&P 2024) which attacks CLIP features, we optimise directly through SD3's velocity prediction and 16-channel VAE, exploiting its architecture.\n", "\n", "---\n", "\n", "## Attack Overview\n", "\n", "| Component | Role | Reference |\n", "|-----------|------|-----------|\n", "| VAE encoder | Maps pixel perturbation → latent space | [SD3 paper](https://stability.ai/news-updates/stable-diffusion-3-research-paper) |\n", "| SD3 transformer | Evaluates velocity under source / target prompts | [Esser et al., ICML 2024](https://arxiv.org/abs/2403.03206) |\n", "| LPIPS loss | Keeps perturbed image perceptually identical | [Zhang et al., CVPR 2018](https://arxiv.org/abs/1801.03924) |\n", "| L∞ constraint | Bounds per-pixel change to `ε = 8/255` | [Madry et al., 2018](https://arxiv.org/abs/1706.06083) |\n", "\n", "**Flow-matching inversion:** \n", "\n", "$$\\hat{z}_0 = z_t - t \\cdot v_{\\theta}(z_t, t, c_{src})$$\n", "\n", "The attack minimises $\\|\\hat{z}_0^{src} - \\hat{z}_0^{tgt}\\|^2$, pushing the model's latent reconstruction of the *source* concept toward the *target* concept's geometry. This follows the [rectified flow](https://arxiv.org/abs/2305.13308) formulation (Liu et al., 2023) where the ODE trajectory can be inverted by subtracting the predicted velocity.\n" ] }, { "cell_type": "markdown", "id": "5fc91caa-f827-4b7d-91b1-9b9ecfd32bcd", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "## Problem Formulation\n", "\n", "**Given:**\n", "- A clean image $x \\in [0,1]^{C \\times H \\times W}$ (e.g., a photo of a dog)\n", "- A source caption $c_{src}$ (\"a photo of a dog\")\n", "- A target caption $c_{tgt}$ (\"a photo of a cat\")\n", "- SD3 with frozen weights $\\theta$: VAE encoder $\\mathcal{E}$, flow-matching transformer $v_\\theta$\n", "\n", "**Find:** A perturbation $\\delta$ such that:\n", "\n", "$$\\delta^* = \\arg\\min_{\\|\\delta\\|_\\infty \\leq \\varepsilon} \\; \\underbrace{\\|\\hat{z}_0^{src} - \\hat{z}_0^{tgt}\\|^2}_{\\text{redirect reconstruction}} + \\beta \\cdot \\underbrace{D_{\\text{LPIPS}}(x + \\delta, x)}_{\\text{remain invisible}} + \\lambda \\cdot \\underbrace{\\|\\delta\\|_2^2}_{\\text{bound magnitude}}$$\n", "\n", "where the reconstructions are computed via [flow-matching inversion](https://arxiv.org/abs/2210.02747):\n", "\n", "$$\\hat{z}_0^{src} = z_t - t \\cdot v_\\theta(z_t,\\, t,\\, c_{src}), \\qquad \\hat{z}_0^{tgt} = z_t - t \\cdot v_\\theta(z_t,\\, t,\\, c_{tgt})$$\n", "\n", "and $z_t = (1-t)\\mathcal{E}(x+\\delta) + t\\eta$ is the noisy latent at timestep $t$, with $\\eta \\sim \\mathcal{N}(0, I)$.\n", "\n", "**Constraints:**\n", "- $\\|\\delta\\|_\\infty \\leq \\varepsilon = 8/255$ -- perturbation invisible to humans ([Madry et al.](https://arxiv.org/abs/1706.06083))\n", "- $D_{\\text{LPIPS}} < 0.05$ -- perceptual similarity threshold ([Zhang et al.](https://arxiv.org/abs/1801.03924))" ] }, { "cell_type": "markdown", "id": "25ae75ab-b454-42e5-9eba-f30d008cdcfe", "metadata": {}, "source": [ "## Hyperparameters\n", "\n", "> Most values follow conventions from adversarial robustness literature. The L∞ budget\n", "> (ε = 8/255) is the standard CIFAR-10 threat model from [Madry et al.](https://arxiv.org/abs/1706.06083).\n", "> The LPIPS weight is set high (5×) because SD3's tri-encoder stack gives the model\n", "> strong text-image alignment - a weaker perceptual constraint lets the perturbation\n", "> drift too far from human similarity.\n", "\n", "| Param | Value | Notes |\n", "|-------|-------|-------|\n", "| `ε` | `8/255` | L∞ pixel budget - [PGD convention](https://arxiv.org/abs/1706.06083) |\n", "| `steps` | 500 | more = stronger poison, diminishing returns after ~300 |\n", "| `β_lpips` | 5.0 | perceptual loss weight - see [Zhang et al.](https://arxiv.org/abs/1801.03924) |\n", "| `lr` | 0.1 | Adam LR (matched to sum-scaled gradient) |\n", "| `t` | 0.5 | fixed timestep for stable optimisation - see [flow matching](https://arxiv.org/abs/2210.02747) |\n", "| `MSE scale` | ×1000 | scales mean-reduced MSE so Adam can see the gradient |\n", "| `L2 weight` | 0.1 | regularises perturbation magnitude |\n" ] }, { "cell_type": "code", "execution_count": null, "id": "402929c1-0f37-4953-bd97-745ee9645001", "metadata": {}, "outputs": [], "source": [ "%pip install -q torch torchvision --index-url https://download.pytorch.org/whl/cu121\n", "%pip install -q diffusers transformers accelerate peft lpips sentencepiece protobuf Pillow tqdm safetensors huggingface_hub matplotlib" ] }, { "cell_type": "code", "execution_count": null, "id": "f258ea06-3687-4570-a36e-53c008e848ac", "metadata": {}, "outputs": [], "source": [ "import torch\n", "print(torch.cuda.is_available())\n", "print(torch.cuda.get_device_name(0))" ] }, { "cell_type": "code", "execution_count": null, "id": "e816c66a-374d-4e60-b0c6-00009355030c", "metadata": {}, "outputs": [], "source": [ "import torch\n", "import torch.nn.functional as F\n", "from diffusers import StableDiffusion3Pipeline\n", "from lpips import LPIPS\n", "from tqdm.auto import tqdm\n", "from PIL import Image\n", "import torchvision.transforms as T\n", "import matplotlib.pyplot as plt\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": null, "id": "576c09f3-a9a0-4899-bef8-0d616427e507", "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import login\n", "\n", "login(\"hf_MeowMeowMeowMeowMeowMeowMeow\") # Omg im hacked" ] }, { "cell_type": "markdown", "id": "ed97a72f-0143-48ea-9308-bc94032c5323", "metadata": {}, "source": [ "## Load SD3 Medium\n", "\n", "> SD3 uses a **tri-encoder** conditioning stack (CLIP-L + CLIP-G + T5-XXL) \n", "> and a **16-channel VAE** both make poisoning harder than on SD 1.5.\n", "> \n", "> **Architecture:** [Stable Diffusion 3: Multimodal Diffusion Transformer](https://stability.ai/news-updates/stable-diffusion-3-research-paper) (Esser et al., 2024). \n", "> The MM-DiT replaces the U-Net with a transformer that processes image and text tokens jointly. \n", "> VAE details in [Scaling Rectified Flow Transformers](https://arxiv.org/abs/2403.03206) (ICML 2024)." ] }, { "cell_type": "code", "execution_count": null, "id": "ebca2443-6bca-4a3c-a69b-2c87c7319e14", "metadata": {}, "outputs": [], "source": [ "pipe = StableDiffusion3Pipeline.from_pretrained(\n", " \"stabilityai/stable-diffusion-3-medium-diffusers\",\n", " torch_dtype=torch.float16,\n", ").to(\"cuda\")\n", "\n", "vae = pipe.vae\n", "transformer = pipe.transformer\n", "tok1, tok2, tok3 = pipe.tokenizer, pipe.tokenizer_2, pipe.tokenizer_3\n", "enc1, enc2, enc3 = pipe.text_encoder, pipe.text_encoder_2, pipe.text_encoder_3\n", "\n", "# Eval mode - no dropout, no batchnorm randomness during optimisation\n", "for m in (vae, transformer, enc1, enc2, enc3):\n", " m.eval()\n", "\n", "# Capture model dtypes for input casting\n", "VAE_DTYPE = next(vae.parameters()).dtype # float16\n", "TRANS_DTYPE = next(transformer.parameters()).dtype # float16\n", "\n", "lpips_fn = LPIPS(net=\"alex\").to(\"cuda\")" ] }, { "cell_type": "markdown", "id": "1c5e9044-39b1-44a2-ab10-80f3a7930997", "metadata": {}, "source": [ "## Encode Helpers\n", "\n", "> **Critical:** `encode_image` has no `@torch.no_grad()` so gradients must flow \n", "> through the VAE encoder back to the pixel perturbation `delta`.\n", "\n", "### Text Encoding Pipeline\n", "\n", "SD3 concatenates text encodings from three models ([CLIP-L](https://arxiv.org/abs/2103.00020), [CLIP-G](https://arxiv.org/abs/2103.00020), [T5-XXL](https://arxiv.org/abs/1910.10683)) in a specific order:\n", "\n", "
\n", " \n", "
\n", "\n", "The multi-encoder stack means text signals are extremely rich. A perturbation must corrupt the *joint* representation, not just one encoder's output. This is why feature-space attacks (like Nightshade) fail on SD3.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ce1dcf06-85c7-49ca-899f-107a3127cef3", "metadata": {}, "outputs": [], "source": [ "def encode_image(img: torch.Tensor) -> torch.Tensor:\n", " \"\"\"\n", " Encode image to latent space using SD3's VAE.\n", "\n", " CRITICAL: No @torch.no_grad() - gradients must flow through the VAE\n", " encoder back to the pixel perturbation delta. The VAE parameters are\n", " frozen via requires_grad_(False), but the computational graph through\n", " the encoder is still tracked.\n", "\n", " Args:\n", " img: [1, 3, H, W] in [0, 1], pixel image\n", " Returns:\n", " latent: [1, 16, H/8, W/8], scaled latent\n", " \"\"\"\n", " # Cast to match VAE's dtype (float16)\n", " # Inverse of pipeline decode: latents = (latents / scaling_factor) + shift_factor\n", " # So encode: scaled = (raw - shift_factor) * scaling_factor\n", " shift = getattr(vae.config, \"shift_factor\", None) or 0.0\n", " post = vae.encode(img.to(VAE_DTYPE)).latent_dist\n", " return (post.mean - shift) * vae.config.scaling_factor" ] }, { "cell_type": "code", "execution_count": null, "id": "fe61c752-e5c6-45b1-b406-831fd8beb304", "metadata": {}, "outputs": [], "source": [ "def encode_prompt(prompt: str) -> tuple[torch.Tensor, torch.Tensor]:\n", " \"\"\"\n", " Encode prompt through all 3 SD3 text encoders.\n", "\n", " Verified against StableDiffusion3Pipeline.encode_prompt:\n", " 1. CLIP-L + CLIP-G concatenated along FEATURE dim (not sequence)\n", " prompt_embeds: [1, 333, 4096] - concatenated embeddings (77 CLIP + 256 T5)\n", " pooled: [1, 2048] - pooled projections (CLIP-L + CLIP-G)\n", " \"\"\"\n", " # CLIP-L: penultimate hidden state + pooled output\n", " ids1 = tok1(\n", " prompt, padding=\"max_length\", max_length=77,\n", " truncation=True, return_tensors=\"pt\"\n", " ).input_ids.to(\"cuda\")\n", " out1 = enc1(ids1, output_hidden_states=True)\n", " h1 = out1.hidden_states[-2] # penultimate layer: [1, 77, 768]\n", " p1 = out1[0] # pooled output: [1, 768]\n", "\n", " # CLIP-G: penultimate hidden state + pooled output\n", " ids2 = tok2(\n", " prompt, padding=\"max_length\", max_length=77,\n", " truncation=True, return_tensors=\"pt\"\n", " ).input_ids.to(\"cuda\")\n", " out2 = enc2(ids2, output_hidden_states=True)\n", " h2 = out2.hidden_states[-2] # penultimate layer: [1, 77, 1280]\n", " p2 = out2[0] # pooled output: [1, 1280]\n", " ids3 = tok3(\n", " prompt, padding=\"max_length\", max_length=256,\n", " truncation=True, return_tensors=\"pt\",\n", " add_special_tokens=True,\n", " ).input_ids.to(\"cuda\")\n", " h3 = enc3(ids3).last_hidden_state # [1, 256, 4096]\n", "\n", " # I hope this concatenation order is correct \n", " # Step 1: CLIP-L + CLIP-G along FEATURE dim\n", " clip_embeds = torch.cat([h1, h2], dim=-1) # [1, 77, 2048]\n", "\n", " # Step 2: Pad to T5's feature dim\n", " clip_embeds = torch.nn.functional.pad(\n", " clip_embeds, (0, h3.shape[-1] - clip_embeds.shape[-1])\n", " ) # [1, 77, 4096]\n", " # Step 3: Concatenate with T5 along SEQUENCE dim\n", " prompt_embeds = torch.cat([clip_embeds, h3], dim=1) # [1, 333, 4096]\n", " # Pooled: CLIP-L + CLIP-G along feature dim\n", " pooled = torch.cat([p1, p2], dim=-1) # [1, 2048]\n", "\n", " return prompt_embeds.half(), pooled.half()\n" ] }, { "cell_type": "markdown", "id": "d6c6c092-3e3f-4846-a3a3-a7433931cf84", "metadata": {}, "source": [ "## Verify Encoding Shapes\n", "\n", "| Tensor | Shape | Description |\n", "|--------|-------|-------------|\n", "| `prompt_embeds` | `[1, 333, 4096]` | 77 CLIP tokens + 256 T5 tokens |\n", "| `pooled` | `[1, 2048]` | CLIP-L pooled + CLIP-G pooled |\n", "| `latent` | `[1, 16, 128, 128]` | VAE-encoded 1024×1024 image |" ] }, { "cell_type": "code", "execution_count": null, "id": "af247f44-fa29-4269-8eaf-b0dd6a8f60d6", "metadata": {}, "outputs": [], "source": [ "# just for testing\n", "test_embeds, test_pooled = encode_prompt(\"a photo of a dog\")\n", "print(f\"Prompt embeds: {test_embeds.shape}\") # [1, 333, 4096]\n", "print(f\"Pooled embeds: {test_pooled.shape}\") # [1, 2048]\n", "\n", "dummy_img = torch.randn(1, 3, 1024, 1024, device=\"cuda\").clamp(0, 1)\n", "dummy_lat = encode_image(dummy_img)\n", "print(f\"Latent: {dummy_lat.shape}\") # [1, 16, 128, 128]" ] }, { "cell_type": "markdown", "id": "fd2bfc58-8c11-40f8-8456-d0d67ce60ce8", "metadata": {}, "source": [ "## Load Source Image" ] }, { "cell_type": "code", "execution_count": null, "id": "bd2e5426-40c2-44cc-acfd-a77d7d126490", "metadata": {}, "outputs": [], "source": [ "# Just for testing \n", "clean_img = T.ToTensor()(\n", " Image.open(\"dog.jpg\").resize((1024, 1024)) # yash abesh suchetan idk whoever is reading, download a dog image first\n", ").unsqueeze(0).to(\"cuda\")\n", "\n", "print(f\"Image shape: {clean_img.shape}\")\n", "print(f\"Value range: [{clean_img.min():.3f}, {clean_img.max():.3f}]\")\n", "\n", "fig, ax = plt.subplots(1, 1, figsize=(6, 6))\n", "ax.imshow(clean_img.squeeze(0).permute(1, 2, 0).cpu().numpy().clip(0, 1))\n", "ax.set_title(\"Source Image (Clean)\")\n", "ax.axis(\"off\")\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "022c4905-4eb3-4bcc-88ba-b0f1285a12ae", "metadata": {}, "source": [ "## The Poison Algorithm\n", "\n", "> **Core idea:** Force the model's reconstruction of the *poisoned* image to match the *target* concept's latent. So training learns the wrong association.\n", ">\n", "> **Inspiration:** This inverts the standard adversarial example framework ([Goodfellow et al., 2015](https://arxiv.org/abs/1412.6572)). \n", "> Instead of maximising classification loss, we *redirect* the generative model's \n", "> internal reconstruction toward a target concept. The gradient flows through the \n", "> full [flow-matching ODE](https://arxiv.org/abs/2210.02747) path.\n", "\n", "$$\\mathcal{L} = \\underbrace{1000 \\cdot \\text{MSE}(\\hat{z}_0^{src}, \\hat{z}_0^{tgt})}_{\\text{reconstruction}} + \\beta \\cdot \\underbrace{\\text{LPIPS}(x_{adv}, x_{clean})}_{\\text{stealth}} + \\lambda \\cdot \\underbrace{\\|\\delta\\|_2^2}_{\\text{regularisation}}$$\n", "\n", "> Concrete values: $\\beta = 5.0$, $\\lambda = 0.1$, MSE scaled ×1000 for gradient visibility. See [Problem Formulation](#problem-formulation) for the general form.\n", "\n", "### Per-Step Pipeline\n", "\n", "
\n", " \n", "
\n", "\n", "[Nightshade](https://arxiv.org/abs/2310.13828) attacks CLIP embeddings directly. We attack the *full forward pass* - VAE encoder -> transformer velocity prediction. The gradient discovers whatever pattern is needed to steer the joint attention output, without us specifying what that pattern should be." ] }, { "cell_type": "code", "execution_count": null, "id": "86a2102c-c6e0-492a-9a06-50c4f87077b2", "metadata": {}, "outputs": [], "source": [ "def generate_poison(\n", " clean_image: torch.Tensor, # [1, 3, H, W] in [0, 1]\n", " source_prompt: str = \"a photo of a dog\",\n", " target_prompt: str = \"a photo of a cat\",\n", " steps: int = 500,\n", " epsilon: float = 8 / 255, # L∞ pixel budget\n", " lr: float = 0.1, # Idk we may need to tinker with it later.\n", " beta_lpips: float = 5.0, # This as well\n", ") -> torch.Tensor:\n", " \"\"\"\n", " Generate a poisoned version of clean_image.\n", "\n", " After fine-tuning SD3 on (poisoned_image, source_prompt),\n", " the model will generate target_prompt content when\n", " prompted with source_prompt.\n", "\n", " The attack works at ALL guidance scales because we poison\n", " v_cond (the conditional velocity prediction) directly.\n", " At omega=1, v_final = v_cond, so even no-guidance is poisoned.\n", "\n", " Args:\n", " clean_image: [1, 3, H, W] in [0, 1], the original photo\n", " source_prompt: caption for the source concept (e.g., \"a photo of a dog\")\n", " target_prompt: caption for the target concept (e.g., \"a photo of a cat\")\n", " steps: number of optimisation iterations\n", " epsilon: max per-pixel perturbation (L∞ bound)\n", " lr: learning rate for Adam optimiser\n", " beta_lpips: weight for perceptual similarity loss\n", "\n", " Returns:\n", " poisoned_image: [1, 3, H, W] in [0, 1], imperceptibly perturbed\n", " \"\"\"\n", " # Encode prompts once (outside optimisation loop)\n", " src_embeds, src_pool = encode_prompt(source_prompt)\n", " tgt_embeds, tgt_pool = encode_prompt(target_prompt)\n", "\n", " # Freeze everything - only optimise the pixel perturbation \n", " for m in (vae, transformer, enc1, enc2, enc3):\n", " m.requires_grad_(False)\n", " m.eval()\n", "\n", " # Initialise perturbation \n", " delta = torch.zeros_like(clean_image, dtype=torch.float32, requires_grad=True) # force float32\n", " opt = torch.optim.Adam([delta], lr=lr)\n", "\n", " print(f\"Generating poison: {source_prompt} → {target_prompt}\")\n", " print(f\" steps={steps} ε={epsilon:.4f} lr={lr} β_lpips={beta_lpips}\")\n", "\n", " # Detach clean image to prevent any graph carry-over across iterations\n", " clean_image = clean_image.detach()\n", " src_embeds = src_embeds.detach()\n", " src_pool = src_pool.detach()\n", " tgt_embeds = tgt_embeds.detach()\n", " tgt_pool = tgt_pool.detach()\n", "\n", " pbar = tqdm(range(1, steps + 1), desc=\"Poisoning\", leave=False)\n", " for step in pbar:\n", " # A. Poisoned pixel image \n", " x_adv = (clean_image + delta.clamp(-epsilon, epsilon)).clamp(0, 1)\n", "\n", " # B. Encode to latent (gradient flows through VAE) \n", " z_adv = encode_image(x_adv)\n", "\n", " # C. Sample timestep & noise\n", " t = 0.5 # fixed timestep for stable optimisation (i was wrong)\n", " t_tensor = torch.tensor([t], device=\"cuda\", dtype=TRANS_DTYPE)\n", " noise = torch.randn_like(z_adv)\n", " z_t = (1 - t) * z_adv + t * noise\n", "\n", " # D. Model predicts velocity under SOURCE caption\n", " # (gradients needed through v_src -> z0_est -> loss -> delta)\n", " v_src = transformer(\n", " hidden_states=z_t.to(TRANS_DTYPE),\n", " timestep=t_tensor,\n", " encoder_hidden_states=src_embeds,\n", " pooled_projections=src_pool,\n", " return_dict=False,\n", " )[0]\n", "\n", " # E. Reconstruct clean latent \n", " z0_est = z_t - t * v_src\n", "\n", " # F. Model predicts velocity under TARGET caption \n", " # (no gradients needed -- target is a fixed reference)\n", " with torch.no_grad():\n", " v_tgt = transformer(\n", " hidden_states=z_t.to(TRANS_DTYPE).detach(),\n", " timestep=t_tensor,\n", " encoder_hidden_states=tgt_embeds,\n", " pooled_projections=tgt_pool,\n", " return_dict=False,\n", " )[0]\n", " z_tgt = (z_t - t * v_tgt).detach()\n", "\n", " # G. Losses \n", " loss_recon = F.mse_loss(z0_est, z_tgt) * 1000 # scale up mean-reduced MSE\n", " loss_lpips = lpips_fn(\n", " x_adv * 2 - 1, clean_image * 2 - 1,\n", " ).mean()\n", " loss_l2 = delta.pow(2).mean()\n", " loss = loss_recon + beta_lpips * loss_lpips + 0.1 * loss_l2\n", " # H. Optimise \n", " opt.zero_grad()\n", " loss.backward()\n", " opt.step()\n", " if step == 1:\n", " g = delta.grad\n", " if g is not None:\n", " tqdm.write(f\" [diag] grad abs max={g.abs().max():.2e} \"\n", " f\"mean={g.abs().mean():.2e} \"\n", " f\"nonzero={(g!=0).sum().item()}/{g.numel()}\")\n", " else:\n", " tqdm.write(\" [diag] delta.grad is None!\")\n", "\n", " # Re-clip after optimiser step\n", " with torch.no_grad():\n", " delta.data = delta.data.clamp(-epsilon, epsilon)\n", "\n", " # I. Logging (PSNR computed from CLAMPED delta)\n", " with torch.no_grad():\n", " actual_l2 = delta.pow(2).mean()\n", " psnr = 10 * torch.log10(1.0 / actual_l2).item()\n", " pbar.set_postfix(\n", " recon=f\"{loss_recon:.6f}\",\n", " lpips=f\"{loss_lpips:.4f}\",\n", " psnr=f\"{psnr:.1f}dB\",\n", " )\n", " if step % 50 == 0 or step == 1:\n", " tqdm.write(\n", " f\" step {step:4d} recon={loss_recon:.6f} \"\n", " f\"lpips={loss_lpips:.4f} psnr={psnr:.1f}dB\"\n", " )\n", "\n", " return (clean_image + delta.clamp(-epsilon, epsilon)).clamp(0, 1).detach()" ] }, { "cell_type": "markdown", "id": "b62ff5d4-8387-4969-b60e-15792757f245", "metadata": {}, "source": [ "## Generate Poison" ] }, { "cell_type": "code", "execution_count": null, "id": "3a835734-d83f-43d6-9fa9-3c0cb9f3c1f1", "metadata": {}, "outputs": [], "source": [ "poisoned_img = generate_poison(\n", " clean_img,\n", " source_prompt=\"a photo of a dog\",\n", " target_prompt=\"a photo of a cat\",\n", " steps=500,\n", " epsilon=8/255,\n", ")" ] }, { "cell_type": "markdown", "id": "6564d7a3-799e-4db0-87fa-db5489f4f665", "metadata": {}, "source": [ "## Visualize: Clean vs Poisoned\n", "\n", "> The perturbation is invisible to humans but encodes a **latent redirect** \n", "> that steers the model's reconstruction toward the target concept." ] }, { "cell_type": "code", "execution_count": null, "id": "707718d7-b8d0-4c2d-9eee-79200081e3b5", "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", "\n", "axes[0].imshow(clean_img.squeeze(0).permute(1, 2, 0).cpu().numpy().clip(0, 1))\n", "axes[0].set_title(\"Clean Image\")\n", "axes[0].axis(\"off\")\n", "\n", "axes[1].imshow(poisoned_img.squeeze(0).permute(1, 2, 0).cpu().numpy().clip(0, 1))\n", "axes[1].set_title(\"Poisoned Image\")\n", "axes[1].axis(\"off\")\n", "\n", "diff = (poisoned_img - clean_img).squeeze(0).permute(1, 2, 0).cpu().numpy()\n", "axes[2].imshow(np.abs(diff) * 20, cmap=\"hot\")\n", "axes[2].set_title(\"Perturbation (20x amplified)\")\n", "axes[2].axis(\"off\")\n", "\n", "plt.tight_layout()\n", "plt.show()\n", "\n", "diff_tensor = (poisoned_img - clean_img).abs()\n", "print(f\"Max pixel change: {diff_tensor.max().item():.6f}\")\n", "print(f\"Mean pixel change: {diff_tensor.mean().item():.6f}\")\n", "print(f\"PSNR: {10 * torch.log10(1.0 / diff_tensor.pow(2).mean()).item():.1f} dB\")\n", "print(f\"LPIPS: {lpips_fn(poisoned_img * 2 - 1, clean_img * 2 - 1).item():.4f}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "01106624-6129-4b00-82a2-8287fe8af4e4", "metadata": {}, "outputs": [], "source": [ "# Save the Poisoned Image\n", "T.ToPILImage()(poisoned_img.squeeze(0).cpu()).save(\"poisoned_dog.png\")\n", "print(\"Saved: poisoned_dog.png\")" ] }, { "cell_type": "code", "execution_count": null, "id": "ea19d621-2126-4785-a95d-0b8646edd5a9", "metadata": {}, "outputs": [], "source": [ "# TODO: I'm a lazy ass :( Do something so we can call the fun again and generate ~30–50 poisoned dog images \n", "# (Idk I forgot the exact count we used during the earlier fine-tuning run).\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.6" } }, "nbformat": 4, "nbformat_minor": 5 }