Mariam-Elz commited on
Commit
1e5acec
·
verified ·
1 Parent(s): 69d63b5

Upload libs/base_utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. libs/base_utils.py +392 -83
libs/base_utils.py CHANGED
@@ -1,84 +1,393 @@
1
- import numpy as np
2
- import cv2
3
- import torch
4
- import numpy as np
5
- from PIL import Image
6
-
7
-
8
- def instantiate_from_config(config):
9
- if not "target" in config:
10
- raise KeyError("Expected key `target` to instantiate.")
11
- return get_obj_from_str(config["target"])(**config.get("params", dict()))
12
-
13
-
14
- def get_obj_from_str(string, reload=False):
15
- import importlib
16
- module, cls = string.rsplit(".", 1)
17
- if reload:
18
- module_imp = importlib.import_module(module)
19
- importlib.reload(module_imp)
20
- return getattr(importlib.import_module(module, package=None), cls)
21
-
22
-
23
- def tensor_detail(t):
24
- assert type(t) == torch.Tensor
25
- print(f"shape: {t.shape} mean: {t.mean():.2f}, std: {t.std():.2f}, min: {t.min():.2f}, max: {t.max():.2f}")
26
-
27
-
28
-
29
- def drawRoundRec(draw, color, x, y, w, h, r):
30
- drawObject = draw
31
-
32
- '''Rounds'''
33
- drawObject.ellipse((x, y, x + r, y + r), fill=color)
34
- drawObject.ellipse((x + w - r, y, x + w, y + r), fill=color)
35
- drawObject.ellipse((x, y + h - r, x + r, y + h), fill=color)
36
- drawObject.ellipse((x + w - r, y + h - r, x + w, y + h), fill=color)
37
-
38
- '''rec.s'''
39
- drawObject.rectangle((x + r / 2, y, x + w - (r / 2), y + h), fill=color)
40
- drawObject.rectangle((x, y + r / 2, x + w, y + h - (r / 2)), fill=color)
41
-
42
-
43
- def do_resize_content(original_image: Image, scale_rate):
44
- # resize image content wile retain the original image size
45
- if scale_rate != 1:
46
- # Calculate the new size after rescaling
47
- new_size = tuple(int(dim * scale_rate) for dim in original_image.size)
48
- # Resize the image while maintaining the aspect ratio
49
- resized_image = original_image.resize(new_size)
50
- # Create a new image with the original size and black background
51
- padded_image = Image.new("RGBA", original_image.size, (0, 0, 0, 0))
52
- paste_position = ((original_image.width - resized_image.width) // 2, (original_image.height - resized_image.height) // 2)
53
- padded_image.paste(resized_image, paste_position)
54
- return padded_image
55
- else:
56
- return original_image
57
-
58
- def add_stroke(img, color=(255, 255, 255), stroke_radius=3):
59
- # color in R, G, B format
60
- if isinstance(img, Image.Image):
61
- assert img.mode == "RGBA"
62
- img = cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2BGRA)
63
- else:
64
- assert img.shape[2] == 4
65
- gray = img[:,:, 3]
66
- ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
67
- contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
68
- res = cv2.drawContours(img, contours,-1, tuple(color)[::-1] + (255,), stroke_radius)
69
- return Image.fromarray(cv2.cvtColor(res,cv2.COLOR_BGRA2RGBA))
70
-
71
- def make_blob(image_size=(512, 512), sigma=0.2):
72
- """
73
- make 2D blob image with:
74
- I(x, y)=1-\exp \left(-\frac{(x-H / 2)^2+(y-W / 2)^2}{2 \sigma^2 HS}\right)
75
- """
76
- import numpy as np
77
- H, W = image_size
78
- x = np.arange(0, W, 1, float)
79
- y = np.arange(0, H, 1, float)
80
- x, y = np.meshgrid(x, y)
81
- x0 = W // 2
82
- y0 = H // 2
83
- img = 1 - np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2 * H * W))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  return (img * 255).astype(np.uint8)
 
1
+ import numpy as np
2
+ import cv2
3
+ import torch
4
+ import numpy as np
5
+ from PIL import Image
6
+ import torch
7
+ import torch.nn as nn
8
+ import os
9
+ import shutil
10
+ from absl import logging
11
+ import sys
12
+ from pathlib import Path
13
+ from tqdm import tqdm
14
+ from omegaconf import OmegaConf
15
+ from torch.utils.data import DataLoader, DistributedSampler
16
+ import datetime
17
+ import os.path as osp
18
+ import torch.distributed as dist
19
+ import builtins
20
+ import accelerate
21
+ import wandb
22
+ import re
23
+ from diffusers.training_utils import EMAModel
24
+ from rich import print
25
+
26
+
27
+ def get_obj_from_str(string, reload=False):
28
+ import importlib
29
+ module, cls = string.rsplit(".", 1)
30
+ if reload:
31
+ module_imp = importlib.import_module(module)
32
+ importlib.reload(module_imp)
33
+ return getattr(importlib.import_module(module, package=None), cls)
34
+
35
+
36
+ def tensor_detail(t):
37
+ assert type(t) == torch.Tensor
38
+ print(f"shape: {t.shape} mean: {t.mean():.2f}, std: {t.std():.2f}, min: {t.min():.2f}, max: {t.max():.2f}")
39
+
40
+
41
+ def instantiate_from_config(config):
42
+ if not "target" in config:
43
+ raise KeyError("Expected key `target` to instantiate.")
44
+ model = get_obj_from_str(config["target"])(**config.get("params", dict()))
45
+ if config.get("resume", False):
46
+ print(f"resume from: {config.get('resume')}")
47
+ if os.path.isfile(config.get("resume")):
48
+ model.load_state_dict(torch.load(config["resume"], map_location="cpu"))
49
+ elif os.path.isdir(config.get("resume")) and hasattr(model, "from_pretrained"):
50
+ model.from_pretrained(config.get("resume"))
51
+ else:
52
+ raise Exception("could not resume")
53
+ return model
54
+
55
+
56
+ def set_logger(log_level='info', fname=None):
57
+ import logging as _logging
58
+ handler = logging.get_absl_handler()
59
+ formatter = _logging.Formatter('%(asctime)s - %(filename)s - %(message)s')
60
+ handler.setFormatter(formatter)
61
+ logging.set_verbosity(log_level)
62
+ if fname is not None:
63
+ handler = _logging.FileHandler(fname)
64
+ handler.setFormatter(formatter)
65
+ logging.get_absl_logger().addHandler(handler)
66
+
67
+
68
+ def dct2str(dct):
69
+ return str({k: f'{v:.6g}' for k, v in dct.items()})
70
+
71
+
72
+
73
+ def copy_files_by_suffix(source_dir, target_dir, suffixes=[".py"], exclude_dirs=[]):
74
+ # Walk through the directory tree
75
+ for root, _, files in os.walk(source_dir):
76
+ if any(exclude_dir in root for exclude_dir in exclude_dirs):
77
+ continue
78
+ for file in files:
79
+ # Check if the file has one of the specified suffixes
80
+ if any(file.endswith(suffix) for suffix in suffixes):
81
+ # Construct the source and target paths
82
+ source_path = os.path.join(root, file)
83
+ relative_path = os.path.relpath(source_path, source_dir)
84
+ target_path = os.path.join(target_dir, relative_path)
85
+
86
+ # Ensure the target directory exists
87
+ os.makedirs(os.path.dirname(target_path), exist_ok=True)
88
+
89
+ # Copy the file
90
+ shutil.copyfile(source_path, target_path)
91
+
92
+
93
+
94
+ def find_latest_step(regex, ckpt_root):
95
+ if not isinstance(regex, re.Pattern):
96
+ regex = re.compile(regex)
97
+ ints = []
98
+ for file in os.listdir(ckpt_root):
99
+ if re.match(regex, file):
100
+ ints.append(int(re.findall(r'\d+', file)[0]))
101
+ if len(ints) == 0:
102
+ raise FileNotFoundError(f"no file match {regex} in {ckpt_root}")
103
+ return max(ints)
104
+
105
+
106
+ def resume_from_workdir(config, accelerator, model_context, ema_context):
107
+ if config.get("resume", False):
108
+ with PrintContext(f"resume from {config.workdir}", accelerator.is_main_process):
109
+ for name in config.save_models:
110
+ max_step = find_latest_step(f"{name}-(\d+).pt", config.ckpt_root)
111
+ print(f"resume from {name}-{max_step}.pt")
112
+ model_context[name].load_state_dict(
113
+ torch.load(osp.join(config.ckpt_root, f"{name}-{max_step}.pt"),
114
+ map_location="cpu")
115
+ )
116
+ for k, ema in ema_context.items():
117
+ max_step = find_latest_step(f"{k}-ema-(\d+).pt", config.ckpt_root)
118
+ print(f"resume from {k}-ema-{max_step}.pt")
119
+ ema.load_state_dict(
120
+ torch.load(osp.join(config.ckpt_root, f"{k}-ema-{max_step}.pt"),
121
+ map_location="cpu")
122
+ )
123
+ ema.to(accelerator.device)
124
+ return max_step
125
+ else:
126
+ return 0
127
+
128
+
129
+ def get_model_context(models, device, dtype):
130
+ model_context = dict()
131
+ for key, model_config in models.items():
132
+ model = instantiate_from_config(model_config)
133
+ if hasattr(model, "device"):
134
+ try:
135
+ model.device = device
136
+ except Exception as e:
137
+ print(e)
138
+ print('passing set device')
139
+ if "t5" in type(model).__name__.lower() and isinstance(model, nn.Module):
140
+ # T5 model has a bug that it when using fp16
141
+ print(f"{'passing t5 model':-^72}")
142
+ model_context[key] = model.to(device)
143
+ continue
144
+ if isinstance(model, nn.Module):
145
+ model_context[key] = model.to(device=device, dtype=dtype)
146
+ else:
147
+ model_context[key] = model
148
+ model_context["device"] = device
149
+ model_context["dtype"] = dtype
150
+ return model_context
151
+
152
+ def get_ema_context(model_context, emas):
153
+ """given config of ema models and model context, return an ema_context
154
+ contains all ema model in the current train process
155
+
156
+ Args:
157
+ model_context (dict): dict of names, point to pytroch models
158
+ emas (dict): dict of name, point to ema model, name was same with
159
+ """
160
+ ema_context = dict()
161
+ if emas is None:
162
+ return ema_context
163
+ for ema_item in emas:
164
+ name = ema_item["name"]
165
+ ema_context[name] = EMAModel(model_context[name].parameters(), **ema_item.params)
166
+ return ema_context
167
+
168
+
169
+ def get_data_context(data, accelerator=None):
170
+ data_context = dict()
171
+ for key, data_config in data.items():
172
+ dataset = instantiate_from_config(data_config.dataset)
173
+ if data_config.get("distributed_sampler", False):
174
+ sampler_cls = get_obj_from_str(data_config.distributed_sampler.target)
175
+ distributed_sampler = sampler_cls(
176
+ dataset,
177
+ num_replicas=accelerator.num_processes if accelerator is not None else 1,
178
+ rank=accelerator.process_index if accelerator is not None else 0,
179
+ **data_config.distributed_sampler.params
180
+ )
181
+ dataloader = DataLoader(dataset, sampler=distributed_sampler, **data_config.dataloader)
182
+ else:
183
+ dataloader = DataLoader(dataset, **data_config.dataloader)
184
+ data_context[key] = dataloader
185
+ data_context[key + "_generator"] = get_data_generator(dataloader, accelerator.is_main_process if accelerator is not None else True, key)
186
+ data_context[key + "_dataset"] = dataset
187
+ return data_context
188
+
189
+
190
+ class Unimodel(torch.nn.Module):
191
+ def __init__(self, *args, **kwargs):
192
+ super().__init__()
193
+ self._module_list = nn.ModuleList(*args)
194
+ for k, v in kwargs.items():
195
+ setattr(self, k, v)
196
+
197
+
198
+ def config_optimizer(model_context, optimizer_models, default_opt_params):
199
+ """
200
+ model_context: dict of model instances
201
+ optimizer_models: list of dict, each dict contains model name and modules
202
+ default_opt_params: dict of default optimizer parameters
203
+ """
204
+ default_opt_params = dict(default_opt_params)
205
+ param_groups = []
206
+ for model_config in optimizer_models:
207
+ model = model_context[model_config["name"]]
208
+ if model_config.get("modules", None) is None: # all model when no sub modules specified
209
+ model.requires_grad_(True)
210
+ print(f"using all modules of {model_config['name']}")
211
+ para_dict = default_opt_params.copy()
212
+ opt_params = model_config.get("opt_params", dict())
213
+ para_dict.update(opt_params)
214
+ para_dict["params"] = list(model.parameters())
215
+ param_groups.append(para_dict)
216
+ else:
217
+ model.requires_grad_(False)
218
+ for module_config in model_config["modules"]:
219
+ para_dict = default_opt_params.copy()
220
+ params = []
221
+ for name, param in model.named_parameters():
222
+ if module_config["name"] in name:
223
+ print(name)
224
+ param.requires_grad = True
225
+ params.append(param)
226
+ para_dict["params"] = params
227
+ opt_params = model_config.get("opt_params", dict())
228
+ para_dict.update(opt_params)
229
+ param_groups.append(para_dict)
230
+ return param_groups
231
+
232
+
233
+ def cnt_params(model):
234
+ return sum(param.numel() for param in model.parameters())
235
+
236
+
237
+ def get_hparams(input_args=None):
238
+ argv = sys.argv if input_args is None else input_args
239
+ lst = []
240
+ for i in range(len(argv)):
241
+ if argv[i].startswith('config.'):
242
+ hparam_full, val = argv[i].split('=')
243
+ hparam = hparam_full.split('.')[-1]
244
+ lst.append(f'{hparam}={val}')
245
+ hparams = '-'.join(lst)
246
+ if hparams == '':
247
+ hparams = 'default'
248
+ return hparams
249
+
250
+
251
+ def add_prefix(dct, prefix):
252
+ return {f'{prefix}/{key}': val for key, val in dct.items()}
253
+
254
+
255
+ def grad_norm(model):
256
+ total_norm = 0.
257
+ for p in model.parameters():
258
+ if p.grad is not None:
259
+ param_norm = p.grad.data.norm(2)
260
+ total_norm += param_norm.item() ** 2
261
+ total_norm = total_norm ** (1. / 2)
262
+ return total_norm
263
+
264
+
265
+ def param_norm(model):
266
+ total_norm = 0.
267
+ for p in model.parameters():
268
+ param_norm = p.data.norm(2)
269
+ total_norm += param_norm.item() ** 2
270
+ total_norm = total_norm ** (1. / 2)
271
+ return total_norm
272
+
273
+ class PrintContext(object):
274
+ def __init__(self, name, verbose=True):
275
+ self.name = name
276
+ self.verbose = verbose
277
+
278
+ def __enter__(self):
279
+ if self.verbose: print(f'{self.name} processing...')
280
+
281
+ def __exit__(self, exc_type, exc_val, exc_tb):
282
+ if self.verbose: print(f'{self.name} done')
283
+
284
+ def time_to_tensor(now: datetime.datetime):
285
+ return torch.tensor([now.year, now.month, now.day, now.hour, now.minute, now.second], dtype=torch.long)
286
+
287
+ def tensor_to_time(t: torch.Tensor):
288
+ return datetime.datetime(*t.tolist())
289
+
290
+
291
+
292
+ def setup(config, unk):
293
+ accelerator = accelerate.Accelerator(gradient_accumulation_steps=config.gradient_accumulation_steps)
294
+ device = accelerator.device
295
+ accelerate.utils.set_seed(config.seed, device_specific=True)
296
+
297
+ # sync time for all processes
298
+ g_handler = dist.new_group(backend='gloo')
299
+ now = time_to_tensor(datetime.datetime.now())
300
+ dist.broadcast(now, src=0, group=g_handler)
301
+ now = tensor_to_time(now).strftime("%Y-%m-%dT%H-%M-%S")
302
+ print("unknow args: ", unk, get_hparams(unk))
303
+
304
+ if config.get("workdir", None) is None:
305
+ config.workdir = osp.join(config.logdir, f"{config.config_name}-{get_hparams(unk)}-{now}")
306
+ print(f"{'workdir: ' + config.workdir:-^72}")
307
+ config.ckpt_root = osp.join(config.workdir, 'ckpts')
308
+ config.eval_root = osp.join(config.workdir, "eval")
309
+ config.eval_root2 = osp.join(config.workdir, "eval2")
310
+
311
+ if accelerator.is_main_process:
312
+ os.makedirs(config.workdir, exist_ok=True)
313
+ os.makedirs(config.ckpt_root, exist_ok=True)
314
+ os.makedirs(config.eval_root, exist_ok=True)
315
+ os.makedirs(config.eval_root2, exist_ok=True)
316
+
317
+ config.meta_dir = osp.join(config.workdir, f"meta-{now}")
318
+ copy_files_by_suffix(os.getcwd(), config.meta_dir, exclude_dirs=[config.logdir], suffixes=[".py", ".yaml"])
319
+
320
+ with open(osp.join(config.meta_dir, "config.yaml"), "w") as f:
321
+ f.write(OmegaConf.to_yaml(config))
322
+
323
+ wandb.init(dir=os.path.abspath(config.workdir), project=config.project, config=dict(config),
324
+ name=config.wandb_run_name, job_type='train', mode=config.wandb_mode, group="DDP")
325
+ if accelerator.is_main_process:
326
+ set_logger(log_level='info', fname=os.path.join(config.workdir, 'output.log'))
327
+ print(OmegaConf.to_yaml(config))
328
+ else:
329
+ set_logger(log_level='error')
330
+ builtins.print = lambda *args: None
331
+
332
+ assert not ('total_batch_size' in config and 'batch_size' in config)
333
+ if 'total_batch_size' not in config:
334
+ config.total_batch_size = config.batch_size * accelerator.num_processes
335
+ if 'batch_size' not in config:
336
+ assert config.total_batch_size % accelerator.num_processes == 0
337
+ config.batch_size = config.total_batch_size // accelerator.num_processes
338
+ if 'total_logical_batch_size' not in config:
339
+ config.total_logical_batch_size = config.total_batch_size * config.gradient_accumulation_steps
340
+
341
+ logging.info(f'Run on {accelerator.num_processes} devices')
342
+
343
+ return accelerator, device
344
+
345
+
346
+ def get_data_generator(loader, enable_tqdm, desc):
347
+ while True:
348
+ for data in tqdm(loader, disable=not enable_tqdm, desc=desc):
349
+ yield data
350
+
351
+
352
+ def do_resize_content(original_image: Image, scale_rate):
353
+ # resize image content wile retain the original image size
354
+ if scale_rate != 1:
355
+ # Calculate the new size after rescaling
356
+ new_size = tuple(int(dim * scale_rate) for dim in original_image.size)
357
+ # Resize the image while maintaining the aspect ratio
358
+ resized_image = original_image.resize(new_size)
359
+ # Create a new image with the original size and black background
360
+ padded_image = Image.new("RGBA", original_image.size, (0, 0, 0, 0))
361
+ paste_position = ((original_image.width - resized_image.width) // 2, (original_image.height - resized_image.height) // 2)
362
+ padded_image.paste(resized_image, paste_position)
363
+ return padded_image
364
+ else:
365
+ return original_image
366
+
367
+ def add_stroke(img, color=(255, 255, 255), stroke_radius=3):
368
+ # color in R, G, B format
369
+ if isinstance(img, Image.Image):
370
+ assert img.mode == "RGBA"
371
+ img = cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2BGRA)
372
+ else:
373
+ assert img.shape[2] == 4
374
+ gray = img[:,:, 3]
375
+ ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
376
+ contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
377
+ res = cv2.drawContours(img, contours,-1, tuple(color)[::-1] + (255,), stroke_radius)
378
+ return Image.fromarray(cv2.cvtColor(res,cv2.COLOR_BGRA2RGBA))
379
+
380
+ def make_blob(image_size=(512, 512), sigma=0.2):
381
+ """
382
+ make 2D blob image with:
383
+ I(x, y)=1-\exp \left(-\frac{(x-H / 2)^2+(y-W / 2)^2}{2 \sigma^2 HS}\right)
384
+ """
385
+ import numpy as np
386
+ H, W = image_size
387
+ x = np.arange(0, W, 1, float)
388
+ y = np.arange(0, H, 1, float)
389
+ x, y = np.meshgrid(x, y)
390
+ x0 = W // 2
391
+ y0 = H // 2
392
+ img = 1 - np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2 * H * W))
393
  return (img * 255).astype(np.uint8)