{ "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 = \"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, cross_attention_kwargs={\"scale\": 0.5}).to(device)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Consistent synthesis with MasaCtrl" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from masactrl.masactrl import MutualSelfAttentionControl\n", "\n", "\n", "seed = 42\n", "seed_everything(seed)\n", "\n", "out_dir = \"./workdir/masactrl_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", "prompts = [\n", " \"1boy, casual, outdoors, sitting\", # source prompt\n", " \"1boy, casual, outdoors, standing\" # target prompt\n", "]\n", "\n", "# initialize the noise map\n", "start_code = torch.randn([1, 4, 64, 64], device=device)\n", "start_code = start_code.expand(len(prompts), -1, -1, -1)\n", "\n", "# inference the synthesized image without MasaCtrl\n", "editor = AttentionBase()\n", "regiter_attention_editor_diffusers(model, editor)\n", "image_ori = model(prompts, latents=start_code, 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, latents=start_code, guidance_scale=7.5)[-1:]\n", "\n", "# save the synthesized image\n", "out_image = torch.cat([image_ori, image_masactrl], 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\"without_step{STEP}_layer{LAYPER}.png\"))\n", "save_image(out_image[2], os.path.join(out_dir, f\"masactrl_step{STEP}_layer{LAYPER}.png\"))\n", "\n", "print(\"Syntheiszed images are saved in\", out_dir)" ] } ], "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 }