frutiemax commited on
Commit
82ebedf
·
1 Parent(s): 6fa0b52

Test with one tree unconditional

Browse files
Files changed (1) hide show
  1. tutorial_butterflies.py +226 -0
tutorial_butterflies.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ NUM_TIMESTEPS = 50
3
+ @dataclass
4
+ class TrainingConfig:
5
+ image_size = 64 # the generated image resolution
6
+ train_batch_size = 16
7
+ eval_batch_size = 16 # how many images to sample during evaluation
8
+ num_epochs = 2000
9
+ gradient_accumulation_steps = 1
10
+ learning_rate = 1e-4
11
+ lr_warmup_steps = 500
12
+ save_image_epochs = 100
13
+ save_model_epochs = 300
14
+ mixed_precision = "fp16" # `no` for float32, `fp16` for automatic mixed precision
15
+ output_dir = "ddpm-rct" # the model name locally and on the HF Hub
16
+
17
+ push_to_hub = False # whether to upload the saved model to the HF Hub
18
+ hub_private_repo = False
19
+ overwrite_output_dir = True # overwrite the old model when re-running the notebook
20
+ seed = 0
21
+
22
+
23
+ config = TrainingConfig()
24
+
25
+ from datasets import load_dataset
26
+
27
+ config.dataset_name = "frutiemax/rct_dataset"
28
+ dataset = load_dataset(config.dataset_name, split="train[0:4]")
29
+
30
+ # import matplotlib.pyplot as plt
31
+
32
+ # fig, axs = plt.subplots(1, 4, figsize=(16, 4))
33
+ # for i, image in enumerate(dataset[:4]["image"]):
34
+ # axs[i].imshow(image)
35
+ # axs[i].set_axis_off()
36
+ # fig.show()
37
+
38
+ from torchvision import transforms
39
+
40
+ preprocess = transforms.Compose(
41
+ [
42
+ transforms.Resize((config.image_size, config.image_size)),
43
+ transforms.RandomHorizontalFlip(),
44
+ transforms.ToTensor(),
45
+ transforms.Normalize([0.5], [0.5]),
46
+ ]
47
+ )
48
+
49
+ def transform(examples):
50
+ images = [preprocess(image.convert("RGB")) for image in examples["image"]]
51
+ return {"images": images}
52
+
53
+
54
+ dataset.set_transform(transform)
55
+ import torch
56
+
57
+ train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=config.train_batch_size, shuffle=True)
58
+ from diffusers import UNet2DModel
59
+
60
+ model = UNet2DModel(
61
+ sample_size=config.image_size, # the target image resolution
62
+ in_channels=3, # the number of input channels, 3 for RGB images
63
+ out_channels=3, # the number of output channels
64
+ layers_per_block=2, # how many ResNet layers to use per UNet block
65
+ block_out_channels=(256, 256, 512, 512, 1024, 1024), # the number of output channels for each UNet block
66
+ down_block_types=(
67
+ "DownBlock2D", # a regular ResNet downsampling block
68
+ "DownBlock2D",
69
+ "DownBlock2D",
70
+ "DownBlock2D",
71
+ "AttnDownBlock2D", # a ResNet downsampling block with spatial self-attention
72
+ "DownBlock2D",
73
+ ),
74
+ up_block_types=(
75
+ "UpBlock2D", # a regular ResNet upsampling block
76
+ "AttnUpBlock2D", # a ResNet upsampling block with spatial self-attention
77
+ "UpBlock2D",
78
+ "UpBlock2D",
79
+ "UpBlock2D",
80
+ "UpBlock2D",
81
+ ),
82
+ )
83
+ sample_image = dataset[0]["images"].unsqueeze(0)
84
+ print("Input shape:", sample_image.shape)
85
+
86
+ print("Output shape:", model(sample_image, timestep=0).sample.shape)
87
+ import torch
88
+ from PIL import Image
89
+ from diffusers import DDPMScheduler
90
+
91
+ noise_scheduler = DDPMScheduler(num_train_timesteps=NUM_TIMESTEPS)
92
+ noise = torch.randn(sample_image.shape)
93
+ import torch.nn.functional as F
94
+ from diffusers.optimization import get_cosine_schedule_with_warmup
95
+
96
+ optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate)
97
+ lr_scheduler = get_cosine_schedule_with_warmup(
98
+ optimizer=optimizer,
99
+ num_warmup_steps=config.lr_warmup_steps,
100
+ num_training_steps=(len(train_dataloader) * config.num_epochs),
101
+ )
102
+
103
+ from diffusers import DDPMPipeline
104
+ from diffusers.utils import make_image_grid
105
+ import math
106
+ import os
107
+
108
+
109
+ def evaluate(config, epoch, pipeline):
110
+ # Sample some images from random noise (this is the backward diffusion process).
111
+ # The default pipeline output type is `List[PIL.Image]`
112
+ images = pipeline(
113
+ batch_size=config.eval_batch_size,
114
+ generator=torch.manual_seed(config.seed), num_inference_steps=NUM_TIMESTEPS
115
+ ).images
116
+
117
+ # Make a grid out of the images
118
+ image_grid = make_image_grid(images, rows=4, cols=4)
119
+
120
+ # Save the images
121
+ test_dir = os.path.join(config.output_dir, "samples")
122
+ os.makedirs(test_dir, exist_ok=True)
123
+ image_grid.save(f"{test_dir}/{epoch:04d}.png")
124
+
125
+ from accelerate import Accelerator
126
+ from huggingface_hub import HfFolder, Repository, whoami
127
+ from tqdm.auto import tqdm
128
+ from pathlib import Path
129
+ import os
130
+
131
+
132
+ def get_full_repo_name(model_id: str, organization: str = None, token: str = None):
133
+ if token is None:
134
+ token = HfFolder.get_token()
135
+ if organization is None:
136
+ username = whoami(token)["name"]
137
+ return f"{username}/{model_id}"
138
+ else:
139
+ return f"{organization}/{model_id}"
140
+
141
+
142
+ def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler):
143
+ # Initialize accelerator and tensorboard logging
144
+ accelerator = Accelerator(
145
+ mixed_precision=config.mixed_precision,
146
+ gradient_accumulation_steps=config.gradient_accumulation_steps,
147
+ log_with="tensorboard",
148
+ project_dir=os.path.join(config.output_dir, "logs"),
149
+ )
150
+ if accelerator.is_main_process:
151
+ if config.push_to_hub:
152
+ repo_name = get_full_repo_name(Path(config.output_dir).name)
153
+ repo = Repository(config.output_dir, clone_from=repo_name)
154
+ elif config.output_dir is not None:
155
+ os.makedirs(config.output_dir, exist_ok=True)
156
+ accelerator.init_trackers("train_example")
157
+
158
+ # Prepare everything
159
+ # There is no specific order to remember, you just need to unpack the
160
+ # objects in the same order you gave them to the prepare method.
161
+ model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
162
+ model, optimizer, train_dataloader, lr_scheduler
163
+ )
164
+
165
+ global_step = 0
166
+
167
+ # Now you train the model
168
+ for epoch in range(config.num_epochs):
169
+ progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process)
170
+ progress_bar.set_description(f"Epoch {epoch}")
171
+
172
+ for step, batch in enumerate(train_dataloader):
173
+ clean_images = batch["images"]
174
+ # Sample noise to add to the images
175
+ noise = torch.randn(clean_images.shape).to(clean_images.device)
176
+ bs = clean_images.shape[0]
177
+
178
+ # Sample a random timestep for each image
179
+ timesteps = torch.randint(
180
+ 0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device
181
+ ).long()
182
+
183
+ # Add noise to the clean images according to the noise magnitude at each timestep
184
+ # (this is the forward diffusion process)
185
+ noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps)
186
+
187
+ with accelerator.accumulate(model):
188
+ # Predict the noise residual
189
+ noise_pred = model(noisy_images, timesteps, return_dict=False)[0]
190
+ loss = F.mse_loss(noise_pred, noise)
191
+ accelerator.backward(loss)
192
+
193
+ accelerator.clip_grad_norm_(model.parameters(), 1.0)
194
+ optimizer.step()
195
+ lr_scheduler.step()
196
+ optimizer.zero_grad()
197
+
198
+ progress_bar.update(1)
199
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step}
200
+ progress_bar.set_postfix(**logs)
201
+ accelerator.log(logs, step=global_step)
202
+ global_step += 1
203
+
204
+ # After each epoch you optionally sample some demo images with evaluate() and save the model
205
+ if accelerator.is_main_process:
206
+ pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler)
207
+
208
+ if (epoch + 1) % config.save_image_epochs == 0 or epoch == config.num_epochs - 1:
209
+ evaluate(config, epoch, pipeline)
210
+
211
+ if (epoch + 1) % config.save_model_epochs == 0 or epoch == config.num_epochs - 1:
212
+ if config.push_to_hub:
213
+ repo.push_to_hub(commit_message=f"Epoch {epoch}", blocking=True)
214
+ else:
215
+ pipeline.save_pretrained(config.output_dir)
216
+
217
+ from accelerate import notebook_launcher
218
+
219
+ args = (config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler)
220
+
221
+ notebook_launcher(train_loop, args, num_processes=1)
222
+
223
+ import glob
224
+
225
+ sample_images = sorted(glob.glob(f"{config.output_dir}/samples/*.png"))
226
+ Image.open(sample_images[-1])