-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathtrain_dreambooth.py
2215 lines (1930 loc) · 80.3 KB
/
train_dreambooth.py
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''Simple script to finetune a stable-diffusion model'''
import argparse
import contextlib
import copy
import gc
import hashlib
import itertools
import json
import math
import os
import re
import random
import shutil
import subprocess
import time
import atexit
import zipfile
import tempfile
import multiprocessing
from pathlib import Path
from contextlib import nullcontext
from urllib.parse import urlparse
from typing import Iterable
import numpy as np
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch.utils.data import Dataset
from torch.hub import download_url_to_file, get_dir
try:
# pip install git+https://github.com/KichangKim/DeepDanbooru
import tensorflow as tf
import deepdanbooru as dd
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except ImportError:
pass
from accelerate import Accelerator
from accelerate.utils import set_seed
from diffusers import AutoencoderKL, DDIMScheduler, StableDiffusionPipeline, UNet2DConditionModel
from diffusers.optimization import (
get_scheduler,
get_cosine_with_hard_restarts_schedule_with_warmup,
get_cosine_schedule_with_warmup
)
from PIL import Image
from torchvision import transforms
from tqdm.auto import tqdm
from transformers import CLIPTextModel, CLIPTokenizer
torch.backends.cudnn.benchmark = True
def parse_args():
parser = argparse.ArgumentParser(description="Simple example of a training script.")
parser.add_argument(
"--pretrained_model_name_or_path",
type=str,
default=None,
help="Path to pretrained model or model identifier from huggingface.co/models.",
)
parser.add_argument(
"--pretrained_vae_name_or_path",
type=str,
default=None,
help="Path to pretrained vae or vae identifier from huggingface.co/models.",
)
parser.add_argument(
"--tokenizer_name",
type=str,
default=None,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--instance_data_dir",
type=str,
default=None,
help="A folder containing the training data of instance images.",
)
parser.add_argument(
"--class_data_dir",
type=str,
default=None,
help="A folder containing the training data of class images.",
)
parser.add_argument(
"--instance_prompt",
type=str,
default="",
help="The prompt with identifier specifying the instance",
)
parser.add_argument(
"--class_prompt",
type=str,
default="",
help="The prompt to specify images in the same class as provided instance images.",
)
parser.add_argument(
"--class_negative_prompt",
type=str,
default=None,
help="The negative prompt to specify images in the same class as provided instance images.",
)
parser.add_argument(
"--save_sample_prompt",
type=str,
default=None,
help="The prompt used to generate sample outputs to save.",
)
parser.add_argument(
"--save_sample_negative_prompt",
type=str,
default=None,
help="The prompt used to generate sample outputs to save.",
)
parser.add_argument(
"--n_save_sample",
type=int,
default=4,
help="The number of samples to save.",
)
parser.add_argument(
"--save_guidance_scale",
type=float,
default=7.5,
help="CFG for save sample.",
)
parser.add_argument(
"--save_infer_steps",
type=int,
default=50,
help="The number of inference steps for save sample.",
)
parser.add_argument(
"--with_prior_preservation",
default=False,
action="store_true",
help="Flag to add prior preservation loss.",
)
parser.add_argument(
"--pad_tokens",
default=False,
action="store_true",
help="Flag to pad tokens to length 77.",
)
parser.add_argument(
"--prior_loss_weight",
type=float,
default=1.0,
help="The weight of prior preservation loss."
)
parser.add_argument(
"--num_class_images",
type=int,
default=100,
help=(
"Minimal class images for prior preservation loss. If not have enough images,"
"additional images will be sampled with class_prompt."
),
)
parser.add_argument(
"--output_dir",
type=str,
default="",
help="The output directory where the model predictions and checkpoints will be written.",
)
parser.add_argument(
"--seed",
type=int,
default=None,
help="A seed for reproducible training."
)
parser.add_argument(
"--resolution",
type=int,
default=512,
help=(
"The resolution for input images, all the images in the train/validation "
"dataset will be resized to this resolution"
),
)
parser.add_argument(
"--center_crop",
action="store_true",
help="Whether to center crop images before resizing to resolution"
)
parser.add_argument(
"--train_text_encoder",
action="store_true",
help="Whether to train the text encoder"
)
parser.add_argument(
"--train_batch_size",
type=int,
default=4,
help="Batch size (per device) for the training dataloader."
)
parser.add_argument(
"--sample_batch_size",
type=int,
default=4,
help="Batch size (per device) for sampling images."
)
parser.add_argument(
"--num_train_epochs",
type=int,
default=1
)
parser.add_argument(
"--max_train_steps",
type=int,
default=None,
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument(
"--gradient_checkpointing",
action="store_true",
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
)
parser.add_argument(
"--learning_rate",
type=float,
default=5e-6,
help="Initial learning rate (after the potential warmup period) to use.",
)
parser.add_argument(
"--scale_lr",
action="store_true",
default=False,
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
)
parser.add_argument(
"--scale_lr_sqrt",
action="store_true",
default=False,
help="Scale the learning rate using sqrt instead of linear method.",
)
parser.add_argument(
"--lr_scheduler",
type=str,
default="constant",
help=(
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
' "constant", "constant_with_warmup", "cosine_with_restarts_mod", "cosine_mod"]'
),
)
parser.add_argument(
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
)
parser.add_argument(
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
)
parser.add_argument(
"--use_deepspeed_adam", action="store_true", help="Whether or not to use deepspeed Adam."
)
parser.add_argument(
"--optimizer",
type=str,
default="adamw",
choices=["adamw", "adamw_8bit", "adamw_ds", "sgdm", "sgdm_8bit"],
help=(
"The optimizer to use. _8bit optimizers require bitsandbytes, _ds optimizers require deepspeed."
)
)
parser.add_argument(
"--adam_beta1",
type=float,
default=0.9,
help="The beta1 parameter for the Adam optimizer."
)
parser.add_argument(
"--adam_beta2",
type=float,
default=0.999,
help="The beta2 parameter for the Adam optimizer."
)
parser.add_argument(
"--adam_epsilon",
type=float,
default=1e-08,
help="Epsilon value for the Adam optimizer"
)
parser.add_argument(
"--sgd_momentum",
type=float,
default=0.9,
help="Momentum value for the SGDM optimizer"
)
parser.add_argument(
"--sgd_dampening",
type=float,
default=0,
help="Dampening value for the SGDM optimizer"
)
parser.add_argument(
"--max_grad_norm",
default=1.0,
type=float,
help="Max gradient norm."
)
parser.add_argument(
"--weight_decay",
type=float,
default=1e-2,
help="Weight decay to use."
)
parser.add_argument(
"--logging_dir",
type=str,
default="logs",
help=(
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
),
)
parser.add_argument(
"--log_interval",
type=int,
default=10,
help="Log every N steps."
)
parser.add_argument(
"--save_interval",
type=int,
default=10_000,
help="Save weights every N steps."
)
parser.add_argument(
"--save_min_steps",
type=int,
default=10,
help="Start saving weights after N steps."
)
parser.add_argument(
"--mixed_precision",
type=str,
default="no",
choices=["no", "fp16", "bf16"],
help=(
"Whether to use mixed precision. Choose"
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
"and an Nvidia Ampere GPU."
),
)
parser.add_argument(
"--not_cache_latents",
action="store_true",
help="Do not precompute and cache latents from VAE."
)
parser.add_argument(
"--local_rank",
type=int,
default=-1,
help="For distributed training: local_rank"
)
parser.add_argument(
"--concepts_list",
type=str,
default=None,
help="Path to json containing multiple concepts, will overwrite parameters like instance_prompt, class_prompt, etc.",
)
parser.add_argument(
"--wandb",
default=False,
action="store_true",
help="Use wandb to watch training process.",
)
parser.add_argument(
"--wandb_artifact",
default=False,
action="store_true",
help="Upload saved weights to wandb.",
)
parser.add_argument(
"--rm_after_wandb_saved",
default=False,
action="store_true",
help="Remove saved weights from local machine after uploaded to wandb. Useful in colab.",
)
parser.add_argument(
"--wandb_name",
type=str,
default="Stable-Diffusion-Dreambooth",
help="Project name in your wandb.",
)
parser.add_argument(
"--read_prompt_filename",
default=False,
action="store_true",
help="Append extra prompt from filename.",
)
parser.add_argument(
"--read_prompt_txt",
default=False,
action="store_true",
help="Append extra prompt from txt.",
)
parser.add_argument(
"--append_prompt",
type=str,
default="instance",
choices=["class", "instance", "both"],
help="Append extra prompt to which part of input.",
)
parser.add_argument(
"--save_unet_half",
default=False,
action="store_true",
help="Use half precision to save unet weights, saves storage.",
)
parser.add_argument(
"--unet_half",
default=False,
action="store_true",
help="Use half precision to save unet weights, saves storage.",
)
parser.add_argument(
"--clip_skip",
type=int,
default=1,
help="Stop At last [n] layers of CLIP model when training."
)
parser.add_argument(
"--num_cycles",
type=int,
default=1,
help="The number of hard restarts to use. Only works with --lr_scheduler=[cosine_with_restarts_mod, cosine_mod]"
)
parser.add_argument(
"--last_epoch",
type=int,
default=-1,
help="The index of the last epoch when resuming training. Only works with --lr_scheduler=[cosine_with_restarts_mod, cosine_mod]"
)
parser.add_argument(
"--use_aspect_ratio_bucket",
default=False,
action="store_true",
help="Use aspect ratio bucketing as image processing strategy, which may improve the quality of outputs. Use it with --not_cache_latents"
)
parser.add_argument(
"--debug_arb",
default=False,
action="store_true",
help="Enable debug logging on aspect ratio bucket."
)
parser.add_argument(
"--save_optimizer",
default=True,
action="store_true",
help="Save optimizer and scheduler state dict when training. Deprecated: use --save_states"
)
parser.add_argument(
"--save_states",
default=True,
action="store_true",
help="Save optimizer and scheduler state dict when training."
)
parser.add_argument(
"--resume",
default=False,
action="store_true",
help="Load optimizer and scheduler state dict to continue training."
)
parser.add_argument(
"--resume_from",
type=str,
default="",
help="Specify checkpoint to resume. Use wandb://[artifact-full-name] for wandb artifact."
)
parser.add_argument(
"--config",
type=str,
default=None,
help="Read args from config file. Command line args have higher priority and will override it.",
)
parser.add_argument(
"--arb_dim_limit",
type=int,
default=1024,
help="Aspect ratio bucketing arguments: dim_limit."
)
parser.add_argument(
"--arb_divisible",
type=int,
default=64,
help="Aspect ratio bucketing arguments: divisbile."
)
parser.add_argument(
"--arb_max_ar_error",
type=int,
default=4,
help="Aspect ratio bucketing arguments: max_ar_error."
)
parser.add_argument(
"--arb_max_size",
type=int,
nargs="+",
default=(768, 512),
help="Aspect ratio bucketing arguments: max_size. example: --arb_max_size 768 512"
)
parser.add_argument(
"--arb_min_dim",
type=int,
default=256,
help="Aspect ratio bucketing arguments: min_dim."
)
parser.add_argument(
"--deepdanbooru",
default=False,
action="store_true",
help="Use deepdanbooru to tag images when prompt txt is not available."
)
parser.add_argument(
"--dd_threshold",
type=float,
default=0.6,
help="Threshold for Deepdanbooru tag estimation"
)
parser.add_argument(
"--dd_alpha_sort",
default=False,
action="store_true",
help="Sort deepbooru tags alphabetically."
)
parser.add_argument(
"--dd_use_spaces",
default=True,
action="store_true",
help="Use spaces for tags in deepbooru."
)
parser.add_argument(
"--dd_use_escape",
default=True,
action="store_true",
help="Use escape (\\) brackets in deepbooru (so they are used as literal brackets and not for emphasis)"
)
parser.add_argument(
"--enable_rotate",
default=False,
action="store_true",
help="Enable experimental feature to rotate image when buckets is not fit."
)
parser.add_argument(
"--dd_include_ranks",
default=False,
action="store_true",
help="Include rank tag in deepdanbooru."
)
parser.add_argument(
"--use_ema",
action="store_true",
help="Whether to use EMA model."
)
parser.add_argument(
"--ucg",
type=float,
default=0.0,
help="Percentage chance of dropping out the text condition per batch. \
Ranges from 0.0 to 1.0 where 1.0 means 100% text condition dropout."
)
parser.add_argument(
"--debug_prompt",
default=False,
action="store_true",
help="Print input prompt when training."
)
parser.add_argument(
"--xformers",
default=False,
action="store_true",
help="Enable memory efficient attention when training."
)
args = parser.parse_args()
resume_from = args.resume_from
if resume_from.startswith("wandb://"):
import wandb
run = wandb.init(project=args.wandb_name, reinit=False)
artifact = run.use_artifact(resume_from.replace("wandb://", ""), type='model')
resume_from = artifact.download()
elif args.resume_from != "":
fp = os.path.join(resume_from, "state.pt")
if not Path(fp).is_file():
raise ValueError(f"State_dict file {fp} not found.")
elif args.resume:
rx = re.compile(r'checkpoint_(\d+)')
ckpts = rx.findall(" ".join([x.name for x in Path(args.output_dir).iterdir() if x.is_dir() and rx.match(x.name)]))
if not any(ckpts):
raise ValueError("At least one model is needed to resume training.")
ckpts.sort(key=lambda e: int(e), reverse=True)
for k in ckpts:
fp = os.path.join(args.output_dir, f"checkpoint_{k}", "state.pt")
if Path(fp).is_file():
resume_from = os.path.join(args.output_dir, f"checkpoint_{k}")
break
print(f"[*] Selected {resume_from}. To specify other checkpoint, use --resume-from")
if resume_from:
args.config = os.path.join(resume_from, "args.json")
if args.config:
with open(args.config, 'r') as f:
config = json.load(f)
parser.set_defaults(**config)
args = parser.parse_args()
if args.resume:
args.pretrained_model_name_or_path = resume_from
if not args.pretrained_model_name_or_path or not Path(args.pretrained_model_name_or_path).is_dir():
raise ValueError("A model is needed.")
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
if env_local_rank != -1 and env_local_rank != args.local_rank:
args.local_rank = env_local_rank
return args
class DeepDanbooru:
def __init__(
self,
dd_threshold=0.6,
dd_alpha_sort=False,
dd_use_spaces=True,
dd_use_escape=True,
dd_include_ranks=False,
**kwargs
):
self.threshold = dd_threshold
self.alpha_sort = dd_alpha_sort
self.use_spaces = dd_use_spaces
self.use_escape = dd_use_escape
self.include_ranks = dd_include_ranks
self.re_special = re.compile(r"([\\()])")
self.new_process()
def get_tags_local(self,image):
self.returns["value"] = -1
self.queue.put(image)
while self.returns["value"] == -1:
time.sleep(0.1)
return self.returns["value"]
def deepbooru_process(self):
import tensorflow, deepdanbooru
print(f"Deepdanbooru initialized using threshold: {self.threshold}")
self.load_model()
while True:
image = self.queue.get()
if image == "QUIT":
break
else:
self.returns["value"] = self.get_tags(image)
def new_process(self):
context = multiprocessing.get_context("spawn")
manager = context.Manager()
self.queue = manager.Queue()
self.returns = manager.dict()
self.returns["value"] = -1
self.process = context.Process(target=self.deepbooru_process)
self.process.start()
def kill_process(self):
self.queue.put("QUIT")
self.process.join()
self.queue = None
self.returns = None
self.process = None
def load_model(self):
model_path = Path(tempfile.gettempdir()) / "deepbooru"
if not Path(model_path / "project.json").is_file():
self.load_file_from_url(r"https://github.com/KichangKim/DeepDanbooru/releases/download/v3-20211112-sgd-e28/deepdanbooru-v3-20211112-sgd-e28.zip", model_path)
with zipfile.ZipFile(model_path / "deepdanbooru-v3-20211112-sgd-e28.zip", "r") as zip_ref:
zip_ref.extractall(model_path)
os.remove(model_path / "deepdanbooru-v3-20211112-sgd-e28.zip")
self.tags = dd.project.load_tags_from_project(model_path)
self.model = dd.project.load_model_from_project(model_path, compile_model=False)
def unload_model(self):
self.kill_process()
from tensorflow.python.framework import ops
ops.reset_default_graph()
tf.keras.backend.clear_session()
@staticmethod
def load_file_from_url(url, model_dir=None, progress=True, file_name=None):
if model_dir is None: # use the pytorch hub_dir
hub_dir = get_dir()
model_dir = os.path.join(hub_dir, 'checkpoints')
os.makedirs(model_dir, exist_ok=True)
parts = urlparse(url)
filename = os.path.basename(parts.path)
if file_name is not None:
filename = file_name
cached_file = os.path.abspath(os.path.join(model_dir, filename))
if not os.path.exists(cached_file):
print(f'Downloading: "{url}" to {cached_file}\n')
download_url_to_file(url, cached_file, hash_prefix=None, progress=progress)
return cached_file
def process_img(self, image):
width = self.model.input_shape[2]
height = self.model.input_shape[1]
image = np.array(image)
image = tf.image.resize(
image,
size=(height, width),
method=tf.image.ResizeMethod.BICUBIC,
preserve_aspect_ratio=True,
)
image = image.numpy() # EagerTensor to np.array
image = dd.image.transform_and_pad_image(image, width, height)
image = image / 255.0
image_shape = image.shape
image = image.reshape((1, image_shape[0], image_shape[1], image_shape[2]))
return image
def process_tag(self, y):
result_dict = {}
for i, tag in enumerate(self.tags):
result_dict[tag] = y[i]
unsorted_tags_in_theshold = []
result_tags_print = []
for tag in self.tags:
if result_dict[tag] >= self.threshold:
if tag.startswith("rating:"):
continue
unsorted_tags_in_theshold.append((result_dict[tag], tag))
result_tags_print.append(f"{result_dict[tag]} {tag}")
# sort tags
result_tags_out = []
sort_ndx = 0
if self.alpha_sort:
sort_ndx = 1
# sort by reverse by likelihood and normal for alpha, and format tag text as requested
unsorted_tags_in_theshold.sort(key=lambda y: y[sort_ndx], reverse=(not self.alpha_sort))
for weight, tag in unsorted_tags_in_theshold:
tag_outformat = tag
if self.use_spaces:
tag_outformat = tag_outformat.replace("_", " ")
if self.use_escape:
tag_outformat = re.sub(self.re_special, r"\\\1", tag_outformat)
if self.include_ranks:
tag_outformat = f"({tag_outformat}:{weight:.3f})"
result_tags_out.append(tag_outformat)
# print("\n".join(sorted(result_tags_print, reverse=True)))
return ", ".join(result_tags_out)
def get_tags(self, image):
result = self.model.predict(self.process_img(image))[0]
return self.process_tag(result)
class AspectRatioBucket:
'''
Code from https://github.com/NovelAI/novelai-aspect-ratio-bucketing/blob/main/bucketmanager.py
BucketManager impls NovelAI Aspect Ratio Bucketing, which may greatly improve the quality of outputs according to Novelai's blog (https://blog.novelai.net/novelai-improvements-on-stable-diffusion-e10d38db82ac)
Requires a pickle with mapping of dataset IDs to resolutions called resolutions.pkl to use this.
'''
def __init__(self,
id_size_map,
max_size=(768, 512),
divisible=64,
step_size=8,
min_dim=256,
base_res=(512, 512),
bsz=1,
world_size=1,
global_rank=0,
max_ar_error=4,
seed=42,
dim_limit=1024,
debug=True,
):
if global_rank == -1:
global_rank = 0
self.res_map = id_size_map
self.max_size = max_size
self.f = 8
self.max_tokens = (max_size[0]/self.f) * (max_size[1]/self.f)
self.div = divisible
self.min_dim = min_dim
self.dim_limit = dim_limit
self.base_res = base_res
self.bsz = bsz
self.world_size = world_size
self.global_rank = global_rank
self.max_ar_error = max_ar_error
self.prng = self.get_prng(seed)
epoch_seed = self.prng.tomaxint() % (2**32-1)
# separate prng for sharding use for increased thread resilience
self.epoch_prng = self.get_prng(epoch_seed)
self.epoch = None
self.left_over = None
self.batch_total = None
self.batch_delivered = None
self.debug = debug
self.gen_buckets()
self.assign_buckets()
self.start_epoch()
@staticmethod
def get_prng(seed):
return np.random.RandomState(seed)
def __len__(self):
return len(self.res_map) // self.bsz
def gen_buckets(self):
if self.debug:
timer = time.perf_counter()
resolutions = []
aspects = []
w = self.min_dim
while (w/self.f) * (self.min_dim/self.f) <= self.max_tokens and w <= self.dim_limit:
h = self.min_dim
got_base = False
while (w/self.f) * ((h+self.div)/self.f) <= self.max_tokens and (h+self.div) <= self.dim_limit:
if w == self.base_res[0] and h == self.base_res[1]:
got_base = True
h += self.div
if (w != self.base_res[0] or h != self.base_res[1]) and got_base:
resolutions.append(self.base_res)
aspects.append(1)
resolutions.append((w, h))
aspects.append(float(w)/float(h))
w += self.div
h = self.min_dim
while (h/self.f) * (self.min_dim/self.f) <= self.max_tokens and h <= self.dim_limit:
w = self.min_dim
got_base = False
while (h/self.f) * ((w+self.div)/self.f) <= self.max_tokens and (w+self.div) <= self.dim_limit:
if w == self.base_res[0] and h == self.base_res[1]:
got_base = True
w += self.div
resolutions.append((w, h))
aspects.append(float(w)/float(h))
h += self.div
res_map = {}
for i, res in enumerate(resolutions):
res_map[res] = aspects[i]
self.resolutions = sorted(
res_map.keys(), key=lambda x: x[0] * 4096 - x[1])
self.aspects = np.array(
list(map(lambda x: res_map[x], self.resolutions)))
self.resolutions = np.array(self.resolutions)
if self.debug:
timer = time.perf_counter() - timer
print(f"resolutions:\n{self.resolutions}")
print(f"aspects:\n{self.aspects}")
print(f"gen_buckets: {timer:.5f}s")
def assign_buckets(self):
if self.debug:
timer = time.perf_counter()
self.buckets = {}
self.aspect_errors = []
skipped = 0
skip_list = []
for post_id in self.res_map.keys():
w, h = self.res_map[post_id]
aspect = float(w)/float(h)
bucket_id = np.abs(self.aspects - aspect).argmin()
if bucket_id not in self.buckets:
self.buckets[bucket_id] = []
error = abs(self.aspects[bucket_id] - aspect)
if error < self.max_ar_error:
self.buckets[bucket_id].append(post_id)
if self.debug:
self.aspect_errors.append(error)
else:
skipped += 1
skip_list.append(post_id)
for post_id in skip_list:
del self.res_map[post_id]
if self.debug:
timer = time.perf_counter() - timer
self.aspect_errors = np.array(self.aspect_errors)
try:
print(f"skipped images: {skipped}")
print(f"aspect error: mean {self.aspect_errors.mean()}, median {np.median(self.aspect_errors)}, max {self.aspect_errors.max()}")
for bucket_id in reversed(sorted(self.buckets.keys(), key=lambda b: len(self.buckets[b]))):
print(
f"bucket {bucket_id}: {self.resolutions[bucket_id]}, aspect {self.aspects[bucket_id]:.5f}, entries {len(self.buckets[bucket_id])}")
print(f"assign_buckets: {timer:.5f}s")
except Exception as e:
pass
def start_epoch(self, world_size=None, global_rank=None):
if self.debug:
timer = time.perf_counter()
if world_size is not None:
self.world_size = world_size
if global_rank is not None:
self.global_rank = global_rank
# select ids for this epoch/rank
index = sorted(list(self.res_map.keys()))
index_len = len(index)
index = self.epoch_prng.permutation(index)
index = index[:index_len - (index_len % (self.bsz * self.world_size))]
# if self.debug:
# print("perm", self.global_rank, index[0:16])
index = index[self.global_rank::self.world_size]
self.batch_total = len(index) // self.bsz
assert (len(index) % self.bsz == 0)
index = set(index)
self.epoch = {}
self.left_over = []
self.batch_delivered = 0
for bucket_id in sorted(self.buckets.keys()):
if len(self.buckets[bucket_id]) > 0:
self.epoch[bucket_id] = [post_id for post_id in self.buckets[bucket_id] if post_id in index]
self.prng.shuffle(self.epoch[bucket_id])
self.epoch[bucket_id] = list(self.epoch[bucket_id])
overhang = len(self.epoch[bucket_id]) % self.bsz
if overhang != 0:
self.left_over.extend(self.epoch[bucket_id][:overhang])
self.epoch[bucket_id] = self.epoch[bucket_id][overhang:]
if len(self.epoch[bucket_id]) == 0:
del self.epoch[bucket_id]
if self.debug:
timer = time.perf_counter() - timer
count = 0
for bucket_id in self.epoch.keys():
count += len(self.epoch[bucket_id])
print(
f"correct item count: {count == len(index)} ({count} of {len(index)})")
print(f"start_epoch: {timer:.5f}s")
def get_batch(self):
if self.debug:
timer = time.perf_counter()
# check if no data left or no epoch initialized
if self.epoch is None or self.left_over is None or (len(self.left_over) == 0 and not bool(self.epoch)) or self.batch_total == self.batch_delivered:
self.start_epoch()
found_batch = False
batch_data = None
resolution = self.base_res
while not found_batch:
bucket_ids = list(self.epoch.keys())
if len(self.left_over) >= self.bsz:
bucket_probs = [
len(self.left_over)] + [len(self.epoch[bucket_id]) for bucket_id in bucket_ids]
bucket_ids = [-1] + bucket_ids
else:
bucket_probs = [len(self.epoch[bucket_id])
for bucket_id in bucket_ids]
bucket_probs = np.array(bucket_probs, dtype=np.float32)
bucket_lens = bucket_probs
bucket_probs = bucket_probs / bucket_probs.sum()
if bool(self.epoch):
chosen_id = int(self.prng.choice(