File size: 4,679 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
{
 "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
}