scrapware commited on
Commit
b7a1259
1 Parent(s): 3341938

Upload kohya_lora_dreambooth_latest.py

Browse files
Files changed (1) hide show
  1. kohya_lora_dreambooth_latest.py +2002 -0
kohya_lora_dreambooth_latest.py ADDED
@@ -0,0 +1,2002 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """kohya-LoRA-dreambooth-latest.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1V6iv4_OdHivIrJlEqjsNPjeRai_pM9ei
8
+
9
+ ![visitors](https://visitor-badge.glitch.me/badge?page_id=linaqruf.lora-dreambooth) [![](https://dcbadge.vercel.app/api/shield/850007095775723532?style=flat)](https://lookup.guru/850007095775723532) [![ko-fi](https://img.shields.io/badge/Support%20me%20on%20Ko--fi-F16061?logo=ko-fi&logoColor=white&style=flat)](https://ko-fi.com/linaqruf) <a href="https://saweria.co/linaqruf"><img alt="Saweria" src="https://img.shields.io/badge/Saweria-7B3F00?style=flat&logo=ko-fi&logoColor=white"/></a>
10
+
11
+ # **Kohya LoRA Dreambooth**
12
+ A Colab Notebook For LoRA Training (Dreambooth Method)
13
+
14
+ | Notebook Name | Description | Link | V14 |
15
+ | --- | --- | --- | --- |
16
+ | [Kohya LoRA Dreambooth](https://github.com/Linaqruf/kohya-trainer/blob/main/kohya-LoRA-dreambooth.ipynb) | LoRA Training (Dreambooth method) | [![](https://img.shields.io/static/v1?message=Open%20in%20Colab&logo=googlecolab&labelColor=5c5c5c&color=0f80c1&label=%20&style=flat)](https://colab.research.google.com/github/Linaqruf/kohya-trainer/blob/main/kohya-LoRA-dreambooth.ipynb) | [![](https://img.shields.io/static/v1?message=Older%20Version&logo=googlecolab&labelColor=5c5c5c&color=e74c3c&label=%20&style=flat)](https://colab.research.google.com/github/Linaqruf/kohya-trainer/blob/ff701379c65380c967cd956e4e9e8f6349563878/kohya-LoRA-dreambooth.ipynb) |
17
+ | [Kohya LoRA Fine-Tuning](https://github.com/Linaqruf/kohya-trainer/blob/main/kohya-LoRA-finetuner.ipynb) | LoRA Training (Fine-tune method) | [![](https://img.shields.io/static/v1?message=Open%20in%20Colab&logo=googlecolab&labelColor=5c5c5c&color=0f80c1&label=%20&style=flat)](https://colab.research.google.com/github/Linaqruf/kohya-trainer/blob/main/kohya-LoRA-finetuner.ipynb) | [![](https://img.shields.io/static/v1?message=Older%20Version&logo=googlecolab&labelColor=5c5c5c&color=e74c3c&label=%20&style=flat)](https://colab.research.google.com/github/Linaqruf/kohya-trainer/blob/ff701379c65380c967cd956e4e9e8f6349563878/kohya-LoRA-finetuner.ipynb) |
18
+ | [Kohya Trainer](https://github.com/Linaqruf/kohya-trainer/blob/main/kohya-trainer.ipynb) | Native Training | [![](https://img.shields.io/static/v1?message=Open%20in%20Colab&logo=googlecolab&labelColor=5c5c5c&color=0f80c1&label=%20&style=flat)](https://colab.research.google.com/github/Linaqruf/kohya-trainer/blob/main/kohya-trainer.ipynb) | [![](https://img.shields.io/static/v1?message=Older%20Version&logo=googlecolab&labelColor=5c5c5c&color=e74c3c&label=%20&style=flat)](https://colab.research.google.com/github/Linaqruf/kohya-trainer/blob/ff701379c65380c967cd956e4e9e8f6349563878/kohya-trainer.ipynb) |
19
+ | [Kohya Dreambooth](https://github.com/Linaqruf/kohya-trainer/blob/main/kohya-dreambooth.ipynb) | Dreambooth Training | [![](https://img.shields.io/static/v1?message=Open%20in%20Colab&logo=googlecolab&labelColor=5c5c5c&color=0f80c1&label=%20&style=flat)](https://colab.research.google.com/github/Linaqruf/kohya-trainer/blob/main/kohya-dreambooth.ipynb) | [![](https://img.shields.io/static/v1?message=Older%20Version&logo=googlecolab&labelColor=5c5c5c&color=e74c3c&label=%20&style=flat)](https://colab.research.google.com/github/Linaqruf/kohya-trainer/blob/ff701379c65380c967cd956e4e9e8f6349563878/kohya-dreambooth.ipynb) |
20
+ | [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection/blob/main/cagliostro-colab-ui.ipynb) `NEW`| A Customizable Stable Diffusion Web UI| [![](https://img.shields.io/static/v1?message=Open%20in%20Colab&logo=googlecolab&labelColor=5c5c5c&color=0f80c1&label=%20&style=flat)](https://colab.research.google.com/github/Linaqruf/sd-notebook-collection/blob/main/cagliostro-colab-ui.ipynb) |
21
+
22
+ # I. Install Kohya Trainer
23
+ """
24
+
25
+ # Commented out IPython magic to ensure Python compatibility.
26
+ # @title ## 1.1. Install Dependencies
27
+ # @markdown Clone Kohya Trainer from GitHub and check for updates. Use textbox below if you want to checkout other branch or old commit. Leave it empty to stay the HEAD on main. This will also install the required libraries.
28
+ import os
29
+ import zipfile
30
+ import shutil
31
+ import time
32
+ from subprocess import getoutput
33
+ from IPython.utils import capture
34
+ from google.colab import drive
35
+
36
+ # %store -r
37
+
38
+ # root_dir
39
+ root_dir = "/content"
40
+ deps_dir = os.path.join(root_dir, "deps")
41
+ repo_dir = os.path.join(root_dir, "kohya-trainer")
42
+ training_dir = os.path.join(root_dir, "LoRA")
43
+ pretrained_model = os.path.join(root_dir, "pretrained_model")
44
+ vae_dir = os.path.join(root_dir, "vae")
45
+ config_dir = os.path.join(training_dir, "config")
46
+
47
+ # repo_dir
48
+ accelerate_config = os.path.join(repo_dir, "accelerate_config/config.yaml")
49
+ tools_dir = os.path.join(repo_dir, "tools")
50
+ finetune_dir = os.path.join(repo_dir, "finetune")
51
+
52
+ for store in [
53
+ "root_dir",
54
+ "deps_dir",
55
+ "repo_dir",
56
+ "training_dir",
57
+ "pretrained_model",
58
+ "vae_dir",
59
+ "accelerate_config",
60
+ "tools_dir",
61
+ "finetune_dir",
62
+ "config_dir",
63
+ ]:
64
+ with capture.capture_output() as cap:
65
+ # %store {store}
66
+ del cap
67
+
68
+ repo_url = "https://github.com/Linaqruf/kohya-trainer"
69
+ bitsandytes_main_py = "/usr/local/lib/python3.10/dist-packages/bitsandbytes/cuda_setup/main.py"
70
+ branch = "" # @param {type: "string"}
71
+ mount_drive = True # @param {type: "boolean"}
72
+ verbose = False # @param {type: "boolean"}
73
+
74
+ def read_file(filename):
75
+ with open(filename, "r") as f:
76
+ contents = f.read()
77
+ return contents
78
+
79
+
80
+ def write_file(filename, contents):
81
+ with open(filename, "w") as f:
82
+ f.write(contents)
83
+
84
+
85
+ def clone_repo(url):
86
+ if not os.path.exists(repo_dir):
87
+ os.chdir(root_dir)
88
+ !git clone {url} {repo_dir}
89
+ else:
90
+ os.chdir(repo_dir)
91
+ !git pull origin {branch} if branch else !git pull
92
+
93
+
94
+ def install_dependencies():
95
+ s = getoutput('nvidia-smi')
96
+
97
+ if 'T4' in s:
98
+ !sed -i "s@cpu@cuda@" library/model_util.py
99
+
100
+ !pip install {'-q' if not verbose else ''} --upgrade -r requirements.txt
101
+
102
+ from accelerate.utils import write_basic_config
103
+
104
+ if not os.path.exists(accelerate_config):
105
+ write_basic_config(save_location=accelerate_config)
106
+
107
+
108
+ def remove_bitsandbytes_message(filename):
109
+ welcome_message = """
110
+ def evaluate_cuda_setup():
111
+ print('')
112
+ print('='*35 + 'BUG REPORT' + '='*35)
113
+ print('Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues')
114
+ print('For effortless bug reporting copy-paste your error into this form: https://docs.google.com/forms/d/e/1FAIpQLScPB8emS3Thkp66nvqwmjTEgxp8Y9ufuWTzFyr9kJ5AoI47dQ/viewform?usp=sf_link')
115
+ print('='*80)"""
116
+
117
+ new_welcome_message = """
118
+ def evaluate_cuda_setup():
119
+ import os
120
+ if 'BITSANDBYTES_NOWELCOME' not in os.environ or str(os.environ['BITSANDBYTES_NOWELCOME']) == '0':
121
+ print('')
122
+ print('=' * 35 + 'BUG REPORT' + '=' * 35)
123
+ print('Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues')
124
+ print('For effortless bug reporting copy-paste your error into this form: https://docs.google.com/forms/d/e/1FAIpQLScPB8emS3Thkp66nvqwmjTEgxp8Y9ufuWTzFyr9kJ5AoI47dQ/viewform?usp=sf_link')
125
+ print('To hide this message, set the BITSANDBYTES_NOWELCOME variable like so: export BITSANDBYTES_NOWELCOME=1')
126
+ print('=' * 80)"""
127
+
128
+ contents = read_file(filename)
129
+ new_contents = contents.replace(welcome_message, new_welcome_message)
130
+ write_file(filename, new_contents)
131
+
132
+
133
+ def main():
134
+ os.chdir(root_dir)
135
+
136
+ if mount_drive:
137
+ if not os.path.exists("/content/drive"):
138
+ drive.mount("/content/drive")
139
+
140
+ for dir in [
141
+ deps_dir,
142
+ training_dir,
143
+ config_dir,
144
+ pretrained_model,
145
+ vae_dir
146
+ ]:
147
+ os.makedirs(dir, exist_ok=True)
148
+
149
+ clone_repo(repo_url)
150
+
151
+ if branch:
152
+ os.chdir(repo_dir)
153
+ status = os.system(f"git checkout {branch}")
154
+ if status != 0:
155
+ raise Exception("Failed to checkout branch or commit")
156
+
157
+ os.chdir(repo_dir)
158
+
159
+ !apt install aria2 {'-qq' if not verbose else ''}
160
+
161
+ install_dependencies()
162
+ time.sleep(3)
163
+
164
+ remove_bitsandbytes_message(bitsandytes_main_py)
165
+
166
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
167
+ os.environ["BITSANDBYTES_NOWELCOME"] = "1"
168
+ os.environ["SAFETENSORS_FAST_GPU"] = "1"
169
+
170
+ cuda_path = "/usr/local/cuda-11.8/targets/x86_64-linux/lib/"
171
+ ld_library_path = os.environ.get("LD_LIBRARY_PATH", "")
172
+ os.environ["LD_LIBRARY_PATH"] = f"{ld_library_path}:{cuda_path}"
173
+
174
+ main()
175
+
176
+ # @title ## 1.2. Start `File Explorer`
177
+ # @markdown This will work in real-time even when you run other cells
178
+ import threading
179
+ from google.colab import output
180
+ from imjoy_elfinder.app import main
181
+
182
+ open_in_new_tab = False # @param {type:"boolean"}
183
+
184
+ def start_file_explorer(root_dir=root_dir, port=8765):
185
+ try:
186
+ main(["--root-dir=" + root_dir, "--port=" + str(port)])
187
+ except Exception as e:
188
+ print("Error starting file explorer:", str(e))
189
+
190
+
191
+ def open_file_explorer(open_in_new_tab=False, root_dir=root_dir, port=8765):
192
+ thread = threading.Thread(target=start_file_explorer, args=[root_dir, port])
193
+ thread.start()
194
+
195
+ if open_in_new_tab:
196
+ output.serve_kernel_port_as_window(port)
197
+ else:
198
+ output.serve_kernel_port_as_iframe(port, height="500")
199
+
200
+ open_file_explorer(open_in_new_tab=open_in_new_tab, root_dir=root_dir, port=8765)
201
+
202
+ """# II. Pretrained Model Selection"""
203
+
204
+ # Commented out IPython magic to ensure Python compatibility.
205
+ # @title ## 2.1. Download Available Model
206
+ import os
207
+
208
+ # %store -r
209
+
210
+ models = {
211
+ "AnyLoRA": "https://huggingface.co/Linaqruf/stolen/resolve/main/pruned-models/AnyLoRA_noVae_fp16-pruned.safetensors",
212
+ "AnyLoRA-anime-mix": "https://huggingface.co/Lykon/AnyLoRA/resolve/main/AAM_Anylora_AnimeMix.safetensors",
213
+ "AnimePastelDream": "https://huggingface.co/Lykon/AnimePastelDream/resolve/main/AnimePastelDream_Soft_noVae_fp16.safetensors",
214
+ "Chillout-mix": "https://huggingface.co/Linaqruf/stolen/resolve/main/pruned-models/chillout_mix-pruned.safetensors",
215
+ "DosMix": "https://huggingface.co/scrapware/personal-backup/resolve/main/models/dosmix/dosmix_.safetensors",
216
+ "DDosMix_V2": "https://huggingface.co/scrapware/personal-backup/resolve/main/models/dosmix/ddosmix_V2.safetensors",
217
+ "RealDosMix": "https://huggingface.co/scrapware/personal-backup/resolve/main/models/dosmix/realdosmix_.safetensors",
218
+ "anidosmix_A": "https://huggingface.co/scrapware/personal-backup/resolv/main/models/dosmix/anidosmix_A.safetensors",
219
+ "cartoonish_v1": "https://huggingface.co/scrapware/personal-backup/resolve/main/models/dosmix/cartoonish_v1.safetensors",
220
+ "cbi_MOMO_v2HQ": "https://huggingface.co/scrapware/personal-backup/resolve/main/specials/cbi_MOMO_v2HQ.safetensors",
221
+ "cbi_MOMO_v2.1": "https://huggingface.co/scrapware/personal-backup/resolve/main/specials/cbi_MOMO_v2.1.safetensors",
222
+ "Nordrin_little-v3": "https://huggingface.co/scrapware/personal-backup/resolve/main/models/nordrinLittleLittle_v30.safetensors",
223
+ "majicMIX-v25": "https://huggingface.co/scrapware/personal-backup/resolve/main/majicmixRealistic_betterV2V25.safetensors",
224
+ "Anything-v3-0": "https://huggingface.co/Linaqruf/stolen/resolve/main/pruned-models/anything-v3-0.safetensors",
225
+ "Anything-v3-1": "https://huggingface.co/cag/anything-v3-1/resolve/main/anything-v3-1.safetensors",
226
+ "Anything-v3-2": "https://huggingface.co/Linaqruf/stolen/resolve/main/pruned-models/anything-v3-2.safetensors",
227
+ "Anything-v3-3": "https://huggingface.co/Linaqruf/stolen/resolve/main/pruned-models/anything-v3-3.safetensors",
228
+ "OpenJourney-v4": "https://huggingface.co/prompthero/openjourney-v4/resolve/main/openjourney-v4.ckpt",
229
+ "Stable-Diffusion-v1-5": "https://huggingface.co/Linaqruf/stolen/resolve/main/pruned-models/stable_diffusion_1_5-pruned.safetensors",
230
+ "Animefull-final-pruned": "https://huggingface.co/scrapware/personal-backup/resolve/main/novelailatest-pruned.ckpt",
231
+ }
232
+
233
+ v2_models = {
234
+ "stable-diffusion-2-1-base": "https://huggingface.co/stabilityai/stable-diffusion-2-1-base/resolve/main/v2-1_512-ema-pruned.safetensors",
235
+ "stable-diffusion-2-1-768v": "https://huggingface.co/stabilityai/stable-diffusion-2-1/resolve/main/v2-1_768-ema-pruned.safetensors",
236
+ "plat-diffusion-v1-3-1": "https://huggingface.co/p1atdev/pd-archive/resolve/main/plat-v1-3-1.safetensors",
237
+ "replicant-v1": "https://huggingface.co/gsdf/Replicant-V1.0/resolve/main/Replicant-V1.0.safetensors",
238
+ "illuminati-diffusion-v1-0": "https://huggingface.co/IlluminatiAI/Illuminati_Diffusion_v1.0/resolve/main/illuminati_diffusion_v1.0.safetensors",
239
+ "illuminati-diffusion-v1-1": "https://huggingface.co/4eJIoBek/Illuminati-Diffusion-v1-1/resolve/main/illuminatiDiffusionV1_v11.safetensors",
240
+ "waifu-diffusion-1-4-anime-e2": "https://huggingface.co/hakurei/waifu-diffusion-v1-4/resolve/main/wd-1-4-anime_e2.ckpt",
241
+ "waifu-diffusion-1-5-e2": "https://huggingface.co/waifu-diffusion/wd-1-5-beta2/resolve/main/checkpoints/wd-1-5-beta2-fp32.safetensors",
242
+ "waifu-diffusion-1-5-e2-aesthetic": "https://huggingface.co/waifu-diffusion/wd-1-5-beta2/resolve/main/checkpoints/wd-1-5-beta2-aesthetic-fp32.safetensors",
243
+ }
244
+
245
+ installModels = []
246
+ installv2Models = []
247
+
248
+ # @markdown ### SD1.x model
249
+ model_name = "" # @param ["", "AnyLoRA", "AnyLoRA-anime-mix", "AnimePastelDream", "Chillout-mix", "dosmix", "ddosmix_V2", "realdosmix", "anidosmix_A", "cartoonish_v1", "cbi_MOMO_v2HQ", "cbi_MOMO_v2.1", "Nordrin_little-v3", "majicMIX-v25", "Anything-v3-0", "Anything-v3-1", "Anything-v3-2", "Anything-v3-3", "OpenJourney-v4", "Stable-Diffusion-v1-5", "Animefull-final-pruned"]
250
+ # @markdown ### SD2.x model
251
+ v2_model_name = "" # @param ["", "stable-diffusion-2-1-base", "stable-diffusion-2-1-768v", "plat-diffusion-v1-3-1", "replicant-v1", "illuminati-diffusion-v1-0", "illuminati-diffusion-v1-1", "waifu-diffusion-1-4-anime-e2", "waifu-diffusion-1-5-e2", "waifu-diffusion-1-5-e2-aesthetic"]
252
+
253
+ if model_name:
254
+ model_url = models.get(model_name)
255
+ if model_url:
256
+ installModels.append((model_name, model_url))
257
+ elif v2_model_name:
258
+ v2_model_url = v2_models.get(v2_model_name)
259
+ if v2_model_url:
260
+ installv2Models.append((v2_model_name, v2_model_url))
261
+
262
+
263
+ def install(checkpoint_name, url):
264
+ ext = "ckpt" if url.endswith(".ckpt") else "safetensors"
265
+
266
+ hf_token = "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"
267
+ user_header = f'"Authorization: Bearer {hf_token}"'
268
+ !aria2c --console-log-level=error --summary-interval=10 --header={user_header} -c -x 16 -k 1M -s 16 -d {pretrained_model} -o {checkpoint_name}.{ext} "{url}"
269
+
270
+
271
+ def install_checkpoint():
272
+ for model in installModels:
273
+ install(model[0], model[1])
274
+ for v2model in installv2Models:
275
+ install(v2model[0], v2model[1])
276
+
277
+ install_checkpoint()
278
+
279
+ # Commented out IPython magic to ensure Python compatibility.
280
+ # @title ## 2.2. Download Custom Model
281
+ import os
282
+
283
+ # %store -r
284
+
285
+ os.chdir(root_dir)
286
+
287
+ # @markdown ### Custom model
288
+ modelUrls = "" # @param {'type': 'string'}
289
+
290
+ def install(url):
291
+ base_name = os.path.basename(url)
292
+
293
+ if "drive.google.com" in url:
294
+ os.chdir(pretrained_model)
295
+ !gdown --fuzzy {url}
296
+ elif "huggingface.co" in url:
297
+ if "/blob/" in url:
298
+ url = url.replace("/blob/", "/resolve/")
299
+ # @markdown Change this part with your own huggingface token if you need to download your private model
300
+ hf_token = "" # @param {type:"string"}
301
+ user_header = f'"Authorization: Bearer {hf_token}"'
302
+ !aria2c --console-log-level=error --summary-interval=10 --header={user_header} -c -x 16 -k 1M -s 16 -d {pretrained_model} -o {base_name} {url}
303
+ else:
304
+ !aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {pretrained_model} {url}
305
+
306
+ if modelUrls:
307
+ urls = modelUrls.split(",")
308
+ for url in urls:
309
+ install(url.strip())
310
+
311
+ # Commented out IPython magic to ensure Python compatibility.
312
+ # @title ## 2.3. Download Available VAE (Optional)
313
+ import os
314
+
315
+ # %store -r
316
+
317
+ vaes = {
318
+ "none": "",
319
+ "anime.vae.pt": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/animevae.pt",
320
+ "kl-f8-anime1.ckpt": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/kl-f8-anime1.ckpt",
321
+ "kl-f8-anime2.ckpt": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/kl-f8-anime2.ckpt",
322
+ "waifudiffusion.vae.pt": "https://huggingface.co/hakurei/waifu-diffusion-v1-4/resolve/main/vae/kl-f8-anime.ckpt",
323
+ "kl-f8-anime3.ckpt": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/kl-f8-anime3.ckpt", "blessed2.vae.pt": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/blessed2.vae.pt",
324
+ "vae-ft-ema-560000-ema-pruned.safetensors": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/vae-ft-ema-560000-ema-pruned.safetensors",
325
+ "vae-ft-mse-840000-ema-pruned.safetensors": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/vae-ft-mse-840000-ema-pruned.safetensors",
326
+ "stablediffusion.vae.pt": "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt",
327
+ "ft-mse-840000-darken.pt": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/ft-mse-840000-darken.pt",
328
+ "ft-mse-840000-deeper.pt": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/ft-mse-840000-deeper.pt",
329
+ "apricots_vae.safetensors": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/apricots_vae_v1.safetensors",
330
+ "apricots_quantizer.safetensors": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/apricots_quantizer_v1.safetensors",
331
+ "twinkle_vae.safetensors": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/twinkle_vae_v1.safetensors",
332
+ "twinkle_v1-darken.vae": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/twinkle_v1-darken.vae",
333
+ "twinkle_v1-deeper.vae": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/twinkle_v1-deeper.vae",
334
+ "tensor_quantizer.safetensors": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/tensor_quantizer.safetensors",
335
+ "mangledMergeVAE_v10.pt": "https://huggingface.co/scrapware/personal-backup/resolve/main/vae/mangledMergeVAE_v10.pt",
336
+ }
337
+
338
+ install_vaes = []
339
+
340
+ # @markdown Select one of the VAEs to download, select `none` for not download VAE: (wd=k8a2, sd=mse)
341
+ vae_name = "none" # @param ["none", "anime.vae.pt", "kl-f8-anime1.ckpt", "kl-f8-anime2.ckpt", "waifudiffusion.vae.pt", "kl-f8-anime3.ckpt", "vae-ft-ema-560000-ema-pruned.safetensors", "vae-ft-mse-840000-ema-pruned.safetensors", "stablediffusion.vae.pt", "ft-mse-840000-darken.pt", "ft-mse-840000-deeper.pt", "apricots_vae.safetensors", "apricots_quantizer.safetensors", "twinkle_vae.safetensors", "twinkle_v1-darken.vae", "twinkle_v1-deeper.vae", "tensor_quantizer.safetensors", "mangledMergeVAE_v10.pt"]
342
+
343
+ if vae_name in vaes:
344
+ vae_url = vaes[vae_name]
345
+ if vae_url:
346
+ install_vaes.append((vae_name, vae_url))
347
+
348
+ def install(vae_name, url):
349
+ hf_token = "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"
350
+ user_header = f'"Authorization: Bearer {hf_token}"'
351
+ !aria2c --console-log-level=error --summary-interval=10 --header={user_header} -c -x 16 -k 1M -s 16 -d {vae_dir} -o {vae_name} "{url}"
352
+
353
+ def install_vae():
354
+ for vae in install_vaes:
355
+ install(vae[0], vae[1])
356
+
357
+ install_vae()
358
+
359
+ """# III. Data Acquisition
360
+
361
+ You have three options for acquiring your dataset:
362
+
363
+ 1. Uploading it to Colab's local files.
364
+ 2. Bulk downloading images from Danbooru using the `Simple Booru Scraper`.
365
+ 3. Locating your dataset from Google Drive.
366
+
367
+ """
368
+
369
+ # Commented out IPython magic to ensure Python compatibility.
370
+ # @title ## 3.1. Locating Train Data Directory
371
+ # @markdown Define the location of your training data. This cell will also create a folder based on your input. Regularization Images is optional and can be skipped.
372
+ import os
373
+ from IPython.utils import capture
374
+
375
+ # %store -r
376
+
377
+ train_data_dir = "/content/LoRA/train_data" # @param {type:'string'}
378
+ reg_data_dir = "/content/LoRA/reg_data" # @param {type:'string'}
379
+
380
+ for dir in [train_data_dir, reg_data_dir]:
381
+ if dir:
382
+ with capture.capture_output() as cap:
383
+ os.makedirs(dir, exist_ok=True)
384
+ # %store dir
385
+ del cap
386
+
387
+ print(f"Your train data directory : {train_data_dir}")
388
+ if reg_data_dir:
389
+ print(f"Your reg data directory : {reg_data_dir}")
390
+
391
+ # @title ## 3.2. Unzip Dataset
392
+
393
+ import os
394
+ import shutil
395
+ from pathlib import Path
396
+
397
+ #@title ## Unzip Dataset
398
+ # @markdown Use this section if your dataset is in a `zip` file and has been uploaded somewhere. This code cell will download your dataset and automatically extract it to the `train_data_dir` if the `unzip_to` variable is empty.
399
+ zipfile_url = "/content/drive/MyDrive/Stable-diffusion/zipfile/xxxx.zip" #@param {type:"string"}
400
+ zipfile_name = "zipfile.zip"
401
+ unzip_to = "/content/LoRA" #@param {type:"string"}
402
+
403
+ hf_token = "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"
404
+ user_header = f'"Authorization: Bearer {hf_token}"'
405
+
406
+ if unzip_to:
407
+ os.makedirs(unzip_to, exist_ok=True)
408
+ else:
409
+ unzip_to = train_data_dir
410
+
411
+
412
+ def download_dataset(url):
413
+ if url.startswith("/content"):
414
+ return url
415
+ elif "drive.google.com" in url:
416
+ os.chdir(root_dir)
417
+ !gdown --fuzzy {url}
418
+ return f"{root_dir}/{zipfile_name}"
419
+ elif "huggingface.co" in url:
420
+ if "/blob/" in url:
421
+ url = url.replace("/blob/", "/resolve/")
422
+ !aria2c --console-log-level=error --summary-interval=10 --header={user_header} -c -x 16 -k 1M -s 16 -d {root_dir} -o {zipfile_name} {url}
423
+ return f"{root_dir}/{zipfile_name}"
424
+ else:
425
+ !aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {root_dir} -o {zipfile_name} {url}
426
+ return f"{root_dir}/{zipfile_name}"
427
+
428
+
429
+ def extract_dataset(zip_file, output_path):
430
+ if zip_file.startswith("/content"):
431
+ !unzip -o {zip_file} -d "{output_path}"
432
+ else:
433
+ !unzip -o "{zip_file}" -d "{output_path}"
434
+
435
+
436
+ def remove_files(train_dir, files_to_move):
437
+ for filename in os.listdir(train_dir):
438
+ file_path = os.path.join(train_dir, filename)
439
+ if filename in files_to_move:
440
+ if not os.path.exists(file_path):
441
+ shutil.move(file_path, training_dir)
442
+ else:
443
+ os.remove(file_path)
444
+
445
+
446
+ zip_file = download_dataset(zipfile_url)
447
+ extract_dataset(zip_file, unzip_to)
448
+ #os.remove(zip_file)
449
+
450
+ files_to_move = (
451
+ "meta_cap.json",
452
+ "meta_cap_dd.json",
453
+ "meta_lat.json",
454
+ "meta_clean.json",
455
+ )
456
+
457
+ remove_files(train_data_dir, files_to_move)
458
+
459
+ # Commented out IPython magic to ensure Python compatibility.
460
+ #@title ## 3.3. Image Scraper (Optional)
461
+ import os
462
+ import html
463
+ from IPython.utils import capture
464
+ # %store -r
465
+
466
+ os.chdir(root_dir)
467
+ #@markdown Use `gallery-dl` to scrape images from an imageboard site. Specify the `prompt(s)` by separating them with commas, e.g., `hito_komoru, touhou`.
468
+ booru = "Danbooru" #@param ["Danbooru", "Gelbooru", "Safebooru"]
469
+ prompt = "" #@param {type: "string"}
470
+ #@markdown You can also specify a `custom_url` instead of using a predefined site.
471
+ custom_url = "" #@param {type: "string"}
472
+ #@markdown `sub_folder` option can be used to organize the downloaded images into separate folders based on their concept or category.
473
+ sub_folder = "" #@param {type: "string"}
474
+ user_agent = "gdl/1.24.5"
475
+ #@markdown You can limit the number of images to download by using the `--range` option followed by the desired range. For example `1-200`.
476
+ range = "1-200" #@param {type: "string"}
477
+ write_tags = True #@param {type: "boolean"}
478
+ additional_arguments = "--filename /O --no-part" #@param {type: "string"}
479
+ #@markdown Set `with_aria_2c` to `True` to scrape images using aria2c.
480
+ with_aria_2c = True #@param {type: "boolean"}
481
+
482
+ tags = prompt.split(',')
483
+ tags = '+'.join(tags)
484
+
485
+ replacement_dict = {" ": "", "(": "%28", ")": "%29", ":": "%3a"}
486
+ tags = ''.join(replacement_dict.get(c, c) for c in tags)
487
+
488
+ if sub_folder == "":
489
+ image_dir = train_data_dir
490
+ elif sub_folder.startswith("/content"):
491
+ image_dir = sub_folder
492
+ else:
493
+ image_dir = os.path.join(train_data_dir, sub_folder)
494
+ os.makedirs(image_dir, exist_ok=True)
495
+
496
+ if booru == "Danbooru":
497
+ url = "https://danbooru.donmai.us/posts?tags={}".format(tags)
498
+ elif booru == "Gelbooru":
499
+ url = "https://gelbooru.com/index.php?page=post&s=list&tags={}".format(tags)
500
+ else:
501
+ url = "https://safebooru.org/index.php?page=post&s=list&tags={}".format(tags)
502
+
503
+ valid_url = custom_url if custom_url else url
504
+
505
+ def scrape(config):
506
+ args = ""
507
+ for k, v in config.items():
508
+ if k.startswith("_"):
509
+ args += f'"{v}" '
510
+ elif isinstance(v, str):
511
+ args += f'--{k}="{v}" '
512
+ elif isinstance(v, bool) and v:
513
+ args += f"--{k} "
514
+ elif isinstance(v, float) and not isinstance(v, bool):
515
+ args += f"--{k}={v} "
516
+ elif isinstance(v, int) and not isinstance(v, bool):
517
+ args += f"--{k}={v} "
518
+
519
+ return args
520
+
521
+ def pre_process_tags(directory):
522
+ for item in os.listdir(directory):
523
+ item_path = os.path.join(directory, item)
524
+ if os.path.isfile(item_path) and item.endswith(".txt"):
525
+ old_path = item_path
526
+ new_file_name = os.path.splitext(os.path.splitext(item)[0])[0] + ".txt"
527
+ new_path = os.path.join(directory, new_file_name)
528
+
529
+ os.rename(old_path, new_path)
530
+
531
+ with open(new_path, "r") as f:
532
+ contents = f.read()
533
+
534
+ contents = html.unescape(contents)
535
+ contents = contents.replace("_", " ")
536
+ contents = ", ".join(contents.split("\n"))
537
+
538
+ with open(new_path, "w") as f:
539
+ f.write(contents)
540
+
541
+ elif os.path.isdir(item_path):
542
+ pre_process_tags(item_path)
543
+
544
+ get_url_config = {
545
+ "get-urls" : True,
546
+ "range" : range if range else None,
547
+ "user-agent" : user_agent
548
+ }
549
+
550
+ scrape_config = {
551
+ "directory" : image_dir,
552
+ "write-tags" : write_tags,
553
+ "range" : range if range else None,
554
+ "user-agent" : user_agent
555
+ }
556
+
557
+ if with_aria_2c:
558
+ scraper_text = os.path.join(root_dir, "scrape_this.txt")
559
+ with capture.capture_output() as cap:
560
+ args = scrape(get_url_config)
561
+ !gallery-dl "{valid_url}" {args} {additional_arguments}
562
+ with open(scraper_text, "w") as f:
563
+ f.write(cap.stdout)
564
+
565
+ os.chdir(image_dir)
566
+ !aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -i {scraper_text}
567
+
568
+ else:
569
+ args = scrape(scrape_config)
570
+ !gallery-dl "{valid_url}" {args} {additional_arguments}
571
+
572
+ if write_tags:
573
+ pre_process_tags(train_data_dir)
574
+
575
+ """# IV. Data Preprocessing"""
576
+
577
+ # Commented out IPython magic to ensure Python compatibility.
578
+ # @title ## 4.1. Data Cleaning
579
+ import os
580
+ import random
581
+ import concurrent.futures
582
+ from tqdm import tqdm
583
+ from PIL import Image
584
+
585
+ # %store -r
586
+
587
+ os.chdir(root_dir)
588
+
589
+ test = os.listdir(train_data_dir)
590
+ # @markdown This section will delete unnecessary files and unsupported media such as `.mp4`, `.webm`, and `.gif`.
591
+ # @markdown Set the `convert` parameter to convert your transparent dataset with an alpha channel (RGBA) to RGB and give it a white background.
592
+ convert = False # @param {type:"boolean"}
593
+ # @markdown You can choose to give it a `random_color` background instead of white by checking the corresponding option.
594
+ random_color = False # @param {type:"boolean"}
595
+ # @markdown Use the `recursive` option to preprocess subfolders as well.
596
+ recursive = False # @param {type:"boolean"}
597
+
598
+
599
+ batch_size = 32
600
+ supported_types = [
601
+ ".png",
602
+ ".jpg",
603
+ ".jpeg",
604
+ ".webp",
605
+ ".bmp",
606
+ ".caption",
607
+ ".npz",
608
+ ".txt",
609
+ ".json",
610
+ ]
611
+
612
+ background_colors = [
613
+ (255, 255, 255),
614
+ (0, 0, 0),
615
+ (255, 0, 0),
616
+ (0, 255, 0),
617
+ (0, 0, 255),
618
+ (255, 255, 0),
619
+ (255, 0, 255),
620
+ (0, 255, 255),
621
+ ]
622
+
623
+ def clean_directory(directory):
624
+ for item in os.listdir(directory):
625
+ file_path = os.path.join(directory, item)
626
+ if os.path.isfile(file_path):
627
+ file_ext = os.path.splitext(item)[1]
628
+ if file_ext not in supported_types:
629
+ print(f"Deleting file {item} from {directory}")
630
+ os.remove(file_path)
631
+ elif os.path.isdir(file_path) and recursive:
632
+ clean_directory(file_path)
633
+
634
+ def process_image(image_path):
635
+ img = Image.open(image_path)
636
+ img_dir, image_name = os.path.split(image_path)
637
+
638
+ if img.mode in ("RGBA", "LA"):
639
+ if random_color:
640
+ background_color = random.choice(background_colors)
641
+ else:
642
+ background_color = (255, 255, 255)
643
+ bg = Image.new("RGB", img.size, background_color)
644
+ bg.paste(img, mask=img.split()[-1])
645
+
646
+ if image_name.endswith(".webp"):
647
+ bg = bg.convert("RGB")
648
+ new_image_path = os.path.join(img_dir, image_name.replace(".webp", ".jpg"))
649
+ bg.save(new_image_path, "JPEG")
650
+ os.remove(image_path)
651
+ print(f" Converted image: {image_name} to {os.path.basename(new_image_path)}")
652
+ else:
653
+ bg.save(image_path, "PNG")
654
+ print(f" Converted image: {image_name}")
655
+ else:
656
+ if image_name.endswith(".webp"):
657
+ new_image_path = os.path.join(img_dir, image_name.replace(".webp", ".jpg"))
658
+ img.save(new_image_path, "JPEG")
659
+ os.remove(image_path)
660
+ print(f" Converted image: {image_name} to {os.path.basename(new_image_path)}")
661
+ else:
662
+ img.save(image_path, "PNG")
663
+
664
+ def find_images(directory):
665
+ images = []
666
+ for root, _, files in os.walk(directory):
667
+ for file in files:
668
+ if file.endswith(".png") or file.endswith(".webp"):
669
+ images.append(os.path.join(root, file))
670
+ return images
671
+
672
+ clean_directory(train_data_dir)
673
+ images = find_images(train_data_dir)
674
+ num_batches = len(images) // batch_size + 1
675
+
676
+ if convert:
677
+ with concurrent.futures.ThreadPoolExecutor() as executor:
678
+ for i in tqdm(range(num_batches)):
679
+ start = i * batch_size
680
+ end = start + batch_size
681
+ batch = images[start:end]
682
+ executor.map(process_image, batch)
683
+
684
+ print("All images have been converted")
685
+
686
+ """## 4.2. Data Annotation
687
+ You can choose to train a model using captions. We're using [BLIP](https://huggingface.co/spaces/Salesforce/BLIP) for image captioning and [Waifu Diffusion 1.4 Tagger](https://huggingface.co/spaces/SmilingWolf/wd-v1-4-tags) for image tagging similar to Danbooru.
688
+ - Use BLIP Captioning for: `General Images`
689
+ - Use Waifu Diffusion 1.4 Tagger V2 for: `Anime and Manga-style Images`
690
+ """
691
+
692
+ #@title ### 4.2.1. BLIP Captioning
693
+ #@markdown BLIP is a pre-training framework for unified vision-language understanding and generation, which achieves state-of-the-art results on a wide range of vision-language tasks. It can be used as a tool for image captioning, for example, `astronaut riding a horse in space`.
694
+ import os
695
+
696
+ os.chdir(finetune_dir)
697
+
698
+ batch_size = 8 #@param {type:'number'}
699
+ max_data_loader_n_workers = 2 #@param {type:'number'}
700
+ beam_search = True #@param {type:'boolean'}
701
+ min_length = 5 #@param {type:"slider", min:0, max:100, step:5.0}
702
+ max_length = 75 #@param {type:"slider", min:0, max:100, step:5.0}
703
+ #@markdown Use the `recursive` option to process subfolders as well, useful for multi-concept training.
704
+ recursive = False #@param {type:"boolean"}
705
+ #@markdown Debug while captioning, it will print your image file with generated captions.
706
+ verbose_logging = True #@param {type:"boolean"}
707
+
708
+ config = {
709
+ "_train_data_dir" : train_data_dir,
710
+ "batch_size" : batch_size,
711
+ "beam_search" : beam_search,
712
+ "min_length" : min_length,
713
+ "max_length" : max_length,
714
+ "debug" : verbose_logging,
715
+ "caption_extension" : ".caption",
716
+ "max_data_loader_n_workers" : max_data_loader_n_workers,
717
+ "recursive" : recursive
718
+ }
719
+
720
+ args = ""
721
+ for k, v in config.items():
722
+ if k.startswith("_"):
723
+ args += f'"{v}" '
724
+ elif isinstance(v, str):
725
+ args += f'--{k}="{v}" '
726
+ elif isinstance(v, bool) and v:
727
+ args += f"--{k} "
728
+ elif isinstance(v, float) and not isinstance(v, bool):
729
+ args += f"--{k}={v} "
730
+ elif isinstance(v, int) and not isinstance(v, bool):
731
+ args += f"--{k}={v} "
732
+
733
+ final_args = f"python make_captions.py {args}"
734
+
735
+ os.chdir(finetune_dir)
736
+ !{final_args}
737
+
738
+ # Commented out IPython magic to ensure Python compatibility.
739
+ #@title ### 4.2.2. Waifu Diffusion 1.4 Tagger V2
740
+ import os
741
+ # %store -r
742
+
743
+ os.chdir(finetune_dir)
744
+
745
+ #@markdown [Waifu Diffusion 1.4 Tagger V2](https://huggingface.co/spaces/SmilingWolf/wd-v1-4-tags) is a Danbooru-styled image classification model developed by SmilingWolf. It can also be useful for general image tagging, for example, `1girl, solo, looking_at_viewer, short_hair, bangs, simple_background`.
746
+ batch_size = 8 #@param {type:'number'}
747
+ max_data_loader_n_workers = 2 #@param {type:'number'}
748
+ model = "SmilingWolf/wd-v1-4-convnextv2-tagger-v2" #@param ["SmilingWolf/wd-v1-4-convnextv2-tagger-v2", "SmilingWolf/wd-v1-4-swinv2-tagger-v2", "SmilingWolf/wd-v1-4-convnext-tagger-v2", "SmilingWolf/wd-v1-4-vit-tagger-v2"]
749
+ #@markdown Use the `recursive` option to process subfolders as well, useful for multi-concept training.
750
+ recursive = False #@param {type:"boolean"}
751
+ #@markdown Debug while tagging, it will print your image file with general tags and character tags.
752
+ verbose_logging = True #@param {type:"boolean"}
753
+ #@markdown Separate `undesired_tags` with comma `(,)` if you want to remove multiple tags, e.g. `1girl,solo,smile`.
754
+ undesired_tags = "" #@param {type:'string'}
755
+ #@markdown Adjust `general_threshold` for pruning tags (less tags, less flexible). `character_threshold` is useful if you want to train with character tags, e.g. `hakurei reimu`.
756
+ general_threshold = 0.35 #@param {type:"slider", min:0, max:1, step:0.05}
757
+ character_threshold = 0.35 #@param {type:"slider", min:0, max:1, step:0.05}
758
+
759
+ config = {
760
+ "_train_data_dir": train_data_dir,
761
+ "batch_size": batch_size,
762
+ "repo_id": model,
763
+ "recursive": recursive,
764
+ "remove_underscore": True,
765
+ "general_threshold": general_threshold,
766
+ "character_threshold": character_threshold,
767
+ "caption_extension": ".txt",
768
+ "max_data_loader_n_workers": max_data_loader_n_workers,
769
+ "debug": verbose_logging,
770
+ "undesired_tags": undesired_tags
771
+ }
772
+
773
+ args = ""
774
+ for k, v in config.items():
775
+ if k.startswith("_"):
776
+ args += f'"{v}" '
777
+ elif isinstance(v, str):
778
+ args += f'--{k}="{v}" '
779
+ elif isinstance(v, bool) and v:
780
+ args += f"--{k} "
781
+ elif isinstance(v, float) and not isinstance(v, bool):
782
+ args += f"--{k}={v} "
783
+ elif isinstance(v, int) and not isinstance(v, bool):
784
+ args += f"--{k}={v} "
785
+
786
+ final_args = f"python tag_images_by_wd14_tagger.py {args}"
787
+
788
+ os.chdir(finetune_dir)
789
+ !{final_args}
790
+
791
+ # Commented out IPython magic to ensure Python compatibility.
792
+ # @title ### 4.2.3. Custom Caption/Tag
793
+ import os
794
+
795
+ # %store -r
796
+
797
+ os.chdir(root_dir)
798
+
799
+ # @markdown Add or remove custom tags here. You can refer to this [cheatsheet](https://rentry.org/kohyaminiguide#c-custom-tagscaption) for more information.
800
+ extension = ".txt" # @param [".txt", ".caption"]
801
+ custom_tag = "" # @param {type:"string"}
802
+ # @markdown Use `sub_folder` option to specify a subfolder for multi-concept training.
803
+ # @markdown > Specify `--all` to process all subfolders/`recursive`
804
+ sub_folder = "" #@param {type: "string"}
805
+ # @markdown Enable this to append custom tags at the end of lines.
806
+ append = False # @param {type:"boolean"}
807
+ # @markdown Enable this if you want to remove captions/tags instead.
808
+ remove_tag = False # @param {type:"boolean"}
809
+ recursive = False
810
+
811
+ if sub_folder == "":
812
+ image_dir = train_data_dir
813
+ elif sub_folder == "--all":
814
+ image_dir = train_data_dir
815
+ recursive = True
816
+ elif sub_folder.startswith("/content"):
817
+ image_dir = sub_folder
818
+ else:
819
+ image_dir = os.path.join(train_data_dir, sub_folder)
820
+ os.makedirs(image_dir, exist_ok=True)
821
+
822
+ def read_file(filename):
823
+ with open(filename, "r") as f:
824
+ contents = f.read()
825
+ return contents
826
+
827
+ def write_file(filename, contents):
828
+ with open(filename, "w") as f:
829
+ f.write(contents)
830
+
831
+ def process_tags(filename, custom_tag, append, remove_tag):
832
+ contents = read_file(filename)
833
+ tags = [tag.strip() for tag in contents.split(',')]
834
+ custom_tags = [tag.strip() for tag in custom_tag.split(',')]
835
+
836
+ for custom_tag in custom_tags:
837
+ custom_tag = custom_tag.replace("_", " ")
838
+ if remove_tag:
839
+ while custom_tag in tags:
840
+ tags.remove(custom_tag)
841
+ else:
842
+ if custom_tag not in tags:
843
+ if append:
844
+ tags.append(custom_tag)
845
+ else:
846
+ tags.insert(0, custom_tag)
847
+
848
+ contents = ', '.join(tags)
849
+ write_file(filename, contents)
850
+
851
+ def process_directory(image_dir, tag, append, remove_tag, recursive):
852
+ for filename in os.listdir(image_dir):
853
+ file_path = os.path.join(image_dir, filename)
854
+
855
+ if os.path.isdir(file_path) and recursive:
856
+ process_directory(file_path, tag, append, remove_tag, recursive)
857
+ elif filename.endswith(extension):
858
+ process_tags(file_path, tag, append, remove_tag)
859
+
860
+ tag = custom_tag
861
+
862
+ if not any(
863
+ [filename.endswith(extension) for filename in os.listdir(image_dir)]
864
+ ):
865
+ for filename in os.listdir(image_dir):
866
+ if filename.endswith((".png", ".jpg", ".jpeg", ".webp", ".bmp")):
867
+ open(
868
+ os.path.join(image_dir, filename.split(".")[0] + extension),
869
+ "w",
870
+ ).close()
871
+
872
+ if custom_tag:
873
+ process_directory(image_dir, tag, append, remove_tag, recursive)
874
+
875
+ """# V. Training Model
876
+
877
+
878
+ """
879
+
880
+ # Commented out IPython magic to ensure Python compatibility.
881
+ # @title ## 5.1. Model Config
882
+ from google.colab import drive
883
+
884
+ v2 = False # @param {type:"boolean"}
885
+ v_parameterization = False # @param {type:"boolean"}
886
+ project_name = "" # @param {type:"string"}
887
+ if not project_name:
888
+ project_name = "last"
889
+ # %store project_name
890
+ pretrained_model_name_or_path = "/content/pretrained_model/AnyLoRA.safetensors" # @param {type:"string"}
891
+ vae = "" # @param {type:"string"}
892
+ output_dir = "/content/LoRA/output" # @param {'type':'string'}
893
+
894
+ # @markdown `output_to_drive` sets default `output_dir` to `/content/drive/MyDrive/LoRA/output`. This will override the `output_dir` variable defined above.
895
+ output_to_drive = True # @param {'type':'boolean'}
896
+
897
+ if output_to_drive:
898
+ output_dir = "/content/drive/MyDrive/LoRA/output"
899
+
900
+ if not os.path.exists("/content/drive"):
901
+ drive.mount("/content/drive")
902
+
903
+ sample_dir = os.path.join(output_dir, "sample")
904
+ for dir in [output_dir, sample_dir]:
905
+ os.makedirs(dir, exist_ok=True)
906
+
907
+ print("Project Name: ", project_name)
908
+ print("Model Version: Stable Diffusion V1.x") if not v2 else ""
909
+ print("Model Version: Stable Diffusion V2.x") if v2 and not v_parameterization else ""
910
+ print("Model Version: Stable Diffusion V2.x 768v") if v2 and v_parameterization else ""
911
+ print(
912
+ "Pretrained Model Path: ", pretrained_model_name_or_path
913
+ ) if pretrained_model_name_or_path else print("No Pretrained Model path specified.")
914
+ print("VAE Path: ", vae) if vae else print("No VAE path specified.")
915
+ print("Output Path: ", output_dir)
916
+
917
+ # @title ## 5.2. Dataset Config
918
+ import os
919
+ import toml
920
+ import glob
921
+
922
+ dataset_repeats = 10 # @param {type:"number"}
923
+ # @markdown `activation_word` is not used in training if you train with captions/tags, but it is still printed to metadata.
924
+ activation_word = "" # @param {type:"string"}
925
+ caption_extension = ".txt" # @param ["none", ".txt", ".caption"]
926
+ # @markdown Please refer to `4.2.3. Custom Caption/Tag (Optional)` if you want to append `activation_word` to captions/tags
927
+ resolution = 512 # @param {type:"slider", min:512, max:1024, step:128}
928
+ flip_aug = False # @param {type:"boolean"}
929
+ keep_tokens = 0 # @param {type:"number"}
930
+
931
+ def parse_folder_name(folder_name, default_num_repeats, default_class_token):
932
+ folder_name_parts = folder_name.split("_")
933
+
934
+ if len(folder_name_parts) == 2:
935
+ if folder_name_parts[0].isdigit():
936
+ num_repeats = int(folder_name_parts[0])
937
+ class_token = folder_name_parts[1].replace("_", " ")
938
+ else:
939
+ num_repeats = default_num_repeats
940
+ class_token = default_class_token
941
+ else:
942
+ num_repeats = default_num_repeats
943
+ class_token = default_class_token
944
+
945
+ return num_repeats, class_token
946
+
947
+ def find_image_files(path):
948
+ supported_extensions = (".png", ".jpg", ".jpeg", ".webp", ".bmp")
949
+ return [file for file in glob.glob(path + '/**/*', recursive=True) if file.lower().endswith(supported_extensions)]
950
+
951
+ def process_data_dir(data_dir, default_num_repeats, default_class_token, is_reg=False):
952
+ subsets = []
953
+
954
+ images = find_image_files(data_dir)
955
+ if images:
956
+ subsets.append({
957
+ "image_dir": data_dir,
958
+ "class_tokens": default_class_token,
959
+ "num_repeats": default_num_repeats,
960
+ **({"is_reg": is_reg} if is_reg else {}),
961
+ })
962
+
963
+ for root, dirs, files in os.walk(data_dir):
964
+ for folder in dirs:
965
+ folder_path = os.path.join(root, folder)
966
+ images = find_image_files(folder_path)
967
+
968
+ if images:
969
+ num_repeats, class_token = parse_folder_name(folder, default_num_repeats, default_class_token)
970
+
971
+ subset = {
972
+ "image_dir": folder_path,
973
+ "class_tokens": class_token,
974
+ "num_repeats": num_repeats,
975
+ }
976
+
977
+ if is_reg:
978
+ subset["is_reg"] = True
979
+
980
+ subsets.append(subset)
981
+
982
+ return subsets
983
+
984
+
985
+ train_subsets = process_data_dir(train_data_dir, dataset_repeats, activation_word)
986
+ reg_subsets = process_data_dir(reg_data_dir, dataset_repeats, activation_word, is_reg=True)
987
+
988
+ subsets = train_subsets + reg_subsets
989
+
990
+ config = {
991
+ "general": {
992
+ "enable_bucket": True,
993
+ "caption_extension": caption_extension,
994
+ "shuffle_caption": True,
995
+ "keep_tokens": keep_tokens,
996
+ "bucket_reso_steps": 64,
997
+ "bucket_no_upscale": False,
998
+ },
999
+ "datasets": [
1000
+ {
1001
+ "resolution": resolution,
1002
+ "min_bucket_reso": 320 if resolution > 640 else 256,
1003
+ "max_bucket_reso": 1280 if resolution > 640 else 1024,
1004
+ "caption_dropout_rate": 0,
1005
+ "caption_tag_dropout_rate": 0,
1006
+ "caption_dropout_every_n_epochs": 0,
1007
+ "flip_aug": flip_aug,
1008
+ "color_aug": False,
1009
+ "face_crop_aug_range": None,
1010
+ "subsets": subsets,
1011
+ }
1012
+ ],
1013
+ }
1014
+
1015
+ dataset_config = os.path.join(config_dir, "dataset_config.toml")
1016
+
1017
+ for key in config:
1018
+ if isinstance(config[key], dict):
1019
+ for sub_key in config[key]:
1020
+ if config[key][sub_key] == "":
1021
+ config[key][sub_key] = None
1022
+ elif config[key] == "":
1023
+ config[key] = None
1024
+
1025
+ config_str = toml.dumps(config)
1026
+
1027
+ with open(dataset_config, "w") as f:
1028
+ f.write(config_str)
1029
+
1030
+ print(config_str)
1031
+
1032
+ # @title ## 5.3. LoRA and Optimizer Config
1033
+
1034
+ # @markdown ### LoRA Config:
1035
+ network_category = "LoCon_Lycoris" # @param ["LoRA", "LoCon", "LoCon_Lycoris", "LoHa"]
1036
+
1037
+ # @markdown Recommended values:
1038
+
1039
+ # @markdown | network_category | network_dim | network_alpha | conv_dim | conv_alpha |
1040
+ # @markdown | :---: | :---: | :---: | :---: | :---: |
1041
+ # @markdown | LoRA | 32 | 1 | - | - |
1042
+ # @markdown | LoCon | 16 | 8 | 8 | 1 |
1043
+ # @markdown | LoHa | 8 | 4 | 4 | 1 |
1044
+
1045
+ # @markdown - Note that `dropout` and `cp_decomposition` are not available in this notebook.
1046
+
1047
+ # @markdown `conv_dim` and `conv_alpha` are needed to train `LoCon` and `LoHa`; skip them if you are training normal `LoRA`. However, when in doubt, set `dim = alpha`.
1048
+ conv_dim = 32 # @param {'type':'number'}
1049
+ conv_alpha = 16 # @param {'type':'number'}
1050
+ # @markdown It's recommended not to set `network_dim` and `network_alpha` higher than 64, especially for `LoHa`.
1051
+ # @markdown If you want to use a higher value for `dim` or `alpha`, consider using a higher learning rate, as models with higher dimensions tend to learn faster.
1052
+ network_dim = 32 # @param {'type':'number'}
1053
+ network_alpha = 16 # @param {'type':'number'}
1054
+ # @markdown You can specify this field for resume training.
1055
+ network_weight = "" # @param {'type':'string'}
1056
+ network_module = "lycoris.kohya" if network_category in ["LoHa", "LoCon_Lycoris"] else "networks.lora"
1057
+ network_args = "" if network_category == "LoRA" else [
1058
+ f"conv_dim={conv_dim}", f"conv_alpha={conv_alpha}",
1059
+ ]
1060
+ # @markdown ### <br>Optimizer Config:
1061
+ # @markdown `NEW` Gamma for reducing the weight of high-loss timesteps. Lower numbers have a stronger effect. The paper recommends 5. Read the paper [here](https://arxiv.org/abs/2303.09556).
1062
+ min_snr_gamma = -1 #@param {type:"number"}
1063
+ # @markdown `AdamW8bit` was the old `--use_8bit_adam`.
1064
+ optimizer_type = "AdaFactor" # @param ["AdamW", "AdamW8bit", "Lion", "SGDNesterov", "SGDNesterov8bit", "DAdaptation", "AdaFactor"]
1065
+ # @markdown Additional arguments for optimizer, e.g: `["decouple=True","weight_decay=0.6"]`
1066
+ optimizer_args = "[\"warmup_init=False\", \"relative_step=True\",]" # @param {'type':'string'}
1067
+ # @markdown Set `unet_lr` to `1.0` if you use `DAdaptation` optimizer, because it's a [free learning rate](https://github.com/facebookresearch/dadaptation) algorithm.
1068
+ # @markdown However, it is recommended to set `text_encoder_lr = 0.5 * unet_lr`.
1069
+ # @markdown Also, you don't need to specify `learning_rate` value if both `unet_lr` and `text_encoder_lr` are defined.
1070
+ train_unet = True # @param {'type':'boolean'}
1071
+ unet_lr = 1e-5 # @param {'type':'number'}
1072
+ train_text_encoder = True # @param {'type':'boolean'}
1073
+ text_encoder_lr = 5e-6 # @param {'type':'number'}
1074
+ lr_scheduler = "adafactor" # @param ["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup", "adafactor"] {allow-input: false}
1075
+ lr_warmup_steps = 0 # @param {'type':'number'}
1076
+ # @markdown You can define `num_cycles` value for `cosine_with_restarts` or `power` value for `polynomial` in the field below.
1077
+ lr_scheduler_num_cycles = 0 # @param {'type':'number'}
1078
+ lr_scheduler_power = 0 # @param {'type':'number'}
1079
+
1080
+ if network_category == "LoHa":
1081
+ network_args.append("algo=loha")
1082
+ elif network_category == "LoCon_Lycoris":
1083
+ network_args.append("algo=lora")
1084
+
1085
+ print("- LoRA Config:")
1086
+ print(f" - Min-SNR Weighting: {min_snr_gamma}") if not min_snr_gamma == -1 else ""
1087
+ print(f" - Loading network module: {network_module}")
1088
+ if not network_category == "LoRA":
1089
+ print(f" - network args: {network_args}")
1090
+ print(f" - {network_module} linear_dim set to: {network_dim}")
1091
+ print(f" - {network_module} linear_alpha set to: {network_alpha}")
1092
+ if not network_category == "LoRA":
1093
+ print(f" - {network_module} conv_dim set to: {conv_dim}")
1094
+ print(f" - {network_module} conv_alpha set to: {conv_alpha}")
1095
+
1096
+ if not network_weight:
1097
+ print(" - No LoRA weight loaded.")
1098
+ else:
1099
+ if os.path.exists(network_weight):
1100
+ print(f" - Loading LoRA weight: {network_weight}")
1101
+ else:
1102
+ print(f" - {network_weight} does not exist.")
1103
+ network_weight = ""
1104
+
1105
+ print("- Optimizer Config:")
1106
+ print(f" - Additional network category: {network_category}")
1107
+ print(f" - Using {optimizer_type} as Optimizer")
1108
+ if optimizer_args:
1109
+ print(f" - Optimizer Args: {optimizer_args}")
1110
+ if train_unet and train_text_encoder:
1111
+ print(" - Train UNet and Text Encoder")
1112
+ print(f" - UNet learning rate: {unet_lr}")
1113
+ print(f" - Text encoder learning rate: {text_encoder_lr}")
1114
+ if train_unet and not train_text_encoder:
1115
+ print(" - Train UNet only")
1116
+ print(f" - UNet learning rate: {unet_lr}")
1117
+ if train_text_encoder and not train_unet:
1118
+ print(" - Train Text Encoder only")
1119
+ print(f" - Text encoder learning rate: {text_encoder_lr}")
1120
+ print(f" - Learning rate warmup steps: {lr_warmup_steps}")
1121
+ print(f" - Learning rate Scheduler: {lr_scheduler}")
1122
+ if lr_scheduler == "cosine_with_restarts":
1123
+ print(f" - lr_scheduler_num_cycles: {lr_scheduler_num_cycles}")
1124
+ elif lr_scheduler == "polynomial":
1125
+ print(f" - lr_scheduler_power: {lr_scheduler_power}")
1126
+
1127
+ # Commented out IPython magic to ensure Python compatibility.
1128
+ # @title ## 5.4. Training Config
1129
+
1130
+ import toml
1131
+ import os
1132
+
1133
+ # %store -r
1134
+ lowram = True # @param {type:"boolean"}
1135
+ enable_sample_prompt = True # @param {type:"boolean"}
1136
+ sampler = "euler_a" # @param ["ddim", "pndm", "lms", "euler", "euler_a", "heun", "dpm_2", "dpm_2_a", "dpmsolver","dpmsolver++", "dpmsingle", "k_lms", "k_euler", "k_euler_a", "k_dpm_2", "k_dpm_2_a"]
1137
+ noise_offset = 0.0 # @param {type:"number"}
1138
+ num_epochs = 10 # @param {type:"number"}
1139
+ vae_batch_size = 6 # @param {type:"number"}
1140
+ train_batch_size = 8 # @param {type:"number"}
1141
+ mixed_precision = "fp16" # @param ["no","fp8", "fp16", "bf16"] {allow-input: false}
1142
+ save_precision = "fp16" # @param ["float", "fp8", "fp16", "bf16"] {allow-input: false}
1143
+ save_n_epochs_type = "save_every_n_epochs" # @param ["save_every_n_epochs", "save_n_epoch_ratio"] {allow-input: false}
1144
+ save_n_epochs_type_value = 2 # @param {type:"number"}
1145
+ save_model_as = "safetensors" # @param ["ckpt", "pt", "safetensors"] {allow-input: false}
1146
+ max_token_length = 225 # @param {type:"number"}
1147
+ clip_skip = 2 # @param {type:"number"}
1148
+ gradient_checkpointing = False # @param {type:"boolean"}
1149
+ gradient_accumulation_steps = 1 # @param {type:"number"}
1150
+ seed = -1 # @param {type:"number"}
1151
+ logging_dir = "/content/LoRA/logs"
1152
+ prior_loss_weight = 1.0
1153
+
1154
+ os.chdir(repo_dir)
1155
+
1156
+ sample_str = f"""
1157
+ masterpiece, best quality, 1girl, aqua eyes, baseball cap, blonde hair, closed mouth, earrings, green background, hat, hoop earrings, jewelry, looking at viewer, shirt, short hair, simple background, solo, upper body, yellow shirt \
1158
+ --n lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry \
1159
+ --w 512 \
1160
+ --h 768 \
1161
+ --l 7 \
1162
+ --s 28
1163
+ """
1164
+
1165
+ config = {
1166
+ "model_arguments": {
1167
+ "v2": v2,
1168
+ "v_parameterization": v_parameterization if v2 and v_parameterization else False,
1169
+ "pretrained_model_name_or_path": pretrained_model_name_or_path,
1170
+ "vae": vae,
1171
+ },
1172
+ "additional_network_arguments": {
1173
+ "no_metadata": False,
1174
+ "unet_lr": float(unet_lr) if train_unet else None,
1175
+ "text_encoder_lr": float(text_encoder_lr) if train_text_encoder else None,
1176
+ "network_weights": network_weight,
1177
+ "network_module": network_module,
1178
+ "network_dim": network_dim,
1179
+ "network_alpha": network_alpha,
1180
+ "network_args": network_args,
1181
+ "network_train_unet_only": True if train_unet and not train_text_encoder else False,
1182
+ "network_train_text_encoder_only": True if train_text_encoder and not train_unet else False,
1183
+ "training_comment": None,
1184
+ },
1185
+ "optimizer_arguments": {
1186
+ "min_snr_gamma": min_snr_gamma if not min_snr_gamma == -1 else None,
1187
+ "optimizer_type": optimizer_type,
1188
+ "learning_rate": unet_lr,
1189
+ "max_grad_norm": 1.0,
1190
+ "optimizer_args": eval(optimizer_args) if optimizer_args else None,
1191
+ "lr_scheduler": lr_scheduler,
1192
+ "lr_warmup_steps": lr_warmup_steps,
1193
+ "lr_scheduler_num_cycles": lr_scheduler_num_cycles if lr_scheduler == "cosine_with_restarts" else None,
1194
+ "lr_scheduler_power": lr_scheduler_power if lr_scheduler == "polynomial" else None,
1195
+ },
1196
+ "dataset_arguments": {
1197
+ "cache_latents": True,
1198
+ "debug_dataset": False,
1199
+ "vae_batch_size": vae_batch_size,
1200
+ },
1201
+ "training_arguments": {
1202
+ "output_dir": output_dir,
1203
+ "output_name": project_name,
1204
+ "save_precision": save_precision,
1205
+ "save_every_n_epochs": save_n_epochs_type_value if save_n_epochs_type == "save_every_n_epochs" else None,
1206
+ "save_n_epoch_ratio": save_n_epochs_type_value if save_n_epochs_type == "save_n_epoch_ratio" else None,
1207
+ "save_last_n_epochs": None,
1208
+ "save_state": None,
1209
+ "save_last_n_epochs_state": None,
1210
+ "resume": None,
1211
+ "train_batch_size": train_batch_size,
1212
+ "max_token_length": 225,
1213
+ "mem_eff_attn": False,
1214
+ "xformers": True,
1215
+ "max_train_epochs": num_epochs,
1216
+ "max_data_loader_n_workers": 8,
1217
+ "persistent_data_loader_workers": True,
1218
+ "seed": seed if seed > 0 else None,
1219
+ "gradient_checkpointing": gradient_checkpointing,
1220
+ "gradient_accumulation_steps": gradient_accumulation_steps,
1221
+ "mixed_precision": mixed_precision,
1222
+ "clip_skip": clip_skip if not v2 else None,
1223
+ "logging_dir": logging_dir,
1224
+ "log_prefix": project_name,
1225
+ "noise_offset": noise_offset if noise_offset > 0 else None,
1226
+ "lowram": lowram,
1227
+ },
1228
+ "sample_prompt_arguments": {
1229
+ "sample_every_n_steps": None,
1230
+ "sample_every_n_epochs": 1 if enable_sample_prompt else 999999,
1231
+ "sample_sampler": sampler,
1232
+ },
1233
+ "dreambooth_arguments": {
1234
+ "prior_loss_weight": 1.0,
1235
+ },
1236
+ "saving_arguments": {
1237
+ "save_model_as": save_model_as
1238
+ },
1239
+ }
1240
+
1241
+ config_path = os.path.join(config_dir, "config_file.toml")
1242
+ prompt_path = os.path.join(config_dir, "sample_prompt.txt")
1243
+
1244
+ for key in config:
1245
+ if isinstance(config[key], dict):
1246
+ for sub_key in config[key]:
1247
+ if config[key][sub_key] == "":
1248
+ config[key][sub_key] = None
1249
+ elif config[key] == "":
1250
+ config[key] = None
1251
+
1252
+ config_str = toml.dumps(config)
1253
+
1254
+ def write_file(filename, contents):
1255
+ with open(filename, "w") as f:
1256
+ f.write(contents)
1257
+
1258
+ write_file(config_path, config_str)
1259
+ write_file(prompt_path, sample_str)
1260
+
1261
+ print(config_str)
1262
+
1263
+ #@title ## 5.5. Start Training
1264
+
1265
+ #@markdown Check your config here if you want to edit something:
1266
+ #@markdown - `sample_prompt` : /content/LoRA/config/sample_prompt.txt
1267
+ #@markdown - `config_file` : /content/LoRA/config/config_file.toml
1268
+ #@markdown - `dataset_config` : /content/LoRA/config/dataset_config.toml
1269
+
1270
+ #@markdown Generated sample can be seen here: /content/LoRA/output/sample
1271
+
1272
+ #@markdown You can import config from another session if you want.
1273
+ sample_prompt = "/content/LoRA/config/sample_prompt.txt" #@param {type:'string'}
1274
+ config_file = "/content/LoRA/config/config_file.toml" #@param {type:'string'}
1275
+ dataset_config = "/content/LoRA/config/dataset_config.toml" #@param {type:'string'}
1276
+
1277
+ accelerate_conf = {
1278
+ "config_file" : accelerate_config,
1279
+ "num_cpu_threads_per_process" : 1,
1280
+ }
1281
+
1282
+ train_conf = {
1283
+ "sample_prompts" : sample_prompt,
1284
+ "dataset_config" : dataset_config,
1285
+ "config_file" : config_file
1286
+ }
1287
+
1288
+ def train(config):
1289
+ args = ""
1290
+ for k, v in config.items():
1291
+ if k.startswith("_"):
1292
+ args += f'"{v}" '
1293
+ elif isinstance(v, str):
1294
+ args += f'--{k}="{v}" '
1295
+ elif isinstance(v, bool) and v:
1296
+ args += f"--{k} "
1297
+ elif isinstance(v, float) and not isinstance(v, bool):
1298
+ args += f"--{k}={v} "
1299
+ elif isinstance(v, int) and not isinstance(v, bool):
1300
+ args += f"--{k}={v} "
1301
+
1302
+ return args
1303
+
1304
+ accelerate_args = train(accelerate_conf)
1305
+ train_args = train(train_conf)
1306
+ final_args = f"accelerate launch {accelerate_args} train_network.py {train_args}"
1307
+
1308
+ os.chdir(repo_dir)
1309
+ !{final_args}
1310
+
1311
+ """# VI. Testing"""
1312
+
1313
+ # Commented out IPython magic to ensure Python compatibility.
1314
+ # @title ## 6.1. Visualize loss graph (Optional)
1315
+ training_logs_path = "/content/LoRA/logs" # @param {type : "string"}
1316
+
1317
+ os.chdir(repo_dir)
1318
+ # %load_ext tensorboard
1319
+ # %tensorboard --logdir {training_logs_path}
1320
+
1321
+ # @title ## 6.2. Interrogating LoRA Weights
1322
+ # @markdown Now you can check if your LoRA trained properly.
1323
+ import os
1324
+ import torch
1325
+ import json
1326
+ from safetensors.torch import load_file
1327
+ from safetensors.torch import safe_open
1328
+
1329
+ # @markdown If you used `clip_skip = 2` during training, the values of `lora_te_text_model_encoder_layers_11_*` will be `0.0`, this is normal. These layers are not trained at this value of `Clip Skip`.
1330
+ network_weight = "" # @param {'type':'string'}
1331
+ verbose = False # @param {type:"boolean"}
1332
+
1333
+ def is_safetensors(path):
1334
+ return os.path.splitext(path)[1].lower() == ".safetensors"
1335
+
1336
+ def load_weight_data(file_path):
1337
+ if is_safetensors(file_path):
1338
+ return load_file(file_path)
1339
+ else:
1340
+ return torch.load(file_path, map_location="cuda")
1341
+
1342
+ def extract_lora_weights(weight_data):
1343
+ lora_weights = [
1344
+ (key, weight_data[key])
1345
+ for key in weight_data.keys()
1346
+ if "lora_up" in key or "lora_down" in key
1347
+ ]
1348
+ return lora_weights
1349
+
1350
+ def print_lora_weight_stats(lora_weights):
1351
+ print(f"Number of LoRA modules: {len(lora_weights)}")
1352
+
1353
+ for key, value in lora_weights:
1354
+ value = value.to(torch.float32)
1355
+ print(f"{key}, {torch.mean(torch.abs(value))}, {torch.min(torch.abs(value))}")
1356
+
1357
+ def print_metadata(file_path):
1358
+ if is_safetensors(file_path):
1359
+ with safe_open(file_path, framework="pt") as f:
1360
+ metadata = f.metadata()
1361
+ if metadata is not None:
1362
+ print(f"\nLoad metadata for: {file_path}")
1363
+ print(json.dumps(metadata, indent=4))
1364
+ else:
1365
+ print("No metadata saved, your model is not in safetensors format")
1366
+
1367
+ def main(file_path, verbose: bool):
1368
+ weight_data = load_weight_data(file_path)
1369
+
1370
+ if verbose:
1371
+ lora_weights = extract_lora_weights(weight_data)
1372
+ print_lora_weight_stats(lora_weights)
1373
+
1374
+ print_metadata(file_path)
1375
+
1376
+ if __name__ == "__main__":
1377
+ main(network_weight, verbose)
1378
+
1379
+ # Commented out IPython magic to ensure Python compatibility.
1380
+ # @title ## 6.3. Inference
1381
+ # %store -r
1382
+
1383
+ # @markdown ### LoRA Config
1384
+ # @markdown Currently, `LoHa` and `LoCon_Lycoris` are not supported. Please run `Portable Web UI` instead
1385
+ network_weight = "" # @param {'type':'string'}
1386
+ network_mul = 0.7 # @param {type:"slider", min:-1, max:2, step:0.05}
1387
+ network_module = "networks.lora"
1388
+ network_args = ""
1389
+
1390
+ # @markdown ### <br> General Config
1391
+ v2 = False # @param {type:"boolean"}
1392
+ v_parameterization = False # @param {type:"boolean"}
1393
+ prompt = "masterpiece, best quality, 1girl, aqua eyes, baseball cap, blonde hair, closed mouth, earrings, green background, hat, hoop earrings, jewelry, looking at viewer, shirt, short hair, simple background, solo, upper body, yellow shirt" # @param {type: "string"}
1394
+ negative = "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry" # @param {type: "string"}
1395
+ model = "/content/pretrained_model/AnyLoRA.safetensors" # @param {type: "string"}
1396
+ vae = "" # @param {type: "string"}
1397
+ outdir = "/content/tmp" # @param {type: "string"}
1398
+ scale = 7 # @param {type: "slider", min: 1, max: 40}
1399
+ sampler = "ddim" # @param ["ddim", "pndm", "lms", "euler", "euler_a", "heun", "dpm_2", "dpm_2_a", "dpmsolver","dpmsolver++", "dpmsingle", "k_lms", "k_euler", "k_euler_a", "k_dpm_2", "k_dpm_2_a"]
1400
+ steps = 28 # @param {type: "slider", min: 1, max: 100}
1401
+ precision = "fp16" # @param ["fp16", "bf16"] {allow-input: false}
1402
+ width = 512 # @param {type: "integer"}
1403
+ height = 768 # @param {type: "integer"}
1404
+ images_per_prompt = 4 # @param {type: "integer"}
1405
+ batch_size = 4 # @param {type: "integer"}
1406
+ clip_skip = 2 # @param {type: "slider", min: 1, max: 40}
1407
+ seed = -1 # @param {type: "integer"}
1408
+
1409
+ final_prompt = f"{prompt} --n {negative}"
1410
+
1411
+ config = {
1412
+ "v2": v2,
1413
+ "v_parameterization": v_parameterization,
1414
+ "network_module": network_module,
1415
+ "network_weight": network_weight,
1416
+ "network_mul": float(network_mul),
1417
+ "network_args": eval(network_args) if network_args else None,
1418
+ "ckpt": model,
1419
+ "outdir": outdir,
1420
+ "xformers": True,
1421
+ "vae": vae if vae else None,
1422
+ "fp16": True,
1423
+ "W": width,
1424
+ "H": height,
1425
+ "seed": seed if seed > 0 else None,
1426
+ "scale": scale,
1427
+ "sampler": sampler,
1428
+ "steps": steps,
1429
+ "max_embeddings_multiples": 3,
1430
+ "batch_size": batch_size,
1431
+ "images_per_prompt": images_per_prompt,
1432
+ "clip_skip": clip_skip if not v2 else None,
1433
+ "prompt": final_prompt,
1434
+ }
1435
+
1436
+ args = ""
1437
+ for k, v in config.items():
1438
+ if k.startswith("_"):
1439
+ args += f'"{v}" '
1440
+ elif isinstance(v, str):
1441
+ args += f'--{k}="{v}" '
1442
+ elif isinstance(v, bool) and v:
1443
+ args += f"--{k} "
1444
+ elif isinstance(v, float) and not isinstance(v, bool):
1445
+ args += f"--{k}={v} "
1446
+ elif isinstance(v, int) and not isinstance(v, bool):
1447
+ args += f"--{k}={v} "
1448
+
1449
+ final_args = f"python gen_img_diffusers.py {args}"
1450
+
1451
+ os.chdir(repo_dir)
1452
+ !{final_args}
1453
+
1454
+ #@title ## 6.4. Launch Portable Web UI
1455
+ import os
1456
+ import random
1457
+ import shutil
1458
+ import zipfile
1459
+ import time
1460
+ import json
1461
+ from google.colab import drive
1462
+ from datetime import timedelta
1463
+ from subprocess import getoutput
1464
+ from IPython.display import clear_output, display, HTML
1465
+ from IPython.utils import capture
1466
+ from tqdm import tqdm
1467
+
1468
+ webui_dir = os.path.join(root_dir, "stable-diffusion-webui")
1469
+ tmp_dir = os.path.join(root_dir, "tmp")
1470
+ patches_dir = os.path.join(root_dir, "patches")
1471
+ deps_dir = os.path.join(root_dir, "deps")
1472
+ extensions_dir = os.path.join(webui_dir, "extensions")
1473
+ control_dir = os.path.join(webui_dir, "models/ControlNet")
1474
+
1475
+ webui_models_dir = os.path.join(webui_dir, "models/Stable-diffusion")
1476
+ webui_lora_dir = os.path.join(webui_dir, "models/Lora")
1477
+ webui_vaes_dir = os.path.join(webui_dir, "models/VAE")
1478
+
1479
+ control_net_max_models_num = 2
1480
+ theme = "ogxBGreen"
1481
+
1482
+ default_prompt = "masterpiece, best quality,"
1483
+ default_neg_prompt = "(worst quality, low quality:1.4)"
1484
+ default_sampler = "DPM++ 2M Karras"
1485
+ default_steps = 20
1486
+ default_width = 512
1487
+ default_height = 768
1488
+ default_denoising_strength = 0.55
1489
+ default_cfg_scale = 7
1490
+
1491
+ config_file = os.path.join(webui_dir, "config.json")
1492
+ ui_config_file = os.path.join(webui_dir, "ui-config.json")
1493
+ webui_style_path = os.path.join(webui_dir, "style.css")
1494
+
1495
+ os.chdir(root_dir)
1496
+
1497
+ for dir in [patches_dir, deps_dir]:
1498
+ os.makedirs(dir, exist_ok=True)
1499
+
1500
+ package_url = [
1501
+ f"https://huggingface.co/Linaqruf/fast-repo/resolve/main/anapnoe-webui.tar.lz4",
1502
+ f"https://huggingface.co/Linaqruf/fast-repo/resolve/main/anapnoe-webui-deps.tar.lz4",
1503
+ f"https://huggingface.co/Linaqruf/fast-repo/resolve/main/anapnoe-webui-cache.tar.lz4",
1504
+ ]
1505
+
1506
+ def pre_download(desc):
1507
+ for package in tqdm(package_url, desc=desc):
1508
+ with capture.capture_output() as cap:
1509
+ package_name = os.path.basename(package)
1510
+ !aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {root_dir} -o {package_name} {package}
1511
+ if package_name == f"anapnoe-webui-deps.tar.lz4":
1512
+ !tar -xI lz4 -f {package_name} --overwrite-dir --directory=/usr/local/lib/python3.10/dist-packages/
1513
+ else:
1514
+ !tar -xI lz4 -f {package_name} --directory=/
1515
+ os.remove(package_name)
1516
+ del cap
1517
+
1518
+ if os.path.exists("/usr/local/lib/python3.10/dist-packages/ffmpy-0.3.0.dist-info"):
1519
+ shutil.rmtree("/usr/local/lib/python3.10/dist-packages/ffmpy-0.3.0.dist-info")
1520
+
1521
+ s = getoutput("nvidia-smi")
1522
+ with capture.capture_output() as cap:
1523
+ if not "T4" in s:
1524
+ !pip uninstall -y xformers
1525
+ !pip install -q xformers==0.0.18 triton
1526
+ del cap
1527
+
1528
+
1529
+ def read_config(filename):
1530
+ if filename.endswith(".json"):
1531
+ with open(filename, "r") as f:
1532
+ config = json.load(f)
1533
+ else:
1534
+ with open(filename, 'r') as f:
1535
+ config = f.read()
1536
+ return config
1537
+
1538
+
1539
+ def write_config(filename, config):
1540
+ if filename.endswith(".json"):
1541
+ with open(filename, "w") as f:
1542
+ json.dump(config, f, indent=4)
1543
+ else:
1544
+ with open(filename, 'w', encoding="utf-8") as f:
1545
+ f.write(config)
1546
+
1547
+
1548
+ def open_theme(filename):
1549
+ themes_folder = os.path.join(webui_dir, "extensions-builtin/sd_theme_editor/themes")
1550
+ themes_file = os.path.join(themes_folder, f"{filename}.css")
1551
+ webui_style_path = os.path.join(webui_dir, "style.css")
1552
+
1553
+ style_config = read_config(webui_style_path)
1554
+ style_css_contents = style_config.split("/*BREAKPOINT_CSS_CONTENT*/")[1]
1555
+
1556
+ theme_config = read_config(themes_file)
1557
+ style_data = ":host{" + theme_config + "}" + "/*BREAKPOINT_CSS_CONTENT*/" + style_css_contents
1558
+ write_config(webui_style_path, style_data)
1559
+
1560
+
1561
+ def change_config(filename):
1562
+ config = read_config(filename)
1563
+ if not "stable-diffusion-webui" in config["disabled_extensions"]:
1564
+ config["disabled_extensions"].append("stable-diffusion-webui")
1565
+ config["outdir_txt2img_samples"] = os.path.join(tmp_dir, "outputs/txt2img-images")
1566
+ config["outdir_img2img_samples"] = os.path.join(tmp_dir, "outputs/img2img-images")
1567
+ config["outdir_extras_samples"] = os.path.join(tmp_dir, "outputs/extras-images")
1568
+ config["outdir_txt2img_grids"] = os.path.join(tmp_dir, "outputs/txt2img-grids")
1569
+ config["outdir_img2img_grids"] = os.path.join(tmp_dir, "outputs/img2img-grids")
1570
+ config["outdir_save"] = os.path.join(tmp_dir, "log/images")
1571
+ config["control_net_max_models_num"] = control_net_max_models_num
1572
+ config["control_net_models_path"] = control_dir
1573
+ config["control_net_allow_script_control"] = True
1574
+ config["additional_networks_extra_lora_path"] = webui_lora_dir
1575
+ config["CLIP_stop_at_last_layers"] = 2
1576
+ config["eta_noise_seed_delta"] = 0
1577
+ config["show_progress_every_n_steps"] = 10
1578
+ config["show_progressbar"] = True
1579
+ config["quicksettings"] = "sd_model_checkpoint, sd_vae, CLIP_stop_at_last_layers, use_old_karras_scheduler_sigmas, always_discard_next_to_last_sigma"
1580
+ write_config(filename, config)
1581
+
1582
+
1583
+ def change_ui_config(filename):
1584
+ config = read_config(filename)
1585
+ config["txt2img/Prompt/value"] = default_prompt
1586
+ config["txt2img/Negative prompt/value"] = default_neg_prompt
1587
+ config["txt2img/Sampling method/value"] = default_sampler
1588
+ config["txt2img/Sampling steps/value"] = default_steps
1589
+ config["txt2img/Width/value"] = default_width
1590
+ config["txt2img/Height/value"] = default_height
1591
+ config["txt2img/Upscaler/value"] = "Latent (nearest-exact)"
1592
+ config["txt2img/Denoising strength/value"] = default_denoising_strength
1593
+ config["txt2img/CFG Scale/value"] = default_cfg_scale
1594
+ config["img2img/Prompt/value"] = default_prompt
1595
+ config["img2img/Negative prompt/value"] = default_neg_prompt
1596
+ config["img2img/Sampling method/value"] = default_sampler
1597
+ config["img2img/Sampling steps/value"] = default_steps
1598
+ config["img2img/Width/value"] = default_width
1599
+ config["img2img/Height/value"] = default_height
1600
+ config["img2img/Denoising strength/value"] = default_denoising_strength
1601
+ config["img2img/CFG Scale/value"] = default_cfg_scale
1602
+ write_config(filename, config)
1603
+
1604
+
1605
+ def update_extensions():
1606
+ start_time = time.time()
1607
+ extensions_updated = []
1608
+ with tqdm(
1609
+ total=len(os.listdir(extensions_dir)),
1610
+ desc="Updating extensions",
1611
+ mininterval=0,
1612
+ ) as pbar:
1613
+ for dir in os.listdir(extensions_dir):
1614
+ if os.path.isdir(os.path.join(extensions_dir, dir)):
1615
+ os.chdir(os.path.join(extensions_dir, dir))
1616
+ try:
1617
+ with capture.capture_output() as cap:
1618
+ !git fetch origin
1619
+ !git pull
1620
+ except Exception as e:
1621
+ print(f"An error occurred while updating {dir}: {e}")
1622
+
1623
+ output = cap.stdout.strip()
1624
+ if "Already up to date." not in output:
1625
+ extensions_updated.append(dir)
1626
+ pbar.update(1)
1627
+
1628
+ print("\n")
1629
+ for ext in extensions_updated:
1630
+ print(f"- {ext} updated to new version")
1631
+
1632
+ end_time = time.time()
1633
+ elapsed_time = int(end_time - start_time)
1634
+
1635
+ if elapsed_time < 60:
1636
+ print(f"\nAll extensions are up to date. Took {elapsed_time} sec")
1637
+ else:
1638
+ mins, secs = divmod(elapsed_time, 60)
1639
+ print(f"\nAll extensions are up to date. Took {mins} mins {secs} sec")
1640
+
1641
+
1642
+ def main():
1643
+ start_time = time.time()
1644
+
1645
+ print("Installing...\n")
1646
+
1647
+ if not os.path.exists(webui_dir):
1648
+ desc = "Unpacking Webui"
1649
+ pre_download(desc)
1650
+ else:
1651
+ print("Already installed, skipping...")
1652
+
1653
+ with capture.capture_output() as cap:
1654
+ os.chdir(os.path.join(webui_dir, "repositories/stable-diffusion-stability-ai"))
1655
+ !git apply {patches_dir}/stablediffusion-lowram.patch
1656
+
1657
+ !sed -i "s@os.path.splitext(checkpoint_.*@os.path.splitext(checkpoint_file); map_location='cuda'@" {webui_dir}/modules/sd_models.py
1658
+ !sed -i 's@ui.create_ui().*@ui.create_ui();shared.demo.queue(concurrency_count=999999,status_update_rate=0.1)@' {webui_dir}/webui.py
1659
+
1660
+ !sed -i "s@'cpu'@'cuda'@" {webui_dir}/modules/extras.py
1661
+ del cap
1662
+
1663
+ end_time = time.time()
1664
+ elapsed_time = int(end_time - start_time)
1665
+
1666
+ change_config(config_file)
1667
+ change_ui_config(ui_config_file)
1668
+ open_theme(theme)
1669
+
1670
+ if elapsed_time < 60:
1671
+ print(f"Finished unpacking. Took {elapsed_time} sec")
1672
+ else:
1673
+ mins, secs = divmod(elapsed_time, 60)
1674
+ print(f"Finished unpacking. Took {mins} mins {secs} sec")
1675
+
1676
+ update_extensions()
1677
+
1678
+ #@markdown > Get <b>your</b> `ngrok_token` [here](https://dashboard.ngrok.com/get-started/your-authtoken)
1679
+ ngrok_token = "" #@param {type: 'string'}
1680
+ ngrok_region = "ap" #@param ["us", "eu", "au", "ap", "sa", "jp", "in"]
1681
+
1682
+ with capture.capture_output() as cap:
1683
+ for file in os.listdir(output_dir):
1684
+ file_path = os.path.join(output_dir, file)
1685
+ if file_path.endswith((".safetensors", ".pt", ".ckpt")):
1686
+ !ln "{file_path}" {webui_lora_dir}
1687
+
1688
+ for file in os.listdir(pretrained_model):
1689
+ file_path = os.path.join(pretrained_model, file)
1690
+ if file_path.endswith((".safetensors", ".ckpt")):
1691
+ !ln "{file_path}" {webui_models_dir}
1692
+
1693
+ for file in os.listdir(vae_dir):
1694
+ file_path = os.path.join(vae_dir, file)
1695
+ if file_path.endswith(".vae.pt"):
1696
+ !ln "{file_path}" {webui_vaes_dir}
1697
+
1698
+ del cap
1699
+
1700
+ os.chdir(webui_dir)
1701
+
1702
+ print("")
1703
+
1704
+ config = {
1705
+ "enable-insecure-extension-access": True,
1706
+ "disable-safe-unpickle": True,
1707
+ "multiple": True if not ngrok_token else False,
1708
+ "ckpt-dir": webui_models_dir,
1709
+ "vae-dir": webui_vaes_dir,
1710
+ "share": True if not ngrok_token else False,
1711
+ "no-half-vae": True,
1712
+ "lowram": True,
1713
+ "gradio-queue": True,
1714
+ "no-hashing": True,
1715
+ "disable-console-progressbars": True,
1716
+ "ngrok": ngrok_token if ngrok_token else None,
1717
+ "ngrok-region": ngrok_region if ngrok_token else None,
1718
+ "xformers": True,
1719
+ "opt-sub-quad-attention": True,
1720
+ "opt-channelslast": True,
1721
+ "theme": "dark"
1722
+ }
1723
+
1724
+ args = ""
1725
+ for k, v in config.items():
1726
+ if k.startswith("_"):
1727
+ args += f'"{v}" '
1728
+ elif isinstance(v, str):
1729
+ args += f'--{k}="{v}" '
1730
+ elif isinstance(v, bool) and v:
1731
+ args += f"--{k} "
1732
+ elif isinstance(v, float) and not isinstance(v, bool):
1733
+ args += f"--{k}={v} "
1734
+ elif isinstance(v, int) and not isinstance(v, bool):
1735
+ args += f"--{k}={v} "
1736
+
1737
+ final_args = f"python launch.py {args}"
1738
+
1739
+ os.chdir(webui_dir)
1740
+ !{final_args}
1741
+
1742
+ main()
1743
+
1744
+ """# VII. Deployment"""
1745
+
1746
+ # @title ## 7.1. Upload Config
1747
+ from huggingface_hub import login
1748
+ from huggingface_hub import HfApi
1749
+ from huggingface_hub.utils import validate_repo_id, HfHubHTTPError
1750
+
1751
+ # @markdown Login to Huggingface Hub
1752
+ # @markdown > Get **your** huggingface `WRITE` token [here](https://huggingface.co/settings/tokens)
1753
+ write_token = "" # @param {type:"string"}
1754
+ # @markdown Fill this if you want to upload to your organization, or just leave it empty.
1755
+ orgs_name = "" # @param{type:"string"}
1756
+ # @markdown If your model/dataset repo does not exist, it will automatically create it.
1757
+ model_name = "your-model-name" # @param{type:"string"}
1758
+ dataset_name = "your-dataset-name" # @param{type:"string"}
1759
+ make_private = False # @param{type:"boolean"}
1760
+
1761
+ def authenticate(write_token):
1762
+ login(write_token, add_to_git_credential=True)
1763
+ api = HfApi()
1764
+ return api.whoami(write_token), api
1765
+
1766
+
1767
+ def create_repo(api, user, orgs_name, repo_name, repo_type, make_private=False):
1768
+ global model_repo
1769
+ global datasets_repo
1770
+
1771
+ if orgs_name == "":
1772
+ repo_id = user["name"] + "/" + repo_name.strip()
1773
+ else:
1774
+ repo_id = orgs_name + "/" + repo_name.strip()
1775
+
1776
+ try:
1777
+ validate_repo_id(repo_id)
1778
+ api.create_repo(repo_id=repo_id, repo_type=repo_type, private=make_private)
1779
+ print(f"{repo_type.capitalize()} repo '{repo_id}' didn't exist, creating repo")
1780
+ except HfHubHTTPError as e:
1781
+ print(f"{repo_type.capitalize()} repo '{repo_id}' exists, skipping create repo")
1782
+
1783
+ if repo_type == "model":
1784
+ model_repo = repo_id
1785
+ print(f"{repo_type.capitalize()} repo '{repo_id}' link: https://huggingface.co/{repo_id}\n")
1786
+ else:
1787
+ datasets_repo = repo_id
1788
+ print(f"{repo_type.capitalize()} repo '{repo_id}' link: https://huggingface.co/datasets/{repo_id}\n")
1789
+
1790
+ user, api = authenticate(write_token)
1791
+
1792
+ if model_name:
1793
+ create_repo(api, user, orgs_name, model_name, "model", make_private)
1794
+ if dataset_name:
1795
+ create_repo(api, user, orgs_name, dataset_name, "dataset", make_private)
1796
+
1797
+ """## 7.2. Upload with Huggingface Hub"""
1798
+
1799
+ # Commented out IPython magic to ensure Python compatibility.
1800
+ # @title ### 7.2.1. Upload LoRA
1801
+ from huggingface_hub import HfApi
1802
+ from pathlib import Path
1803
+
1804
+ # %store -r
1805
+
1806
+ api = HfApi()
1807
+
1808
+ # @markdown This will be uploaded to model repo
1809
+ model_path = "/content/LoRA/output" # @param {type :"string"}
1810
+ path_in_repo = "" # @param {type :"string"}
1811
+
1812
+ # @markdown Now you can save your config file for future use
1813
+ config_path = "/content/LoRA/config" # @param {type :"string"}
1814
+
1815
+ # @markdown Other Information
1816
+ commit_message = "" # @param {type :"string"}
1817
+
1818
+ if not commit_message:
1819
+ commit_message = f"feat: upload {project_name} lora model"
1820
+
1821
+ def upload_to_hf(model_path, is_folder, is_config):
1822
+ path_obj = Path(model_path)
1823
+ trained_model = path_obj.parts[-1]
1824
+
1825
+ if path_in_repo:
1826
+ trained_model = path_in_repo
1827
+
1828
+ if is_config:
1829
+ trained_model = f"{project_name}_config"
1830
+
1831
+ print(f"Uploading {trained_model} to https://huggingface.co/{model_repo}")
1832
+ print("Please wait...")
1833
+
1834
+ if is_folder:
1835
+ api.upload_folder(
1836
+ folder_path=model_path,
1837
+ path_in_repo=trained_model,
1838
+ repo_id=model_repo,
1839
+ commit_message=commit_message,
1840
+ ignore_patterns=".ipynb_checkpoints",
1841
+ )
1842
+ print(f"Upload success, located at https://huggingface.co/{model_repo}/tree/main\n")
1843
+ else:
1844
+ api.upload_file(
1845
+ path_or_fileobj=model_path,
1846
+ path_in_repo=trained_model,
1847
+ repo_id=model_repo,
1848
+ commit_message=commit_message,
1849
+ )
1850
+ print(f"Upload success, located at https://huggingface.co/{model_repo}/blob/main/{trained_model}\n")
1851
+
1852
+ def upload():
1853
+ is_model_file = model_path.endswith((".ckpt", ".safetensors", ".pt"))
1854
+ upload_to_hf(model_path, not is_model_file, False)
1855
+
1856
+ if config_path:
1857
+ upload_to_hf(config_path, True, True)
1858
+
1859
+ upload()
1860
+
1861
+ # @title ### 7.2.2. Upload Dataset
1862
+ from huggingface_hub import HfApi
1863
+ from pathlib import Path
1864
+ import shutil
1865
+ import zipfile
1866
+ import os
1867
+
1868
+ api = HfApi()
1869
+
1870
+ # @markdown This will be compressed to zip and uploaded to datasets repo, leave it empty if not necessary
1871
+ train_data_path = "/content/LoRA/train_data" # @param {type :"string"}
1872
+
1873
+ # @markdown `Nerd stuff, only if you want to save training logs`
1874
+ logs_path = "/content/LoRA/logs" # @param {type :"string"}
1875
+
1876
+ tmp_dataset = f"/content/LoRA/{project_name}_dataset" if project_name else "/content/LoRA/tmp_dataset"
1877
+ tmp_train_data = f"{tmp_dataset}/train_data"
1878
+ dataset_zip = f"{tmp_dataset}.zip"
1879
+
1880
+ # @markdown Other Information
1881
+ commit_message = "" # @param {type :"string"}
1882
+
1883
+ if not commit_message:
1884
+ commit_message = f"feat: upload {project_name} dataset and logs"
1885
+
1886
+ os.makedirs(tmp_dataset, exist_ok=True)
1887
+ os.makedirs(tmp_train_data, exist_ok=True)
1888
+
1889
+ def upload_dataset(dataset_path, is_zip):
1890
+ path_obj = Path(dataset_path)
1891
+ dataset_name = path_obj.parts[-1]
1892
+
1893
+ print(f"Uploading {dataset_name} to https://huggingface.co/datasets/{datasets_repo}")
1894
+ print("Please wait...")
1895
+
1896
+ if is_zip:
1897
+ api.upload_file(
1898
+ path_or_fileobj=dataset_path,
1899
+ path_in_repo=dataset_name,
1900
+ repo_id=datasets_repo,
1901
+ repo_type="dataset",
1902
+ commit_message=commit_message,
1903
+ )
1904
+ print(f"Upload success, located at https://huggingface.co/datasets/{datasets_repo}/blob/main/{dataset_name}\n")
1905
+ else:
1906
+ api.upload_folder(
1907
+ folder_path=dataset_path,
1908
+ path_in_repo=dataset_name,
1909
+ repo_id=datasets_repo,
1910
+ repo_type="dataset",
1911
+ commit_message=commit_message,
1912
+ ignore_patterns=".ipynb_checkpoints",
1913
+ )
1914
+ print(f"Upload success, located at https://huggingface.co/datasets/{datasets_repo}/tree/main/{dataset_name}\n")
1915
+
1916
+ def zip_file(folder_path):
1917
+ zip_path = f"{folder_path}.zip"
1918
+ with zipfile.ZipFile(zip_path, "w") as zip_file:
1919
+ for root, dirs, files in os.walk(folder_path):
1920
+ for file in files:
1921
+ zip_file.write(os.path.join(root, file))
1922
+
1923
+ def move(src_path, dst_path, move_metadata):
1924
+ metadata_files = [
1925
+ "meta_cap.json",
1926
+ "meta_cap_dd.json",
1927
+ "meta_lat.json",
1928
+ "meta_clean.json",
1929
+ "meta_final.json",
1930
+ ]
1931
+
1932
+ if os.path.exists(src_path):
1933
+ shutil.move(src_path, dst_path)
1934
+
1935
+ if move_metadata:
1936
+ parent_meta_path = os.path.dirname(src_path)
1937
+
1938
+ for filename in os.listdir(parent_meta_path):
1939
+ file_path = os.path.join(parent_meta_path, filename)
1940
+ if filename in metadata_files:
1941
+ shutil.move(file_path, dst_path)
1942
+
1943
+ def upload():
1944
+ if train_data_path:
1945
+ move(train_data_path, tmp_train_data, False)
1946
+ zip_file(tmp_dataset)
1947
+ upload_dataset(dataset_zip, True)
1948
+ os.remove(dataset_zip)
1949
+ if logs_path:
1950
+ upload_dataset(logs_path, False)
1951
+
1952
+ upload()
1953
+
1954
+ """## 7.3. Upload with GIT (Alternative)"""
1955
+
1956
+ # @title ### 7.3.1. Clone Repository
1957
+
1958
+ clone_model = True # @param {'type': 'boolean'}
1959
+ clone_dataset = True # @param {'type': 'boolean'}
1960
+
1961
+ def clone_repository(repo_url, local_path):
1962
+ !git lfs install --skip-smudge
1963
+ os.environ["GIT_LFS_SKIP_SMUDGE"] = "1"
1964
+ !git clone {repo_url} {local_path}
1965
+
1966
+ if clone_model:
1967
+ clone_repository(f"https://huggingface.co/{model_repo}", f"/content/{model_name}")
1968
+
1969
+ if clone_dataset:
1970
+ clone_repository(f"https://huggingface.co/datasets/{datasets_repo}", f"/content/{dataset_name}")
1971
+
1972
+ # @title ### 7.3.2. Commit using Git
1973
+ import os
1974
+
1975
+ os.chdir(root_dir)
1976
+
1977
+ # @markdown Choose which repo you want to commit
1978
+ commit_model = True # @param {'type': 'boolean'}
1979
+ commit_dataset = True # @param {'type': 'boolean'}
1980
+ # @markdown Other Information
1981
+ commit_message = "" # @param {type :"string"}
1982
+
1983
+ if not commit_message:
1984
+ commit_message = f"feat: upload {project_name} lora model and dataset"
1985
+
1986
+ !git config --global user.email "example@mail.com"
1987
+ !git config --global user.name "example"
1988
+
1989
+ def commit(repo_folder, commit_message):
1990
+ os.chdir(os.path.join(root_dir, repo_folder))
1991
+ !git lfs install
1992
+ !huggingface-cli lfs-enable-largefiles .
1993
+ !git add .
1994
+ !git commit -m "{commit_message}"
1995
+ !git push
1996
+
1997
+
1998
+ if commit_model:
1999
+ commit(model_name, commit_message)
2000
+
2001
+ if commit_dataset:
2002
+ commit(dataset_name, commit_message)