English
Japanese
a
File size: 35,133 Bytes
db276de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XU7NuMAA2drw",
        "outputId": "b71fda33-9ca0-4d63-9f20-472db963db22"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "NVIDIA A100-SXM4-40GB, 40960 MiB, 40536 MiB\n"
          ]
        }
      ],
      "source": [
        "#@markdown Check type of GPU and VRAM available.\n",
        "!nvidia-smi --query-gpu=name,memory.total,memory.free --format=csv,noheader"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "9rIK1aqT1Cf0",
        "outputId": "0769ad3a-6f27-4c7a-bf32-a1513bffef63"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Mounted at /content/drive\n"
          ]
        }
      ],
      "source": [
        "from google.colab import drive\n",
        "drive.mount('/content/drive')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BzM7j0ZSc_9c"
      },
      "source": [
        "https://github.com/ShivamShrirao/diffusers/tree/main/examples/dreambooth"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wnTMyW41cC1E"
      },
      "source": [
        "## Install Requirements"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "aLWXPZqjsZVV",
        "outputId": "e97c0864-61b4-4d81-8f65-773e32aef9ac"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "  Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n",
            "  Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n",
            "  Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m190.3/190.3 KB\u001b[0m \u001b[31m17.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Building wheel for diffusers (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m18.7/18.7 MB\u001b[0m \u001b[31m79.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m144.0/144.0 KB\u001b[0m \u001b[31m15.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m6.3/6.3 MB\u001b[0m \u001b[31m103.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m53.1/53.1 KB\u001b[0m \u001b[31m6.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m76.3/76.3 MB\u001b[0m \u001b[31m21.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m14.2/14.2 MB\u001b[0m \u001b[31m76.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m7.6/7.6 MB\u001b[0m \u001b[31m118.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m55.8/55.8 KB\u001b[0m \u001b[31m7.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m71.5/71.5 KB\u001b[0m \u001b[31m5.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m140.6/140.6 KB\u001b[0m \u001b[31m16.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m107.0/107.0 KB\u001b[0m \u001b[31m14.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m84.5/84.5 KB\u001b[0m \u001b[31m10.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.1/2.1 MB\u001b[0m \u001b[31m91.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m56.9/56.9 KB\u001b[0m \u001b[31m7.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m50.5/50.5 KB\u001b[0m \u001b[31m4.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m64.3/64.3 KB\u001b[0m \u001b[31m9.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m80.6/80.6 KB\u001b[0m \u001b[31m11.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m69.6/69.6 KB\u001b[0m \u001b[31m8.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m58.3/58.3 KB\u001b[0m \u001b[31m6.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Building wheel for ffmpy (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "  Building wheel for python-multipart (setup.py) ... \u001b[?25l\u001b[?25hdone\n"
          ]
        }
      ],
      "source": [
        "!wget -q https://github.com/ShivamShrirao/diffusers/raw/main/examples/dreambooth/train_dreambooth.py\n",
        "%pip install -qq git+https://github.com/ShivamShrirao/diffusers\n",
        "%pip install -q -U --pre triton\n",
        "%pip install -q accelerate==0.12.0 transformers ftfy bitsandbytes gradio"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 327
        },
        "id": "y4lqqWT_uxD2",
        "outputId": "8baacd05-301c-4bec-ff16-9fedabac3dd8"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Login successful\n",
            "Your token has been saved to /root/.huggingface/token\n"
          ]
        }
      ],
      "source": [
        "#@title Login to HuggingFace πŸ€—\n",
        "\n",
        "#@markdown You need to accept the model license before downloading or using the Stable Diffusion weights. Please, visit the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4), read the license and tick the checkbox if you agree. You have to be a registered user in πŸ€— Hugging Face Hub, and you'll also need to use an access token for the code to work.\n",
        "from huggingface_hub import notebook_login\n",
        "!git config --global credential.helper store\n",
        "notebook_login()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XfTlc8Mqb8iH"
      },
      "source": [
        "### Install xformers from precompiled wheel."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "n6dcjPnnaiCn",
        "outputId": "515ea33d-bca8-4d59-c04e-ab97382ea848"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
            "Collecting xformers\n",
            "  Cloning https://github.com/facebookresearch/xformers (to revision 1d31a3a) to /tmp/pip-install-7ejn07wq/xformers_3f27ca8ec2e5417990ad2bfde90dbaaa\n",
            "  Running command git clone --filter=blob:none --quiet https://github.com/facebookresearch/xformers /tmp/pip-install-7ejn07wq/xformers_3f27ca8ec2e5417990ad2bfde90dbaaa\n",
            "\u001b[33m  WARNING: Did not find branch or tag '1d31a3a', assuming revision or ref.\u001b[0m\u001b[33m\n",
            "\u001b[0m  Running command git checkout -q 1d31a3a\n",
            "  Resolved https://github.com/facebookresearch/xformers to commit 1d31a3a\n",
            "  Running command git submodule update --init --recursive -q\n",
            "  Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "Requirement already satisfied: torch>=1.12 in /usr/local/lib/python3.8/dist-packages (from xformers) (1.13.1+cu116)\n",
            "Requirement already satisfied: numpy in /usr/local/lib/python3.8/dist-packages (from xformers) (1.21.6)\n",
            "Collecting pyre-extensions==0.0.23\n",
            "  Using cached pyre_extensions-0.0.23-py3-none-any.whl (11 kB)\n",
            "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.8/dist-packages (from pyre-extensions==0.0.23->xformers) (4.4.0)\n",
            "Collecting typing-inspect\n",
            "  Using cached typing_inspect-0.8.0-py3-none-any.whl (8.7 kB)\n",
            "Collecting mypy-extensions>=0.3.0\n",
            "  Using cached mypy_extensions-1.0.0-py3-none-any.whl (4.7 kB)\n",
            "Building wheels for collected packages: xformers\n",
            "  Building wheel for xformers (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "  Created wheel for xformers: filename=xformers-0.0.14.dev0-cp38-cp38-linux_x86_64.whl size=93158187 sha256=5151194336bd969942c59696c06bff6dbd0498d9315e192b6b773b97dadb6ebb\n",
            "  Stored in directory: /tmp/pip-ephem-wheel-cache-shg3tlmw/wheels/5f/3f/8d/a1f7db4c46304e4c83f3ce87dd959d5fcc266b04b9095a737c\n",
            "Successfully built xformers\n",
            "Installing collected packages: mypy-extensions, typing-inspect, pyre-extensions, xformers\n",
            "Successfully installed mypy-extensions-1.0.0 pyre-extensions-0.0.23 typing-inspect-0.8.0 xformers-0.0.14.dev0\n"
          ]
        }
      ],
      "source": [
        "#%pip install -q https://github.com/metrolobo/xformers_wheels/releases/download/1d31a3ac_various_6/xformers-0.0.14.dev0-cp37-cp37m-linux_x86_64.whl\n",
        "# These were compiled on Tesla T4, should also work on P100, thanks to https://github.com/metrolobo\n",
        "\n",
        "# If precompiled wheels don't work, install it with the following command. It will take around 40 minutes to compile.\n",
        "%pip install git+https://github.com/facebookresearch/xformers@1d31a3a#egg=xformers"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G0NV324ZcL9L"
      },
      "source": [
        "## Settings and run"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 195,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Rxg0y5MBudmd",
        "outputId": "eeb1e86d-bf2f-47e6-a4e0-82d26aeb0549"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n",
            "[*] Weights will be saved at /content/drive/MyDrive/stable_diffusion_weights/aitop_roiyaruRIZ_style\n"
          ]
        }
      ],
      "source": [
        "#@markdown Name/Path of the initial model.\n",
        "MODEL_NAME = \"hakurei/waifu-diffusion\" #@param {type:\"string\"}\n",
        "\n",
        "#@markdown A general name for class like dog for dog images.\n",
        "CLASS_NAME = \"roiyaruRIZ_style\" #@param {type:\"string\"}\n",
        "\n",
        "#@markdown Path for images of the concept for training.\n",
        "INSTANCE_DIR = \"/content/data/aitop_\" #@param {type:\"string\"}\n",
        "INSTANCE_DIR += CLASS_NAME\n",
        "!mkdir -p $INSTANCE_DIR\n",
        "CLASS_DIR = f\"/content/data/{CLASS_NAME}\"\n",
        "\n",
        "#@markdown If model weights should be saved directly in google drive (takes around 4-5 GB).\n",
        "save_to_gdrive = True #@param {type:\"boolean\"}\n",
        "if save_to_gdrive:\n",
        "    from google.colab import drive\n",
        "    drive.mount('/content/drive')\n",
        "\n",
        "#@markdown Enter the directory name to save model at.\n",
        "\n",
        "OUTPUT_DIR = \"stable_diffusion_weights/aitop_\" #@param {type:\"string\"}\n",
        "OUTPUT_DIR += CLASS_NAME\n",
        "if save_to_gdrive:\n",
        "    OUTPUT_DIR = \"/content/drive/MyDrive/\" + OUTPUT_DIR\n",
        "else:\n",
        "    OUTPUT_DIR = \"/content/\" + OUTPUT_DIR\n",
        "\n",
        "print(f\"[*] Weights will be saved at {OUTPUT_DIR}\")\n",
        "\n",
        "!mkdir -p $OUTPUT_DIR\n",
        "\n",
        "#@markdown sks is a rare identifier, feel free to replace it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fe-GgtnUVO_e"
      },
      "outputs": [],
      "source": [
        "#@markdown Upload your images by running this cell.\n",
        "\n",
        "#@markdown OR\n",
        "\n",
        "#@markdown You can use the file manager on the left panel to upload (drag and drop) to INSTANCE_DIR (it uploads faster)\n",
        "\n",
        "import os\n",
        "from google.colab import files\n",
        "import shutil\n",
        "\n",
        "uploaded = files.upload()\n",
        "for filename in uploaded.keys():\n",
        "    dst_path = os.path.join(INSTANCE_DIR, filename)\n",
        "    shutil.move(filename, dst_path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qn5ILIyDJIcX"
      },
      "source": [
        "# Start Training\n",
        "\n",
        "Use the table below to choose the best flags based on your memory and speed requirements. Tested on Tesla T4 GPU.\n",
        "\n",
        "\n",
        "| `fp16` | `train_batch_size` | `gradient_accumulation_steps` | `gradient_checkpointing` | `use_8bit_adam` | GB VRAM usage | Speed (it/s) |\n",
        "| ---- | ------------------ | ----------------------------- | ----------------------- | --------------- | ---------- | ------------ |\n",
        "| fp16 | 1                  | 1                             | TRUE                    | TRUE            | 9.92       | 0.93         |\n",
        "| no   | 1                  | 1                             | TRUE                    | TRUE            | 10.08      | 0.42         |\n",
        "| fp16 | 2                  | 1                             | TRUE                    | TRUE            | 10.4       | 0.66         |\n",
        "| fp16 | 1                  | 1                             | FALSE                   | TRUE            | 11.17      | 1.14         |\n",
        "| no   | 1                  | 1                             | FALSE                   | TRUE            | 11.17      | 0.49         |\n",
        "| fp16 | 1                  | 2                             | TRUE                    | TRUE            | 11.56      | 1            |\n",
        "| fp16 | 2                  | 1                             | FALSE                   | TRUE            | 13.67      | 0.82         |\n",
        "| fp16 | 1                  | 2                             | FALSE                   | TRUE            | 13.7       | 0.83          |\n",
        "| fp16 | 1                  | 1                             | TRUE                    | FALSE           | 15.79      | 0.77         |\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-ioxxvHoicPs"
      },
      "source": [
        "Add `--gradient_checkpointing` flag for around 9.92 GB VRAM usage.\n",
        "\n",
        "remove `--use_8bit_adam` flag for full precision. Requires 15.79 GB with `--gradient_checkpointing` else 17.8 GB."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 196,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "jjcSXTp-u-Eg",
        "outputId": "4bdae706-74ed-4a40-f821-ce3f765ce87a"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The following values were not passed to `accelerate launch` and had defaults used instead:\n",
            "\t`--num_processes` was set to a value of `1`\n",
            "\t`--num_machines` was set to a value of `1`\n",
            "\t`--mixed_precision` was set to a value of `'no'`\n",
            "\t`--num_cpu_threads_per_process` was set to `6` to improve out-of-box performance\n",
            "To avoid this warning pass in values for each of the problematic parameters or run `accelerate config`.\n",
            "Fetching 15 files: 100% 15/15 [00:00<00:00, 171897.70it/s]\n",
            "You have disabled the safety checker for <class 'diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline'> by passing `safety_checker=None`. Ensure that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered results in services or applications open to the public. Both the diffusers team and Hugging Face strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling it only for use-cases that involve analyzing network behavior or auditing its results. For more information, please have a look at https://github.com/huggingface/diffusers/pull/254 .\n",
            "Generating class images: 100% 13/13 [00:38<00:00,  2.95s/it]\n",
            "Caching latents: 100% 50/50 [00:05<00:00,  9.18it/s]\n",
            "Steps: 100% 1000/1000 [05:56<00:00,  2.84it/s, loss=0.351, lr=5e-6]\n",
            "Fetching 15 files: 100% 15/15 [00:00<00:00, 33447.40it/s]\n",
            "You have disabled the safety checker for <class 'diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline'> by passing `safety_checker=None`. Ensure that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered results in services or applications open to the public. Both the diffusers team and Hugging Face strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling it only for use-cases that involve analyzing network behavior or auditing its results. For more information, please have a look at https://github.com/huggingface/diffusers/pull/254 .\n",
            "[*] Weights saved at /content/drive/MyDrive/stable_diffusion_weights/aitop_roiyaruRIZ_style/1000\n",
            "Steps: 100% 1000/1000 [06:21<00:00,  2.62it/s, loss=0.351, lr=5e-6]\n"
          ]
        }
      ],
      "source": [
        "!accelerate launch train_dreambooth.py \\\n",
        "  --pretrained_model_name_or_path=$MODEL_NAME \\\n",
        "  --instance_data_dir=$INSTANCE_DIR \\\n",
        "  --class_data_dir=$CLASS_DIR \\\n",
        "  --output_dir=$OUTPUT_DIR \\\n",
        "  --with_prior_preservation --prior_loss_weight=1.0 \\\n",
        "  --instance_prompt=\"aitop {CLASS_NAME}\" \\\n",
        "  --class_prompt=\"{CLASS_NAME}\" \\\n",
        "  --seed=1337 \\\n",
        "  --resolution=512 \\\n",
        "  --train_batch_size=1 \\\n",
        "  --mixed_precision=\"fp16\" \\\n",
        "  --gradient_accumulation_steps=1 \\\n",
        "  --gradient_checkpointing \\\n",
        "  --learning_rate=5e-6 \\\n",
        "  --lr_scheduler=\"constant\" \\\n",
        "  --lr_warmup_steps=0 \\\n",
        "  --num_class_images=50 \\\n",
        "  --sample_batch_size=4 \\\n",
        "  --max_train_steps=1000\n",
        "  #--use_8bit_adam \\\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5V8wgU0HN-Kq"
      },
      "source": [
        "## Convert weights to ckpt to use in web UIs like AUTOMATIC1111."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "baL22PHzOLeP",
        "outputId": "7969edd9-51f6-4f35-ba16-8e04700c132d"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
            "Collecting safetensors\n",
            "  Downloading safetensors-0.2.8-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.2 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.2/1.2 MB\u001b[0m \u001b[31m63.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hInstalling collected packages: safetensors\n",
            "Successfully installed safetensors-0.2.8\n"
          ]
        }
      ],
      "source": [
        "#@markdown Download script\n",
        "!wget -q https://github.com/ShivamShrirao/diffusers/raw/main/scripts/convert_diffusers_to_original_stable_diffusion.py\n",
        "!pip install safetensors"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 197,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "89Az5NUxOWdy",
        "outputId": "e97e902b-d673-47de-c7fb-99dad404a8ca"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Reshaping encoder.mid.attn_1.q.weight for SD format\n",
            "Reshaping encoder.mid.attn_1.k.weight for SD format\n",
            "Reshaping encoder.mid.attn_1.v.weight for SD format\n",
            "Reshaping encoder.mid.attn_1.proj_out.weight for SD format\n",
            "Reshaping decoder.mid.attn_1.q.weight for SD format\n",
            "Reshaping decoder.mid.attn_1.k.weight for SD format\n",
            "Reshaping decoder.mid.attn_1.v.weight for SD format\n",
            "Reshaping decoder.mid.attn_1.proj_out.weight for SD format\n",
            "[*] Converted ckpt saved at /content/drive/MyDrive/stable_diffusion_weights/aitop_roiyaruRIZ_style/1000/phantom_roiyaruRIZ_style_Diffusion.ckpt\n"
          ]
        }
      ],
      "source": [
        "#@markdown Run conversion.\n",
        "ckpt_path = OUTPUT_DIR + f\"/1000/phantom_{CLASS_NAME}_Diffusion.ckpt\"\n",
        "output_dir_with_steps = OUTPUT_DIR + \"/1000\"\n",
        "\n",
        "half_arg = \"\"\n",
        "#@markdown  Whether to convert to fp16, takes half the space (2GB), might loose some quality.\n",
        "fp16 = False #@param {type: \"boolean\"}\n",
        "if fp16:\n",
        "    half_arg = \"--half\"\n",
        "!python convert_diffusers_to_original_stable_diffusion.py --model_path $output_dir_with_steps  --checkpoint_path $ckpt_path $half_arg\n",
        "print(f\"[*] Converted ckpt saved at {ckpt_path}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ToNG4fd_dTbF"
      },
      "source": [
        "## Inference"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NA8IECI8InNr"
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "from torch import autocast\n",
        "from diffusers import StableDiffusionPipeline\n",
        "from IPython.display import display"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 199,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "gW15FjffdTID",
        "outputId": "92a545d0-f9b6-4b33-d6de-1b0e3e0d00b8"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "You have disabled the safety checker for <class 'diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline'> by passing `safety_checker=None`. Ensure that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered results in services or applications open to the public. Both the diffusers team and Hugging Face strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling it only for use-cases that involve analyzing network behavior or auditing its results. For more information, please have a look at https://github.com/huggingface/diffusers/pull/254 .\n"
          ]
        }
      ],
      "source": [
        "model_path = output_dir_with_steps             # If you want to use previously trained model saved in gdrive, replace this with the full path of model in gdrive\n",
        "\n",
        "pipe = StableDiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float16).to(\"cuda\")\n",
        "g_cuda = None"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "oIzkltjpVO_f",
        "outputId": "1db9fcaa-2d0f-4966-dc4f-baac60cdb807"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<torch._C.Generator at 0x7f81b9035570>"
            ]
          },
          "execution_count": 38,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "#@markdown Can set random seed here for reproducibility.\n",
        "g_cuda = torch.Generator(device='cuda')\n",
        "seed = 52362 #@param {type:\"number\"}\n",
        "g_cuda.manual_seed(seed)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 240
        },
        "id": "K6xoHWSsbcS3",
        "outputId": "7bbe13a0-0e31-48a3-cf94-f7200c02ceb7"
      },
      "outputs": [
        {
          "output_type": "error",
          "ename": "NameError",
          "evalue": "ignored",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-1-c0940be36692>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      9\u001b[0m \u001b[0mwidth\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m512\u001b[0m \u001b[0;31m#@param {type:\"number\"}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 11\u001b[0;31m \u001b[0;32mwith\u001b[0m \u001b[0mautocast\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"cuda\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0minference_mode\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     12\u001b[0m     images = pipe(\n\u001b[1;32m     13\u001b[0m         \u001b[0mprompt\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mNameError\u001b[0m: name 'autocast' is not defined"
          ]
        }
      ],
      "source": [
        "#@title Run for generating images.\n",
        "\n",
        "prompt = \"masterpiece, best quality, 1girl, aitop roiyaruRIZ_style\" #@param {type:\"string\"}\n",
        "negative_prompt = \"nsfw, worst quality, low quality, medium quality, deleted, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digits, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry, simple background\" #@param {type:\"string\"}\n",
        "num_samples = 4 #@param {type:\"number\"}\n",
        "guidance_scale = 11 #@param {type:\"number\"}\n",
        "num_inference_steps = 50 #@param {type:\"number\"}\n",
        "height = 512 #@param {type:\"number\"}\n",
        "width = 512 #@param {type:\"number\"}\n",
        "\n",
        "with autocast(\"cuda\"), torch.inference_mode():\n",
        "    images = pipe(\n",
        "        prompt,\n",
        "        height=height,\n",
        "        width=width,\n",
        "        negative_prompt=negative_prompt,\n",
        "        num_images_per_prompt=num_samples,\n",
        "        num_inference_steps=num_inference_steps,\n",
        "        guidance_scale=guidance_scale,\n",
        "        generator=g_cuda\n",
        "    ).images\n",
        "\n",
        "for img in images:\n",
        "    display(img)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "WMCqQ5Tcdsm2"
      },
      "outputs": [],
      "source": [
        "#@markdown Run Gradio UI for generating images.\n",
        "import gradio as gr\n",
        "\n",
        "def inference(prompt, negative_prompt, num_samples, height=512, width=512, num_inference_steps=50, guidance_scale=7.5):\n",
        "    with torch.autocast(\"cuda\"), torch.inference_mode():\n",
        "        return pipe(\n",
        "                prompt, height=int(height), width=int(width),\n",
        "                negative_prompt=negative_prompt,\n",
        "                num_images_per_prompt=int(num_samples),\n",
        "                num_inference_steps=int(num_inference_steps), guidance_scale=guidance_scale,\n",
        "                generator=g_cuda\n",
        "            ).images\n",
        "\n",
        "with gr.Blocks() as demo:\n",
        "    with gr.Row():\n",
        "        with gr.Column():\n",
        "            prompt = gr.Textbox(label=\"Prompt\", value=\"photo of sks guy, digital painting\")\n",
        "            negative_prompt = gr.Textbox(label=\"Negative Prompt\", value=\"\")\n",
        "            run = gr.Button(value=\"Generate\")\n",
        "            with gr.Row():\n",
        "                num_samples = gr.Number(label=\"Number of Samples\", value=4)\n",
        "                guidance_scale = gr.Number(label=\"Guidance Scale\", value=7.5)\n",
        "            with gr.Row():\n",
        "                height = gr.Number(label=\"Height\", value=512)\n",
        "                width = gr.Number(label=\"Width\", value=512)\n",
        "            num_inference_steps = gr.Slider(label=\"Steps\", value=50)\n",
        "        with gr.Column():\n",
        "            gallery = gr.Gallery()\n",
        "\n",
        "    run.click(inference, inputs=[prompt, negative_prompt, num_samples, height, width, num_inference_steps, guidance_scale], outputs=gallery)\n",
        "\n",
        "demo.launch(debug=True)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lJoOgLQHnC8L"
      },
      "outputs": [],
      "source": [
        "#@title (Optional) Delete diffuser weights and only keep the ckpt to free up drive space (4GB).\n",
        "\n",
        "#@markdown [ ! ] Caution, Only execute if you are sure u want to delete the diffuser format weights and only use the ckpt.\n",
        "import shutil\n",
        "from glob import glob\n",
        "for f in glob(OUTPUT_DIR+\"/*\"):\n",
        "    if not f.endswith(\".ckpt\"):\n",
        "        try:\n",
        "            shutil.rmtree(f)\n",
        "        except NotADirectoryError:\n",
        "            continue\n",
        "        print(\"Deleted\", f)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jXgi8HM4c-DA"
      },
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "provenance": []
    },
    "gpuClass": "premium",
    "kernelspec": {
      "display_name": "Python 3.10.7 64-bit",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.10.7"
    },
    "vscode": {
      "interpreter": {
        "hash": "e7370f93d1d0cde622a1f8e1c04877d8463912d04d973331ad4851f04de6915a"
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}