File size: 6,356 Bytes
5fc5efa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
{
 "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
}