Skip to content

Instantly share code, notes, and snippets.

@Stella2211
Last active January 17, 2024 03:59
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Stella2211/ab17625d63aa03e38d82ddc8c1aae151 to your computer and use it in GitHub Desktop.
Save Stella2211/ab17625d63aa03e38d82ddc8c1aae151 to your computer and use it in GitHub Desktop.
DeepFloyd IF for around 12GB of VRAM
# huggingface login
from huggingface_hub import login
login()
# load textencorder in 8bit quantized
from transformers import T5EncoderModel
from diffusers import DiffusionPipeline
import datetime
import gc
import torch
from diffusers.utils import pt_to_pil
def flush():
gc.collect()
torch.cuda.empty_cache()
default_prompt = "anime girl, silver hair and blue eyes, smile"
default_negative_prompt = "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry"
default_steps = 50
while(True):
prompt = input("prompt: ")
if(prompt == ""):prompt = default_prompt
elif(prompt == "exit()"):break
negative_prompt = input("negative_prompt: ")
if(negative_prompt == ""):negative_prompt = default_negative_prompt
elif(negative_prompt == " "):negative_prompt = ""
steps = input(f"stage1 steps(default: {default_steps}): ")
if(steps == ""):steps = default_steps
else:steps = int(steps)
start_dt = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
print("Loading Text Encoder...",end="")
text_encoder = T5EncoderModel.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0",
subfolder="text_encoder",
device_map="auto",
load_in_8bit=True,
variant="8bit"
)
print("finish!")
# load stage1 model for text encording
print("Encording Text...",end="")
pipe = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0",
text_encoder=text_encoder, # pass the previously instantiated 8bit text encoder
unet=None,
device_map="auto"
)
prompt_embeds, negative_embeds = pipe.encode_prompt(prompt=prompt, negative_prompt=negative_prompt)
print("finish!")
# unload textencorder
del text_encoder
del pipe
flush()
# load stage1 model for generation
print("Loading stage1 model...",end="")
pipe = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0",
text_encoder=None,
variant="fp16",
torch_dtype=torch.float16,
device_map="auto"
)
print("finish!")
print("Generating images...",end="")
generator = torch.Generator().manual_seed(1)
image = pipe(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
output_type="pt",
generator=generator,
num_inference_steps=steps,
).images
print("finish!")
#apply watermarks
pil_image = pt_to_pil(image)
pipe.watermarker.apply_watermark(pil_image, pipe.unet.config.sample_size)
pil_image[0].save(f"./{start_dt}_DeepFloyd_IFstage1.png")
# unload stage1 model
del pipe
flush()
proceed_check = input("Proceed to the next stage?: ")
if(proceed_check == "no" or proceed_check == "NO" or proceed_check == "N"):
continue
# load stage2 model
print("Loading stage2 model...",end="")
pipe = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0",
text_encoder=None, # no use of text encoder => memory savings!
variant="fp16",
torch_dtype=torch.float16,
device_map="auto"
)
print("Generating...")
image = pipe(
image=image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
output_type="pt",
generator=generator,
).images
print("finish!")
pil_image = pt_to_pil(image)
pipe.watermarker.apply_watermark(pil_image, pipe.unet.config.sample_size)
pil_image[0].save(f"./{start_dt}_DeepFloyd_IFstage2.png")
#unload stage2 model
del pipe
flush()
proceed_check = input("Proceed to the next stage?: ")
if(proceed_check == "no" or proceed_check == "NO" or proceed_check == "N"):
continue
# load stage3 model
print("Loading stage3 model...",end="")
pipe = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler",
torch_dtype=torch.float16,
device_map="auto"
)
print("finish!")
pil_image = pipe(prompt, generator=generator, image=image).images
#apply watermarks
from diffusers.pipelines.deepfloyd_if import IFWatermarker
watermarker = IFWatermarker.from_pretrained("DeepFloyd/IF-I-XL-v1.0", subfolder="watermarker")
watermarker.apply_watermark(pil_image, pipe.unet.config.sample_size)
pil_image[0].save(f"./{start_dt}_DeepFloyd_IFstage3.png")
del watermarker
flush()
Copyright (c) 2023 Stella
This code is based on the original code developed by DeepFloyd and StabilityAI.
The original code is licensed under the following terms:
Copyright (c) 2023 DeepFloyd, StabilityAI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
2. All persons obtaining a copy or substantial portion of the Software,
a modified version of the Software (or substantial portion thereof), or
a derivative work based upon this Software (or substantial portion thereof)
must not delete, remove, disable, diminish, or circumvent any inference filters or
inference filter mechanisms in the Software, or any portion of the Software that
implements any such filters or filter mechanisms.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This code is subject to the same terms and conditions as the original code.
@Stella2211
Copy link
Author

Stella2211 commented Apr 28, 2023

公式Colabのコードをベースに、WSL環境で動作するようにしました。/Based on the official Colab code, it works in a WSL environment.
bitsandbytesの問題でwindowsでは動作しないので、必ずWSLを利用してください!/Be sure to use WSL as it will not work on windows due to bitsandbytes issues!
下記のコマンドでパッケージをインストールしてください。/Install the package with the following command.

pip install --upgrade diffusers~=0.16 transformers~=4.28 safetensors~=0.3 sentencepiece~=0.1 accelerate~=0.18 bitsandbytes~=0.38 torch torchvision

@LIU-ZHIHAO
Copy link

im try it,but has error:

(venv) root@liuzh:/deepfloyd-if# python test.py

_|    _|  _|    _|    _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|_|_|_|    _|_|      _|_|_|  _|_|_|_|
_|    _|  _|    _|  _|        _|          _|    _|_|    _|  _|            _|        _|    _|  _|        _|
_|_|_|_|  _|    _|  _|  _|_|  _|  _|_|    _|    _|  _|  _|  _|  _|_|      _|_|_|    _|_|_|_|  _|        _|_|_|
_|    _|  _|    _|  _|    _|  _|    _|    _|    _|    _|_|  _|    _|      _|        _|    _|  _|        _|
_|    _|    _|_|      _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|        _|    _|    _|_|_|  _|_|_|_|

A token is already saved on your machine. Run `huggingface-cli whoami` to get more information or `huggingface-cli logout` if you want to log out.
Setting a new token will erase the existing one.
To login, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .

Token:
Add token as git credential? (Y/n) y
Token is valid.
Cannot authenticate through git-credential as no helper is defined on your machine.
You might have to re-authenticate when pushing to the Hugging Face Hub.
Run the following command in your terminal in case you want to set the 'store' credential helper as default.

git config --global credential.helper store

Read https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more details.
Token has not been saved to git credential helper.
Your token has been saved to /root/.cache/huggingface/token
Login successful
prompt:
negative_prompt:
stage1 steps(default: 50):
Loading Text Encoder...Traceback (most recent call last):
File "test.py", line 37, in
text_encoder = T5EncoderModel.from_pretrained(
File "/deepfloyd-if/venv/lib/python3.8/site-packages/transformers/modeling_utils.py", line 2276, in from_pretrained
model = cls(config, *model_args, **model_kwargs)
TypeError: init() got an unexpected keyword argument 'variant'
(venv) root@liuzh:/deepfloyd-if# pip list
Package Version


accelerate 0.15.0
antlr4-python3-runtime 4.9.3
beautifulsoup4 4.11.2
bitsandbytes 0.38.1
certifi 2022.12.7
charset-normalizer 3.1.0
cmake 3.26.3
contourpy 1.0.7
cycler 0.11.0
deepfloyd-if 1.0.1
diffusers 0.16.1
filelock 3.12.0
fonttools 4.39.3
fsspec 2023.4.0
ftfy 6.1.1
huggingface-hub 0.14.1
idna 3.4
importlib-metadata 6.6.0
importlib-resources 5.12.0
Jinja2 3.1.2
kiwisolver 1.4.4
lit 16.0.2
MarkupSafe 2.1.2
matplotlib 3.7.1
mpmath 1.3.0
networkx 3.1
numpy 1.24.3
nvidia-cublas-cu11 11.10.3.66
nvidia-cuda-cupti-cu11 11.7.101
nvidia-cuda-nvrtc-cu11 11.7.99
nvidia-cuda-runtime-cu11 11.7.99
nvidia-cudnn-cu11 8.5.0.96
nvidia-cufft-cu11 10.9.0.58
nvidia-curand-cu11 10.2.10.91
nvidia-cusolver-cu11 11.4.0.1
nvidia-cusparse-cu11 11.7.4.91
nvidia-nccl-cu11 2.14.3
nvidia-nvtx-cu11 11.7.91
omegaconf 2.3.0
packaging 23.1
Pillow 9.5.0
pip 20.0.2
pkg-resources 0.0.0
psutil 5.9.5
pyparsing 3.0.9
python-dateutil 2.8.2
PyYAML 6.0
regex 2023.5.4
requests 2.29.0
safetensors 0.3.1
sentencepiece 0.1.99
setuptools 44.0.0
six 1.16.0
soupsieve 2.4.1
sympy 1.11.1
tokenizers 0.13.3
torch 1.13.1
torchvision 0.15.1
tqdm 4.65.0
transformers 4.25.1
triton 2.0.0
typing-extensions 4.5.0
urllib3 1.26.15
wcwidth 0.2.6
wheel 0.40.0
zipp 3.15.0
(venv) root@liuzh:/deepfloyd-if# nvi
nvidia-smi nvidia-smi.exe nvinfo.pb
(venv) root@liuzh:/deepfloyd-if# nvidia-smi
Wed May 3 10:05:01 2023
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 527.92.01 Driver Version: 528.02 CUDA Version: 12.0 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 NVIDIA GeForce ... On | 00000000:2E:00.0 On | N/A |
| 30% 34C P8 24W / 300W | 761MiB / 22528MiB | 2% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
| No running processes found |
+-----------------------------------------------------------------------------+
(venv) root@liuzh:/deepfloyd-if#

@Stella2211
Copy link
Author

Stella2211 commented May 3, 2023

Thank you for reporting this issue!
It is probably due to the deepfloyd-if package specifying an older version of the transformer, so I think the following command will solve the problem.

pip uninstall deepfloyd-if
pip install -U transformers~=4.28

If this does not solve the problem, please create venv again and re-install the dependencies with the following command.
You do not need to install the deepfloyd-if package.
pip install --upgrade diffusers~=0.16 transformers~=4.28 safetensors~=0.3 sentencepiece~=0.1 accelerate~=0.18 bitsandbytes~=0.38 torch torchvision

@LIU-ZHIHAO
Copy link

I tried to regenerate the venv environment(not install deepfloyd-if), but the execution of the script still gave an error:
Token has not been saved to git credential helper.
Your token has been saved to /root/.cache/huggingface/token
Login successful
prompt:
negative_prompt:
stage1 steps(default: 50):
Overriding torch_dtype=None with torch_dtype=torch.float16 due to requirements of bitsandbytes to enable model loading in mixed int8. Either pass torch_dtype=torch.float16 or don't pass this argument at all to remove this warning.
Loading Text Encoder...
===================================BUG REPORT===================================
Welcome to bitsandbytes. For bug reports, please run

python -m bitsandbytes

and submit this information together with your error trace to: https://github.com/TimDettmers/bitsandbytes/issues

bin /deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so
/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/cuda_setup/main.py:145: UserWarning: /deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so did not contain ['libcudart.so', 'libcudart.so.11.0', 'libcudart.so.12.0'] as expected! Searching further paths...
warn(msg)
CUDA_SETUP: WARNING! libcudart.so not found in any environmental path. Searching in backup paths...
/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/cuda_setup/main.py:145: UserWarning: WARNING: The following directories listed in your path were found to be non-existent: {PosixPath('/usr/local/cuda/lib64')}
warn(msg)
CUDA SETUP: WARNING! libcuda.so not found! Do you have a CUDA driver installed? If you are on a cluster, make sure you are on a CUDA machine!
/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/cuda_setup/main.py:145: UserWarning: WARNING: No libcudart.so found! Install CUDA or the cudatoolkit package (anaconda)!
warn(msg)
/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/cuda_setup/main.py:145: UserWarning: WARNING: No GPU detected! Check your CUDA paths. Proceeding to load CPU-only library...
warn(msg)
CUDA SETUP: Loading binary /deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so...
libcudart.so.12: cannot open shared object file: No such file or directory
CUDA SETUP: Problem: The main issue seems to be that the main CUDA library was not detected.
CUDA SETUP: Solution 1): Your paths are probably not up-to-date. You can update them via: sudo ldconfig.
CUDA SETUP: Solution 2): If you do not have sudo rights, you can do the following:
CUDA SETUP: Solution 2a): Find the cuda library via: find / -name libcuda.so 2>/dev/null
CUDA SETUP: Solution 2b): Once the library is found add it to the LD_LIBRARY_PATH: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:FOUND_PATH_FROM_2a
CUDA SETUP: Solution 2c): For a permanent solution add the export from 2b into your .bashrc file, located at ~/.bashrc
Traceback (most recent call last):
File "/mnt/e/example2.py", line 37, in
text_encoder = T5EncoderModel.from_pretrained(
File "/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/transformers/modeling_utils.py", line 2639, in from_pretrained
from .utils.bitsandbytes import get_keys_to_not_convert, replace_8bit_linear
File "/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/transformers/utils/bitsandbytes.py", line 9, in
import bitsandbytes as bnb
File "/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/init.py", line 6, in
from . import cuda_setup, utils, research
File "/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/research/init.py", line 1, in
from . import nn
File "/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/research/nn/init.py", line 1, in
from .modules import LinearFP8Mixed, LinearFP8Global
File "/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/research/nn/modules.py", line 8, in
from bitsandbytes.optim import GlobalOptimManager
File "/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/optim/init.py", line 6, in
from bitsandbytes.cextension import COMPILED_WITH_CUDA
File "/deepfloyd-if/IF-16GB/lib/python3.8/site-packages/bitsandbytes/cextension.py", line 20, in
raise RuntimeError('''
RuntimeError:
CUDA Setup failed despite GPU being available. Please run the following command to get more information:

    python -m bitsandbytes

    Inspect the output of the command and see if you can locate CUDA libraries. You might need to add them
    to your LD_LIBRARY_PATH. If you suspect a bug, please take the information from python -m bitsandbytes
    and open an issue at: https://github.com/TimDettmers/bitsandbytes/issues

@Stella2211
Copy link
Author

Stella2211 commented May 3, 2023

Thank you for reporting this issue.
It may be related to the bitsandbytes issue at TimDettmers/bitsandbytes#332.
According to this issue, it can be solved by making bitsandbytes recognize the path to libcuda.so with the following command:

export PATH="$PATH:/usr/local/cuda/bin"
export LD_LIBRARY_PATH="/usr/lib/wsl/lib:/usr/local/cuda/lib64"

@LIU-ZHIHAO
Copy link

Thank you for your reply, I am Ubuntu20.04 system, there is no such directory in the system:/usr/local/cuda

@Stella2211
Copy link
Author

Stella2211 commented May 3, 2023

Thank you for your reply.
Could you please make the following changes to lines 41 and 42:
From:

load_in_8bit=True, 
variant="8bit"

To:

load_in_8bit=False, 
variant="fp16"

Alternatively, you could try the project below, which is a DeepFloyd IF clone that runs on 8GB VRAM. It's likely faster, so give it a try: https://github.com/neonsecret/IF

@LIU-ZHIHAO
Copy link

After installing the cuda environment and set PATH*, it can be executed:
URL:https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&Distribution=WSL-Ubuntu&target_version=2.0&target_type=deb_local

export PATH="$PATH:/usr/local/cuda/bin"
export LD_LIBRARY_PATH="/usr/lib/wsl/lib:/usr/local/cuda/lib64"

@Stella2211
Copy link
Author

Stella2211 commented May 3, 2023

Sorry, correction to my earlier comment, instead of setting variant=None, please change it to variant="fp16" as it is faster and lighter.
I will change my earlier comment to that as well.

These steps have been modified so that they do not use bitsandbytes, so if bitsandbytes seems to work normally, they are unnecessary.

@LIU-ZHIHAO
Copy link

During my use, the program takes up a lot of memory, and sometimes even causes memory overflow (32GB RAM), and the gc recovery of the script seems to have no effect

@Stella2211
Copy link
Author

Stella2211 commented May 4, 2023

Thank you for reporting the memory overflow issue on my GitHub repository. However, I am unable to reproduce the issue on my 16GB RAM Windows PC, and thus cannot provide a solution at this time. Thank you for bringing this to my attention.

As an alternative solution, there is a project called Radiata on GitHub that is planning to implement DeepFloyd IF within this week. I am not affiliated with the project, so I do not have any further details, but it appears that they are developing a web UI that supports both stable diffusion and DeepFloyd IF. Here is the link to their repository: https://github.com/ddPn08/Radiata

@behelit2
Copy link

behelit2 commented May 4, 2023

I really like this script, but unfortunately I had trouble getting it working with the Tesla K80. I think it's just too old to work with bitsandbytes properly. However, your code was very helpful in getting my own script working. Thank you!

@Stella2211
Copy link
Author

Thank you for your feedback, and I'm glad to hear that my code was helpful for you!
You can run this script without relying on bitsandbytes by making the following changes to lines 41 and 42:

load_in_8bit=False, 
variant="fp16"

This should allow the script to work without issue, though it may run a bit slower. Please let me know if you have any further questions or encounter any issues!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment