File size: 26,322 Bytes
b2cf481
292e34d
b36a4e8
 
 
 
 
 
 
af83976
b36a4e8
af83976
 
b2cf481
 
 
 
 
 
af83976
 
 
b2cf481
 
af83976
b2cf481
 
af83976
 
 
b2cf481
af83976
b2cf481
292e34d
 
b2cf481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5b76c0
b36a4e8
b2cf481
f5d7c00
b2cf481
 
 
f5d7c00
 
b2cf481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bef1f5e
 
b2cf481
 
bef1f5e
 
b2cf481
bef1f5e
b2cf481
bef1f5e
 
b2cf481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d7c00
b2cf481
 
 
 
 
f5d7c00
b2cf481
 
 
f5d7c00
b2cf481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d7c00
 
 
b2cf481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
---
license: openrail++
base_model: diffusers/stable-diffusion-xl-base-1.0
tags:
- stable-diffusion-xl
- stable-diffusion-xl-diffusers
- stable-diffusion
- text-to-image
- diffusers
- di.FFusion.ai
inference: true
widget:
  - text: >-
      a dog in colorful exploding clouds, dreamlike surrealism colorful smoke and fire coming
      out of it, explosion of data fragments, exploding background,realistic explosion, 3d digital art
    example_title: Dogo FFusion
  - text: >-
      a sprinkled donut sitting on top of a table, colorful hyperrealism, everything is made of candy, hyperrealistic digital
      painting, covered in sprinkles and crumbs, vibrant colors hyper realism,colorful smoke explosion background
    example_title: Donut FFusion
  - text: >-
      a cup of coffee with a tree in it, surreal art, awesome great composition,
      surrealism, ice cubes in tree, colorful clouds, perfectly realistic yet surreal
    example_title: CoFFee FFusion
  - text: >-
      brightly colored headphones with a splash of colorful paint splash, vibing
      to music, stunning artwork, music is life, beautiful digital artwork, concept art, cinematic, dramatic, intricate details, dark
      lighting
    example_title: Headset FFusion
  - text: >-
      high-quality game character digital design, Unreal Engine, Water color painting, Mecha- Monstrous high quality game fantasy rpg character design, dark rainbow Fur Scarf, inside of a Superficial Outhouse, at Twilight, Overdetailed art
    example_title: Digital Fusion

language:
- en
model-index:
- name: FFusion/FFusionXL-BASE
  results:
  - task:
      type: text-to-image
      name: Text to Image Generation
    dataset:
      type: poloclub/diffusiondb
      name: DiffusionDB
      split: train
    metrics:
      - type: is
        value: 4.9797071218490601
        name: Inception Score
        verified: true
      - type: fid
        value: 311.33686580590006
        name: Fréchet Inception Distance
        verified: true
      - type: text-image-similarity
        value: 14.368797302246094
        name: Similarity Score (CLIP)
thumbnail: >-
  https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/p54u7dEP1u8en0--NMEjS.png
---

 ![FFusionXL-openvino-onnx-directml.png](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/Yhp6RIF2oKbx7cLPXCxMe.png)
<div style="display: flex; flex-wrap: wrap; gap: 2px;">
  <a href="https://huggingface.co/FFusion/"><img src="https://img.shields.io/badge/ONNX_Version-Available-brightgreen" alt="ONNX Version Available"></a>
  <a href="https://huggingface.co/FFusion/"><img src="https://img.shields.io/badge/OpenVINO-Support-blue" alt="OpenVINO Support"></a>
  <a href="https://huggingface.co/FFusion/"><img src="https://img.shields.io/badge/Compatibility-Intel%20|%20AMD%20|%20NVIDIA-orange" alt="Intel/AMD/NVIDIA Compatible"></a>
</div>

## 🌟 Overview


- 🚀 Fast Training: Optimized for high-speed training, allowing rapid experimentation.
- 🧩 Versatility: Suitable for various applications and standards, from NLP to Computer Vision.
- 🎓 Train Your Way: A base for training your own models, tailored to your needs.
- 🌐 Multilingual Support: Train models in multiple languages.
- 🛡️ Robust Architecture: Built on proven technologies to ensure stability and reliability.


## 📜 Model Description

FFusionXL "Base" is a foundational model designed to accelerate training processes. Crafted with flexibility in mind, it serves as a base for training custom models across a variety of standards, enabling innovation and efficiency.


<div style="display: flex; flex-wrap: wrap; gap: 2px;">
  <a href="#"><img src="https://img.shields.io/badge/Safetensor-FP16%20%26%20FP32-blue" alt="Safetensor checkpoints"></a>
  <a href="#"><img src="https://img.shields.io/badge/Diffusers(Safetensors)-FP16%20%26%20FP32-green" alt="Diffusers(safetensors)"></a>
  <a href="#"><img src="https://img.shields.io/badge/Diffusers(PyTorch%20Bin)-FP16%20%26%20FP32-orange" alt="Diffusers(pytorch bin)"></a>
  <a href="#"><img src="https://img.shields.io/badge/ONNX-Unoptimized%20FP32-red" alt="ONNX un-optimized FP32"></a>
  <a href="#"><img src="https://img.shields.io/badge/ONNX%20Optimized-FP16%20DirectML%20Support-blueviolet" alt="ONNX Optimized FP16 full DirectML support"></a>
  <a href="#"><img src="https://img.shields.io/badge/Intel®%20OpenVINO™-FP32%20%26%20FP16-brightgreen" alt="Intel® OpenVINO™ FP32 & FP16"></a>
</div>



**Available formats for training:**
 - Safetensor checkpoints fp16 & fp32
 - Diffusers(safetensors) FP 16 & FP32
 - Diffusers(pytorch bin) FP16 & FP32

 - ONNX un-optimzed FP32
 - **ONNX Optimized** FP16 full **DirectML** support / AMD / NVIDIA
 - Intel® OpenVINO™ FP32 - unoptimized
 - **Intel® OpenVINO™** FP16 

- **Trained by:** FFusion AI
- **Model type:** Diffusion-based text-to-image generative model
- **License:** [FFXL Research License](https://huggingface.co/FFusion/FFusionXL-09-SDXL/blob/main/LICENSE.md)
- **Model Description:** This is a trained model based on SDXL that can be used to generate and modify images based on text prompts. It is a [Latent Diffusion Model](https://arxiv.org/abs/2112.10752) that uses two fixed, pretrained text encoders ([OpenCLIP-ViT/G](https://github.com/mlfoundations/open_clip) and [CLIP-ViT/L](https://github.com/openai/CLIP/tree/main)).
- **Resources for more information:** [SDXL paper on arXiv](https://arxiv.org/abs/2307.01952).

## 📊 Model Sources

- **Demo:** [FFusionXL SDXL DEMO](https://huggingface.co/spaces/FFusion/FFusionXL-SDXL-DEMO)
![ffusionXL-Demo.png](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/qN9C9hn1lmhjD03wH34fo.png)


## Table of Contents

1. [📌 ONNX Version](#📌-onnx-version)
    1. [🔖 ### 📌 ONNX Details](#🔖-###-📌-onnx-details)
    2. [🔖 ### 📌 AMD Support for Microsoft® DirectML Optimization of Stable Diffusion](#🔖-###-📌-amd-support-for-microsoft®-directml-optimization-of-stable-diffusion)
    3. [🔖 ### 📌 ONNX Inference Instructions](#🔖-###-📌-onnx-inference-instructions)
    4. [🔖 ### 📌 Text-to-Image](#🔖-###-📌-text-to-image)
2. [📌 Intel® OpenVINO™ Version](#📌-intel®-openvino™-version)
    1. [📌 OpenVINO Inference with FFusion/FFusionXL-BASE](#📌-openvino-inference-with-ffusion/ffusionxl-base)
    2. [🔖 ### 📌 Installing Dependencies](#🔖-###-📌-installing-dependencies)
    3. [🔖 ### 📌 Text-to-Image](#🔖-###-📌-text-to-image)
    4. [🔖 ### 📌 Text-to-Image with Textual Inversion](#🔖-###-📌-text-to-image-with-textual-inversion)
    5. [🔖 ### 📌 Image-to-Image](#🔖-###-📌-image-to-image)
    6. [🔖 ### 📌 Refining the Image Output](#🔖-###-📌-refining-the-image-output)
  3. [📜 Part 003: 🧨 Model Diffusers, Fast LoRa Loading, and Training](#📜-part-001:-🧨-model-diffusers,-fast-lora-loading,-and-training)
    1. [📌 Model Diffusers: Unleashing the Power of FFusion/FFusionXL-BASE](#📌-model-diffusers:-unleashing-the-power-of-ffusion/ffusionxl-base)
    2. [📌 Installing the dependencies](#📌-installing-the-dependencies)
    3. [📌 Training](#📌-training)
    4. [📌 Inference](#📌-inference)
    5. [📌 Training](#📌-training)
    6. [📌 Finetuning the text encoder and UNet](#📌-finetuning-the-text-encoder-and-unet)
    7. [📌 Inference](#📌-inference)
4. [📌 Evaluation](#📌-evaluation)






### ### 📌 ONNX Version
![preview-ffusionAI__base_00026_ copy.jpg](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/tJgVy8KKQljYCgW3SH--K.jpeg)

We are proud to announce a fully optimized Microsoft ONNX Version exclusively compatible with the latest DirectML Execution Provider. All the ONNX files are optimized (Quantization) to fp16 for fast inference and training across all devices.

The Vae_Decoder is kept at fp32 with settings:

```json
"float16": false,
"use_gpu": true,
"keep_io_types": true,
"force_fp32_ops": ["RandomNormalLike"]
```

to avoid black screens and broken renders. As soon as a proper solution for a full fp16 VAE decoder arrives, we will update it. VAE encoder and everything else is fully optimized 🤟.

Our ONNX is OPTIMIZED using ONNX v8:

- **producer:** onnxruntime.transformers 1.15.1
- **imports:** ai.onnx v18, com.microsoft.nchwc v1, ai.onnx.ml v3, com.ms.internal.nhwc v19, ai.onnx.training v1, ai.onnx.preview.training v1, com.microsoft v1, com.microsoft.experimental v1, org.pytorch.aten v1, com.microsoft.dml v1, graph: torch_jit


#### 🔖 ### 📌 ONNX Details

**NETRON** Detrails:
![onxxapp-nutron-ffusionai.jpg](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/8dpibhpV7_Uo0B8_7zQXk.jpeg)
## Install

**macOS**: [**Download**](https://github.com/lutzroeder/netron/releases/latest) the `.dmg` file or run `brew install --cask netron`

**Linux**: [**Download**](https://github.com/lutzroeder/netron/releases/latest) the `.AppImage` file or run `snap install netron`

**Windows**: [**Download**](https://github.com/lutzroeder/netron/releases/latest) the `.exe` installer or run `winget install -s winget netron`


https://netron.app/

-- **NETRON browser version**:  [Start **Text Encoder**](https://netron.app/?url=https://huggingface.co/FFusion/FFusionXL-BASE/blob/main/text_encoder/model.onnx)
[![Text Encoder1 FFusionXL.jpg](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/KdC7aG_qiUsLctMb6Ij3Y.jpeg)](https://netron.app/?url=https://huggingface.co/FFusion/FFusionXL-BASE/blob/main/text_encoder/model.onnx)


--**NETRON browser version**:  [Start **Text Encoder 2**](https://netron.app/?url=https://huggingface.co/FFusion/FFusionXL-BASE/blob/main/text_encoder_2/model.onnx)
[![TextEncoder2 FFusionXL.jpg](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/faCpPKG1fHmqQmi7BdlbO.jpeg)](https://netron.app/?url=https://huggingface.co/FFusion/FFusionXL-BASE/blob/main/text_encoder_2/model.onnx)

--**NETRON browser version**:  [Start **VAE decoder**](https://netron.app/?url=https://huggingface.co/FFusion/FFusionXL-BASE/blob/main/vae_decoder/model.onnx)

--**NETRON browser version**:  [Start **VAE encoder**](https://netron.app/?url=https://huggingface.co/FFusion/FFusionXL-BASE/blob/main/vae_encoder/model.onnx)
[![VAE encoder FFUSION-ai-Screenshot_2016.jpg](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/pm824V7Fyv22x7yHjDsfE.jpeg)](https://netron.app/?url=https://huggingface.co/FFusion/FFusionXL-BASE/blob/main/vae_encoder/model.onnx)

--**NETRON browser version**:  [Start **UNET**](https://netron.app/?url=https://huggingface.co/stabilityai/FFusion/FFusionXL-BASE/blob/main/unet/model.onnx)



##### 🔖 ### 📌 AMD Support for Microsoft® DirectML Optimization of Stable Diffusion

![FFusionXL-directML.jpg](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/AWcddnCm1rEpSW0Ta6beV.jpeg)

AMD has released support for Microsoft DirectML optimizations for Stable Diffusion, working closely with Microsoft for optimal performance on AMD devices.

[Microsoft DirectML](https://microsoft.github.io/DirectML/)
[AMD Microsoft DirectML Stable Diffusion](https://gpuopen.com/amd-microsoft-directml-stable-diffusion/)


#### 🔖 ### 📌 ONNX Inference Instructions
![Onnx-FFusionXL1.jpg](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/QJjulnRe4iJHhWPb1c2nY.jpeg)



##### 🔖 ### 📌 Text-to-Image

Here is an example of how you can load an ONNX Stable Diffusion model and run inference using ONNX Runtime:

```python
from optimum.onnxruntime import ORTStableDiffusionPipeline

model_id = "FFusion/FFusionXL-BASE"
pipeline = ORTStableDiffusionPipeline.from_pretrained(model_id)
prompt = "sailing ship in storm by Leonardo da Vinci"
images = pipeline(prompt).images
```




### ### 📌 Intel® OpenVINO™ Version

A converted Intel® OpenVINO™ model is also included for inference testing and training. No Quantization and optimization applied yet.





---

### ### 📌 OpenVINO Inference with FFusion/FFusionXL-BASE

#### 🔖 ### 📌 Installing Dependencies

Before using `OVStableDiffusionXLPipeline`, make sure to have `diffusers` and `invisible_watermark` installed. You can install the libraries as follows:

```bash
pip install diffusers
pip install invisible-watermark>=0.2.0
```

#### 🔖 ### 📌 Text-to-Image

Here is an example of how you can load a FFusion/FFusionXL-BASE OpenVINO model and run inference using OpenVINO Runtime:

```python
from optimum.intel import OVStableDiffusionXLPipeline

model_id = "FFusion/FFusionXL-BASE"
base = OVStableDiffusionXLPipeline.from_pretrained(model_id)
prompt = "train station by Caspar David Friedrich"
image = base(prompt).images[0]
image.save("train_station.png")
```

#### 🔖 ### 📌 Text-to-Image with Textual Inversion

First, you can run the original pipeline without textual inversion:

```python
from optimum.intel import OVStableDiffusionXLPipeline
import numpy as np

model_id = "FFusion/FFusionXL-BASE"
prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a beautiful cyber female wearing a black corset and pink latex shirt, scifi best quality, intricate details."
np.random.seed(0)

base = OVStableDiffusionXLPipeline.from_pretrained(model_id, export=False, compile=False)
base.compile()
image1 = base(prompt, num_inference_steps=50).images[0]
image1.save("sdxl_without_textual_inversion.png")
```

Then, you can load `charturnerv2` textual inversion embedding and run the pipeline with the same prompt again:

```python
# Reset stable diffusion pipeline
base.clear_requests()

# Load textual inversion into stable diffusion pipeline
base.load_textual_inversion("./charturnerv2.pt", "charturnerv2")

# Compile the model before the first inference
base.compile()
image2 = base(prompt, num_inference_steps=50).images[0]
image2.save("sdxl_with_textual_inversion.png")
```

![SDXL-preview.png](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/HocDOL_Tlxsqe9qKMRwyp.png)
![FFusi1onXL_with_textual_inveaarsion1.png](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/bkkQSPWD8Zt736eihubEi.png)
![FFusionXL_with_textual_inversion1.png](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/oX4CWQwbuQn4WiBDbOwM6.png)


#### 🔖 ### 📌 Image-to-Image

Here is an example of how you can load a PyTorch FFusion/FFusionXL-BASE model, convert it to OpenVINO on-the-fly, and run inference using OpenVINO Runtime for image-to-image:

```python
from optimum.intel import OVStableDiffusionXLImg2ImgPipeline
from diffusers.utils import load_image

model_id = "FFusion/FFusionXL-BASE-refiner-1.0"
pipeline = OVStableDiffusionXLImg2ImgPipeline.from_pretrained(model_id, export=True)

url = "https://huggingface.co/datasets/optimum/documentation-images/resolve/main/intel/openvino/sd_xl/castle_friedrich.png"
image = load_image(url).convert("RGB")
prompt = "medieval castle by Caspar David Friedrich"
image = pipeline(prompt, image=image).images[0]
pipeline.save_pretrained("openvino-FF-xl-refiner-1.0")
```

#### 🔖 ### 📌 Refining the Image Output

The image can be refined by making use of a model like `FFusion/FFusionXL-BASE-refiner-1.0`. In this case, you only have to output the latents from the base model.

```python
from optimum.intel import OVStableDiffusionXLImg2ImgPipeline

model_id = "FFusion/FFusionXL-BASE-refiner-1.0"
refiner = OVStableDiffusionXLImg2ImgPipeline.from_pretrained(model_id, export=True)

image = base(prompt=prompt, output_type="latent").images[0]
image = refiner(prompt=prompt, image=image[None, :]).images[0]
```

## 📜 Part 003: 🧨 Model Diffusers, Fast LoRa Loading, and Training

### ### 📌 Model Diffusers: Unleashing the Power of FFusion/FFusionXL-BASE

Whether you're an artist, researcher, or AI enthusiast, our model is designed to make your journey smooth and exciting.
Make sure to upgrade diffusers to >= 0.19.3:
```bash
pip install diffusers --upgrade
```
In addition, make sure to install `transformers`, `safetensors`, `accelerate`, and the invisible watermark:
```bash
pip install invisible_watermark transformers accelerate safetensors
```

You can use the model then as follows:
```python
from diffusers import DiffusionPipeline
import torch

pipe = DiffusionPipeline.from_pretrained("FFusion/FFusionXL-09-SDXL", torch_dtype=torch.float16, use_safetensors=True, variant="fp16")
pipe.to("cuda")

# if using torch < 2.0
# pipe.enable_xformers_memory_efficient_attention()

prompt = "An astronaut riding a green horse"

images = pipe(prompt=prompt).images[0]
```

## 📜 Diffusers Training Guide: Training FFusion/FFusionXL-BASE with LoRA

# Stable Diffusion XL text-to-image fine-tuning

The `train_text_to_image_sdxl.py` script shows how to fine-tune Stable Diffusion XL (SDXL) on your own dataset.

🚨 This script is experimental. The script fine-tunes the whole model and often times the model overfits and runs into issues like catastrophic forgetting. It's recommended to try different hyperparamters to get the best result on your dataset. 🚨

## 📜 Running locally with PyTorch

### ### 📌 Installing the dependencies

Before running the scripts, make sure to install the library's training dependencies:

**Important**

To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:

```bash
git clone https://github.com/huggingface/diffusers
cd diffusers
pip install -e .
```

Then cd in the `examples/text_to_image` folder and run
```bash
pip install -r requirements_sdxl.txt
```

And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:

```bash
accelerate config
```

Or for a default accelerate configuration without answering questions about your environment

```bash
accelerate config default
```

Or if your environment doesn't support an interactive shell (e.g., a notebook)

```python
from accelerate.utils import write_basic_config
write_basic_config()
```

When running `accelerate config`, if we specify torch compile mode to True there can be dramatic speedups. 





### ### 📌 Training

```bash
export MODEL_NAME="FFusion/FFusionXL-BASE"
export VAE="madebyollin/sdxl-vae-fp16-fix"
export DATASET_NAME="lambdalabs/pokemon-blip-captions"

accelerate launch train_text_to_image_sdxl.py \
  --pretrained_model_name_or_path=$MODEL_NAME \
  --pretrained_vae_model_name_or_path=$VAE \
  --dataset_name=$DATASET_NAME \
  --enable_xformers_memory_efficient_attention \
  --resolution=512 --center_crop --random_flip \
  --proportion_empty_prompts=0.2 \
  --train_batch_size=1 \
  --gradient_accumulation_steps=4 --gradient_checkpointing \
  --max_train_steps=10000 \
  --use_8bit_adam \
  --learning_rate=1e-06 --lr_scheduler="constant" --lr_warmup_steps=0 \
  --mixed_precision="fp16" \
  --report_to="wandb" \
  --validation_prompt="a cute Sundar Pichai creature" --validation_epochs 5 \
  --checkpointing_steps=5000 \
  --output_dir="sdxl-pokemon-model" \
  --push_to_hub
```

**Notes**: 

*  The `train_text_to_image_sdxl.py`(diffusers/examples/text_to_image) script pre-computes text embeddings and the VAE encodings and keeps them in memory. While for smaller datasets like [`lambdalabs/pokemon-blip-captions`](https://hf.co/datasets/lambdalabs/pokemon-blip-captions), it might not be a problem, it can definitely lead to memory problems when the script is used on a larger dataset. For those purposes, you would want to serialize these pre-computed representations to disk separately and load them during the fine-tuning process. Refer to [this PR](https://github.com/huggingface/diffusers/pull/4505) for a more in-depth discussion. 
* The training script is compute-intensive and may not run on a consumer GPU like Tesla T4. 
* The training command shown above performs intermediate quality validation in between the training epochs and logs the results to Weights and Biases. `--report_to`, `--validation_prompt`, and `--validation_epochs` are the relevant CLI arguments here.
examples/text_to_image 
### ### 📌 Inference

```python
from diffusers import DiffusionPipeline
import torch

model_path = "FFusion/FFusionXL-BASE" # <-- change this to your new trained model
pipe = DiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float16)
pipe.to("cuda")

prompt = "A pokemon with green eyes and red legs."
image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
image.save("pokemon.png")
```

## 📜 LoRA training example for Stable Diffusion XL (SDXL)

Low-Rank Adaption of Large Language Models was first introduced by Microsoft in [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/abs/2106.09685) by *Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen*.

In a nutshell, LoRA allows adapting pretrained models by adding pairs of rank-decomposition matrices to existing weights and **only** training those newly added weights. This has a couple of advantages:

- Previous pretrained weights are kept frozen so that model is not prone to [catastrophic forgetting](https://www.pnas.org/doi/10.1073/pnas.1611835114).
- Rank-decomposition matrices have significantly fewer parameters than original model, which means that trained LoRA weights are easily portable.
- LoRA attention layers allow to control to which extent the model is adapted toward new training images via a `scale` parameter.

[cloneofsimo](https://github.com/cloneofsimo) was the first to try out LoRA training for Stable Diffusion in the popular [lora](https://github.com/cloneofsimo/lora) GitHub repository.

With LoRA, it's possible to fine-tune Stable Diffusion on a custom image-caption pair dataset
on consumer GPUs like Tesla T4, Tesla V100.

### ### 📌 Training

First, you need to set up your development environment as is explained in the [installation section](#installing-the-dependencies). Make sure to set the `MODEL_NAME` and `DATASET_NAME` environment variables. Here, we will use [Stable Diffusion XL 1.0-base](https://huggingface.co/FFusion/FFusionXL-BASE) and the [Pokemons dataset](https://huggingface.co/datasets/lambdalabs/pokemon-blip-captions).  

**___Note: It is quite useful to monitor the training progress by regularly generating sample images during training. [Weights and Biases](https://docs.wandb.ai/quickstart) is a nice solution to easily see generating images during training. All you need to do is to run `pip install wandb` before training to automatically log images.___**

```bash
export MODEL_NAME="FFusion/FFusionXL-BASE"
export DATASET_NAME="lambdalabs/pokemon-blip-captions"
```

For this example we want to directly store the trained LoRA embeddings on the Hub, so 
we need to be logged in and add the `--push_to_hub` flag.

```bash
huggingface-cli login
```

Now we can start training!

```bash
accelerate launch train_text_to_image_lora_sdxl.py \
  --pretrained_model_name_or_path=$MODEL_NAME \
  --dataset_name=$DATASET_NAME --caption_column="text" \
  --resolution=1024 --random_flip \
  --train_batch_size=1 \
  --num_train_epochs=2 --checkpointing_steps=500 \
  --learning_rate=1e-04 --lr_scheduler="constant" --lr_warmup_steps=0 \
  --seed=42 \
  --output_dir="sd-pokemon-model-lora-sdxl" \
  --validation_prompt="cute dragon creature" --report_to="wandb" \
  --push_to_hub
```

The above command will also run inference as fine-tuning progresses and log the results to Weights and Biases.

### ### 📌 Finetuning the text encoder and UNet

The script also allows you to finetune the `text_encoder` along with the `unet`.

🚨 Training the text encoder requires additional memory.

Pass the `--train_text_encoder` argument to the training script to enable finetuning the `text_encoder` and `unet`:

```bash
accelerate launch train_text_to_image_lora_sdxl.py \
  --pretrained_model_name_or_path=$MODEL_NAME \
  --dataset_name=$DATASET_NAME --caption_column="text" \
  --resolution=1024 --random_flip \
  --train_batch_size=1 \
  --num_train_epochs=2 --checkpointing_steps=500 \
  --learning_rate=1e-04 --lr_scheduler="constant" --lr_warmup_steps=0 \
  --seed=42 \
  --output_dir="sd-pokemon-model-lora-sdxl-txt" \
  --train_text_encoder \
  --validation_prompt="cute dragon creature" --report_to="wandb" \
  --push_to_hub
```

### ### 📌 Inference

Once you have trained a model using above command, the inference can be done simply using the `DiffusionPipeline` after loading the trained LoRA weights.  You 
need to pass the `output_dir` for loading the LoRA weights which, in this case, is `sd-pokemon-model-lora-sdxl`.

```python
from diffusers import DiffusionPipeline
import torch

model_path = "takuoko/sd-pokemon-model-lora-sdxl"
pipe = DiffusionPipeline.from_pretrained("FFusion/FFusionXL-BASE", torch_dtype=torch.float16)
pipe.to("cuda")
pipe.load_lora_weights(model_path)

prompt = "A pokemon with green eyes and red legs."
image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
image.save("pokemon.png")
```


### ### 📌 Evaluation

![evaluation-ffusionAI.jpg](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/NPrW6dc_JsAxZrZZRDC_M.jpeg)
![evaluation-ffusionXL.jpg](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/b0Z2M7wp-MqCXes595ulX.jpeg)

![image_comparisons.png](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/m890TYI3HTk6xYMPBrLQN.png)
![combined_FFigure.png](https://cdn-uploads.huggingface.co/production/uploads/6380cf05f496d57325c12194/I67ri4P06doH7l2n7x1G0.png)


Utilizing yuvalkirstain/PickScore_v1 model, this analysis was conducted by FFusion.AI. It serves as a vital contribution to the ongoing research in testing Stable Diffusion Models' prompt win rate and accuracy.


📧 For any inquiries or support, please contact di@ffusion.ai. We're here to help you every step of the way!