lsmpp commited on
Commit
d926b4c
·
verified ·
1 Parent(s): 8e244f5

Add files using upload-large-folder tool

Browse files
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ /models/
2
+
3
+ /download.py
4
+
5
+ /illustrious_generated
6
+
7
+ *.png
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.12
.vscode/launch.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "name": "Python Debugger: Current File",
9
+ "type": "debugpy",
10
+ "request": "launch",
11
+ "program": "${file}",
12
+ "console": "integratedTerminal",
13
+ "justMyCode": false
14
+ },
15
+ ]
16
+ }
README.md CHANGED
@@ -1,3 +0,0 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
civitai_image.csv ADDED
The diff for this file is too large to render. See raw diff
 
civitai_image.csv.backup ADDED
The diff for this file is too large to render. See raw diff
 
data_quality_optimization.log ADDED
File without changes
demo.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Qwen-SDXL 架构演示
3
+ 演示如何将 Qwen3 Embedding 集成到 SDXL 管道中
4
+
5
+ 这个脚本展示了我们的核心设计思路:
6
+ 1. 使用 Qwen3 Embedding 替代 CLIP text encoder
7
+ 2. 通过 Adapter 层处理维度不匹配问题
8
+ 3. 保持 SDXL 的其他组件不变
9
+ """
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ from typing import List, Optional, Union, Tuple
14
+ import matplotlib.pyplot as plt
15
+ import numpy as np
16
+
17
+
18
+ class QwenEmbeddingAdapter(nn.Module):
19
+ """
20
+ Qwen3 Embedding 到 SDXL 的适配器层
21
+
22
+ 功能:
23
+ - 将 Qwen3 的 1024 维嵌入投影到 SDXL 需要的 2048 维
24
+ - 添加必要的激活函数和归一化
25
+ - 处理序列长度适配
26
+ """
27
+
28
+ def __init__(self, qwen_dim=1024, sdxl_dim=2048, dropout=0.1):
29
+ super().__init__()
30
+
31
+ # 主投影层
32
+ self.projection = nn.Sequential(
33
+ nn.Linear(qwen_dim, sdxl_dim // 2),
34
+ nn.GELU(),
35
+ nn.Dropout(dropout),
36
+ nn.Linear(sdxl_dim // 2, sdxl_dim),
37
+ )
38
+
39
+ # 层归一化
40
+ self.layer_norm = nn.LayerNorm(sdxl_dim)
41
+
42
+ # 残差连接的投影(用于跳过连接)
43
+ self.skip_projection = nn.Linear(qwen_dim, sdxl_dim)
44
+
45
+ # 初始化权重
46
+ self._init_weights()
47
+
48
+ def _init_weights(self):
49
+ """初始化网络权重"""
50
+ for module in self.modules():
51
+ if isinstance(module, nn.Linear):
52
+ nn.init.xavier_uniform_(module.weight)
53
+ if module.bias is not None:
54
+ nn.init.zeros_(module.bias)
55
+
56
+ def forward(self, qwen_embeddings):
57
+ """
58
+ 前向传播
59
+
60
+ Args:
61
+ qwen_embeddings: [batch_size, seq_len, 1024] 或 [batch_size, 1024]
62
+
63
+ Returns:
64
+ projected_embeddings: [batch_size, seq_len, 2048] 或 [batch_size, 2048]
65
+ """
66
+ # 主路径
67
+ main_output = self.projection(qwen_embeddings)
68
+
69
+ # 跳过连接
70
+ skip_output = self.skip_projection(qwen_embeddings)
71
+
72
+ # 残差连接 + 层归一化
73
+ output = self.layer_norm(main_output + skip_output)
74
+
75
+ return output
76
+
77
+
78
+ def simulate_qwen_embedding(batch_size: int, seq_len: int = 1, dim: int = 1024) -> torch.Tensor:
79
+ """
80
+ 模拟 Qwen3 Embedding 的输出
81
+ 在实际使用中,这会被真实的 Qwen3 模型替代
82
+ """
83
+ return torch.randn(batch_size, seq_len, dim)
84
+
85
+
86
+ def simulate_clip_embedding(batch_size: int, seq_len: int = 77, dim: int = 2048) -> torch.Tensor:
87
+ """
88
+ 模拟 CLIP 的嵌入输出,用于对比
89
+ """
90
+ return torch.randn(batch_size, seq_len, dim)
91
+
92
+
93
+ class QwenSDXLTextEncoder(nn.Module):
94
+ """
95
+ 完整的 Qwen-SDXL 文本编码器
96
+
97
+ 组合了:
98
+ 1. Qwen3 Embedding Model (模拟)
99
+ 2. Adapter Layer
100
+ 3. 序列长度处理
101
+ """
102
+
103
+ def __init__(self, qwen_dim=1024, sdxl_dim=2048, max_seq_len=77):
104
+ super().__init__()
105
+
106
+ self.qwen_dim = qwen_dim
107
+ self.sdxl_dim = sdxl_dim
108
+ self.max_seq_len = max_seq_len
109
+
110
+ # Qwen3 适配器
111
+ self.adapter = QwenEmbeddingAdapter(qwen_dim, sdxl_dim)
112
+
113
+ # 位置编码(如果需要)
114
+ self.position_embeddings = nn.Parameter(
115
+ torch.randn(1, max_seq_len, sdxl_dim) * 0.02
116
+ )
117
+
118
+ def encode_text(self, texts: List[str]) -> Tuple[torch.Tensor, torch.Tensor]:
119
+ """
120
+ 编码文本为 SDXL 兼容的嵌入
121
+
122
+ Args:
123
+ texts: 文本列表
124
+
125
+ Returns:
126
+ prompt_embeds: [batch_size, seq_len, 2048] - 序列嵌入
127
+ pooled_embeds: [batch_size, 2048] - 池化嵌入
128
+ """
129
+ batch_size = len(texts)
130
+
131
+ # 1. 模拟 Qwen3 编码过程 (在实际实现中使用真实的 Qwen3)
132
+ # 这里我们假设 Qwen3 为每个文本输出一个全局嵌入
133
+ qwen_embeddings = simulate_qwen_embedding(batch_size, 1, self.qwen_dim)
134
+
135
+ # 2. 扩展到序列长度 (CLIP 使用 77 个 token)
136
+ qwen_embeddings_seq = qwen_embeddings.expand(-1, self.max_seq_len, -1)
137
+
138
+ # 3. 通过适配器投影到 SDXL 维度
139
+ projected_embeddings = self.adapter(qwen_embeddings_seq)
140
+
141
+ # 4. 添加位置编码
142
+ prompt_embeds = projected_embeddings + self.position_embeddings
143
+
144
+ # 5. 创建池化嵌入 (SDXL 需要)
145
+ pooled_embeds = prompt_embeds.mean(dim=1) # 简单平均池化
146
+
147
+ return prompt_embeds, pooled_embeds
148
+
149
+ def forward(self, texts: List[str]) -> Tuple[torch.Tensor, torch.Tensor]:
150
+ return self.encode_text(texts)
151
+
152
+
153
+ def compare_embeddings():
154
+ """
155
+ 比较 Qwen-SDXL 和原始 CLIP 的嵌入
156
+ """
157
+ print("🔍 比较 Qwen-SDXL 与 CLIP 嵌入")
158
+ print("=" * 50)
159
+
160
+ # 初始化模型
161
+ qwen_encoder = QwenSDXLTextEncoder()
162
+
163
+ # 测试文本
164
+ test_texts = [
165
+ "A beautiful landscape painting",
166
+ "A cute cat with blue eyes",
167
+ "Abstract art with vibrant colors"
168
+ ]
169
+
170
+ print(f"📝 测试文本数量: {len(test_texts)}")
171
+
172
+ # Qwen-SDXL 编码
173
+ with torch.no_grad():
174
+ qwen_prompt_embeds, qwen_pooled_embeds = qwen_encoder(test_texts)
175
+
176
+ # CLIP 编码 (模拟)
177
+ clip_prompt_embeds = simulate_clip_embedding(len(test_texts))
178
+ clip_pooled_embeds = clip_prompt_embeds.mean(dim=1)
179
+
180
+ # 打印维度信息
181
+ print(f"\n📊 嵌入维度对比:")
182
+ print(f" Qwen-SDXL 序列嵌入: {qwen_prompt_embeds.shape}")
183
+ print(f" Qwen-SDXL 池化嵌入: {qwen_pooled_embeds.shape}")
184
+ print(f" CLIP 序列嵌入: {clip_prompt_embeds.shape}")
185
+ print(f" CLIP 池化嵌入: {clip_pooled_embeds.shape}")
186
+
187
+ # 计算统计信息
188
+ print(f"\n📈 嵌入统计:")
189
+ print(f" Qwen-SDXL 序列嵌入 - 均值: {qwen_prompt_embeds.mean():.4f}, 标准差: {qwen_prompt_embeds.std():.4f}")
190
+ print(f" Qwen-SDXL 池化嵌入 - 均值: {qwen_pooled_embeds.mean():.4f}, 标准差: {qwen_pooled_embeds.std():.4f}")
191
+ print(f" CLIP 序列嵌入 - 均值: {clip_prompt_embeds.mean():.4f}, 标准差: {clip_prompt_embeds.std():.4f}")
192
+
193
+ return qwen_prompt_embeds, qwen_pooled_embeds, clip_prompt_embeds, clip_pooled_embeds
194
+
195
+
196
+ def visualize_adapter_transformation():
197
+ """
198
+ 可视化适配器的变换过程
199
+ """
200
+ print("\n🎨 可视化适配器变换过程")
201
+ print("=" * 30)
202
+
203
+ # 创建适配器
204
+ adapter = QwenEmbeddingAdapter()
205
+
206
+ # 生成测试数据
207
+ batch_size = 5
208
+ input_embeddings = torch.randn(batch_size, 1024) # Qwen3 输出
209
+
210
+ # 通过适配器
211
+ with torch.no_grad():
212
+ output_embeddings = adapter(input_embeddings)
213
+
214
+ print(f"输入维度: {input_embeddings.shape}")
215
+ print(f"输出维度: {output_embeddings.shape}")
216
+ print(f"维度扩展比例: {output_embeddings.shape[-1] / input_embeddings.shape[-1]:.1f}x")
217
+
218
+ # 计算变换统计
219
+ input_norm = torch.norm(input_embeddings, dim=-1).mean()
220
+ output_norm = torch.norm(output_embeddings, dim=-1).mean()
221
+
222
+ print(f"输入嵌入模长: {input_norm:.4f}")
223
+ print(f"输出嵌入模长: {output_norm:.4f}")
224
+ print(f"模长变化比例: {output_norm / input_norm:.4f}")
225
+
226
+
227
+ def demonstrate_training_flow():
228
+ """
229
+ 演示训练流程的关键步骤
230
+ """
231
+ print("\n🎯 训练流程演示")
232
+ print("=" * 20)
233
+
234
+ # 1. 初始化组件
235
+ print("1️⃣ 初始化 Qwen-SDXL 文本编码器")
236
+ text_encoder = QwenSDXLTextEncoder()
237
+
238
+ # 2. 准备训练数据
239
+ print("2️⃣ 准备训练数据")
240
+ sample_prompts = [
241
+ "A serene mountain landscape at sunset",
242
+ "Portrait of a wise old wizard",
243
+ "Modern cityscape with neon lights"
244
+ ]
245
+
246
+ # 3. 前向传播
247
+ print("3️⃣ 执行前向传播")
248
+ with torch.no_grad():
249
+ prompt_embeds, pooled_embeds = text_encoder(sample_prompts)
250
+
251
+ print(f" 编码了 {len(sample_prompts)} 个提示词")
252
+ print(f" 序列嵌入形状: {prompt_embeds.shape}")
253
+ print(f" 池化嵌入形状: {pooled_embeds.shape}")
254
+
255
+ # 4. 模拟与 SDXL 其他组件的集成
256
+ print("4️⃣ 与 SDXL 组件集成")
257
+ print(" ✅ 嵌入维度兼容 SDXL UNet")
258
+ print(" ✅ 支持 classifier-free guidance")
259
+ print(" ✅ 支持 micro-conditioning")
260
+
261
+ return text_encoder
262
+
263
+
264
+ def main():
265
+ """
266
+ 主演示函数
267
+ """
268
+ print("🚀 Qwen-SDXL 架构演示")
269
+ print("=" * 60)
270
+ print("本演示展示如何将 Qwen3 Embedding 集成到 SDXL 管道中")
271
+ print()
272
+
273
+ # 1. 比较嵌入
274
+ qwen_prompt, qwen_pooled, clip_prompt, clip_pooled = compare_embeddings()
275
+
276
+ # 2. 可视化适配器
277
+ visualize_adapter_transformation()
278
+
279
+ # 3. 训练流程演示
280
+ text_encoder = demonstrate_training_flow()
281
+
282
+ print("\n" + "=" * 60)
283
+ print("🎉 演示完成!")
284
+ print("\n核心改进点:")
285
+ print("1. 🔄 Qwen3 替代 CLIP: 更强的中文理解能力")
286
+ print("2. 🔧 Adapter 层: 处理维度不匹配问题")
287
+ print("3. 🎯 保持兼容性: 与原 SDXL 管道完全兼容")
288
+ print("4. 🚀 易于训练: 只需训练 Adapter 层参数")
289
+ print("\n下一步:")
290
+ print("- 📝 准备训练数据集")
291
+ print("- 🏃 开始 Adapter 层训练")
292
+ print("- 🔬 评估生成质量")
293
+ print("- 🎨 微调超参数")
294
+
295
+
296
+ if __name__ == "__main__":
297
+ # 设置随机种子以确保结果可重复
298
+ torch.manual_seed(42)
299
+
300
+ main()
diffusers/.gitignore ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Initially taken from GitHub's Python gitignore file
2
+
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+
8
+ # C extensions
9
+ *.so
10
+
11
+ # tests and logs
12
+ tests/fixtures/cached_*_text.txt
13
+ logs/
14
+ lightning_logs/
15
+ lang_code_data/
16
+
17
+ # Distribution / packaging
18
+ .Python
19
+ build/
20
+ develop-eggs/
21
+ dist/
22
+ downloads/
23
+ eggs/
24
+ .eggs/
25
+ lib/
26
+ lib64/
27
+ parts/
28
+ sdist/
29
+ var/
30
+ wheels/
31
+ *.egg-info/
32
+ .installed.cfg
33
+ *.egg
34
+ MANIFEST
35
+
36
+ # PyInstaller
37
+ # Usually these files are written by a Python script from a template
38
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
39
+ *.manifest
40
+ *.spec
41
+
42
+ # Installer logs
43
+ pip-log.txt
44
+ pip-delete-this-directory.txt
45
+
46
+ # Unit test / coverage reports
47
+ htmlcov/
48
+ .tox/
49
+ .nox/
50
+ .coverage
51
+ .coverage.*
52
+ .cache
53
+ nosetests.xml
54
+ coverage.xml
55
+ *.cover
56
+ .hypothesis/
57
+ .pytest_cache/
58
+
59
+ # Translations
60
+ *.mo
61
+ *.pot
62
+
63
+ # Django stuff:
64
+ *.log
65
+ local_settings.py
66
+ db.sqlite3
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ target/
80
+
81
+ # Jupyter Notebook
82
+ .ipynb_checkpoints
83
+
84
+ # IPython
85
+ profile_default/
86
+ ipython_config.py
87
+
88
+ # pyenv
89
+ .python-version
90
+
91
+ # celery beat schedule file
92
+ celerybeat-schedule
93
+
94
+ # SageMath parsed files
95
+ *.sage.py
96
+
97
+ # Environments
98
+ .env
99
+ .venv
100
+ env/
101
+ venv/
102
+ ENV/
103
+ env.bak/
104
+ venv.bak/
105
+
106
+ # Spyder project settings
107
+ .spyderproject
108
+ .spyproject
109
+
110
+ # Rope project settings
111
+ .ropeproject
112
+
113
+ # mkdocs documentation
114
+ /site
115
+
116
+ # mypy
117
+ .mypy_cache/
118
+ .dmypy.json
119
+ dmypy.json
120
+
121
+ # Pyre type checker
122
+ .pyre/
123
+
124
+ # vscode
125
+ .vs
126
+ .vscode
127
+
128
+ # Pycharm
129
+ .idea
130
+
131
+ # TF code
132
+ tensorflow_code
133
+
134
+ # Models
135
+ proc_data
136
+
137
+ # examples
138
+ runs
139
+ /runs_old
140
+ /wandb
141
+ /examples/runs
142
+ /examples/**/*.args
143
+ /examples/rag/sweep
144
+
145
+ # data
146
+ /data
147
+ serialization_dir
148
+
149
+ # emacs
150
+ *.*~
151
+ debug.env
152
+
153
+ # vim
154
+ .*.swp
155
+
156
+ # ctags
157
+ tags
158
+
159
+ # pre-commit
160
+ .pre-commit*
161
+
162
+ # .lock
163
+ *.lock
164
+
165
+ # DS_Store (MacOS)
166
+ .DS_Store
167
+
168
+ # RL pipelines may produce mp4 outputs
169
+ *.mp4
170
+
171
+ # dependencies
172
+ /transformers
173
+
174
+ # ruff
175
+ .ruff_cache
176
+
177
+ # wandb
178
+ wandb
diffusers/CITATION.cff ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ title: 'Diffusers: State-of-the-art diffusion models'
3
+ message: >-
4
+ If you use this software, please cite it using the
5
+ metadata from this file.
6
+ type: software
7
+ authors:
8
+ - given-names: Patrick
9
+ family-names: von Platen
10
+ - given-names: Suraj
11
+ family-names: Patil
12
+ - given-names: Anton
13
+ family-names: Lozhkov
14
+ - given-names: Pedro
15
+ family-names: Cuenca
16
+ - given-names: Nathan
17
+ family-names: Lambert
18
+ - given-names: Kashif
19
+ family-names: Rasul
20
+ - given-names: Mishig
21
+ family-names: Davaadorj
22
+ - given-names: Dhruv
23
+ family-names: Nair
24
+ - given-names: Sayak
25
+ family-names: Paul
26
+ - given-names: Steven
27
+ family-names: Liu
28
+ - given-names: William
29
+ family-names: Berman
30
+ - given-names: Yiyi
31
+ family-names: Xu
32
+ - given-names: Thomas
33
+ family-names: Wolf
34
+ repository-code: 'https://github.com/huggingface/diffusers'
35
+ abstract: >-
36
+ Diffusers provides pretrained diffusion models across
37
+ multiple modalities, such as vision and audio, and serves
38
+ as a modular toolbox for inference and training of
39
+ diffusion models.
40
+ keywords:
41
+ - deep-learning
42
+ - pytorch
43
+ - image-generation
44
+ - hacktoberfest
45
+ - diffusion
46
+ - text2image
47
+ - image2image
48
+ - score-based-generative-modeling
49
+ - stable-diffusion
50
+ - stable-diffusion-diffusers
51
+ license: Apache-2.0
52
+ version: 0.12.1
diffusers/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Contributor Covenant Code of Conduct
3
+
4
+ ## Our Pledge
5
+
6
+ We as members, contributors, and leaders pledge to make participation in our
7
+ community a harassment-free experience for everyone, regardless of age, body
8
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
9
+ identity and expression, level of experience, education, socio-economic status,
10
+ nationality, personal appearance, race, caste, color, religion, or sexual identity
11
+ and orientation.
12
+
13
+ We pledge to act and interact in ways that contribute to an open, welcoming,
14
+ diverse, inclusive, and healthy community.
15
+
16
+ ## Our Standards
17
+
18
+ Examples of behavior that contributes to a positive environment for our
19
+ community include:
20
+
21
+ * Demonstrating empathy and kindness toward other people
22
+ * Being respectful of differing opinions, viewpoints, and experiences
23
+ * Giving and gracefully accepting constructive feedback
24
+ * Accepting responsibility and apologizing to those affected by our mistakes,
25
+ and learning from the experience
26
+ * Focusing on what is best not just for us as individuals, but for the
27
+ overall Diffusers community
28
+
29
+ Examples of unacceptable behavior include:
30
+
31
+ * The use of sexualized language or imagery, and sexual attention or
32
+ advances of any kind
33
+ * Trolling, insulting or derogatory comments, and personal or political attacks
34
+ * Public or private harassment
35
+ * Publishing others' private information, such as a physical or email
36
+ address, without their explicit permission
37
+ * Spamming issues or PRs with links to projects unrelated to this library
38
+ * Other conduct which could reasonably be considered inappropriate in a
39
+ professional setting
40
+
41
+ ## Enforcement Responsibilities
42
+
43
+ Community leaders are responsible for clarifying and enforcing our standards of
44
+ acceptable behavior and will take appropriate and fair corrective action in
45
+ response to any behavior that they deem inappropriate, threatening, offensive,
46
+ or harmful.
47
+
48
+ Community leaders have the right and responsibility to remove, edit, or reject
49
+ comments, commits, code, wiki edits, issues, and other contributions that are
50
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
51
+ decisions when appropriate.
52
+
53
+ ## Scope
54
+
55
+ This Code of Conduct applies within all community spaces, and also applies when
56
+ an individual is officially representing the community in public spaces.
57
+ Examples of representing our community include using an official e-mail address,
58
+ posting via an official social media account, or acting as an appointed
59
+ representative at an online or offline event.
60
+
61
+ ## Enforcement
62
+
63
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
64
+ reported to the community leaders responsible for enforcement at
65
+ feedback@huggingface.co.
66
+ All complaints will be reviewed and investigated promptly and fairly.
67
+
68
+ All community leaders are obligated to respect the privacy and security of the
69
+ reporter of any incident.
70
+
71
+ ## Enforcement Guidelines
72
+
73
+ Community leaders will follow these Community Impact Guidelines in determining
74
+ the consequences for any action they deem in violation of this Code of Conduct:
75
+
76
+ ### 1. Correction
77
+
78
+ **Community Impact**: Use of inappropriate language or other behavior deemed
79
+ unprofessional or unwelcome in the community.
80
+
81
+ **Consequence**: A private, written warning from community leaders, providing
82
+ clarity around the nature of the violation and an explanation of why the
83
+ behavior was inappropriate. A public apology may be requested.
84
+
85
+ ### 2. Warning
86
+
87
+ **Community Impact**: A violation through a single incident or series
88
+ of actions.
89
+
90
+ **Consequence**: A warning with consequences for continued behavior. No
91
+ interaction with the people involved, including unsolicited interaction with
92
+ those enforcing the Code of Conduct, for a specified period of time. This
93
+ includes avoiding interactions in community spaces as well as external channels
94
+ like social media. Violating these terms may lead to a temporary or
95
+ permanent ban.
96
+
97
+ ### 3. Temporary Ban
98
+
99
+ **Community Impact**: A serious violation of community standards, including
100
+ sustained inappropriate behavior.
101
+
102
+ **Consequence**: A temporary ban from any sort of interaction or public
103
+ communication with the community for a specified period of time. No public or
104
+ private interaction with the people involved, including unsolicited interaction
105
+ with those enforcing the Code of Conduct, is allowed during this period.
106
+ Violating these terms may lead to a permanent ban.
107
+
108
+ ### 4. Permanent Ban
109
+
110
+ **Community Impact**: Demonstrating a pattern of violation of community
111
+ standards, including sustained inappropriate behavior, harassment of an
112
+ individual, or aggression toward or disparagement of classes of individuals.
113
+
114
+ **Consequence**: A permanent ban from any sort of public interaction within
115
+ the community.
116
+
117
+ ## Attribution
118
+
119
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
120
+ version 2.1, available at
121
+ https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
122
+
123
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
124
+ enforcement ladder](https://github.com/mozilla/diversity).
125
+
126
+ [homepage]: https://www.contributor-covenant.org
127
+
128
+ For answers to common questions about this code of conduct, see the FAQ at
129
+ https://www.contributor-covenant.org/faq. Translations are available at
130
+ https://www.contributor-covenant.org/translations.
diffusers/CONTRIBUTING.md ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # How to contribute to Diffusers 🧨
14
+
15
+ We ❤️ contributions from the open-source community! Everyone is welcome, and all types of participation –not just code– are valued and appreciated. Answering questions, helping others, reaching out, and improving the documentation are all immensely valuable to the community, so don't be afraid and get involved if you're up for it!
16
+
17
+ Everyone is encouraged to start by saying 👋 in our public Discord channel. We discuss the latest trends in diffusion models, ask questions, show off personal projects, help each other with contributions, or just hang out ☕. <a href="https://discord.gg/G7tWnz98XR"><img alt="Join us on Discord" src="https://img.shields.io/discord/823813159592001537?color=5865F2&logo=Discord&logoColor=white"></a>
18
+
19
+ Whichever way you choose to contribute, we strive to be part of an open, welcoming, and kind community. Please, read our [code of conduct](https://github.com/huggingface/diffusers/blob/main/CODE_OF_CONDUCT.md) and be mindful to respect it during your interactions. We also recommend you become familiar with the [ethical guidelines](https://huggingface.co/docs/diffusers/conceptual/ethical_guidelines) that guide our project and ask you to adhere to the same principles of transparency and responsibility.
20
+
21
+ We enormously value feedback from the community, so please do not be afraid to speak up if you believe you have valuable feedback that can help improve the library - every message, comment, issue, and pull request (PR) is read and considered.
22
+
23
+ ## Overview
24
+
25
+ You can contribute in many ways ranging from answering questions on issues to adding new diffusion models to
26
+ the core library.
27
+
28
+ In the following, we give an overview of different ways to contribute, ranked by difficulty in ascending order. All of them are valuable to the community.
29
+
30
+ * 1. Asking and answering questions on [the Diffusers discussion forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers) or on [Discord](https://discord.gg/G7tWnz98XR).
31
+ * 2. Opening new issues on [the GitHub Issues tab](https://github.com/huggingface/diffusers/issues/new/choose).
32
+ * 3. Answering issues on [the GitHub Issues tab](https://github.com/huggingface/diffusers/issues).
33
+ * 4. Fix a simple issue, marked by the "Good first issue" label, see [here](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22).
34
+ * 5. Contribute to the [documentation](https://github.com/huggingface/diffusers/tree/main/docs/source).
35
+ * 6. Contribute a [Community Pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3Acommunity-examples).
36
+ * 7. Contribute to the [examples](https://github.com/huggingface/diffusers/tree/main/examples).
37
+ * 8. Fix a more difficult issue, marked by the "Good second issue" label, see [here](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+second+issue%22).
38
+ * 9. Add a new pipeline, model, or scheduler, see ["New Pipeline/Model"](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22) and ["New scheduler"](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22) issues. For this contribution, please have a look at [Design Philosophy](https://github.com/huggingface/diffusers/blob/main/PHILOSOPHY.md).
39
+
40
+ As said before, **all contributions are valuable to the community**.
41
+ In the following, we will explain each contribution a bit more in detail.
42
+
43
+ For all contributions 4-9, you will need to open a PR. It is explained in detail how to do so in [Opening a pull request](#how-to-open-a-pr).
44
+
45
+ ### 1. Asking and answering questions on the Diffusers discussion forum or on the Diffusers Discord
46
+
47
+ Any question or comment related to the Diffusers library can be asked on the [discussion forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/) or on [Discord](https://discord.gg/G7tWnz98XR). Such questions and comments include (but are not limited to):
48
+ - Reports of training or inference experiments in an attempt to share knowledge
49
+ - Presentation of personal projects
50
+ - Questions to non-official training examples
51
+ - Project proposals
52
+ - General feedback
53
+ - Paper summaries
54
+ - Asking for help on personal projects that build on top of the Diffusers library
55
+ - General questions
56
+ - Ethical questions regarding diffusion models
57
+ - ...
58
+
59
+ Every question that is asked on the forum or on Discord actively encourages the community to publicly
60
+ share knowledge and might very well help a beginner in the future who has the same question you're
61
+ having. Please do pose any questions you might have.
62
+ In the same spirit, you are of immense help to the community by answering such questions because this way you are publicly documenting knowledge for everybody to learn from.
63
+
64
+ **Please** keep in mind that the more effort you put into asking or answering a question, the higher
65
+ the quality of the publicly documented knowledge. In the same way, well-posed and well-answered questions create a high-quality knowledge database accessible to everybody, while badly posed questions or answers reduce the overall quality of the public knowledge database.
66
+ In short, a high quality question or answer is *precise*, *concise*, *relevant*, *easy-to-understand*, *accessible*, and *well-formatted/well-posed*. For more information, please have a look through the [How to write a good issue](#how-to-write-a-good-issue) section.
67
+
68
+ **NOTE about channels**:
69
+ [*The forum*](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) is much better indexed by search engines, such as Google. Posts are ranked by popularity rather than chronologically. Hence, it's easier to look up questions and answers that we posted some time ago.
70
+ In addition, questions and answers posted in the forum can easily be linked to.
71
+ In contrast, *Discord* has a chat-like format that invites fast back-and-forth communication.
72
+ While it will most likely take less time for you to get an answer to your question on Discord, your
73
+ question won't be visible anymore over time. Also, it's much harder to find information that was posted a while back on Discord. We therefore strongly recommend using the forum for high-quality questions and answers in an attempt to create long-lasting knowledge for the community. If discussions on Discord lead to very interesting answers and conclusions, we recommend posting the results on the forum to make the information more available for future readers.
74
+
75
+ ### 2. Opening new issues on the GitHub issues tab
76
+
77
+ The 🧨 Diffusers library is robust and reliable thanks to the users who notify us of
78
+ the problems they encounter. So thank you for reporting an issue.
79
+
80
+ Remember, GitHub issues are reserved for technical questions directly related to the Diffusers library, bug reports, feature requests, or feedback on the library design.
81
+
82
+ In a nutshell, this means that everything that is **not** related to the **code of the Diffusers library** (including the documentation) should **not** be asked on GitHub, but rather on either the [forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) or [Discord](https://discord.gg/G7tWnz98XR).
83
+
84
+ **Please consider the following guidelines when opening a new issue**:
85
+ - Make sure you have searched whether your issue has already been asked before (use the search bar on GitHub under Issues).
86
+ - Please never report a new issue on another (related) issue. If another issue is highly related, please
87
+ open a new issue nevertheless and link to the related issue.
88
+ - Make sure your issue is written in English. Please use one of the great, free online translation services, such as [DeepL](https://www.deepl.com/translator) to translate from your native language to English if you are not comfortable in English.
89
+ - Check whether your issue might be solved by updating to the newest Diffusers version. Before posting your issue, please make sure that `python -c "import diffusers; print(diffusers.__version__)"` is higher or matches the latest Diffusers version.
90
+ - Remember that the more effort you put into opening a new issue, the higher the quality of your answer will be and the better the overall quality of the Diffusers issues.
91
+
92
+ New issues usually include the following.
93
+
94
+ #### 2.1. Reproducible, minimal bug reports
95
+
96
+ A bug report should always have a reproducible code snippet and be as minimal and concise as possible.
97
+ This means in more detail:
98
+ - Narrow the bug down as much as you can, **do not just dump your whole code file**.
99
+ - Format your code.
100
+ - Do not include any external libraries except for Diffusers depending on them.
101
+ - **Always** provide all necessary information about your environment; for this, you can run: `diffusers-cli env` in your shell and copy-paste the displayed information to the issue.
102
+ - Explain the issue. If the reader doesn't know what the issue is and why it is an issue, she cannot solve it.
103
+ - **Always** make sure the reader can reproduce your issue with as little effort as possible. If your code snippet cannot be run because of missing libraries or undefined variables, the reader cannot help you. Make sure your reproducible code snippet is as minimal as possible and can be copy-pasted into a simple Python shell.
104
+ - If in order to reproduce your issue a model and/or dataset is required, make sure the reader has access to that model or dataset. You can always upload your model or dataset to the [Hub](https://huggingface.co) to make it easily downloadable. Try to keep your model and dataset as small as possible, to make the reproduction of your issue as effortless as possible.
105
+
106
+ For more information, please have a look through the [How to write a good issue](#how-to-write-a-good-issue) section.
107
+
108
+ You can open a bug report [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&projects=&template=bug-report.yml).
109
+
110
+ #### 2.2. Feature requests
111
+
112
+ A world-class feature request addresses the following points:
113
+
114
+ 1. Motivation first:
115
+ * Is it related to a problem/frustration with the library? If so, please explain
116
+ why. Providing a code snippet that demonstrates the problem is best.
117
+ * Is it related to something you would need for a project? We'd love to hear
118
+ about it!
119
+ * Is it something you worked on and think could benefit the community?
120
+ Awesome! Tell us what problem it solved for you.
121
+ 2. Write a *full paragraph* describing the feature;
122
+ 3. Provide a **code snippet** that demonstrates its future use;
123
+ 4. In case this is related to a paper, please attach a link;
124
+ 5. Attach any additional information (drawings, screenshots, etc.) you think may help.
125
+
126
+ You can open a feature request [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feature_request.md&title=).
127
+
128
+ #### 2.3 Feedback
129
+
130
+ Feedback about the library design and why it is good or not good helps the core maintainers immensely to build a user-friendly library. To understand the philosophy behind the current design philosophy, please have a look [here](https://huggingface.co/docs/diffusers/conceptual/philosophy). If you feel like a certain design choice does not fit with the current design philosophy, please explain why and how it should be changed. If a certain design choice follows the design philosophy too much, hence restricting use cases, explain why and how it should be changed.
131
+ If a certain design choice is very useful for you, please also leave a note as this is great feedback for future design decisions.
132
+
133
+ You can open an issue about feedback [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=).
134
+
135
+ #### 2.4 Technical questions
136
+
137
+ Technical questions are mainly about why certain code of the library was written in a certain way, or what a certain part of the code does. Please make sure to link to the code in question and please provide detail on
138
+ why this part of the code is difficult to understand.
139
+
140
+ You can open an issue about a technical question [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&template=bug-report.yml).
141
+
142
+ #### 2.5 Proposal to add a new model, scheduler, or pipeline
143
+
144
+ If the diffusion model community released a new model, pipeline, or scheduler that you would like to see in the Diffusers library, please provide the following information:
145
+
146
+ * Short description of the diffusion pipeline, model, or scheduler and link to the paper or public release.
147
+ * Link to any of its open-source implementation.
148
+ * Link to the model weights if they are available.
149
+
150
+ If you are willing to contribute to the model yourself, let us know so we can best guide you. Also, don't forget
151
+ to tag the original author of the component (model, scheduler, pipeline, etc.) by GitHub handle if you can find it.
152
+
153
+ You can open a request for a model/pipeline/scheduler [here](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=New+model%2Fpipeline%2Fscheduler&template=new-model-addition.yml).
154
+
155
+ ### 3. Answering issues on the GitHub issues tab
156
+
157
+ Answering issues on GitHub might require some technical knowledge of Diffusers, but we encourage everybody to give it a try even if you are not 100% certain that your answer is correct.
158
+ Some tips to give a high-quality answer to an issue:
159
+ - Be as concise and minimal as possible.
160
+ - Stay on topic. An answer to the issue should concern the issue and only the issue.
161
+ - Provide links to code, papers, or other sources that prove or encourage your point.
162
+ - Answer in code. If a simple code snippet is the answer to the issue or shows how the issue can be solved, please provide a fully reproducible code snippet.
163
+
164
+ Also, many issues tend to be simply off-topic, duplicates of other issues, or irrelevant. It is of great
165
+ help to the maintainers if you can answer such issues, encouraging the author of the issue to be
166
+ more precise, provide the link to a duplicated issue or redirect them to [the forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) or [Discord](https://discord.gg/G7tWnz98XR).
167
+
168
+ If you have verified that the issued bug report is correct and requires a correction in the source code,
169
+ please have a look at the next sections.
170
+
171
+ For all of the following contributions, you will need to open a PR. It is explained in detail how to do so in the [Opening a pull request](#how-to-open-a-pr) section.
172
+
173
+ ### 4. Fixing a "Good first issue"
174
+
175
+ *Good first issues* are marked by the [Good first issue](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) label. Usually, the issue already
176
+ explains how a potential solution should look so that it is easier to fix.
177
+ If the issue hasn't been closed and you would like to try to fix this issue, you can just leave a message "I would like to try this issue.". There are usually three scenarios:
178
+ - a.) The issue description already proposes a fix. In this case and if the solution makes sense to you, you can open a PR or draft PR to fix it.
179
+ - b.) The issue description does not propose a fix. In this case, you can ask what a proposed fix could look like and someone from the Diffusers team should answer shortly. If you have a good idea of how to fix it, feel free to directly open a PR.
180
+ - c.) There is already an open PR to fix the issue, but the issue hasn't been closed yet. If the PR has gone stale, you can simply open a new PR and link to the stale PR. PRs often go stale if the original contributor who wanted to fix the issue suddenly cannot find the time anymore to proceed. This often happens in open-source and is very normal. In this case, the community will be very happy if you give it a new try and leverage the knowledge of the existing PR. If there is already a PR and it is active, you can help the author by giving suggestions, reviewing the PR or even asking whether you can contribute to the PR.
181
+
182
+
183
+ ### 5. Contribute to the documentation
184
+
185
+ A good library **always** has good documentation! The official documentation is often one of the first points of contact for new users of the library, and therefore contributing to the documentation is a **highly
186
+ valuable contribution**.
187
+
188
+ Contributing to the library can have many forms:
189
+
190
+ - Correcting spelling or grammatical errors.
191
+ - Correct incorrect formatting of the docstring. If you see that the official documentation is weirdly displayed or a link is broken, we are very happy if you take some time to correct it.
192
+ - Correct the shape or dimensions of a docstring input or output tensor.
193
+ - Clarify documentation that is hard to understand or incorrect.
194
+ - Update outdated code examples.
195
+ - Translating the documentation to another language.
196
+
197
+ Anything displayed on [the official Diffusers doc page](https://huggingface.co/docs/diffusers/index) is part of the official documentation and can be corrected, adjusted in the respective [documentation source](https://github.com/huggingface/diffusers/tree/main/docs/source).
198
+
199
+ Please have a look at [this page](https://github.com/huggingface/diffusers/tree/main/docs) on how to verify changes made to the documentation locally.
200
+
201
+
202
+ ### 6. Contribute a community pipeline
203
+
204
+ [Pipelines](https://huggingface.co/docs/diffusers/api/pipelines/overview) are usually the first point of contact between the Diffusers library and the user.
205
+ Pipelines are examples of how to use Diffusers [models](https://huggingface.co/docs/diffusers/api/models/overview) and [schedulers](https://huggingface.co/docs/diffusers/api/schedulers/overview).
206
+ We support two types of pipelines:
207
+
208
+ - Official Pipelines
209
+ - Community Pipelines
210
+
211
+ Both official and community pipelines follow the same design and consist of the same type of components.
212
+
213
+ Official pipelines are tested and maintained by the core maintainers of Diffusers. Their code
214
+ resides in [src/diffusers/pipelines](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines).
215
+ In contrast, community pipelines are contributed and maintained purely by the **community** and are **not** tested.
216
+ They reside in [examples/community](https://github.com/huggingface/diffusers/tree/main/examples/community) and while they can be accessed via the [PyPI diffusers package](https://pypi.org/project/diffusers/), their code is not part of the PyPI distribution.
217
+
218
+ The reason for the distinction is that the core maintainers of the Diffusers library cannot maintain and test all
219
+ possible ways diffusion models can be used for inference, but some of them may be of interest to the community.
220
+ Officially released diffusion pipelines,
221
+ such as Stable Diffusion are added to the core src/diffusers/pipelines package which ensures
222
+ high quality of maintenance, no backward-breaking code changes, and testing.
223
+ More bleeding edge pipelines should be added as community pipelines. If usage for a community pipeline is high, the pipeline can be moved to the official pipelines upon request from the community. This is one of the ways we strive to be a community-driven library.
224
+
225
+ To add a community pipeline, one should add a <name-of-the-community>.py file to [examples/community](https://github.com/huggingface/diffusers/tree/main/examples/community) and adapt the [examples/community/README.md](https://github.com/huggingface/diffusers/tree/main/examples/community/README.md) to include an example of the new pipeline.
226
+
227
+ An example can be seen [here](https://github.com/huggingface/diffusers/pull/2400).
228
+
229
+ Community pipeline PRs are only checked at a superficial level and ideally they should be maintained by their original authors.
230
+
231
+ Contributing a community pipeline is a great way to understand how Diffusers models and schedulers work. Having contributed a community pipeline is usually the first stepping stone to contributing an official pipeline to the
232
+ core package.
233
+
234
+ ### 7. Contribute to training examples
235
+
236
+ Diffusers examples are a collection of training scripts that reside in [examples](https://github.com/huggingface/diffusers/tree/main/examples).
237
+
238
+ We support two types of training examples:
239
+
240
+ - Official training examples
241
+ - Research training examples
242
+
243
+ Research training examples are located in [examples/research_projects](https://github.com/huggingface/diffusers/tree/main/examples/research_projects) whereas official training examples include all folders under [examples](https://github.com/huggingface/diffusers/tree/main/examples) except the `research_projects` and `community` folders.
244
+ The official training examples are maintained by the Diffusers' core maintainers whereas the research training examples are maintained by the community.
245
+ This is because of the same reasons put forward in [6. Contribute a community pipeline](#6-contribute-a-community-pipeline) for official pipelines vs. community pipelines: It is not feasible for the core maintainers to maintain all possible training methods for diffusion models.
246
+ If the Diffusers core maintainers and the community consider a certain training paradigm to be too experimental or not popular enough, the corresponding training code should be put in the `research_projects` folder and maintained by the author.
247
+
248
+ Both official training and research examples consist of a directory that contains one or more training scripts, a `requirements.txt` file, and a `README.md` file. In order for the user to make use of the
249
+ training examples, it is required to clone the repository:
250
+
251
+ ```bash
252
+ git clone https://github.com/huggingface/diffusers
253
+ ```
254
+
255
+ as well as to install all additional dependencies required for training:
256
+
257
+ ```bash
258
+ cd diffusers
259
+ pip install -r examples/<your-example-folder>/requirements.txt
260
+ ```
261
+
262
+ Therefore when adding an example, the `requirements.txt` file shall define all pip dependencies required for your training example so that once all those are installed, the user can run the example's training script. See, for example, the [DreamBooth `requirements.txt` file](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/requirements.txt).
263
+
264
+ Training examples of the Diffusers library should adhere to the following philosophy:
265
+ - All the code necessary to run the examples should be found in a single Python file.
266
+ - One should be able to run the example from the command line with `python <your-example>.py --args`.
267
+ - Examples should be kept simple and serve as **an example** on how to use Diffusers for training. The purpose of example scripts is **not** to create state-of-the-art diffusion models, but rather to reproduce known training schemes without adding too much custom logic. As a byproduct of this point, our examples also strive to serve as good educational materials.
268
+
269
+ To contribute an example, it is highly recommended to look at already existing examples such as [dreambooth](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth.py) to get an idea of how they should look like.
270
+ We strongly advise contributors to make use of the [Accelerate library](https://github.com/huggingface/accelerate) as it's tightly integrated
271
+ with Diffusers.
272
+ Once an example script works, please make sure to add a comprehensive `README.md` that states how to use the example exactly. This README should include:
273
+ - An example command on how to run the example script as shown [here e.g.](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth#running-locally-with-pytorch).
274
+ - A link to some training results (logs, models, ...) that show what the user can expect as shown [here e.g.](https://api.wandb.ai/report/patrickvonplaten/xm6cd5q5).
275
+ - If you are adding a non-official/research training example, **please don't forget** to add a sentence that you are maintaining this training example which includes your git handle as shown [here](https://github.com/huggingface/diffusers/tree/main/examples/research_projects/intel_opts#diffusers-examples-with-intel-optimizations).
276
+
277
+ If you are contributing to the official training examples, please also make sure to add a test to [examples/test_examples.py](https://github.com/huggingface/diffusers/blob/main/examples/test_examples.py). This is not necessary for non-official training examples.
278
+
279
+ ### 8. Fixing a "Good second issue"
280
+
281
+ *Good second issues* are marked by the [Good second issue](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+second+issue%22) label. Good second issues are
282
+ usually more complicated to solve than [Good first issues](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22).
283
+ The issue description usually gives less guidance on how to fix the issue and requires
284
+ a decent understanding of the library by the interested contributor.
285
+ If you are interested in tackling a good second issue, feel free to open a PR to fix it and link the PR to the issue. If you see that a PR has already been opened for this issue but did not get merged, have a look to understand why it wasn't merged and try to open an improved PR.
286
+ Good second issues are usually more difficult to get merged compared to good first issues, so don't hesitate to ask for help from the core maintainers. If your PR is almost finished the core maintainers can also jump into your PR and commit to it in order to get it merged.
287
+
288
+ ### 9. Adding pipelines, models, schedulers
289
+
290
+ Pipelines, models, and schedulers are the most important pieces of the Diffusers library.
291
+ They provide easy access to state-of-the-art diffusion technologies and thus allow the community to
292
+ build powerful generative AI applications.
293
+
294
+ By adding a new model, pipeline, or scheduler you might enable a new powerful use case for any of the user interfaces relying on Diffusers which can be of immense value for the whole generative AI ecosystem.
295
+
296
+ Diffusers has a couple of open feature requests for all three components - feel free to gloss over them
297
+ if you don't know yet what specific component you would like to add:
298
+ - [Model or pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22)
299
+ - [Scheduler](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22)
300
+
301
+ Before adding any of the three components, it is strongly recommended that you give the [Philosophy guide](https://github.com/huggingface/diffusers/blob/main/PHILOSOPHY.md) a read to better understand the design of any of the three components. Please be aware that
302
+ we cannot merge model, scheduler, or pipeline additions that strongly diverge from our design philosophy
303
+ as it will lead to API inconsistencies. If you fundamentally disagree with a design choice, please
304
+ open a [Feedback issue](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=) instead so that it can be discussed whether a certain design
305
+ pattern/design choice shall be changed everywhere in the library and whether we shall update our design philosophy. Consistency across the library is very important for us.
306
+
307
+ Please make sure to add links to the original codebase/paper to the PR and ideally also ping the
308
+ original author directly on the PR so that they can follow the progress and potentially help with questions.
309
+
310
+ If you are unsure or stuck in the PR, don't hesitate to leave a message to ask for a first review or help.
311
+
312
+ ## How to write a good issue
313
+
314
+ **The better your issue is written, the higher the chances that it will be quickly resolved.**
315
+
316
+ 1. Make sure that you've used the correct template for your issue. You can pick between *Bug Report*, *Feature Request*, *Feedback about API Design*, *New model/pipeline/scheduler addition*, *Forum*, or a blank issue. Make sure to pick the correct one when opening [a new issue](https://github.com/huggingface/diffusers/issues/new/choose).
317
+ 2. **Be precise**: Give your issue a fitting title. Try to formulate your issue description as simple as possible. The more precise you are when submitting an issue, the less time it takes to understand the issue and potentially solve it. Make sure to open an issue for one issue only and not for multiple issues. If you found multiple issues, simply open multiple issues. If your issue is a bug, try to be as precise as possible about what bug it is - you should not just write "Error in diffusers".
318
+ 3. **Reproducibility**: No reproducible code snippet == no solution. If you encounter a bug, maintainers **have to be able to reproduce** it. Make sure that you include a code snippet that can be copy-pasted into a Python interpreter to reproduce the issue. Make sure that your code snippet works, *i.e.* that there are no missing imports or missing links to images, ... Your issue should contain an error message **and** a code snippet that can be copy-pasted without any changes to reproduce the exact same error message. If your issue is using local model weights or local data that cannot be accessed by the reader, the issue cannot be solved. If you cannot share your data or model, try to make a dummy model or dummy data.
319
+ 4. **Minimalistic**: Try to help the reader as much as you can to understand the issue as quickly as possible by staying as concise as possible. Remove all code / all information that is irrelevant to the issue. If you have found a bug, try to create the easiest code example you can to demonstrate your issue, do not just dump your whole workflow into the issue as soon as you have found a bug. E.g., if you train a model and get an error at some point during the training, you should first try to understand what part of the training code is responsible for the error and try to reproduce it with a couple of lines. Try to use dummy data instead of full datasets.
320
+ 5. Add links. If you are referring to a certain naming, method, or model make sure to provide a link so that the reader can better understand what you mean. If you are referring to a specific PR or issue, make sure to link it to your issue. Do not assume that the reader knows what you are talking about. The more links you add to your issue the better.
321
+ 6. Formatting. Make sure to nicely format your issue by formatting code into Python code syntax, and error messages into normal code syntax. See the [official GitHub formatting docs](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) for more information.
322
+ 7. Think of your issue not as a ticket to be solved, but rather as a beautiful entry to a well-written encyclopedia. Every added issue is a contribution to publicly available knowledge. By adding a nicely written issue you not only make it easier for maintainers to solve your issue, but you are helping the whole community to better understand a certain aspect of the library.
323
+
324
+ ## How to write a good PR
325
+
326
+ 1. Be a chameleon. Understand existing design patterns and syntax and make sure your code additions flow seamlessly into the existing code base. Pull requests that significantly diverge from existing design patterns or user interfaces will not be merged.
327
+ 2. Be laser focused. A pull request should solve one problem and one problem only. Make sure to not fall into the trap of "also fixing another problem while we're adding it". It is much more difficult to review pull requests that solve multiple, unrelated problems at once.
328
+ 3. If helpful, try to add a code snippet that displays an example of how your addition can be used.
329
+ 4. The title of your pull request should be a summary of its contribution.
330
+ 5. If your pull request addresses an issue, please mention the issue number in
331
+ the pull request description to make sure they are linked (and people
332
+ consulting the issue know you are working on it);
333
+ 6. To indicate a work in progress please prefix the title with `[WIP]`. These
334
+ are useful to avoid duplicated work, and to differentiate it from PRs ready
335
+ to be merged;
336
+ 7. Try to formulate and format your text as explained in [How to write a good issue](#how-to-write-a-good-issue).
337
+ 8. Make sure existing tests pass;
338
+ 9. Add high-coverage tests. No quality testing = no merge.
339
+ - If you are adding new `@slow` tests, make sure they pass using
340
+ `RUN_SLOW=1 python -m pytest tests/test_my_new_model.py`.
341
+ CircleCI does not run the slow tests, but GitHub Actions does every night!
342
+ 10. All public methods must have informative docstrings that work nicely with markdown. See [`pipeline_latent_diffusion.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py) for an example.
343
+ 11. Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos, and other non-text files. We prefer to leverage a hf.co hosted `dataset` like
344
+ [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) or [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images) to place these files.
345
+ If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images
346
+ to this dataset.
347
+
348
+ ## How to open a PR
349
+
350
+ Before writing code, we strongly advise you to search through the existing PRs or
351
+ issues to make sure that nobody is already working on the same thing. If you are
352
+ unsure, it is always a good idea to open an issue to get some feedback.
353
+
354
+ You will need basic `git` proficiency to be able to contribute to
355
+ 🧨 Diffusers. `git` is not the easiest tool to use but it has the greatest
356
+ manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro
357
+ Git](https://git-scm.com/book/en/v2) is a very good reference.
358
+
359
+ Follow these steps to start contributing ([supported Python versions](https://github.com/huggingface/diffusers/blob/42f25d601a910dceadaee6c44345896b4cfa9928/setup.py#L270)):
360
+
361
+ 1. Fork the [repository](https://github.com/huggingface/diffusers) by
362
+ clicking on the 'Fork' button on the repository's page. This creates a copy of the code
363
+ under your GitHub user account.
364
+
365
+ 2. Clone your fork to your local disk, and add the base repository as a remote:
366
+
367
+ ```bash
368
+ $ git clone git@github.com:<your GitHub handle>/diffusers.git
369
+ $ cd diffusers
370
+ $ git remote add upstream https://github.com/huggingface/diffusers.git
371
+ ```
372
+
373
+ 3. Create a new branch to hold your development changes:
374
+
375
+ ```bash
376
+ $ git checkout -b a-descriptive-name-for-my-changes
377
+ ```
378
+
379
+ **Do not** work on the `main` branch.
380
+
381
+ 4. Set up a development environment by running the following command in a virtual environment:
382
+
383
+ ```bash
384
+ $ pip install -e ".[dev]"
385
+ ```
386
+
387
+ If you have already cloned the repo, you might need to `git pull` to get the most recent changes in the
388
+ library.
389
+
390
+ 5. Develop the features on your branch.
391
+
392
+ As you work on the features, you should make sure that the test suite
393
+ passes. You should run the tests impacted by your changes like this:
394
+
395
+ ```bash
396
+ $ pytest tests/<TEST_TO_RUN>.py
397
+ ```
398
+
399
+ Before you run the tests, please make sure you install the dependencies required for testing. You can do so
400
+ with this command:
401
+
402
+ ```bash
403
+ $ pip install -e ".[test]"
404
+ ```
405
+
406
+ You can also run the full test suite with the following command, but it takes
407
+ a beefy machine to produce a result in a decent amount of time now that
408
+ Diffusers has grown a lot. Here is the command for it:
409
+
410
+ ```bash
411
+ $ make test
412
+ ```
413
+
414
+ 🧨 Diffusers relies on `ruff` and `isort` to format its source code
415
+ consistently. After you make changes, apply automatic style corrections and code verifications
416
+ that can't be automated in one go with:
417
+
418
+ ```bash
419
+ $ make style
420
+ ```
421
+
422
+ 🧨 Diffusers also uses `ruff` and a few custom scripts to check for coding mistakes. Quality
423
+ control runs in CI, however, you can also run the same checks with:
424
+
425
+ ```bash
426
+ $ make quality
427
+ ```
428
+
429
+ Once you're happy with your changes, add changed files using `git add` and
430
+ make a commit with `git commit` to record your changes locally:
431
+
432
+ ```bash
433
+ $ git add modified_file.py
434
+ $ git commit -m "A descriptive message about your changes."
435
+ ```
436
+
437
+ It is a good idea to sync your copy of the code with the original
438
+ repository regularly. This way you can quickly account for changes:
439
+
440
+ ```bash
441
+ $ git pull upstream main
442
+ ```
443
+
444
+ Push the changes to your account using:
445
+
446
+ ```bash
447
+ $ git push -u origin a-descriptive-name-for-my-changes
448
+ ```
449
+
450
+ 6. Once you are satisfied, go to the
451
+ webpage of your fork on GitHub. Click on 'Pull request' to send your changes
452
+ to the project maintainers for review.
453
+
454
+ 7. It's ok if maintainers ask you for changes. It happens to core contributors
455
+ too! So everyone can see the changes in the Pull request, work in your local
456
+ branch and push the changes to your fork. They will automatically appear in
457
+ the pull request.
458
+
459
+ ### Tests
460
+
461
+ An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
462
+ the [tests folder](https://github.com/huggingface/diffusers/tree/main/tests).
463
+
464
+ We like `pytest` and `pytest-xdist` because it's faster. From the root of the
465
+ repository, here's how to run tests with `pytest` for the library:
466
+
467
+ ```bash
468
+ $ python -m pytest -n auto --dist=loadfile -s -v ./tests/
469
+ ```
470
+
471
+ In fact, that's how `make test` is implemented!
472
+
473
+ You can specify a smaller set of tests in order to test only the feature
474
+ you're working on.
475
+
476
+ By default, slow tests are skipped. Set the `RUN_SLOW` environment variable to
477
+ `yes` to run them. This will download many gigabytes of models — make sure you
478
+ have enough disk space and a good Internet connection, or a lot of patience!
479
+
480
+ ```bash
481
+ $ RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/
482
+ ```
483
+
484
+ `unittest` is fully supported, here's how to run tests with it:
485
+
486
+ ```bash
487
+ $ python -m unittest discover -s tests -t . -v
488
+ $ python -m unittest discover -s examples -t examples -v
489
+ ```
490
+
491
+ ### Syncing forked main with upstream (HuggingFace) main
492
+
493
+ To avoid pinging the upstream repository which adds reference notes to each upstream PR and sends unnecessary notifications to the developers involved in these PRs,
494
+ when syncing the main branch of a forked repository, please, follow these steps:
495
+ 1. When possible, avoid syncing with the upstream using a branch and PR on the forked repository. Instead, merge directly into the forked main.
496
+ 2. If a PR is absolutely necessary, use the following steps after checking out your branch:
497
+ ```bash
498
+ $ git checkout -b your-branch-for-syncing
499
+ $ git pull --squash --no-commit upstream main
500
+ $ git commit -m '<your message without GitHub references>'
501
+ $ git push --set-upstream origin your-branch-for-syncing
502
+ ```
503
+
504
+ ### Style guide
505
+
506
+ For documentation strings, 🧨 Diffusers follows the [Google style](https://google.github.io/styleguide/pyguide.html).
diffusers/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
diffusers/MANIFEST.in ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ include LICENSE
2
+ include src/diffusers/utils/model_card_template.md
diffusers/Makefile ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: deps_table_update modified_only_fixup extra_style_checks quality style fixup fix-copies test test-examples
2
+
3
+ # make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!)
4
+ export PYTHONPATH = src
5
+
6
+ check_dirs := examples scripts src tests utils benchmarks
7
+
8
+ modified_only_fixup:
9
+ $(eval modified_py_files := $(shell python utils/get_modified_files.py $(check_dirs)))
10
+ @if test -n "$(modified_py_files)"; then \
11
+ echo "Checking/fixing $(modified_py_files)"; \
12
+ ruff check $(modified_py_files) --fix; \
13
+ ruff format $(modified_py_files);\
14
+ else \
15
+ echo "No library .py files were modified"; \
16
+ fi
17
+
18
+ # Update src/diffusers/dependency_versions_table.py
19
+
20
+ deps_table_update:
21
+ @python setup.py deps_table_update
22
+
23
+ deps_table_check_updated:
24
+ @md5sum src/diffusers/dependency_versions_table.py > md5sum.saved
25
+ @python setup.py deps_table_update
26
+ @md5sum -c --quiet md5sum.saved || (printf "\nError: the version dependency table is outdated.\nPlease run 'make fixup' or 'make style' and commit the changes.\n\n" && exit 1)
27
+ @rm md5sum.saved
28
+
29
+ # autogenerating code
30
+
31
+ autogenerate_code: deps_table_update
32
+
33
+ # Check that the repo is in a good state
34
+
35
+ repo-consistency:
36
+ python utils/check_dummies.py
37
+ python utils/check_repo.py
38
+ python utils/check_inits.py
39
+
40
+ # this target runs checks on all files
41
+
42
+ quality:
43
+ ruff check $(check_dirs) setup.py
44
+ ruff format --check $(check_dirs) setup.py
45
+ doc-builder style src/diffusers docs/source --max_len 119 --check_only
46
+ python utils/check_doc_toc.py
47
+
48
+ # Format source code automatically and check is there are any problems left that need manual fixing
49
+
50
+ extra_style_checks:
51
+ python utils/custom_init_isort.py
52
+ python utils/check_doc_toc.py --fix_and_overwrite
53
+
54
+ # this target runs checks on all files and potentially modifies some of them
55
+
56
+ style:
57
+ ruff check $(check_dirs) setup.py --fix
58
+ ruff format $(check_dirs) setup.py
59
+ doc-builder style src/diffusers docs/source --max_len 119
60
+ ${MAKE} autogenerate_code
61
+ ${MAKE} extra_style_checks
62
+
63
+ # Super fast fix and check target that only works on relevant modified files since the branch was made
64
+
65
+ fixup: modified_only_fixup extra_style_checks autogenerate_code repo-consistency
66
+
67
+ # Make marked copies of snippets of codes conform to the original
68
+
69
+ fix-copies:
70
+ python utils/check_copies.py --fix_and_overwrite
71
+ python utils/check_dummies.py --fix_and_overwrite
72
+
73
+ # Run tests for the library
74
+
75
+ test:
76
+ python -m pytest -n auto --dist=loadfile -s -v ./tests/
77
+
78
+ # Run tests for examples
79
+
80
+ test-examples:
81
+ python -m pytest -n auto --dist=loadfile -s -v ./examples/
82
+
83
+
84
+ # Release stuff
85
+
86
+ pre-release:
87
+ python utils/release.py
88
+
89
+ pre-patch:
90
+ python utils/release.py --patch
91
+
92
+ post-release:
93
+ python utils/release.py --post_release
94
+
95
+ post-patch:
96
+ python utils/release.py --post_release --patch
diffusers/PHILOSOPHY.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Philosophy
14
+
15
+ 🧨 Diffusers provides **state-of-the-art** pretrained diffusion models across multiple modalities.
16
+ Its purpose is to serve as a **modular toolbox** for both inference and training.
17
+
18
+ We aim to build a library that stands the test of time and therefore take API design very seriously.
19
+
20
+ In a nutshell, Diffusers is built to be a natural extension of PyTorch. Therefore, most of our design choices are based on [PyTorch's Design Principles](https://pytorch.org/docs/stable/community/design.html#pytorch-design-philosophy). Let's go over the most important ones:
21
+
22
+ ## Usability over Performance
23
+
24
+ - While Diffusers has many built-in performance-enhancing features (see [Memory and Speed](https://huggingface.co/docs/diffusers/optimization/fp16)), models are always loaded with the highest precision and lowest optimization. Therefore, by default diffusion pipelines are always instantiated on CPU with float32 precision if not otherwise defined by the user. This ensures usability across different platforms and accelerators and means that no complex installations are required to run the library.
25
+ - Diffusers aims to be a **light-weight** package and therefore has very few required dependencies, but many soft dependencies that can improve performance (such as `accelerate`, `safetensors`, `onnx`, etc...). We strive to keep the library as lightweight as possible so that it can be added without much concern as a dependency on other packages.
26
+ - Diffusers prefers simple, self-explainable code over condensed, magic code. This means that short-hand code syntaxes such as lambda functions, and advanced PyTorch operators are often not desired.
27
+
28
+ ## Simple over easy
29
+
30
+ As PyTorch states, **explicit is better than implicit** and **simple is better than complex**. This design philosophy is reflected in multiple parts of the library:
31
+ - We follow PyTorch's API with methods like [`DiffusionPipeline.to`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.to) to let the user handle device management.
32
+ - Raising concise error messages is preferred to silently correct erroneous input. Diffusers aims at teaching the user, rather than making the library as easy to use as possible.
33
+ - Complex model vs. scheduler logic is exposed instead of magically handled inside. Schedulers/Samplers are separated from diffusion models with minimal dependencies on each other. This forces the user to write the unrolled denoising loop. However, the separation allows for easier debugging and gives the user more control over adapting the denoising process or switching out diffusion models or schedulers.
34
+ - Separately trained components of the diffusion pipeline, *e.g.* the text encoder, the UNet, and the variational autoencoder, each has their own model class. This forces the user to handle the interaction between the different model components, and the serialization format separates the model components into different files. However, this allows for easier debugging and customization. DreamBooth or Textual Inversion training
35
+ is very simple thanks to Diffusers' ability to separate single components of the diffusion pipeline.
36
+
37
+ ## Tweakable, contributor-friendly over abstraction
38
+
39
+ For large parts of the library, Diffusers adopts an important design principle of the [Transformers library](https://github.com/huggingface/transformers), which is to prefer copy-pasted code over hasty abstractions. This design principle is very opinionated and stands in stark contrast to popular design principles such as [Don't repeat yourself (DRY)](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).
40
+ In short, just like Transformers does for modeling files, Diffusers prefers to keep an extremely low level of abstraction and very self-contained code for pipelines and schedulers.
41
+ Functions, long code blocks, and even classes can be copied across multiple files which at first can look like a bad, sloppy design choice that makes the library unmaintainable.
42
+ **However**, this design has proven to be extremely successful for Transformers and makes a lot of sense for community-driven, open-source machine learning libraries because:
43
+ - Machine Learning is an extremely fast-moving field in which paradigms, model architectures, and algorithms are changing rapidly, which therefore makes it very difficult to define long-lasting code abstractions.
44
+ - Machine Learning practitioners like to be able to quickly tweak existing code for ideation and research and therefore prefer self-contained code over one that contains many abstractions.
45
+ - Open-source libraries rely on community contributions and therefore must build a library that is easy to contribute to. The more abstract the code, the more dependencies, the harder to read, and the harder to contribute to. Contributors simply stop contributing to very abstract libraries out of fear of breaking vital functionality. If contributing to a library cannot break other fundamental code, not only is it more inviting for potential new contributors, but it is also easier to review and contribute to multiple parts in parallel.
46
+
47
+ At Hugging Face, we call this design the **single-file policy** which means that almost all of the code of a certain class should be written in a single, self-contained file. To read more about the philosophy, you can have a look
48
+ at [this blog post](https://huggingface.co/blog/transformers-design-philosophy).
49
+
50
+ In Diffusers, we follow this philosophy for both pipelines and schedulers, but only partly for diffusion models. The reason we don't follow this design fully for diffusion models is because almost all diffusion pipelines, such
51
+ as [DDPM](https://huggingface.co/docs/diffusers/api/pipelines/ddpm), [Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/overview#stable-diffusion-pipelines), [unCLIP (DALL·E 2)](https://huggingface.co/docs/diffusers/api/pipelines/unclip) and [Imagen](https://imagen.research.google/) all rely on the same diffusion model, the [UNet](https://huggingface.co/docs/diffusers/api/models/unet2d-cond).
52
+
53
+ Great, now you should have generally understood why 🧨 Diffusers is designed the way it is 🤗.
54
+ We try to apply these design principles consistently across the library. Nevertheless, there are some minor exceptions to the philosophy or some unlucky design choices. If you have feedback regarding the design, we would ❤️ to hear it [directly on GitHub](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=).
55
+
56
+ ## Design Philosophy in Details
57
+
58
+ Now, let's look a bit into the nitty-gritty details of the design philosophy. Diffusers essentially consists of three major classes: [pipelines](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines), [models](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models), and [schedulers](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers).
59
+ Let's walk through more detailed design decisions for each class.
60
+
61
+ ### Pipelines
62
+
63
+ Pipelines are designed to be easy to use (therefore do not follow [*Simple over easy*](#simple-over-easy) 100%), are not feature complete, and should loosely be seen as examples of how to use [models](#models) and [schedulers](#schedulers) for inference.
64
+
65
+ The following design principles are followed:
66
+ - Pipelines follow the single-file policy. All pipelines can be found in individual directories under src/diffusers/pipelines. One pipeline folder corresponds to one diffusion paper/project/release. Multiple pipeline files can be gathered in one pipeline folder, as it’s done for [`src/diffusers/pipelines/stable-diffusion`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/stable_diffusion). If pipelines share similar functionality, one can make use of the [# Copied from mechanism](https://github.com/huggingface/diffusers/blob/125d783076e5bd9785beb05367a2d2566843a271/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L251).
67
+ - Pipelines all inherit from [`DiffusionPipeline`].
68
+ - Every pipeline consists of different model and scheduler components, that are documented in the [`model_index.json` file](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/model_index.json), are accessible under the same name as attributes of the pipeline and can be shared between pipelines with [`DiffusionPipeline.components`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.components) function.
69
+ - Every pipeline should be loadable via the [`DiffusionPipeline.from_pretrained`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.from_pretrained) function.
70
+ - Pipelines should be used **only** for inference.
71
+ - Pipelines should be very readable, self-explanatory, and easy to tweak.
72
+ - Pipelines should be designed to build on top of each other and be easy to integrate into higher-level APIs.
73
+ - Pipelines are **not** intended to be feature-complete user interfaces. For feature-complete user interfaces one should rather have a look at [InvokeAI](https://github.com/invoke-ai/InvokeAI), [Diffuzers](https://github.com/abhishekkrthakur/diffuzers), and [lama-cleaner](https://github.com/Sanster/lama-cleaner).
74
+ - Every pipeline should have one and only one way to run it via a `__call__` method. The naming of the `__call__` arguments should be shared across all pipelines.
75
+ - Pipelines should be named after the task they are intended to solve.
76
+ - In almost all cases, novel diffusion pipelines shall be implemented in a new pipeline folder/file.
77
+
78
+ ### Models
79
+
80
+ Models are designed as configurable toolboxes that are natural extensions of [PyTorch's Module class](https://pytorch.org/docs/stable/generated/torch.nn.Module.html). They only partly follow the **single-file policy**.
81
+
82
+ The following design principles are followed:
83
+ - Models correspond to **a type of model architecture**. *E.g.* the [`UNet2DConditionModel`] class is used for all UNet variations that expect 2D image inputs and are conditioned on some context.
84
+ - All models can be found in [`src/diffusers/models`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models) and every model architecture shall be defined in its file, e.g. [`unets/unet_2d_condition.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unets/unet_2d_condition.py), [`transformers/transformer_2d.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_2d.py), etc...
85
+ - Models **do not** follow the single-file policy and should make use of smaller model building blocks, such as [`attention.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py), [`resnet.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py), [`embeddings.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/embeddings.py), etc... **Note**: This is in stark contrast to Transformers' modeling files and shows that models do not really follow the single-file policy.
86
+ - Models intend to expose complexity, just like PyTorch's `Module` class, and give clear error messages.
87
+ - Models all inherit from `ModelMixin` and `ConfigMixin`.
88
+ - Models can be optimized for performance when it doesn’t demand major code changes, keep backward compatibility, and give significant memory or compute gain.
89
+ - Models should by default have the highest precision and lowest performance setting.
90
+ - To integrate new model checkpoints whose general architecture can be classified as an architecture that already exists in Diffusers, the existing model architecture shall be adapted to make it work with the new checkpoint. One should only create a new file if the model architecture is fundamentally different.
91
+ - Models should be designed to be easily extendable to future changes. This can be achieved by limiting public function arguments, configuration arguments, and "foreseeing" future changes, *e.g.* it is usually better to add `string` "...type" arguments that can easily be extended to new future types instead of boolean `is_..._type` arguments. Only the minimum amount of changes shall be made to existing architectures to make a new model checkpoint work.
92
+ - The model design is a difficult trade-off between keeping code readable and concise and supporting many model checkpoints. For most parts of the modeling code, classes shall be adapted for new model checkpoints, while there are some exceptions where it is preferred to add new classes to make sure the code is kept concise and
93
+ readable long-term, such as [UNet blocks](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unets/unet_2d_blocks.py) and [Attention processors](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
94
+
95
+ ### Schedulers
96
+
97
+ Schedulers are responsible to guide the denoising process for inference as well as to define a noise schedule for training. They are designed as individual classes with loadable configuration files and strongly follow the **single-file policy**.
98
+
99
+ The following design principles are followed:
100
+ - All schedulers are found in [`src/diffusers/schedulers`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers).
101
+ - Schedulers are **not** allowed to import from large utils files and shall be kept very self-contained.
102
+ - One scheduler Python file corresponds to one scheduler algorithm (as might be defined in a paper).
103
+ - If schedulers share similar functionalities, we can make use of the `# Copied from` mechanism.
104
+ - Schedulers all inherit from `SchedulerMixin` and `ConfigMixin`.
105
+ - Schedulers can be easily swapped out with the [`ConfigMixin.from_config`](https://huggingface.co/docs/diffusers/main/en/api/configuration#diffusers.ConfigMixin.from_config) method as explained in detail [here](./docs/source/en/using-diffusers/schedulers.md).
106
+ - Every scheduler has to have a `set_num_inference_steps`, and a `step` function. `set_num_inference_steps(...)` has to be called before every denoising process, *i.e.* before `step(...)` is called.
107
+ - Every scheduler exposes the timesteps to be "looped over" via a `timesteps` attribute, which is an array of timesteps the model will be called upon.
108
+ - The `step(...)` function takes a predicted model output and the "current" sample (x_t) and returns the "previous", slightly more denoised sample (x_t-1).
109
+ - Given the complexity of diffusion schedulers, the `step` function does not expose all the complexity and can be a bit of a "black box".
110
+ - In almost all cases, novel schedulers shall be implemented in a new scheduling file.
diffusers/README.md ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2022 - The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ <p align="center">
18
+ <br>
19
+ <img src="https://raw.githubusercontent.com/huggingface/diffusers/main/docs/source/en/imgs/diffusers_library.jpg" width="400"/>
20
+ <br>
21
+ <p>
22
+ <p align="center">
23
+ <a href="https://github.com/huggingface/diffusers/blob/main/LICENSE"><img alt="GitHub" src="https://img.shields.io/github/license/huggingface/datasets.svg?color=blue"></a>
24
+ <a href="https://github.com/huggingface/diffusers/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/diffusers.svg"></a>
25
+ <a href="https://pepy.tech/project/diffusers"><img alt="GitHub release" src="https://static.pepy.tech/badge/diffusers/month"></a>
26
+ <a href="CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg"></a>
27
+ <a href="https://twitter.com/diffuserslib"><img alt="X account" src="https://img.shields.io/twitter/url/https/twitter.com/diffuserslib.svg?style=social&label=Follow%20%40diffuserslib"></a>
28
+ </p>
29
+
30
+ 🤗 Diffusers is the go-to library for state-of-the-art pretrained diffusion models for generating images, audio, and even 3D structures of molecules. Whether you're looking for a simple inference solution or training your own diffusion models, 🤗 Diffusers is a modular toolbox that supports both. Our library is designed with a focus on [usability over performance](https://huggingface.co/docs/diffusers/conceptual/philosophy#usability-over-performance), [simple over easy](https://huggingface.co/docs/diffusers/conceptual/philosophy#simple-over-easy), and [customizability over abstractions](https://huggingface.co/docs/diffusers/conceptual/philosophy#tweakable-contributorfriendly-over-abstraction).
31
+
32
+ 🤗 Diffusers offers three core components:
33
+
34
+ - State-of-the-art [diffusion pipelines](https://huggingface.co/docs/diffusers/api/pipelines/overview) that can be run in inference with just a few lines of code.
35
+ - Interchangeable noise [schedulers](https://huggingface.co/docs/diffusers/api/schedulers/overview) for different diffusion speeds and output quality.
36
+ - Pretrained [models](https://huggingface.co/docs/diffusers/api/models/overview) that can be used as building blocks, and combined with schedulers, for creating your own end-to-end diffusion systems.
37
+
38
+ ## Installation
39
+
40
+ We recommend installing 🤗 Diffusers in a virtual environment from PyPI or Conda. For more details about installing [PyTorch](https://pytorch.org/get-started/locally/) and [Flax](https://flax.readthedocs.io/en/latest/#installation), please refer to their official documentation.
41
+
42
+ ### PyTorch
43
+
44
+ With `pip` (official package):
45
+
46
+ ```bash
47
+ pip install --upgrade diffusers[torch]
48
+ ```
49
+
50
+ With `conda` (maintained by the community):
51
+
52
+ ```sh
53
+ conda install -c conda-forge diffusers
54
+ ```
55
+
56
+ ### Flax
57
+
58
+ With `pip` (official package):
59
+
60
+ ```bash
61
+ pip install --upgrade diffusers[flax]
62
+ ```
63
+
64
+ ### Apple Silicon (M1/M2) support
65
+
66
+ Please refer to the [How to use Stable Diffusion in Apple Silicon](https://huggingface.co/docs/diffusers/optimization/mps) guide.
67
+
68
+ ## Quickstart
69
+
70
+ Generating outputs is super easy with 🤗 Diffusers. To generate an image from text, use the `from_pretrained` method to load any pretrained diffusion model (browse the [Hub](https://huggingface.co/models?library=diffusers&sort=downloads) for 30,000+ checkpoints):
71
+
72
+ ```python
73
+ from diffusers import DiffusionPipeline
74
+ import torch
75
+
76
+ pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16)
77
+ pipeline.to("cuda")
78
+ pipeline("An image of a squirrel in Picasso style").images[0]
79
+ ```
80
+
81
+ You can also dig into the models and schedulers toolbox to build your own diffusion system:
82
+
83
+ ```python
84
+ from diffusers import DDPMScheduler, UNet2DModel
85
+ from PIL import Image
86
+ import torch
87
+
88
+ scheduler = DDPMScheduler.from_pretrained("google/ddpm-cat-256")
89
+ model = UNet2DModel.from_pretrained("google/ddpm-cat-256").to("cuda")
90
+ scheduler.set_timesteps(50)
91
+
92
+ sample_size = model.config.sample_size
93
+ noise = torch.randn((1, 3, sample_size, sample_size), device="cuda")
94
+ input = noise
95
+
96
+ for t in scheduler.timesteps:
97
+ with torch.no_grad():
98
+ noisy_residual = model(input, t).sample
99
+ prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
100
+ input = prev_noisy_sample
101
+
102
+ image = (input / 2 + 0.5).clamp(0, 1)
103
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
104
+ image = Image.fromarray((image * 255).round().astype("uint8"))
105
+ image
106
+ ```
107
+
108
+ Check out the [Quickstart](https://huggingface.co/docs/diffusers/quicktour) to launch your diffusion journey today!
109
+
110
+ ## How to navigate the documentation
111
+
112
+ | **Documentation** | **What can I learn?** |
113
+ |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
114
+ | [Tutorial](https://huggingface.co/docs/diffusers/tutorials/tutorial_overview) | A basic crash course for learning how to use the library's most important features like using models and schedulers to build your own diffusion system, and training your own diffusion model. |
115
+ | [Loading](https://huggingface.co/docs/diffusers/using-diffusers/loading) | Guides for how to load and configure all the components (pipelines, models, and schedulers) of the library, as well as how to use different schedulers. |
116
+ | [Pipelines for inference](https://huggingface.co/docs/diffusers/using-diffusers/overview_techniques) | Guides for how to use pipelines for different inference tasks, batched generation, controlling generated outputs and randomness, and how to contribute a pipeline to the library. |
117
+ | [Optimization](https://huggingface.co/docs/diffusers/optimization/fp16) | Guides for how to optimize your diffusion model to run faster and consume less memory. |
118
+ | [Training](https://huggingface.co/docs/diffusers/training/overview) | Guides for how to train a diffusion model for different tasks with different training techniques. |
119
+ ## Contribution
120
+
121
+ We ❤️ contributions from the open-source community!
122
+ If you want to contribute to this library, please check out our [Contribution guide](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md).
123
+ You can look out for [issues](https://github.com/huggingface/diffusers/issues) you'd like to tackle to contribute to the library.
124
+ - See [Good first issues](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) for general opportunities to contribute
125
+ - See [New model/pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22) to contribute exciting new diffusion models / diffusion pipelines
126
+ - See [New scheduler](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22)
127
+
128
+ Also, say 👋 in our public Discord channel <a href="https://discord.gg/G7tWnz98XR"><img alt="Join us on Discord" src="https://img.shields.io/discord/823813159592001537?color=5865F2&logo=discord&logoColor=white"></a>. We discuss the hottest trends about diffusion models, help each other with contributions, personal projects or just hang out ☕.
129
+
130
+
131
+ ## Popular Tasks & Pipelines
132
+
133
+ <table>
134
+ <tr>
135
+ <th>Task</th>
136
+ <th>Pipeline</th>
137
+ <th>🤗 Hub</th>
138
+ </tr>
139
+ <tr style="border-top: 2px solid black">
140
+ <td>Unconditional Image Generation</td>
141
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/ddpm"> DDPM </a></td>
142
+ <td><a href="https://huggingface.co/google/ddpm-ema-church-256"> google/ddpm-ema-church-256 </a></td>
143
+ </tr>
144
+ <tr style="border-top: 2px solid black">
145
+ <td>Text-to-Image</td>
146
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/text2img">Stable Diffusion Text-to-Image</a></td>
147
+ <td><a href="https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5"> stable-diffusion-v1-5/stable-diffusion-v1-5 </a></td>
148
+ </tr>
149
+ <tr>
150
+ <td>Text-to-Image</td>
151
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/unclip">unCLIP</a></td>
152
+ <td><a href="https://huggingface.co/kakaobrain/karlo-v1-alpha"> kakaobrain/karlo-v1-alpha </a></td>
153
+ </tr>
154
+ <tr>
155
+ <td>Text-to-Image</td>
156
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/deepfloyd_if">DeepFloyd IF</a></td>
157
+ <td><a href="https://huggingface.co/DeepFloyd/IF-I-XL-v1.0"> DeepFloyd/IF-I-XL-v1.0 </a></td>
158
+ </tr>
159
+ <tr>
160
+ <td>Text-to-Image</td>
161
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/kandinsky">Kandinsky</a></td>
162
+ <td><a href="https://huggingface.co/kandinsky-community/kandinsky-2-2-decoder"> kandinsky-community/kandinsky-2-2-decoder </a></td>
163
+ </tr>
164
+ <tr style="border-top: 2px solid black">
165
+ <td>Text-guided Image-to-Image</td>
166
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/controlnet">ControlNet</a></td>
167
+ <td><a href="https://huggingface.co/lllyasviel/sd-controlnet-canny"> lllyasviel/sd-controlnet-canny </a></td>
168
+ </tr>
169
+ <tr>
170
+ <td>Text-guided Image-to-Image</td>
171
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/pix2pix">InstructPix2Pix</a></td>
172
+ <td><a href="https://huggingface.co/timbrooks/instruct-pix2pix"> timbrooks/instruct-pix2pix </a></td>
173
+ </tr>
174
+ <tr>
175
+ <td>Text-guided Image-to-Image</td>
176
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/img2img">Stable Diffusion Image-to-Image</a></td>
177
+ <td><a href="https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5"> stable-diffusion-v1-5/stable-diffusion-v1-5 </a></td>
178
+ </tr>
179
+ <tr style="border-top: 2px solid black">
180
+ <td>Text-guided Image Inpainting</td>
181
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/inpaint">Stable Diffusion Inpainting</a></td>
182
+ <td><a href="https://huggingface.co/runwayml/stable-diffusion-inpainting"> runwayml/stable-diffusion-inpainting </a></td>
183
+ </tr>
184
+ <tr style="border-top: 2px solid black">
185
+ <td>Image Variation</td>
186
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/image_variation">Stable Diffusion Image Variation</a></td>
187
+ <td><a href="https://huggingface.co/lambdalabs/sd-image-variations-diffusers"> lambdalabs/sd-image-variations-diffusers </a></td>
188
+ </tr>
189
+ <tr style="border-top: 2px solid black">
190
+ <td>Super Resolution</td>
191
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/upscale">Stable Diffusion Upscale</a></td>
192
+ <td><a href="https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler"> stabilityai/stable-diffusion-x4-upscaler </a></td>
193
+ </tr>
194
+ <tr>
195
+ <td>Super Resolution</td>
196
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/latent_upscale">Stable Diffusion Latent Upscale</a></td>
197
+ <td><a href="https://huggingface.co/stabilityai/sd-x2-latent-upscaler"> stabilityai/sd-x2-latent-upscaler </a></td>
198
+ </tr>
199
+ </table>
200
+
201
+ ## Popular libraries using 🧨 Diffusers
202
+
203
+ - https://github.com/microsoft/TaskMatrix
204
+ - https://github.com/invoke-ai/InvokeAI
205
+ - https://github.com/InstantID/InstantID
206
+ - https://github.com/apple/ml-stable-diffusion
207
+ - https://github.com/Sanster/lama-cleaner
208
+ - https://github.com/IDEA-Research/Grounded-Segment-Anything
209
+ - https://github.com/ashawkey/stable-dreamfusion
210
+ - https://github.com/deep-floyd/IF
211
+ - https://github.com/bentoml/BentoML
212
+ - https://github.com/bmaltais/kohya_ss
213
+ - +14,000 other amazing GitHub repositories 💪
214
+
215
+ Thank you for using us ❤️.
216
+
217
+ ## Credits
218
+
219
+ This library concretizes previous work by many different authors and would not have been possible without their great research and implementations. We'd like to thank, in particular, the following implementations which have helped us in our development and without which the API could not have been as polished today:
220
+
221
+ - @CompVis' latent diffusion models library, available [here](https://github.com/CompVis/latent-diffusion)
222
+ - @hojonathanho original DDPM implementation, available [here](https://github.com/hojonathanho/diffusion) as well as the extremely useful translation into PyTorch by @pesser, available [here](https://github.com/pesser/pytorch_diffusion)
223
+ - @ermongroup's DDIM implementation, available [here](https://github.com/ermongroup/ddim)
224
+ - @yang-song's Score-VE and Score-VP implementations, available [here](https://github.com/yang-song/score_sde_pytorch)
225
+
226
+ We also want to thank @heejkoo for the very helpful overview of papers, code and resources on diffusion models, available [here](https://github.com/heejkoo/Awesome-Diffusion-Models) as well as @crowsonkb and @rromb for useful discussions and insights.
227
+
228
+ ## Citation
229
+
230
+ ```bibtex
231
+ @misc{von-platen-etal-2022-diffusers,
232
+ author = {Patrick von Platen and Suraj Patil and Anton Lozhkov and Pedro Cuenca and Nathan Lambert and Kashif Rasul and Mishig Davaadorj and Dhruv Nair and Sayak Paul and William Berman and Yiyi Xu and Steven Liu and Thomas Wolf},
233
+ title = {Diffusers: State-of-the-art diffusion models},
234
+ year = {2022},
235
+ publisher = {GitHub},
236
+ journal = {GitHub repository},
237
+ howpublished = {\url{https://github.com/huggingface/diffusers}}
238
+ }
239
+ ```
diffusers/_typos.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Files for typos
2
+ # Instruction: https://github.com/marketplace/actions/typos-action#getting-started
3
+
4
+ [default.extend-identifiers]
5
+
6
+ [default.extend-words]
7
+ NIN="NIN" # NIN is used in scripts/convert_ncsnpp_original_checkpoint_to_diffusers.py
8
+ nd="np" # nd may be np (numpy)
9
+ parms="parms" # parms is used in scripts/convert_original_stable_diffusion_to_diffusers.py
10
+
11
+
12
+ [files]
13
+ extend-exclude = ["_typos.toml"]
diffusers/pyproject.toml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.ruff]
2
+ line-length = 119
3
+
4
+ [tool.ruff.lint]
5
+ # Never enforce `E501` (line length violations).
6
+ ignore = ["C901", "E501", "E721", "E741", "F402", "F823"]
7
+ select = ["C", "E", "F", "I", "W"]
8
+
9
+ # Ignore import violations in all `__init__.py` files.
10
+ [tool.ruff.lint.per-file-ignores]
11
+ "__init__.py" = ["E402", "F401", "F403", "F811"]
12
+ "src/diffusers/utils/dummy_*.py" = ["F401"]
13
+
14
+ [tool.ruff.lint.isort]
15
+ lines-after-imports = 2
16
+ known-first-party = ["diffusers"]
17
+
18
+ [tool.ruff.format]
19
+ # Like Black, use double quotes for strings.
20
+ quote-style = "double"
21
+
22
+ # Like Black, indent with spaces, rather than tabs.
23
+ indent-style = "space"
24
+
25
+ # Like Black, respect magic trailing commas.
26
+ skip-magic-trailing-comma = false
27
+
28
+ # Like Black, automatically detect the appropriate line ending.
29
+ line-ending = "auto"
diffusers/setup.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/main/setup.py
17
+
18
+ To create the package for PyPI.
19
+
20
+ 1. Run `make pre-release` (or `make pre-patch` for a patch release) then run `make fix-copies` to fix the index of the
21
+ documentation.
22
+
23
+ If releasing on a special branch, copy the updated README.md on the main branch for the commit you will make
24
+ for the post-release and run `make fix-copies` on the main branch as well.
25
+
26
+ 2. Unpin specific versions from setup.py that use a git install.
27
+
28
+ 3. Checkout the release branch (v<RELEASE>-release, for example v4.19-release), and commit these changes with the
29
+ message: "Release: <RELEASE>" and push.
30
+
31
+ 4. Manually trigger the "Nightly and release tests on main/release branch" workflow from the release branch. Wait for
32
+ the tests to complete. We can safely ignore the known test failures.
33
+
34
+ 5. Wait for the tests on main to be completed and be green (otherwise revert and fix bugs).
35
+
36
+ 6. Add a tag in git to mark the release: "git tag v<RELEASE> -m 'Adds tag v<RELEASE> for PyPI'"
37
+ Push the tag to git: git push --tags origin v<RELEASE>-release
38
+
39
+ 7. Build both the sources and the wheel. Do not change anything in setup.py between
40
+ creating the wheel and the source distribution (obviously).
41
+
42
+ For the wheel, run: "python setup.py bdist_wheel" in the top level directory
43
+ (This will build a wheel for the Python version you use to build it).
44
+
45
+ For the sources, run: "python setup.py sdist"
46
+ You should now have a /dist directory with both .whl and .tar.gz source versions.
47
+
48
+ Long story cut short, you need to run both before you can upload the distribution to the
49
+ test PyPI and the actual PyPI servers:
50
+
51
+ python setup.py bdist_wheel && python setup.py sdist
52
+
53
+ 8. Check that everything looks correct by uploading the package to the PyPI test server:
54
+
55
+ twine upload dist/* -r pypitest
56
+ (pypi suggests using twine as other methods upload files via plaintext.)
57
+ You may have to specify the repository url, use the following command then:
58
+ twine upload dist/* -r pypitest --repository-url=https://test.pypi.org/legacy/
59
+
60
+ Check that you can install it in a virtualenv by running:
61
+ pip install -i https://testpypi.python.org/pypi diffusers
62
+
63
+ If you are testing from a Colab Notebook, for instance, then do:
64
+ pip install diffusers && pip uninstall diffusers
65
+ pip install -i https://testpypi.python.org/pypi diffusers
66
+
67
+ Check you can run the following commands:
68
+ python -c "from diffusers import __version__; print(__version__)"
69
+ python -c "from diffusers import DiffusionPipeline; pipe = DiffusionPipeline.from_pretrained('fusing/unet-ldm-dummy-update'); pipe()"
70
+ python -c "from diffusers import DiffusionPipeline; pipe = DiffusionPipeline.from_pretrained('hf-internal-testing/tiny-stable-diffusion-pipe', safety_checker=None); pipe('ah suh du')"
71
+ python -c "from diffusers import *"
72
+
73
+ 9. Upload the final version to the actual PyPI:
74
+ twine upload dist/* -r pypi
75
+
76
+ 10. Prepare the release notes and publish them on GitHub once everything is looking hunky-dory. You can use the following
77
+ Space to fetch all the commits applicable for the release: https://huggingface.co/spaces/sayakpaul/auto-release-notes-diffusers.
78
+ It automatically fetches the correct tag and branch but also provides the option to configure them.
79
+ `tag` should be the previous release tag (v0.26.1, for example), and `branch` should be
80
+ the latest release branch (v0.27.0-release, for example). It denotes all commits that have happened on branch
81
+ v0.27.0-release after the tag v0.26.1 was created.
82
+
83
+ 11. Run `make post-release` (or, for a patch release, `make post-patch`). If you were on a branch for the release,
84
+ you need to go back to main before executing this.
85
+ """
86
+
87
+ import os
88
+ import re
89
+ import sys
90
+
91
+ from setuptools import Command, find_packages, setup
92
+
93
+
94
+ # IMPORTANT:
95
+ # 1. all dependencies should be listed here with their version requirements if any
96
+ # 2. once modified, run: `make deps_table_update` to update src/diffusers/dependency_versions_table.py
97
+ _deps = [
98
+ "Pillow", # keep the PIL.Image.Resampling deprecation away
99
+ "accelerate>=0.31.0",
100
+ "compel==0.1.8",
101
+ "datasets",
102
+ "filelock",
103
+ "flax>=0.4.1",
104
+ "hf-doc-builder>=0.3.0",
105
+ "huggingface-hub>=0.27.0",
106
+ "requests-mock==1.10.0",
107
+ "importlib_metadata",
108
+ "invisible-watermark>=0.2.0",
109
+ "isort>=5.5.4",
110
+ "jax>=0.4.1",
111
+ "jaxlib>=0.4.1",
112
+ "Jinja2",
113
+ "k-diffusion==0.0.12",
114
+ "torchsde",
115
+ "note_seq",
116
+ "librosa",
117
+ "numpy",
118
+ "parameterized",
119
+ "peft>=0.15.0",
120
+ "protobuf>=3.20.3,<4",
121
+ "pytest",
122
+ "pytest-timeout",
123
+ "pytest-xdist",
124
+ "python>=3.8.0",
125
+ "ruff==0.9.10",
126
+ "safetensors>=0.3.1",
127
+ "sentencepiece>=0.1.91,!=0.1.92",
128
+ "GitPython<3.1.19",
129
+ "scipy",
130
+ "onnx",
131
+ "optimum_quanto>=0.2.6",
132
+ "gguf>=0.10.0",
133
+ "torchao>=0.7.0",
134
+ "bitsandbytes>=0.43.3",
135
+ "regex!=2019.12.17",
136
+ "requests",
137
+ "tensorboard",
138
+ "tiktoken>=0.7.0",
139
+ "torch>=1.4",
140
+ "torchvision",
141
+ "transformers>=4.41.2",
142
+ "urllib3<=2.0.0",
143
+ "black",
144
+ "phonemizer",
145
+ "opencv-python",
146
+ ]
147
+
148
+ # this is a lookup table with items like:
149
+ #
150
+ # tokenizers: "huggingface-hub==0.8.0"
151
+ # packaging: "packaging"
152
+ #
153
+ # some of the values are versioned whereas others aren't.
154
+ deps = {b: a for a, b in (re.findall(r"^(([^!=<>~]+)(?:[!=<>~].*)?$)", x)[0] for x in _deps)}
155
+
156
+ # since we save this data in src/diffusers/dependency_versions_table.py it can be easily accessed from
157
+ # anywhere. If you need to quickly access the data from this table in a shell, you can do so easily with:
158
+ #
159
+ # python -c 'import sys; from diffusers.dependency_versions_table import deps; \
160
+ # print(" ".join([deps[x] for x in sys.argv[1:]]))' tokenizers datasets
161
+ #
162
+ # Just pass the desired package names to that script as it's shown with 2 packages above.
163
+ #
164
+ # If diffusers is not yet installed and the work is done from the cloned repo remember to add `PYTHONPATH=src` to the script above
165
+ #
166
+ # You can then feed this for example to `pip`:
167
+ #
168
+ # pip install -U $(python -c 'import sys; from diffusers.dependency_versions_table import deps; \
169
+ # print(" ".join([deps[x] for x in sys.argv[1:]]))' tokenizers datasets)
170
+ #
171
+
172
+
173
+ def deps_list(*pkgs):
174
+ return [deps[pkg] for pkg in pkgs]
175
+
176
+
177
+ class DepsTableUpdateCommand(Command):
178
+ """
179
+ A custom command that updates the dependency table.
180
+ usage: python setup.py deps_table_update
181
+ """
182
+
183
+ description = "build runtime dependency table"
184
+ user_options = [
185
+ # format: (long option, short option, description).
186
+ (
187
+ "dep-table-update",
188
+ None,
189
+ "updates src/diffusers/dependency_versions_table.py",
190
+ ),
191
+ ]
192
+
193
+ def initialize_options(self):
194
+ pass
195
+
196
+ def finalize_options(self):
197
+ pass
198
+
199
+ def run(self):
200
+ entries = "\n".join([f' "{k}": "{v}",' for k, v in deps.items()])
201
+ content = [
202
+ "# THIS FILE HAS BEEN AUTOGENERATED. To update:",
203
+ "# 1. modify the `_deps` dict in setup.py",
204
+ "# 2. run `make deps_table_update`",
205
+ "deps = {",
206
+ entries,
207
+ "}",
208
+ "",
209
+ ]
210
+ target = "src/diffusers/dependency_versions_table.py"
211
+ print(f"updating {target}")
212
+ with open(target, "w", encoding="utf-8", newline="\n") as f:
213
+ f.write("\n".join(content))
214
+
215
+
216
+ extras = {}
217
+ extras["quality"] = deps_list("urllib3", "isort", "ruff", "hf-doc-builder")
218
+ extras["docs"] = deps_list("hf-doc-builder")
219
+ extras["training"] = deps_list("accelerate", "datasets", "protobuf", "tensorboard", "Jinja2", "peft")
220
+ extras["test"] = deps_list(
221
+ "compel",
222
+ "GitPython",
223
+ "datasets",
224
+ "Jinja2",
225
+ "invisible-watermark",
226
+ "k-diffusion",
227
+ "librosa",
228
+ "parameterized",
229
+ "pytest",
230
+ "pytest-timeout",
231
+ "pytest-xdist",
232
+ "requests-mock",
233
+ "safetensors",
234
+ "sentencepiece",
235
+ "scipy",
236
+ "tiktoken",
237
+ "torchvision",
238
+ "transformers",
239
+ "phonemizer",
240
+ )
241
+ extras["torch"] = deps_list("torch", "accelerate")
242
+
243
+ extras["bitsandbytes"] = deps_list("bitsandbytes", "accelerate")
244
+ extras["gguf"] = deps_list("gguf", "accelerate")
245
+ extras["optimum_quanto"] = deps_list("optimum_quanto", "accelerate")
246
+ extras["torchao"] = deps_list("torchao", "accelerate")
247
+
248
+ if os.name == "nt": # windows
249
+ extras["flax"] = [] # jax is not supported on windows
250
+ else:
251
+ extras["flax"] = deps_list("jax", "jaxlib", "flax")
252
+
253
+ extras["dev"] = (
254
+ extras["quality"] + extras["test"] + extras["training"] + extras["docs"] + extras["torch"] + extras["flax"]
255
+ )
256
+
257
+ install_requires = [
258
+ deps["importlib_metadata"],
259
+ deps["filelock"],
260
+ deps["huggingface-hub"],
261
+ deps["numpy"],
262
+ deps["regex"],
263
+ deps["requests"],
264
+ deps["safetensors"],
265
+ deps["Pillow"],
266
+ ]
267
+
268
+ version_range_max = max(sys.version_info[1], 10) + 1
269
+
270
+ setup(
271
+ name="diffusers",
272
+ version="0.35.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots)
273
+ description="State-of-the-art diffusion in PyTorch and JAX.",
274
+ long_description=open("README.md", "r", encoding="utf-8").read(),
275
+ long_description_content_type="text/markdown",
276
+ keywords="deep learning diffusion jax pytorch stable diffusion audioldm",
277
+ license="Apache 2.0 License",
278
+ author="The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/diffusers/graphs/contributors)",
279
+ author_email="diffusers@huggingface.co",
280
+ url="https://github.com/huggingface/diffusers",
281
+ package_dir={"": "src"},
282
+ packages=find_packages("src"),
283
+ package_data={"diffusers": ["py.typed"]},
284
+ include_package_data=True,
285
+ python_requires=">=3.8.0",
286
+ install_requires=list(install_requires),
287
+ extras_require=extras,
288
+ entry_points={"console_scripts": ["diffusers-cli=diffusers.commands.diffusers_cli:main"]},
289
+ classifiers=[
290
+ "Development Status :: 5 - Production/Stable",
291
+ "Intended Audience :: Developers",
292
+ "Intended Audience :: Education",
293
+ "Intended Audience :: Science/Research",
294
+ "License :: OSI Approved :: Apache Software License",
295
+ "Operating System :: OS Independent",
296
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
297
+ "Programming Language :: Python :: 3",
298
+ ]
299
+ + [f"Programming Language :: Python :: 3.{i}" for i in range(8, version_range_max)],
300
+ cmdclass={"deps_table_update": DepsTableUpdateCommand},
301
+ )
download.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import snapshot_download
2
+
3
+ local_dir = "/home/ubuntu/zhixingyuan/QwenIllustrious/models/Qwen2.5-VL-7B-Instruct" # 自定义目录
4
+ snapshot_download(
5
+ repo_id="Qwen/Qwen2.5-VL-7B-Instruct",
6
+ local_dir=local_dir,
7
+ local_dir_use_symlinks=False, # 推荐设为 False,实际复制文件
8
+ ignore_patterns=["flux1-dev.safetensors"]
9
+ )
inference.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Qwen-SDXL Inference Script
3
+ 基于 Qwen3 Embedding 的 SDXL 推理管道
4
+ """
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from typing import List, Optional, Union, Dict, Any, Tuple
10
+ import json
11
+ import numpy as np
12
+ from PIL import Image
13
+ import safetensors.torch
14
+
15
+
16
+ class QwenEmbeddingAdapter(nn.Module):
17
+ """
18
+ Adapter layer to project Qwen3 embeddings to SDXL-compatible dimensions
19
+ 将 Qwen3 嵌入维度投影到 SDXL 兼容维度
20
+ - Text embeddings: 1024 -> 2048 (for encoder_hidden_states)
21
+ - Pooled embeddings: 1024 -> 1280 (for text_embeds in added_cond_kwargs)
22
+ """
23
+ def __init__(self, qwen_dim=1024, sdxl_text_dim=2048, sdxl_pooled_dim=1280):
24
+ super().__init__()
25
+ # Text embeddings projection (for encoder_hidden_states)
26
+ self.text_projection = nn.Linear(qwen_dim, sdxl_text_dim)
27
+ self.text_layer_norm = nn.LayerNorm(sdxl_text_dim)
28
+ self.text_activation = nn.GELU()
29
+
30
+ # Pooled embeddings MLP (for text_embeds in added_cond_kwargs)
31
+ self.pooled_mlp = nn.Sequential(
32
+ nn.Linear(qwen_dim, qwen_dim * 2),
33
+ nn.GELU(),
34
+ nn.Dropout(0.1),
35
+ nn.Linear(qwen_dim * 2, sdxl_pooled_dim),
36
+ nn.LayerNorm(sdxl_pooled_dim)
37
+ )
38
+
39
+ # 初始化权重
40
+ self._init_weights()
41
+
42
+ def _init_weights(self):
43
+ # Text projection initialization
44
+ nn.init.xavier_uniform_(self.text_projection.weight)
45
+ nn.init.zeros_(self.text_projection.bias)
46
+
47
+ # Pooled MLP initialization
48
+ for module in self.pooled_mlp:
49
+ if isinstance(module, nn.Linear):
50
+ nn.init.xavier_uniform_(module.weight)
51
+ nn.init.zeros_(module.bias)
52
+
53
+ def forward_text_embeddings(self, qwen_embeddings):
54
+ """
55
+ Project text embeddings for encoder_hidden_states
56
+ Args:
57
+ qwen_embeddings: tensor of shape [batch_size, seq_len, 1024]
58
+ Returns:
59
+ text_embeddings: tensor of shape [batch_size, seq_len, 2048]
60
+ """
61
+ projected = self.text_projection(qwen_embeddings)
62
+ projected = self.text_activation(projected)
63
+ return self.text_layer_norm(projected)
64
+
65
+ def forward_pooled_embeddings(self, qwen_embeddings):
66
+ """
67
+ Project pooled embeddings for text_embeds (using MLP)
68
+ Args:
69
+ qwen_embeddings: tensor of shape [batch_size, 1024]
70
+ Returns:
71
+ pooled_embeddings: tensor of shape [batch_size, 1280]
72
+ """
73
+ return self.pooled_mlp(qwen_embeddings)
74
+
75
+
76
+ def load_qwen_model(model_path: str, device: str = "cuda"):
77
+ """
78
+ Load Qwen3 embedding model
79
+ 加载 Qwen3 嵌入模型
80
+ """
81
+ try:
82
+ # from sentence_transformers import SentenceTransformer
83
+ from sentence_transformers import QwenIllustriousSentenceTransformer
84
+ model = QwenIllustriousSentenceTransformer(model_path)
85
+ model.to(device)
86
+ return model
87
+ except ImportError:
88
+ print("Warning: sentence-transformers not available. Using mock embeddings.")
89
+ return None
90
+
91
+
92
+ def encode_text_with_qwen(
93
+ qwen_model,
94
+ texts: List[str],
95
+ device: str = "cuda",
96
+ max_length: int = 512,
97
+ use_query_mode: bool = False
98
+ ) -> torch.Tensor:
99
+ """
100
+ Encode text using Qwen3 model
101
+ 使用 Qwen3 模型编码文本
102
+ Args:
103
+ qwen_model: Qwen3 embedding model
104
+ texts: List of text strings to encode
105
+ device: Device to run on
106
+ max_length: Maximum sequence length
107
+ use_query_mode: Whether to use query prompt for better understanding
108
+ """
109
+ if qwen_model is None:
110
+ # Mock embeddings for testing when sentence-transformers is not available
111
+ batch_size = len(texts)
112
+ return torch.randn(batch_size, 1024, device=device, dtype=torch.float32)
113
+
114
+ with torch.no_grad():
115
+ # Use query prompt for better text understanding when specified
116
+ embeddings = qwen_model.encode(
117
+ texts,
118
+ prompt_name="query" if use_query_mode else None,
119
+ convert_to_tensor=True,
120
+ max_length=max_length,
121
+ device=device
122
+ )
123
+
124
+ return embeddings
125
+
126
+
127
+ def load_unet_from_safetensors(unet_path: str, config_path: str, device: str = "cuda", dtype: torch.dtype = torch.bfloat16):
128
+ """
129
+ Load UNet from safetensors file
130
+ 从 safetensors 文件加载 UNet
131
+ """
132
+ try:
133
+ from diffusers import UNet2DConditionModel
134
+
135
+ # Load config
136
+ with open(config_path, 'r') as f:
137
+ unet_config = json.load(f)
138
+
139
+ # Create UNet
140
+ unet = UNet2DConditionModel.from_config(unet_config)
141
+
142
+ # Load weights
143
+ state_dict = safetensors.torch.load_file(unet_path)
144
+ unet.load_state_dict(state_dict)
145
+ unet.to(device, dtype)
146
+
147
+ return unet
148
+ except Exception as e:
149
+ print(f"Error loading UNet: {e}")
150
+ return None
151
+
152
+
153
+ def load_vae_from_safetensors(vae_path: str, config_path: str, device: str = "cuda", dtype: torch.dtype = torch.bfloat16):
154
+ """
155
+ Load VAE from safetensors file
156
+ 从 safetensors 文件加载 VAE
157
+ """
158
+ try:
159
+ from diffusers import AutoencoderKL
160
+
161
+ # Load config
162
+ with open(config_path, 'r') as f:
163
+ vae_config = json.load(f)
164
+
165
+ # Create VAE
166
+ vae = AutoencoderKL.from_config(vae_config)
167
+
168
+ # Load weights
169
+ state_dict = safetensors.torch.load_file(vae_path)
170
+ vae.load_state_dict(state_dict)
171
+ vae.to(device, dtype)
172
+
173
+ return vae
174
+ except Exception as e:
175
+ print(f"Error loading VAE: {e}")
176
+ return None
177
+
178
+
179
+ def create_scheduler():
180
+ """
181
+ Create DDPM scheduler
182
+ 创建 DDPM 调度器
183
+ """
184
+ try:
185
+ from diffusers import DDPMScheduler
186
+ scheduler = DDPMScheduler.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="scheduler")
187
+ return scheduler
188
+ except Exception as e:
189
+ print(f"Error creating scheduler: {e}")
190
+ return None
191
+
192
+
193
+ class QwenSDXLInference:
194
+ """
195
+ Qwen-SDXL 推理管道
196
+ 使用 Qwen3 嵌入模型替代 CLIP 文本编码器的 SDXL 推理管道
197
+ """
198
+
199
+ def __init__(
200
+ self,
201
+ qwen_model_path: str = "models/Qwen3-Embedding-0.6B",
202
+ unet_path: str = "models/extracted_components/waiNSFWIllustrious_v140_unet.safetensors",
203
+ unet_config_path: str = "models/extracted_components/waiNSFWIllustrious_v140_unet_config.json",
204
+ vae_path: str = "models/extracted_components/waiNSFWIllustrious_v140_vae.safetensors",
205
+ vae_config_path: str = "models/extracted_components/waiNSFWIllustrious_v140_vae_config.json",
206
+ device: str = "cuda",
207
+ dtype: torch.dtype = torch.bfloat16
208
+ ):
209
+ self.device = device
210
+ self.dtype = dtype
211
+ self.vae_scale_factor = 8 # SDXL default
212
+
213
+ print("🚀 初始化 Qwen-SDXL 推理管道...")
214
+
215
+ # Load Qwen3 embedding model
216
+ print("📝 加载 Qwen3 嵌入模型...")
217
+ self.qwen_model = load_qwen_model(qwen_model_path, device)
218
+
219
+ # Initialize adapter layer
220
+ print("🔧 初始化适配器层...")
221
+ self.adapter = QwenEmbeddingAdapter()
222
+ self.adapter.to(device, dtype)
223
+
224
+ # Load UNet
225
+ print("🏗️ 加载 UNet 模型...")
226
+ self.unet = load_unet_from_safetensors(unet_path, unet_config_path, device, dtype)
227
+
228
+ # Load VAE
229
+ print("🎨 加载 VAE 模型...")
230
+ self.vae = load_vae_from_safetensors(vae_path, vae_config_path, device, dtype)
231
+
232
+ # Initialize scheduler
233
+ print("⏰ 创建调度器...")
234
+ self.scheduler = create_scheduler()
235
+
236
+ # Check if all components loaded successfully
237
+ self.is_ready = all([
238
+ self.adapter is not None,
239
+ self.unet is not None,
240
+ self.vae is not None,
241
+ self.scheduler is not None
242
+ ])
243
+
244
+ if self.is_ready:
245
+ print("✅ 管道初始化完成!")
246
+ else:
247
+ print("❌ 管道初始化失败,某些组件加载失败")
248
+
249
+ def encode_prompts(
250
+ self,
251
+ prompts: List[str],
252
+ negative_prompts: Optional[List[str]] = None,
253
+ do_classifier_free_guidance: bool = True
254
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
255
+ """
256
+ Encode prompts using Qwen3 + adapter
257
+ 使用 Qwen3 + 适配器编码提示词
258
+ """
259
+ batch_size = len(prompts)
260
+
261
+ # Encode positive prompts for text embeddings (normal mode)
262
+ qwen_text_embeddings = encode_text_with_qwen(
263
+ self.qwen_model, prompts, self.device, use_query_mode=False
264
+ )
265
+
266
+ # Encode positive prompts for pooled embeddings (query mode)
267
+ qwen_pooled_embeddings = encode_text_with_qwen(
268
+ self.qwen_model, prompts, self.device, use_query_mode=True
269
+ )
270
+
271
+ # Add sequence dimension for text embeddings (CLIP uses 512 tokens for SDXL)
272
+ seq_len = 512
273
+ qwen_text_embeddings = qwen_text_embeddings.unsqueeze(1).expand(-1, seq_len, -1) # [B, 512, 1024]
274
+
275
+ # Project to SDXL dimensions
276
+ prompt_embeds = self.adapter.forward_text_embeddings(qwen_text_embeddings.to(self.dtype)) # [B, 77, 2048]
277
+
278
+ # Project pooled embeddings to 1280 dimensions
279
+ pooled_prompt_embeds = self.adapter.forward_pooled_embeddings(qwen_pooled_embeddings.to(self.dtype)) # [B, 1280]
280
+
281
+ # Handle negative prompts
282
+ if do_classifier_free_guidance:
283
+ if negative_prompts is None:
284
+ negative_prompts = [""] * batch_size
285
+
286
+ # Encode negative prompts for text embeddings (normal mode)
287
+ negative_qwen_text_embeddings = encode_text_with_qwen(
288
+ self.qwen_model, negative_prompts, self.device, use_query_mode=False
289
+ )
290
+
291
+ # Encode negative prompts for pooled embeddings (query mode)
292
+ negative_qwen_pooled_embeddings = encode_text_with_qwen(
293
+ self.qwen_model, negative_prompts, self.device, use_query_mode=True
294
+ )
295
+
296
+ negative_qwen_text_embeddings = negative_qwen_text_embeddings.unsqueeze(1).expand(-1, seq_len, -1)
297
+ negative_prompt_embeds = self.adapter.forward_text_embeddings(negative_qwen_text_embeddings.to(self.dtype))
298
+ negative_pooled_prompt_embeds = self.adapter.forward_pooled_embeddings(negative_qwen_pooled_embeddings.to(self.dtype))
299
+
300
+ # Concatenate for classifier-free guidance
301
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
302
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
303
+
304
+ return prompt_embeds, pooled_prompt_embeds
305
+
306
+ def prepare_latents(
307
+ self,
308
+ batch_size: int,
309
+ height: int,
310
+ width: int,
311
+ generator: Optional[torch.Generator] = None
312
+ ) -> torch.Tensor:
313
+ """
314
+ Prepare initial latents
315
+ 准备初始潜在变量
316
+ """
317
+ if self.unet is None:
318
+ # Mock latents for testing
319
+ shape = (batch_size, 4, height // self.vae_scale_factor, width // self.vae_scale_factor)
320
+ return torch.randn(shape, device=self.device, dtype=self.dtype)
321
+
322
+ shape = (
323
+ batch_size,
324
+ self.unet.config.in_channels,
325
+ height // self.vae_scale_factor,
326
+ width // self.vae_scale_factor,
327
+ )
328
+
329
+ try:
330
+ from diffusers.utils import randn_tensor
331
+ latents = randn_tensor(shape, generator=generator, device=self.device, dtype=self.dtype)
332
+ except ImportError:
333
+ latents = torch.randn(shape, device=self.device, dtype=self.dtype, generator=generator)
334
+
335
+ # Scale initial noise
336
+ if self.scheduler is not None:
337
+ latents = latents * self.scheduler.init_noise_sigma
338
+
339
+ return latents
340
+
341
+ def get_time_ids(
342
+ self,
343
+ height: int,
344
+ width: int,
345
+ original_size: Tuple[int, int],
346
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
347
+ target_size: Optional[Tuple[int, int]] = None
348
+ ) -> torch.Tensor:
349
+ """
350
+ Get SDXL time IDs for micro-conditioning
351
+ 获取 SDXL 时间 ID 用于微调节
352
+ """
353
+ if target_size is None:
354
+ target_size = (height, width)
355
+
356
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
357
+ add_time_ids = torch.tensor([add_time_ids], dtype=self.dtype, device=self.device)
358
+
359
+ return add_time_ids
360
+
361
+ def _get_add_time_ids(
362
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
363
+ ):
364
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
365
+
366
+ passed_add_embed_dim = (
367
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
368
+ )
369
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
370
+
371
+ if expected_add_embed_dim != passed_add_embed_dim:
372
+ raise ValueError(
373
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
374
+ )
375
+
376
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
377
+ return add_time_ids
378
+
379
+ @torch.no_grad()
380
+ def generate(
381
+ self,
382
+ prompt: Union[str, List[str]],
383
+ negative_prompt: Optional[Union[str, List[str]]] = None,
384
+ height: int = 1024,
385
+ width: int = 1024,
386
+ num_inference_steps: int = 50,
387
+ guidance_scale: float = 7.5,
388
+ generator: Optional[torch.Generator] = None,
389
+ return_type: str = "pil"
390
+ ) -> List[Image.Image]:
391
+ """
392
+ Generate images using Qwen-SDXL pipeline
393
+ 使用 Qwen-SDXL 管道生成图像
394
+ """
395
+ if not self.is_ready:
396
+ print("❌ 管道未准备就绪,无法生成图像")
397
+ return []
398
+
399
+ # Prepare prompts
400
+ if isinstance(prompt, str):
401
+ prompt = [prompt]
402
+ if isinstance(negative_prompt, str):
403
+ negative_prompt = [negative_prompt]
404
+
405
+ batch_size = len(prompt)
406
+ do_classifier_free_guidance = guidance_scale > 1.0
407
+
408
+ print(f"🎯 开始生成 {batch_size} 张图像...")
409
+ print(f"📏 尺寸: {width}x{height}")
410
+ print(f"🔄 推理步数: {num_inference_steps}")
411
+ print(f"🎚️ 引导强度: {guidance_scale}")
412
+
413
+ # 1. Encode prompts
414
+ print("📝 编码提示词...")
415
+ prompt_embeds, pooled_prompt_embeds = self.encode_prompts(
416
+ prompt, negative_prompt, do_classifier_free_guidance
417
+ )
418
+
419
+ # 2. Prepare timesteps
420
+ print("⏰ 准备时间步...")
421
+ if self.scheduler is not None:
422
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
423
+ timesteps = self.scheduler.timesteps
424
+ else:
425
+ timesteps = torch.linspace(1000, 0, num_inference_steps, device=self.device)
426
+
427
+ # 3. Prepare latents
428
+ print("🌀 准备潜在变量...")
429
+ latents = self.prepare_latents(batch_size, height, width, generator)
430
+
431
+ # 4. Prepare time IDs
432
+ original_size = (height, width)
433
+ target_size = (height, width)
434
+ add_time_ids = self.get_time_ids(height, width, original_size, target_size=target_size)
435
+
436
+ if do_classifier_free_guidance:
437
+ add_time_ids = add_time_ids.repeat(2, 1)
438
+ add_time_ids = add_time_ids.repeat(batch_size, 1)
439
+
440
+ # 5. Denoising loop
441
+ print("🔄 开始去噪过程...")
442
+ for i, t in enumerate(timesteps):
443
+ # Expand latents for classifier-free guidance
444
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
445
+
446
+ if self.scheduler is not None:
447
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
448
+
449
+ # Predict noise
450
+ if self.unet is not None:
451
+ added_cond_kwargs = {
452
+ "text_embeds": pooled_prompt_embeds,
453
+ "time_ids": add_time_ids
454
+ }
455
+
456
+ noise_pred = self.unet(
457
+ latent_model_input,
458
+ t,
459
+ encoder_hidden_states=prompt_embeds,
460
+ added_cond_kwargs=added_cond_kwargs,
461
+ return_dict=False,
462
+ )[0]
463
+
464
+ # Classifier-free guidance
465
+ if do_classifier_free_guidance:
466
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
467
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
468
+
469
+ # Scheduler step
470
+ if self.scheduler is not None:
471
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
472
+
473
+ if (i + 1) % 5 == 0:
474
+ print(f" 步骤 {i+1}/{len(timesteps)} 完成")
475
+
476
+ # 6. Decode latents
477
+ print("🎨 解码生成图像...")
478
+ if self.vae is not None:
479
+ latents = latents / self.vae.config.scaling_factor
480
+ images = self.vae.decode(latents, return_dict=False)[0]
481
+ else:
482
+ # Mock image generation for testing
483
+ images = torch.randn(batch_size, 3, height, width, device=self.device)
484
+
485
+ # 7. Convert to PIL images
486
+ images = (images / 2 + 0.5).clamp(0, 1)
487
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
488
+
489
+ if return_type == "pil":
490
+ images = [Image.fromarray((img * 255).astype(np.uint8)) for img in images]
491
+
492
+ print("✅ 图像生成完成!")
493
+ return images
494
+
495
+
496
+ def test_qwen_sdxl_inference():
497
+ """
498
+ Test the Qwen-SDXL inference pipeline
499
+ 测试 Qwen-SDXL 推理管道
500
+ """
501
+ print("🧪 测试 Qwen-SDXL 推理管道")
502
+ print("=" * 50)
503
+
504
+ # Initialize pipeline
505
+ pipeline = QwenSDXLInference(
506
+ device="cuda" if torch.cuda.is_available() else "cpu",
507
+ dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32
508
+ )
509
+
510
+ if not pipeline.is_ready:
511
+ print("⚠️ 管道未准备就绪,使用模拟模式进行测试")
512
+
513
+ # Test prompts
514
+ test_prompts = [
515
+ "A beautiful landscape with mountains and rivers, oil painting style",
516
+ "A cute cat wearing a red hat, anime style, high quality",
517
+ ]
518
+
519
+ negative_prompt = "low quality, blurry, distorted, watermark"
520
+
521
+ # Generate images
522
+ for i, prompt in enumerate(test_prompts):
523
+ print(f"\n🎨 生成测试图像 {i+1}")
524
+ print(f"📝 提示词: {prompt}")
525
+
526
+ # try:
527
+ images = pipeline.generate(
528
+ prompt=prompt,
529
+ negative_prompt=negative_prompt,
530
+ height=512, # 使用较小尺寸进行测试
531
+ width=512,
532
+ num_inference_steps=50, # 较少步数用于快速测试
533
+ guidance_scale=7.5,
534
+ )
535
+
536
+ if images:
537
+ output_path = f"test_qwen_sdxl_{i+1}.png"
538
+ images[0].save(output_path)
539
+ print(f"💾 已保存: {output_path}")
540
+ else:
541
+ print("❌ 图像生成失败")
542
+
543
+ # except Exception as e:
544
+
545
+ # print(f"❌ 生成过程中发生错误: {e}")
546
+
547
+ print("\n🎉 测试完成!")
548
+
549
+
550
+ if __name__ == "__main__":
551
+ test_qwen_sdxl_inference()
inference_updated.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Qwen-SDXL Inference Script (Updated to use arch components)
3
+ 基于 Qwen3 Embedding 的 SDXL 推理管道 - 使用架构组件
4
+ """
5
+
6
+ import torch
7
+ from typing import List, Optional, Union
8
+ from PIL import Image
9
+
10
+ # Import from arch components
11
+ from arch import QwenIllustriousInference
12
+
13
+
14
+ def test_qwen_sdxl_inference():
15
+ """
16
+ Test the Qwen-SDXL inference pipeline using arch components
17
+ 使用架构组件测试 Qwen-SDXL 推理管道
18
+ """
19
+ print("🧪 测试 Qwen-SDXL 推理管道 (使用架构组件)")
20
+ print("=" * 50)
21
+
22
+ # Initialize pipeline using arch components
23
+ pipeline = QwenIllustriousInference(
24
+ device="cuda" if torch.cuda.is_available() else "cpu",
25
+ dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32
26
+ )
27
+
28
+ if not pipeline.is_ready:
29
+ print("⚠️ 管道未准备就绪,使用模拟模式进行测试")
30
+
31
+ # Test prompts
32
+ test_prompts = [
33
+ "A beautiful landscape with mountains and rivers, oil painting style",
34
+ "A cute cat wearing a red hat, anime style, high quality",
35
+ ]
36
+
37
+ negative_prompt = "low quality, blurry, distorted, watermark"
38
+
39
+ # Generate images
40
+ for i, prompt in enumerate(test_prompts):
41
+ print(f"\n🎨 生成测试图像 {i+1}")
42
+ print(f"📝 提示词: {prompt}")
43
+
44
+ try:
45
+ images = pipeline.generate(
46
+ prompt=prompt,
47
+ negative_prompt=negative_prompt,
48
+ height=512, # 使用较小尺寸进行测试
49
+ width=512,
50
+ num_inference_steps=50, # 较少步数用于快速测试
51
+ guidance_scale=7.5,
52
+ )
53
+
54
+ if images:
55
+ output_path = f"test_qwen_sdxl_{i+1}.png"
56
+ images[0].save(output_path)
57
+ print(f"💾 已保存: {output_path}")
58
+ else:
59
+ print("❌ 图像生成失败")
60
+
61
+ except Exception as e:
62
+ print(f"❌ 生成过程中发生错误: {e}")
63
+
64
+ print("\n🎉 测试完成!")
65
+
66
+
67
+ def generate_single_image(
68
+ prompt: str,
69
+ negative_prompt: str = "low quality, blurry, distorted",
70
+ height: int = 1024,
71
+ width: int = 1024,
72
+ num_inference_steps: int = 50,
73
+ guidance_scale: float = 7.5,
74
+ output_path: str = "output.png",
75
+ adapter_path: Optional[str] = None,
76
+ lora_weights_path: Optional[str] = None,
77
+ lora_config_path: Optional[str] = None,
78
+ use_fused_unet: bool = False,
79
+ fused_unet_path: Optional[str] = None
80
+ ) -> bool:
81
+ """
82
+ Generate a single image using Qwen-SDXL pipeline
83
+ 使用 Qwen-SDXL 管道生成单张图像
84
+
85
+ Args:
86
+ prompt: Text prompt for image generation
87
+ negative_prompt: Negative prompt
88
+ height: Image height
89
+ width: Image width
90
+ num_inference_steps: Number of denoising steps
91
+ guidance_scale: Guidance scale for CFG
92
+ output_path: Path to save the generated image
93
+ adapter_path: Path to trained adapter weights (safetensors)
94
+ lora_weights_path: Path to LoRA weights (safetensors)
95
+ lora_config_path: Path to LoRA config directory
96
+ use_fused_unet: Whether to use fused UNet with merged LoRA
97
+ fused_unet_path: Path to fused UNet model directory
98
+
99
+ Returns:
100
+ True if generation successful, False otherwise
101
+ """
102
+ print(f"🎨 使用 Qwen-SDXL 生成图像")
103
+ print(f"📝 提示词: {prompt}")
104
+ print(f"📏 尺寸: {width}x{height}")
105
+
106
+ try:
107
+ # Initialize pipeline
108
+ pipeline = QwenIllustriousInference(
109
+ adapter_path=adapter_path,
110
+ lora_weights_path=lora_weights_path,
111
+ lora_config_path=lora_config_path,
112
+ use_fused_unet=use_fused_unet,
113
+ fused_unet_path=fused_unet_path,
114
+ device="cuda" if torch.cuda.is_available() else "cpu",
115
+ dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32
116
+ )
117
+
118
+ if not pipeline.is_ready:
119
+ print("❌ 管道未准备就绪")
120
+ return False
121
+
122
+ # Generate image
123
+ images = pipeline.generate(
124
+ prompt=prompt,
125
+ negative_prompt=negative_prompt,
126
+ height=height,
127
+ width=width,
128
+ num_inference_steps=num_inference_steps,
129
+ guidance_scale=guidance_scale,
130
+ )
131
+
132
+ if images:
133
+ images[0].save(output_path)
134
+ print(f"✅ 图像已保存到: {output_path}")
135
+ return True
136
+ else:
137
+ print("❌ 图像生成失败")
138
+ return False
139
+
140
+ except Exception as e:
141
+ print(f"❌ 生成过程中发生错误: {e}")
142
+ return False
143
+
144
+
145
+ if __name__ == "__main__":
146
+ import argparse
147
+
148
+ parser = argparse.ArgumentParser(description="Qwen-SDXL Inference")
149
+ parser.add_argument("--prompt", type=str, help="Text prompt for generation", default=None)
150
+ parser.add_argument("--negative_prompt", type=str, default="low quality, blurry", help="Negative prompt")
151
+ parser.add_argument("--height", type=int, default=1024, help="Image height")
152
+ parser.add_argument("--width", type=int, default=1024, help="Image width")
153
+ parser.add_argument("--steps", type=int, default=35, help="Number of inference steps")
154
+ parser.add_argument("--guidance_scale", type=float, default=3.5, help="Guidance scale")
155
+ parser.add_argument("--output", type=str, default="output.png", help="Output image path")
156
+ parser.add_argument("--adapter_path", type=str, help="Path to trained adapter weights (safetensors)")
157
+ parser.add_argument("--lora_weights_path", type=str, help="Path to LoRA weights (safetensors)")
158
+ parser.add_argument("--lora_config_path", type=str, help="Path to LoRA config directory")
159
+ parser.add_argument("--use_fused_unet", action="store_true", help="Use fused UNet with merged LoRA weights")
160
+ parser.add_argument("--fused_unet_path", type=str, help="Path to fused UNet model directory")
161
+ parser.add_argument("--test", action="store_true", help="Run test mode")
162
+
163
+ args = parser.parse_args()
164
+
165
+ if args.test or args.prompt is None:
166
+ # Run test mode
167
+ test_qwen_sdxl_inference()
168
+ else:
169
+ # Generate single image
170
+ generate_single_image(
171
+ prompt=args.prompt,
172
+ negative_prompt=args.negative_prompt,
173
+ height=args.height,
174
+ width=args.width,
175
+ num_inference_steps=args.steps,
176
+ guidance_scale=args.guidance_scale,
177
+ output_path=args.output,
178
+ adapter_path=args.adapter_path,
179
+ lora_weights_path=args.lora_weights_path,
180
+ lora_config_path=args.lora_config_path,
181
+ use_fused_unet=args.use_fused_unet,
182
+ fused_unet_path=args.fused_unet_path
183
+ )
main.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def main():
2
+ print("Hello from qwenillustrious!")
3
+
4
+
5
+ if __name__ == "__main__":
6
+ main()
natural_caption_generation.log ADDED
File without changes
pyproject.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "qwenillustrious"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "accelerate>=1.10.1",
9
+ "diffusers",
10
+ "huggingface-hub>=0.35.3",
11
+ "peft>=0.17.1",
12
+ "protobuf>=6.32.1",
13
+ "sentence-transformers",
14
+ "sentencepiece>=0.2.1",
15
+ "torch>=2.8.0",
16
+ "torchaudio>=2.8.0",
17
+ "torchvision>=0.23.0",
18
+ "tqdm>=4.67.1",
19
+ "transformers",
20
+ "wandb>=0.22.2",
21
+ ]
22
+
23
+ [tool.uv.sources]
24
+ diffusers = { path = "diffusers", editable = true }
25
+ sentence-transformers = { path = "sentence-transformers", editable = true }
26
+ transformers = { path = "transformers", editable = true }
test_usage.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import torch
2
+ # from diffusers import FluxKontextPipeline, FluxTransformer2DModel, TorchAoConfig
3
+ # from diffusers.utils import load_image
4
+
5
+ # dtype = torch.bfloat16
6
+ # quantization_config = TorchAoConfig("float8wo_e4m3")
7
+ # model_id = "models/FLUX.1-Kontext-dev"
8
+
9
+ # transformer = FluxTransformer2DModel.from_pretrained(
10
+ # model_id,
11
+ # subfolder="transformer",
12
+ # quantization_config=quantization_config,
13
+ # torch_dtype=dtype,
14
+ # )
15
+ # pipe = FluxKontextPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch.bfloat16)
16
+ # pipe.to("cuda")
17
+ # pipe.enable_model_cpu_offload()
18
+
19
+
20
+ # input_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png")
21
+
22
+ # image = pipe(
23
+ # image=input_image,
24
+ # prompt="Add a hat to the cat",
25
+ # guidance_scale=2.5
26
+ # ).images[0]
27
+
28
+ # image.save("output.png")
29
+
30
+
31
+ # Requires transformers>=4.51.0
32
+ # Requires sentence-transformers>=2.7.0
33
+
34
+ from sentence_transformers import SentenceTransformer
35
+
36
+ # Load the model
37
+ model = SentenceTransformer("models/Qwen3-Embedding-0.6B")
38
+
39
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving,
40
+ # together with setting `padding_side` to "left":
41
+ # model = SentenceTransformer(
42
+ # "Qwen/Qwen3-Embedding-0.6B",
43
+ # model_kwargs={"attn_implementation": "flash_attention_2", "device_map": "auto"},
44
+ # tokenizer_kwargs={"padding_side": "left"},
45
+ # )
46
+
47
+ # The queries and documents to embed
48
+ queries = [
49
+ "What is the capital of China?",
50
+ "Explain gravity",
51
+ ]
52
+ documents = [
53
+ "The capital of China is Beijing.",
54
+ "Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun.",
55
+ ]
56
+
57
+ # Encode the queries and documents. Note that queries benefit from using a prompt
58
+ # Here we use the prompt called "query" stored under `model.prompts`, but you can
59
+ # also pass your own prompt via the `prompt` argument
60
+ query_embeddings = model.encode(queries, prompt_name="query")
61
+ document_embeddings = model.encode(documents)
62
+
63
+ # Compute the (cosine) similarity between the query and document embeddings
64
+ similarity = model.similarity(query_embeddings, document_embeddings)
65
+ print(similarity)
66
+ # tensor([[0.7646, 0.1414],
67
+ # [0.1355, 0.6000]])
68
+
69
+ # import torch
70
+ # from diffusers import StableDiffusionXLPipeline
71
+
72
+ # model_id = "models/waiNSFWIllustrious_v140.safetensors"
73
+ # pipe = StableDiffusionXLPipeline.from_single_file(
74
+ # model_id,
75
+ # torch_dtype=torch.float16,
76
+ # use_safetensors=True,
77
+ # )
78
+ # pipe.to("cuda")
79
+ # image = pipe(prompt="A fantasy landscape, trending on artstation", negative_prompt="nsfw", num_inference_steps=35).images[0]
80
+ # image.save("output.png")
81
+
train.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from typing import List, Optional, Union, Dict, Any, Tuple
5
+ import json
6
+ from sentence_transformers import SentenceTransformer
7
+ from diffusers import AutoencoderKL, UNet2DConditionModel, DDPMScheduler
8
+ from diffusers.utils import randn_tensor
9
+ import safetensors.torch
10
+
11
+
12
+ class QwenEmbeddingAdapter(nn.Module):
13
+ """
14
+ Adapter layer to project Qwen3 embeddings (1024) to SDXL-compatible dimensions (2048)
15
+ """
16
+ def __init__(self, qwen_dim=1024, sdxl_dim=2048):
17
+ super().__init__()
18
+ self.projection = nn.Linear(qwen_dim, sdxl_dim)
19
+ self.layer_norm = nn.LayerNorm(sdxl_dim)
20
+
21
+ def forward(self, qwen_embeddings):
22
+ """
23
+ Args:
24
+ qwen_embeddings: tensor of shape [batch_size, seq_len, 1024]
25
+ Returns:
26
+ projected_embeddings: tensor of shape [batch_size, seq_len, 2048]
27
+ """
28
+ projected = self.projection(qwen_embeddings)
29
+ return self.layer_norm(projected)
30
+
31
+
32
+ class QwenSDXLPipeline:
33
+ """
34
+ SDXL Pipeline with Qwen3 embedding model replacing CLIP text encoders
35
+ """
36
+ def __init__(
37
+ self,
38
+ qwen_model_path: str = "models/Qwen3-Embedding-0.6B",
39
+ unet_path: str = "models/extracted_components/waiNSFWIllustrious_v140_unet.safetensors",
40
+ unet_config_path: str = "models/extracted_components/waiNSFWIllustrious_v140_unet_config.json",
41
+ vae_path: str = "models/extracted_components/waiNSFWIllustrious_v140_vae.safetensors",
42
+ vae_config_path: str = "models/extracted_components/waiNSFWIllustrious_v140_vae_config.json",
43
+ device: str = "cuda",
44
+ dtype: torch.dtype = torch.bfloat16
45
+ ):
46
+ self.device = device
47
+ self.dtype = dtype
48
+
49
+ # Load Qwen3 embedding model
50
+ print("Loading Qwen3 embedding model...")
51
+ self.qwen_model = SentenceTransformer(qwen_model_path)
52
+ self.qwen_model.to(device)
53
+
54
+ # Initialize adapter layer
55
+ self.adapter = QwenEmbeddingAdapter()
56
+ self.adapter.to(device, dtype)
57
+
58
+ # Load UNet
59
+ print("Loading UNet...")
60
+ with open(unet_config_path, 'r') as f:
61
+ unet_config = json.load(f)
62
+ self.unet = UNet2DConditionModel.from_config(unet_config)
63
+ unet_state_dict = safetensors.torch.load_file(unet_path)
64
+ self.unet.load_state_dict(unet_state_dict)
65
+ self.unet.to(device, dtype)
66
+
67
+ # Load VAE
68
+ print("Loading VAE...")
69
+ with open(vae_config_path, 'r') as f:
70
+ vae_config = json.load(f)
71
+ self.vae = AutoencoderKL.from_config(vae_config)
72
+ vae_state_dict = safetensors.torch.load_file(vae_path)
73
+ self.vae.load_state_dict(vae_state_dict)
74
+ self.vae.to(device, dtype)
75
+
76
+ # Initialize scheduler
77
+ self.scheduler = DDPMScheduler.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="scheduler")
78
+
79
+ # Set pipeline attributes
80
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
81
+ self.default_sample_size = self.unet.config.sample_size
82
+
83
+ print("Pipeline initialization complete!")
84
+
85
+ def encode_prompt_with_qwen(
86
+ self,
87
+ prompt: Union[str, List[str]],
88
+ device: torch.device,
89
+ num_images_per_prompt: int = 1,
90
+ do_classifier_free_guidance: bool = True,
91
+ negative_prompt: Optional[Union[str, List[str]]] = None,
92
+ prompt_embeds: Optional[torch.Tensor] = None,
93
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
94
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
95
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
96
+ ):
97
+ """
98
+ Encode prompts using Qwen3 embedding model instead of CLIP
99
+ """
100
+ if prompt_embeds is not None:
101
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
102
+
103
+ # Ensure prompt is a list
104
+ if isinstance(prompt, str):
105
+ prompt = [prompt]
106
+
107
+ batch_size = len(prompt)
108
+
109
+ # Encode prompts with Qwen3
110
+ with torch.no_grad():
111
+ # Use query prompt for better text understanding
112
+ qwen_embeddings = self.qwen_model.encode(
113
+ prompt,
114
+ prompt_name="query",
115
+ convert_to_tensor=True,
116
+ device=device
117
+ ) # Shape: [batch_size, 1024]
118
+
119
+ # Add sequence dimension and project to SDXL dimensions
120
+ # Expand to sequence length 77 (CLIP's default)
121
+ seq_len = 77
122
+ qwen_embeddings = qwen_embeddings.unsqueeze(1).expand(-1, seq_len, -1) # [batch_size, 77, 1024]
123
+
124
+ # Project to SDXL dimensions using adapter
125
+ prompt_embeds = self.adapter(qwen_embeddings.to(self.dtype)) # [batch_size, 77, 2048]
126
+
127
+ # For SDXL, we need pooled embeddings (global representation)
128
+ pooled_prompt_embeds = prompt_embeds.mean(dim=1) # [batch_size, 2048]
129
+
130
+ # Handle negative prompts
131
+ if do_classifier_free_guidance:
132
+ if negative_prompt is None:
133
+ negative_prompt = [""] * batch_size
134
+ elif isinstance(negative_prompt, str):
135
+ negative_prompt = [negative_prompt] * batch_size
136
+
137
+ # Encode negative prompts
138
+ with torch.no_grad():
139
+ negative_qwen_embeddings = self.qwen_model.encode(
140
+ negative_prompt,
141
+ prompt_name="query",
142
+ convert_to_tensor=True,
143
+ device=device
144
+ )
145
+
146
+ negative_qwen_embeddings = negative_qwen_embeddings.unsqueeze(1).expand(-1, seq_len, -1)
147
+ negative_prompt_embeds = self.adapter(negative_qwen_embeddings.to(self.dtype))
148
+ negative_pooled_prompt_embeds = negative_prompt_embeds.mean(dim=1)
149
+ else:
150
+ negative_prompt_embeds = None
151
+ negative_pooled_prompt_embeds = None
152
+
153
+ # Duplicate embeddings for each generation per prompt
154
+ if num_images_per_prompt > 1:
155
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
156
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
157
+
158
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt)
159
+ pooled_prompt_embeds = pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
160
+
161
+ if negative_prompt_embeds is not None:
162
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
163
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
164
+
165
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt)
166
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
167
+
168
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
169
+
170
+ def prepare_latents(
171
+ self,
172
+ batch_size: int,
173
+ num_channels_latents: int,
174
+ height: int,
175
+ width: int,
176
+ dtype: torch.dtype,
177
+ device: torch.device,
178
+ generator: Optional[torch.Generator] = None,
179
+ latents: Optional[torch.Tensor] = None
180
+ ):
181
+ """Prepare latent variables for diffusion process"""
182
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
183
+
184
+ if isinstance(generator, list) and len(generator) != batch_size:
185
+ raise ValueError(
186
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
187
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
188
+ )
189
+
190
+ if latents is None:
191
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
192
+ else:
193
+ latents = latents.to(device)
194
+
195
+ # scale the initial noise by the standard deviation required by the scheduler
196
+ latents = latents * self.scheduler.init_noise_sigma
197
+ return latents
198
+
199
+ def _get_add_time_ids(
200
+ self,
201
+ original_size: Tuple[int, int],
202
+ crops_coords_top_left: Tuple[int, int],
203
+ target_size: Tuple[int, int],
204
+ dtype: torch.dtype,
205
+ text_encoder_projection_dim: int = 2048
206
+ ):
207
+ """Get additional time IDs for SDXL micro-conditioning"""
208
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
209
+
210
+ passed_add_embed_dim = (
211
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
212
+ )
213
+ expected_add_embed_dim = self.unet.config.addition_embed_type_num_heads
214
+
215
+ if expected_add_embed_dim != passed_add_embed_dim:
216
+ raise ValueError(
217
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, "
218
+ f"but a vector of {passed_add_embed_dim} was created. The model has an incorrect config."
219
+ )
220
+
221
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
222
+ return add_time_ids
223
+
224
+ @torch.no_grad()
225
+ def __call__(
226
+ self,
227
+ prompt: Union[str, List[str]] = None,
228
+ height: Optional[int] = None,
229
+ width: Optional[int] = None,
230
+ num_inference_steps: int = 50,
231
+ guidance_scale: float = 7.5,
232
+ negative_prompt: Optional[Union[str, List[str]]] = None,
233
+ num_images_per_prompt: Optional[int] = 1,
234
+ eta: float = 0.0,
235
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
236
+ latents: Optional[torch.Tensor] = None,
237
+ prompt_embeds: Optional[torch.Tensor] = None,
238
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
239
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
240
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
241
+ output_type: Optional[str] = "pil",
242
+ return_dict: bool = True,
243
+ original_size: Optional[Tuple[int, int]] = None,
244
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
245
+ target_size: Optional[Tuple[int, int]] = None,
246
+ ):
247
+ """
248
+ Modified SDXL inference pipeline using Qwen3 embeddings
249
+ """
250
+ # 0. Default height and width to unet
251
+ height = height or self.default_sample_size * self.vae_scale_factor
252
+ width = width or self.default_sample_size * self.vae_scale_factor
253
+
254
+ original_size = original_size or (height, width)
255
+ target_size = target_size or (height, width)
256
+
257
+ # 1. Define call parameters
258
+ if prompt is not None and isinstance(prompt, str):
259
+ batch_size = 1
260
+ elif prompt is not None and isinstance(prompt, list):
261
+ batch_size = len(prompt)
262
+ else:
263
+ batch_size = prompt_embeds.shape[0]
264
+
265
+ device = self.device
266
+ do_classifier_free_guidance = guidance_scale > 1.0
267
+
268
+ # 2. Encode input prompt with Qwen3
269
+ (
270
+ prompt_embeds,
271
+ negative_prompt_embeds,
272
+ pooled_prompt_embeds,
273
+ negative_pooled_prompt_embeds,
274
+ ) = self.encode_prompt_with_qwen(
275
+ prompt=prompt,
276
+ device=device,
277
+ num_images_per_prompt=num_images_per_prompt,
278
+ do_classifier_free_guidance=do_classifier_free_guidance,
279
+ negative_prompt=negative_prompt,
280
+ prompt_embeds=prompt_embeds,
281
+ negative_prompt_embeds=negative_prompt_embeds,
282
+ pooled_prompt_embeds=pooled_prompt_embeds,
283
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
284
+ )
285
+
286
+ # 3. Prepare timesteps
287
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
288
+ timesteps = self.scheduler.timesteps
289
+
290
+ # 4. Prepare latent variables
291
+ num_channels_latents = self.unet.config.in_channels
292
+ latents = self.prepare_latents(
293
+ batch_size * num_images_per_prompt,
294
+ num_channels_latents,
295
+ height,
296
+ width,
297
+ prompt_embeds.dtype,
298
+ device,
299
+ generator,
300
+ latents,
301
+ )
302
+
303
+ # 5. Prepare added time ids & embeddings (SDXL micro-conditioning)
304
+ add_text_embeds = pooled_prompt_embeds
305
+ text_encoder_projection_dim = pooled_prompt_embeds.shape[-1] # 2048
306
+
307
+ add_time_ids = self._get_add_time_ids(
308
+ original_size,
309
+ crops_coords_top_left,
310
+ target_size,
311
+ dtype=prompt_embeds.dtype,
312
+ text_encoder_projection_dim=text_encoder_projection_dim,
313
+ )
314
+
315
+ if do_classifier_free_guidance:
316
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
317
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
318
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
319
+
320
+ prompt_embeds = prompt_embeds.to(device)
321
+ add_text_embeds = add_text_embeds.to(device)
322
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
323
+
324
+ # 6. Denoising loop
325
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
326
+ with torch.cuda.amp.autocast(enabled=(self.dtype == torch.float16)):
327
+ for i, t in enumerate(timesteps):
328
+ # expand the latents if we are doing classifier free guidance
329
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
330
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
331
+
332
+ # predict the noise residual
333
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
334
+ noise_pred = self.unet(
335
+ latent_model_input,
336
+ t,
337
+ encoder_hidden_states=prompt_embeds,
338
+ added_cond_kwargs=added_cond_kwargs,
339
+ return_dict=False,
340
+ )[0]
341
+
342
+ # perform guidance
343
+ if do_classifier_free_guidance:
344
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
345
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
346
+
347
+ # compute the previous noisy sample x_t -> x_t-1
348
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
349
+
350
+ # 7. Decode latents to images
351
+ if output_type != "latent":
352
+ # make sure the VAE is in float32 mode, as it overflows in float16
353
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
354
+
355
+ if needs_upcasting:
356
+ self.vae.to(dtype=torch.float32)
357
+ latents = latents.to(torch.float32)
358
+
359
+ latents = latents / self.vae.config.scaling_factor
360
+ image = self.vae.decode(latents, return_dict=False)[0]
361
+
362
+ if needs_upcasting:
363
+ self.vae.to(dtype=torch.float16)
364
+ else:
365
+ image = latents
366
+
367
+ # 8. Post-process images
368
+ if output_type == "pil":
369
+ image = (image / 2 + 0.5).clamp(0, 1)
370
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
371
+ # Convert to PIL
372
+ from PIL import Image
373
+ image = [Image.fromarray((img * 255).astype("uint8")) for img in image]
374
+
375
+ if not return_dict:
376
+ return (image,)
377
+
378
+ return {"images": image}
379
+
380
+
381
+ def test_inference():
382
+ """Test the Qwen-SDXL pipeline"""
383
+ print("Initializing Qwen-SDXL Pipeline...")
384
+
385
+ pipeline = QwenSDXLPipeline(
386
+ device="cuda" if torch.cuda.is_available() else "cpu",
387
+ dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32
388
+ )
389
+
390
+ # Test prompts
391
+ prompts = [
392
+ "A beautiful landscape with mountains and rivers, oil painting style",
393
+ "A cute cat wearing a hat, anime style",
394
+ ]
395
+
396
+ print("Generating images...")
397
+ for i, prompt in enumerate(prompts):
398
+ print(f"Generating image {i+1}: {prompt}")
399
+
400
+ result = pipeline(
401
+ prompt=prompt,
402
+ negative_prompt="low quality, blurry, distorted",
403
+ num_inference_steps=20,
404
+ guidance_scale=7.5,
405
+ height=1024,
406
+ width=1024,
407
+ )
408
+
409
+ # Save image
410
+ if "images" in result:
411
+ image = result["images"][0]
412
+ image.save(f"output_qwen_sdxl_{i+1}.png")
413
+ print(f"Saved: output_qwen_sdxl_{i+1}.png")
414
+
415
+
416
+ if __name__ == "__main__":
417
+ test_inference()
train/MODEL_FORMAT.md ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # QwenIllustrious Model Save/Load Format
2
+
3
+ 本文档说明QwenIllustrious模型的保存和加载格式。
4
+
5
+ ## 模型保存格式
6
+
7
+ 训练完成后,模型将以以下结构保存:
8
+
9
+ ```
10
+ qwen_illustrious_output/
11
+ ├── adapter/
12
+ │ └── adapter.safetensors # Adapter权重 (safetensor格式)
13
+ ├── lora_weights/
14
+ │ ├── lora_weights.safetensors # LoRA权重 (safetensor格式)
15
+ │ └── adapter_config.json # LoRA配置文件
16
+ ├── unet_fused/
17
+ │ ├── diffusion_pytorch_model.safetensors # 融合LoRA的完整UNet
18
+ │ └── config.json # UNet配置文件
19
+ └── training_config.json # 训练配置文件
20
+ ```
21
+
22
+ ## 保存的组件说明
23
+
24
+ ### 1. Adapter权重 (`adapter/adapter.safetensors`)
25
+ - **内容**: QwenEmbeddingAdapter的权重
26
+ - **格式**: SafeTensor
27
+ - **用途**: 将Qwen嵌入映射到SDXL嵌入空间
28
+ - **大小**: 约几MB
29
+
30
+ ### 2. LoRA权重 (`lora_weights/lora_weights.safetensors`)
31
+ - **内容**: 仅LoRA权重,不包含基础UNet权重
32
+ - **格式**: SafeTensor
33
+ - **用途**: 可以应用到任何兼容的SDXL UNet上
34
+ - **大小**: 取决于LoRA rank,通常几十MB
35
+ - **优势**:
36
+ - 文件小
37
+ - 可以与其他LoRA组合
38
+ - 便于分享和存储
39
+
40
+ ### 3. 融合UNet (`unet_fused/`)
41
+ - **内容**: LoRA权重已合并到UNet中的完整模型
42
+ - **格式**: SafeTensor
43
+ - **用途**: 可以直接作为标准UNet使用
44
+ - **大小**: 完整UNet大小 (~5GB)
45
+ - **优势**:
46
+ - 推理时无需额外的LoRA加载
47
+ - 推理速度可能稍快
48
+ - 兼容更多推理工具
49
+
50
+ ## 加载方式
51
+
52
+ ### 方式1: 使用LoRA权重
53
+
54
+ ```python
55
+ from arch import QwenIllustriousInference
56
+
57
+ pipeline = QwenIllustriousInference(
58
+ # 基础模型
59
+ qwen_model_path="models/Qwen3-Embedding-0.6B",
60
+ unet_path="models/sdxl_base", # 原始SDXL模型
61
+ vae_path="models/sdxl_base",
62
+
63
+ # 训练后的组件
64
+ adapter_path="qwen_illustrious_output/adapter/adapter.safetensors",
65
+ lora_weights_path="qwen_illustrious_output/lora_weights/lora_weights.safetensors",
66
+ lora_config_path="qwen_illustrious_output/lora_weights",
67
+
68
+ device="cuda"
69
+ )
70
+ ```
71
+
72
+ ### 方式2: 使用融合UNet
73
+
74
+ ```python
75
+ from arch import QwenIllustriousInference
76
+
77
+ pipeline = QwenIllustriousInference(
78
+ # 基础模型
79
+ qwen_model_path="models/Qwen3-Embedding-0.6B",
80
+ vae_path="models/sdxl_base",
81
+
82
+ # 训练后的组件
83
+ adapter_path="qwen_illustrious_output/adapter/adapter.safetensors",
84
+ use_fused_unet=True,
85
+ fused_unet_path="qwen_illustrious_output/unet_fused",
86
+
87
+ device="cuda"
88
+ )
89
+ ```
90
+
91
+ ## 命令行推理
92
+
93
+ ### 使用LoRA权重
94
+ ```bash
95
+ python inference_updated.py \
96
+ --prompt "A beautiful anime girl in a garden" \
97
+ --adapter_path qwen_illustrious_output/adapter/adapter.safetensors \
98
+ --lora_weights_path qwen_illustrious_output/lora_weights/lora_weights.safetensors \
99
+ --lora_config_path qwen_illustrious_output/lora_weights \
100
+ --output my_image.png
101
+ ```
102
+
103
+ ### 使用融合UNet
104
+ ```bash
105
+ python inference_updated.py \
106
+ --prompt "A beautiful anime girl in a garden" \
107
+ --adapter_path qwen_illustrious_output/adapter/adapter.safetensors \
108
+ --use_fused_unet \
109
+ --fused_unet_path qwen_illustrious_output/unet_fused \
110
+ --output my_image.png
111
+ ```
112
+
113
+ ## SafeTensor格式优势
114
+
115
+ 1. **安全性**: 不能包含恶意代码
116
+ 2. **速度**: 加载速度比pickle快
117
+ 3. **跨平台**: 在不同平台间兼容性好
118
+ 4. **元数据**: 支持存储模型元信息
119
+ 5. **内存效率**: 支持惰性加载
120
+
121
+ ## 兼容性说明
122
+
123
+ - **Adapter**: 总是需要加载,因为它是我们模型的核心组件
124
+ - **LoRA vs Fused**: 两种方式功能等价,根据需求选择:
125
+ - LoRA权重:适合实验、组合、分享
126
+ - 融合模型:适合生产、部署、简化推理
127
+
128
+ ## 文件大小对比
129
+
130
+ | 组件 | 大小 (估计) | 说明 |
131
+ |------|------------|------|
132
+ | adapter.safetensors | ~10MB | Adapter权重 |
133
+ | lora_weights.safetensors | ~50MB | LoRA权重 (rank=64) |
134
+ | unet_fused/ | ~5GB | 完整UNet模型 |
135
+
136
+ 总存储需求约5GB,但实际使用时只需要选择一种UNet格式。
train/precompute_embeddings.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Precompute Embeddings Script
4
+ 预计算嵌入脚本 - 提前计算Qwen嵌入和VAE潜在空间编码以加速训练
5
+ """
6
+
7
+ import argparse
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+ import torch
12
+ from tqdm import tqdm
13
+ import traceback
14
+
15
+ # 添加项目路径
16
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
17
+ from arch import QwenTextEncoder
18
+ from arch.data_loader import QwenIllustriousDataset
19
+ from diffusers import AutoencoderKL
20
+
21
+ from arch.model_loader import load_qwen_model, load_unet_from_safetensors, load_vae_from_safetensors, create_scheduler
22
+
23
+
24
+ def parse_args():
25
+ parser = argparse.ArgumentParser(description="Precompute embeddings for QwenIllustrious training")
26
+
27
+ parser.add_argument(
28
+ "--qwen_model_path",
29
+ type=str,
30
+ default="models/Qwen3-Embedding-0.6B",
31
+ help="Path to Qwen text encoder model"
32
+ )
33
+ parser.add_argument(
34
+ "--sdxl_model_path",
35
+ type=str,
36
+ help="Path to SDXL model (for VAE)"
37
+ )
38
+ parser.add_argument(
39
+ "--vae_model_path",
40
+ type=str,
41
+ default="models/extracted_components/waiNSFWIllustrious_v140_vae.safetensors",
42
+ help="Path to VAE model (if different from SDXL)"
43
+ )
44
+ parser.add_argument(
45
+ "--vae_config_path",
46
+ type=str,
47
+ default="models/extracted_components/waiNSFWIllustrious_v140_vae_config.json",
48
+ help="Path to VAE config file"
49
+ )
50
+ parser.add_argument(
51
+ "--dataset_path",
52
+ type=str,
53
+ default="illustrious_generated",
54
+ help="Path to illustrious_generated dataset"
55
+ )
56
+ parser.add_argument(
57
+ "--cache_dir",
58
+ type=str,
59
+ default="illustrious_generated/cache",
60
+ help="Directory to store precomputed embeddings"
61
+ )
62
+ parser.add_argument(
63
+ "--batch_size",
64
+ type=int,
65
+ default=8,
66
+ help="Batch size for processing"
67
+ )
68
+ parser.add_argument(
69
+ "--device",
70
+ type=str,
71
+ default="cuda",
72
+ help="Device to use for computation"
73
+ )
74
+ parser.add_argument(
75
+ "--mixed_precision",
76
+ type=str,
77
+ default="fp16",
78
+ choices=["no", "fp16", "bf16"],
79
+ help="Mixed precision mode"
80
+ )
81
+
82
+ return parser.parse_args()
83
+
84
+
85
+ def main():
86
+ args = parse_args()
87
+
88
+ print("Setting up models...")
89
+
90
+ # Setup device
91
+ device = torch.device(args.device if torch.cuda.is_available() else "cpu")
92
+ print(f"Using device: {device}")
93
+
94
+ # Load models
95
+ print("Loading Qwen text encoder...")
96
+ qwen_text_encoder = QwenTextEncoder(
97
+ model_path=args.qwen_model_path,
98
+ device=device,
99
+ freeze_encoder=True
100
+ # torch_dtype=torch.float16 if args.mixed_precision == "fp16" else torch.float32
101
+ )
102
+ qwen_text_encoder.to(device)
103
+
104
+ print("Loading VAE...")
105
+ vae = load_vae_from_safetensors(args.vae_model_path, args.vae_config_path, device=device, dtype=torch.bfloat16)
106
+ vae.to(device)
107
+
108
+ # Note: We don't load adapter here as it's a trainable component
109
+
110
+ # Create cache directory
111
+ cache_dir = Path(args.cache_dir)
112
+ cache_dir.mkdir(parents=True, exist_ok=True)
113
+
114
+ # Setup dataset (without precomputation initially)
115
+ print("Setting up dataset...")
116
+ dataset = QwenIllustriousDataset(
117
+ dataset_path=args.dataset_path,
118
+ qwen_text_encoder=qwen_text_encoder,
119
+ vae=vae,
120
+ cache_dir=args.cache_dir,
121
+ precompute_embeddings=False # We'll do this manually
122
+ )
123
+
124
+ print(f"Found {len(dataset)} items to process")
125
+
126
+ # Process in batches
127
+ print("Starting precomputation...")
128
+
129
+ with torch.no_grad():
130
+ for i in tqdm(range(0, len(dataset), args.batch_size), desc="Processing batches"):
131
+ batch_end = min(i + args.batch_size, len(dataset))
132
+
133
+ # Process items in current batch
134
+ batch_prompts = []
135
+ batch_metadata = []
136
+ batch_images = []
137
+
138
+ for j in range(i, batch_end):
139
+ try:
140
+ item = dataset[j] # This will load image and get prompt
141
+ batch_prompts.append(item['prompts'])
142
+ batch_metadata.append(item['metadata'])
143
+ batch_images.append(item['images'].unsqueeze(0))
144
+ except Exception as e:
145
+ print(f"Error processing item {j}: {e}")
146
+ traceback.print_exc() # 打印完整的调用栈
147
+ raise # 重新抛出异常,中断程序执行
148
+
149
+ if not batch_prompts:
150
+ continue
151
+
152
+ # Batch process text embeddings
153
+ try:
154
+ print(f"Processing text embeddings for batch {i//args.batch_size + 1}...")
155
+
156
+ # Encode texts with Qwen (save raw embeddings for training)
157
+ qwen_embeddings = qwen_text_encoder.encode_prompts(batch_prompts, do_classifier_free_guidance=False)
158
+
159
+ # Process each item in the batch
160
+ for k, (prompt, metadata, image_tensor) in enumerate(zip(batch_prompts, batch_metadata, batch_images)):
161
+ filename_hash = metadata['filename_hash']
162
+
163
+ # Save raw Qwen embeddings (before adapter)
164
+ text_cache_path = dataset._get_text_cache_path(filename_hash)
165
+ text_data = {
166
+ 'text_embeddings': qwen_embeddings[0][k:k+1].cpu(),
167
+ 'pooled_embeddings': qwen_embeddings[1][k:k+1].cpu()
168
+ }
169
+ torch.save(text_data, text_cache_path)
170
+
171
+ # Process VAE latents
172
+ try:
173
+ image_tensor = image_tensor.to(device)
174
+ latents = vae.encode(image_tensor.to(vae.dtype)).latent_dist.sample()
175
+ latents = latents * vae.config.scaling_factor
176
+
177
+ # Save VAE latents
178
+ vae_cache_path = dataset._get_vae_cache_path(filename_hash)
179
+ torch.save(latents.cpu(), vae_cache_path)
180
+
181
+ except Exception as e:
182
+ print(f"Error processing VAE latents for {filename_hash}: {e}")
183
+ traceback.print_exc()
184
+ raise
185
+
186
+ except Exception as e:
187
+ print(f"Error processing batch {i//args.batch_size + 1}: {e}")
188
+ traceback.print_exc()
189
+ raise # 中断程序执行
190
+
191
+ print("Precomputation completed!")
192
+ print(f"Cached embeddings saved to: {cache_dir}")
193
+
194
+ # Verify cache
195
+ text_cache_dir = cache_dir / "text_embeddings"
196
+ vae_cache_dir = cache_dir / "vae_latents"
197
+
198
+ text_files = list(text_cache_dir.glob("*.pt"))
199
+ vae_files = list(vae_cache_dir.glob("*.pt"))
200
+
201
+ print(f"Text embeddings cached: {len(text_files)}")
202
+ print(f"VAE latents cached: {len(vae_files)}")
203
+ print(f"Total dataset size: {len(dataset)}")
204
+
205
+ if len(text_files) != len(dataset) or len(vae_files) != len(dataset):
206
+ print("Warning: Not all items were successfully cached!")
207
+ else:
208
+ print("All items successfully cached!")
209
+
210
+
211
+ if __name__ == "__main__":
212
+ main()
train/start_training.sh ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ """
3
+ Quick Start Training Script for QwenIllustrious
4
+ 快速启动训练脚本
5
+ """
6
+
7
+ # 设置基本路径
8
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
9
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
10
+
11
+ PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
12
+
13
+ # 默认参数
14
+ QWEN_MODEL_PATH="${QWEN_MODEL_PATH:-models/Qwen3-Embedding-0.6B}"
15
+ SDXL_MODEL_PATH="${SDXL_MODEL_PATH:-models/waiNSFWIllustrious_v140.safetensors}"
16
+ DATASET_PATH="${DATASET_PATH:-${PROJECT_ROOT}/illustrious_generated}"
17
+ OUTPUT_DIR="${OUTPUT_DIR:-${PROJECT_ROOT}/output/qwen_illustrious}"
18
+ CACHE_DIR="${CACHE_DIR:-${PROJECT_ROOT}/cache}"
19
+
20
+ # 训练参数
21
+ BATCH_SIZE="${BATCH_SIZE:-4}"
22
+ LEARNING_RATE="${LEARNING_RATE:-1e-4}"
23
+ NUM_EPOCHS="${NUM_EPOCHS:-10}"
24
+ LORA_RANK="${LORA_RANK:-64}"
25
+
26
+ # 混合精度和梯度设置
27
+ MIXED_PRECISION="${MIXED_PRECISION:-fp16}"
28
+ GRADIENT_ACCUMULATION_STEPS="${GRADIENT_ACCUMULATION_STEPS:-1}"
29
+
30
+ # 预计算嵌入选项
31
+ PRECOMPUTE_EMBEDDINGS="${PRECOMPUTE_EMBEDDINGS:-true}"
32
+
33
+ echo "=== QwenIllustrious Training Setup ==="
34
+ echo "Qwen Model: $QWEN_MODEL_PATH"
35
+ echo "SDXL Model: $SDXL_MODEL_PATH"
36
+ echo "Dataset: $DATASET_PATH"
37
+ echo "Output: $OUTPUT_DIR"
38
+ echo "Cache: $CACHE_DIR"
39
+ echo "Batch Size: $BATCH_SIZE"
40
+ echo "Learning Rate: $LEARNING_RATE"
41
+ echo "Epochs: $NUM_EPOCHS"
42
+ echo "LoRA Rank: $LORA_RANK"
43
+ echo "Mixed Precision: $MIXED_PRECISION"
44
+ echo "Precompute Embeddings: $PRECOMPUTE_EMBEDDINGS"
45
+ echo "=================================="
46
+
47
+ # 检查模型文件是否存在
48
+ if [ ! -e "$QWEN_MODEL_PATH" ]; then
49
+ echo "Error: Qwen model not found at $QWEN_MODEL_PATH"
50
+ echo "Please set QWEN_MODEL_PATH environment variable or place model in models/ directory"
51
+ exit 1
52
+ fi
53
+
54
+ if [ ! -e "$SDXL_MODEL_PATH" ]; then
55
+ echo "Error: SDXL model not found at $SDXL_MODEL_PATH"
56
+ echo "Please set SDXL_MODEL_PATH environment variable or place model in models/ directory"
57
+ exit 1
58
+ fi
59
+
60
+ if [ ! -d "$DATASET_PATH" ]; then
61
+ echo "Error: Dataset not found at $DATASET_PATH"
62
+ echo "Please set DATASET_PATH environment variable"
63
+ exit 1
64
+ fi
65
+
66
+ # 创建必要的目录
67
+ mkdir -p "$OUTPUT_DIR"
68
+ mkdir -p "$CACHE_DIR"
69
+
70
+ # 步骤1: 预计算嵌入 (如果启用)
71
+ if [ "$PRECOMPUTE_EMBEDDINGS" = "true" ]; then
72
+ echo ""
73
+ echo "=== Step 1: Precomputing Embeddings ==="
74
+ python "$SCRIPT_DIR/precompute_embeddings.py" \
75
+ --qwen_model_path "$QWEN_MODEL_PATH" \
76
+ --sdxl_model_path "$SDXL_MODEL_PATH" \
77
+ --dataset_path "$DATASET_PATH" \
78
+ --cache_dir "$CACHE_DIR" \
79
+ --batch_size 8 \
80
+ --mixed_precision "$MIXED_PRECISION"
81
+
82
+ if [ $? -ne 0 ]; then
83
+ echo "Error: Precomputation failed!"
84
+ exit 1
85
+ fi
86
+
87
+ echo "Precomputation completed successfully!"
88
+ fi
89
+
90
+ # 步骤2: 开始训练
91
+ echo ""
92
+ echo "=== Step 2: Starting Training ==="
93
+
94
+ # 构建训练命令
95
+ TRAIN_CMD="python $SCRIPT_DIR/train_qwen_illustrious.py"
96
+ TRAIN_CMD="$TRAIN_CMD --qwen_model_path '$QWEN_MODEL_PATH'"
97
+ TRAIN_CMD="$TRAIN_CMD --sdxl_model_path '$SDXL_MODEL_PATH'"
98
+ TRAIN_CMD="$TRAIN_CMD --dataset_path '$DATASET_PATH'"
99
+ TRAIN_CMD="$TRAIN_CMD --output_dir '$OUTPUT_DIR'"
100
+ TRAIN_CMD="$TRAIN_CMD --train_batch_size $BATCH_SIZE"
101
+ TRAIN_CMD="$TRAIN_CMD --learning_rate $LEARNING_RATE"
102
+ TRAIN_CMD="$TRAIN_CMD --num_train_epochs $NUM_EPOCHS"
103
+ TRAIN_CMD="$TRAIN_CMD --lora_rank $LORA_RANK"
104
+ TRAIN_CMD="$TRAIN_CMD --mixed_precision $MIXED_PRECISION"
105
+ TRAIN_CMD="$TRAIN_CMD --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS"
106
+
107
+ if [ "$PRECOMPUTE_EMBEDDINGS" = "true" ]; then
108
+ TRAIN_CMD="$TRAIN_CMD --precompute_embeddings"
109
+ TRAIN_CMD="$TRAIN_CMD --cache_dir '$CACHE_DIR'"
110
+ fi
111
+
112
+ # 添加其他有用的参数
113
+ TRAIN_CMD="$TRAIN_CMD --gradient_checkpointing"
114
+ TRAIN_CMD="$TRAIN_CMD --checkpointing_steps 500"
115
+ TRAIN_CMD="$TRAIN_CMD --validation_epochs 2"
116
+ TRAIN_CMD="$TRAIN_CMD --report_to tensorboard"
117
+
118
+ echo "Running command:"
119
+ echo "$TRAIN_CMD"
120
+ echo ""
121
+
122
+ # 执行训练
123
+ eval $TRAIN_CMD
124
+
125
+ if [ $? -eq 0 ]; then
126
+ echo ""
127
+ echo "=== Training Completed Successfully! ==="
128
+ echo "Model saved to: $OUTPUT_DIR"
129
+ echo "Adapter weights: $OUTPUT_DIR/adapter/"
130
+ echo "LoRA weights: $OUTPUT_DIR/lora/"
131
+ echo "Logs: $OUTPUT_DIR/logs/"
132
+ else
133
+ echo ""
134
+ echo "=== Training Failed! ==="
135
+ exit 1
136
+ fi
train/train_qwen_illustrious.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ 训练 QwenIllustrious 模型 - 结合 Qwen 文本编码器和 SDXL UNet
4
+ """
5
+
6
+ import argparse
7
+ import logging
8
+ import math
9
+ import os
10
+ import random
11
+ import sys
12
+ from pathlib import Path
13
+ from typing import Dict, List, Tuple
14
+
15
+ import torch
16
+ import torch.nn.functional as F
17
+ import torch.utils.checkpoint
18
+ import transformers
19
+ import numpy as np
20
+ import wandb
21
+ from accelerate import Accelerator
22
+ from accelerate.logging import get_logger
23
+ from accelerate.utils import ProjectConfiguration, set_seed
24
+ from tqdm.auto import tqdm
25
+ from transformers import AutoTokenizer
26
+ from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
27
+ from diffusers.optimization import get_scheduler
28
+ from diffusers.training_utils import compute_snr
29
+ from diffusers.utils import check_min_version
30
+ from peft import LoraConfig, get_peft_model, TaskType
31
+
32
+ # 导入项目组件
33
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
34
+ from arch import QwenTextEncoder, QwenEmbeddingAdapter
35
+ from arch.data_loader import QwenIllustriousDataset, collate_fn
36
+
37
+ from arch.model_loader import load_qwen_model, load_unet_from_safetensors, load_vae_from_safetensors, create_scheduler
38
+
39
+ # 检查最低版本
40
+ check_min_version("0.35.0.dev0")
41
+
42
+ logger = get_logger(__name__)
43
+
44
+
45
+ def parse_args():
46
+ parser = argparse.ArgumentParser(description="Train QwenIllustrious model")
47
+
48
+ # Model arguments
49
+ parser.add_argument(
50
+ "--qwen_model_path",
51
+ type=str,
52
+ default="models/Qwen3-Embedding-0.6B",
53
+ help="Path to Qwen text encoder model"
54
+ )
55
+ parser.add_argument(
56
+ "--unet_model_path",
57
+ type=str,
58
+ default="models/extracted_components/waiNSFWIllustrious_v140_unet.safetensors",
59
+ help="Path to UNet model"
60
+ )
61
+ parser.add_argument(
62
+ "--unet_config_path",
63
+ type=str,
64
+ default="models/extracted_components/waiNSFWIllustrious_v140_unet_config.json",
65
+ help="Path to SDXL model config file"
66
+ )
67
+ parser.add_argument(
68
+ "--vae_model_path",
69
+ type=str,
70
+ default="models/extracted_components/waiNSFWIllustrious_v140_vae.safetensors",
71
+ help="Path to VAE model (if different from SDXL)"
72
+ )
73
+ parser.add_argument(
74
+ "--vae_config_path",
75
+ type=str,
76
+ default="models/extracted_components/waiNSFWIllustrious_v140_vae_config.json",
77
+ help="Path to VAE config file"
78
+ )
79
+
80
+ # Dataset arguments
81
+ parser.add_argument(
82
+ "--dataset_path",
83
+ type=str,
84
+ default='illustrious_generated',
85
+ help="Path to illustrious_generated dataset"
86
+ )
87
+ parser.add_argument(
88
+ "--no_precompute_embeddings",
89
+ action="store_false",
90
+ dest="precompute_embeddings",
91
+ help="Disable precomputing and caching Qwen embeddings and VAE latents"
92
+ )
93
+ parser.set_defaults(precompute_embeddings=True)
94
+
95
+ parser.add_argument(
96
+ "--cache_dir",
97
+ type=str,
98
+ default="./illustrious_generated/cache",
99
+ help="Directory to store precomputed embeddings"
100
+ )
101
+
102
+ # Training arguments
103
+ parser.add_argument(
104
+ "--output_dir",
105
+ type=str,
106
+ default="./qwen_illustrious_output",
107
+ help="Output directory for trained model"
108
+ )
109
+ parser.add_argument(
110
+ "--train_batch_size",
111
+ type=int,
112
+ default=1,
113
+ help="Batch size for training"
114
+ )
115
+ parser.add_argument(
116
+ "--num_train_epochs",
117
+ type=int,
118
+ default=10,
119
+ help="Number of training epochs"
120
+ )
121
+ parser.add_argument(
122
+ "--learning_rate",
123
+ type=float,
124
+ default=1e-4,
125
+ help="Learning rate"
126
+ )
127
+ parser.add_argument(
128
+ "--max_train_steps",
129
+ type=int,
130
+ default=None,
131
+ help="Maximum number of training steps"
132
+ )
133
+ parser.add_argument(
134
+ "--gradient_accumulation_steps",
135
+ type=int,
136
+ default=1,
137
+ help="Number of gradient accumulation steps"
138
+ )
139
+ parser.add_argument(
140
+ "--gradient_checkpointing",
141
+ action="store_true",
142
+ help="Enable gradient checkpointing"
143
+ )
144
+ parser.add_argument(
145
+ "--mixed_precision",
146
+ type=str,
147
+ default="fp16",
148
+ choices=["no", "fp16", "bf16"],
149
+ help="Mixed precision training"
150
+ )
151
+
152
+ # LoRA arguments
153
+ parser.add_argument(
154
+ "--lora_rank",
155
+ type=int,
156
+ default=64,
157
+ help="LoRA rank for SDXL UNet cross attention"
158
+ )
159
+ parser.add_argument(
160
+ "--lora_alpha",
161
+ type=int,
162
+ default=64,
163
+ help="LoRA alpha"
164
+ )
165
+ parser.add_argument(
166
+ "--lora_dropout",
167
+ type=float,
168
+ default=0.1,
169
+ help="LoRA dropout"
170
+ )
171
+
172
+ # Other arguments
173
+ parser.add_argument(
174
+ "--seed",
175
+ type=int,
176
+ default=42,
177
+ help="Random seed"
178
+ )
179
+ parser.add_argument(
180
+ "--logging_dir",
181
+ type=str,
182
+ default="logs",
183
+ help="Logging directory"
184
+ )
185
+ parser.add_argument(
186
+ "--report_to",
187
+ type=str,
188
+ default="wandb",
189
+ help="Logging service (tensorboard, wandb, or all)"
190
+ )
191
+ parser.add_argument(
192
+ "--wandb_project",
193
+ type=str,
194
+ default="qwen-illustrious",
195
+ help="Wandb project name"
196
+ )
197
+ parser.add_argument(
198
+ "--wandb_run_name",
199
+ type=str,
200
+ default=None,
201
+ help="Wandb run name (optional)"
202
+ )
203
+ parser.add_argument(
204
+ "--checkpointing_steps",
205
+ type=int,
206
+ default=25000,
207
+ help="Save checkpoint every N steps"
208
+ )
209
+ parser.add_argument(
210
+ "--resume_from_checkpoint",
211
+ type=str,
212
+ default=None,
213
+ help="Path to checkpoint to resume from"
214
+ )
215
+ parser.add_argument(
216
+ "--validation_epochs",
217
+ type=int,
218
+ default=1,
219
+ help="Run validation every N epochs"
220
+ )
221
+ parser.add_argument(
222
+ "--validation_prompts",
223
+ type=str,
224
+ nargs="+",
225
+ default=[
226
+ "A beautiful anime girl in a garden",
227
+ "Two characters having a conversation",
228
+ "A magical fantasy scene"
229
+ ],
230
+ help="Validation prompts"
231
+ )
232
+
233
+ return parser.parse_args()
234
+
235
+
236
+ def setup_models(args, accelerator):
237
+ """Setup and configure all models"""
238
+ logger.info("Loading models...")
239
+
240
+ # Load Qwen text encoder
241
+ # qwen_text_encoder = load_qwen_model(args.qwen_model_path)
242
+ qwen_text_encoder = QwenTextEncoder(
243
+ model_path=args.qwen_model_path,
244
+ device='cuda' if torch.cuda.is_available() else 'cpu',
245
+ max_length=512, # Default max length for Qwen
246
+ freeze_encoder=True # Freeze encoder parameters
247
+ )
248
+
249
+ # Load SDXL components
250
+ vae = load_vae_from_safetensors(args.vae_model_path, args.vae_config_path)
251
+
252
+ unet = load_unet_from_safetensors(args.unet_model_path, args.unet_config_path)
253
+
254
+ # Load scheduler
255
+ noise_scheduler = create_scheduler()
256
+
257
+ # Create adapter
258
+ adapter = QwenEmbeddingAdapter()
259
+
260
+ # Configure LoRA for UNet cross attention
261
+ logger.info(f"Setting up LoRA with rank={args.lora_rank}, alpha={args.lora_alpha}")
262
+
263
+ # Define target modules for cross attention to_k and to_v
264
+ target_modules = []
265
+ for name, module in unet.named_modules():
266
+ if "attn2" in name and ("to_k" in name or "to_v" in name):
267
+ target_modules.append(name)
268
+
269
+ if not target_modules:
270
+ logger.warning("No cross attention to_k/to_v modules found. Using default modules.")
271
+ target_modules = ["to_k", "to_v"]
272
+
273
+ logger.info(f"Applying LoRA to modules: {target_modules}")
274
+
275
+ lora_config = LoraConfig(
276
+ r=args.lora_rank,
277
+ lora_alpha=args.lora_alpha,
278
+ target_modules=target_modules,
279
+ lora_dropout=args.lora_dropout,
280
+ bias="none",
281
+ )
282
+
283
+ # Apply LoRA to UNet
284
+ unet = get_peft_model(unet, lora_config)
285
+
286
+ # Set requires_grad
287
+ vae.requires_grad_(False)
288
+ qwen_text_encoder.requires_grad_(False)
289
+ unet.requires_grad_(False)
290
+
291
+ # Enable gradients for adapter and LoRA parameters
292
+ adapter.requires_grad_(True)
293
+ for name, param in unet.named_parameters():
294
+ if "lora" in name:
295
+ param.requires_grad_(True)
296
+
297
+ # Log trainable parameters
298
+ total_params = sum(p.numel() for p in unet.parameters())
299
+ trainable_params = sum(p.numel() for p in unet.parameters() if p.requires_grad)
300
+ adapter_params = sum(p.numel() for p in adapter.parameters())
301
+
302
+ logger.info(f"UNet total parameters: {total_params:,}")
303
+ logger.info(f"UNet trainable parameters: {trainable_params:,}")
304
+ logger.info(f"Adapter parameters: {adapter_params:,}")
305
+ logger.info(f"Total trainable parameters: {trainable_params + adapter_params:,}")
306
+
307
+ return qwen_text_encoder, unet, vae, noise_scheduler, adapter
308
+
309
+
310
+ def setup_dataset(args, qwen_text_encoder, vae, accelerator):
311
+ """Setup dataset with optional precomputation"""
312
+ logger.info("Setting up dataset...")
313
+
314
+ dataset = QwenIllustriousDataset(
315
+ dataset_path=args.dataset_path,
316
+ qwen_text_encoder=qwen_text_encoder if args.precompute_embeddings else None,
317
+ vae=vae if args.precompute_embeddings else None,
318
+ cache_dir=args.cache_dir if args.precompute_embeddings else None,
319
+ precompute_embeddings=args.precompute_embeddings
320
+ )
321
+
322
+ if args.precompute_embeddings:
323
+ logger.info("Precomputing embeddings...")
324
+ dataset.precompute_all(accelerator.device)
325
+
326
+ dataloader = torch.utils.data.DataLoader(
327
+ dataset,
328
+ batch_size=args.train_batch_size,
329
+ shuffle=True,
330
+ num_workers=4,
331
+ pin_memory=True,
332
+ collate_fn=collate_fn
333
+ )
334
+
335
+ return dataset, dataloader
336
+
337
+
338
+ def training_step(batch, unet, adapter, noise_scheduler, vae, qwen_text_encoder, accelerator, args):
339
+ """Single training step"""
340
+
341
+ # Get batch data
342
+ if args.precompute_embeddings:
343
+ latents = batch["latents"].to(accelerator.device)
344
+ # For precomputed embeddings, we need to pass them through the adapter
345
+ qwen_text_embeddings = batch["text_embeddings"].to(accelerator.device)
346
+ qwen_pooled_embeddings = batch["pooled_embeddings"].to(accelerator.device)
347
+
348
+ # Project embeddings through adapter
349
+ text_embeddings = adapter.forward_text_embeddings(qwen_text_embeddings)
350
+ pooled_embeddings = adapter.forward_pooled_embeddings(qwen_pooled_embeddings)
351
+ else:
352
+ images = batch["images"].to(accelerator.device)
353
+ prompts = batch["prompts"]
354
+
355
+ # Encode images to latents
356
+ with torch.no_grad():
357
+ latents = vae.encode(images).latent_dist.sample()
358
+ latents = latents * vae.config.scaling_factor
359
+
360
+ # Encode text with Qwen
361
+ with torch.no_grad():
362
+ qwen_embeddings = qwen_text_encoder.encode_prompts(prompts, do_classifier_free_guidance=False)
363
+
364
+ # Project embeddings through adapter
365
+ text_embeddings = adapter.forward_text_embeddings(qwen_embeddings[0])
366
+ pooled_embeddings = adapter.forward_pooled_embeddings(qwen_embeddings[1])
367
+
368
+ # Sample noise and timesteps
369
+ noise = torch.randn_like(latents)
370
+ bsz = latents.shape[0]
371
+ timesteps = torch.randint(
372
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,),
373
+ device=latents.device, dtype=torch.long
374
+ )
375
+
376
+ # Add noise to latents
377
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
378
+
379
+ # Prepare cross attention inputs
380
+ encoder_hidden_states = text_embeddings
381
+
382
+ # Prepare added condition kwargs for SDXL
383
+ add_time_ids = torch.zeros((bsz, 6), device=latents.device) # Dummy time IDs
384
+ added_cond_kwargs = {
385
+ "text_embeds": pooled_embeddings,
386
+ "time_ids": add_time_ids
387
+ }
388
+
389
+ # Forward pass through UNet
390
+ model_pred = unet(
391
+ noisy_latents,
392
+ timesteps,
393
+ encoder_hidden_states,
394
+ added_cond_kwargs=added_cond_kwargs,
395
+ return_dict=False
396
+ )[0]
397
+
398
+ # Compute loss
399
+ if noise_scheduler.config.prediction_type == "epsilon":
400
+ target = noise
401
+ elif noise_scheduler.config.prediction_type == "v_prediction":
402
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
403
+ else:
404
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
405
+
406
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
407
+
408
+ return loss
409
+
410
+
411
+ def validate_model(args, qwen_text_encoder, unet, adapter, vae, accelerator, epoch):
412
+ """Run validation"""
413
+ logger.info(f"Running validation at epoch {epoch}")
414
+
415
+ # TODO: Implement validation logic
416
+ # For now, just log that validation ran
417
+ logger.info("Validation completed")
418
+
419
+ return {}
420
+
421
+
422
+ def main():
423
+ args = parse_args()
424
+
425
+ # Initialize wandb if using it
426
+ if args.report_to in ["wandb", "all"]:
427
+ wandb.init(
428
+ project=args.wandb_project,
429
+ name=args.wandb_run_name,
430
+ config=vars(args)
431
+ )
432
+
433
+ # Setup accelerator
434
+ logging_dir = Path(args.output_dir, args.logging_dir)
435
+ accelerator_project_config = ProjectConfiguration(
436
+ project_dir=args.output_dir,
437
+ logging_dir=logging_dir
438
+ )
439
+
440
+ accelerator = Accelerator(
441
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
442
+ mixed_precision=args.mixed_precision,
443
+ log_with=args.report_to,
444
+ project_config=accelerator_project_config,
445
+ )
446
+
447
+ # Setup logging
448
+ logging.basicConfig(
449
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
450
+ datefmt="%m/%d/%Y %H:%M:%S",
451
+ level=logging.INFO,
452
+ )
453
+ logger.info(accelerator.state, main_process_only=False)
454
+
455
+ # Set seed
456
+ if args.seed is not None:
457
+ set_seed(args.seed)
458
+
459
+ # Create output directory
460
+ if accelerator.is_main_process:
461
+ os.makedirs(args.output_dir, exist_ok=True)
462
+ if args.precompute_embeddings:
463
+ os.makedirs(args.cache_dir, exist_ok=True)
464
+
465
+ # Setup models
466
+ qwen_text_encoder, unet, vae, noise_scheduler, adapter = setup_models(args, accelerator)
467
+
468
+ # Setup dataset
469
+ dataset, dataloader = setup_dataset(args, qwen_text_encoder, vae, accelerator)
470
+
471
+ # Setup optimizer
472
+ trainable_params = list(adapter.parameters())
473
+ for param in unet.parameters():
474
+ if param.requires_grad:
475
+ trainable_params.append(param)
476
+
477
+ optimizer = torch.optim.AdamW(
478
+ trainable_params,
479
+ lr=args.learning_rate,
480
+ betas=(0.9, 0.999),
481
+ weight_decay=0.01,
482
+ eps=1e-8,
483
+ )
484
+
485
+ # Calculate training steps
486
+ num_update_steps_per_epoch = math.ceil(len(dataloader) / args.gradient_accumulation_steps)
487
+ if args.max_train_steps is None:
488
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
489
+
490
+ # Setup scheduler
491
+ lr_scheduler = get_scheduler(
492
+ "cosine",
493
+ optimizer=optimizer,
494
+ num_warmup_steps=500,
495
+ num_training_steps=args.max_train_steps,
496
+ )
497
+
498
+ # Prepare for training
499
+ unet, adapter, optimizer, dataloader, lr_scheduler = accelerator.prepare(
500
+ unet, adapter, optimizer, dataloader, lr_scheduler
501
+ )
502
+
503
+ # Move other models to device
504
+ qwen_text_encoder.to('cpu')
505
+ vae.to('cpu')
506
+
507
+ # Initialize tracking
508
+ if accelerator.is_main_process:
509
+ tracker_config = vars(args)
510
+ accelerator.init_trackers(args.wandb_project, config=tracker_config)
511
+
512
+ # Training loop
513
+ logger.info("***** Running training *****")
514
+ logger.info(f" Num examples = {len(dataset)}")
515
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
516
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
517
+ logger.info(f" Total train batch size = {args.train_batch_size * accelerator.num_processes}")
518
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
519
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
520
+
521
+ global_step = 0
522
+ first_epoch = 0
523
+
524
+ # Resume from checkpoint if specified
525
+ if args.resume_from_checkpoint:
526
+ if args.resume_from_checkpoint != "latest":
527
+ path = os.path.basename(args.resume_from_checkpoint)
528
+ else:
529
+ # Get the most recent checkpoint
530
+ dirs = os.listdir(args.output_dir)
531
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
532
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
533
+ path = dirs[-1] if len(dirs) > 0 else None
534
+
535
+ if path is None:
536
+ accelerator.print(f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting new training.")
537
+ else:
538
+ accelerator.print(f"Resuming from checkpoint {path}")
539
+ accelerator.load_state(os.path.join(args.output_dir, path))
540
+ global_step = int(path.split("-")[1])
541
+ first_epoch = global_step // num_update_steps_per_epoch
542
+
543
+ progress_bar = tqdm(
544
+ range(0, args.max_train_steps),
545
+ initial=global_step,
546
+ desc="Steps",
547
+ disable=not accelerator.is_local_main_process,
548
+ )
549
+
550
+ for epoch in range(first_epoch, args.num_train_epochs):
551
+ unet.train()
552
+ adapter.train()
553
+ train_loss = 0.0
554
+ epoch_loss = 0.0
555
+ num_batches = 0
556
+
557
+ for step, batch in enumerate(dataloader):
558
+ with accelerator.accumulate(unet):
559
+ loss = training_step(batch, unet, adapter, noise_scheduler, vae, qwen_text_encoder, accelerator, args)
560
+
561
+ # Backward pass
562
+ accelerator.backward(loss)
563
+
564
+ if accelerator.sync_gradients:
565
+ accelerator.clip_grad_norm_(trainable_params, 1.0)
566
+
567
+ optimizer.step()
568
+ lr_scheduler.step()
569
+ optimizer.zero_grad()
570
+
571
+ # Checks if the accelerator has performed an optimization step behind the scenes
572
+ if accelerator.sync_gradients:
573
+ progress_bar.update(1)
574
+ global_step += 1
575
+
576
+ # Logging
577
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
578
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
579
+ epoch_loss += avg_loss.item()
580
+ num_batches += 1
581
+
582
+ # Log metrics to both accelerator and wandb
583
+ log_dict = {
584
+ "train/step_loss": avg_loss.item(),
585
+ "train/learning_rate": lr_scheduler.get_last_lr()[0],
586
+ "train/epoch": epoch,
587
+ "train/global_step": global_step
588
+ }
589
+ accelerator.log(log_dict, step=global_step)
590
+
591
+ # Additional wandb logging
592
+ if args.report_to in ["wandb", "all"] and accelerator.is_main_process:
593
+ wandb.log(log_dict, step=global_step)
594
+
595
+ train_loss = 0.0
596
+
597
+ # Save checkpoint
598
+ if global_step % args.checkpointing_steps == 0:
599
+ if accelerator.is_main_process:
600
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
601
+ accelerator.save_state(save_path)
602
+ logger.info(f"Saved state to {save_path}")
603
+
604
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
605
+ progress_bar.set_postfix(**logs)
606
+
607
+ if global_step >= args.max_train_steps:
608
+ break
609
+
610
+ # Log epoch statistics
611
+ if num_batches > 0 and accelerator.is_main_process:
612
+ avg_epoch_loss = epoch_loss / num_batches
613
+ epoch_log_dict = {
614
+ "train/epoch_loss": avg_epoch_loss,
615
+ "train/epoch_num": epoch
616
+ }
617
+ accelerator.log(epoch_log_dict, step=global_step)
618
+ if args.report_to in ["wandb", "all"]:
619
+ wandb.log(epoch_log_dict, step=global_step)
620
+ logger.info(f"Epoch {epoch} - Average Loss: {avg_epoch_loss:.4f}")
621
+
622
+ # Validation
623
+ if epoch % args.validation_epochs == 0:
624
+ validation_metrics = validate_model(
625
+ args, qwen_text_encoder, unet, adapter, vae, accelerator, epoch
626
+ )
627
+ if validation_metrics:
628
+ accelerator.log(validation_metrics, step=global_step)
629
+ if args.report_to in ["wandb", "all"] and accelerator.is_main_process:
630
+ wandb.log(validation_metrics, step=global_step)
631
+
632
+ # Save final model
633
+ accelerator.wait_for_everyone()
634
+ if accelerator.is_main_process:
635
+ from safetensors.torch import save_file
636
+ from peft import get_peft_model_state_dict
637
+
638
+ logger.info("Saving trained models...")
639
+
640
+ # Save adapter in safetensor format
641
+ adapter_save_path = os.path.join(args.output_dir, "adapter")
642
+ os.makedirs(adapter_save_path, exist_ok=True)
643
+ adapter_state_dict = adapter.state_dict()
644
+ save_file(adapter_state_dict, os.path.join(adapter_save_path, "adapter.safetensors"))
645
+ logger.info(f"Adapter saved to {adapter_save_path}/adapter.safetensors")
646
+
647
+ # Save LoRA weights only (in safetensor format)
648
+ lora_save_path = os.path.join(args.output_dir, "lora_weights")
649
+ os.makedirs(lora_save_path, exist_ok=True)
650
+
651
+ # Get only LoRA state dict
652
+ lora_state_dict = get_peft_model_state_dict(unet)
653
+ save_file(lora_state_dict, os.path.join(lora_save_path, "lora_weights.safetensors"))
654
+ logger.info(f"LoRA weights saved to {lora_save_path}/lora_weights.safetensors")
655
+
656
+ # Save LoRA config
657
+ lora_config_path = os.path.join(lora_save_path, "adapter_config.json")
658
+ unet.peft_config['default'].save_pretrained(lora_save_path)
659
+ logger.info(f"LoRA config saved to {lora_save_path}/adapter_config.json")
660
+
661
+ # Save full UNet with fused LoRA weights
662
+ logger.info("Fusing LoRA weights into UNet...")
663
+ unet_fused_save_path = os.path.join(args.output_dir, "unet_fused")
664
+ os.makedirs(unet_fused_save_path, exist_ok=True)
665
+
666
+ # Create a copy of the original UNet and merge LoRA weights
667
+ from diffusers import UNet2DConditionModel
668
+ unet_base = unet
669
+
670
+ # Merge LoRA weights into base model
671
+ from peft import PeftModel
672
+ unet_merged = PeftModel.from_pretrained(unet_base, lora_save_path)
673
+ unet_merged = unet_merged.merge_and_unload()
674
+
675
+ # Save the merged model in safetensor format
676
+ unet_merged.save_pretrained(
677
+ unet_fused_save_path,
678
+ safe_serialization=True
679
+ )
680
+ logger.info(f"Fused UNet saved to {unet_fused_save_path}")
681
+
682
+ # Save training config
683
+ import json
684
+ config_save_path = os.path.join(args.output_dir, "training_config.json")
685
+ training_config = {
686
+ "qwen_model_path": args.qwen_model_path,
687
+ "unet_model_path": args.unet_model_path,
688
+ "vae_model_path": args.vae_model_path,
689
+ "lora_rank": args.lora_rank,
690
+ "lora_alpha": args.lora_alpha,
691
+ "lora_dropout": args.lora_dropout,
692
+ "learning_rate": args.learning_rate,
693
+ "train_batch_size": args.train_batch_size,
694
+ "num_train_epochs": args.num_train_epochs,
695
+ "gradient_accumulation_steps": args.gradient_accumulation_steps,
696
+ }
697
+ with open(config_save_path, 'w') as f:
698
+ json.dump(training_config, f, indent=2)
699
+ logger.info(f"Training config saved to {config_save_path}")
700
+
701
+ logger.info(f"Training completed. All models saved to {args.output_dir}")
702
+ logger.info("Saved components:")
703
+ logger.info(f" - Adapter: {adapter_save_path}/adapter.safetensors")
704
+ logger.info(f" - LoRA weights only: {lora_save_path}/lora_weights.safetensors")
705
+ logger.info(f" - UNet with fused LoRA: {unet_fused_save_path}")
706
+ logger.info(f" - Training config: {config_save_path}")
707
+
708
+ # Finish wandb run
709
+ if args.report_to in ["wandb", "all"] and accelerator.is_main_process:
710
+ wandb.finish()
711
+
712
+ accelerator.end_training()
713
+
714
+
715
+ if __name__ == "__main__":
716
+ main()
train/usage_example.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Usage Example for Trained QwenIllustrious Model
4
+ 展示如何使用训练后的QwenIllustrious模型
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ # 添加项目路径
12
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
13
+ from arch import QwenIllustriousInference
14
+
15
+
16
+ def example_usage_lora_weights():
17
+ """
18
+ Example: Using LoRA weights (separate from base model)
19
+ 示例:使用LoRA权重(与基础模型分离)
20
+ """
21
+ print("🚀 示例:使用LoRA权重进行推理")
22
+ print("=" * 50)
23
+
24
+ # 假设训练输出在这个目录
25
+ output_dir = "./qwen_illustrious_output"
26
+
27
+ pipeline = QwenIllustriousInference(
28
+ # 基础模型路径
29
+ qwen_model_path="models/Qwen3-Embedding-0.6B",
30
+ unet_path="models/sdxl_base", # 原始SDXL模型路径
31
+ vae_path="models/sdxl_base",
32
+
33
+ # 训练后的组件
34
+ adapter_path=f"{output_dir}/adapter/adapter.safetensors",
35
+ lora_weights_path=f"{output_dir}/lora_weights/lora_weights.safetensors",
36
+ lora_config_path=f"{output_dir}/lora_weights",
37
+
38
+ device="cuda",
39
+ dtype="bfloat16"
40
+ )
41
+
42
+ if pipeline.is_ready:
43
+ # 生成图像
44
+ images = pipeline.generate(
45
+ prompt="A beautiful anime girl in a magical garden, high quality",
46
+ negative_prompt="low quality, blurry, distorted",
47
+ height=1024,
48
+ width=1024,
49
+ num_inference_steps=50,
50
+ guidance_scale=7.5
51
+ )
52
+
53
+ if images:
54
+ images[0].save("example_lora_output.png")
55
+ print("✅ 图像已保存到 example_lora_output.png")
56
+ else:
57
+ print("❌ 管道未准备就绪")
58
+
59
+
60
+ def example_usage_fused_model():
61
+ """
62
+ Example: Using fused model (LoRA merged into UNet)
63
+ 示例:使用融合模型(LoRA已合并到UNet中)
64
+ """
65
+ print("\n🚀 示例:使用融合模型进行推理")
66
+ print("=" * 50)
67
+
68
+ # 假设训练输出在这个目录
69
+ output_dir = "./qwen_illustrious_output"
70
+
71
+ pipeline = QwenIllustriousInference(
72
+ # 基础模型路径
73
+ qwen_model_path="models/Qwen3-Embedding-0.6B",
74
+ vae_path="models/sdxl_base",
75
+
76
+ # 训练后的组件
77
+ adapter_path=f"{output_dir}/adapter/adapter.safetensors",
78
+ use_fused_unet=True,
79
+ fused_unet_path=f"{output_dir}/unet_fused",
80
+
81
+ device="cuda",
82
+ dtype="bfloat16"
83
+ )
84
+
85
+ if pipeline.is_ready:
86
+ # 生成图像
87
+ images = pipeline.generate(
88
+ prompt="Two anime characters having a conversation in a cozy room",
89
+ negative_prompt="low quality, blurry, distorted",
90
+ height=1024,
91
+ width=1024,
92
+ num_inference_steps=50,
93
+ guidance_scale=7.5
94
+ )
95
+
96
+ if images:
97
+ images[0].save("example_fused_output.png")
98
+ print("✅ 图像已保存到 example_fused_output.png")
99
+ else:
100
+ print("❌ 管道未准备就绪")
101
+
102
+
103
+ def training_command_examples():
104
+ """
105
+ Show example training commands
106
+ 显示训练命令示例
107
+ """
108
+ print("\n📚 训练命令示例")
109
+ print("=" * 50)
110
+
111
+ print("1. 基础训练命令:")
112
+ print("python train/train_qwen_illustrious.py \\")
113
+ print(" --qwen_model_path models/Qwen3-Embedding-0.6B \\")
114
+ print(" --sdxl_model_path models/sdxl_base \\")
115
+ print(" --dataset_path illustrious_generated \\")
116
+ print(" --output_dir qwen_illustrious_output \\")
117
+ print(" --train_batch_size 4 \\")
118
+ print(" --num_train_epochs 10 \\")
119
+ print(" --learning_rate 1e-4 \\")
120
+ print(" --lora_rank 64 \\")
121
+ print(" --mixed_precision fp16")
122
+
123
+ print("\n2. 使用预计算嵌入加速训练:")
124
+ print("# 第一步:预计算嵌入")
125
+ print("python train/precompute_embeddings.py \\")
126
+ print(" --qwen_model_path models/Qwen3-Embedding-0.6B \\")
127
+ print(" --sdxl_model_path models/sdxl_base \\")
128
+ print(" --dataset_path illustrious_generated \\")
129
+ print(" --cache_dir cache \\")
130
+ print(" --batch_size 8")
131
+
132
+ print("\n# 第二步:使用预计算嵌入训练")
133
+ print("python train/train_qwen_illustrious.py \\")
134
+ print(" --qwen_model_path models/Qwen3-Embedding-0.6B \\")
135
+ print(" --sdxl_model_path models/sdxl_base \\")
136
+ print(" --dataset_path illustrious_generated \\")
137
+ print(" --precompute_embeddings \\")
138
+ print(" --cache_dir cache \\")
139
+ print(" --output_dir qwen_illustrious_output \\")
140
+ print(" --train_batch_size 8 \\") # 可以使用更大的batch size
141
+ print(" --num_train_epochs 10")
142
+
143
+
144
+ def inference_command_examples():
145
+ """
146
+ Show example inference commands
147
+ 显示推理命令示例
148
+ """
149
+ print("\n🎨 推理命令示例")
150
+ print("=" * 50)
151
+
152
+ print("1. 使用LoRA权重推理:")
153
+ print("python inference_updated.py \\")
154
+ print(" --prompt 'A beautiful anime girl in a garden' \\")
155
+ print(" --adapter_path qwen_illustrious_output/adapter/adapter.safetensors \\")
156
+ print(" --lora_weights_path qwen_illustrious_output/lora_weights/lora_weights.safetensors \\")
157
+ print(" --lora_config_path qwen_illustrious_output/lora_weights \\")
158
+ print(" --output my_image.png")
159
+
160
+ print("\n2. 使用融合模型推理:")
161
+ print("python inference_updated.py \\")
162
+ print(" --prompt 'Two characters having a conversation' \\")
163
+ print(" --adapter_path qwen_illustrious_output/adapter/adapter.safetensors \\")
164
+ print(" --use_fused_unet \\")
165
+ print(" --fused_unet_path qwen_illustrious_output/unet_fused \\")
166
+ print(" --output my_image.png")
167
+
168
+
169
+ if __name__ == "__main__":
170
+ print("🎯 QwenIllustrious 使用示例")
171
+ print("=" * 60)
172
+
173
+ training_command_examples()
174
+ inference_command_examples()
175
+
176
+ # 如果模型文件存在,运行实际示例
177
+ output_dir = Path("./qwen_illustrious_output")
178
+ if output_dir.exists():
179
+ print("\n" + "=" * 60)
180
+ print("🧪 运行实际推理示例 (检测到训练输出)")
181
+ print("=" * 60)
182
+
183
+ try:
184
+ example_usage_lora_weights()
185
+ example_usage_fused_model()
186
+ except Exception as e:
187
+ print(f"❌ 运行示例时出错: {e}")
188
+ else:
189
+ print(f"\n⚠️ 未找到训练输出目录: {output_dir}")
190
+ print("请先运行训练脚本生成模型文件")
transformers/.gitattributes ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ *.py eol=lf
2
+ *.rst eol=lf
3
+ *.md eol=lf
4
+ *.mdx eol=lf
transformers/.gitignore ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Initially taken from Github's Python gitignore file
2
+
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+
8
+ # C extensions
9
+ *.so
10
+
11
+ # tests and logs
12
+ tests/fixtures/cached_*_text.txt
13
+ logs/
14
+ lightning_logs/
15
+ lang_code_data/
16
+
17
+ # Distribution / packaging
18
+ .Python
19
+ build/
20
+ develop-eggs/
21
+ dist/
22
+ downloads/
23
+ eggs/
24
+ .eggs/
25
+ lib/
26
+ lib64/
27
+ parts/
28
+ sdist/
29
+ var/
30
+ wheels/
31
+ *.egg-info/
32
+ .installed.cfg
33
+ *.egg
34
+ MANIFEST
35
+
36
+ # PyInstaller
37
+ # Usually these files are written by a python script from a template
38
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
39
+ *.manifest
40
+ *.spec
41
+
42
+ # Installer logs
43
+ pip-log.txt
44
+ pip-delete-this-directory.txt
45
+
46
+ # Unit test / coverage reports
47
+ htmlcov/
48
+ .tox/
49
+ .nox/
50
+ .coverage
51
+ .coverage.*
52
+ .cache
53
+ nosetests.xml
54
+ coverage.xml
55
+ *.cover
56
+ .hypothesis/
57
+ .pytest_cache/
58
+
59
+ # Translations
60
+ *.mo
61
+ *.pot
62
+
63
+ # Django stuff:
64
+ *.log
65
+ local_settings.py
66
+ db.sqlite3
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ target/
80
+
81
+ # Jupyter Notebook
82
+ .ipynb_checkpoints
83
+
84
+ # IPython
85
+ profile_default/
86
+ ipython_config.py
87
+
88
+ # pyenv
89
+ .python-version
90
+
91
+ # celery beat schedule file
92
+ celerybeat-schedule
93
+
94
+ # SageMath parsed files
95
+ *.sage.py
96
+
97
+ # Environments
98
+ .env
99
+ .venv
100
+ env/
101
+ venv/
102
+ ENV/
103
+ env.bak/
104
+ venv.bak/
105
+
106
+ # Spyder project settings
107
+ .spyderproject
108
+ .spyproject
109
+
110
+ # Rope project settings
111
+ .ropeproject
112
+
113
+ # mkdocs documentation
114
+ /site
115
+
116
+ # mypy
117
+ .mypy_cache/
118
+ .dmypy.json
119
+ dmypy.json
120
+
121
+ # Pyre type checker
122
+ .pyre/
123
+
124
+ # vscode
125
+ .vs
126
+ .vscode
127
+
128
+ # Pycharm
129
+ .idea
130
+
131
+ # TF code
132
+ tensorflow_code
133
+
134
+ # Models
135
+ proc_data
136
+
137
+ # examples
138
+ runs
139
+ /runs_old
140
+ /wandb
141
+ /examples/runs
142
+ /examples/**/*.args
143
+ /examples/rag/sweep
144
+
145
+ # data
146
+ /data
147
+ serialization_dir
148
+
149
+ # emacs
150
+ *.*~
151
+ debug.env
152
+
153
+ # vim
154
+ .*.swp
155
+
156
+ #ctags
157
+ tags
158
+
159
+ # pre-commit
160
+ .pre-commit*
161
+
162
+ # .lock
163
+ *.lock
164
+
165
+ # DS_Store (MacOS)
166
+ .DS_Store
167
+
168
+ # ruff
169
+ .ruff_cache
170
+
171
+ # modular conversion
172
+ *.modular_backup
transformers/AGENTS.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AGENTS.md Guide for Hugging Face Transformers
2
+
3
+ This AGENTS.md file provides guidance for code agents working with this codebase.
4
+
5
+ ## Core Project Structure
6
+
7
+ - `/src/transformers`: This contains the core source code for the library
8
+ - `/models`: Code for individual models. Models inherit from base classes in the root `/src/transformers` directory.
9
+ - `/tests`: This contains the core test classes for the library. These are usually inherited rather than directly run.
10
+ - `/models`: Tests for individual models. Model tests inherit from common tests in the root `/tests` directory.
11
+ - `/docs`: This contains the documentation for the library, including guides, tutorials, and API references.
12
+
13
+ ## Coding Conventions for Hugging Face Transformers
14
+
15
+ - PRs should be as brief as possible. Bugfix PRs in particular can often be only one or two lines long, and do not need large comments, docstrings or new functions in this case. Aim to minimize the size of the diff.
16
+ - When writing tests, they should be added to an existing file. The only exception is for PRs to add a new model, when a new test directory should be created for that model.
17
+ - Code style is enforced in the CI. You can install the style tools with `pip install -e .[quality]`. You can then run `make fixup` to apply style and consistency fixes to your code.
18
+
19
+ ## Copying and inheritance
20
+
21
+ Many models in the codebase have similar code, but it is not shared by inheritance because we want each model file to be self-contained.
22
+ We use two mechanisms to keep this code in sync:
23
+
24
+ - "Copied from" syntax. Functions or entire classes can have a comment at the top like this: `# Copied from transformers.models.llama.modeling_llama.rotate_half` or `# Copied from transformers.models.t5.modeling_t5.T5LayerNorm with T5->MT5`
25
+ These comments are actively checked by the style tools, and copies will automatically be updated when the base code is updated. If you need to update a copied function, you should
26
+ either update the base function and use `make fixup` to propagate the change to all copies, or simply remove the `# Copied from` comment if that is inappropriate.
27
+ - "Modular" files. These files briefly define models by composing them using inheritance from other models. They are not meant to be used directly. Instead, the style tools
28
+ automatically generate a complete modeling file, like `modeling_bert.py`, from the modular file like `modular_bert.py`. If a model has a modular file, the modeling file
29
+ should never be edited directly! Instead, changes should be made in the modular file, and then you should run `make fixup` to update the modeling file automatically.
30
+
31
+ When adding new models, you should prefer `modular` style.
32
+
33
+ ## Testing
34
+
35
+ After making changes, you should usually run `make fixup` to ensure any copies and modular files are updated, and then test all affected models. This includes both
36
+ the model you made the changes in and any other models that were updated by `make fixup`. Tests can be run with `pytest tests/models/[name]/test_modeling_[name].py`
37
+ If your changes affect code in other classes like tokenizers or processors, you should run those tests instead, like `test_processing_[name].py` or `test_tokenization_[name].py`.
38
+
39
+ In order to run tests, you may need to install dependencies. You can do this with `pip install -e .[testing]`. You will probably also need to `pip install torch accelerate` if your environment does not already have them.
transformers/CITATION.cff ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: "1.2.0"
2
+ date-released: 2020-10
3
+ message: "If you use this software, please cite it using these metadata."
4
+ title: "Transformers: State-of-the-Art Natural Language Processing"
5
+ url: "https://github.com/huggingface/transformers"
6
+ authors:
7
+ - family-names: Wolf
8
+ given-names: Thomas
9
+ - family-names: Debut
10
+ given-names: Lysandre
11
+ - family-names: Sanh
12
+ given-names: Victor
13
+ - family-names: Chaumond
14
+ given-names: Julien
15
+ - family-names: Delangue
16
+ given-names: Clement
17
+ - family-names: Moi
18
+ given-names: Anthony
19
+ - family-names: Cistac
20
+ given-names: Perric
21
+ - family-names: Ma
22
+ given-names: Clara
23
+ - family-names: Jernite
24
+ given-names: Yacine
25
+ - family-names: Plu
26
+ given-names: Julien
27
+ - family-names: Xu
28
+ given-names: Canwen
29
+ - family-names: "Le Scao"
30
+ given-names: Teven
31
+ - family-names: Gugger
32
+ given-names: Sylvain
33
+ - family-names: Drame
34
+ given-names: Mariama
35
+ - family-names: Lhoest
36
+ given-names: Quentin
37
+ - family-names: Rush
38
+ given-names: "Alexander M."
39
+ preferred-citation:
40
+ type: conference-paper
41
+ authors:
42
+ - family-names: Wolf
43
+ given-names: Thomas
44
+ - family-names: Debut
45
+ given-names: Lysandre
46
+ - family-names: Sanh
47
+ given-names: Victor
48
+ - family-names: Chaumond
49
+ given-names: Julien
50
+ - family-names: Delangue
51
+ given-names: Clement
52
+ - family-names: Moi
53
+ given-names: Anthony
54
+ - family-names: Cistac
55
+ given-names: Perric
56
+ - family-names: Ma
57
+ given-names: Clara
58
+ - family-names: Jernite
59
+ given-names: Yacine
60
+ - family-names: Plu
61
+ given-names: Julien
62
+ - family-names: Xu
63
+ given-names: Canwen
64
+ - family-names: "Le Scao"
65
+ given-names: Teven
66
+ - family-names: Gugger
67
+ given-names: Sylvain
68
+ - family-names: Drame
69
+ given-names: Mariama
70
+ - family-names: Lhoest
71
+ given-names: Quentin
72
+ - family-names: Rush
73
+ given-names: "Alexander M."
74
+ booktitle: "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations"
75
+ month: 10
76
+ start: 38
77
+ end: 45
78
+ title: "Transformers: State-of-the-Art Natural Language Processing"
79
+ year: 2020
80
+ publisher: "Association for Computational Linguistics"
81
+ url: "https://www.aclweb.org/anthology/2020.emnlp-demos.6"
82
+ address: "Online"
transformers/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Contributor Covenant Code of Conduct
3
+
4
+ ## Our Pledge
5
+
6
+ We as members, contributors, and leaders pledge to make participation in our
7
+ community a harassment-free experience for everyone, regardless of age, body
8
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
9
+ identity and expression, level of experience, education, socio-economic status,
10
+ nationality, personal appearance, race, caste, color, religion, or sexual
11
+ identity and orientation.
12
+
13
+ We pledge to act and interact in ways that contribute to an open, welcoming,
14
+ diverse, inclusive, and healthy community.
15
+
16
+ ## Our Standards
17
+
18
+ Examples of behavior that contributes to a positive environment for our
19
+ community include:
20
+
21
+ * Demonstrating empathy and kindness toward other people
22
+ * Being respectful of differing opinions, viewpoints, and experiences
23
+ * Giving and gracefully accepting constructive feedback
24
+ * Accepting responsibility and apologizing to those affected by our mistakes,
25
+ and learning from the experience
26
+ * Focusing on what is best not just for us as individuals, but for the overall
27
+ community
28
+
29
+ Examples of unacceptable behavior include:
30
+
31
+ * The use of sexualized language or imagery, and sexual attention or advances of
32
+ any kind
33
+ * Trolling, insulting or derogatory comments, and personal or political attacks
34
+ * Public or private harassment
35
+ * Publishing others' private information, such as a physical or email address,
36
+ without their explicit permission
37
+ * Other conduct which could reasonably be considered inappropriate in a
38
+ professional setting
39
+
40
+ ## Enforcement Responsibilities
41
+
42
+ Community leaders are responsible for clarifying and enforcing our standards of
43
+ acceptable behavior and will take appropriate and fair corrective action in
44
+ response to any behavior that they deem inappropriate, threatening, offensive,
45
+ or harmful.
46
+
47
+ Community leaders have the right and responsibility to remove, edit, or reject
48
+ comments, commits, code, wiki edits, issues, and other contributions that are
49
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
50
+ decisions when appropriate.
51
+
52
+ ## Scope
53
+
54
+ This Code of Conduct applies within all community spaces, and also applies when
55
+ an individual is officially representing the community in public spaces.
56
+ Examples of representing our community include using an official e-mail address,
57
+ posting via an official social media account, or acting as an appointed
58
+ representative at an online or offline event.
59
+
60
+ ## Enforcement
61
+
62
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
63
+ reported to the community leaders responsible for enforcement at
64
+ feedback@huggingface.co.
65
+ All complaints will be reviewed and investigated promptly and fairly.
66
+
67
+ All community leaders are obligated to respect the privacy and security of the
68
+ reporter of any incident.
69
+
70
+ ## Enforcement Guidelines
71
+
72
+ Community leaders will follow these Community Impact Guidelines in determining
73
+ the consequences for any action they deem in violation of this Code of Conduct:
74
+
75
+ ### 1. Correction
76
+
77
+ **Community Impact**: Use of inappropriate language or other behavior deemed
78
+ unprofessional or unwelcome in the community.
79
+
80
+ **Consequence**: A private, written warning from community leaders, providing
81
+ clarity around the nature of the violation and an explanation of why the
82
+ behavior was inappropriate. A public apology may be requested.
83
+
84
+ ### 2. Warning
85
+
86
+ **Community Impact**: A violation through a single incident or series of
87
+ actions.
88
+
89
+ **Consequence**: A warning with consequences for continued behavior. No
90
+ interaction with the people involved, including unsolicited interaction with
91
+ those enforcing the Code of Conduct, for a specified period of time. This
92
+ includes avoiding interactions in community spaces as well as external channels
93
+ like social media. Violating these terms may lead to a temporary or permanent
94
+ ban.
95
+
96
+ ### 3. Temporary Ban
97
+
98
+ **Community Impact**: A serious violation of community standards, including
99
+ sustained inappropriate behavior.
100
+
101
+ **Consequence**: A temporary ban from any sort of interaction or public
102
+ communication with the community for a specified period of time. No public or
103
+ private interaction with the people involved, including unsolicited interaction
104
+ with those enforcing the Code of Conduct, is allowed during this period.
105
+ Violating these terms may lead to a permanent ban.
106
+
107
+ ### 4. Permanent Ban
108
+
109
+ **Community Impact**: Demonstrating a pattern of violation of community
110
+ standards, including sustained inappropriate behavior, harassment of an
111
+ individual, or aggression toward or disparagement of classes of individuals.
112
+
113
+ **Consequence**: A permanent ban from any sort of public interaction within the
114
+ community.
115
+
116
+ ## Attribution
117
+
118
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119
+ version 2.1, available at
120
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
121
+
122
+ Community Impact Guidelines were inspired by
123
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
124
+
125
+ For answers to common questions about this code of conduct, see the FAQ at
126
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
127
+ [https://www.contributor-covenant.org/translations][translations].
128
+
129
+ [homepage]: https://www.contributor-covenant.org
130
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
131
+ [Mozilla CoC]: https://github.com/mozilla/diversity
132
+ [FAQ]: https://www.contributor-covenant.org/faq
133
+ [translations]: https://www.contributor-covenant.org/translations
transformers/CONTRIBUTING.md ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2020 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Contribute to 🤗 Transformers
18
+
19
+ Everyone is welcome to contribute, and we value everybody's contribution. Code
20
+ contributions are not the only way to help the community. Answering questions, helping
21
+ others, and improving the documentation are also immensely valuable.
22
+
23
+ It also helps us if you spread the word! Reference the library in blog posts
24
+ about the awesome projects it made possible, shout out on Twitter every time it has
25
+ helped you, or simply ⭐️ the repository to say thank you.
26
+
27
+ However you choose to contribute, please be mindful and respect our
28
+ [code of conduct](https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md).
29
+
30
+ **This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).**
31
+
32
+ ## Ways to contribute
33
+
34
+ There are several ways you can contribute to 🤗 Transformers:
35
+
36
+ * Fix outstanding issues with the existing code.
37
+ * Submit issues related to bugs or desired new features.
38
+ * Implement new models.
39
+ * Contribute to the examples or to the documentation.
40
+
41
+ If you don't know where to start, there is a special [Good First
42
+ Issue](https://github.com/huggingface/transformers/contribute) listing. It will give you a list of
43
+ open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over.
44
+
45
+ For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/transformers/labels/Good%20Second%20Issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀
46
+
47
+ > All contributions are equally valuable to the community. 🥰
48
+
49
+ ## Fixing outstanding issues
50
+
51
+ If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#create-a-pull-request) and open a Pull Request!
52
+
53
+ ## Submitting a bug-related issue or feature request
54
+
55
+ Do your best to follow these guidelines when submitting a bug-related issue or a feature
56
+ request. It will make it easier for us to come back to you quickly and with good
57
+ feedback.
58
+
59
+ ### Did you find a bug?
60
+
61
+ The 🤗 Transformers library is robust and reliable thanks to users who report the problems they encounter.
62
+
63
+ Before you report an issue, we would really appreciate it if you could **make sure the bug was not
64
+ already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code. If you're unsure whether the bug is in your code or the library, please ask in the [forum](https://discuss.huggingface.co/) or on our [discord](https://discord.com/invite/hugging-face-879548962464493619) first. This helps us respond quicker to fixing issues related to the library versus general questions.
65
+
66
+ > [!TIP]
67
+ > We have a [docs bot](https://huggingface.co/spaces/huggingchat/hf-docs-chat), and we highly encourage you to ask all your questions there. There is always a chance your bug can be fixed with a simple flag 👾🔫
68
+
69
+ Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it:
70
+
71
+ * Your **OS type and version** and **Python**, **PyTorch** and
72
+ **TensorFlow** versions when applicable.
73
+ * A short, self-contained, code snippet that allows us to reproduce the bug in
74
+ less than 30s.
75
+ * The *full* traceback if an exception is raised.
76
+ * Attach any other additional information, like screenshots, you think may help.
77
+
78
+ To get the OS and software versions automatically, run the following command:
79
+
80
+ ```bash
81
+ transformers env
82
+ ```
83
+
84
+ You can also run the same command from the root of the repository:
85
+
86
+ ```bash
87
+ python src/transformers/commands/transformers_cli.py env
88
+ ```
89
+
90
+ ### Do you want a new feature?
91
+
92
+ If there is a new feature you'd like to see in 🤗 Transformers, please open an issue and describe:
93
+
94
+ 1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community?
95
+
96
+ Whatever it is, we'd love to hear about it!
97
+
98
+ 2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you.
99
+ 3. Provide a *code snippet* that demonstrates the features usage.
100
+ 4. If the feature is related to a paper, please include a link.
101
+
102
+ If your issue is well written we're already 80% of the way there by the time you create it.
103
+
104
+ We have added [templates](https://github.com/huggingface/transformers/tree/main/templates) to help you get started with your issue.
105
+
106
+ ## Do you want to implement a new model?
107
+
108
+ New models are constantly released and if you want to implement a new model, please provide the following information:
109
+
110
+ * A short description of the model and a link to the paper.
111
+ * Link to the implementation if it is open-sourced.
112
+ * Link to the model weights if they are available.
113
+
114
+ If you are willing to contribute the model yourself, let us know so we can help you add it to 🤗 Transformers!
115
+
116
+ We have a technical guide for [how to add a model to 🤗 Transformers](https://huggingface.co/docs/transformers/add_new_model).
117
+
118
+ ## Do you want to add documentation?
119
+
120
+ We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved such as typos and any content that is missing, unclear or inaccurate. We'll be happy to make the changes or help you make a contribution if you're interested!
121
+
122
+ For more details about how to generate, build, and write the documentation, take a look at the documentation [README](https://github.com/huggingface/transformers/tree/main/docs).
123
+
124
+ ## Create a Pull Request
125
+
126
+ Before writing any code, we strongly advise you to search through the existing PRs or
127
+ issues to make sure nobody is already working on the same thing. If you are
128
+ unsure, it is always a good idea to open an issue to get some feedback.
129
+
130
+ You will need basic `git` proficiency to contribute to
131
+ 🤗 Transformers. While `git` is not the easiest tool to use, it has the greatest
132
+ manual. Type `git --help` in a shell and enjoy! If you prefer books, [Pro
133
+ Git](https://git-scm.com/book/en/v2) is a very good reference.
134
+
135
+ You'll need **[Python 3.9](https://github.com/huggingface/transformers/blob/main/setup.py#L449)** or above to contribute to 🤗 Transformers. Follow the steps below to start contributing:
136
+
137
+ 1. Fork the [repository](https://github.com/huggingface/transformers) by
138
+ clicking on the **[Fork](https://github.com/huggingface/transformers/fork)** button on the repository's page. This creates a copy of the code
139
+ under your GitHub user account.
140
+
141
+ 2. Clone your fork to your local disk, and add the base repository as a remote:
142
+
143
+ ```bash
144
+ git clone git@github.com:<your Github handle>/transformers.git
145
+ cd transformers
146
+ git remote add upstream https://github.com/huggingface/transformers.git
147
+ ```
148
+
149
+ 3. Create a new branch to hold your development changes:
150
+
151
+ ```bash
152
+ git checkout -b a-descriptive-name-for-my-changes
153
+ ```
154
+
155
+ 🚨 **Do not** work on the `main` branch!
156
+
157
+ 4. Set up a development environment by running the following command in a virtual environment:
158
+
159
+ ```bash
160
+ pip install -e ".[dev]"
161
+ ```
162
+
163
+ If 🤗 Transformers was already installed in the virtual environment, remove
164
+ it with `pip uninstall transformers` before reinstalling it in editable
165
+ mode with the `-e` flag.
166
+
167
+ Depending on your OS, and since the number of optional dependencies of Transformers is growing, you might get a
168
+ failure with this command. If that's the case make sure to install the Deep Learning framework you are working with
169
+ (PyTorch, TensorFlow and/or Flax) then do:
170
+
171
+ ```bash
172
+ pip install -e ".[quality]"
173
+ ```
174
+
175
+ which should be enough for most use cases.
176
+
177
+ 5. Develop the features in your branch.
178
+
179
+ As you work on your code, you should make sure the test suite
180
+ passes. Run the tests impacted by your changes like this:
181
+
182
+ ```bash
183
+ pytest tests/<TEST_TO_RUN>.py
184
+ ```
185
+
186
+ For more information about tests, check out the
187
+ [Testing](https://huggingface.co/docs/transformers/testing) guide.
188
+
189
+ 🤗 Transformers relies on `black` and `ruff` to format its source code
190
+ consistently. After you make changes, apply automatic style corrections and code verifications
191
+ that can't be automated in one go with:
192
+
193
+ ```bash
194
+ make fixup
195
+ ```
196
+
197
+ This target is also optimized to only work with files modified by the PR you're working on.
198
+
199
+ If you prefer to run the checks one after the other, the following command applies the
200
+ style corrections:
201
+
202
+ ```bash
203
+ make style
204
+ ```
205
+
206
+ 🤗 Transformers also uses `ruff` and a few custom scripts to check for coding mistakes. Quality
207
+ controls are run by the CI, but you can run the same checks with:
208
+
209
+ ```bash
210
+ make quality
211
+ ```
212
+
213
+ Finally, we have a lot of scripts to make sure we don't forget to update
214
+ some files when adding a new model. You can run these scripts with:
215
+
216
+ ```bash
217
+ make repo-consistency
218
+ ```
219
+
220
+ To learn more about those checks and how to fix any issues with them, check out the
221
+ [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide.
222
+
223
+ If you're modifying documents under the `docs/source` directory, make sure the documentation can still be built. This check will also run in the CI when you open a pull request. To run a local check
224
+ make sure you install the [documentation builder](https://github.com/huggingface/doc-builder).
225
+
226
+ ```bash
227
+ pip install hf-doc-builder
228
+ ```
229
+
230
+ Run the following command from the root of the repository:
231
+
232
+ ```bash
233
+ doc-builder build transformers docs/source/en --build_dir ~/tmp/test-build
234
+ ```
235
+
236
+ This will build the documentation in the `~/tmp/test-build` folder where you can inspect the generated
237
+ Markdown files with your favorite editor. You can also preview the docs on GitHub when you open a pull request.
238
+
239
+ Once you're happy with your changes, add the changed files with `git add` and
240
+ record your changes locally with `git commit`:
241
+
242
+ ```bash
243
+ git add modified_file.py
244
+ git commit
245
+ ```
246
+
247
+ Please remember to write [good commit
248
+ messages](https://chris.beams.io/posts/git-commit/) to clearly communicate the changes you made!
249
+
250
+ To keep your copy of the code up to date with the original
251
+ repository, rebase your branch on `upstream/branch` *before* you open a pull request or if requested by a maintainer:
252
+
253
+ ```bash
254
+ git fetch upstream
255
+ git rebase upstream/main
256
+ ```
257
+
258
+ Push your changes to your branch:
259
+
260
+ ```bash
261
+ git push -u origin a-descriptive-name-for-my-changes
262
+ ```
263
+
264
+ If you've already opened a pull request, you'll need to force push with the `--force` flag. Otherwise, if the pull request hasn't been opened yet, you can just push your changes normally.
265
+
266
+ 6. Now you can go to your fork of the repository on GitHub and click on **Pull Request** to open a pull request. Make sure you tick off all the boxes on our [checklist](#pull-request-checklist) below. When you're ready, you can send your changes to the project maintainers for review.
267
+
268
+ 7. It's ok if maintainers request changes, it happens to our core contributors
269
+ too! So everyone can see the changes in the pull request, work in your local
270
+ branch and push the changes to your fork. They will automatically appear in
271
+ the pull request.
272
+
273
+ ### Pull request checklist
274
+
275
+ ☐ The pull request title should summarize your contribution.<br>
276
+ ☐ If your pull request addresses an issue, please mention the issue number in the pull
277
+ request description to make sure they are linked (and people viewing the issue know you
278
+ are working on it).<br>
279
+ ☐ To indicate a work in progress please prefix the title with `[WIP]`. These are
280
+ useful to avoid duplicated work, and to differentiate it from PRs ready to be merged.<br>
281
+ ☐ Make sure existing tests pass.<br>
282
+ ☐ If adding a new feature, also add tests for it.<br>
283
+ - If you are adding a new model, make sure you use
284
+ `ModelTester.all_model_classes = (MyModel, MyModelWithLMHead,...)` to trigger the common tests.
285
+ - If you are adding new `@slow` tests, make sure they pass using
286
+ `RUN_SLOW=1 python -m pytest tests/models/my_new_model/test_my_new_model.py`.
287
+ - If you are adding a new tokenizer, write tests and make sure
288
+ `RUN_SLOW=1 python -m pytest tests/models/{your_model_name}/test_tokenization_{your_model_name}.py` passes.
289
+ - CircleCI does not run the slow tests, but GitHub Actions does every night!<br>
290
+
291
+ ☐ All public methods must have informative docstrings (see
292
+ [`modeling_bert.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py)
293
+ for an example).<br>
294
+ ☐ Due to the rapidly growing repository, don't add any images, videos and other
295
+ non-text files that'll significantly weigh down the repository. Instead, use a Hub
296
+ repository such as [`hf-internal-testing`](https://huggingface.co/hf-internal-testing)
297
+ to host these files and reference them by URL. We recommend placing documentation
298
+ related images in the following repository:
299
+ [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images).
300
+ You can open a PR on this dataset repository and ask a Hugging Face member to merge it.
301
+
302
+ For more information about the checks run on a pull request, take a look at our [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide.
303
+
304
+ ### Tests
305
+
306
+ An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
307
+ the [tests](https://github.com/huggingface/transformers/tree/main/tests) folder and examples tests in the
308
+ [examples](https://github.com/huggingface/transformers/tree/main/examples) folder.
309
+
310
+ We like `pytest` and `pytest-xdist` because it's faster. From the root of the
311
+ repository, specify a *path to a subfolder or a test file* to run the test:
312
+
313
+ ```bash
314
+ python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model
315
+ ```
316
+
317
+ Similarly, for the `examples` directory, specify a *path to a subfolder or test file* to run the test. For example, the following command tests the text classification subfolder in the PyTorch `examples` directory:
318
+
319
+ ```bash
320
+ pip install -r examples/xxx/requirements.txt # only needed the first time
321
+ python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification
322
+ ```
323
+
324
+ In fact, this is actually how our `make test` and `make test-examples` commands are implemented (not including the `pip install`)!
325
+
326
+ You can also specify a smaller set of tests in order to test only the feature
327
+ you're working on.
328
+
329
+ By default, slow tests are skipped but you can set the `RUN_SLOW` environment variable to
330
+ `yes` to run them. This will download many gigabytes of models so make sure you
331
+ have enough disk space, a good internet connection or a lot of patience!
332
+
333
+ <Tip warning={true}>
334
+
335
+ Remember to specify a *path to a subfolder or a test file* to run the test. Otherwise, you'll run all the tests in the `tests` or `examples` folder, which will take a very long time!
336
+
337
+ </Tip>
338
+
339
+ ```bash
340
+ RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model
341
+ RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification
342
+ ```
343
+
344
+ Like the slow tests, there are other environment variables available which are not enabled by default during testing:
345
+ - `RUN_CUSTOM_TOKENIZERS`: Enables tests for custom tokenizers.
346
+
347
+ More environment variables and additional information can be found in the [testing_utils.py](https://github.com/huggingface/transformers/blob/main/src/transformers/testing_utils.py).
348
+
349
+ 🤗 Transformers uses `pytest` as a test runner only. It doesn't use any
350
+ `pytest`-specific features in the test suite itself.
351
+
352
+ This means `unittest` is fully supported. Here's how to run tests with
353
+ `unittest`:
354
+
355
+ ```bash
356
+ python -m unittest discover -s tests -t . -v
357
+ python -m unittest discover -s examples -t examples -v
358
+ ```
359
+
360
+ ### Style guide
361
+
362
+ For documentation strings, 🤗 Transformers follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html).
363
+ Check our [documentation writing guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification)
364
+ for more information.
365
+
366
+ ### Develop on Windows
367
+
368
+ On Windows (unless you're working in [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/) or WSL), you need to configure git to transform Windows `CRLF` line endings to Linux `LF` line endings:
369
+
370
+ ```bash
371
+ git config core.autocrlf input
372
+ ```
373
+
374
+ One way to run the `make` command on Windows is with MSYS2:
375
+
376
+ 1. [Download MSYS2](https://www.msys2.org/), and we assume it's installed in `C:\msys64`.
377
+ 2. Open the command line `C:\msys64\msys2.exe` (it should be available from the **Start** menu).
378
+ 3. Run in the shell: `pacman -Syu` and install `make` with `pacman -S make`.
379
+ 4. Add `C:\msys64\usr\bin` to your PATH environment variable.
380
+
381
+ You can now use `make` from any terminal (PowerShell, cmd.exe, etc.)! 🎉
382
+
383
+ ### Sync a forked repository with upstream main (the Hugging Face repository)
384
+
385
+ When updating the main branch of a forked repository, please follow these steps to avoid pinging the upstream repository which adds reference notes to each upstream PR, and sends unnecessary notifications to the developers involved in these PRs.
386
+
387
+ 1. When possible, avoid syncing with the upstream using a branch and PR on the forked repository. Instead, merge directly into the forked main.
388
+ 2. If a PR is absolutely necessary, use the following steps after checking out your branch:
389
+
390
+ ```bash
391
+ git checkout -b your-branch-for-syncing
392
+ git pull --squash --no-commit upstream main
393
+ git commit -m '<your message without GitHub references>'
394
+ git push --set-upstream origin your-branch-for-syncing
395
+ ```
transformers/ISSUES.md ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2020 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # How To Request Support
18
+
19
+ This is an Open Source Project so please be mindful that like in any other project of this kind there is no obligation to answer all requests for help.
20
+
21
+ However, we want to encourage you to ask for help whenever you think it's needed! We are happy about every question we get because it allows us to better understand your needs, possible misunderstandings, and most importantly a way for you to help us make this library better. That being said, this document's main purpose is to provide guidelines at how you can formulate your requests to increase your chances to be understood and to get support.
22
+
23
+ There are two main venues to receive support: [the forums](https://discuss.huggingface.co/) and [the GitHub issues](https://github.com/huggingface/transformers/issues).
24
+
25
+ ## The Forums
26
+
27
+ [The user forums](https://discuss.huggingface.co/) are supported by the wide community of the library users and backed up by developers when needed.
28
+
29
+ If you have a difficulty with deploying this library or some questions, or you'd like to discuss a new feature, please first consider discussing those things at the forums. Only when you feel your subject matter has been crystallized and you still need support from the library developers do proceed to file an [issue](https://github.com/huggingface/transformers/issues).
30
+
31
+ In particular all "Please explain" questions or objectively very user-specific feature requests belong to the forums. Here are some example of such questions:
32
+
33
+ * "I would like to use a BertModel within a RL-Agent for a customer support service. How can I use a BertForMaskedLM in my ChatBotModel?"
34
+
35
+ * "Could you please explain why T5 has no positional embedding matrix under T5Model?"
36
+
37
+ * "How should I set my generation parameters for translation?"
38
+
39
+ * "How to train T5 on De->En translation?"
40
+
41
+
42
+ ## The GitHub Issues
43
+
44
+ Everything which hints at a bug should be opened as an [issue](https://github.com/huggingface/transformers/issues).
45
+
46
+ You are not required to read the following guidelines before opening an issue. However, if you notice that your issue doesn't get any replies, chances are that the developers have one or several difficulties with its quality. In this case, reading the following points and adjusting your issue accordingly could help.
47
+
48
+ 1. Before posting an issue, first search for already posted issues, since chances are someone has already asked a similar question before you.
49
+
50
+ If you use Google your search query should be:
51
+
52
+ ```
53
+ "huggingface" "transformers" your query
54
+ ```
55
+
56
+ The first two quoted words tell Google to limit the search to the context of the Huggingface Transformers. The remainder is your query - most commonly this would be the error message the software fails with. We will go deeper into details shortly.
57
+
58
+ The results of such a query will typically match GitHub issues, Hugging Face forums, StackExchange, and blogs.
59
+
60
+ If you find relevant hints, you may choose to continue the discussion there if you have follow up questions.
61
+
62
+ If what you found is similar but doesn't quite answer your problem, please, post a new issue and do include links to similar issues or forum discussions you may have found.
63
+
64
+ Let's look at some examples:
65
+
66
+ The error message, often referred to as an assertion, tells us what went wrong. Here is an example of an assertion:
67
+
68
+ ```python
69
+ Traceback (most recent call last):
70
+ File "<string>", line 1, in <module>
71
+ File "/transformers/src/transformers/__init__.py", line 34, in <module>
72
+ from . import dependency_versions_check
73
+ File "/transformers/src/transformers/dependency_versions_check.py", line 34, in <module>
74
+ from .utils import is_tokenizers_available
75
+ File "/transformers/src/transformers/utils/import_utils.py", line 40, in <module>
76
+ from tqdm.auto import tqdm
77
+ ModuleNotFoundError: No module named 'tqdm.auto'
78
+ ```
79
+
80
+ and it typically includes a traceback, so that we can see the full stack of calls the program made before it fails. This gives us the context to know why the program failed.
81
+
82
+ Going back to the above example. If you received this error search, look at the very last line of the error which is:
83
+
84
+ ```python
85
+ ModuleNotFoundError: No module named 'tqdm.auto'
86
+ ```
87
+
88
+ And now we can use it to do the searching on your favorite search engine:
89
+
90
+ 1. first for `"huggingface" "transformers" "ModuleNotFoundError: No module named 'tqdm.auto'"`
91
+ 2. if you don't find relevant results, then search for just `"ModuleNotFoundError: No module named 'tqdm.auto'"`
92
+ 3. and finally if nothing still comes up, then remove the outside quotes: `ModuleNotFoundError: No module named 'tqdm.auto'`
93
+
94
+ If the error includes any messages that include bits unique to your filesystem, always remove those in the search query since other users will not have the same filesystem as yours. For example:
95
+
96
+ ```bash
97
+ python -c 'open("/tmp/wrong_path.txt", "r")'
98
+ Traceback (most recent call last):
99
+ File "<string>", line 1, in <module>
100
+ FileNotFoundError: [Errno 2] No such file or directory: '/tmp/wrong_path.txt'
101
+ ```
102
+ Here you'd search for just: `"FileNotFoundError: [Errno 2] No such file or directory"`
103
+
104
+ If the local information that you removed were inside the error message and you removed them you may need to remove double quotes since your query is no longer exact. So if the error message was something like:
105
+
106
+ ```bash
107
+ ValueError: '/tmp/wrong_path.txt' cannot be found
108
+ ```
109
+
110
+ then you'd search for `"ValueError" "cannot be found"`
111
+
112
+ As you search you will notice that when you don't use quotes often the search engines will return a variety of unrelated hits, which may or may not be what you want.
113
+
114
+ Experiment with different ways and find which approach gives the most satisfactory results.
115
+
116
+ 2. Keep the issue short, providing the information that you think will aid the developers to understand your situation. Put yourself in the shoes of the person who has never seen your code or knows anything about your custom setup. This mental exercise will help to develop an intuition to what/what not to share"
117
+
118
+ 3. If there is a software failure, always provide the full traceback, for example:
119
+
120
+ ```python
121
+ $ python -c 'import transformers'
122
+ Traceback (most recent call last):
123
+ File "<string>", line 1, in <module>
124
+ File "/transformers/src/transformers/__init__.py", line 34, in <module>
125
+ from . import dependency_versions_check
126
+ File "/transformers/src/transformers/dependency_versions_check.py", line 34, in <module>
127
+ from .utils import is_tokenizers_available
128
+ File "/transformers/src/transformers/utils/import_utils.py", line 40, in <module>
129
+ from tqdm.auto import tqdm
130
+ ModuleNotFoundError: No module named 'tqdm.auto'
131
+ ```
132
+
133
+ As compared to providing just the last line of the error message, e.g.:
134
+ ```python
135
+ ModuleNotFoundError: No module named 'tqdm.auto'
136
+ ```
137
+ which is not sufficient.
138
+
139
+ If your application is running on more than one GPU (e.g. under `DistributedDataParallel`) and typically getting every log and traceback printed multiple times, please make sure that you paste only one copy of it. At times the traceback from parallel processes may get interleaved - so either disentangle these or change the loggers to log only for `local_rank==0` so that only one process logs things.
140
+
141
+ 4. When quoting a traceback, command line instructions and any type of code always enclose it in triple backticks inside the editor window, that is:
142
+
143
+ ````
144
+ ```
145
+ git clone https://github.com/huggingface/transformers
146
+ cd transformers
147
+ pip install .
148
+ ```
149
+ ````
150
+
151
+ If it's a command line with a long argument list, please consider breaking it down using backslashes and new lines. Here is an example of a good command line quote:
152
+
153
+ ```bash
154
+ cd examples/seq2seq
155
+ torchrun --nproc_per_node=2 ./finetune_trainer.py \
156
+ --model_name_or_path sshleifer/distill-mbart-en-ro-12-4 --data_dir wmt_en_ro \
157
+ --output_dir output_dir --overwrite_output_dir \
158
+ --do_train --n_train 500 --num_train_epochs 1 \
159
+ --per_device_train_batch_size 1 --freeze_embeds \
160
+ --src_lang en_XX --tgt_lang ro_RO --task translation \
161
+ --fp16
162
+ ```
163
+
164
+ If you don't break it up, one has to scroll horizontally which often makes it quite difficult to quickly see what's happening.
165
+
166
+ The backslashes allow us to copy the command directly into the console to run it, without needing to edit it.
167
+
168
+ 5. Include only the important information that you think will help the developer to quickly identify the problem.
169
+
170
+ For example applications often create huge amounts of logs. Ask yourself whether providing all or parts of the log is useful.
171
+
172
+ Pasting a 100-1000 lines of log into the issue is an immediate turn off, since it will take a lot of time to figure out where the pertinent parts of the log are.
173
+
174
+ Attaching a full log can be helpful if it's done as an attachment, if it's enclosed in the following html code in the comment editor window:
175
+
176
+ ```
177
+ <details>
178
+ <summary>Full log</summary>
179
+ <pre>
180
+
181
+ many
182
+ lines
183
+ go
184
+ here
185
+
186
+ </pre>
187
+ </details>
188
+ ```
189
+
190
+ which would result in the following entry, which can be opened if desired, but otherwise takes little space.
191
+
192
+ <details>
193
+ <summary>Full log</summary>
194
+ <pre>
195
+ many
196
+ lines
197
+ go
198
+ here
199
+ </pre>
200
+ </details>
201
+
202
+ You could also provide a link to a pastebin service, but this is less beneficial since those links tend to expire quickly and future readers of your issue might not be able to access that log file anymore and may lack some context.
203
+
204
+ 6. If this is an issue in your code, do try to reduce that code to a minimal example that still demonstrates the problem. Please ask at the forums if you have a hard time figuring how to do that. Please realize that we don't have the luxury of having time to try and understand all of your custom code.
205
+
206
+ If you really tried to make a short reproducible code but couldn't figure it out, it might be that having a traceback will give the developer enough information to know what's going on. But if it is not enough and we can't reproduce the problem, we can't really solve it.
207
+
208
+ Do not despair if you can't figure it out from the beginning, just share what you can and perhaps someone else will be able to help you at the forums.
209
+
210
+ If your setup involves any custom datasets, the best way to help us reproduce the problem is to create a [Google Colab notebook](https://colab.research.google.com/) that demonstrates the issue and once you verify that the issue still exists, include a link to that notebook in the Issue. Just make sure that you don't copy and paste the location bar url of the open notebook - as this is private and we won't be able to open it. Instead, you need to click on `Share` in the right upper corner of the notebook, select `Get Link` and then copy and paste the public link it will give to you.
211
+
212
+ 7. If you forked off some of this project's code or example applications, please, do not ask us to go into your code repository and figure out what you may have done. The code is already very complex and unless there is an easy way to do a diff and it's a small diff, it won't be possible to find someone with time on their hands to make a lengthy investigation. Albeit, you might find someone at the forums who will be generous to do this for you.
213
+
214
+ 8. Before reporting an issue, first, always try to update your environment to the latest official version of this library. We have no resources to go and debug older revisions, which could easily have bugs that have been fixed in the latest released version.
215
+
216
+ We understand that this is not always possible, especially when APIs change, in which case file an issue against the highest library version your environment can support.
217
+
218
+ Of course, if you upgrade the library, always retest that the problem is still there.
219
+
220
+ 9. Please do not ask us to reproduce an issue with your custom data, since we don't have it. So, either you should use some existing dataset supported by HF datasets or you need to supply a code that generates a small sample on the fly, or some another quick and simple way to get it.
221
+
222
+ Please do not send us any non-public domain data that may require a license or a permission to be used.
223
+
224
+ 10. Do not tag multiple developers on the issue unless you know this is expected, either because you asked them and they gave you an explicit permission to tag them or the issue template instructs you to do so.
225
+
226
+ The "who to tag for what domain" part of the issue template is there to help users direct their questions to the right developers who are designated maintainers of project's specific domains. They can then decide at their own discretion to tag other developers if they feel it'd help move the issue forward.
227
+
228
+ We currently don't have a triage service and we trust your capacity to identify the right domain and thus the persons to tag in your issue. If you are not sure, please use the forums to ask for guidance.
229
+
230
+ When in doubt, err on the side of not tagging a given person. If you tag multiple people out of context or permission don't be surprised if you get no response at all. Please remember that every time you tag someone, they get a notification and you're taking their time without their permission. Please be sensitive to that.
231
+
232
+ If you got helped by one of the developers in the past please don't tag them in future issues, unless they are listed in the issue template for the domain you are asking about or that developer gave you an explicit permission to tag them in future issues.
233
+
234
+ If you see a certain developer doing multiple and/or recent commits into a specific area of the project that you feel is relevant to your issue, it is not a good reason to tag them. Various developers may be fixing things that prevent them from moving forward, but often their work is focused on a totally different domain. And while they may or may not know how to help you with the problem at hand, it would benefit the whole community much more if they focus on the domain of their unique expertise.
235
+
236
+ 11. Use the Edit button. Take your time, and re-read and improve the wording and formatting to make your posts and comments as easy to understand as possible.
237
+
238
+ Avoid posting multiple comments in a row, as each comment generates a notification for the developers tagged in that issue. If you happened to post multiple comments in a row, and nobody followed up yet - consider merging those into one or a few comments while editing the combined content to be coherent.
239
+
240
+ If you choose to edit your older comments after others posted follow up comments you need to be aware that your modifications might not be noticed, so if it's not a typo fixing, try to write a new comment flagging that something has been changed in the previous comments.
241
+
242
+ For example, the very first comment is the most important one. If while the thread unfolds you realize that things aren't as they seemed to you originally you may want to edit the first post to reflect the up-to-date understanding of the issue at hand so that it helps those who read your issue in the future quickly understand what's going on and not need to sift through dozens of comments. It also helps to indicate that the post was edited. So, those reading the thread later can understand why there might be certain discontinuity in the information flow.
243
+
244
+ Use bullets and items if you have lists of items and the outcome improves overall readability.
245
+
246
+ Use backticks to refer to class and function names, e.g. `BartModel` and `generate` as these stand out and improve the speed of a reader's comprehension.
247
+
248
+ Try not use italics and bold text too much as these often make the text more difficult to read.
249
+
250
+
251
+ 12. If you are cross-referencing a specific comment in a given thread or another issue, always link to that specific comment, rather than using the issue link. If you do the latter it could be quite impossible to find which specific comment you're referring to.
252
+
253
+ To get the link to the specific comment do not copy the url from the location bar of your browser, but instead, click the `...` icon in the upper right corner of the comment and then select "Copy Link".
254
+
255
+ For example the first link is a link to an issue, and the second to a specific comment in the same issue:
256
+
257
+ 1. https://github.com/huggingface/transformers/issues/9257
258
+ 2. https://github.com/huggingface/transformers/issues/9257#issuecomment-749945162
259
+
260
+
261
+ 13. If you are replying to a last comment, it's totally fine to make your reply with just your comment in it. The readers can follow the information flow here.
262
+
263
+ But if you're replying to a comment that happened some comments back it's always a good practice to quote just the relevant lines you're replying it. The `>` is used for quoting, or you can always use the menu to do so. For example your editor box will look like:
264
+
265
+ ```
266
+ > How big is your GPU cluster?
267
+
268
+ Our cluster is made of 256 GPUs.
269
+ ```
270
+
271
+ If you are addressing multiple comments, quote the relevant parts of each before your answer. Some people use the same comment to do multiple replies, others separate them into separate comments. Either way works. The latter approach helps for linking to a specific comment.
272
+
273
+ In general the best way to figure out what works the best is learn from issues posted by other people - see which issues get great responses and which get little to no response - observe what the posters who received great responses did differently from those who did not.
274
+
275
+ Thank you for reading this somewhat lengthy document. We would like to conclude that these are not absolute rules, but a friendly advice that will help maximize the chances for us to understand what you are trying to communicate, reproduce the problem then resolve it to your satisfaction and the benefit of the whole community.
276
+
277
+ If after reading this document there are remaining questions on how and why or there is a need for further elucidation, please, don't hesitate to ask your question in [this thread](https://discuss.huggingface.co/t/how-to-request-support/3128).
transformers/LICENSE ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2018- The Hugging Face team. All rights reserved.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
transformers/Makefile ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: deps_table_update modified_only_fixup extra_style_checks quality style fixup fix-copies test test-examples benchmark
2
+
3
+ # make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!)
4
+ export PYTHONPATH = src
5
+
6
+ check_dirs := examples tests src utils
7
+
8
+ exclude_folders := ""
9
+
10
+ modified_only_fixup:
11
+ @current_branch=$$(git branch --show-current); \
12
+ if [ "$$current_branch" = "main" ]; then \
13
+ echo "On main branch, running 'style' target instead..."; \
14
+ $(MAKE) style; \
15
+ else \
16
+ modified_py_files=$$(python utils/get_modified_files.py $(check_dirs)); \
17
+ if [ -n "$$modified_py_files" ]; then \
18
+ echo "Checking/fixing files: $${modified_py_files}"; \
19
+ ruff check $${modified_py_files} --fix --exclude $(exclude_folders); \
20
+ ruff format $${modified_py_files} --exclude $(exclude_folders); \
21
+ else \
22
+ echo "No library .py files were modified"; \
23
+ fi; \
24
+ fi
25
+
26
+ # Update src/transformers/dependency_versions_table.py
27
+
28
+ deps_table_update:
29
+ @python setup.py deps_table_update
30
+
31
+ deps_table_check_updated:
32
+ @md5sum src/transformers/dependency_versions_table.py > md5sum.saved
33
+ @python setup.py deps_table_update
34
+ @md5sum -c --quiet md5sum.saved || (printf "\nError: the version dependency table is outdated.\nPlease run 'make fixup' or 'make style' and commit the changes.\n\n" && exit 1)
35
+ @rm md5sum.saved
36
+
37
+ # autogenerating code
38
+
39
+ autogenerate_code: deps_table_update
40
+
41
+ # Check that the repo is in a good state
42
+
43
+ repo-consistency:
44
+ python utils/check_copies.py
45
+ python utils/check_modular_conversion.py
46
+ python utils/check_dummies.py
47
+ python utils/check_repo.py
48
+ python utils/check_inits.py
49
+ python utils/check_pipeline_typing.py
50
+ python utils/check_config_docstrings.py
51
+ python utils/check_config_attributes.py
52
+ python utils/check_doctest_list.py
53
+ python utils/update_metadata.py --check-only
54
+ python utils/check_docstrings.py
55
+
56
+ # this target runs checks on all files
57
+
58
+ quality:
59
+ @python -c "from transformers import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1)
60
+ ruff check $(check_dirs) setup.py conftest.py
61
+ ruff format --check $(check_dirs) setup.py conftest.py
62
+ python utils/sort_auto_mappings.py --check_only
63
+ python utils/check_doc_toc.py
64
+ python utils/check_docstrings.py --check_all
65
+
66
+
67
+ # Format source code automatically and check is there are any problems left that need manual fixing
68
+
69
+ extra_style_checks:
70
+ python utils/sort_auto_mappings.py
71
+ python utils/check_doc_toc.py --fix_and_overwrite
72
+
73
+ # this target runs checks on all files and potentially modifies some of them
74
+
75
+ style:
76
+ ruff check $(check_dirs) setup.py conftest.py --fix --exclude $(exclude_folders)
77
+ ruff format $(check_dirs) setup.py conftest.py --exclude $(exclude_folders)
78
+ ${MAKE} autogenerate_code
79
+ ${MAKE} extra_style_checks
80
+
81
+ # Super fast fix and check target that only works on relevant modified files since the branch was made
82
+
83
+ fixup: modified_only_fixup extra_style_checks autogenerate_code repo-consistency
84
+
85
+ # Make marked copies of snippets of codes conform to the original
86
+
87
+ fix-copies:
88
+ python utils/check_copies.py --fix_and_overwrite
89
+ python utils/check_modular_conversion.py --fix_and_overwrite
90
+ python utils/check_dummies.py --fix_and_overwrite
91
+ python utils/check_pipeline_typing.py --fix_and_overwrite
92
+ python utils/check_doctest_list.py --fix_and_overwrite
93
+ python utils/check_docstrings.py --fix_and_overwrite
94
+
95
+ # Run tests for the library
96
+
97
+ test:
98
+ python -m pytest -n auto --dist=loadfile -s -v ./tests/
99
+
100
+ # Run tests for examples
101
+
102
+ test-examples:
103
+ python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/
104
+
105
+ # Run benchmark
106
+
107
+ benchmark:
108
+ python3 benchmark/benchmark.py --config-dir benchmark/config --config-name generation --commit=diff backend.model=google/gemma-2b backend.cache_implementation=null,static backend.torch_compile=false,true --multirun
109
+
110
+ # Run tests for SageMaker DLC release
111
+
112
+ test-sagemaker: # install sagemaker dependencies in advance with pip install .[sagemaker]
113
+ TEST_SAGEMAKER=True python -m pytest -n auto -s -v ./tests/sagemaker
114
+
115
+
116
+ # Release stuff
117
+
118
+ pre-release:
119
+ python utils/release.py
120
+
121
+ pre-patch:
122
+ python utils/release.py --patch
123
+
124
+ post-release:
125
+ python utils/release.py --post_release
126
+
127
+ post-patch:
128
+ python utils/release.py --post_release --patch
129
+
130
+ build-release:
131
+ rm -rf dist
132
+ rm -rf build
133
+ python setup.py bdist_wheel
134
+ python setup.py sdist
135
+ python utils/check_build.py
transformers/README.md ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2020 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ <p align="center">
18
+ <picture>
19
+ <source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-dark.svg">
20
+ <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-light.svg">
21
+ <img alt="Hugging Face Transformers Library" src="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-light.svg" width="352" height="59" style="max-width: 100%;">
22
+ </picture>
23
+ <br/>
24
+ <br/>
25
+ </p>
26
+
27
+ <p align="center">
28
+ <a href="https://huggingface.com/models"><img alt="Checkpoints on Hub" src="https://img.shields.io/endpoint?url=https://huggingface.co/api/shields/models&color=brightgreen"></a>
29
+ <a href="https://circleci.com/gh/huggingface/transformers"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/main"></a>
30
+ <a href="https://github.com/huggingface/transformers/blob/main/LICENSE"><img alt="GitHub" src="https://img.shields.io/github/license/huggingface/transformers.svg?color=blue"></a>
31
+ <a href="https://huggingface.co/docs/transformers/index"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/transformers/index.svg?down_color=red&down_message=offline&up_message=online"></a>
32
+ <a href="https://github.com/huggingface/transformers/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/transformers.svg"></a>
33
+ <a href="https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
34
+ <a href="https://zenodo.org/badge/latestdoi/155220641"><img src="https://zenodo.org/badge/155220641.svg" alt="DOI"></a>
35
+ </p>
36
+
37
+ <h4 align="center">
38
+ <p>
39
+ <b>English</b> |
40
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_zh-hans.md">简体中文</a> |
41
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_zh-hant.md">繁體中文</a> |
42
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ko.md">한국어</a> |
43
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_es.md">Español</a> |
44
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ja.md">日本語</a> |
45
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_hd.md">हिन्दी</a> |
46
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ru.md">Русский</a> |
47
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_pt-br.md">Рortuguês</a> |
48
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_te.md">తెలుగు</a> |
49
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_fr.md">Français</a> |
50
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_de.md">Deutsch</a> |
51
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_vi.md">Tiếng Việt</a> |
52
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ar.md">العربية</a> |
53
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ur.md">اردو</a> |
54
+ </p>
55
+ </h4>
56
+
57
+ <h3 align="center">
58
+ <p>State-of-the-art pretrained models for inference and training</p>
59
+ </h3>
60
+
61
+ <h3 align="center">
62
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/transformers_as_a_model_definition.png"/>
63
+ </h3>
64
+
65
+
66
+ Transformers acts as the model-definition framework for state-of-the-art machine learning models in text, computer
67
+ vision, audio, video, and multimodal model, for both inference and training.
68
+
69
+ It centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the
70
+ pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training
71
+ frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),
72
+ and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`.
73
+
74
+ We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be
75
+ simple, customizable, and efficient.
76
+
77
+ There are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://huggingface.com/models) you can use.
78
+
79
+ Explore the [Hub](https://huggingface.com/) today to find a model and use Transformers to help you get started right away.
80
+
81
+ ## Installation
82
+
83
+ Transformers works with Python 3.9+ [PyTorch](https://pytorch.org/get-started/locally/) 2.1+, [TensorFlow](https://www.tensorflow.org/install/pip) 2.6+, and [Flax](https://flax.readthedocs.io/en/latest/) 0.4.1+.
84
+
85
+ Create and activate a virtual environment with [venv](https://docs.python.org/3/library/venv.html) or [uv](https://docs.astral.sh/uv/), a fast Rust-based Python package and project manager.
86
+
87
+ ```py
88
+ # venv
89
+ python -m venv .my-env
90
+ source .my-env/bin/activate
91
+ # uv
92
+ uv venv .my-env
93
+ source .my-env/bin/activate
94
+ ```
95
+
96
+ Install Transformers in your virtual environment.
97
+
98
+ ```py
99
+ # pip
100
+ pip install "transformers[torch]"
101
+
102
+ # uv
103
+ uv pip install "transformers[torch]"
104
+ ```
105
+
106
+ Install Transformers from source if you want the latest changes in the library or are interested in contributing. However, the *latest* version may not be stable. Feel free to open an [issue](https://github.com/huggingface/transformers/issues) if you encounter an error.
107
+
108
+ ```shell
109
+ git clone https://github.com/huggingface/transformers.git
110
+ cd transformers
111
+
112
+ # pip
113
+ pip install .[torch]
114
+
115
+ # uv
116
+ uv pip install .[torch]
117
+ ```
118
+
119
+ ## Quickstart
120
+
121
+ Get started with Transformers right away with the [Pipeline](https://huggingface.co/docs/transformers/pipeline_tutorial) API. The `Pipeline` is a high-level inference class that supports text, audio, vision, and multimodal tasks. It handles preprocessing the input and returns the appropriate output.
122
+
123
+ Instantiate a pipeline and specify model to use for text generation. The model is downloaded and cached so you can easily reuse it again. Finally, pass some text to prompt the model.
124
+
125
+ ```py
126
+ from transformers import pipeline
127
+
128
+ pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B")
129
+ pipeline("the secret to baking a really good cake is ")
130
+ [{'generated_text': 'the secret to baking a really good cake is 1) to use the right ingredients and 2) to follow the recipe exactly. the recipe for the cake is as follows: 1 cup of sugar, 1 cup of flour, 1 cup of milk, 1 cup of butter, 1 cup of eggs, 1 cup of chocolate chips. if you want to make 2 cakes, how much sugar do you need? To make 2 cakes, you will need 2 cups of sugar.'}]
131
+ ```
132
+
133
+ To chat with a model, the usage pattern is the same. The only difference is you need to construct a chat history (the input to `Pipeline`) between you and the system.
134
+
135
+ > [!TIP]
136
+ > You can also chat with a model directly from the command line.
137
+ > ```shell
138
+ > transformers chat Qwen/Qwen2.5-0.5B-Instruct
139
+ > ```
140
+
141
+ ```py
142
+ import torch
143
+ from transformers import pipeline
144
+
145
+ chat = [
146
+ {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
147
+ {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
148
+ ]
149
+
150
+ pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", torch_dtype=torch.bfloat16, device_map="auto")
151
+ response = pipeline(chat, max_new_tokens=512)
152
+ print(response[0]["generated_text"][-1]["content"])
153
+ ```
154
+
155
+ Expand the examples below to see how `Pipeline` works for different modalities and tasks.
156
+
157
+ <details>
158
+ <summary>Automatic speech recognition</summary>
159
+
160
+ ```py
161
+ from transformers import pipeline
162
+
163
+ pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
164
+ pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
165
+ {'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
166
+ ```
167
+
168
+ </details>
169
+
170
+ <details>
171
+ <summary>Image classification</summary>
172
+
173
+ <h3 align="center">
174
+ <a><img src="https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png"></a>
175
+ </h3>
176
+
177
+ ```py
178
+ from transformers import pipeline
179
+
180
+ pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
181
+ pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
182
+ [{'label': 'macaw', 'score': 0.997848391532898},
183
+ {'label': 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
184
+ 'score': 0.0016551691805943847},
185
+ {'label': 'lorikeet', 'score': 0.00018523589824326336},
186
+ {'label': 'African grey, African gray, Psittacus erithacus',
187
+ 'score': 7.85409429227002e-05},
188
+ {'label': 'quail', 'score': 5.502637941390276e-05}]
189
+ ```
190
+
191
+ </details>
192
+
193
+ <details>
194
+ <summary>Visual question answering</summary>
195
+
196
+
197
+ <h3 align="center">
198
+ <a><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg"></a>
199
+ </h3>
200
+
201
+ ```py
202
+ from transformers import pipeline
203
+
204
+ pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
205
+ pipeline(
206
+ image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
207
+ question="What is in the image?",
208
+ )
209
+ [{'answer': 'statue of liberty'}]
210
+ ```
211
+
212
+ </details>
213
+
214
+ ## Why should I use Transformers?
215
+
216
+ 1. Easy-to-use state-of-the-art models:
217
+ - High performance on natural language understanding & generation, computer vision, audio, video, and multimodal tasks.
218
+ - Low barrier to entry for researchers, engineers, and developers.
219
+ - Few user-facing abstractions with just three classes to learn.
220
+ - A unified API for using all our pretrained models.
221
+
222
+ 1. Lower compute costs, smaller carbon footprint:
223
+ - Share trained models instead of training from scratch.
224
+ - Reduce compute time and production costs.
225
+ - Dozens of model architectures with 1M+ pretrained checkpoints across all modalities.
226
+
227
+ 1. Choose the right framework for every part of a models lifetime:
228
+ - Train state-of-the-art models in 3 lines of code.
229
+ - Move a single model between PyTorch/JAX/TF2.0 frameworks at will.
230
+ - Pick the right framework for training, evaluation, and production.
231
+
232
+ 1. Easily customize a model or an example to your needs:
233
+ - We provide examples for each architecture to reproduce the results published by its original authors.
234
+ - Model internals are exposed as consistently as possible.
235
+ - Model files can be used independently of the library for quick experiments.
236
+
237
+ <a target="_blank" href="https://huggingface.co/enterprise">
238
+ <img alt="Hugging Face Enterprise Hub" src="https://github.com/user-attachments/assets/247fb16d-d251-4583-96c4-d3d76dda4925">
239
+ </a><br>
240
+
241
+ ## Why shouldn't I use Transformers?
242
+
243
+ - This library is not a modular toolbox of building blocks for neural nets. The code in the model files is not refactored with additional abstractions on purpose, so that researchers can quickly iterate on each of the models without diving into additional abstractions/files.
244
+ - The training API is optimized to work with PyTorch models provided by Transformers. For generic machine learning loops, you should use another library like [Accelerate](https://huggingface.co/docs/accelerate).
245
+ - The [example scripts]((https://github.com/huggingface/transformers/tree/main/examples)) are only *examples*. They may not necessarily work out-of-the-box on your specific use case and you'll need to adapt the code for it to work.
246
+
247
+ ## 100 projects using Transformers
248
+
249
+ Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the
250
+ Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone
251
+ else to build their dream projects.
252
+
253
+ In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the
254
+ community with the [awesome-transformers](./awesome-transformers.md) page which lists 100
255
+ incredible projects built with Transformers.
256
+
257
+ If you own or use a project that you believe should be part of the list, please open a PR to add it!
258
+
259
+ ## Example models
260
+
261
+ You can test most of our models directly on their [Hub model pages](https://huggingface.co/models).
262
+
263
+ Expand each modality below to see a few example models for various use cases.
264
+
265
+ <details>
266
+ <summary>Audio</summary>
267
+
268
+ - Audio classification with [Whisper](https://huggingface.co/openai/whisper-large-v3-turbo)
269
+ - Automatic speech recognition with [Moonshine](https://huggingface.co/UsefulSensors/moonshine)
270
+ - Keyword spotting with [Wav2Vec2](https://huggingface.co/superb/wav2vec2-base-superb-ks)
271
+ - Speech to speech generation with [Moshi](https://huggingface.co/kyutai/moshiko-pytorch-bf16)
272
+ - Text to audio with [MusicGen](https://huggingface.co/facebook/musicgen-large)
273
+ - Text to speech with [Bark](https://huggingface.co/suno/bark)
274
+
275
+ </details>
276
+
277
+ <details>
278
+ <summary>Computer vision</summary>
279
+
280
+ - Automatic mask generation with [SAM](https://huggingface.co/facebook/sam-vit-base)
281
+ - Depth estimation with [DepthPro](https://huggingface.co/apple/DepthPro-hf)
282
+ - Image classification with [DINO v2](https://huggingface.co/facebook/dinov2-base)
283
+ - Keypoint detection with [SuperGlue](https://huggingface.co/magic-leap-community/superglue_outdoor)
284
+ - Keypoint matching with [SuperGlue](https://huggingface.co/magic-leap-community/superglue)
285
+ - Object detection with [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r50vd)
286
+ - Pose Estimation with [VitPose](https://huggingface.co/usyd-community/vitpose-base-simple)
287
+ - Universal segmentation with [OneFormer](https://huggingface.co/shi-labs/oneformer_ade20k_swin_large)
288
+ - Video classification with [VideoMAE](https://huggingface.co/MCG-NJU/videomae-large)
289
+
290
+ </details>
291
+
292
+ <details>
293
+ <summary>Multimodal</summary>
294
+
295
+ - Audio or text to text with [Qwen2-Audio](https://huggingface.co/Qwen/Qwen2-Audio-7B)
296
+ - Document question answering with [LayoutLMv3](https://huggingface.co/microsoft/layoutlmv3-base)
297
+ - Image or text to text with [Qwen-VL](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct)
298
+ - Image captioning [BLIP-2](https://huggingface.co/Salesforce/blip2-opt-2.7b)
299
+ - OCR-based document understanding with [GOT-OCR2](https://huggingface.co/stepfun-ai/GOT-OCR-2.0-hf)
300
+ - Table question answering with [TAPAS](https://huggingface.co/google/tapas-base)
301
+ - Unified multimodal understanding and generation with [Emu3](https://huggingface.co/BAAI/Emu3-Gen)
302
+ - Vision to text with [Llava-OneVision](https://huggingface.co/llava-hf/llava-onevision-qwen2-0.5b-ov-hf)
303
+ - Visual question answering with [Llava](https://huggingface.co/llava-hf/llava-1.5-7b-hf)
304
+ - Visual referring expression segmentation with [Kosmos-2](https://huggingface.co/microsoft/kosmos-2-patch14-224)
305
+
306
+ </details>
307
+
308
+ <details>
309
+ <summary>NLP</summary>
310
+
311
+ - Masked word completion with [ModernBERT](https://huggingface.co/answerdotai/ModernBERT-base)
312
+ - Named entity recognition with [Gemma](https://huggingface.co/google/gemma-2-2b)
313
+ - Question answering with [Mixtral](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1)
314
+ - Summarization with [BART](https://huggingface.co/facebook/bart-large-cnn)
315
+ - Translation with [T5](https://huggingface.co/google-t5/t5-base)
316
+ - Text generation with [Llama](https://huggingface.co/meta-llama/Llama-3.2-1B)
317
+ - Text classification with [Qwen](https://huggingface.co/Qwen/Qwen2.5-0.5B)
318
+
319
+ </details>
320
+
321
+ ## Citation
322
+
323
+ We now have a [paper](https://www.aclweb.org/anthology/2020.emnlp-demos.6/) you can cite for the 🤗 Transformers library:
324
+ ```bibtex
325
+ @inproceedings{wolf-etal-2020-transformers,
326
+ title = "Transformers: State-of-the-Art Natural Language Processing",
327
+ author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush",
328
+ booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
329
+ month = oct,
330
+ year = "2020",
331
+ address = "Online",
332
+ publisher = "Association for Computational Linguistics",
333
+ url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6",
334
+ pages = "38--45"
335
+ }
336
+ ```
transformers/SECURITY.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Hugging Face Hub, remote artefacts, and remote code
4
+
5
+ Transformers is open-source software that is tightly coupled to the Hugging Face Hub. While you have the ability to use it
6
+ offline with pre-downloaded model weights, it provides a very simple way to download, use, and manage models locally.
7
+
8
+ When downloading artefacts that have been uploaded by others on any platform, you expose yourself to risks. Please
9
+ read below for the security recommendations in order to keep your runtime and local environment safe.
10
+
11
+ ### Remote artefacts
12
+
13
+ Models uploaded on the Hugging Face Hub come in different formats. We heavily recommend uploading and downloading
14
+ models in the [`safetensors`](https://github.com/huggingface/safetensors) format (which is the default prioritized
15
+ by the transformers library), as developed specifically to prevent arbitrary code execution on your system.
16
+
17
+ To avoid loading models from unsafe formats(e.g. [pickle](https://docs.python.org/3/library/pickle.html), you should use the `use_safetensors` parameter. If doing so, in the event that no .safetensors file is present, transformers will error when loading the model.
18
+
19
+ ### Remote code
20
+
21
+ #### Modeling
22
+
23
+ Transformers supports many model architectures, but is also the bridge between your Python runtime and models that
24
+ are stored in model repositories on the Hugging Face Hub.
25
+
26
+ These models require the `trust_remote_code=True` parameter to be set when using them; please **always** verify
27
+ the content of the modeling files when using this argument. We recommend setting a revision in order to ensure you
28
+ protect yourself from updates on the repository.
29
+
30
+ ## Reporting a Vulnerability
31
+
32
+ Feel free to submit vulnerability reports to [security@huggingface.co](mailto:security@huggingface.co), where someone from the HF security team will review and recommend next steps. If reporting a vulnerability specific to open source, please note [Huntr](https://huntr.com) is a vulnerability disclosure program for open source software.
transformers/awesome-transformers.md ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Awesome projects built with Transformers
2
+
3
+ This page lists awesome projects built on top of Transformers. Transformers is more than a toolkit to use pretrained
4
+ models: it's a community of projects built around it and the Hugging Face Hub. We want Transformers to enable
5
+ developers, researchers, students, professors, engineers, and anyone else to build their dream projects.
6
+
7
+ In this list, we showcase incredibly impactful and novel projects that have pushed the field forward. We celebrate
8
+ 100 of these projects as we reach the milestone of 100k stars as a community; but we're very open to pull requests
9
+ adding other projects to the list. If you believe a project should be here and it's not, then please, open a PR
10
+ to add it.
11
+
12
+ ## [gpt4all](https://github.com/nomic-ai/gpt4all)
13
+
14
+ [gpt4all](https://github.com/nomic-ai/gpt4all) is an ecosystem of open-source chatbots trained on massive collections of clean assistant data including code, stories and dialogue. It offers open-source, large language models such as LLaMA and GPT-J trained in an assistant-style.
15
+
16
+ Keywords: Open-source, LLaMa, GPT-J, instruction, assistant
17
+
18
+ ## [recommenders](https://github.com/recommenders-team/recommenders)
19
+
20
+ This repository contains examples and best practices for building recommendation systems, provided as Jupyter notebooks. It goes over several aspects required to build efficient recommendation systems: data preparation, modeling, evaluation, model selection & optimization, as well as operationalization
21
+
22
+ Keywords: Recommender systems, AzureML
23
+
24
+ ## [IOPaint](https://github.com/Sanster/IOPaint)
25
+
26
+ Image inpainting tool powered by Stable Diffusion. Remove any unwanted object, defect, people from your pictures or erase and replace anything on your pictures.
27
+
28
+ Keywords: inpainting, SD, Stable Diffusion
29
+
30
+ ## [flair](https://github.com/flairNLP/flair)
31
+
32
+ FLAIR is a powerful PyTorch NLP framework, covering several important tasks: NER, sentiment-analysis, part-of-speech tagging, text and document embeddings, among other things.
33
+
34
+ Keywords: NLP, text embedding, document embedding, biomedical, NER, PoS, sentiment-analysis
35
+
36
+ ## [mindsdb](https://github.com/mindsdb/mindsdb)
37
+
38
+ MindsDB is a low-code ML platform, which automates and integrates several ML frameworks into the data stack as "AI Tables" to streamline the integration of AI into applications, making it accessible to developers of all skill levels.
39
+
40
+ Keywords: Database, low-code, AI table
41
+
42
+ ## [langchain](https://github.com/langchain-ai/langchain)
43
+
44
+ [langchain](https://github.com/langchain-ai/langchain) is aimed at assisting in the development of apps merging both LLMs and other sources of knowledge. The library allows chaining calls to applications, creating a sequence across many tools.
45
+
46
+ Keywords: LLMs, Large Language Models, Agents, Chains
47
+
48
+ ## [LlamaIndex](https://github.com/run-llama/llama_index)
49
+
50
+ [LlamaIndex](https://github.com/run-llama/llama_index) is a project that provides a central interface to connect your LLM's with external data. It provides various kinds of indices and retrieval mechanisms to perform different LLM tasks and obtain knowledge-augmented results.
51
+
52
+ Keywords: LLMs, Large Language Models, Data Retrieval, Indices, Knowledge Augmentation
53
+
54
+ ## [ParlAI](https://github.com/facebookresearch/ParlAI)
55
+
56
+ [ParlAI](https://github.com/facebookresearch/ParlAI) is a python framework for sharing, training and testing dialogue models, from open-domain chitchat, to task-oriented dialogue, to visual question answering. It provides more than 100 datasets under the same API, a large zoo of pretrained models, a set of agents, and has several integrations.
57
+
58
+ Keywords: Dialogue, Chatbots, VQA, Datasets, Agents
59
+
60
+ ## [sentence-transformers](https://github.com/UKPLab/sentence-transformers)
61
+
62
+ This framework provides an easy method to compute dense vector representations for sentences, paragraphs, and images. The models are based on transformer networks like BERT / RoBERTa / XLM-RoBERTa etc. and achieve state-of-the-art performance in various task. Text is embedding in vector space such that similar text is close and can efficiently be found using cosine similarity.
63
+
64
+ Keywords: Dense vector representations, Text embeddings, Sentence embeddings
65
+
66
+ ## [ludwig](https://github.com/ludwig-ai/ludwig)
67
+
68
+ Ludwig is a declarative machine learning framework that makes it easy to define machine learning pipelines using a simple and flexible data-driven configuration system. Ludwig is targeted at a wide variety of AI tasks. It provides a data-driven configuration system, training, prediction, and evaluation scripts, as well as a programmatic API.
69
+
70
+ Keywords: Declarative, Data-driven, ML Framework
71
+
72
+ ## [InvokeAI](https://github.com/invoke-ai/InvokeAI)
73
+
74
+ [InvokeAI](https://github.com/invoke-ai/InvokeAI) is an engine for Stable Diffusion models, aimed at professionals, artists, and enthusiasts. It leverages the latest AI-driven technologies through CLI as well as a WebUI.
75
+
76
+ Keywords: Stable-Diffusion, WebUI, CLI
77
+
78
+ ## [PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP)
79
+
80
+ [PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP) is an easy-to-use and powerful NLP library particularly targeted at the Chinese languages. It has support for multiple pre-trained model zoos, and supports a wide-range of NLP tasks from research to industrial applications.
81
+
82
+ Keywords: NLP, Chinese, Research, Industry
83
+
84
+ ## [stanza](https://github.com/stanfordnlp/stanza)
85
+
86
+ The Stanford NLP Group's official Python NLP library. It contains support for running various accurate natural language processing tools on 60+ languages and for accessing the Java Stanford CoreNLP software from Python.
87
+
88
+ Keywords: NLP, Multilingual, CoreNLP
89
+
90
+ ## [DeepPavlov](https://github.com/deeppavlov/DeepPavlov)
91
+
92
+ [DeepPavlov](https://github.com/deeppavlov/DeepPavlov) is an open-source conversational AI library. It is designed for the development of production ready chat-bots and complex conversational systems, as well as research in the area of NLP and, particularly, of dialog systems.
93
+
94
+ Keywords: Conversational, Chatbot, Dialog
95
+
96
+ ## [alpaca-lora](https://github.com/tloen/alpaca-lora)
97
+
98
+ Alpaca-lora contains code for reproducing the Stanford Alpaca results using low-rank adaptation (LoRA). The repository provides training (fine-tuning) as well as generation scripts.
99
+
100
+ Keywords: LoRA, Parameter-efficient fine-tuning
101
+
102
+ ## [imagen-pytorch](https://github.com/lucidrains/imagen-pytorch)
103
+
104
+ An open-source Implementation of Imagen, Google's closed-source Text-to-Image Neural Network that beats DALL-E2. As of release, it is the new SOTA for text-to-image synthesis.
105
+
106
+ Keywords: Imagen, Text-to-image
107
+
108
+ ## [adapters](https://github.com/adapter-hub/adapters)
109
+
110
+ [adapters](https://github.com/adapter-hub/adapters) is an extension of HuggingFace's Transformers library, integrating adapters into state-of-the-art language models by incorporating AdapterHub, a central repository for pre-trained adapter modules. It is a drop-in replacement for transformers, which is regularly updated to stay up-to-date with the developments of transformers.
111
+
112
+ Keywords: Adapters, LoRA, Parameter-efficient fine-tuning, Hub
113
+
114
+ ## [NeMo](https://github.com/NVIDIA/NeMo)
115
+
116
+ NVIDIA [NeMo](https://github.com/NVIDIA/NeMo) is a conversational AI toolkit built for researchers working on automatic speech recognition (ASR), text-to-speech synthesis (TTS), large language models (LLMs), and natural language processing (NLP). The primary objective of [NeMo](https://github.com/NVIDIA/NeMo) is to help researchers from industry and academia to reuse prior work (code and pretrained models) and make it easier to create new https://developer.nvidia.com/conversational-ai#started.
117
+
118
+ Keywords: Conversational, ASR, TTS, LLMs, NLP
119
+
120
+ ## [Runhouse](https://github.com/run-house/runhouse)
121
+
122
+ [Runhouse](https://github.com/run-house/runhouse) allows to send code and data to any of your compute or data infra, all in Python, and continue to interact with them normally from your existing code and environment. Runhouse developers mention:
123
+
124
+ > Think of it as an expansion pack to your Python interpreter that lets it take detours to remote machines or manipulate remote data.
125
+
126
+ Keywords: MLOps, Infrastructure, Data storage, Modeling
127
+
128
+ ## [MONAI](https://github.com/Project-MONAI/MONAI)
129
+
130
+ [MONAI](https://github.com/Project-MONAI/MONAI) is a PyTorch-based, open-source framework for deep learning in healthcare imaging, part of PyTorch Ecosystem. Its ambitions are:
131
+ - developing a community of academic, industrial and clinical researchers collaborating on a common foundation;
132
+ - creating state-of-the-art, end-to-end training workflows for healthcare imaging;
133
+ - providing researchers with the optimized and standardized way to create and evaluate deep learning models.
134
+
135
+ Keywords: Healthcare imaging, Training, Evaluation
136
+
137
+ ## [simpletransformers](https://github.com/ThilinaRajapakse/simpletransformers)
138
+
139
+ Simple Transformers lets you quickly train and evaluate Transformer models. Only 3 lines of code are needed to initialize, train, and evaluate a model. It supports a wide variety of NLP tasks.
140
+
141
+ Keywords: Framework, simplicity, NLP
142
+
143
+ ## [JARVIS](https://github.com/microsoft/JARVIS)
144
+
145
+ [JARVIS](https://github.com/microsoft/JARVIS) is a system attempting to merge LLMs such as GPT-4 with the rest of the open-source ML community: leveraging up to 60 downstream models in order to perform tasks identified by the LLM.
146
+
147
+ Keywords: LLM, Agents, HF Hub
148
+
149
+ ## [transformers.js](https://github.com/huggingface/transformers.js/)
150
+
151
+ [transformers.js](https://github.com/huggingface/transformers.js/) is a JavaScript library targeted at running models from transformers directly within the browser.
152
+
153
+ Keywords: Transformers, JavaScript, browser
154
+
155
+ ## [bumblebee](https://github.com/elixir-nx/bumblebee)
156
+
157
+ Bumblebee provides pre-trained Neural Network models on top of Axon, a neural networks library for the Elixir language. It includes integration with 🤗 Models, allowing anyone to download and perform Machine Learning tasks with few lines of code.
158
+
159
+ Keywords: Elixir, Axon
160
+
161
+ ## [argilla](https://github.com/argilla-io/argilla)
162
+
163
+ Argilla is an open-source platform providing advanced NLP labeling, monitoring, and workspaces. It is compatible with many open source ecosystems such as Hugging Face, Stanza, FLAIR, and others.
164
+
165
+ Keywords: NLP, Labeling, Monitoring, Workspaces
166
+
167
+ ## [haystack](https://github.com/deepset-ai/haystack)
168
+
169
+ Haystack is an open source NLP framework to interact with your data using Transformer models and LLMs. It offers production-ready tools to quickly build complex decision making, question answering, semantic search, text generation applications, and more.
170
+
171
+ Keywords: NLP, Framework, LLM
172
+
173
+ ## [spaCy](https://github.com/explosion/spaCy)
174
+
175
+ [spaCy](https://github.com/explosion/spaCy) is a library for advanced Natural Language Processing in Python and Cython. It's built on the very latest research, and was designed from day one to be used in real products. It offers support for transformers models through its third party package, spacy-transformers.
176
+
177
+ Keywords: NLP, Framework
178
+
179
+ ## [speechbrain](https://github.com/speechbrain/speechbrain)
180
+
181
+ SpeechBrain is an open-source and all-in-one conversational AI toolkit based on PyTorch.
182
+ The goal is to create a single, flexible, and user-friendly toolkit that can be used to easily develop state-of-the-art speech technologies, including systems for speech recognition, speaker recognition, speech enhancement, speech separation, language identification, multi-microphone signal processing, and many others.
183
+
184
+ Keywords: Conversational, Speech
185
+
186
+ ## [skorch](https://github.com/skorch-dev/skorch)
187
+
188
+ Skorch is a scikit-learn compatible neural network library that wraps PyTorch. It has support for models within transformers, and tokenizers from tokenizers.
189
+
190
+ Keywords: Scikit-Learn, PyTorch
191
+
192
+ ## [bertviz](https://github.com/jessevig/bertviz)
193
+
194
+ BertViz is an interactive tool for visualizing attention in Transformer language models such as BERT, GPT2, or T5. It can be run inside a Jupyter or Colab notebook through a simple Python API that supports most Huggingface models.
195
+
196
+ Keywords: Visualization, Transformers
197
+
198
+ ## [mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax)
199
+
200
+ [mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax) is a haiku library using the xmap/pjit operators in JAX for model parallelism of transformers. This library is designed for scalability up to approximately 40B parameters on TPUv3s. It was the library used to train the GPT-J model.
201
+
202
+ Keywords: Haiku, Model parallelism, LLM, TPU
203
+
204
+ ## [deepchem](https://github.com/deepchem/deepchem)
205
+
206
+ DeepChem aims to provide a high quality open-source toolchain that democratizes the use of deep-learning in drug discovery, materials science, quantum chemistry, and biology.
207
+
208
+ Keywords: Drug discovery, Materials Science, Quantum Chemistry, Biology
209
+
210
+ ## [OpenNRE](https://github.com/thunlp/OpenNRE)
211
+
212
+ An Open-Source Package for Neural Relation Extraction (NRE). It is targeted at a wide range of users, from newcomers to relation extraction, to developers, researchers, or students.
213
+
214
+ Keywords: Neural Relation Extraction, Framework
215
+
216
+ ## [pycorrector](https://github.com/shibing624/pycorrector)
217
+
218
+ PyCorrector is a Chinese Text Error Correction Tool. It uses a language model to detect errors, pinyin feature and shape feature to correct Chinese text errors. it can be used for Chinese Pinyin and stroke input method.
219
+
220
+ Keywords: Chinese, Error correction tool, Language model, Pinyin
221
+
222
+ ## [nlpaug](https://github.com/makcedward/nlpaug)
223
+
224
+ This python library helps you with augmenting nlp for machine learning projects. It is a lightweight library featuring synthetic data generation for improving model performance, support for audio and text, and compatibility with several ecosystems (scikit-learn, pytorch, tensorflow).
225
+
226
+ Keywords: Data augmentation, Synthetic data generation, Audio, NLP
227
+
228
+ ## [dream-textures](https://github.com/carson-katri/dream-textures)
229
+
230
+ [dream-textures](https://github.com/carson-katri/dream-textures) is a library targeted at bringing stable-diffusion support within Blender. It supports several use-cases, such as image generation, texture projection, inpainting/outpainting, ControlNet, and upscaling.
231
+
232
+ Keywords: Stable-Diffusion, Blender
233
+
234
+ ## [seldon-core](https://github.com/SeldonIO/seldon-core)
235
+
236
+ Seldon core converts your ML models (Tensorflow, Pytorch, H2o, etc.) or language wrappers (Python, Java, etc.) into production REST/GRPC microservices.
237
+ Seldon handles scaling to thousands of production machine learning models and provides advanced machine learning capabilities out of the box including Advanced Metrics, Request Logging, Explainers, Outlier Detectors, A/B Tests, Canaries and more.
238
+
239
+ Keywords: Microservices, Modeling, Language wrappers
240
+
241
+ ## [open_model_zoo](https://github.com/openvinotoolkit/open_model_zoo)
242
+
243
+ This repository includes optimized deep learning models and a set of demos to expedite development of high-performance deep learning inference applications. Use these free pre-trained models instead of training your own models to speed-up the development and production deployment process.
244
+
245
+ Keywords: Optimized models, Demos
246
+
247
+ ## [ml-stable-diffusion](https://github.com/apple/ml-stable-diffusion)
248
+
249
+ ML-Stable-Diffusion is a repository by Apple bringing Stable Diffusion support to Core ML, on Apple Silicon devices. It supports stable diffusion checkpoints hosted on the Hugging Face Hub.
250
+
251
+ Keywords: Stable Diffusion, Apple Silicon, Core ML
252
+
253
+ ## [stable-dreamfusion](https://github.com/ashawkey/stable-dreamfusion)
254
+
255
+ Stable-Dreamfusion is a pytorch implementation of the text-to-3D model Dreamfusion, powered by the Stable Diffusion text-to-2D model.
256
+
257
+ Keywords: Text-to-3D, Stable Diffusion
258
+
259
+ ## [txtai](https://github.com/neuml/txtai)
260
+
261
+ [txtai](https://github.com/neuml/txtai) is an open-source platform for semantic search and workflows powered by language models. txtai builds embeddings databases, which are a union of vector indexes and relational databases enabling similarity search with SQL. Semantic workflows connect language models together into unified applications.
262
+
263
+ Keywords: Semantic search, LLM
264
+
265
+ ## [djl](https://github.com/deepjavalibrary/djl)
266
+
267
+ Deep Java Library (DJL) is an open-source, high-level, engine-agnostic Java framework for deep learning. DJL is designed to be easy to get started with and simple to use for developers. DJL provides a native Java development experience and functions like any other regular Java library. DJL offers [a Java binding](https://github.com/deepjavalibrary/djl/tree/master/extensions/tokenizers) for HuggingFace Tokenizers and easy conversion toolkit for HuggingFace model to deploy in Java.
268
+
269
+ Keywords: Java, Framework
270
+
271
+ ## [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness/)
272
+
273
+ This project provides a unified framework to test generative language models on a large number of different evaluation tasks. It has support for more than 200 tasks, and supports different ecosystems: HF Transformers, GPT-NeoX, DeepSpeed, as well as the OpenAI API.
274
+
275
+ Keywords: LLM, Evaluation, Few-shot
276
+
277
+ ## [gpt-neox](https://github.com/EleutherAI/gpt-neox)
278
+
279
+ This repository records EleutherAI's library for training large-scale language models on GPUs. The framework is based on NVIDIA's Megatron Language Model and has been augmented with techniques from DeepSpeed as well as some novel optimizations. It is focused on training multi-billion-parameter models.
280
+
281
+ Keywords: Training, LLM, Megatron, DeepSpeed
282
+
283
+ ## [muzic](https://github.com/microsoft/muzic)
284
+
285
+ Muzic is a research project on AI music that empowers music understanding and generation with deep learning and artificial intelligence. Muzic was created by researchers from Microsoft Research Asia.
286
+
287
+ Keywords: Music understanding, Music generation
288
+
289
+ ## [dalle-flow](https://github.com/jina-ai/dalle-flow)
290
+
291
+ DALL·E Flow is an interactive workflow for generating high-definition images from a text prompt. It leverages DALL·E-Mega, GLID-3 XL, and Stable Diffusion to generate image candidates, and then calls CLIP-as-service to rank the candidates w.r.t. the prompt.
292
+ The preferred candidate is fed to GLID-3 XL for diffusion, which often enriches the texture and background. Finally, the candidate is upscaled to 1024x1024 via SwinIR.
293
+
294
+ Keywords: High-definition image generation, Stable Diffusion, DALL-E Mega, GLID-3 XL, CLIP, SwinIR
295
+
296
+ ## [lightseq](https://github.com/bytedance/lightseq)
297
+
298
+ LightSeq is a high performance training and inference library for sequence processing and generation implemented in CUDA. It enables highly efficient computation of modern NLP and CV models such as BERT, GPT, Transformer, etc. It is therefore best useful for machine translation, text generation, image classification, and other sequence related tasks.
299
+
300
+ Keywords: Training, Inference, Sequence Processing, Sequence Generation
301
+
302
+ ## [LaTeX-OCR](https://github.com/lukas-blecher/LaTeX-OCR)
303
+
304
+ The goal of this project is to create a learning based system that takes an image of a math formula and returns corresponding LaTeX code.
305
+
306
+ Keywords: OCR, LaTeX, Math formula
307
+
308
+ ## [open_clip](https://github.com/mlfoundations/open_clip)
309
+
310
+ OpenCLIP is an open source implementation of OpenAI's CLIP.
311
+
312
+ The goal of this repository is to enable training models with contrastive image-text supervision, and to investigate their properties such as robustness to distribution shift.
313
+ The starting point is an implementation of CLIP that matches the accuracy of the original CLIP models when trained on the same dataset.
314
+
315
+ Specifically, a ResNet-50 model trained with this codebase on OpenAI's 15 million image subset of YFCC achieves 32.7% top-1 accuracy on ImageNet.
316
+
317
+ Keywords: CLIP, Open-source, Contrastive, Image-text
318
+
319
+ ## [dalle-playground](https://github.com/saharmor/dalle-playground)
320
+
321
+ A playground to generate images from any text prompt using Stable Diffusion and Dall-E mini.
322
+
323
+ Keywords: WebUI, Stable Diffusion, Dall-E mini
324
+
325
+ ## [FedML](https://github.com/FedML-AI/FedML)
326
+
327
+ [FedML](https://github.com/FedML-AI/FedML) is a federated learning and analytics library enabling secure and collaborative machine learning on decentralized data anywhere at any scale.
328
+
329
+ It supports large-scale cross-silo federated learning, and cross-device federated learning on smartphones/IoTs, and research simulation.
330
+
331
+ Keywords: Federated Learning, Analytics, Collaborative ML, Decentralized
332
+
333
+ ## [gpt-code-clippy](https://github.com/CodedotAl/gpt-code-clippy)
334
+
335
+ GPT-Code-Clippy (GPT-CC) is an open source version of GitHub Copilot, a language model -- based on GPT-3, called GPT-Codex -- that is fine-tuned on publicly available code from GitHub.
336
+
337
+ Keywords: LLM, Code
338
+
339
+ ## [TextAttack](https://github.com/QData/TextAttack)
340
+
341
+ [TextAttack](https://github.com/QData/TextAttack) 🐙 is a Python framework for adversarial attacks, data augmentation, and model training in NLP.
342
+
343
+ Keywords: Adversarial attacks, Data augmentation, NLP
344
+
345
+ ## [OpenPrompt](https://github.com/thunlp/OpenPrompt)
346
+
347
+ Prompt-learning is a paradigm to adapt pre-trained language models (PLMs) to downstream NLP tasks, which modify the input text with a textual template and directly uses PLMs to conduct pre-trained tasks. This library provides a standard, flexible and extensible framework to deploy the prompt-learning pipeline. [OpenPrompt](https://github.com/thunlp/OpenPrompt) supports loading PLMs directly from https://github.com/huggingface/transformers.
348
+
349
+ ## [text-generation-webui](https://github.com/oobabooga/text-generation-webui/)
350
+
351
+ [text-generation-webui](https://github.com/oobabooga/text-generation-webui/) is a Gradio Web UI for running Large Language Models like LLaMA, llama.cpp, GPT-J, Pythia, OPT, and GALACTICA.
352
+
353
+ Keywords: LLM, WebUI
354
+
355
+ ## [libra](https://github.com/Palashio/libra)
356
+
357
+ An ergonomic machine learning [libra](https://github.com/Palashio/libra)ry for non-technical users. It focuses on ergonomics and on ensuring that training a model is as simple as it can be.
358
+
359
+ Keywords: Ergonomic, Non-technical
360
+
361
+ ## [alibi](https://github.com/SeldonIO/alibi)
362
+
363
+ Alibi is an open source Python library aimed at machine learning model inspection and interpretation. The focus of the library is to provide high-quality implementations of black-box, white-box, local and global explanation methods for classification and regression models.
364
+
365
+ Keywords: Model inspection, Model interpretation, Black-box, White-box
366
+
367
+ ## [tortoise-tts](https://github.com/neonbjb/tortoise-tts)
368
+
369
+ Tortoise is a text-to-speech program built with the following priorities: strong multi-voice capabilities, and highly realistic prosody and intonation.
370
+
371
+ Keywords: Text-to-speech
372
+
373
+ ## [flower](https://github.com/adap/flower)
374
+
375
+ Flower (flwr) is a framework for building federated learning systems. The design of Flower is based on a few guiding principles: customizability, extendability, framework agnosticity, and ease-of-use.
376
+
377
+ Keywords: Federated learning systems, Customizable, Extendable, Framework-agnostic, Simplicity
378
+
379
+ ## [fast-bert](https://github.com/utterworks/fast-bert)
380
+
381
+ Fast-Bert is a deep learning library that allows developers and data scientists to train and deploy BERT and XLNet based models for natural language processing tasks beginning with Text Classification. It is aimed at simplicity.
382
+
383
+ Keywords: Deployment, BERT, XLNet
384
+
385
+ ## [towhee](https://github.com/towhee-io/towhee)
386
+
387
+ Towhee makes it easy to build neural data processing pipelines for AI applications. We provide hundreds of models, algorithms, and transformations that can be used as standard pipeline building blocks. Users can use Towhee's Pythonic API to build a prototype of their pipeline and automatically optimize it for production-ready environments.
388
+
389
+ Keywords: Data processing pipeline, Optimization
390
+
391
+ ## [alibi-detect](https://github.com/SeldonIO/alibi-detect)
392
+
393
+ Alibi Detect is an open source Python library focused on outlier, adversarial and drift detection. The package aims to cover both online and offline detectors for tabular data, text, images and time series. Both TensorFlow and PyTorch backends are supported for drift detection.
394
+
395
+ Keywords: Adversarial, Outlier, Drift detection
396
+
397
+ ## [FARM](https://github.com/deepset-ai/FARM)
398
+
399
+ [FARM](https://github.com/deepset-ai/FARM) makes Transfer Learning with BERT & Co simple, fast and enterprise-ready. It's built upon transformers and provides additional features to simplify the life of developers: Parallelized preprocessing, highly modular design, multi-task learning, experiment tracking, easy debugging and close integration with AWS SageMaker.
400
+
401
+ Keywords: Transfer Learning, Modular design, Multi-task learning, Experiment tracking
402
+
403
+ ## [aitextgen](https://github.com/minimaxir/aitextgen)
404
+
405
+ A robust Python tool for text-based AI training and generation using OpenAI's GPT-2 and EleutherAI's GPT Neo/GPT-3 architecture.
406
+ [aitextgen](https://github.com/minimaxir/aitextgen) is a Python package that leverages PyTorch, Hugging Face Transformers and pytorch-lightning with specific optimizations for text generation using GPT-2, plus many added features.
407
+
408
+ Keywords: Training, Generation
409
+
410
+ ## [diffgram](https://github.com/diffgram/diffgram)
411
+
412
+ Diffgram aims to integrate human supervision into platforms. We support your team programmatically changing the UI (Schema, layout, etc.) like in Streamlit. This means that you can collect and annotate timely data from users. In other words, we are the platform behind your platform, an integrated part of your application, to ship new & better AI products faster.
413
+
414
+ Keywords: Human supervision, Platform
415
+
416
+ ## [ecco](https://github.com/jalammar/ecco)
417
+
418
+ Explain, analyze, and visualize NLP language models. Ecco creates interactive visualizations directly in Jupyter notebooks explaining the behavior of Transformer-based language models (like GPT2, BERT, RoBERTA, T5, and T0).
419
+
420
+ Keywords: Model explainability
421
+
422
+ ## [s3prl](https://github.com/s3prl/s3prl)
423
+
424
+ [s3prl](https://github.com/s3prl/s3prl) stands for Self-Supervised Speech Pre-training and Representation Learning. Self-supervised speech pre-trained models are called upstream in this toolkit, and are utilized in various downstream tasks.
425
+
426
+ Keywords: Speech, Training
427
+
428
+ ## [ru-dalle](https://github.com/ai-forever/ru-dalle)
429
+
430
+ RuDALL-E aims to be similar to DALL-E, targeted to Russian.
431
+
432
+ Keywords: DALL-E, Russian
433
+
434
+ ## [DeepKE](https://github.com/zjunlp/DeepKE)
435
+
436
+ [DeepKE](https://github.com/zjunlp/DeepKE) is a knowledge extraction toolkit for knowledge graph construction supporting cnSchema,low-resource, document-level and multimodal scenarios for entity, relation and attribute extraction.
437
+
438
+ Keywords: Knowledge Extraction, Knowledge Graphs
439
+
440
+ ## [Nebuly](https://github.com/nebuly-ai/optimate)
441
+
442
+ Nebuly is the next-generation platform to monitor and optimize your AI costs in one place. The platform connects to all your AI cost sources (compute, API providers, AI software licenses, etc) and centralizes them in one place to give you full visibility on a model basis. The platform also provides optimization recommendations and a co-pilot model that can guide during the optimization process. The platform builds on top of the open-source tools allowing you to optimize the different steps of your AI stack to squeeze out the best possible cost performances.
443
+
444
+ Keywords: Optimization, Performance, Monitoring
445
+
446
+ ## [imaginAIry](https://github.com/brycedrennan/imaginAIry)
447
+
448
+ Offers a CLI and a Python API to generate images with Stable Diffusion. It has support for many tools, like image structure control (controlnet), instruction-based image edits (InstructPix2Pix), prompt-based masking (clipseg), among others.
449
+
450
+ Keywords: Stable Diffusion, CLI, Python API
451
+
452
+ ## [sparseml](https://github.com/neuralmagic/sparseml)
453
+
454
+ SparseML is an open-source model optimization toolkit that enables you to create inference-optimized sparse models using pruning, quantization, and distillation algorithms. Models optimized with SparseML can then be exported to the ONNX and deployed with DeepSparse for GPU-class performance on CPU hardware.
455
+
456
+ Keywords: Model optimization, Pruning, Quantization, Distillation
457
+
458
+ ## [opacus](https://github.com/pytorch/opacus)
459
+
460
+ Opacus is a library that enables training PyTorch models with differential privacy. It supports training with minimal code changes required on the client, has little impact on training performance, and allows the client to online track the privacy budget expended at any given moment.
461
+
462
+ Keywords: Differential privacy
463
+
464
+ ## [LAVIS](https://github.com/salesforce/LAVIS)
465
+
466
+ [LAVIS](https://github.com/salesforce/LAVIS) is a Python deep learning library for LAnguage-and-VISion intelligence research and applications. This library aims to provide engineers and researchers with a one-stop solution to rapidly develop models for their specific multimodal scenarios, and benchmark them across standard and customized datasets. It features a unified interface design to access
467
+
468
+ Keywords: Multimodal, NLP, Vision
469
+
470
+ ## [buzz](https://github.com/chidiwilliams/buzz)
471
+
472
+ Buzz transcribes and translates audio offline on your personal computer. Powered by OpenAI's Whisper.
473
+
474
+ Keywords: Audio transcription, Translation
475
+
476
+ ## [rust-bert](https://github.com/guillaume-be/rust-bert)
477
+
478
+ Rust-native state-of-the-art Natural Language Processing models and pipelines. Port of Hugging Face's Transformers library, using the tch-rs crate and pre-processing from rust-tokenizers. Supports multi-threaded tokenization and GPU inference. This repository exposes the model base architecture, task-specific heads and ready-to-use pipelines.
479
+
480
+ Keywords: Rust, BERT, Inference
481
+
482
+ ## [EasyNLP](https://github.com/alibaba/EasyNLP)
483
+
484
+ [EasyNLP](https://github.com/alibaba/EasyNLP) is an easy-to-use NLP development and application toolkit in PyTorch, first released inside Alibaba in 2021. It is built with scalable distributed training strategies and supports a comprehensive suite of NLP algorithms for various NLP applications. [EasyNLP](https://github.com/alibaba/EasyNLP) integrates knowledge distillation and few-shot learning for landing large pre-trained models, together with various popular multi-modality pre-trained models. It provides a unified framework of model training, inference, and deployment for real-world applications.
485
+
486
+ Keywords: NLP, Knowledge distillation, Few-shot learning, Multi-modality, Training, Inference, Deployment
487
+
488
+ ## [TurboTransformers](https://github.com/Tencent/TurboTransformers)
489
+
490
+ A fast and user-friendly runtime for transformer inference (Bert, Albert, GPT2, Decoders, etc) on CPU and GPU.
491
+
492
+ Keywords: Optimization, Performance
493
+
494
+ ## [hivemind](https://github.com/learning-at-home/hivemind)
495
+
496
+ Hivemind is a PyTorch library for decentralized deep learning across the Internet. Its intended usage is training one large model on hundreds of computers from different universities, companies, and volunteers.
497
+
498
+ Keywords: Decentralized training
499
+
500
+ ## [docquery](https://github.com/impira/docquery)
501
+
502
+ DocQuery is a library and command-line tool that makes it easy to analyze semi-structured and unstructured documents (PDFs, scanned images, etc.) using large language models (LLMs). You simply point DocQuery at one or more documents and specify a question you want to ask. DocQuery is created by the team at Impira.
503
+
504
+ Keywords: Semi-structured documents, Unstructured documents, LLM, Document Question Answering
505
+
506
+ ## [CodeGeeX](https://github.com/THUDM/CodeGeeX)
507
+
508
+ [CodeGeeX](https://github.com/THUDM/CodeGeeX) is a large-scale multilingual code generation model with 13 billion parameters, pre-trained on a large code corpus of more than 20 programming languages. It has several unique features:
509
+ - Multilingual code generation
510
+ - Crosslingual code translation
511
+ - Is a customizable programming assistant
512
+
513
+ Keywords: Code Generation Model
514
+
515
+ ## [ktrain](https://github.com/amaiya/ktrain)
516
+
517
+ [ktrain](https://github.com/amaiya/ktrain) is a lightweight wrapper for the deep learning library TensorFlow Keras (and other libraries) to help build, train, and deploy neural networks and other machine learning models. Inspired by ML framework extensions like fastai and ludwig, [ktrain](https://github.com/amaiya/ktrain) is designed to make deep learning and AI more accessible and easier to apply for both newcomers and experienced practitioners.
518
+
519
+ Keywords: Keras wrapper, Model building, Training, Deployment
520
+
521
+ ## [FastDeploy](https://github.com/PaddlePaddle/FastDeploy)
522
+
523
+ [FastDeploy](https://github.com/PaddlePaddle/FastDeploy) is an Easy-to-use and High Performance AI model deployment toolkit for Cloud, Mobile and Edge with packageout-of-the-box and unified experience, endend-to-end optimization for over fire160+ Text, Vision, Speech and Cross-modal AI models. Including image classification, object detection, OCR, face detection, matting, pp-tracking, NLP, stable diffusion, TTS and other tasks to meet developers' industrial deployment needs for multi-scenario, multi-hardware and multi-platform.
524
+
525
+ Keywords: Model deployment, CLoud, Mobile, Edge
526
+
527
+ ## [underthesea](https://github.com/undertheseanlp/underthesea)
528
+
529
+ [underthesea](https://github.com/undertheseanlp/underthesea) is a Vietnamese NLP toolkit. Underthesea is a suite of open source Python modules data sets and tutorials supporting research and development in Vietnamese Natural Language Processing. We provide extremely easy API to quickly apply pretrained NLP models to your Vietnamese text, such as word segmentation, part-of-speech tagging (PoS), named entity recognition (NER), text classification and dependency parsing.
530
+
531
+ Keywords: Vietnamese, NLP
532
+
533
+ ## [hasktorch](https://github.com/hasktorch/hasktorch)
534
+
535
+ Hasktorch is a library for tensors and neural networks in Haskell. It is an independent open source community project which leverages the core C++ libraries shared by PyTorch.
536
+
537
+ Keywords: Haskell, Neural Networks
538
+
539
+ ## [donut](https://github.com/clovaai/donut)
540
+
541
+ Donut, or Document understanding transformer, is a new method of document understanding that utilizes an OCR-free end-to-end Transformer model.
542
+
543
+ Donut does not require off-the-shelf OCR engines/APIs, yet it shows state-of-the-art performances on various visual document understanding tasks, such as visual document classification or information extraction (a.k.a. document parsing).
544
+
545
+ Keywords: Document Understanding
546
+
547
+ ## [transformers-interpret](https://github.com/cdpierse/transformers-interpret)
548
+
549
+ Transformers Interpret is a model explainability tool designed to work exclusively with the transformers package.
550
+
551
+ In line with the philosophy of the Transformers package Transformers Interpret allows any transformers model to be explained in just two lines. Explainers are available for both text and computer vision models. Visualizations are also available in notebooks and as savable png and html files
552
+
553
+ Keywords: Model interpretation, Visualization
554
+
555
+ ## [mlrun](https://github.com/mlrun/mlrun)
556
+
557
+ MLRun is an open MLOps platform for quickly building and managing continuous ML applications across their lifecycle. MLRun integrates into your development and CI/CD environment and automates the delivery of production data, ML pipelines, and online applications, significantly reducing engineering efforts, time to production, and computation resources. With MLRun, you can choose any IDE on your local machine or on the cloud. MLRun breaks the silos between data, ML, software, and DevOps/MLOps teams, enabling collaboration and fast continuous improvements.
558
+
559
+ Keywords: MLOps
560
+
561
+ ## [FederatedScope](https://github.com/alibaba/FederatedScope)
562
+
563
+ [FederatedScope](https://github.com/alibaba/FederatedScope) is a comprehensive federated learning platform that provides convenient usage and flexible customization for various federated learning tasks in both academia and industry. Based on an event-driven architecture, [FederatedScope](https://github.com/alibaba/FederatedScope) integrates rich collections of functionalities to satisfy the burgeoning demands from federated learning, and aims to build up an easy-to-use platform for promoting learning safely and effectively.
564
+
565
+ Keywords: Federated learning, Event-driven
566
+
567
+ ## [pythainlp](https://github.com/PyThaiNLP/pythainlp)
568
+
569
+ PyThaiNLP is a Python package for text processing and linguistic analysis, similar to NLTK with focus on Thai language.
570
+
571
+ Keywords: Thai, NLP, NLTK
572
+
573
+ ## [FlagAI](https://github.com/FlagAI-Open/FlagAI)
574
+
575
+ [FlagAI](https://github.com/FlagAI-Open/FlagAI) (Fast LArge-scale General AI models) is a fast, easy-to-use and extensible toolkit for large-scale model. Our goal is to support training, fine-tuning, and deployment of large-scale models on various downstream tasks with multi-modality.
576
+
577
+ Keywords: Large models, Training, Fine-tuning, Deployment, Multi-modal
578
+
579
+ ## [pyserini](https://github.com/castorini/pyserini)
580
+
581
+ [pyserini](https://github.com/castorini/pyserini) is a Python toolkit for reproducible information retrieval research with sparse and dense representations. Retrieval using sparse representations is provided via integration with the group's Anserini IR toolkit. Retrieval using dense representations is provided via integration with Facebook's Faiss library.
582
+
583
+ Keywords: IR, Information Retrieval, Dense, Sparse
584
+
585
+ ## [baal](https://github.com/baal-org/baal)
586
+
587
+ [baal](https://github.com/baal-org/baal) is an active learning library that supports both industrial applications and research usecases. [baal](https://github.com/baal-org/baal) currently supports Monte-Carlo Dropout, MCDropConnect, deep ensembles, and semi-supervised learning.
588
+
589
+ Keywords: Active Learning, Research, Labeling
590
+
591
+ ## [cleanlab](https://github.com/cleanlab/cleanlab)
592
+
593
+ [cleanlab](https://github.com/cleanlab/cleanlab) is the standard data-centric AI package for data quality and machine learning with messy, real-world data and labels. For text, image, tabular, audio (among others) datasets, you can use cleanlab to automatically: detect data issues (outliers, label errors, near duplicates, etc), train robust ML models, infer consensus + annotator-quality for multi-annotator data, suggest data to (re)label next (active learning).
594
+
595
+ Keywords: Data-Centric AI, Data Quality, Noisy Labels, Outlier Detection, Active Learning
596
+
597
+ ## [BentoML](https://github.com/bentoml/BentoML)
598
+
599
+ [BentoML](https://github.com/bentoml) is the unified framework for building, shipping, and scaling production-ready AI applications incorporating traditional ML, pre-trained AI models, Generative and Large Language Models.
600
+ All Hugging Face models and pipelines can be seamlessly integrated into BentoML applications, enabling the running of models on the most suitable hardware and independent scaling based on usage.
601
+
602
+ Keywords: BentoML, Framework, Deployment, AI Applications
603
+
604
+ ## [LLaMA Factory](https://github.com/hiyouga/LLaMA-Factory)
605
+
606
+ [LLaMA Factory](https://github.com/hiyouga/LLaMA-Factory) offers a user-friendly fine-tuning framework that incorporates PEFT. The repository includes training(fine-tuning) and inference examples for LLaMA-2, BLOOM, Falcon, Baichuan, Qwen, and other LLMs. A ChatGLM version is also available in [ChatGLM-Efficient-Tuning](https://github.com/hiyouga/ChatGLM-Efficient-Tuning).
607
+
608
+ Keywords: PEFT, fine-tuning, LLaMA-2, ChatGLM, Qwen
609
+
transformers/conftest.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # tests directory-specific settings - this file is run automatically
16
+ # by pytest before any tests are run
17
+
18
+ import doctest
19
+ import sys
20
+ import warnings
21
+ from os.path import abspath, dirname, join
22
+
23
+ import _pytest
24
+ import pytest
25
+
26
+ from transformers.testing_utils import HfDoctestModule, HfDocTestParser
27
+
28
+
29
+ NOT_DEVICE_TESTS = {
30
+ "test_tokenization",
31
+ "test_tokenization_mistral_common",
32
+ "test_processor",
33
+ "test_processing",
34
+ "test_beam_constraints",
35
+ "test_configuration_utils",
36
+ "test_data_collator",
37
+ "test_trainer_callback",
38
+ "test_trainer_utils",
39
+ "test_feature_extraction",
40
+ "test_image_processing",
41
+ "test_image_processor",
42
+ "test_image_transforms",
43
+ "test_optimization",
44
+ "test_retrieval",
45
+ "test_config",
46
+ "test_from_pretrained_no_checkpoint",
47
+ "test_keep_in_fp32_modules",
48
+ "test_gradient_checkpointing_backward_compatibility",
49
+ "test_gradient_checkpointing_enable_disable",
50
+ "test_torch_save_load",
51
+ "test_initialization",
52
+ "test_forward_signature",
53
+ "test_model_get_set_embeddings",
54
+ "test_model_main_input_name",
55
+ "test_correct_missing_keys",
56
+ "test_tie_model_weights",
57
+ "test_can_use_safetensors",
58
+ "test_load_save_without_tied_weights",
59
+ "test_tied_weights_keys",
60
+ "test_model_weights_reload_no_missing_tied_weights",
61
+ "test_mismatched_shapes_have_properly_initialized_weights",
62
+ "test_matched_shapes_have_loaded_weights_when_some_mismatched_shapes_exist",
63
+ "test_model_is_small",
64
+ "test_tf_from_pt_safetensors",
65
+ "test_flax_from_pt_safetensors",
66
+ "ModelTest::test_pipeline_", # None of the pipeline tests from PipelineTesterMixin (of which XxxModelTest inherits from) are running on device
67
+ "ModelTester::test_pipeline_",
68
+ "/repo_utils/",
69
+ "/utils/",
70
+ }
71
+
72
+ # allow having multiple repository checkouts and not needing to remember to rerun
73
+ # `pip install -e '.[dev]'` when switching between checkouts and running tests.
74
+ git_repo_path = abspath(join(dirname(__file__), "src"))
75
+ sys.path.insert(1, git_repo_path)
76
+
77
+ # silence FutureWarning warnings in tests since often we can't act on them until
78
+ # they become normal warnings - i.e. the tests still need to test the current functionality
79
+ warnings.simplefilter(action="ignore", category=FutureWarning)
80
+
81
+
82
+ def pytest_configure(config):
83
+ config.addinivalue_line("markers", "is_pipeline_test: mark test to run only when pipelines are tested")
84
+ config.addinivalue_line("markers", "is_staging_test: mark test to run only in the staging environment")
85
+ config.addinivalue_line("markers", "accelerate_tests: mark test that require accelerate")
86
+ config.addinivalue_line("markers", "not_device_test: mark the tests always running on cpu")
87
+
88
+
89
+ def pytest_collection_modifyitems(items):
90
+ for item in items:
91
+ if any(test_name in item.nodeid for test_name in NOT_DEVICE_TESTS):
92
+ item.add_marker(pytest.mark.not_device_test)
93
+
94
+
95
+ def pytest_addoption(parser):
96
+ from transformers.testing_utils import pytest_addoption_shared
97
+
98
+ pytest_addoption_shared(parser)
99
+
100
+
101
+ def pytest_terminal_summary(terminalreporter):
102
+ from transformers.testing_utils import pytest_terminal_summary_main
103
+
104
+ make_reports = terminalreporter.config.getoption("--make-reports")
105
+ if make_reports:
106
+ pytest_terminal_summary_main(terminalreporter, id=make_reports)
107
+
108
+
109
+ def pytest_sessionfinish(session, exitstatus):
110
+ # If no tests are collected, pytest exists with code 5, which makes the CI fail.
111
+ if exitstatus == 5:
112
+ session.exitstatus = 0
113
+
114
+
115
+ # Doctest custom flag to ignore output.
116
+ IGNORE_RESULT = doctest.register_optionflag("IGNORE_RESULT")
117
+
118
+ OutputChecker = doctest.OutputChecker
119
+
120
+
121
+ class CustomOutputChecker(OutputChecker):
122
+ def check_output(self, want, got, optionflags):
123
+ if IGNORE_RESULT & optionflags:
124
+ return True
125
+ return OutputChecker.check_output(self, want, got, optionflags)
126
+
127
+
128
+ doctest.OutputChecker = CustomOutputChecker
129
+ _pytest.doctest.DoctestModule = HfDoctestModule
130
+ doctest.DocTestParser = HfDocTestParser
transformers/setup.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/main/setup.py
17
+
18
+ To create the package for pypi.
19
+
20
+ 1. Create the release branch named: v<RELEASE>-release, for example v4.19-release. For a patch release checkout the
21
+ current release branch.
22
+
23
+ If releasing on a special branch, copy the updated README.md on the main branch for the commit you will make
24
+ for the post-release and run `make fix-copies` on the main branch as well.
25
+
26
+ 2. Run `make pre-release` (or `make pre-patch` for a patch release) and commit these changes with the message:
27
+ "Release: <VERSION>" and push.
28
+
29
+ 3. Go back to the main branch and run `make post-release` then `make fix-copies`. Commit these changes with the
30
+ message "v<NEXT_VERSION>.dev.0" and push to main.
31
+
32
+ # If you were just cutting the branch in preparation for a release, you can stop here for now.
33
+
34
+ 4. Wait for the tests on the release branch to be completed and be green (otherwise revert and fix bugs)
35
+
36
+ 5. On the release branch, add a tag in git to mark the release: "git tag v<VERSION> -m 'Adds tag v<VERSION> for pypi' "
37
+ Push the tag to git: git push --tags origin v<RELEASE>-release
38
+
39
+ 6. Build both the sources and the wheel. Do not change anything in setup.py between
40
+ creating the wheel and the source distribution (obviously).
41
+
42
+ Run `make build-release`. This will build the release and do some sanity checks for you. If this ends with an error
43
+ message, you need to fix things before going further.
44
+
45
+ You should now have a /dist directory with both .whl and .tar.gz source versions.
46
+
47
+ 7. Check that everything looks correct by uploading the package to the pypi test server:
48
+
49
+ twine upload dist/* -r testpypi
50
+ (pypi suggest using twine as other methods upload files via plaintext.)
51
+ You may have to specify the repository url, use the following command then:
52
+ twine upload dist/* -r testpypi --repository-url=https://test.pypi.org/legacy/
53
+
54
+ Check that you can install it in a virtualenv by running:
55
+ pip install -i https://test.pypi.org/simple/ transformers
56
+
57
+ Check you can run the following commands:
58
+ python -c "from transformers import pipeline; classifier = pipeline('text-classification'); print(classifier('What a nice release'))"
59
+ python -c "from transformers import *"
60
+ python utils/check_build.py --check_lib
61
+
62
+ If making a patch release, double check the bug you are patching is indeed resolved.
63
+
64
+ 8. Upload the final version to actual pypi:
65
+ twine upload dist/* -r pypi
66
+
67
+ 9. Copy the release notes from RELEASE.md to the tag in github once everything is looking hunky-dory.
68
+ """
69
+
70
+ import os
71
+ import re
72
+ import shutil
73
+ from pathlib import Path
74
+
75
+ from setuptools import Command, find_packages, setup
76
+
77
+
78
+ # Remove stale transformers.egg-info directory to avoid https://github.com/pypa/pip/issues/5466
79
+ stale_egg_info = Path(__file__).parent / "transformers.egg-info"
80
+ if stale_egg_info.exists():
81
+ print(
82
+ (
83
+ "Warning: {} exists.\n\n"
84
+ "If you recently updated transformers to 3.0 or later, this is expected,\n"
85
+ "but it may prevent transformers from installing in editable mode.\n\n"
86
+ "This directory is automatically generated by Python's packaging tools.\n"
87
+ "I will remove it now.\n\n"
88
+ "See https://github.com/pypa/pip/issues/5466 for details.\n"
89
+ ).format(stale_egg_info)
90
+ )
91
+ shutil.rmtree(stale_egg_info)
92
+
93
+
94
+ # IMPORTANT:
95
+ # 1. all dependencies should be listed here with their version requirements if any
96
+ # 2. once modified, run: `make deps_table_update` to update src/transformers/dependency_versions_table.py
97
+ _deps = [
98
+ "Pillow>=10.0.1,<=15.0",
99
+ "accelerate>=0.26.0",
100
+ "av",
101
+ "beautifulsoup4",
102
+ "blobfile",
103
+ "codecarbon>=2.8.1",
104
+ "cookiecutter==1.7.3",
105
+ "dataclasses",
106
+ "datasets!=2.5.0",
107
+ "deepspeed>=0.9.3",
108
+ "diffusers",
109
+ "dill<0.3.5",
110
+ "evaluate>=0.2.0",
111
+ "faiss-cpu",
112
+ "fastapi",
113
+ "filelock",
114
+ "flax>=0.4.1,<=0.7.0",
115
+ "ftfy",
116
+ "fugashi>=1.0",
117
+ "GitPython<3.1.19",
118
+ "hf-doc-builder>=0.3.0",
119
+ "hf_xet",
120
+ "huggingface-hub>=0.30.0,<1.0",
121
+ "importlib_metadata",
122
+ "ipadic>=1.0.0,<2.0",
123
+ "jax>=0.4.1,<=0.4.13",
124
+ "jaxlib>=0.4.1,<=0.4.13",
125
+ "jieba",
126
+ "jinja2>=3.1.0",
127
+ "kenlm",
128
+ # Keras pin - this is to make sure Keras 3 doesn't destroy us. Remove or change when we have proper support.
129
+ "keras>2.9,<2.16",
130
+ "keras-nlp>=0.3.1,<0.14.0", # keras-nlp 0.14 doesn't support keras 2, see pin on keras.
131
+ "kernels>=0.6.1,<0.7",
132
+ "librosa",
133
+ "natten>=0.14.6,<0.15.0",
134
+ "nltk<=3.8.1",
135
+ "num2words",
136
+ "numpy>=1.17",
137
+ "onnxconverter-common",
138
+ "onnxruntime-tools>=1.4.2",
139
+ "onnxruntime>=1.4.0",
140
+ "opencv-python",
141
+ "optimum-benchmark>=0.3.0",
142
+ "optuna",
143
+ "optax>=0.0.8,<=0.1.4",
144
+ "pandas<2.3.0", # `datasets` requires `pandas` while `pandas==2.3.0` has issues with CircleCI on 2025/06/05
145
+ "packaging>=20.0",
146
+ "parameterized",
147
+ "phonemizer",
148
+ "protobuf",
149
+ "psutil",
150
+ "pyyaml>=5.1",
151
+ "pydantic>=2",
152
+ "pytest>=7.2.0",
153
+ "pytest-asyncio",
154
+ "pytest-rerunfailures",
155
+ "pytest-timeout",
156
+ "pytest-xdist",
157
+ "pytest-order",
158
+ "python>=3.9.0",
159
+ "ray[tune]>=2.7.0",
160
+ "regex!=2019.12.17",
161
+ "requests",
162
+ "rhoknp>=1.1.0,<1.3.1",
163
+ "rjieba",
164
+ "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1",
165
+ "ruff==0.11.2",
166
+ # `sacrebleu` not used in `transformers`. However, it is needed in several tests, when a test calls
167
+ # `evaluate.load("sacrebleu")`. This metric is used in the examples that we use to test the `Trainer` with, in the
168
+ # `Trainer` tests (see references to `run_translation.py`).
169
+ "sacrebleu>=1.4.12,<2.0.0",
170
+ "sacremoses",
171
+ "safetensors>=0.4.3",
172
+ "sagemaker>=2.31.0",
173
+ "schedulefree>=1.2.6",
174
+ "scikit-learn",
175
+ "scipy<1.13.0", # SciPy >= 1.13.0 is not supported with the current jax pin (`jax>=0.4.1,<=0.4.13`)
176
+ "sentencepiece>=0.1.91,!=0.1.92",
177
+ "sigopt",
178
+ "starlette",
179
+ "sudachipy>=0.6.6",
180
+ "sudachidict_core>=20220729",
181
+ "tensorboard",
182
+ # TensorFlow pin. When changing this value, update examples/tensorflow/_tests_requirements.txt accordingly
183
+ "tensorflow-cpu>2.9,<2.16",
184
+ "tensorflow>2.9,<2.16",
185
+ "tensorflow-text<2.16",
186
+ "tensorflow-probability<0.24",
187
+ "tf2onnx",
188
+ "timeout-decorator",
189
+ "tiktoken",
190
+ "timm<=1.0.11",
191
+ "tokenizers>=0.21,<0.22",
192
+ "torch>=2.1",
193
+ "torchaudio",
194
+ "torchvision",
195
+ "pyctcdecode>=0.4.0",
196
+ "tqdm>=4.27",
197
+ "unidic>=1.0.2",
198
+ "unidic_lite>=1.0.7",
199
+ "urllib3<2.0.0",
200
+ "uvicorn",
201
+ "pytest-rich",
202
+ "libcst",
203
+ "rich",
204
+ "opentelemetry-api",
205
+ "opentelemetry-exporter-otlp",
206
+ "opentelemetry-sdk",
207
+ "mistral-common[opencv]>=1.6.3",
208
+ ]
209
+
210
+
211
+ # this is a lookup table with items like:
212
+ #
213
+ # tokenizers: "tokenizers==0.9.4"
214
+ # packaging: "packaging"
215
+ #
216
+ # some of the values are versioned whereas others aren't.
217
+ deps = {b: a for a, b in (re.findall(r"^(([^!=<>~ ]+)(?:[!=<>~ ].*)?$)", x)[0] for x in _deps)}
218
+
219
+ # since we save this data in src/transformers/dependency_versions_table.py it can be easily accessed from
220
+ # anywhere. If you need to quickly access the data from this table in a shell, you can do so easily with:
221
+ #
222
+ # python -c 'import sys; from transformers.dependency_versions_table import deps; \
223
+ # print(" ".join([ deps[x] for x in sys.argv[1:]]))' tokenizers datasets
224
+ #
225
+ # Just pass the desired package names to that script as it's shown with 2 packages above.
226
+ #
227
+ # If transformers is not yet installed and the work is done from the cloned repo remember to add `PYTHONPATH=src` to the script above
228
+ #
229
+ # You can then feed this for example to `pip`:
230
+ #
231
+ # pip install -U $(python -c 'import sys; from transformers.dependency_versions_table import deps; \
232
+ # print(" ".join([deps[x] for x in sys.argv[1:]]))' tokenizers datasets)
233
+ #
234
+
235
+
236
+ def deps_list(*pkgs):
237
+ return [deps[pkg] for pkg in pkgs]
238
+
239
+
240
+ class DepsTableUpdateCommand(Command):
241
+ """
242
+ A custom distutils command that updates the dependency table.
243
+ usage: python setup.py deps_table_update
244
+ """
245
+
246
+ description = "build runtime dependency table"
247
+ user_options = [
248
+ # format: (long option, short option, description).
249
+ ("dep-table-update", None, "updates src/transformers/dependency_versions_table.py"),
250
+ ]
251
+
252
+ def initialize_options(self):
253
+ pass
254
+
255
+ def finalize_options(self):
256
+ pass
257
+
258
+ def run(self):
259
+ entries = "\n".join([f' "{k}": "{v}",' for k, v in deps.items()])
260
+ content = [
261
+ "# THIS FILE HAS BEEN AUTOGENERATED. To update:",
262
+ "# 1. modify the `_deps` dict in setup.py",
263
+ "# 2. run `make deps_table_update``",
264
+ "deps = {",
265
+ entries,
266
+ "}",
267
+ "",
268
+ ]
269
+ target = "src/transformers/dependency_versions_table.py"
270
+ print(f"updating {target}")
271
+ with open(target, "w", encoding="utf-8", newline="\n") as f:
272
+ f.write("\n".join(content))
273
+
274
+
275
+ extras = {}
276
+
277
+ extras["ja"] = deps_list("fugashi", "ipadic", "unidic_lite", "unidic", "sudachipy", "sudachidict_core", "rhoknp")
278
+ extras["sklearn"] = deps_list("scikit-learn")
279
+
280
+ extras["tf"] = deps_list("tensorflow", "onnxconverter-common", "tf2onnx", "tensorflow-text", "keras-nlp")
281
+ extras["tf-cpu"] = deps_list(
282
+ "keras",
283
+ "tensorflow-cpu",
284
+ "onnxconverter-common",
285
+ "tf2onnx",
286
+ "tensorflow-text",
287
+ "keras-nlp",
288
+ "tensorflow-probability",
289
+ )
290
+
291
+ extras["torch"] = deps_list("torch", "accelerate")
292
+ extras["accelerate"] = deps_list("accelerate")
293
+ extras["hf_xet"] = deps_list("hf_xet")
294
+
295
+ if os.name == "nt": # windows
296
+ extras["retrieval"] = deps_list("datasets") # faiss is not supported on windows
297
+ extras["flax"] = [] # jax is not supported on windows
298
+ else:
299
+ extras["retrieval"] = deps_list("faiss-cpu", "datasets")
300
+ extras["flax"] = deps_list("jax", "jaxlib", "flax", "optax", "scipy")
301
+
302
+ extras["tokenizers"] = deps_list("tokenizers")
303
+ extras["ftfy"] = deps_list("ftfy")
304
+ extras["onnxruntime"] = deps_list("onnxruntime", "onnxruntime-tools")
305
+ extras["onnx"] = deps_list("onnxconverter-common", "tf2onnx") + extras["onnxruntime"]
306
+ extras["modelcreation"] = deps_list("cookiecutter")
307
+
308
+ extras["sagemaker"] = deps_list("sagemaker")
309
+ extras["deepspeed"] = deps_list("deepspeed") + extras["accelerate"]
310
+ extras["optuna"] = deps_list("optuna")
311
+ extras["ray"] = deps_list("ray[tune]")
312
+ extras["sigopt"] = deps_list("sigopt")
313
+ extras["hub-kernels"] = deps_list("kernels")
314
+
315
+ extras["integrations"] = extras["hub-kernels"] + extras["optuna"] + extras["ray"] + extras["sigopt"]
316
+
317
+ extras["serving"] = deps_list("pydantic", "uvicorn", "fastapi", "starlette") + extras["torch"]
318
+ extras["audio"] = deps_list(
319
+ "librosa",
320
+ "pyctcdecode",
321
+ "phonemizer",
322
+ "kenlm",
323
+ )
324
+ # `pip install ".[speech]"` is deprecated and `pip install ".[torch-speech]"` should be used instead
325
+ extras["speech"] = deps_list("torchaudio") + extras["audio"]
326
+ extras["torch-speech"] = deps_list("torchaudio") + extras["audio"]
327
+ extras["tf-speech"] = extras["audio"]
328
+ extras["flax-speech"] = extras["audio"]
329
+ extras["vision"] = deps_list("Pillow")
330
+ extras["timm"] = deps_list("timm")
331
+ extras["torch-vision"] = deps_list("torchvision") + extras["vision"]
332
+ extras["natten"] = deps_list("natten")
333
+ extras["codecarbon"] = deps_list("codecarbon")
334
+ extras["video"] = deps_list("av")
335
+ extras["num2words"] = deps_list("num2words")
336
+ extras["sentencepiece"] = deps_list("sentencepiece", "protobuf")
337
+ extras["tiktoken"] = deps_list("tiktoken", "blobfile")
338
+ extras["mistral-common"] = deps_list("mistral-common[opencv]")
339
+ extras["testing"] = (
340
+ deps_list(
341
+ "pytest",
342
+ "pytest-asyncio",
343
+ "pytest-rich",
344
+ "pytest-xdist",
345
+ "pytest-order",
346
+ "pytest-rerunfailures",
347
+ "timeout-decorator",
348
+ "parameterized",
349
+ "psutil",
350
+ "datasets",
351
+ "dill",
352
+ "evaluate",
353
+ "pytest-timeout",
354
+ "ruff",
355
+ "rouge-score",
356
+ "nltk",
357
+ "GitPython",
358
+ "sacremoses",
359
+ "rjieba",
360
+ "beautifulsoup4",
361
+ "tensorboard",
362
+ "pydantic",
363
+ "sentencepiece",
364
+ "sacrebleu", # needed in trainer tests, see references to `run_translation.py`
365
+ )
366
+ + extras["retrieval"]
367
+ + extras["modelcreation"]
368
+ + extras["mistral-common"]
369
+ )
370
+
371
+ extras["deepspeed-testing"] = extras["deepspeed"] + extras["testing"] + extras["optuna"] + extras["sentencepiece"]
372
+ extras["ruff"] = deps_list("ruff")
373
+ extras["quality"] = deps_list("datasets", "ruff", "GitPython", "urllib3", "libcst", "rich", "pandas")
374
+
375
+ extras["all"] = (
376
+ extras["tf"]
377
+ + extras["torch"]
378
+ + extras["flax"]
379
+ + extras["sentencepiece"]
380
+ + extras["tokenizers"]
381
+ + extras["torch-speech"]
382
+ + extras["vision"]
383
+ + extras["integrations"]
384
+ + extras["timm"]
385
+ + extras["torch-vision"]
386
+ + extras["codecarbon"]
387
+ + extras["accelerate"]
388
+ + extras["video"]
389
+ + extras["num2words"]
390
+ + extras["mistral-common"]
391
+ )
392
+
393
+
394
+ extras["dev-torch"] = (
395
+ extras["testing"]
396
+ + extras["torch"]
397
+ + extras["sentencepiece"]
398
+ + extras["tokenizers"]
399
+ + extras["torch-speech"]
400
+ + extras["vision"]
401
+ + extras["integrations"]
402
+ + extras["timm"]
403
+ + extras["torch-vision"]
404
+ + extras["codecarbon"]
405
+ + extras["quality"]
406
+ + extras["ja"]
407
+ + extras["sklearn"]
408
+ + extras["modelcreation"]
409
+ + extras["onnxruntime"]
410
+ + extras["num2words"]
411
+ )
412
+ extras["dev-tensorflow"] = (
413
+ extras["testing"]
414
+ + extras["tf"]
415
+ + extras["sentencepiece"]
416
+ + extras["tokenizers"]
417
+ + extras["vision"]
418
+ + extras["quality"]
419
+ + extras["sklearn"]
420
+ + extras["modelcreation"]
421
+ + extras["onnx"]
422
+ + extras["tf-speech"]
423
+ )
424
+ extras["dev"] = (
425
+ extras["all"] + extras["testing"] + extras["quality"] + extras["ja"] + extras["sklearn"] + extras["modelcreation"]
426
+ )
427
+
428
+ extras["torchhub"] = deps_list(
429
+ "filelock",
430
+ "huggingface-hub",
431
+ "importlib_metadata",
432
+ "numpy",
433
+ "packaging",
434
+ "protobuf",
435
+ "regex",
436
+ "requests",
437
+ "sentencepiece",
438
+ "torch",
439
+ "tokenizers",
440
+ "tqdm",
441
+ )
442
+
443
+ extras["benchmark"] = deps_list("optimum-benchmark")
444
+
445
+ # OpenTelemetry dependencies for metrics collection in continuous batching
446
+ extras["open-telemetry"] = deps_list("opentelemetry-api", "opentelemetry-exporter-otlp", "opentelemetry-sdk")
447
+
448
+ # when modifying the following list, make sure to update src/transformers/dependency_versions_check.py
449
+ install_requires = [
450
+ deps["filelock"], # filesystem locks, e.g., to prevent parallel downloads
451
+ deps["huggingface-hub"],
452
+ deps["numpy"],
453
+ deps["packaging"], # utilities from PyPA to e.g., compare versions
454
+ deps["pyyaml"], # used for the model cards metadata
455
+ deps["regex"], # for OpenAI GPT
456
+ deps["requests"], # for downloading models over HTTPS
457
+ deps["tokenizers"],
458
+ deps["safetensors"],
459
+ deps["tqdm"], # progress bars in model download and training scripts
460
+ ]
461
+
462
+ setup(
463
+ name="transformers",
464
+ version="4.54.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots)
465
+ author="The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)",
466
+ author_email="transformers@huggingface.co",
467
+ description="State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow",
468
+ long_description=open("README.md", "r", encoding="utf-8").read(),
469
+ long_description_content_type="text/markdown",
470
+ keywords="NLP vision speech deep learning transformer pytorch tensorflow jax BERT GPT-2 Wav2Vec2 ViT",
471
+ license="Apache 2.0 License",
472
+ url="https://github.com/huggingface/transformers",
473
+ package_dir={"": "src"},
474
+ packages=find_packages("src"),
475
+ include_package_data=True,
476
+ package_data={"": ["**/*.cu", "**/*.cpp", "**/*.cuh", "**/*.h", "**/*.pyx", "py.typed"]},
477
+ zip_safe=False,
478
+ extras_require=extras,
479
+ entry_points={
480
+ "console_scripts": [
481
+ "transformers=transformers.commands.transformers_cli:main",
482
+ "transformers-cli=transformers.commands.transformers_cli:main_cli",
483
+ ]
484
+ },
485
+ python_requires=">=3.9.0",
486
+ install_requires=list(install_requires),
487
+ classifiers=[
488
+ "Development Status :: 5 - Production/Stable",
489
+ "Intended Audience :: Developers",
490
+ "Intended Audience :: Education",
491
+ "Intended Audience :: Science/Research",
492
+ "License :: OSI Approved :: Apache Software License",
493
+ "Operating System :: OS Independent",
494
+ "Programming Language :: Python :: 3",
495
+ "Programming Language :: Python :: 3.9",
496
+ "Programming Language :: Python :: 3.10",
497
+ "Programming Language :: Python :: 3.11",
498
+ "Programming Language :: Python :: 3.12",
499
+ "Programming Language :: Python :: 3.13",
500
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
501
+ ],
502
+ cmdclass={"deps_table_update": DepsTableUpdateCommand},
503
+ )
504
+
505
+ extras["tests_torch"] = deps_list()
506
+ extras["tests_tf"] = deps_list()
507
+ extras["tests_flax"] = deps_list()
508
+ extras["tests_hub"] = deps_list()
509
+ extras["tests_pipelines_torch"] = deps_list()
510
+ extras["tests_pipelines_tf"] = deps_list()
511
+ extras["tests_onnx"] = deps_list()
512
+ extras["tests_examples_torch"] = deps_list()
513
+ extras["tests_examples_tf"] = deps_list()
514
+ extras["tests_custom_tokenizers"] = deps_list()
515
+ extras["tests_exotic_models"] = deps_list()
516
+ extras["consistency"] = deps_list()
upload2hf.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import HfApi
2
+ api = HfApi()
3
+
4
+ api.upload_large_folder(
5
+ repo_id="lsmpp/qwenillustrious",
6
+ repo_type="model",
7
+ folder_path=".",
8
+ )
uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
wandb/debug.log ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ 2025-10-15 20:49:38,941 INFO MainThread:6946 [wandb_init.py:setup_run_log_directory():705] Logging user logs to /home/ubuntu/lyl/QwenIllustrious/wandb/run-20251015_204938-edfjqsia/logs/debug.log
2
+ 2025-10-15 20:49:38,941 INFO MainThread:6946 [wandb_init.py:setup_run_log_directory():706] Logging internal logs to /home/ubuntu/lyl/QwenIllustrious/wandb/run-20251015_204938-edfjqsia/logs/debug-internal.log
3
+ 2025-10-15 20:49:38,942 INFO MainThread:6946 [wandb_init.py:init():832] calling init triggers
4
+ 2025-10-15 20:49:38,942 INFO MainThread:6946 [wandb_init.py:init():837] wandb.init called with sweep_config: {}
5
+ config: {'_wandb': {}}