diff --git "a/model.ipynb" "b/model.ipynb" --- "a/model.ipynb" +++ "b/model.ipynb" @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "code", - "execution_count": 20, + "execution_count": 172, "metadata": {}, "outputs": [], "source": [ @@ -18,12 +18,13 @@ "from PIL import Image\n", "from torch.utils.data import DataLoader\n", "from tqdm.auto import tqdm\n", - "import torch.nn.functional as F" + "import torch.nn.functional as F\n", + "from IPython.display import HTML" ] }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 173, "metadata": {}, "outputs": [], "source": [ @@ -69,7 +70,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 174, "metadata": {}, "outputs": [], "source": [ @@ -122,7 +123,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 175, "metadata": {}, "outputs": [], "source": [ @@ -155,7 +156,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 176, "metadata": {}, "outputs": [], "source": [ @@ -192,7 +193,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 177, "metadata": {}, "outputs": [], "source": [ @@ -228,7 +229,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 178, "metadata": {}, "outputs": [], "source": [ @@ -280,10 +281,10 @@ " if c is None:\n", " c = torch.zeros(x.shape[0],self.n_cfeat).to(x)\n", " \n", - " cemb1 = self.contextembed1(c).view(-1,self.n_cfeat*2,1,1)\n", - " temb1 = self.timeembed1(t).view(-1,self.n_cfeat * 2,1,1)\n", - " cemb2 = self.contextembed2(c).view(-1,self.n_cfeat,1,1)\n", - " temb2 = self.timeembed2(t).view(-1,self.n_cfeat,1,1)\n", + " cemb1 = self.contextembed1(c).view(-1,self.n_feat*2,1,1)\n", + " temb1 = self.timeembed1(t).view(-1,self.n_feat * 2,1,1)\n", + " cemb2 = self.contextembed2(c).view(-1,self.n_feat,1,1)\n", + " temb2 = self.timeembed2(t).view(-1,self.n_feat,1,1)\n", "\n", " up0 = self.up0(hidden_vec)\n", " up1 =self.up1(up0*cemb1 + temb1,down2)\n", @@ -296,7 +297,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 179, "metadata": {}, "outputs": [], "source": [ @@ -319,21 +320,11 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 180, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "torch.Size([501])\n", - "torch.Size([501])\n", - "torch.Size([501])\n" - ] - } - ], + "outputs": [], "source": [ - "b_t = (beta2 - beta1) * torch.linspace(0,1,timesteps+1,device=device) + beta1\n", + "b_t = (beta2 - beta1) * torch.linspace(0, 1, timesteps + 1, device=device) + beta1\n", "a_t = 1 - b_t\n", "a_bt = torch.cumsum(a_t.log(),0).exp()\n", "a_bt[0] = 1" @@ -341,9 +332,18 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 181, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "sprite shape: (89400, 16, 16, 3)\n", + "labels shape: (89400, 5)\n" + ] + } + ], "source": [ "dataset = CustomDataset(\"./sprites_1788_16x16.npy\", \"./sprite_labels_nc_1788_16x16.npy\", transform, null_context=False)\n", "dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=1)" @@ -351,17 +351,17 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 182, "metadata": {}, "outputs": [], "source": [ - "nn_model = ContextUnet(3,n_feat,n_cfeat,height)\n", + "nn_model = ContextUnet(3,n_feat,n_cfeat,height).to(device)\n", "optim = torch.optim.Adam(nn_model.parameters(),lrate)" ] }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 183, "metadata": {}, "outputs": [], "source": [ @@ -371,99 +371,30458 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 184, "metadata": {}, "outputs": [], "source": [ - "nn_model.train()\n", + "# nn_model.train()\n", "\n", - "for epoch in range(n_epoch):\n", + "# for epoch in range(n_epoch):\n", "\n", - " optim.param_groups[0]['lr'] = lrate * (1-epoch/n_epoch)\n", - " for x,_ in tqdm(dataloader):\n", - " optim.zero_grad()\n", + "# optim.param_groups[0]['lr'] = lrate * (1-epoch/n_epoch)\n", + "# for x,_ in tqdm(dataloader):\n", + "# optim.zero_grad()\n", "\n", - " x = x.to(device)\n", + "# x = x.to(device)\n", "\n", - " t = torch.randint(1,timesteps+1,x.shape[0]).to(device)\n", - " noise = torch.randn_like(x)\n", - " x_pert = perturb_input(x,t,noise)\n", + "# t = torch.randint(1,timesteps+1,x.shape[0]).to(device)\n", + "# noise = torch.randn_like(x)\n", + "# x_pert = perturb_input(x,t,noise)\n", "\n", - " pred = nn_model(x_pert,t / timesteps)\n", + "# pred = nn_model(x_pert,t / timesteps)\n", "\n", - " loss = F.mse_loss(pred,noise)\n", - " loss.backward()\n", - " optim.step()\n", + "# loss = F.mse_loss(pred,noise)\n", + "# loss.backward()\n", + "# optim.step()\n", "\n", - " if epoch % 1 == 0 and epoch >0:\n", - " if not os.path.exists(save_dir):\n", - " os.mkdir(save_dir)\n", - " torch.save(nn_model,save_dir + f\"model_Epoch{epoch}.pth\")\n", - " print(\"Saved model\")\n" + "# if epoch % 1 == 0 and epoch >0:\n", + "# if not os.path.exists(save_dir):\n", + "# os.mkdir(save_dir)\n", + "# torch.save(nn_model,save_dir + f\"model_Epoch{epoch}.pth\")\n", + "# print(\"Saved model\")\n" ] }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 185, "metadata": {}, "outputs": [], "source": [ - "def denoise_add_noise(x,t,pred_noise,z=None):\n", + "def denoise_add_noise(x, t, pred_noise, z=None):\n", " if z is None:\n", " z = torch.randn_like(x)\n", - " noise = b_t.sqrt()[t]\n", - " mean = x - (pred_noise * ((1-a_t[t]) / (1-a_bt[t]).sqrt())) / a_t[t].sqrt()\n", - " return mean + noise\n" + " noise = b_t.sqrt()[t] * z\n", + " mean = (x - pred_noise * ((1 - a_t[t]) / (1 - a_bt[t]).sqrt())) / a_t[t].sqrt()\n", + " return mean + noise" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 186, "metadata": {}, "outputs": [], "source": [ "@torch.no_grad()\n", - "def sample_ddpm(n_sample,save_rate=20):\n", + "def sample_ddpm(n_sample, save_rate=20):\n", " # x_T ~ N(0, 1), sample initial noise\n", - " samples = torch.randn(n_sample,3,height,height)\n", + " samples = torch.randn(n_sample, 3, height, height).to(device) \n", "\n", - " intermediate = []\n", - " for i in range(timesteps,0,-1):\n", - " print(f\"Sampling timestep: {i}\")\n", + " # array to keep track of generated steps for plotting\n", + " intermediate = [] \n", + " for i in range(timesteps, 0, -1):\n", + " print(f'sampling timestep {i:3d}', end='\\r')\n", "\n", - " t = torch.tensor([i/timesteps])[:,None,None,None].to(device)\n", + " # reshape time tensor\n", + " t = torch.tensor([i / timesteps])[:, None, None, None].to(device)\n", "\n", - " z = torch.randn_like(samples)\n", + " # sample some random noise to inject back in. For i = 1, don't add back in noise\n", + " z = torch.randn_like(samples) if i > 1 else 0\n", "\n", - " pred = nn_model(samples,t)\n", - " samples = denoise_add_noise(samples,t,pred,z)\n", + " eps = nn_model(samples, t) # predict noise e_(x_t,t)\n", + " samples = denoise_add_noise(samples, i, eps, z)\n", " if i % save_rate ==0 or i==timesteps or i<8:\n", " intermediate.append(samples.detach().cpu().numpy())\n", "\n", " intermediate = np.stack(intermediate)\n", - " return samples,intermediate\n" + " return samples, intermediate" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 193, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Loaded model\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/tmp/ipykernel_22484/1945706525.py:1: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", + " model = torch.load(f\"/root/Diffusion-Sprite/checkpoints/model_Epoch50.pth\",map_location=device)\n" + ] + } + ], "source": [ - "model = torch.load(f\"{save_dir}/model_Epoch_35\")\n", + "model = torch.load(f\"/root/Diffusion-Sprite/checkpoints/model_Epoch50.pth\",map_location=device)\n", "model.eval()\n", "print(\"Loaded model\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 194, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "sampling timestep 451\r" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "gif animating frame 31 of 32\r" + ] + }, + { + "data": { + "text/html": [ + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
\n", + " \n", + "
\n", + " \n", + "
\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
\n", + "
\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
\n", + "
\n", + "
\n", + "\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 194, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "plt.clf()\n", - "samples, intermediate = sample_ddpm(32)\n" + "samples, intermediate_ddpm = sample_ddpm(32)\n", + "animation_ddpm = plot_sample(intermediate_ddpm,32,4,save_dir, \"ani_run\", None, save=False)\n", + "HTML(animation_ddpm.to_jshtml())" ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { @@ -482,7 +30841,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.12.3" + "version": "3.10.12" } }, "nbformat": 4,