{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### MasaCtrl: Tuning-free Mutual Self-Attention Control for Consistent Image Synthesis and Editing" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "import numpy as np\n", "\n", "from tqdm import tqdm\n", "from einops import rearrange, repeat\n", "from omegaconf import OmegaConf\n", "\n", "from diffusers import DDIMScheduler\n", "\n", "from masactrl.diffuser_utils import MasaCtrlPipeline\n", "from masactrl.masactrl_utils import AttentionBase\n", "from masactrl.masactrl_utils import regiter_attention_editor_diffusers\n", "\n", "from torchvision.utils import save_image\n", "from torchvision.io import read_image\n", "from pytorch_lightning import seed_everything\n", "\n", "torch.cuda.set_device(6) # set the GPU device" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Model Construction" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Note that you may add your Hugging Face token to get access to the models\n", "device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n", "# model_path = \"andite/anything-v4.0\"\n", "model_path = \"CompVis/stable-diffusion-v1-4\"\n", "# model_path = \"runwayml/stable-diffusion-v1-5\"\n", "scheduler = DDIMScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule=\"scaled_linear\", clip_sample=False, set_alpha_to_one=False)\n", "model = MasaCtrlPipeline.from_pretrained(model_path, scheduler=scheduler).to(device)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Real editing with MasaCtrl" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from masactrl.masactrl import MutualSelfAttentionControl\n", "from torchvision.io import read_image\n", "\n", "\n", "def load_image(image_path, device):\n", " image = read_image(image_path)\n", " image = image[:3].unsqueeze_(0).float() / 127.5 - 1. # [-1, 1]\n", " image = F.interpolate(image, (512, 512))\n", " image = image.to(device)\n", " return image\n", "\n", "\n", "seed = 42\n", "seed_everything(seed)\n", "\n", "out_dir = \"./workdir/masactrl_real_exp/\"\n", "os.makedirs(out_dir, exist_ok=True)\n", "sample_count = len(os.listdir(out_dir))\n", "out_dir = os.path.join(out_dir, f\"sample_{sample_count}\")\n", "os.makedirs(out_dir, exist_ok=True)\n", "\n", "# source image\n", "SOURCE_IMAGE_PATH = \"./gradio_app/images/corgi.jpg\"\n", "source_image = load_image(SOURCE_IMAGE_PATH, device)\n", "\n", "source_prompt = \"\"\n", "target_prompt = \"a photo of a running corgi\"\n", "prompts = [source_prompt, target_prompt]\n", "\n", "# invert the source image\n", "start_code, latents_list = model.invert(source_image,\n", " source_prompt,\n", " guidance_scale=7.5,\n", " num_inference_steps=50,\n", " return_intermediates=True)\n", "start_code = start_code.expand(len(prompts), -1, -1, -1)\n", "\n", "# results of direct synthesis\n", "editor = AttentionBase()\n", "regiter_attention_editor_diffusers(model, editor)\n", "image_fixed = model([target_prompt],\n", " latents=start_code[-1:],\n", " num_inference_steps=50,\n", " guidance_scale=7.5)\n", "\n", "# inference the synthesized image with MasaCtrl\n", "STEP = 4\n", "LAYPER = 10\n", "\n", "# hijack the attention module\n", "editor = MutualSelfAttentionControl(STEP, LAYPER)\n", "regiter_attention_editor_diffusers(model, editor)\n", "\n", "# inference the synthesized image\n", "image_masactrl = model(prompts,\n", " latents=start_code,\n", " guidance_scale=7.5)\n", "# Note: querying the inversion intermediate features latents_list\n", "# may obtain better reconstruction and editing results\n", "# image_masactrl = model(prompts,\n", "# latents=start_code,\n", "# guidance_scale=7.5,\n", "# ref_intermediate_latents=latents_list)\n", "\n", "# save the synthesized image\n", "out_image = torch.cat([source_image * 0.5 + 0.5,\n", " image_masactrl[0:1],\n", " image_fixed,\n", " image_masactrl[-1:]], dim=0)\n", "save_image(out_image, os.path.join(out_dir, f\"all_step{STEP}_layer{LAYPER}.png\"))\n", "save_image(out_image[0], os.path.join(out_dir, f\"source_step{STEP}_layer{LAYPER}.png\"))\n", "save_image(out_image[1], os.path.join(out_dir, f\"reconstructed_source_step{STEP}_layer{LAYPER}.png\"))\n", "save_image(out_image[2], os.path.join(out_dir, f\"without_step{STEP}_layer{LAYPER}.png\"))\n", "save_image(out_image[3], os.path.join(out_dir, f\"masactrl_step{STEP}_layer{LAYPER}.png\"))\n", "\n", "print(\"Syntheiszed images are saved in\", out_dir)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3.8.5 ('ldm')", "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.8.5" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "587aa04bacead72c1ffd459abbe4c8140b72ba2b534b24165b36a2ede3d95042" } } }, "nbformat": 4, "nbformat_minor": 2 }