Spaces:
Running
on
Zero
Running
on
Zero
initial commi
Browse files- .gitattributes +3 -0
- LICENSE +201 -0
- README.md +1 -1
- app.py +228 -0
- dreamomni2/pipeline_dreamomni2.py +1148 -0
- example_input/edit_tests/1/ref_0.jpg +3 -0
- example_input/edit_tests/1/ref_1.jpg +3 -0
- example_input/edit_tests/1/res.jpg +3 -0
- example_input/edit_tests/2/ref_0.jpg +3 -0
- example_input/edit_tests/2/ref_1.jpg +3 -0
- example_input/edit_tests/2/res.jpg +3 -0
- example_input/edit_tests/3/ref_0.jpg +3 -0
- example_input/edit_tests/3/ref_1.jpg +3 -0
- example_input/edit_tests/3/res.jpg +3 -0
- example_input/edit_tests/4/ref_0.jpg +3 -0
- example_input/edit_tests/4/ref_1.jpg +3 -0
- example_input/edit_tests/4/res.jpg +3 -0
- example_input/edit_tests/5/ref_0.jpg +3 -0
- example_input/edit_tests/5/ref_1.jpg +3 -0
- example_input/edit_tests/5/res.jpg +3 -0
- example_input/edit_tests/6/ref_0.jpg +3 -0
- example_input/edit_tests/6/ref_1.jpg +3 -0
- example_input/edit_tests/6/res.jpg +3 -0
- example_input/edit_tests/7/ref_0.jpg +3 -0
- example_input/edit_tests/7/ref_1.jpg +3 -0
- example_input/edit_tests/7/res.jpg +3 -0
- example_input/edit_tests/8/ref_0.jpg +3 -0
- example_input/edit_tests/8/ref_1.jpg +3 -0
- example_input/edit_tests/8/res.jpg +3 -0
- example_input/edit_tests/edi_res.png +3 -0
- example_input/edit_tests/ref.jpg +3 -0
- example_input/edit_tests/src.jpg +3 -0
- example_input/gen_tests/gen_res.png +3 -0
- example_input/gen_tests/img1.jpg +3 -0
- example_input/gen_tests/img2.jpg +3 -0
- imgs/cover.png +3 -0
- imgs/gallery.png +3 -0
- inference_edit.py +180 -0
- inference_gen.py +192 -0
- my_datasets/.gitkeep +327 -0
- requirements.txt +16 -0
- utils/fsdp_utils.py +327 -0
- utils/infer_utils.py +163 -0
- utils/init_utils.py +48 -0
- utils/parser_config.py +314 -0
- utils/utils.py +166 -0
- utils/vprocess.py +568 -0
- web_edit.py +252 -0
- web_generate.py +251 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
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.
|
README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
---
|
| 2 |
title: DreamOmni2 Gen
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: pink
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import spaces
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import uuid
|
| 7 |
+
import argparse
|
| 8 |
+
from huggingface_hub import login, snapshot_download
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from dreamomni2.pipeline_dreamomni2 import DreamOmni2Pipeline
|
| 12 |
+
from diffusers.utils import load_image
|
| 13 |
+
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
|
| 14 |
+
from utils.vprocess import process_vision_info, resizeinput
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def extract_gen_content(text):
|
| 18 |
+
text = text[6:-7]
|
| 19 |
+
return text
|
| 20 |
+
|
| 21 |
+
def _load_model_processor():
|
| 22 |
+
|
| 23 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 24 |
+
local_dir = snapshot_download(
|
| 25 |
+
repo_id="xiabs/DreamOmni2",
|
| 26 |
+
revision="main",
|
| 27 |
+
allow_patterns=["vlm-model/**", "gen_lora/**"],
|
| 28 |
+
)
|
| 29 |
+
vlm_dir = os.path.join(local_dir, 'vlm-model')
|
| 30 |
+
lora_dir = os.path.join(local_dir, 'gen_lora')
|
| 31 |
+
|
| 32 |
+
print(f"Loading models from vlm_path: {vlm_dir}, gen_lora_path: {lora_dir}")
|
| 33 |
+
pipe = DreamOmni2Pipeline.from_pretrained(
|
| 34 |
+
"black-forest-labs/FLUX.1-Kontext-dev",
|
| 35 |
+
torch_dtype=torch.bfloat16
|
| 36 |
+
).to(device)
|
| 37 |
+
pipe.load_lora_weights(lora_dir, adapter_name="generation")
|
| 38 |
+
pipe.set_adapters(["generation"], adapter_weights=[1])
|
| 39 |
+
|
| 40 |
+
vlm_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 41 |
+
vlm_dir,
|
| 42 |
+
torch_dtype="bfloat16"
|
| 43 |
+
).to(device)
|
| 44 |
+
processor = AutoProcessor.from_pretrained(vlm_dir)
|
| 45 |
+
return vlm_model, processor, pipe
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _launch_demo(vlm_model, processor, pipe):
|
| 49 |
+
|
| 50 |
+
@spaces.GPU(duration=150)
|
| 51 |
+
def infer_vlm(input_img_path, input_instruction, prefix):
|
| 52 |
+
if not vlm_model or not processor:
|
| 53 |
+
raise gr.Error("VLM Model not loaded. Cannot process prompt.")
|
| 54 |
+
tp = []
|
| 55 |
+
for path in input_img_path:
|
| 56 |
+
tp.append({"type": "image", "image": path})
|
| 57 |
+
tp.append({"type": "text", "text": input_instruction + prefix})
|
| 58 |
+
messages = [{"role": "user", "content": tp}]
|
| 59 |
+
|
| 60 |
+
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 61 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
| 62 |
+
inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt")
|
| 63 |
+
inputs = inputs.to(device=vlm_model.device)
|
| 64 |
+
|
| 65 |
+
generated_ids = vlm_model.generate(**inputs, do_sample=False, max_new_tokens=4096)
|
| 66 |
+
generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
|
| 67 |
+
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 68 |
+
return output_text[0]
|
| 69 |
+
|
| 70 |
+
PREFERRED_KONTEXT_RESOLUTIONS = [
|
| 71 |
+
(672, 1568),
|
| 72 |
+
(688, 1504),
|
| 73 |
+
(720, 1456),
|
| 74 |
+
(752, 1392),
|
| 75 |
+
(800, 1328),
|
| 76 |
+
(832, 1248),
|
| 77 |
+
(880, 1184),
|
| 78 |
+
(944, 1104),
|
| 79 |
+
(1024, 1024),
|
| 80 |
+
(1104, 944),
|
| 81 |
+
(1184, 880),
|
| 82 |
+
(1248, 832),
|
| 83 |
+
(1328, 800),
|
| 84 |
+
(1392, 752),
|
| 85 |
+
(1456, 720),
|
| 86 |
+
(1504, 688),
|
| 87 |
+
(1568, 672),
|
| 88 |
+
]
|
| 89 |
+
def find_closest_resolution(width, height, preferred_resolutions):
|
| 90 |
+
input_ratio = width / height
|
| 91 |
+
closest_resolution = min(
|
| 92 |
+
preferred_resolutions,
|
| 93 |
+
key=lambda res: abs((res[0] / res[1]) - input_ratio)
|
| 94 |
+
)
|
| 95 |
+
return closest_resolution
|
| 96 |
+
|
| 97 |
+
@spaces.GPU(duration=150)
|
| 98 |
+
def perform_generation(input_img_paths, input_instruction, output_path, height=1024, width=1024):
|
| 99 |
+
prefix = " It is generation task."
|
| 100 |
+
source_imgs = []
|
| 101 |
+
for path in input_img_paths:
|
| 102 |
+
img = load_image(path)
|
| 103 |
+
# source_imgs.append(img)
|
| 104 |
+
source_imgs.append(resizeinput(img))
|
| 105 |
+
prompt = infer_vlm(input_img_paths, input_instruction, prefix)
|
| 106 |
+
prompt = extract_gen_content(prompt)
|
| 107 |
+
print(f"Generated Prompt for VLM: {prompt}")
|
| 108 |
+
|
| 109 |
+
image = pipe(
|
| 110 |
+
images=source_imgs,
|
| 111 |
+
height=height,
|
| 112 |
+
width=width,
|
| 113 |
+
prompt=prompt,
|
| 114 |
+
num_inference_steps=30,
|
| 115 |
+
guidance_scale=3.5,
|
| 116 |
+
).images[0]
|
| 117 |
+
image.save(output_path)
|
| 118 |
+
print(f"Generation result saved to {output_path}")
|
| 119 |
+
|
| 120 |
+
@spaces.GPU(duration=150)
|
| 121 |
+
def process_request(image_file_1, image_file_2, instruction):
|
| 122 |
+
# debugpy.listen(5678)
|
| 123 |
+
# print("Waiting for debugger attach...")
|
| 124 |
+
# debugpy.wait_for_client()
|
| 125 |
+
if not image_file_1 or not image_file_2:
|
| 126 |
+
raise gr.Error("Please upload both images.")
|
| 127 |
+
if not instruction:
|
| 128 |
+
raise gr.Error("Please provide an instruction.")
|
| 129 |
+
if not pipe or not vlm_model:
|
| 130 |
+
raise gr.Error("Models not loaded. Check the console for errors.")
|
| 131 |
+
|
| 132 |
+
output_path = f"/tmp/{uuid.uuid4()}.png"
|
| 133 |
+
input_img_paths = [image_file_1, image_file_2] # List of file paths from the two gr.File inputs
|
| 134 |
+
|
| 135 |
+
perform_generation(input_img_paths, instruction, output_path)
|
| 136 |
+
return output_path
|
| 137 |
+
|
| 138 |
+
css = """
|
| 139 |
+
.text-center { text-align: center; }
|
| 140 |
+
.result-img img {
|
| 141 |
+
max-height: 60vh !important;
|
| 142 |
+
min-height: 30vh !important;
|
| 143 |
+
width: auto !important;
|
| 144 |
+
object-fit: contain;
|
| 145 |
+
}
|
| 146 |
+
.input-img img {
|
| 147 |
+
max-height: 30vh !important;
|
| 148 |
+
width: auto !important;
|
| 149 |
+
object-fit: contain;
|
| 150 |
+
}
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="DreamOmni2", css=css) as demo:
|
| 155 |
+
gr.HTML(
|
| 156 |
+
"""
|
| 157 |
+
<h1 style="text-align:center; font-size:48px; font-weight:bold; margin-bottom:20px;">
|
| 158 |
+
DreamOmni2: Omni-purpose Image Generation and Editing
|
| 159 |
+
</h1>
|
| 160 |
+
"""
|
| 161 |
+
)
|
| 162 |
+
gr.Markdown(
|
| 163 |
+
"Select a mode, upload two images, provide an instruction, and click 'Run'.",
|
| 164 |
+
elem_classes="text-center"
|
| 165 |
+
)
|
| 166 |
+
with gr.Row():
|
| 167 |
+
with gr.Column(scale=2):
|
| 168 |
+
gr.Markdown("⬆️ Upload images. Click or drag to upload.")
|
| 169 |
+
|
| 170 |
+
with gr.Row():
|
| 171 |
+
image_uploader_1 = gr.Image(
|
| 172 |
+
label="Img 1",
|
| 173 |
+
type="filepath",
|
| 174 |
+
interactive=True,
|
| 175 |
+
elem_classes="input-img",
|
| 176 |
+
)
|
| 177 |
+
image_uploader_2 = gr.Image(
|
| 178 |
+
label="Img 2",
|
| 179 |
+
type="filepath",
|
| 180 |
+
interactive=True,
|
| 181 |
+
elem_classes="input-img",
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
instruction_text = gr.Textbox(
|
| 185 |
+
label="Instruction",
|
| 186 |
+
lines=2,
|
| 187 |
+
placeholder="Input your instruction for generation or editing here...",
|
| 188 |
+
)
|
| 189 |
+
run_button = gr.Button("Run", variant="primary")
|
| 190 |
+
|
| 191 |
+
with gr.Column(scale=2):
|
| 192 |
+
gr.Markdown("🖼️ **Generation Mode**: Create new scenes from reference images."
|
| 193 |
+
"Tip: If the result is not what you expect, try clicking **Run** again. ")
|
| 194 |
+
output_image = gr.Image(
|
| 195 |
+
label="Result",
|
| 196 |
+
type="filepath",
|
| 197 |
+
elem_classes="result-img",
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
# --- Examples ---
|
| 201 |
+
gr.Markdown("## Examples")
|
| 202 |
+
|
| 203 |
+
gr.Examples(
|
| 204 |
+
label="Generation Examples",
|
| 205 |
+
examples=[
|
| 206 |
+
[
|
| 207 |
+
"example_input/gen_tests/img1.jpg",
|
| 208 |
+
"example_input/gen_tests/img2.jpg",
|
| 209 |
+
"In the scene, the character from the first image stands on the left, and the character from the second image stands on the right. They are shaking hands against the backdrop of a spaceship interior.",
|
| 210 |
+
"example_input/gen_tests/gen_res.png"
|
| 211 |
+
]
|
| 212 |
+
],
|
| 213 |
+
inputs=[image_uploader_1, image_uploader_2, instruction_text, output_image],
|
| 214 |
+
cache_examples=False,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
run_button.click(
|
| 218 |
+
fn=process_request,
|
| 219 |
+
inputs=[image_uploader_1, image_uploader_2, instruction_text],
|
| 220 |
+
outputs=output_image
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
demo.launch()
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
vlm_model, processor, pipe = _load_model_processor()
|
| 228 |
+
_launch_demo(vlm_model, processor, pipe)
|
dreamomni2/pipeline_dreamomni2.py
ADDED
|
@@ -0,0 +1,1148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Black Forest Labs and 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 |
+
import inspect
|
| 16 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from transformers import (
|
| 21 |
+
CLIPImageProcessor,
|
| 22 |
+
CLIPTextModel,
|
| 23 |
+
CLIPTokenizer,
|
| 24 |
+
CLIPVisionModelWithProjection,
|
| 25 |
+
T5EncoderModel,
|
| 26 |
+
T5TokenizerFast,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
|
| 30 |
+
from diffusers.loaders import FluxIPAdapterMixin, FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
|
| 31 |
+
from diffusers.models import AutoencoderKL, FluxTransformer2DModel
|
| 32 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
| 33 |
+
from diffusers.utils import (
|
| 34 |
+
USE_PEFT_BACKEND,
|
| 35 |
+
is_torch_xla_available,
|
| 36 |
+
logging,
|
| 37 |
+
replace_example_docstring,
|
| 38 |
+
scale_lora_layers,
|
| 39 |
+
unscale_lora_layers,
|
| 40 |
+
)
|
| 41 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 42 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 43 |
+
from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_torch_xla_available():
|
| 47 |
+
import torch_xla.core.xla_model as xm
|
| 48 |
+
|
| 49 |
+
XLA_AVAILABLE = True
|
| 50 |
+
else:
|
| 51 |
+
XLA_AVAILABLE = False
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 55 |
+
|
| 56 |
+
EXAMPLE_DOC_STRING = """
|
| 57 |
+
Examples:
|
| 58 |
+
```py
|
| 59 |
+
>>> import torch
|
| 60 |
+
>>> from diffusers import DreamOmni2Pipeline
|
| 61 |
+
>>> from diffusers.utils import load_image
|
| 62 |
+
|
| 63 |
+
>>> pipe = DreamOmni2Pipeline.from_pretrained(
|
| 64 |
+
... "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16
|
| 65 |
+
... )
|
| 66 |
+
>>> pipe.to("cuda")
|
| 67 |
+
|
| 68 |
+
>>> image = load_image(
|
| 69 |
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png"
|
| 70 |
+
... ).convert("RGB")
|
| 71 |
+
>>> prompt = "Make Pikachu hold a sign that says 'Black Forest Labs is awesome', yarn art style, detailed, vibrant colors"
|
| 72 |
+
>>> image = pipe(
|
| 73 |
+
... image=image,
|
| 74 |
+
... prompt=prompt,
|
| 75 |
+
... guidance_scale=2.5,
|
| 76 |
+
... generator=torch.Generator().manual_seed(42),
|
| 77 |
+
... ).images[0]
|
| 78 |
+
>>> image.save("output.png")
|
| 79 |
+
```
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
PREFERRED_KONTEXT_RESOLUTIONS = [
|
| 83 |
+
(672, 1568),
|
| 84 |
+
(688, 1504),
|
| 85 |
+
(720, 1456),
|
| 86 |
+
(752, 1392),
|
| 87 |
+
(800, 1328),
|
| 88 |
+
(832, 1248),
|
| 89 |
+
(880, 1184),
|
| 90 |
+
(944, 1104),
|
| 91 |
+
(1024, 1024),
|
| 92 |
+
(1104, 944),
|
| 93 |
+
(1184, 880),
|
| 94 |
+
(1248, 832),
|
| 95 |
+
(1328, 800),
|
| 96 |
+
(1392, 752),
|
| 97 |
+
(1456, 720),
|
| 98 |
+
(1504, 688),
|
| 99 |
+
(1568, 672),
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def calculate_shift(
|
| 104 |
+
image_seq_len,
|
| 105 |
+
base_seq_len: int = 256,
|
| 106 |
+
max_seq_len: int = 4096,
|
| 107 |
+
base_shift: float = 0.5,
|
| 108 |
+
max_shift: float = 1.15,
|
| 109 |
+
):
|
| 110 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
| 111 |
+
b = base_shift - m * base_seq_len
|
| 112 |
+
mu = image_seq_len * m + b
|
| 113 |
+
return mu
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
| 117 |
+
def retrieve_timesteps(
|
| 118 |
+
scheduler,
|
| 119 |
+
num_inference_steps: Optional[int] = None,
|
| 120 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 121 |
+
timesteps: Optional[List[int]] = None,
|
| 122 |
+
sigmas: Optional[List[float]] = None,
|
| 123 |
+
**kwargs,
|
| 124 |
+
):
|
| 125 |
+
r"""
|
| 126 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
| 127 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
scheduler (`SchedulerMixin`):
|
| 131 |
+
The scheduler to get timesteps from.
|
| 132 |
+
num_inference_steps (`int`):
|
| 133 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
| 134 |
+
must be `None`.
|
| 135 |
+
device (`str` or `torch.device`, *optional*):
|
| 136 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 137 |
+
timesteps (`List[int]`, *optional*):
|
| 138 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
| 139 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
| 140 |
+
sigmas (`List[float]`, *optional*):
|
| 141 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
| 142 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
| 143 |
+
|
| 144 |
+
Returns:
|
| 145 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
| 146 |
+
second element is the number of inference steps.
|
| 147 |
+
"""
|
| 148 |
+
if timesteps is not None and sigmas is not None:
|
| 149 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
| 150 |
+
if timesteps is not None:
|
| 151 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
| 152 |
+
if not accepts_timesteps:
|
| 153 |
+
raise ValueError(
|
| 154 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 155 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
| 156 |
+
)
|
| 157 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
| 158 |
+
timesteps = scheduler.timesteps
|
| 159 |
+
num_inference_steps = len(timesteps)
|
| 160 |
+
elif sigmas is not None:
|
| 161 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
| 162 |
+
if not accept_sigmas:
|
| 163 |
+
raise ValueError(
|
| 164 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 165 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
| 166 |
+
)
|
| 167 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
| 168 |
+
timesteps = scheduler.timesteps
|
| 169 |
+
num_inference_steps = len(timesteps)
|
| 170 |
+
else:
|
| 171 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
| 172 |
+
timesteps = scheduler.timesteps
|
| 173 |
+
return timesteps, num_inference_steps
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
| 177 |
+
def retrieve_latents(
|
| 178 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
| 179 |
+
):
|
| 180 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
| 181 |
+
return encoder_output.latent_dist.sample(generator)
|
| 182 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
| 183 |
+
return encoder_output.latent_dist.mode()
|
| 184 |
+
elif hasattr(encoder_output, "latents"):
|
| 185 |
+
return encoder_output.latents
|
| 186 |
+
else:
|
| 187 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class DreamOmni2Pipeline(
|
| 191 |
+
DiffusionPipeline,
|
| 192 |
+
FluxLoraLoaderMixin,
|
| 193 |
+
FromSingleFileMixin,
|
| 194 |
+
TextualInversionLoaderMixin,
|
| 195 |
+
FluxIPAdapterMixin,
|
| 196 |
+
):
|
| 197 |
+
r"""
|
| 198 |
+
The Flux Kontext pipeline for image-to-image and text-to-image generation.
|
| 199 |
+
|
| 200 |
+
Reference: https://bfl.ai/announcements/flux-1-kontext-dev
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
transformer ([`FluxTransformer2DModel`]):
|
| 204 |
+
Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
|
| 205 |
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
| 206 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 207 |
+
vae ([`AutoencoderKL`]):
|
| 208 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 209 |
+
text_encoder ([`CLIPTextModel`]):
|
| 210 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
| 211 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
| 212 |
+
text_encoder_2 ([`T5EncoderModel`]):
|
| 213 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
| 214 |
+
the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
|
| 215 |
+
tokenizer (`CLIPTokenizer`):
|
| 216 |
+
Tokenizer of class
|
| 217 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 218 |
+
tokenizer_2 (`T5TokenizerFast`):
|
| 219 |
+
Second Tokenizer of class
|
| 220 |
+
[T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->transformer->vae"
|
| 224 |
+
_optional_components = ["image_encoder", "feature_extractor"]
|
| 225 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds"]
|
| 226 |
+
|
| 227 |
+
def __init__(
|
| 228 |
+
self,
|
| 229 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
| 230 |
+
vae: AutoencoderKL,
|
| 231 |
+
text_encoder: CLIPTextModel,
|
| 232 |
+
tokenizer: CLIPTokenizer,
|
| 233 |
+
text_encoder_2: T5EncoderModel,
|
| 234 |
+
tokenizer_2: T5TokenizerFast,
|
| 235 |
+
transformer: FluxTransformer2DModel,
|
| 236 |
+
image_encoder: CLIPVisionModelWithProjection = None,
|
| 237 |
+
feature_extractor: CLIPImageProcessor = None,
|
| 238 |
+
):
|
| 239 |
+
super().__init__()
|
| 240 |
+
|
| 241 |
+
self.register_modules(
|
| 242 |
+
vae=vae,
|
| 243 |
+
text_encoder=text_encoder,
|
| 244 |
+
text_encoder_2=text_encoder_2,
|
| 245 |
+
tokenizer=tokenizer,
|
| 246 |
+
tokenizer_2=tokenizer_2,
|
| 247 |
+
transformer=transformer,
|
| 248 |
+
scheduler=scheduler,
|
| 249 |
+
image_encoder=image_encoder,
|
| 250 |
+
feature_extractor=feature_extractor,
|
| 251 |
+
)
|
| 252 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
|
| 253 |
+
# Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
|
| 254 |
+
# by the patch size. So the vae scale factor is multiplied by the patch size to account for this
|
| 255 |
+
self.latent_channels = self.vae.config.latent_channels if getattr(self, "vae", None) else 16
|
| 256 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
|
| 257 |
+
self.tokenizer_max_length = (
|
| 258 |
+
self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
|
| 259 |
+
)
|
| 260 |
+
self.default_sample_size = 128
|
| 261 |
+
|
| 262 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
|
| 263 |
+
def _get_t5_prompt_embeds(
|
| 264 |
+
self,
|
| 265 |
+
prompt: Union[str, List[str]] = None,
|
| 266 |
+
num_images_per_prompt: int = 1,
|
| 267 |
+
max_sequence_length: int = 512,
|
| 268 |
+
device: Optional[torch.device] = None,
|
| 269 |
+
dtype: Optional[torch.dtype] = None,
|
| 270 |
+
):
|
| 271 |
+
device = device or self._execution_device
|
| 272 |
+
dtype = dtype or self.text_encoder.dtype
|
| 273 |
+
|
| 274 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 275 |
+
batch_size = len(prompt)
|
| 276 |
+
|
| 277 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 278 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
|
| 279 |
+
|
| 280 |
+
text_inputs = self.tokenizer_2(
|
| 281 |
+
prompt,
|
| 282 |
+
padding="max_length",
|
| 283 |
+
max_length=max_sequence_length,
|
| 284 |
+
truncation=True,
|
| 285 |
+
return_length=False,
|
| 286 |
+
return_overflowing_tokens=False,
|
| 287 |
+
return_tensors="pt",
|
| 288 |
+
)
|
| 289 |
+
text_input_ids = text_inputs.input_ids
|
| 290 |
+
untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
|
| 291 |
+
|
| 292 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
| 293 |
+
removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
|
| 294 |
+
logger.warning(
|
| 295 |
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
| 296 |
+
f" {max_sequence_length} tokens: {removed_text}"
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
|
| 300 |
+
|
| 301 |
+
dtype = self.text_encoder_2.dtype
|
| 302 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 303 |
+
|
| 304 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 305 |
+
|
| 306 |
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
| 307 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 308 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 309 |
+
|
| 310 |
+
return prompt_embeds
|
| 311 |
+
|
| 312 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
|
| 313 |
+
def _get_clip_prompt_embeds(
|
| 314 |
+
self,
|
| 315 |
+
prompt: Union[str, List[str]],
|
| 316 |
+
num_images_per_prompt: int = 1,
|
| 317 |
+
device: Optional[torch.device] = None,
|
| 318 |
+
):
|
| 319 |
+
device = device or self._execution_device
|
| 320 |
+
|
| 321 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 322 |
+
batch_size = len(prompt)
|
| 323 |
+
|
| 324 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 325 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 326 |
+
|
| 327 |
+
text_inputs = self.tokenizer(
|
| 328 |
+
prompt,
|
| 329 |
+
padding="max_length",
|
| 330 |
+
max_length=self.tokenizer_max_length,
|
| 331 |
+
truncation=True,
|
| 332 |
+
return_overflowing_tokens=False,
|
| 333 |
+
return_length=False,
|
| 334 |
+
return_tensors="pt",
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
text_input_ids = text_inputs.input_ids
|
| 338 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 339 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
| 340 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
|
| 341 |
+
logger.warning(
|
| 342 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 343 |
+
f" {self.tokenizer_max_length} tokens: {removed_text}"
|
| 344 |
+
)
|
| 345 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
|
| 346 |
+
|
| 347 |
+
# Use pooled output of CLIPTextModel
|
| 348 |
+
prompt_embeds = prompt_embeds.pooler_output
|
| 349 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
| 350 |
+
|
| 351 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 352 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
|
| 353 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
| 354 |
+
|
| 355 |
+
return prompt_embeds
|
| 356 |
+
|
| 357 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
|
| 358 |
+
def encode_prompt(
|
| 359 |
+
self,
|
| 360 |
+
prompt: Union[str, List[str]],
|
| 361 |
+
prompt_2: Union[str, List[str]],
|
| 362 |
+
device: Optional[torch.device] = None,
|
| 363 |
+
num_images_per_prompt: int = 1,
|
| 364 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 365 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 366 |
+
max_sequence_length: int = 512,
|
| 367 |
+
lora_scale: Optional[float] = None,
|
| 368 |
+
):
|
| 369 |
+
r"""
|
| 370 |
+
|
| 371 |
+
Args:
|
| 372 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 373 |
+
prompt to be encoded
|
| 374 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
| 375 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 376 |
+
used in all text-encoders
|
| 377 |
+
device: (`torch.device`):
|
| 378 |
+
torch device
|
| 379 |
+
num_images_per_prompt (`int`):
|
| 380 |
+
number of images that should be generated per prompt
|
| 381 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 382 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 383 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 384 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 385 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 386 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 387 |
+
lora_scale (`float`, *optional*):
|
| 388 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 389 |
+
"""
|
| 390 |
+
device = device or self._execution_device
|
| 391 |
+
|
| 392 |
+
# set lora scale so that monkey patched LoRA
|
| 393 |
+
# function of text encoder can correctly access it
|
| 394 |
+
if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
|
| 395 |
+
self._lora_scale = lora_scale
|
| 396 |
+
|
| 397 |
+
# dynamically adjust the LoRA scale
|
| 398 |
+
if self.text_encoder is not None and USE_PEFT_BACKEND:
|
| 399 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 400 |
+
if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
|
| 401 |
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
| 402 |
+
|
| 403 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 404 |
+
|
| 405 |
+
if prompt_embeds is None:
|
| 406 |
+
prompt_2 = prompt_2 or prompt
|
| 407 |
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
| 408 |
+
|
| 409 |
+
# We only use the pooled prompt output from the CLIPTextModel
|
| 410 |
+
pooled_prompt_embeds = self._get_clip_prompt_embeds(
|
| 411 |
+
prompt=prompt,
|
| 412 |
+
device=device,
|
| 413 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 414 |
+
)
|
| 415 |
+
prompt_embeds = self._get_t5_prompt_embeds(
|
| 416 |
+
prompt=prompt_2,
|
| 417 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 418 |
+
max_sequence_length=max_sequence_length,
|
| 419 |
+
device=device,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
if self.text_encoder is not None:
|
| 423 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 424 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 425 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 426 |
+
|
| 427 |
+
if self.text_encoder_2 is not None:
|
| 428 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 429 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 430 |
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
| 431 |
+
|
| 432 |
+
dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
|
| 433 |
+
text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
|
| 434 |
+
|
| 435 |
+
return prompt_embeds, pooled_prompt_embeds, text_ids
|
| 436 |
+
|
| 437 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_image
|
| 438 |
+
def encode_image(self, image, device, num_images_per_prompt):
|
| 439 |
+
dtype = next(self.image_encoder.parameters()).dtype
|
| 440 |
+
|
| 441 |
+
if not isinstance(image, torch.Tensor):
|
| 442 |
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
| 443 |
+
|
| 444 |
+
image = image.to(device=device, dtype=dtype)
|
| 445 |
+
image_embeds = self.image_encoder(image).image_embeds
|
| 446 |
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
| 447 |
+
return image_embeds
|
| 448 |
+
|
| 449 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.prepare_ip_adapter_image_embeds
|
| 450 |
+
def prepare_ip_adapter_image_embeds(
|
| 451 |
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt
|
| 452 |
+
):
|
| 453 |
+
image_embeds = []
|
| 454 |
+
if ip_adapter_image_embeds is None:
|
| 455 |
+
if not isinstance(ip_adapter_image, list):
|
| 456 |
+
ip_adapter_image = [ip_adapter_image]
|
| 457 |
+
|
| 458 |
+
if len(ip_adapter_image) != self.transformer.encoder_hid_proj.num_ip_adapters:
|
| 459 |
+
raise ValueError(
|
| 460 |
+
f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {self.transformer.encoder_hid_proj.num_ip_adapters} IP Adapters."
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
for single_ip_adapter_image in ip_adapter_image:
|
| 464 |
+
single_image_embeds = self.encode_image(single_ip_adapter_image, device, 1)
|
| 465 |
+
image_embeds.append(single_image_embeds[None, :])
|
| 466 |
+
else:
|
| 467 |
+
if not isinstance(ip_adapter_image_embeds, list):
|
| 468 |
+
ip_adapter_image_embeds = [ip_adapter_image_embeds]
|
| 469 |
+
|
| 470 |
+
if len(ip_adapter_image_embeds) != self.transformer.encoder_hid_proj.num_ip_adapters:
|
| 471 |
+
raise ValueError(
|
| 472 |
+
f"`ip_adapter_image_embeds` must have same length as the number of IP Adapters. Got {len(ip_adapter_image_embeds)} image embeds and {self.transformer.encoder_hid_proj.num_ip_adapters} IP Adapters."
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
for single_image_embeds in ip_adapter_image_embeds:
|
| 476 |
+
image_embeds.append(single_image_embeds)
|
| 477 |
+
|
| 478 |
+
ip_adapter_image_embeds = []
|
| 479 |
+
for single_image_embeds in image_embeds:
|
| 480 |
+
single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
|
| 481 |
+
single_image_embeds = single_image_embeds.to(device=device)
|
| 482 |
+
ip_adapter_image_embeds.append(single_image_embeds)
|
| 483 |
+
|
| 484 |
+
return ip_adapter_image_embeds
|
| 485 |
+
|
| 486 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.check_inputs
|
| 487 |
+
def check_inputs(
|
| 488 |
+
self,
|
| 489 |
+
prompt,
|
| 490 |
+
prompt_2,
|
| 491 |
+
height,
|
| 492 |
+
width,
|
| 493 |
+
negative_prompt=None,
|
| 494 |
+
negative_prompt_2=None,
|
| 495 |
+
prompt_embeds=None,
|
| 496 |
+
negative_prompt_embeds=None,
|
| 497 |
+
pooled_prompt_embeds=None,
|
| 498 |
+
negative_pooled_prompt_embeds=None,
|
| 499 |
+
callback_on_step_end_tensor_inputs=None,
|
| 500 |
+
max_sequence_length=None,
|
| 501 |
+
):
|
| 502 |
+
if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
|
| 503 |
+
logger.warning(
|
| 504 |
+
f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 508 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 509 |
+
):
|
| 510 |
+
raise ValueError(
|
| 511 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
if prompt is not None and prompt_embeds is not None:
|
| 515 |
+
raise ValueError(
|
| 516 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 517 |
+
" only forward one of the two."
|
| 518 |
+
)
|
| 519 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
| 520 |
+
raise ValueError(
|
| 521 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 522 |
+
" only forward one of the two."
|
| 523 |
+
)
|
| 524 |
+
elif prompt is None and prompt_embeds is None:
|
| 525 |
+
raise ValueError(
|
| 526 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 527 |
+
)
|
| 528 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 529 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 530 |
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
| 531 |
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
| 532 |
+
|
| 533 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 534 |
+
raise ValueError(
|
| 535 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 536 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 537 |
+
)
|
| 538 |
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
| 539 |
+
raise ValueError(
|
| 540 |
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
| 541 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
| 545 |
+
raise ValueError(
|
| 546 |
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
| 547 |
+
)
|
| 548 |
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
| 549 |
+
raise ValueError(
|
| 550 |
+
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
if max_sequence_length is not None and max_sequence_length > 512:
|
| 554 |
+
raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
|
| 555 |
+
|
| 556 |
+
@staticmethod
|
| 557 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._prepare_latent_image_ids
|
| 558 |
+
def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
|
| 559 |
+
latent_image_ids = torch.zeros(height, width, 3)
|
| 560 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
|
| 561 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
|
| 562 |
+
|
| 563 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
| 564 |
+
|
| 565 |
+
latent_image_ids = latent_image_ids.reshape(
|
| 566 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
| 570 |
+
|
| 571 |
+
@staticmethod
|
| 572 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
|
| 573 |
+
def _pack_latents(latents, batch_size, num_channels_latents, height, width):
|
| 574 |
+
latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
|
| 575 |
+
latents = latents.permute(0, 2, 4, 1, 3, 5)
|
| 576 |
+
latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
|
| 577 |
+
|
| 578 |
+
return latents
|
| 579 |
+
|
| 580 |
+
@staticmethod
|
| 581 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._unpack_latents
|
| 582 |
+
def _unpack_latents(latents, height, width, vae_scale_factor):
|
| 583 |
+
batch_size, num_patches, channels = latents.shape
|
| 584 |
+
|
| 585 |
+
# VAE applies 8x compression on images but we must also account for packing which requires
|
| 586 |
+
# latent height and width to be divisible by 2.
|
| 587 |
+
height = 2 * (int(height) // (vae_scale_factor * 2))
|
| 588 |
+
width = 2 * (int(width) // (vae_scale_factor * 2))
|
| 589 |
+
|
| 590 |
+
latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
|
| 591 |
+
latents = latents.permute(0, 3, 1, 4, 2, 5)
|
| 592 |
+
|
| 593 |
+
latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
|
| 594 |
+
|
| 595 |
+
return latents
|
| 596 |
+
|
| 597 |
+
def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
|
| 598 |
+
if isinstance(generator, list):
|
| 599 |
+
image_latents = [
|
| 600 |
+
retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i], sample_mode="argmax")
|
| 601 |
+
for i in range(image.shape[0])
|
| 602 |
+
]
|
| 603 |
+
image_latents = torch.cat(image_latents, dim=0)
|
| 604 |
+
else:
|
| 605 |
+
image_latents = retrieve_latents(self.vae.encode(image), generator=generator, sample_mode="argmax")
|
| 606 |
+
|
| 607 |
+
image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
|
| 608 |
+
|
| 609 |
+
return image_latents
|
| 610 |
+
|
| 611 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.enable_vae_slicing
|
| 612 |
+
def enable_vae_slicing(self):
|
| 613 |
+
r"""
|
| 614 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 615 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 616 |
+
"""
|
| 617 |
+
self.vae.enable_slicing()
|
| 618 |
+
|
| 619 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.disable_vae_slicing
|
| 620 |
+
def disable_vae_slicing(self):
|
| 621 |
+
r"""
|
| 622 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
| 623 |
+
computing decoding in one step.
|
| 624 |
+
"""
|
| 625 |
+
self.vae.disable_slicing()
|
| 626 |
+
|
| 627 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.enable_vae_tiling
|
| 628 |
+
def enable_vae_tiling(self):
|
| 629 |
+
r"""
|
| 630 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 631 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 632 |
+
processing larger images.
|
| 633 |
+
"""
|
| 634 |
+
self.vae.enable_tiling()
|
| 635 |
+
|
| 636 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.disable_vae_tiling
|
| 637 |
+
def disable_vae_tiling(self):
|
| 638 |
+
r"""
|
| 639 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
| 640 |
+
computing decoding in one step.
|
| 641 |
+
"""
|
| 642 |
+
self.vae.disable_tiling()
|
| 643 |
+
|
| 644 |
+
def prepare_latents(
|
| 645 |
+
self,
|
| 646 |
+
images: Optional[torch.Tensor],
|
| 647 |
+
batch_size: int,
|
| 648 |
+
num_channels_latents: int,
|
| 649 |
+
height: int,
|
| 650 |
+
width: int,
|
| 651 |
+
dtype: torch.dtype,
|
| 652 |
+
device: torch.device,
|
| 653 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 654 |
+
latents: Optional[torch.Tensor] = None,
|
| 655 |
+
):
|
| 656 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 657 |
+
raise ValueError(
|
| 658 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 659 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
# VAE applies 8x compression on images but we must also account for packing which requires
|
| 663 |
+
# latent height and width to be divisible by 2.
|
| 664 |
+
height = 2 * (int(height) // (self.vae_scale_factor * 2))
|
| 665 |
+
width = 2 * (int(width) // (self.vae_scale_factor * 2))
|
| 666 |
+
shape = (batch_size, num_channels_latents, height, width)
|
| 667 |
+
h_offset = 0
|
| 668 |
+
w_offset = 0
|
| 669 |
+
image_latents = image_ids = None
|
| 670 |
+
if images is not None:
|
| 671 |
+
tp_image_latents = []
|
| 672 |
+
tp_image_ids = []
|
| 673 |
+
for i, image in enumerate(images):
|
| 674 |
+
image = image.to(device=device, dtype=dtype)
|
| 675 |
+
if image.shape[1] != self.latent_channels:
|
| 676 |
+
image_latents = self._encode_vae_image(image=image, generator=generator)
|
| 677 |
+
else:
|
| 678 |
+
image_latents = image
|
| 679 |
+
if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
|
| 680 |
+
# expand init_latents for batch_size
|
| 681 |
+
additional_image_per_prompt = batch_size // image_latents.shape[0]
|
| 682 |
+
image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
|
| 683 |
+
elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
|
| 684 |
+
raise ValueError(
|
| 685 |
+
f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
|
| 686 |
+
)
|
| 687 |
+
else:
|
| 688 |
+
image_latents = torch.cat([image_latents], dim=0)
|
| 689 |
+
|
| 690 |
+
image_latent_height, image_latent_width = image_latents.shape[2:]
|
| 691 |
+
image_latents = self._pack_latents(
|
| 692 |
+
image_latents, batch_size, num_channels_latents, image_latent_height, image_latent_width
|
| 693 |
+
)
|
| 694 |
+
image_ids = self._prepare_latent_image_ids(
|
| 695 |
+
batch_size, image_latent_height // 2, image_latent_width // 2, device, dtype
|
| 696 |
+
)
|
| 697 |
+
image_ids[..., 0] = i+1
|
| 698 |
+
image_ids[..., 2] += w_offset
|
| 699 |
+
tp_image_latents.append(image_latents)
|
| 700 |
+
tp_image_ids.append(image_ids)
|
| 701 |
+
h_offset += image_latent_height //2
|
| 702 |
+
w_offset += image_latent_width //2
|
| 703 |
+
image_latents = torch.cat(tp_image_latents, dim=1)
|
| 704 |
+
image_ids = torch.cat(tp_image_ids, dim=0)
|
| 705 |
+
|
| 706 |
+
latent_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
|
| 707 |
+
|
| 708 |
+
if latents is None:
|
| 709 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 710 |
+
latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
|
| 711 |
+
else:
|
| 712 |
+
latents = latents.to(device=device, dtype=dtype)
|
| 713 |
+
|
| 714 |
+
return latents, image_latents, latent_ids, image_ids
|
| 715 |
+
|
| 716 |
+
@property
|
| 717 |
+
def guidance_scale(self):
|
| 718 |
+
return self._guidance_scale
|
| 719 |
+
|
| 720 |
+
@property
|
| 721 |
+
def joint_attention_kwargs(self):
|
| 722 |
+
return self._joint_attention_kwargs
|
| 723 |
+
|
| 724 |
+
@property
|
| 725 |
+
def num_timesteps(self):
|
| 726 |
+
return self._num_timesteps
|
| 727 |
+
|
| 728 |
+
@property
|
| 729 |
+
def current_timestep(self):
|
| 730 |
+
return self._current_timestep
|
| 731 |
+
|
| 732 |
+
@property
|
| 733 |
+
def interrupt(self):
|
| 734 |
+
return self._interrupt
|
| 735 |
+
|
| 736 |
+
@torch.no_grad()
|
| 737 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 738 |
+
def __call__(
|
| 739 |
+
self,
|
| 740 |
+
images: Optional[List[PipelineImageInput]] = None,
|
| 741 |
+
prompt: Union[str, List[str]] = None,
|
| 742 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 743 |
+
negative_prompt: Union[str, List[str]] = None,
|
| 744 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 745 |
+
true_cfg_scale: float = 1.0,
|
| 746 |
+
height: Optional[int] = None,
|
| 747 |
+
width: Optional[int] = None,
|
| 748 |
+
num_inference_steps: int = 28,
|
| 749 |
+
sigmas: Optional[List[float]] = None,
|
| 750 |
+
guidance_scale: float = 3.5,
|
| 751 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 752 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 753 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 754 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 755 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 756 |
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
| 757 |
+
ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
| 758 |
+
negative_ip_adapter_image: Optional[PipelineImageInput] = None,
|
| 759 |
+
negative_ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
| 760 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 761 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 762 |
+
output_type: Optional[str] = "pil",
|
| 763 |
+
return_dict: bool = True,
|
| 764 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 765 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 766 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 767 |
+
max_sequence_length: int = 512,
|
| 768 |
+
max_area: int = 1024**2,
|
| 769 |
+
_auto_resize: bool = True,
|
| 770 |
+
):
|
| 771 |
+
r"""
|
| 772 |
+
Function invoked when calling the pipeline for generation.
|
| 773 |
+
|
| 774 |
+
Args:
|
| 775 |
+
image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
|
| 776 |
+
`Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
|
| 777 |
+
numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
|
| 778 |
+
or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
|
| 779 |
+
list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
|
| 780 |
+
latents as `image`, but if passing latents directly it is not encoded again.
|
| 781 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 782 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 783 |
+
instead.
|
| 784 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
| 785 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 786 |
+
will be used instead.
|
| 787 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 788 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 789 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
|
| 790 |
+
not greater than `1`).
|
| 791 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 792 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
| 793 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
|
| 794 |
+
true_cfg_scale (`float`, *optional*, defaults to 1.0):
|
| 795 |
+
When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
|
| 796 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 797 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 798 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 799 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 800 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 801 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 802 |
+
expense of slower inference.
|
| 803 |
+
sigmas (`List[float]`, *optional*):
|
| 804 |
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
| 805 |
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
| 806 |
+
will be used.
|
| 807 |
+
guidance_scale (`float`, *optional*, defaults to 3.5):
|
| 808 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
| 809 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
| 810 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
| 811 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
| 812 |
+
the text `prompt`, usually at the expense of lower image quality.
|
| 813 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 814 |
+
The number of images to generate per prompt.
|
| 815 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 816 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 817 |
+
to make generation deterministic.
|
| 818 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 819 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 820 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 821 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 822 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 823 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 824 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 825 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 826 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 827 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 828 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*):
|
| 829 |
+
Optional image input to work with IP Adapters.
|
| 830 |
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
| 831 |
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
| 832 |
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
|
| 833 |
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
| 834 |
+
negative_ip_adapter_image:
|
| 835 |
+
(`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
| 836 |
+
negative_ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
| 837 |
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
| 838 |
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
|
| 839 |
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
| 840 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 841 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 842 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 843 |
+
argument.
|
| 844 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 845 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 846 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 847 |
+
input argument.
|
| 848 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 849 |
+
The output format of the generate image. Choose between
|
| 850 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 851 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 852 |
+
Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
|
| 853 |
+
joint_attention_kwargs (`dict`, *optional*):
|
| 854 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 855 |
+
`self.processor` in
|
| 856 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 857 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 858 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 859 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 860 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 861 |
+
`callback_on_step_end_tensor_inputs`.
|
| 862 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 863 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 864 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 865 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 866 |
+
max_sequence_length (`int` defaults to 512):
|
| 867 |
+
Maximum sequence length to use with the `prompt`.
|
| 868 |
+
max_area (`int`, defaults to `1024 ** 2`):
|
| 869 |
+
The maximum area of the generated image in pixels. The height and width will be adjusted to fit this
|
| 870 |
+
area while maintaining the aspect ratio.
|
| 871 |
+
|
| 872 |
+
Examples:
|
| 873 |
+
|
| 874 |
+
Returns:
|
| 875 |
+
[`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
|
| 876 |
+
is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
|
| 877 |
+
images.
|
| 878 |
+
"""
|
| 879 |
+
|
| 880 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
| 881 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
| 882 |
+
|
| 883 |
+
original_height, original_width = height, width
|
| 884 |
+
aspect_ratio = width / height
|
| 885 |
+
width = round((max_area * aspect_ratio) ** 0.5)
|
| 886 |
+
height = round((max_area / aspect_ratio) ** 0.5)
|
| 887 |
+
|
| 888 |
+
multiple_of = self.vae_scale_factor * 2
|
| 889 |
+
width = width // multiple_of * multiple_of
|
| 890 |
+
height = height // multiple_of * multiple_of
|
| 891 |
+
|
| 892 |
+
if height != original_height or width != original_width:
|
| 893 |
+
logger.warning(
|
| 894 |
+
f"Generation `height` and `width` have been adjusted to {height} and {width} to fit the model requirements."
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
# 1. Check inputs. Raise error if not correct
|
| 898 |
+
self.check_inputs(
|
| 899 |
+
prompt,
|
| 900 |
+
prompt_2,
|
| 901 |
+
height,
|
| 902 |
+
width,
|
| 903 |
+
negative_prompt=negative_prompt,
|
| 904 |
+
negative_prompt_2=negative_prompt_2,
|
| 905 |
+
prompt_embeds=prompt_embeds,
|
| 906 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 907 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 908 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 909 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 910 |
+
max_sequence_length=max_sequence_length,
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
self._guidance_scale = guidance_scale
|
| 914 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
| 915 |
+
self._current_timestep = None
|
| 916 |
+
self._interrupt = False
|
| 917 |
+
|
| 918 |
+
# 2. Define call parameters
|
| 919 |
+
if prompt is not None and isinstance(prompt, str):
|
| 920 |
+
batch_size = 1
|
| 921 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 922 |
+
batch_size = len(prompt)
|
| 923 |
+
else:
|
| 924 |
+
batch_size = prompt_embeds.shape[0]
|
| 925 |
+
|
| 926 |
+
device = self._execution_device
|
| 927 |
+
|
| 928 |
+
lora_scale = (
|
| 929 |
+
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
|
| 930 |
+
)
|
| 931 |
+
has_neg_prompt = negative_prompt is not None or (
|
| 932 |
+
negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None
|
| 933 |
+
)
|
| 934 |
+
do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
|
| 935 |
+
(
|
| 936 |
+
prompt_embeds,
|
| 937 |
+
pooled_prompt_embeds,
|
| 938 |
+
text_ids,
|
| 939 |
+
) = self.encode_prompt(
|
| 940 |
+
prompt=prompt,
|
| 941 |
+
prompt_2=prompt_2,
|
| 942 |
+
prompt_embeds=prompt_embeds,
|
| 943 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 944 |
+
device=device,
|
| 945 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 946 |
+
max_sequence_length=max_sequence_length,
|
| 947 |
+
lora_scale=lora_scale,
|
| 948 |
+
)
|
| 949 |
+
if do_true_cfg:
|
| 950 |
+
(
|
| 951 |
+
negative_prompt_embeds,
|
| 952 |
+
negative_pooled_prompt_embeds,
|
| 953 |
+
negative_text_ids,
|
| 954 |
+
) = self.encode_prompt(
|
| 955 |
+
prompt=negative_prompt,
|
| 956 |
+
prompt_2=negative_prompt_2,
|
| 957 |
+
prompt_embeds=negative_prompt_embeds,
|
| 958 |
+
pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 959 |
+
device=device,
|
| 960 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 961 |
+
max_sequence_length=max_sequence_length,
|
| 962 |
+
lora_scale=lora_scale,
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
# 3. Preprocess image
|
| 966 |
+
if images is not None and not (isinstance(images[0], torch.Tensor) and images[0].size(1) == self.latent_channels):
|
| 967 |
+
tp_images=[]
|
| 968 |
+
for img in images:
|
| 969 |
+
image = img
|
| 970 |
+
image_height, image_width = self.image_processor.get_default_height_width(img)
|
| 971 |
+
aspect_ratio = image_width / image_height
|
| 972 |
+
if _auto_resize:
|
| 973 |
+
# Kontext is trained on specific resolutions, using one of them is recommended
|
| 974 |
+
_, image_width, image_height = min(
|
| 975 |
+
(abs(aspect_ratio - w / h), w, h) for w, h in PREFERRED_KONTEXT_RESOLUTIONS
|
| 976 |
+
)
|
| 977 |
+
image_width = image_width // multiple_of * multiple_of
|
| 978 |
+
image_height = image_height // multiple_of * multiple_of
|
| 979 |
+
image = self.image_processor.resize(image, image_height, image_width)
|
| 980 |
+
image = self.image_processor.preprocess(image, image_height, image_width)
|
| 981 |
+
tp_images.append(image)
|
| 982 |
+
images = tp_images
|
| 983 |
+
|
| 984 |
+
# 4. Prepare latent variables
|
| 985 |
+
num_channels_latents = self.transformer.config.in_channels // 4
|
| 986 |
+
latents, image_latents, latent_ids, image_ids = self.prepare_latents(
|
| 987 |
+
images,
|
| 988 |
+
batch_size * num_images_per_prompt,
|
| 989 |
+
num_channels_latents,
|
| 990 |
+
height,
|
| 991 |
+
width,
|
| 992 |
+
prompt_embeds.dtype,
|
| 993 |
+
device,
|
| 994 |
+
generator,
|
| 995 |
+
latents,
|
| 996 |
+
)
|
| 997 |
+
if image_ids is not None:
|
| 998 |
+
latent_ids = torch.cat([latent_ids, image_ids], dim=0) # dim 0 is sequence dimension
|
| 999 |
+
|
| 1000 |
+
# 5. Prepare timesteps
|
| 1001 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
|
| 1002 |
+
image_seq_len = latents.shape[1]
|
| 1003 |
+
mu = calculate_shift(
|
| 1004 |
+
image_seq_len,
|
| 1005 |
+
self.scheduler.config.get("base_image_seq_len", 256),
|
| 1006 |
+
self.scheduler.config.get("max_image_seq_len", 4096),
|
| 1007 |
+
self.scheduler.config.get("base_shift", 0.5),
|
| 1008 |
+
self.scheduler.config.get("max_shift", 1.15),
|
| 1009 |
+
)
|
| 1010 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
| 1011 |
+
self.scheduler,
|
| 1012 |
+
num_inference_steps,
|
| 1013 |
+
device,
|
| 1014 |
+
sigmas=sigmas,
|
| 1015 |
+
mu=mu,
|
| 1016 |
+
)
|
| 1017 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
| 1018 |
+
self._num_timesteps = len(timesteps)
|
| 1019 |
+
|
| 1020 |
+
# handle guidance
|
| 1021 |
+
if self.transformer.config.guidance_embeds:
|
| 1022 |
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
|
| 1023 |
+
guidance = guidance.expand(latents.shape[0])
|
| 1024 |
+
else:
|
| 1025 |
+
guidance = None
|
| 1026 |
+
|
| 1027 |
+
if (ip_adapter_image is not None or ip_adapter_image_embeds is not None) and (
|
| 1028 |
+
negative_ip_adapter_image is None and negative_ip_adapter_image_embeds is None
|
| 1029 |
+
):
|
| 1030 |
+
negative_ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8)
|
| 1031 |
+
negative_ip_adapter_image = [negative_ip_adapter_image] * self.transformer.encoder_hid_proj.num_ip_adapters
|
| 1032 |
+
|
| 1033 |
+
elif (ip_adapter_image is None and ip_adapter_image_embeds is None) and (
|
| 1034 |
+
negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None
|
| 1035 |
+
):
|
| 1036 |
+
ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8)
|
| 1037 |
+
ip_adapter_image = [ip_adapter_image] * self.transformer.encoder_hid_proj.num_ip_adapters
|
| 1038 |
+
|
| 1039 |
+
if self.joint_attention_kwargs is None:
|
| 1040 |
+
self._joint_attention_kwargs = {}
|
| 1041 |
+
|
| 1042 |
+
image_embeds = None
|
| 1043 |
+
negative_image_embeds = None
|
| 1044 |
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
| 1045 |
+
image_embeds = self.prepare_ip_adapter_image_embeds(
|
| 1046 |
+
ip_adapter_image,
|
| 1047 |
+
ip_adapter_image_embeds,
|
| 1048 |
+
device,
|
| 1049 |
+
batch_size * num_images_per_prompt,
|
| 1050 |
+
)
|
| 1051 |
+
if negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None:
|
| 1052 |
+
negative_image_embeds = self.prepare_ip_adapter_image_embeds(
|
| 1053 |
+
negative_ip_adapter_image,
|
| 1054 |
+
negative_ip_adapter_image_embeds,
|
| 1055 |
+
device,
|
| 1056 |
+
batch_size * num_images_per_prompt,
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
# 6. Denoising loop
|
| 1060 |
+
# We set the index here to remove DtoH sync, helpful especially during compilation.
|
| 1061 |
+
# Check out more details here: https://github.com/huggingface/diffusers/pull/11696
|
| 1062 |
+
self.scheduler.set_begin_index(0)
|
| 1063 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 1064 |
+
for i, t in enumerate(timesteps):
|
| 1065 |
+
if self.interrupt:
|
| 1066 |
+
continue
|
| 1067 |
+
|
| 1068 |
+
self._current_timestep = t
|
| 1069 |
+
if image_embeds is not None:
|
| 1070 |
+
self._joint_attention_kwargs["ip_adapter_image_embeds"] = image_embeds
|
| 1071 |
+
|
| 1072 |
+
latent_model_input = latents
|
| 1073 |
+
if image_latents is not None:
|
| 1074 |
+
latent_model_input = torch.cat([latents, image_latents], dim=1)
|
| 1075 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
| 1076 |
+
|
| 1077 |
+
noise_pred = self.transformer(
|
| 1078 |
+
hidden_states=latent_model_input,
|
| 1079 |
+
timestep=timestep / 1000,
|
| 1080 |
+
guidance=guidance,
|
| 1081 |
+
pooled_projections=pooled_prompt_embeds,
|
| 1082 |
+
encoder_hidden_states=prompt_embeds,
|
| 1083 |
+
txt_ids=text_ids,
|
| 1084 |
+
img_ids=latent_ids,
|
| 1085 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 1086 |
+
return_dict=False,
|
| 1087 |
+
)[0]
|
| 1088 |
+
noise_pred = noise_pred[:, : latents.size(1)]
|
| 1089 |
+
|
| 1090 |
+
if do_true_cfg:
|
| 1091 |
+
if negative_image_embeds is not None:
|
| 1092 |
+
self._joint_attention_kwargs["ip_adapter_image_embeds"] = negative_image_embeds
|
| 1093 |
+
neg_noise_pred = self.transformer(
|
| 1094 |
+
hidden_states=latent_model_input,
|
| 1095 |
+
timestep=timestep / 1000,
|
| 1096 |
+
guidance=guidance,
|
| 1097 |
+
pooled_projections=negative_pooled_prompt_embeds,
|
| 1098 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 1099 |
+
txt_ids=negative_text_ids,
|
| 1100 |
+
img_ids=latent_ids,
|
| 1101 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 1102 |
+
return_dict=False,
|
| 1103 |
+
)[0]
|
| 1104 |
+
neg_noise_pred = neg_noise_pred[:, : latents.size(1)]
|
| 1105 |
+
noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
|
| 1106 |
+
|
| 1107 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 1108 |
+
latents_dtype = latents.dtype
|
| 1109 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 1110 |
+
|
| 1111 |
+
if latents.dtype != latents_dtype:
|
| 1112 |
+
if torch.backends.mps.is_available():
|
| 1113 |
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
| 1114 |
+
latents = latents.to(latents_dtype)
|
| 1115 |
+
|
| 1116 |
+
if callback_on_step_end is not None:
|
| 1117 |
+
callback_kwargs = {}
|
| 1118 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 1119 |
+
callback_kwargs[k] = locals()[k]
|
| 1120 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 1121 |
+
|
| 1122 |
+
latents = callback_outputs.pop("latents", latents)
|
| 1123 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 1124 |
+
|
| 1125 |
+
# call the callback, if provided
|
| 1126 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 1127 |
+
progress_bar.update()
|
| 1128 |
+
|
| 1129 |
+
if XLA_AVAILABLE:
|
| 1130 |
+
xm.mark_step()
|
| 1131 |
+
|
| 1132 |
+
self._current_timestep = None
|
| 1133 |
+
|
| 1134 |
+
if output_type == "latent":
|
| 1135 |
+
image = latents
|
| 1136 |
+
else:
|
| 1137 |
+
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
| 1138 |
+
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
| 1139 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 1140 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 1141 |
+
|
| 1142 |
+
# Offload all models
|
| 1143 |
+
self.maybe_free_model_hooks()
|
| 1144 |
+
|
| 1145 |
+
if not return_dict:
|
| 1146 |
+
return (image,)
|
| 1147 |
+
|
| 1148 |
+
return FluxPipelineOutput(images=image)
|
example_input/edit_tests/1/ref_0.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/1/ref_1.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/1/res.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/2/ref_0.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/2/ref_1.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/2/res.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/3/ref_0.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/3/ref_1.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/3/res.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/4/ref_0.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/4/ref_1.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/4/res.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/5/ref_0.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/5/ref_1.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/5/res.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/6/ref_0.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/6/ref_1.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/6/res.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/7/ref_0.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/7/ref_1.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/7/res.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/8/ref_0.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/8/ref_1.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/8/res.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/edi_res.png
ADDED
|
Git LFS Details
|
example_input/edit_tests/ref.jpg
ADDED
|
Git LFS Details
|
example_input/edit_tests/src.jpg
ADDED
|
Git LFS Details
|
example_input/gen_tests/gen_res.png
ADDED
|
Git LFS Details
|
example_input/gen_tests/img1.jpg
ADD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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
try:
|
| 3 |
+
import torch_npu
|
| 4 |
+
from torch_npu.contrib import transfer_to_npu
|
| 5 |
+
import importlib
|
| 6 |
+
import transformers.utils
|
| 7 |
+
import transformers.models
|
| 8 |
+
origin_utils = transformers.utils
|
| 9 |
+
origin_models = transformers.models
|
| 10 |
+
import flash_attn
|
| 11 |
+
flash_attn.hack_transformers_flash_attn_2_available_check()
|
| 12 |
+
importlib.reload(transformers.utils)
|
| 13 |
+
importlib.reload(transformers.models)
|
| 14 |
+
origin_func = torch.nn.functional.interpolate
|
| 15 |
+
def new_func(input, size=None, scale_factor=None, mode='nearest', align_corners=None, recompute_scale_factor=None, antialias=False):
|
| 16 |
+
if mode == "bilinear":
|
| 17 |
+
dtype = input.dtype
|
| 18 |
+
res = origin_func(input.to(torch.bfloat16), size, scale_factor, mode, align_corners, recompute_scale_factor, antialias)
|
| 19 |
+
return res.to(dtype)
|
| 20 |
+
else:
|
| 21 |
+
return origin_func(input, size, scale_factor, mode, align_corners, recompute_scale_factor, antialias)
|
| 22 |
+
torch.nn.functional.interpolate = new_func
|
| 23 |
+
from utils import patch_npu_record_stream
|
| 24 |
+
from utils import patch_npu_diffusers_get_1d_rotary_pos_embed
|
| 25 |
+
patch_npu_record_stream()
|
| 26 |
+
patch_npu_diffusers_get_1d_rotary_pos_embed()
|
| 27 |
+
USE_NPU = True
|
| 28 |
+
except:
|
| 29 |
+
USE_NPU = False
|
| 30 |
+
from dreamomni2.pipeline_dreamomni2 import DreamOmni2Pipeline
|
| 31 |
+
from diffusers.utils import load_image
|
| 32 |
+
from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
|
| 33 |
+
# from qwen_vl_utils import process_vision_info
|
| 34 |
+
from utils.vprocess import process_vision_info, resizeinput
|
| 35 |
+
import os
|
| 36 |
+
import argparse
|
| 37 |
+
from tqdm import tqdm
|
| 38 |
+
import json
|
| 39 |
+
from PIL import Image
|
| 40 |
+
import re
|
| 41 |
+
import argparse
|
| 42 |
+
|
| 43 |
+
if USE_NPU:
|
| 44 |
+
device = "npu"
|
| 45 |
+
else:
|
| 46 |
+
device = "cuda"
|
| 47 |
+
|
| 48 |
+
def extract_gen_content(text):
|
| 49 |
+
text = text[6:-7]
|
| 50 |
+
|
| 51 |
+
return text
|
| 52 |
+
|
| 53 |
+
def parse_args():
|
| 54 |
+
"""Parses command-line arguments for model paths and server configuration."""
|
| 55 |
+
parser = argparse.ArgumentParser()
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
"--vlm_path",
|
| 58 |
+
type=str,
|
| 59 |
+
default="./models/vlm-model",
|
| 60 |
+
help="Path to the VLM model directory."
|
| 61 |
+
)
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"--edit_lora_path",
|
| 64 |
+
type=str,
|
| 65 |
+
default="./models/edit_lora",
|
| 66 |
+
help="Path to the FLUX.1-Kontext editing LoRA weights directory."
|
| 67 |
+
)
|
| 68 |
+
parser.add_argument(
|
| 69 |
+
"--base_model_path",
|
| 70 |
+
type=str,
|
| 71 |
+
default="black-forest-labs/FLUX.1-Kontext-dev",
|
| 72 |
+
help="Path to the FLUX.1-Kontext editing."
|
| 73 |
+
)
|
| 74 |
+
parser.add_argument(
|
| 75 |
+
"--input_img_path",
|
| 76 |
+
type=str,
|
| 77 |
+
nargs='+', # Accept one or more input paths
|
| 78 |
+
default=["example_input/edit_tests/src.jpg", "example_input/edit_tests/ref.jpg"],
|
| 79 |
+
help="List of input image paths (e.g., src and ref images)."
|
| 80 |
+
)
|
| 81 |
+
# Argument for the input instruction
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--input_instruction",
|
| 84 |
+
type=str,
|
| 85 |
+
default="Make the woman from the second image stand on the road in the first image.",
|
| 86 |
+
help="Instruction for image editing."
|
| 87 |
+
)
|
| 88 |
+
# Argument for the output image path
|
| 89 |
+
parser.add_argument(
|
| 90 |
+
"--output_path",
|
| 91 |
+
type=str,
|
| 92 |
+
default="example_input/edit_tests/edi_res.png",
|
| 93 |
+
help="Path to save the output image."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
args = parser.parse_args()
|
| 97 |
+
return args
|
| 98 |
+
|
| 99 |
+
ARGS = parse_args()
|
| 100 |
+
vlm_path = ARGS.vlm_path
|
| 101 |
+
edit_lora_path = ARGS.edit_lora_path
|
| 102 |
+
base_model = ARGS.base_model_path
|
| 103 |
+
pipe = DreamOmni2Pipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16)
|
| 104 |
+
pipe.to(device)
|
| 105 |
+
|
| 106 |
+
pipe.load_lora_weights(
|
| 107 |
+
edit_lora_path,
|
| 108 |
+
adapter_name="edit"
|
| 109 |
+
)
|
| 110 |
+
pipe.set_adapters(["edit"], adapter_weights=[1])
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
vlm_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 114 |
+
vlm_path, torch_dtype="bfloat16", device_map="cuda"
|
| 115 |
+
)
|
| 116 |
+
processor = AutoProcessor.from_pretrained(vlm_path)
|
| 117 |
+
|
| 118 |
+
def infer_vlm(input_img_path,input_instruction,prefix):
|
| 119 |
+
tp=[]
|
| 120 |
+
for path in input_img_path:
|
| 121 |
+
tp.append({"type": "image", "image": path})
|
| 122 |
+
tp.append({"type": "text", "text": input_instruction+prefix})
|
| 123 |
+
messages = [
|
| 124 |
+
{
|
| 125 |
+
"role": "user",
|
| 126 |
+
"content": tp,
|
| 127 |
+
}
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
# Preparation for inference
|
| 131 |
+
text = processor.apply_chat_template(
|
| 132 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 133 |
+
)
|
| 134 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
| 135 |
+
inputs = processor(
|
| 136 |
+
text=[text],
|
| 137 |
+
images=image_inputs,
|
| 138 |
+
videos=video_inputs,
|
| 139 |
+
padding=True,
|
| 140 |
+
return_tensors="pt",
|
| 141 |
+
)
|
| 142 |
+
inputs = inputs.to("cuda")
|
| 143 |
+
|
| 144 |
+
# Inference
|
| 145 |
+
generated_ids = vlm_model.generate(**inputs, do_sample=False, max_new_tokens=4096)
|
| 146 |
+
generated_ids_trimmed = [
|
| 147 |
+
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 148 |
+
]
|
| 149 |
+
output_text = processor.batch_decode(
|
| 150 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 151 |
+
)
|
| 152 |
+
return output_text[0]
|
| 153 |
+
|
| 154 |
+
def infer(source_imgs,prompt):
|
| 155 |
+
image = pipe(
|
| 156 |
+
images=source_imgs,
|
| 157 |
+
height=source_imgs[0].height,
|
| 158 |
+
width=source_imgs[0].width,
|
| 159 |
+
prompt=prompt,
|
| 160 |
+
num_inference_steps=30,
|
| 161 |
+
guidance_scale=3.5,
|
| 162 |
+
).images[0]
|
| 163 |
+
return image
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
input_img_path=ARGS.input_img_path
|
| 167 |
+
input_instruction=ARGS.input_instruction
|
| 168 |
+
|
| 169 |
+
prefix=" It is editing task."
|
| 170 |
+
source_imgs = []
|
| 171 |
+
for path in input_img_path:
|
| 172 |
+
img = load_image(path)
|
| 173 |
+
# source_imgs.append(img)
|
| 174 |
+
source_imgs.append(resizeinput(img))
|
| 175 |
+
|
| 176 |
+
prompt=infer_vlm(input_img_path,input_instruction,prefix)
|
| 177 |
+
prompt = extract_gen_content(prompt)
|
| 178 |
+
image=infer(source_imgs,prompt)
|
| 179 |
+
output_path = ARGS.output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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
try:
|
| 3 |
+
import torch_npu
|
| 4 |
+
from torch_npu.contrib import transfer_to_npu
|
| 5 |
+
import importlib
|
| 6 |
+
import transformers.utils
|
| 7 |
+
import transformers.models
|
| 8 |
+
origin_utils = transformers.utils
|
| 9 |
+
origin_models = transformers.models
|
| 10 |
+
import flash_attn
|
| 11 |
+
flash_attn.hack_transformers_flash_attn_2_available_check()
|
| 12 |
+
importlib.reload(transformers.utils)
|
| 13 |
+
importlib.reload(transformers.models)
|
| 14 |
+
origin_func = torch.nn.functional.interpolate
|
| 15 |
+
def new_func(input, size=None, scale_factor=None, mode='nearest', align_corners=None, recompute_scale_factor=None, antialias=False):
|
| 16 |
+
if mode == "bilinear":
|
| 17 |
+
dtype = input.dtype
|
| 18 |
+
res = origin_func(input.to(torch.bfloat16), size, scale_factor, mode, align_corners, recompute_scale_factor, antialias)
|
| 19 |
+
return res.to(dtype)
|
| 20 |
+
else:
|
| 21 |
+
return origin_func(input, size, scale_factor, mode, align_corners, recompute_scale_factor, antialias)
|
| 22 |
+
torch.nn.functional.interpolate = new_func
|
| 23 |
+
from utils import patch_npu_record_stream
|
| 24 |
+
from utils import patch_npu_diffusers_get_1d_rotary_pos_embed
|
| 25 |
+
patch_npu_record_stream()
|
| 26 |
+
patch_npu_diffusers_get_1d_rotary_pos_embed()
|
| 27 |
+
USE_NPU = True
|
| 28 |
+
except:
|
| 29 |
+
USE_NPU = False
|
| 30 |
+
from dreamomni2.pipeline_dreamomni2 import DreamOmni2Pipeline
|
| 31 |
+
from diffusers.utils import load_image
|
| 32 |
+
from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
|
| 33 |
+
# from qwen_vl_utils import process_vision_info
|
| 34 |
+
from utils.vprocess import process_vision_info, resizeinput
|
| 35 |
+
import os
|
| 36 |
+
import argparse
|
| 37 |
+
from tqdm import tqdm
|
| 38 |
+
import json
|
| 39 |
+
from PIL import Image
|
| 40 |
+
import re
|
| 41 |
+
import argparse
|
| 42 |
+
|
| 43 |
+
if USE_NPU:
|
| 44 |
+
device = "npu"
|
| 45 |
+
else:
|
| 46 |
+
device = "cuda"
|
| 47 |
+
|
| 48 |
+
def extract_gen_content(text):
|
| 49 |
+
text = text[6:-7]
|
| 50 |
+
|
| 51 |
+
return text
|
| 52 |
+
|
| 53 |
+
def parse_args():
|
| 54 |
+
"""Parses command-line arguments for model paths and server configuration."""
|
| 55 |
+
parser = argparse.ArgumentParser()
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
"--vlm_path",
|
| 58 |
+
type=str,
|
| 59 |
+
default="./models/vlm-model",
|
| 60 |
+
help="Path to the VLM model directory."
|
| 61 |
+
)
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"--gen_lora_path",
|
| 64 |
+
type=str,
|
| 65 |
+
default="./models/gen_lora",
|
| 66 |
+
help="Path to the FLUX.1-Kontext generation LoRA weights directory."
|
| 67 |
+
)
|
| 68 |
+
parser.add_argument(
|
| 69 |
+
"--base_model_path",
|
| 70 |
+
type=str,
|
| 71 |
+
default="black-forest-labs/FLUX.1-Kontext-dev",
|
| 72 |
+
help="Path to the FLUX.1-Kontext editing."
|
| 73 |
+
)
|
| 74 |
+
parser.add_argument(
|
| 75 |
+
"--input_img_path",
|
| 76 |
+
type=str,
|
| 77 |
+
nargs='+', # Accept one or more input paths
|
| 78 |
+
default=["example_input/gen_tests/img1.jpg","example_input/gen_tests/img2.jpg"],
|
| 79 |
+
help="List of input image paths (e.g., src and ref images)."
|
| 80 |
+
)
|
| 81 |
+
# Argument for the input instruction
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--input_instruction",
|
| 84 |
+
type=str,
|
| 85 |
+
default="In the scene, the character from the first image stands on the left, and the character from the second image stands on the right. They are shaking hands against the backdrop of a spaceship interior.",
|
| 86 |
+
help="Instruction for image generation."
|
| 87 |
+
)
|
| 88 |
+
parser.add_argument(
|
| 89 |
+
"--height",
|
| 90 |
+
type=int,
|
| 91 |
+
default=1024,
|
| 92 |
+
help="The height of output image."
|
| 93 |
+
)
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--width",
|
| 96 |
+
type=int,
|
| 97 |
+
default=1024,
|
| 98 |
+
help="The width of output image."
|
| 99 |
+
)
|
| 100 |
+
# Argument for the output image path
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--output_path",
|
| 103 |
+
type=str,
|
| 104 |
+
default="example_input/gen_tests/gen_res.png",
|
| 105 |
+
help="Path to save the output image."
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
args = parser.parse_args()
|
| 109 |
+
return args
|
| 110 |
+
|
| 111 |
+
ARGS = parse_args()
|
| 112 |
+
vlm_path = ARGS.vlm_path
|
| 113 |
+
gen_lora_path = ARGS.gen_lora_path
|
| 114 |
+
base_model = ARGS.base_model_path
|
| 115 |
+
pipe = DreamOmni2Pipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16)
|
| 116 |
+
pipe.to(device)
|
| 117 |
+
|
| 118 |
+
pipe.load_lora_weights(
|
| 119 |
+
gen_lora_path,
|
| 120 |
+
adapter_name="generation"
|
| 121 |
+
)
|
| 122 |
+
pipe.set_adapters(["generation"], adapter_weights=[1])
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
vlm_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 126 |
+
vlm_path, torch_dtype="bfloat16", device_map="cuda"
|
| 127 |
+
)
|
| 128 |
+
processor = AutoProcessor.from_pretrained(vlm_path)
|
| 129 |
+
|
| 130 |
+
def infer_vlm(input_img_path,input_instruction,prefix):
|
| 131 |
+
tp=[]
|
| 132 |
+
for path in input_img_path:
|
| 133 |
+
tp.append({"type": "image", "image": path})
|
| 134 |
+
tp.append({"type": "text", "text": input_instruction+prefix})
|
| 135 |
+
messages = [
|
| 136 |
+
{
|
| 137 |
+
"role": "user",
|
| 138 |
+
"content": tp,
|
| 139 |
+
}
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
# Preparation for inference
|
| 143 |
+
text = processor.apply_chat_template(
|
| 144 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 145 |
+
)
|
| 146 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
| 147 |
+
inputs = processor(
|
| 148 |
+
text=[text],
|
| 149 |
+
images=image_inputs,
|
| 150 |
+
videos=video_inputs,
|
| 151 |
+
padding=True,
|
| 152 |
+
return_tensors="pt",
|
| 153 |
+
)
|
| 154 |
+
inputs = inputs.to("cuda")
|
| 155 |
+
|
| 156 |
+
# Inference
|
| 157 |
+
generated_ids = vlm_model.generate(**inputs, do_sample=False, max_new_tokens=4096)
|
| 158 |
+
generated_ids_trimmed = [
|
| 159 |
+
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 160 |
+
]
|
| 161 |
+
output_text = processor.batch_decode(
|
| 162 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 163 |
+
)
|
| 164 |
+
return output_text[0]
|
| 165 |
+
|
| 166 |
+
def infer(source_imgs,prompt,height=1024,width=1024):
|
| 167 |
+
image = pipe(
|
| 168 |
+
images=source_imgs,
|
| 169 |
+
height=height,
|
| 170 |
+
width=width,
|
| 171 |
+
prompt=prompt,
|
| 172 |
+
num_inference_steps=30,
|
| 173 |
+
guidance_scale=3.5,
|
| 174 |
+
).images[0]
|
| 175 |
+
return image
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
input_img_path=ARGS.input_img_path
|
| 179 |
+
input_instruction=ARGS.input_instruction
|
| 180 |
+
|
| 181 |
+
prefix=" It is generation task."
|
| 182 |
+
source_imgs = []
|
| 183 |
+
for path in input_img_path:
|
| 184 |
+
img = load_image(path)
|
| 185 |
+
# source_imgs.append(img)
|
| 186 |
+
source_imgs.append(resizeinput(img))
|
| 187 |
+
|
| 188 |
+
prompt=infer_vlm(input_img_path,input_instruction,prefix)
|
| 189 |
+
prompt = extract_gen_content(prompt)
|
| 190 |
+
image=infer(source_imgs,prompt,height=ARGS.height,width=ARGS.width)
|
| 191 |
+
output_path = ARGS.output_path
|
| 192 |
+
image.save(output_path)
|
my_datasets/.gitkeep
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import gc
|
| 5 |
+
import functools
|
| 6 |
+
import contextlib
|
| 7 |
+
from typing import Dict, Union, Optional, Type, Set
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
|
| 11 |
+
from torch.distributed.fsdp import (
|
| 12 |
+
StateDictType,
|
| 13 |
+
FullOptimStateDictConfig,
|
| 14 |
+
FullStateDictConfig,
|
| 15 |
+
)
|
| 16 |
+
import torch.distributed.checkpoint as torch_dcp
|
| 17 |
+
import torch.distributed.checkpoint.state_dict
|
| 18 |
+
from torch.distributed.fsdp.api import (
|
| 19 |
+
ShardingStrategy,
|
| 20 |
+
BackwardPrefetch,
|
| 21 |
+
MixedPrecision,
|
| 22 |
+
)
|
| 23 |
+
import accelerate
|
| 24 |
+
import safetensors
|
| 25 |
+
import diffusers
|
| 26 |
+
import transformers
|
| 27 |
+
from huggingface_hub.serialization import split_torch_state_dict_into_shards
|
| 28 |
+
import os, re, json
|
| 29 |
+
from typing import Union
|
| 30 |
+
import torch
|
| 31 |
+
import safetensors.torch
|
| 32 |
+
import accelerate
|
| 33 |
+
# from .ema_utils import EMAModel
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def upcast_trainable_param_to_fp32_(fsdp_model):
|
| 37 |
+
for m in FSDP.fsdp_modules(fsdp_model):
|
| 38 |
+
if m._has_params:
|
| 39 |
+
param = m._flat_param
|
| 40 |
+
if (
|
| 41 |
+
param.dtype != torch.float32
|
| 42 |
+
and param.device != torch.device("meta")
|
| 43 |
+
and param.requires_grad
|
| 44 |
+
):
|
| 45 |
+
param.data = param.data.to(torch.float32)
|
| 46 |
+
m._handle._orig_param_dtype = torch.float32
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_module_to_ignore_mixed_precision():
|
| 50 |
+
try:
|
| 51 |
+
from apex.normalization import FusedLayerNorm
|
| 52 |
+
|
| 53 |
+
return [
|
| 54 |
+
torch.nn.GroupNorm,
|
| 55 |
+
torch.nn.modules.batchnorm._BatchNorm,
|
| 56 |
+
torch.nn.LayerNorm,
|
| 57 |
+
FusedLayerNorm,
|
| 58 |
+
]
|
| 59 |
+
except:
|
| 60 |
+
return [
|
| 61 |
+
torch.nn.GroupNorm,
|
| 62 |
+
torch.nn.modules.batchnorm._BatchNorm,
|
| 63 |
+
torch.nn.LayerNorm,
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def is_fsdp_model(model):
|
| 68 |
+
return len(FSDP.fsdp_modules(model)) > 0
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def size_based_auto_wrap_policy(
|
| 72 |
+
module: torch.nn.Module,
|
| 73 |
+
recurse: bool,
|
| 74 |
+
nonwrapped_numel: int,
|
| 75 |
+
# Additional custom arguments
|
| 76 |
+
min_num_params: int = int(1e8),
|
| 77 |
+
force_leaf_modules: Optional[Set[Type[torch.nn.Module]]] = None,
|
| 78 |
+
exclude_wrap_modules: Optional[Set[Type[torch.nn.Module]]] = None,
|
| 79 |
+
) -> bool:
|
| 80 |
+
"""
|
| 81 |
+
A size-based auto wrap policy.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
module (nn.Module): Current module being considered.
|
| 85 |
+
recurse (bool): If ``False``, then this function must decide whether
|
| 86 |
+
``module`` should be wrapped as an FSDP instance or not. If
|
| 87 |
+
``True``, then the function is still recursing down the module
|
| 88 |
+
tree as a part of the DFS.
|
| 89 |
+
nonwrapped_numel (int): Parameter numel not yet wrapped.
|
| 90 |
+
|
| 91 |
+
min_num_params (int): Customizable policy input that controls the size
|
| 92 |
+
threshold over which a module is ready to be wrapped. This is in
|
| 93 |
+
units of numel.
|
| 94 |
+
force_leaf_modules (Set[Type[nn.Module]]): Set of module types to keep
|
| 95 |
+
as leaves, i.e. their children will never be wrapped.
|
| 96 |
+
exclude_wrap_modules (Set[Type[nn.Module]]): Set of module types to be
|
| 97 |
+
excluded in wrapping.
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
Whether ``module`` should be wrapped.
|
| 101 |
+
"""
|
| 102 |
+
force_leaf_modules = (
|
| 103 |
+
size_based_auto_wrap_policy.FORCE_LEAF_MODULES # type: ignore[attr-defined]
|
| 104 |
+
if force_leaf_modules is None
|
| 105 |
+
else force_leaf_modules
|
| 106 |
+
)
|
| 107 |
+
exclude_wrap_modules = (
|
| 108 |
+
size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES # type: ignore[attr-defined]
|
| 109 |
+
if exclude_wrap_modules is None
|
| 110 |
+
else exclude_wrap_modules
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Keep the argument `min_num_params` for BC for now, but it represents the
|
| 114 |
+
# minimum non-wrapped *numel* before triggering a wrapping
|
| 115 |
+
min_nonwrapped_numel = min_num_params
|
| 116 |
+
is_large = nonwrapped_numel >= min_nonwrapped_numel
|
| 117 |
+
STOP_FLAG_NAME = "__FSDP_STOP_WARP_FLAG_CUSTOM_POLICY_size_based_auto_wrap_policy"
|
| 118 |
+
if recurse:
|
| 119 |
+
# use MixedPrecision cause ALWAYS recurse
|
| 120 |
+
if isinstance(module, tuple(force_leaf_modules)):
|
| 121 |
+
for m in module.children():
|
| 122 |
+
m.apply(lambda m: setattr(m, STOP_FLAG_NAME, True))
|
| 123 |
+
return True
|
| 124 |
+
else:
|
| 125 |
+
if getattr(module, size_based_auto_wrap_policy.LEAF_ROOT_FLAG_NAME, False):
|
| 126 |
+
return True
|
| 127 |
+
elif getattr(module, STOP_FLAG_NAME, False):
|
| 128 |
+
return False
|
| 129 |
+
else:
|
| 130 |
+
# If we are not recursing, determine if we should wrap.
|
| 131 |
+
return is_large and not isinstance(module, tuple(exclude_wrap_modules))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# Set those defaults to the size_based_auto_wrap_policy function. Make them easy to be imported.
|
| 135 |
+
size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES = {torch.nn.ModuleList, torch.nn.ModuleDict} # type: ignore[attr-defined]
|
| 136 |
+
size_based_auto_wrap_policy.FORCE_LEAF_MODULES = {torch.nn.MultiheadAttention} # type: ignore[attr-defined]
|
| 137 |
+
size_based_auto_wrap_policy.LEAF_ROOT_FLAG_NAME = (
|
| 138 |
+
"__FSDP_LEAF_ROOT_FLAG_CUSTOM_POLICY_size_based_auto_wrap_policy"
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def mark_leaf_root_(module):
|
| 143 |
+
setattr(
|
| 144 |
+
module,
|
| 145 |
+
size_based_auto_wrap_policy.LEAF_ROOT_FLAG_NAME,
|
| 146 |
+
True,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def make_model_fsdp(
|
| 151 |
+
model,
|
| 152 |
+
param_dtype,
|
| 153 |
+
device,
|
| 154 |
+
reduce_dtype=None,
|
| 155 |
+
buffer_dtype=None,
|
| 156 |
+
sync_module_states=True,
|
| 157 |
+
process_group=None,
|
| 158 |
+
sharding_strategy=ShardingStrategy.HYBRID_SHARD,
|
| 159 |
+
module_classes_to_ignore_mixed_precision=None,
|
| 160 |
+
ignored_states=None,
|
| 161 |
+
ignored_modules=None,
|
| 162 |
+
auto_wrap_policy=None,
|
| 163 |
+
part_size=1e6,
|
| 164 |
+
force_leaf_modules=None,
|
| 165 |
+
exclude_wrap_modules=None,
|
| 166 |
+
use_orig_params=False
|
| 167 |
+
):
|
| 168 |
+
if module_classes_to_ignore_mixed_precision is None:
|
| 169 |
+
module_classes_to_ignore_mixed_precision = (
|
| 170 |
+
get_module_to_ignore_mixed_precision()
|
| 171 |
+
)
|
| 172 |
+
if auto_wrap_policy is not None:
|
| 173 |
+
auto_wrap_policy = auto_wrap_policy
|
| 174 |
+
elif sharding_strategy == ShardingStrategy.NO_SHARD:
|
| 175 |
+
auto_wrap_policy = None
|
| 176 |
+
else:
|
| 177 |
+
auto_wrap_policy = functools.partial(
|
| 178 |
+
size_based_auto_wrap_policy,
|
| 179 |
+
min_num_params=part_size,
|
| 180 |
+
force_leaf_modules=force_leaf_modules,
|
| 181 |
+
exclude_wrap_modules=exclude_wrap_modules,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
model = FSDP(
|
| 185 |
+
model,
|
| 186 |
+
sharding_strategy=sharding_strategy,
|
| 187 |
+
process_group=process_group,
|
| 188 |
+
forward_prefetch=True,
|
| 189 |
+
backward_prefetch=BackwardPrefetch.BACKWARD_PRE,
|
| 190 |
+
limit_all_gathers=True,
|
| 191 |
+
use_orig_params=use_orig_params,
|
| 192 |
+
sync_module_states=sync_module_states,
|
| 193 |
+
mixed_precision=MixedPrecision(
|
| 194 |
+
param_dtype=param_dtype,
|
| 195 |
+
reduce_dtype=reduce_dtype or torch.float32,
|
| 196 |
+
buffer_dtype=buffer_dtype or torch.float32,
|
| 197 |
+
keep_low_precision_grads=False,
|
| 198 |
+
cast_forward_inputs=False,
|
| 199 |
+
cast_root_forward_inputs=True,
|
| 200 |
+
_module_classes_to_ignore=module_classes_to_ignore_mixed_precision,
|
| 201 |
+
),
|
| 202 |
+
auto_wrap_policy=auto_wrap_policy,
|
| 203 |
+
ignored_states=ignored_states,
|
| 204 |
+
ignored_modules=ignored_modules,
|
| 205 |
+
device_id=device,
|
| 206 |
+
)
|
| 207 |
+
torch.cuda.empty_cache()
|
| 208 |
+
gc.collect()
|
| 209 |
+
return model
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def save_fsdp_lora(
|
| 213 |
+
model_to_save, # FSDP 包裹的模型
|
| 214 |
+
save_directory: Union[str, os.PathLike],
|
| 215 |
+
is_main_process: bool = True,
|
| 216 |
+
lora_regex: str = r"(?:lora)", # 根据自己命名习惯调
|
| 217 |
+
):
|
| 218 |
+
"""
|
| 219 |
+
仅保存 LoRA 层的权重。适用于 FSDP 并与 safetensors 兼容。
|
| 220 |
+
"""
|
| 221 |
+
# 1. 解包 FSDP,拿到裸模型
|
| 222 |
+
unwrapped_model = accelerate.utils.extract_model_from_parallel(model_to_save)
|
| 223 |
+
|
| 224 |
+
# 2. 创建保存目录
|
| 225 |
+
if is_main_process:
|
| 226 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 227 |
+
|
| 228 |
+
# 3. 收集完整 state_dict(CPU 上)
|
| 229 |
+
state_dict = torch_dcp.state_dict.get_model_state_dict(
|
| 230 |
+
model_to_save,
|
| 231 |
+
options=torch_dcp.state_dict.StateDictOptions(
|
| 232 |
+
full_state_dict=True,
|
| 233 |
+
cpu_offload=True,
|
| 234 |
+
ignore_frozen_params=False,
|
| 235 |
+
),
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# 4. 过滤出 LoRA 参数
|
| 239 |
+
lora_pattern = re.compile(lora_regex)
|
| 240 |
+
lora_state_dict = {
|
| 241 |
+
k: v for k, v in state_dict.items() if lora_pattern.search(k) is not None
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
if not lora_state_dict:
|
| 245 |
+
raise ValueError(
|
| 246 |
+
"未找到匹配 LoRA 的参数。请检查 lora_regex 是否符合命名规则。"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
# 5. 保存为单文件 *.safetensors
|
| 250 |
+
if is_main_process:
|
| 251 |
+
weight_file = os.path.join(save_directory, "adapter_model.safetensors")
|
| 252 |
+
safetensors.torch.save_file(
|
| 253 |
+
lora_state_dict, weight_file, metadata={"format": "pt", "type": "lora"}
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def load_fsdp_model_(model_to_load: FSDP, save_directory: Union[str, os.PathLike]):
|
| 258 |
+
with FSDP.state_dict_type(
|
| 259 |
+
model_to_load,
|
| 260 |
+
state_dict_type=StateDictType.FULL_STATE_DICT,
|
| 261 |
+
state_dict_config=FullStateDictConfig(
|
| 262 |
+
rank0_only=False,
|
| 263 |
+
),
|
| 264 |
+
):
|
| 265 |
+
_model = model_to_load.from_pretrained(save_directory)
|
| 266 |
+
model_to_load.load_state_dict(_model.state_dict())
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def save_fsdp_optimizer(
|
| 270 |
+
models: Dict,
|
| 271 |
+
optimizer_to_save: torch.optim.Optimizer,
|
| 272 |
+
save_directory: Union[str, os.PathLike],
|
| 273 |
+
is_main_process: bool = True,
|
| 274 |
+
):
|
| 275 |
+
_fsdp_state_dict_config = dict(
|
| 276 |
+
state_dict_type=StateDictType.FULL_STATE_DICT,
|
| 277 |
+
optim_state_dict_config=FullOptimStateDictConfig(
|
| 278 |
+
offload_to_cpu=True,
|
| 279 |
+
rank0_only=True,
|
| 280 |
+
),
|
| 281 |
+
)
|
| 282 |
+
mgrs = list()
|
| 283 |
+
for m in models.values():
|
| 284 |
+
if len(FSDP.fsdp_modules(m)) > 0:
|
| 285 |
+
mgrs.append(FSDP.state_dict_type(m, **_fsdp_state_dict_config))
|
| 286 |
+
|
| 287 |
+
with contextlib.ExitStack() as stack:
|
| 288 |
+
for mgr in mgrs:
|
| 289 |
+
stack.enter_context(mgr)
|
| 290 |
+
optim_state_dict = FSDP.optim_state_dict(
|
| 291 |
+
torch.nn.ModuleDict(models),
|
| 292 |
+
optimizer_to_save,
|
| 293 |
+
)
|
| 294 |
+
if is_main_process:
|
| 295 |
+
torch.save(
|
| 296 |
+
optim_state_dict, os.path.join(save_directory, "optim_states.pth")
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def load_fsdp_optimizer_(
|
| 301 |
+
models: Dict,
|
| 302 |
+
optimizer_to_load: torch.optim.Optimizer,
|
| 303 |
+
save_directory: Union[str, os.PathLike],
|
| 304 |
+
):
|
| 305 |
+
_fsdp_state_dict_config = dict(
|
| 306 |
+
state_dict_type=StateDictType.FULL_STATE_DICT,
|
| 307 |
+
optim_state_dict_config=FullOptimStateDictConfig(
|
| 308 |
+
rank0_only=False,
|
| 309 |
+
),
|
| 310 |
+
)
|
| 311 |
+
mgrs = list()
|
| 312 |
+
for m in models.values():
|
| 313 |
+
if len(FSDP.fsdp_modules(m)) > 0:
|
| 314 |
+
mgrs.append(FSDP.state_dict_type(m, **_fsdp_state_dict_config))
|
| 315 |
+
|
| 316 |
+
with contextlib.ExitStack() as stack:
|
| 317 |
+
for mgr in mgrs:
|
| 318 |
+
stack.enter_context(mgr)
|
| 319 |
+
optimizer_path = os.path.join(save_directory, "optim_states.pth")
|
| 320 |
+
assert os.path.isfile(optimizer_path)
|
| 321 |
+
optim_state_dict = torch.load(optimizer_path)
|
| 322 |
+
optim_state_dict = FSDP.optim_state_dict_to_load(
|
| 323 |
+
torch.nn.ModuleDict(models),
|
| 324 |
+
optimizer_to_load,
|
| 325 |
+
optim_state_dict,
|
| 326 |
+
)
|
| 327 |
+
optimizer_to_load.load_state_dict(optim_state_dict)
|
requirements.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
timm==1.0.20
|
| 2 |
+
ujson
|
| 3 |
+
peft==0.17.1
|
| 4 |
+
datasets==4.1.1
|
| 5 |
+
transformers==4.56.2
|
| 6 |
+
opencv-python
|
| 7 |
+
qwen-vl-utils==0.0.14
|
| 8 |
+
lmdb==1.7.3
|
| 9 |
+
diffusers==0.35.1
|
| 10 |
+
numpy==1.26.4
|
| 11 |
+
torch==2.8.0
|
| 12 |
+
torchaudio==2.8.0
|
| 13 |
+
torchvision==0.23.0
|
| 14 |
+
gradio==5.47.2
|
| 15 |
+
sentenc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import re
|
| 3 |
+
import json
|
| 4 |
+
import gc
|
| 5 |
+
import functools
|
| 6 |
+
import contextlib
|
| 7 |
+
from typing import Dict, Union, Optional, Type, Set
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
|
| 11 |
+
from torch.distributed.fsdp import (
|
| 12 |
+
StateDictType,
|
| 13 |
+
FullOptimStateDictConfig,
|
| 14 |
+
FullStateDictConfig,
|
| 15 |
+
)
|
| 16 |
+
import torch.distributed.checkpoint as torch_dcp
|
| 17 |
+
import torch.distributed.checkpoint.state_dict
|
| 18 |
+
from torch.distributed.fsdp.api import (
|
| 19 |
+
ShardingStrategy,
|
| 20 |
+
BackwardPrefetch,
|
| 21 |
+
MixedPrecision,
|
| 22 |
+
)
|
| 23 |
+
import accelerate
|
| 24 |
+
import safetensors
|
| 25 |
+
import diffusers
|
| 26 |
+
import transformers
|
| 27 |
+
from huggingface_hub.serialization import split_torch_state_dict_into_shards
|
| 28 |
+
import os, re, json
|
| 29 |
+
from typing import Union
|
| 30 |
+
import torch
|
| 31 |
+
import safetensors.torch
|
| 32 |
+
import accelerate
|
| 33 |
+
# from .ema_utils import EMAModel
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def upcast_trainable_param_to_fp32_(fsdp_model):
|
| 37 |
+
for m in FSDP.fsdp_modules(fsdp_model):
|
| 38 |
+
if m._has_params:
|
| 39 |
+
param = m._flat_param
|
| 40 |
+
if (
|
| 41 |
+
param.dtype != torch.float32
|
| 42 |
+
and param.device != torch.device("meta")
|
| 43 |
+
and param.requires_grad
|
| 44 |
+
):
|
| 45 |
+
param.data = param.data.to(torch.float32)
|
| 46 |
+
m._handle._orig_param_dtype = torch.float32
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_module_to_ignore_mixed_precision():
|
| 50 |
+
try:
|
| 51 |
+
from apex.normalization import FusedLayerNorm
|
| 52 |
+
|
| 53 |
+
return [
|
| 54 |
+
torch.nn.GroupNorm,
|
| 55 |
+
torch.nn.modules.batchnorm._BatchNorm,
|
| 56 |
+
torch.nn.LayerNorm,
|
| 57 |
+
FusedLayerNorm,
|
| 58 |
+
]
|
| 59 |
+
except:
|
| 60 |
+
return [
|
| 61 |
+
torch.nn.GroupNorm,
|
| 62 |
+
torch.nn.modules.batchnorm._BatchNorm,
|
| 63 |
+
torch.nn.LayerNorm,
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def is_fsdp_model(model):
|
| 68 |
+
return len(FSDP.fsdp_modules(model)) > 0
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def size_based_auto_wrap_policy(
|
| 72 |
+
module: torch.nn.Module,
|
| 73 |
+
recurse: bool,
|
| 74 |
+
nonwrapped_numel: int,
|
| 75 |
+
# Additional custom arguments
|
| 76 |
+
min_num_params: int = int(1e8),
|
| 77 |
+
force_leaf_modules: Optional[Set[Type[torch.nn.Module]]] = None,
|
| 78 |
+
exclude_wrap_modules: Optional[Set[Type[torch.nn.Module]]] = None,
|
| 79 |
+
) -> bool:
|
| 80 |
+
"""
|
| 81 |
+
A size-based auto wrap policy.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
module (nn.Module): Current module being considered.
|
| 85 |
+
recurse (bool): If ``False``, then this function must decide whether
|
| 86 |
+
``module`` should be wrapped as an FSDP instance or not. If
|
| 87 |
+
``True``, then the function is still recursing down the module
|
| 88 |
+
tree as a part of the DFS.
|
| 89 |
+
nonwrapped_numel (int): Parameter numel not yet wrapped.
|
| 90 |
+
|
| 91 |
+
min_num_params (int): Customizable policy input that controls the size
|
| 92 |
+
threshold over which a module is ready to be wrapped. This is in
|
| 93 |
+
units of numel.
|
| 94 |
+
force_leaf_modules (Set[Type[nn.Module]]): Set of module types to keep
|
| 95 |
+
as leaves, i.e. their children will never be wrapped.
|
| 96 |
+
exclude_wrap_modules (Set[Type[nn.Module]]): Set of module types to be
|
| 97 |
+
excluded in wrapping.
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
Whether ``module`` should be wrapped.
|
| 101 |
+
"""
|
| 102 |
+
force_leaf_modules = (
|
| 103 |
+
size_based_auto_wrap_policy.FORCE_LEAF_MODULES # type: ignore[attr-defined]
|
| 104 |
+
if force_leaf_modules is None
|
| 105 |
+
else force_leaf_modules
|
| 106 |
+
)
|
| 107 |
+
exclude_wrap_modules = (
|
| 108 |
+
size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES # type: ignore[attr-defined]
|
| 109 |
+
if exclude_wrap_modules is None
|
| 110 |
+
else exclude_wrap_modules
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Keep the argument `min_num_params` for BC for now, but it represents the
|
| 114 |
+
# minimum non-wrapped *numel* before triggering a wrapping
|
| 115 |
+
min_nonwrapped_numel = min_num_params
|
| 116 |
+
is_large = nonwrapped_numel >= min_nonwrapped_numel
|
| 117 |
+
STOP_FLAG_NAME = "__FSDP_STOP_WARP_FLAG_CUSTOM_POLICY_size_based_auto_wrap_policy"
|
| 118 |
+
if recurse:
|
| 119 |
+
# use MixedPrecision cause ALWAYS recurse
|
| 120 |
+
if isinstance(module, tuple(force_leaf_modules)):
|
| 121 |
+
for m in module.children():
|
| 122 |
+
m.apply(lambda m: setattr(m, STOP_FLAG_NAME, True))
|
| 123 |
+
return True
|
| 124 |
+
else:
|
| 125 |
+
if getattr(module, size_based_auto_wrap_policy.LEAF_ROOT_FLAG_NAME, False):
|
| 126 |
+
return True
|
| 127 |
+
elif getattr(module, STOP_FLAG_NAME, False):
|
| 128 |
+
return False
|
| 129 |
+
else:
|
| 130 |
+
# If we are not recursing, determine if we should wrap.
|
| 131 |
+
return is_large and not isinstance(module, tuple(exclude_wrap_modules))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# Set those defaults to the size_based_auto_wrap_policy function. Make them easy to be imported.
|
| 135 |
+
size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES = {torch.nn.ModuleList, torch.nn.ModuleDict} # type: ignore[attr-defined]
|
| 136 |
+
size_based_auto_wrap_policy.FORCE_LEAF_MODULES = {torch.nn.MultiheadAttention} # type: ignore[attr-defined]
|
| 137 |
+
size_based_auto_wrap_policy.LEAF_ROOT_FLAG_NAME = (
|
| 138 |
+
"__FSDP_LEAF_ROOT_FLAG_CUSTOM_POLICY_size_based_auto_wrap_policy"
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def mark_leaf_root_(module):
|
| 143 |
+
setattr(
|
| 144 |
+
module,
|
| 145 |
+
size_based_auto_wrap_policy.LEAF_ROOT_FLAG_NAME,
|
| 146 |
+
True,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def make_model_fsdp(
|
| 151 |
+
model,
|
| 152 |
+
param_dtype,
|
| 153 |
+
device,
|
| 154 |
+
reduce_dtype=None,
|
| 155 |
+
buffer_dtype=None,
|
| 156 |
+
sync_module_states=True,
|
| 157 |
+
process_group=None,
|
| 158 |
+
sharding_strategy=ShardingStrategy.HYBRID_SHARD,
|
| 159 |
+
module_classes_to_ignore_mixed_precision=None,
|
| 160 |
+
ignored_states=None,
|
| 161 |
+
ignored_modules=None,
|
| 162 |
+
auto_wrap_policy=None,
|
| 163 |
+
part_size=1e6,
|
| 164 |
+
force_leaf_modules=None,
|
| 165 |
+
exclude_wrap_modules=None,
|
| 166 |
+
use_orig_params=False
|
| 167 |
+
):
|
| 168 |
+
if module_classes_to_ignore_mixed_precision is None:
|
| 169 |
+
module_classes_to_ignore_mixed_precision = (
|
| 170 |
+
get_module_to_ignore_mixed_precision()
|
| 171 |
+
)
|
| 172 |
+
if auto_wrap_policy is not None:
|
| 173 |
+
auto_wrap_policy = auto_wrap_policy
|
| 174 |
+
elif sharding_strategy == ShardingStrategy.NO_SHARD:
|
| 175 |
+
auto_wrap_policy = None
|
| 176 |
+
else:
|
| 177 |
+
auto_wrap_policy = functools.partial(
|
| 178 |
+
size_based_auto_wrap_policy,
|
| 179 |
+
min_num_params=part_size,
|
| 180 |
+
force_leaf_modules=force_leaf_modules,
|
| 181 |
+
exclude_wrap_modules=exclude_wrap_modules,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
model = FSDP(
|
| 185 |
+
model,
|
| 186 |
+
sharding_strategy=sharding_strategy,
|
| 187 |
+
process_group=process_group,
|
| 188 |
+
forward_prefetch=True,
|
| 189 |
+
backward_prefetch=BackwardPrefetch.BACKWARD_PRE,
|
| 190 |
+
limit_all_gathers=True,
|
| 191 |
+
use_orig_params=use_orig_params,
|
| 192 |
+
sync_module_states=sync_module_states,
|
| 193 |
+
mixed_precision=MixedPrecision(
|
| 194 |
+
param_dtype=param_dtype,
|
| 195 |
+
reduce_dtype=reduce_dtype or torch.float32,
|
| 196 |
+
buffer_dtype=buffer_dtype or torch.float32,
|
| 197 |
+
keep_low_precision_grads=False,
|
| 198 |
+
cast_forward_inputs=False,
|
| 199 |
+
cast_root_forward_inputs=True,
|
| 200 |
+
_module_classes_to_ignore=module_classes_to_ignore_mixed_precision,
|
| 201 |
+
),
|
| 202 |
+
auto_wrap_policy=auto_wrap_policy,
|
| 203 |
+
ignored_states=ignored_states,
|
| 204 |
+
ignored_modules=ignored_modules,
|
| 205 |
+
device_id=device,
|
| 206 |
+
)
|
| 207 |
+
torch.cuda.empty_cache()
|
| 208 |
+
gc.collect()
|
| 209 |
+
return model
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def save_fsdp_lora(
|
| 213 |
+
model_to_save, # FSDP 包裹的模型
|
| 214 |
+
save_directory: Union[str, os.PathLike],
|
| 215 |
+
is_main_process: bool = True,
|
| 216 |
+
lora_regex: str = r"(?:lora)", # 根据自己命名习惯调
|
| 217 |
+
):
|
| 218 |
+
"""
|
| 219 |
+
仅保存 LoRA 层的权重。适用于 FSDP 并与 safetensors 兼容。
|
| 220 |
+
"""
|
| 221 |
+
# 1. 解包 FSDP,拿到裸模型
|
| 222 |
+
unwrapped_model = accelerate.utils.extract_model_from_parallel(model_to_save)
|
| 223 |
+
|
| 224 |
+
# 2. 创建保存目录
|
| 225 |
+
if is_main_process:
|
| 226 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 227 |
+
|
| 228 |
+
# 3. 收集完整 state_dict(CPU 上)
|
| 229 |
+
state_dict = torch_dcp.state_dict.get_model_state_dict(
|
| 230 |
+
model_to_save,
|
| 231 |
+
options=torch_dcp.state_dict.StateDictOptions(
|
| 232 |
+
full_state_dict=True,
|
| 233 |
+
cpu_offload=True,
|
| 234 |
+
ignore_frozen_params=False,
|
| 235 |
+
),
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# 4. 过滤出 LoRA 参数
|
| 239 |
+
lora_pattern = re.compile(lora_regex)
|
| 240 |
+
lora_state_dict = {
|
| 241 |
+
k: v for k, v in state_dict.items() if lora_pattern.search(k) is not None
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
if not lora_state_dict:
|
| 245 |
+
raise ValueError(
|
| 246 |
+
"未找到匹配 LoRA 的参数。请检查 lora_regex 是否符合命名规则。"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
# 5. 保存为单文件 *.safetensors
|
| 250 |
+
if is_main_process:
|
| 251 |
+
weight_file = os.path.join(save_directory, "adapter_model.safetensors")
|
| 252 |
+
safetensors.torch.save_file(
|
| 253 |
+
lora_state_dict, weight_file, metadata={"format": "pt", "type": "lora"}
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def load_fsdp_model_(model_to_load: FSDP, save_directory: Union[str, os.PathLike]):
|
| 258 |
+
with FSDP.state_dict_type(
|
| 259 |
+
model_to_load,
|
| 260 |
+
state_dict_type=StateDictType.FULL_STATE_DICT,
|
| 261 |
+
state_dict_config=FullStateDictConfig(
|
| 262 |
+
rank0_only=False,
|
| 263 |
+
),
|
| 264 |
+
):
|
| 265 |
+
_model = model_to_load.from_pretrained(save_directory)
|
| 266 |
+
model_to_load.load_state_dict(_model.state_dict())
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def save_fsdp_optimizer(
|
| 270 |
+
models: Dict,
|
| 271 |
+
optimizer_to_save: torch.optim.Optimizer,
|
| 272 |
+
save_directory: Union[str, os.PathLike],
|
| 273 |
+
is_main_process: bool = True,
|
| 274 |
+
):
|
| 275 |
+
_fsdp_state_dict_config = dict(
|
| 276 |
+
state_dict_type=StateDictType.FULL_STATE_DICT,
|
| 277 |
+
optim_state_dict_config=FullOptimStateDictConfig(
|
| 278 |
+
offload_to_cpu=True,
|
| 279 |
+
rank0_only=True,
|
| 280 |
+
),
|
| 281 |
+
)
|
| 282 |
+
mgrs = list()
|
| 283 |
+
for m in models.values():
|
| 284 |
+
if len(FSDP.fsdp_modules(m)) > 0:
|
| 285 |
+
mgrs.append(FSDP.state_dict_type(m, **_fsdp_state_dict_config))
|
| 286 |
+
|
| 287 |
+
with contextlib.ExitStack() as stack:
|
| 288 |
+
for mgr in mgrs:
|
| 289 |
+
stack.enter_context(mgr)
|
| 290 |
+
optim_state_dict = FSDP.optim_state_dict(
|
| 291 |
+
torch.nn.ModuleDict(models),
|
| 292 |
+
optimizer_to_save,
|
| 293 |
+
)
|
| 294 |
+
if is_main_process:
|
| 295 |
+
torch.save(
|
| 296 |
+
optim_state_dict, os.path.join(save_directory, "optim_states.pth")
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def load_fsdp_optimizer_(
|
| 301 |
+
models: Dict,
|
| 302 |
+
optimizer_to_load: torch.optim.Optimizer,
|
| 303 |
+
save_directory: Union[str, os.PathLike],
|
| 304 |
+
):
|
| 305 |
+
_fsdp_state_dict_config = dict(
|
| 306 |
+
state_dict_type=StateDictType.FULL_STATE_DICT,
|
| 307 |
+
optim_state_dict_config=FullOptimStateDictConfig(
|
| 308 |
+
rank0_only=False,
|
| 309 |
+
),
|
| 310 |
+
)
|
| 311 |
+
mgrs = list()
|
| 312 |
+
for m in models.values():
|
| 313 |
+
if len(FSDP.fsdp_modules(m)) > 0:
|
| 314 |
+
mgrs.append(FSDP.state_dict_type(m, **_fsdp_state_dict_config))
|
| 315 |
+
|
| 316 |
+
with contextlib.ExitStack() as stack:
|
| 317 |
+
for mgr in mgrs:
|
| 318 |
+
stack.enter_context(mgr)
|
| 319 |
+
optimizer_path = os.path.join(save_directory, "optim_states.pth")
|
| 320 |
+
assert os.path.isfile(optimizer_path)
|
| 321 |
+
optim_state_dict = torch.load(optimizer_path)
|
| 322 |
+
optim_state_dict = FSDP.optim_state_dict_to_load(
|
| 323 |
+
torch.nn.ModuleDict(models),
|
| 324 |
+
optimizer_to_load,
|
| 325 |
+
optim_state_dict,
|
| 326 |
+
)
|
| 327 |
+
optimizer_to_load.load_state_dict(optim_state_dict)
|
utils/infer_utils.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
def tokenize_prompt(tokenizer, prompt, max_sequence_length):
|
| 4 |
+
text_inputs = tokenizer(
|
| 5 |
+
prompt,
|
| 6 |
+
padding="max_length",
|
| 7 |
+
max_length=max_sequence_length,
|
| 8 |
+
truncation=True,
|
| 9 |
+
return_length=False,
|
| 10 |
+
return_overflowing_tokens=False,
|
| 11 |
+
return_tensors="pt",
|
| 12 |
+
)
|
| 13 |
+
text_input_ids = text_inputs.input_ids
|
| 14 |
+
return text_input_ids
|
| 15 |
+
|
| 16 |
+
def _encode_prompt_with_t5(
|
| 17 |
+
text_encoder,
|
| 18 |
+
tokenizer,
|
| 19 |
+
max_sequence_length=512,
|
| 20 |
+
prompt=None,
|
| 21 |
+
num_images_per_prompt=1,
|
| 22 |
+
device=None,
|
| 23 |
+
text_input_ids=None,
|
| 24 |
+
):
|
| 25 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 26 |
+
batch_size = len(prompt)
|
| 27 |
+
|
| 28 |
+
if tokenizer is not None:
|
| 29 |
+
text_inputs = tokenizer(
|
| 30 |
+
prompt,
|
| 31 |
+
padding="max_length",
|
| 32 |
+
max_length=max_sequence_length,
|
| 33 |
+
truncation=True,
|
| 34 |
+
return_length=False,
|
| 35 |
+
return_overflowing_tokens=False,
|
| 36 |
+
return_tensors="pt",
|
| 37 |
+
)
|
| 38 |
+
text_input_ids = text_inputs.input_ids
|
| 39 |
+
else:
|
| 40 |
+
if text_input_ids is None:
|
| 41 |
+
raise ValueError("text_input_ids must be provided when the tokenizer is not specified")
|
| 42 |
+
|
| 43 |
+
prompt_embeds = text_encoder(text_input_ids.to(device))[0]
|
| 44 |
+
|
| 45 |
+
if hasattr(text_encoder, "module"):
|
| 46 |
+
dtype = text_encoder.module.dtype
|
| 47 |
+
else:
|
| 48 |
+
dtype = text_encoder.dtype
|
| 49 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 50 |
+
|
| 51 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 52 |
+
|
| 53 |
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
| 54 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 55 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 56 |
+
|
| 57 |
+
return prompt_embeds
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _encode_prompt_with_clip(
|
| 61 |
+
text_encoder,
|
| 62 |
+
tokenizer,
|
| 63 |
+
prompt: str,
|
| 64 |
+
device=None,
|
| 65 |
+
text_input_ids=None,
|
| 66 |
+
num_images_per_prompt: int = 1,
|
| 67 |
+
):
|
| 68 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 69 |
+
batch_size = len(prompt)
|
| 70 |
+
|
| 71 |
+
if tokenizer is not None:
|
| 72 |
+
text_inputs = tokenizer(
|
| 73 |
+
prompt,
|
| 74 |
+
padding="max_length",
|
| 75 |
+
max_length=77,
|
| 76 |
+
truncation=True,
|
| 77 |
+
return_overflowing_tokens=False,
|
| 78 |
+
return_length=False,
|
| 79 |
+
return_tensors="pt",
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
text_input_ids = text_inputs.input_ids
|
| 83 |
+
else:
|
| 84 |
+
if text_input_ids is None:
|
| 85 |
+
raise ValueError("text_input_ids must be provided when the tokenizer is not specified")
|
| 86 |
+
|
| 87 |
+
prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=False)
|
| 88 |
+
|
| 89 |
+
if hasattr(text_encoder, "module"):
|
| 90 |
+
dtype = text_encoder.module.dtype
|
| 91 |
+
else:
|
| 92 |
+
dtype = text_encoder.dtype
|
| 93 |
+
# Use pooled output of CLIPTextModel
|
| 94 |
+
prompt_embeds = prompt_embeds.pooler_output
|
| 95 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 96 |
+
|
| 97 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 98 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 99 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
| 100 |
+
|
| 101 |
+
return prompt_embeds
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def encode_prompt(
|
| 105 |
+
text_encoders,
|
| 106 |
+
tokenizers,
|
| 107 |
+
prompt: str,
|
| 108 |
+
max_sequence_length,
|
| 109 |
+
device=None,
|
| 110 |
+
num_images_per_prompt: int = 1,
|
| 111 |
+
text_input_ids_list=None,
|
| 112 |
+
):
|
| 113 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 114 |
+
|
| 115 |
+
if hasattr(text_encoders[0], "module"):
|
| 116 |
+
dtype = text_encoders[0].module.dtype
|
| 117 |
+
else:
|
| 118 |
+
dtype = text_encoders[0].dtype
|
| 119 |
+
|
| 120 |
+
pooled_prompt_embeds = _encode_prompt_with_clip(
|
| 121 |
+
text_encoder=text_encoders[0],
|
| 122 |
+
tokenizer=tokenizers[0],
|
| 123 |
+
prompt=prompt,
|
| 124 |
+
device=device if device is not None else text_encoders[0].device,
|
| 125 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 126 |
+
text_input_ids=text_input_ids_list[0] if text_input_ids_list else None,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
prompt_embeds = _encode_prompt_with_t5(
|
| 130 |
+
text_encoder=text_encoders[1],
|
| 131 |
+
tokenizer=tokenizers[1],
|
| 132 |
+
max_sequence_length=max_sequence_length,
|
| 133 |
+
prompt=prompt,
|
| 134 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 135 |
+
device=device if device is not None else text_encoders[1].device,
|
| 136 |
+
text_input_ids=text_input_ids_list[1] if text_input_ids_list else None,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
|
| 140 |
+
|
| 141 |
+
return prompt_embeds, pooled_prompt_embeds, text_ids
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def compute_text_embeddings( args, accelerator, prompt, text_encoders, tokenizers):
|
| 145 |
+
with torch.no_grad():
|
| 146 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = encode_prompt(
|
| 147 |
+
text_encoders, tokenizers, prompt, args.max_sequence_length
|
| 148 |
+
)
|
| 149 |
+
prompt_embeds = prompt_embeds.to(accelerator.device)
|
| 150 |
+
pooled_prompt_embeds = pooled_prompt_embeds.to(accelerator.device)
|
| 151 |
+
text_ids = text_ids.to(accelerator.device)
|
| 152 |
+
return prompt_embeds, pooled_prompt_embeds, text_ids
|
| 153 |
+
|
| 154 |
+
def get_sigmas(noise_scheduler_copy,accelerator, timesteps, n_dim=4, dtype=torch.float32):
|
| 155 |
+
sigmas = noise_scheduler_copy.sigmas.to(device=accelerator.device, dtype=dtype)
|
| 156 |
+
schedule_timesteps = noise_scheduler_copy.timesteps.to(accelerator.device)
|
| 157 |
+
timesteps = timesteps.to(accelerator.device)
|
| 158 |
+
step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 159 |
+
|
| 160 |
+
sigma = sigmas[step_indices].flatten()
|
| 161 |
+
while len(sigma.shape) < n_dim:
|
| 162 |
+
sigma = sigma.unsqueeze(-1)
|
| 163 |
+
return sigma
|
utils/init_utils.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import CLIPTokenizer, PretrainedConfig, T5TokenizerFast
|
| 2 |
+
import logging
|
| 3 |
+
def load_text_encoders(args, class_one, class_two):
|
| 4 |
+
text_encoder_one = class_one.from_pretrained(
|
| 5 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
|
| 6 |
+
)
|
| 7 |
+
text_encoder_two = class_two.from_pretrained(
|
| 8 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
|
| 9 |
+
)
|
| 10 |
+
return text_encoder_one, text_encoder_two
|
| 11 |
+
|
| 12 |
+
def import_model_class_from_model_name_or_path(
|
| 13 |
+
pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
|
| 14 |
+
):
|
| 15 |
+
text_encoder_config = PretrainedConfig.from_pretrained(
|
| 16 |
+
pretrained_model_name_or_path, subfolder=subfolder, revision=revision
|
| 17 |
+
)
|
| 18 |
+
model_class = text_encoder_config.architectures[0]
|
| 19 |
+
if model_class == "CLIPTextModel":
|
| 20 |
+
from transformers import CLIPTextModel
|
| 21 |
+
|
| 22 |
+
return CLIPTextModel
|
| 23 |
+
elif model_class == "T5EncoderModel":
|
| 24 |
+
from transformers import T5EncoderModel
|
| 25 |
+
|
| 26 |
+
return T5EncoderModel
|
| 27 |
+
else:
|
| 28 |
+
raise ValueError(f"{model_class} is not supported.")
|
| 29 |
+
|
| 30 |
+
def create_logger(logging_dir,accelerator):
|
| 31 |
+
"""
|
| 32 |
+
Create a logger that writes to a log file and stdout.
|
| 33 |
+
"""
|
| 34 |
+
if accelerator.is_main_process: # real logger
|
| 35 |
+
logging.basicConfig(
|
| 36 |
+
level=logging.INFO,
|
| 37 |
+
format="[\033[34m%(asctime)s\033[0m] %(message)s",
|
| 38 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 39 |
+
handlers=[
|
| 40 |
+
logging.StreamHandler(),
|
| 41 |
+
logging.FileHandler(f"{logging_dir}/log.txt"),
|
| 42 |
+
],
|
| 43 |
+
)
|
| 44 |
+
logger = logging.getLogger(__name__)
|
| 45 |
+
else: # dummy logger (does nothing)
|
| 46 |
+
logger = logging.getLogger(__name__)
|
| 47 |
+
logger.addHandler(logging.NullHandler())
|
| 48 |
+
return logger
|
utils/parser_config.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
def parse_args(input_args=None):
|
| 5 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 6 |
+
parser.add_argument(
|
| 7 |
+
"--pretrained_model_name_or_path",
|
| 8 |
+
type=str,
|
| 9 |
+
default=None,
|
| 10 |
+
required=True,
|
| 11 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 12 |
+
)
|
| 13 |
+
parser.add_argument(
|
| 14 |
+
"--revision",
|
| 15 |
+
type=str,
|
| 16 |
+
default=None,
|
| 17 |
+
required=False,
|
| 18 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 19 |
+
)
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
"--vae_encode_mode",
|
| 22 |
+
type=str,
|
| 23 |
+
default="mode",
|
| 24 |
+
choices=["sample", "mode"],
|
| 25 |
+
help="VAE encoding mode.",
|
| 26 |
+
)
|
| 27 |
+
parser.add_argument(
|
| 28 |
+
"--variant",
|
| 29 |
+
type=str,
|
| 30 |
+
default=None,
|
| 31 |
+
help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
|
| 32 |
+
)
|
| 33 |
+
parser.add_argument("--repeats", type=int, default=1, help="How many times to repeat the training data.")
|
| 34 |
+
parser.add_argument(
|
| 35 |
+
"--max_sequence_length",
|
| 36 |
+
type=int,
|
| 37 |
+
default=512,
|
| 38 |
+
help="Maximum sequence length to use with with the T5 text encoder",
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument(
|
| 41 |
+
"--rank",
|
| 42 |
+
type=int,
|
| 43 |
+
default=4,
|
| 44 |
+
help=("The dimension of the LoRA update matrices."),
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--lora_alpha",
|
| 48 |
+
type=int,
|
| 49 |
+
default=4,
|
| 50 |
+
help="LoRA alpha to be used for additional scaling.",
|
| 51 |
+
)
|
| 52 |
+
parser.add_argument("--lora_dropout", type=float, default=0.0, help="Dropout probability for LoRA layers")
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"--output_dir",
|
| 55 |
+
type=str,
|
| 56 |
+
default="flux-dreambooth-lora",
|
| 57 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 58 |
+
)
|
| 59 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--resolution",
|
| 62 |
+
type=int,
|
| 63 |
+
default=512,
|
| 64 |
+
help=(
|
| 65 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 66 |
+
" resolution"
|
| 67 |
+
),
|
| 68 |
+
)
|
| 69 |
+
parser.add_argument(
|
| 70 |
+
"--aspect_ratio_buckets",
|
| 71 |
+
type=str,
|
| 72 |
+
default=None,
|
| 73 |
+
help=(
|
| 74 |
+
"Aspect ratio buckets to use for training. Define as a string of 'h1,w1;h2,w2;...'. "
|
| 75 |
+
"e.g. '1024,1024;768,1360;1360,768;880,1168;1168,880;1248,832;832,1248'"
|
| 76 |
+
"Images will be resized and cropped to fit the nearest bucket. If provided, --resolution is ignored."
|
| 77 |
+
),
|
| 78 |
+
)
|
| 79 |
+
parser.add_argument(
|
| 80 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 86 |
+
parser.add_argument(
|
| 87 |
+
"--max_train_steps",
|
| 88 |
+
type=int,
|
| 89 |
+
default=None,
|
| 90 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 91 |
+
)
|
| 92 |
+
parser.add_argument(
|
| 93 |
+
"--checkpointing_steps",
|
| 94 |
+
type=int,
|
| 95 |
+
default=500,
|
| 96 |
+
help=(
|
| 97 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 98 |
+
" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
|
| 99 |
+
" training using `--resume_from_checkpoint`."
|
| 100 |
+
),
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--checkpoints_total_limit",
|
| 104 |
+
type=int,
|
| 105 |
+
default=None,
|
| 106 |
+
help=("Max number of checkpoints to store."),
|
| 107 |
+
)
|
| 108 |
+
parser.add_argument(
|
| 109 |
+
"--resume_from_checkpoint",
|
| 110 |
+
type=str,
|
| 111 |
+
default=None,
|
| 112 |
+
help=(
|
| 113 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 114 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 115 |
+
),
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--gradient_accumulation_steps",
|
| 119 |
+
type=int,
|
| 120 |
+
default=1,
|
| 121 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--gradient_checkpointing",
|
| 125 |
+
action="store_true",
|
| 126 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--learning_rate",
|
| 130 |
+
type=float,
|
| 131 |
+
default=1e-4,
|
| 132 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
parser.add_argument(
|
| 136 |
+
"--guidance_scale",
|
| 137 |
+
type=float,
|
| 138 |
+
default=3.5,
|
| 139 |
+
help="the FLUX.1 dev variant is a guidance distilled model",
|
| 140 |
+
)
|
| 141 |
+
parser.add_argument(
|
| 142 |
+
"--lr_scheduler",
|
| 143 |
+
type=str,
|
| 144 |
+
default="constant",
|
| 145 |
+
help=(
|
| 146 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 147 |
+
' "constant", "constant_with_warmup"]'
|
| 148 |
+
),
|
| 149 |
+
)
|
| 150 |
+
parser.add_argument(
|
| 151 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 152 |
+
)
|
| 153 |
+
parser.add_argument(
|
| 154 |
+
"--lr_num_cycles",
|
| 155 |
+
type=int,
|
| 156 |
+
default=1,
|
| 157 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 158 |
+
)
|
| 159 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 160 |
+
parser.add_argument(
|
| 161 |
+
"--dataloader_num_workers",
|
| 162 |
+
type=int,
|
| 163 |
+
default=0,
|
| 164 |
+
help=(
|
| 165 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 166 |
+
),
|
| 167 |
+
)
|
| 168 |
+
parser.add_argument(
|
| 169 |
+
"--weighting_scheme",
|
| 170 |
+
type=str,
|
| 171 |
+
default="none",
|
| 172 |
+
choices=["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"],
|
| 173 |
+
help=('We default to the "none" weighting scheme for uniform sampling and uniform loss'),
|
| 174 |
+
)
|
| 175 |
+
parser.add_argument(
|
| 176 |
+
"--logit_mean", type=float, default=0.0, help="mean to use when using the `'logit_normal'` weighting scheme."
|
| 177 |
+
)
|
| 178 |
+
parser.add_argument(
|
| 179 |
+
"--logit_std", type=float, default=1.0, help="std to use when using the `'logit_normal'` weighting scheme."
|
| 180 |
+
)
|
| 181 |
+
parser.add_argument(
|
| 182 |
+
"--mode_scale",
|
| 183 |
+
type=float,
|
| 184 |
+
default=1.29,
|
| 185 |
+
help="Scale of mode weighting scheme. Only effective when using the `'mode'` as the `weighting_scheme`.",
|
| 186 |
+
)
|
| 187 |
+
parser.add_argument(
|
| 188 |
+
"--optimizer",
|
| 189 |
+
type=str,
|
| 190 |
+
default="AdamW",
|
| 191 |
+
help=('The optimizer type to use. Choose between ["AdamW", "prodigy"]'),
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
parser.add_argument(
|
| 195 |
+
"--use_8bit_adam",
|
| 196 |
+
action="store_true",
|
| 197 |
+
help="Whether or not to use 8-bit Adam from bitsandbytes. Ignored if optimizer is not set to AdamW",
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
parser.add_argument(
|
| 201 |
+
"--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam and Prodigy optimizers."
|
| 202 |
+
)
|
| 203 |
+
parser.add_argument(
|
| 204 |
+
"--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam and Prodigy optimizers."
|
| 205 |
+
)
|
| 206 |
+
parser.add_argument(
|
| 207 |
+
"--prodigy_beta3",
|
| 208 |
+
type=float,
|
| 209 |
+
default=None,
|
| 210 |
+
help="coefficients for computing the Prodigy stepsize using running averages. If set to None, "
|
| 211 |
+
"uses the value of square root of beta2. Ignored if optimizer is adamW",
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument("--prodigy_decouple", type=bool, default=True, help="Use AdamW style decoupled weight decay")
|
| 214 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-04, help="Weight decay to use for unet params")
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--adam_weight_decay_text_encoder", type=float, default=1e-03, help="Weight decay to use for text_encoder"
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
parser.add_argument(
|
| 220 |
+
"--lora_layers",
|
| 221 |
+
type=str,
|
| 222 |
+
default=None,
|
| 223 |
+
help=(
|
| 224 |
+
'The transformer modules to apply LoRA training on. Please specify the layers in a comma separated. E.g. - "to_k,to_q,to_v,to_out.0" will result in lora training of attention layers only'
|
| 225 |
+
),
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
parser.add_argument(
|
| 229 |
+
"--adam_epsilon",
|
| 230 |
+
type=float,
|
| 231 |
+
default=1e-08,
|
| 232 |
+
help="Epsilon value for the Adam optimizer and Prodigy optimizers.",
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
parser.add_argument(
|
| 236 |
+
"--prodigy_use_bias_correction",
|
| 237 |
+
type=bool,
|
| 238 |
+
default=True,
|
| 239 |
+
help="Turn on Adam's bias correction. True by default. Ignored if optimizer is adamW",
|
| 240 |
+
)
|
| 241 |
+
parser.add_argument(
|
| 242 |
+
"--prodigy_safeguard_warmup",
|
| 243 |
+
type=bool,
|
| 244 |
+
default=True,
|
| 245 |
+
help="Remove lr from the denominator of D estimate to avoid issues during warm-up stage. True by default. "
|
| 246 |
+
"Ignored if optimizer is adamW",
|
| 247 |
+
)
|
| 248 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 249 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 250 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 251 |
+
parser.add_argument(
|
| 252 |
+
"--hub_model_id",
|
| 253 |
+
type=str,
|
| 254 |
+
default=None,
|
| 255 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 256 |
+
)
|
| 257 |
+
parser.add_argument(
|
| 258 |
+
"--logging_dir",
|
| 259 |
+
type=str,
|
| 260 |
+
default="logs",
|
| 261 |
+
help=(
|
| 262 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 263 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 264 |
+
),
|
| 265 |
+
)
|
| 266 |
+
parser.add_argument(
|
| 267 |
+
"--allow_tf32",
|
| 268 |
+
action="store_true",
|
| 269 |
+
help=(
|
| 270 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 271 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 272 |
+
),
|
| 273 |
+
)
|
| 274 |
+
parser.add_argument(
|
| 275 |
+
"--report_to",
|
| 276 |
+
type=str,
|
| 277 |
+
default="tensorboard",
|
| 278 |
+
help=(
|
| 279 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 280 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 281 |
+
),
|
| 282 |
+
)
|
| 283 |
+
parser.add_argument(
|
| 284 |
+
"--mixed_precision",
|
| 285 |
+
type=str,
|
| 286 |
+
default=None,
|
| 287 |
+
choices=["no", "fp16", "bf16"],
|
| 288 |
+
help=(
|
| 289 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 290 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 291 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 292 |
+
),
|
| 293 |
+
)
|
| 294 |
+
parser.add_argument(
|
| 295 |
+
"--upcast_before_saving",
|
| 296 |
+
action="store_true",
|
| 297 |
+
default=False,
|
| 298 |
+
help=(
|
| 299 |
+
"Whether to upcast the trained transformer layers to float32 before saving (at the end of training). "
|
| 300 |
+
"Defaults to precision dtype used for training to save memory"
|
| 301 |
+
),
|
| 302 |
+
)
|
| 303 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 304 |
+
|
| 305 |
+
if input_args is not None:
|
| 306 |
+
args = parser.parse_args(input_args)
|
| 307 |
+
else:
|
| 308 |
+
args = parser.parse_args()
|
| 309 |
+
|
| 310 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 311 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 312 |
+
args.local_rank = env_local_rank
|
| 313 |
+
|
| 314 |
+
return args
|
utils/utils.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import threading
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def import_from_transformers_modules(
|
| 10 |
+
pretrained_model_name_or_path, file_name, class_name
|
| 11 |
+
):
|
| 12 |
+
import transformers
|
| 13 |
+
|
| 14 |
+
module_path = transformers.dynamic_module_utils.get_cached_module_file(
|
| 15 |
+
pretrained_model_name_or_path, file_name
|
| 16 |
+
)
|
| 17 |
+
return transformers.dynamic_module_utils.get_class_in_module(
|
| 18 |
+
class_name, module_path
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def deepspeed_zero_init_disabled_context_manager():
|
| 23 |
+
"""
|
| 24 |
+
returns either a context list that includes one that will disable zero.Init or an empty context list
|
| 25 |
+
"""
|
| 26 |
+
import accelerate
|
| 27 |
+
|
| 28 |
+
deepspeed_plugin = (
|
| 29 |
+
accelerate.state.AcceleratorState().deepspeed_plugin
|
| 30 |
+
if accelerate.state.is_initialized()
|
| 31 |
+
else None
|
| 32 |
+
)
|
| 33 |
+
if deepspeed_plugin is None:
|
| 34 |
+
return []
|
| 35 |
+
|
| 36 |
+
return [deepspeed_plugin.zero3_init_context_manager(enable=False)]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def remove_excess_checkpoints(
|
| 40 |
+
save_directory,
|
| 41 |
+
checkpoints_total_limit: int = None,
|
| 42 |
+
checkpoint_prefix="checkpoint",
|
| 43 |
+
is_main_process: bool = True,
|
| 44 |
+
):
|
| 45 |
+
# _after_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 46 |
+
if is_main_process and checkpoints_total_limit is not None:
|
| 47 |
+
checkpoints = os.listdir(save_directory)
|
| 48 |
+
checkpoints = [d for d in checkpoints if d.startswith(checkpoint_prefix)]
|
| 49 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[2]))
|
| 50 |
+
|
| 51 |
+
# _after_ we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit` checkpoints
|
| 52 |
+
if len(checkpoints) > checkpoints_total_limit:
|
| 53 |
+
num_to_remove = len(checkpoints) - checkpoints_total_limit
|
| 54 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 55 |
+
|
| 56 |
+
print(
|
| 57 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 58 |
+
)
|
| 59 |
+
print(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 60 |
+
|
| 61 |
+
for removing_checkpoint in removing_checkpoints:
|
| 62 |
+
removing_checkpoint = os.path.join(save_directory, removing_checkpoint)
|
| 63 |
+
shutil.rmtree(removing_checkpoint)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def is_distributed_training():
|
| 67 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
| 68 |
+
return True
|
| 69 |
+
world_size = int(os.environ.get("WORLD_SIZE", 1))
|
| 70 |
+
return world_size > 1
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def contain_invalid_grad(optimizer):
|
| 74 |
+
invalid_grad = False
|
| 75 |
+
for param_group in optimizer.param_groups:
|
| 76 |
+
for param in param_group["params"]:
|
| 77 |
+
if param.grad is not None:
|
| 78 |
+
invalid_grad = invalid_grad or (
|
| 79 |
+
torch.isnan(param.grad).any()
|
| 80 |
+
or torch.isinf(param.grad).any()
|
| 81 |
+
or torch.isneginf(param.grad).any()
|
| 82 |
+
)
|
| 83 |
+
if is_distributed_training():
|
| 84 |
+
invalid_grad_flag = torch.tensor(
|
| 85 |
+
[1.0 if invalid_grad else 0.0],
|
| 86 |
+
dtype=torch.float32,
|
| 87 |
+
requires_grad=False,
|
| 88 |
+
).cuda()
|
| 89 |
+
torch.distributed.all_reduce(
|
| 90 |
+
invalid_grad_flag, op=torch.distributed.ReduceOp.MAX
|
| 91 |
+
)
|
| 92 |
+
invalid_grad = invalid_grad_flag.item() > 0
|
| 93 |
+
return invalid_grad
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def patch_npu_record_stream():
|
| 97 |
+
torch.utils.rename_privateuse1_backend("npu")
|
| 98 |
+
record_stream = torch.Tensor.record_stream
|
| 99 |
+
|
| 100 |
+
def _func(*args, **kwargs):
|
| 101 |
+
ret = record_stream(*args, **kwargs)
|
| 102 |
+
torch.cuda.synchronize()
|
| 103 |
+
return ret
|
| 104 |
+
|
| 105 |
+
torch.Tensor.record_stream = _func
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def patch_npu_diffusers_get_1d_rotary_pos_embed():
|
| 109 |
+
from typing import Union
|
| 110 |
+
import numpy as np
|
| 111 |
+
import diffusers
|
| 112 |
+
|
| 113 |
+
def __get_1d_rotary_pos_embed(
|
| 114 |
+
dim: int,
|
| 115 |
+
pos: Union[np.ndarray, int],
|
| 116 |
+
theta: float = 10000.0,
|
| 117 |
+
use_real=False,
|
| 118 |
+
linear_factor=1.0,
|
| 119 |
+
ntk_factor=1.0,
|
| 120 |
+
repeat_interleave_real=True,
|
| 121 |
+
freqs_dtype=torch.float32, # torch.float32, torch.float64 (flux)
|
| 122 |
+
):
|
| 123 |
+
assert dim % 2 == 0
|
| 124 |
+
|
| 125 |
+
if isinstance(pos, int):
|
| 126 |
+
pos = torch.arange(pos)
|
| 127 |
+
if isinstance(pos, np.ndarray):
|
| 128 |
+
pos = torch.from_numpy(pos) # type: ignore # [S]
|
| 129 |
+
|
| 130 |
+
theta = theta * ntk_factor
|
| 131 |
+
freqs = (
|
| 132 |
+
1.0
|
| 133 |
+
/ (
|
| 134 |
+
theta
|
| 135 |
+
** (
|
| 136 |
+
torch.arange(0, dim, 2, dtype=freqs_dtype, device=pos.device)[
|
| 137 |
+
: (dim // 2)
|
| 138 |
+
]
|
| 139 |
+
/ dim
|
| 140 |
+
)
|
| 141 |
+
)
|
| 142 |
+
/ linear_factor
|
| 143 |
+
) # [D/2]
|
| 144 |
+
freqs = torch.outer(pos, freqs) # type: ignore # [S, D/2]
|
| 145 |
+
if use_real and repeat_interleave_real:
|
| 146 |
+
# flux, hunyuan-dit, cogvideox
|
| 147 |
+
freqs_cos = (
|
| 148 |
+
freqs.cos().float().repeat_interleave(2, dim=1).float()
|
| 149 |
+
) # [S, D]
|
| 150 |
+
freqs_sin = (
|
| 151 |
+
freqs.sin().float().repeat_interleave(2, dim=1).float()
|
| 152 |
+
) # [S, D]
|
| 153 |
+
return freqs_cos, freqs_sin
|
| 154 |
+
elif use_real:
|
| 155 |
+
# stable audio
|
| 156 |
+
freqs_cos = torch.cat([freqs.cos(), freqs.cos()], dim=-1).float() # [S, D]
|
| 157 |
+
freqs_sin = torch.cat([freqs.sin(), freqs.sin()], dim=-1).float() # [S, D]
|
| 158 |
+
return freqs_cos, freqs_sin
|
| 159 |
+
else:
|
| 160 |
+
# lumina
|
| 161 |
+
freqs_cis = torch.polar(
|
| 162 |
+
torch.ones_like(freqs), freqs
|
| 163 |
+
) # complex64 # [S, D/2]
|
| 164 |
+
return freqs_cis
|
| 165 |
+
|
| 166 |
+
diffusers.models.embeddings.get_1d_rotary_pos_embed = __get_1d_rotary_pos_embed
|
utils/vprocess.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import copy
|
| 3 |
+
import logging
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import time
|
| 8 |
+
import warnings
|
| 9 |
+
from functools import lru_cache
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
from typing import Optional, Union, Tuple, List, Any, Dict
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 13 |
+
|
| 14 |
+
import requests
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision
|
| 17 |
+
from packaging import version
|
| 18 |
+
from PIL import Image
|
| 19 |
+
import numpy as np
|
| 20 |
+
from torchvision import io, transforms
|
| 21 |
+
from torchvision.transforms import InterpolationMode
|
| 22 |
+
|
| 23 |
+
PREFERRED_KONTEXT_RESOLUTIONS = [
|
| 24 |
+
(672, 1568),
|
| 25 |
+
(688, 1504),
|
| 26 |
+
(720, 1456),
|
| 27 |
+
(752, 1392),
|
| 28 |
+
(800, 1328),
|
| 29 |
+
(832, 1248),
|
| 30 |
+
(880, 1184),
|
| 31 |
+
(944, 1104),
|
| 32 |
+
(1024, 1024),
|
| 33 |
+
(1104, 944),
|
| 34 |
+
(1184, 880),
|
| 35 |
+
(1248, 832),
|
| 36 |
+
(1328, 800),
|
| 37 |
+
(1392, 752),
|
| 38 |
+
(1456, 720),
|
| 39 |
+
(1504, 688),
|
| 40 |
+
(1568, 672),
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
def resizeinput(img):
|
| 44 |
+
multiple_of = 16
|
| 45 |
+
image_height, image_width = img.height, img.width
|
| 46 |
+
aspect_ratio = image_width / image_height
|
| 47 |
+
_, image_width, image_height = min(
|
| 48 |
+
(abs(aspect_ratio - w / h), w, h) for w, h in PREFERRED_KONTEXT_RESOLUTIONS
|
| 49 |
+
)
|
| 50 |
+
image_width = image_width // multiple_of * multiple_of
|
| 51 |
+
image_height = image_height // multiple_of * multiple_of
|
| 52 |
+
img = img.resize((image_width, image_height), Image.LANCZOS)
|
| 53 |
+
return img
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
MAX_RATIO = 200
|
| 57 |
+
SPATIAL_MERGE_SIZE = 2
|
| 58 |
+
IMAGE_MIN_TOKEN_NUM = 4
|
| 59 |
+
IMAGE_MAX_TOKEN_NUM = 16384
|
| 60 |
+
VIDEO_MIN_TOKEN_NUM = 128
|
| 61 |
+
VIDEO_MAX_TOKEN_NUM = 768
|
| 62 |
+
|
| 63 |
+
FPS = 2.0
|
| 64 |
+
FRAME_FACTOR = 2
|
| 65 |
+
FPS_MIN_FRAMES = 4
|
| 66 |
+
FPS_MAX_FRAMES = 768
|
| 67 |
+
MAX_NUM_WORKERS_FETCH_VIDEO = 8
|
| 68 |
+
|
| 69 |
+
MODEL_SEQ_LEN = int(float(os.environ.get('MODEL_SEQ_LEN', 128000)))
|
| 70 |
+
logger = logging.getLogger(__name__)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def round_by_factor(number: int, factor: int) -> int:
|
| 74 |
+
"""Returns the closest integer to 'number' that is divisible by 'factor'."""
|
| 75 |
+
return round(number / factor) * factor
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def ceil_by_factor(number: int, factor: int) -> int:
|
| 79 |
+
"""Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'."""
|
| 80 |
+
return math.ceil(number / factor) * factor
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def floor_by_factor(number: int, factor: int) -> int:
|
| 84 |
+
"""Returns the largest integer less than or equal to 'number' that is divisible by 'factor'."""
|
| 85 |
+
return math.floor(number / factor) * factor
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def smart_resize(height: int, width: int, factor: int, min_pixels: Optional[int] = None, max_pixels: Optional[int] = None) -> Tuple[int, int]:
|
| 89 |
+
"""
|
| 90 |
+
Rescales the image so that the following conditions are met:
|
| 91 |
+
|
| 92 |
+
1. Both dimensions (height and width) are divisible by 'factor'.
|
| 93 |
+
2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
|
| 94 |
+
3. The aspect ratio of the image is maintained as closely as possible.
|
| 95 |
+
"""
|
| 96 |
+
max_pixels = max_pixels if max_pixels is not None else (IMAGE_MAX_TOKEN_NUM * factor ** 2)
|
| 97 |
+
min_pixels = min_pixels if min_pixels is not None else (IMAGE_MIN_TOKEN_NUM * factor ** 2)
|
| 98 |
+
assert max_pixels >= min_pixels, "The max_pixels of image must be greater than or equal to min_pixels."
|
| 99 |
+
if max(height, width) / min(height, width) > MAX_RATIO:
|
| 100 |
+
raise ValueError(
|
| 101 |
+
f"absolute aspect ratio must be smaller than {MAX_RATIO}, got {max(height, width) / min(height, width)}"
|
| 102 |
+
)
|
| 103 |
+
h_bar = max(factor, round_by_factor(height, factor))
|
| 104 |
+
w_bar = max(factor, round_by_factor(width, factor))
|
| 105 |
+
if h_bar * w_bar > max_pixels:
|
| 106 |
+
beta = math.sqrt((height * width) / max_pixels)
|
| 107 |
+
h_bar = floor_by_factor(height / beta, factor)
|
| 108 |
+
w_bar = floor_by_factor(width / beta, factor)
|
| 109 |
+
elif h_bar * w_bar < min_pixels:
|
| 110 |
+
beta = math.sqrt(min_pixels / (height * width))
|
| 111 |
+
h_bar = ceil_by_factor(height * beta, factor)
|
| 112 |
+
w_bar = ceil_by_factor(width * beta, factor)
|
| 113 |
+
return h_bar, w_bar
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def to_rgb(pil_image: Image.Image) -> Image.Image:
|
| 117 |
+
if pil_image.mode == 'RGBA':
|
| 118 |
+
white_background = Image.new("RGB", pil_image.size, (255, 255, 255))
|
| 119 |
+
white_background.paste(pil_image, mask=pil_image.split()[3]) # Use alpha channel as mask
|
| 120 |
+
return white_background
|
| 121 |
+
else:
|
| 122 |
+
return pil_image.convert("RGB")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def fetch_image(ele: Dict[str, Union[str, Image.Image]], image_patch_size: int = 14) -> Image.Image:
|
| 126 |
+
if "image" in ele:
|
| 127 |
+
image = ele["image"]
|
| 128 |
+
else:
|
| 129 |
+
image = ele["image_url"]
|
| 130 |
+
|
| 131 |
+
image_obj = None
|
| 132 |
+
patch_factor = int(image_patch_size * SPATIAL_MERGE_SIZE)
|
| 133 |
+
if isinstance(image, Image.Image):
|
| 134 |
+
image_obj = image
|
| 135 |
+
elif image.startswith("http://") or image.startswith("https://"):
|
| 136 |
+
with requests.get(image, stream=True) as response:
|
| 137 |
+
response.raise_for_status()
|
| 138 |
+
with BytesIO(response.content) as bio:
|
| 139 |
+
image_obj = copy.deepcopy(Image.open(bio))
|
| 140 |
+
elif image.startswith("file://"):
|
| 141 |
+
image_obj = Image.open(image[7:])
|
| 142 |
+
elif image.startswith("data:image"):
|
| 143 |
+
if "base64," in image:
|
| 144 |
+
_, base64_data = image.split("base64,", 1)
|
| 145 |
+
data = base64.b64decode(base64_data)
|
| 146 |
+
with BytesIO(data) as bio:
|
| 147 |
+
image_obj = copy.deepcopy(Image.open(bio))
|
| 148 |
+
else:
|
| 149 |
+
image_obj = Image.open(image)
|
| 150 |
+
if image_obj is None:
|
| 151 |
+
raise ValueError(f"Unrecognized image input, support local path, http url, base64 and PIL.Image, got {image}")
|
| 152 |
+
image = to_rgb(image_obj)
|
| 153 |
+
|
| 154 |
+
## resize
|
| 155 |
+
image = resizeinput(image)
|
| 156 |
+
# if "resized_height" in ele and "resized_width" in ele:
|
| 157 |
+
# resized_height, resized_width = smart_resize(
|
| 158 |
+
# ele["resized_height"],
|
| 159 |
+
# ele["resized_width"],
|
| 160 |
+
# factor=patch_factor,
|
| 161 |
+
# )
|
| 162 |
+
# else:
|
| 163 |
+
# width, height = image.size
|
| 164 |
+
# min_pixels = ele.get("min_pixels", IMAGE_MIN_TOKEN_NUM * patch_factor ** 2)
|
| 165 |
+
# max_pixels = ele.get("max_pixels", IMAGE_MAX_TOKEN_NUM * patch_factor ** 2)
|
| 166 |
+
# resized_height, resized_width = smart_resize(
|
| 167 |
+
# height,
|
| 168 |
+
# width,
|
| 169 |
+
# factor=patch_factor,
|
| 170 |
+
# min_pixels=min_pixels,
|
| 171 |
+
# max_pixels=max_pixels,
|
| 172 |
+
# )
|
| 173 |
+
# print(f"resized_height: {resized_height}, resized_width: {resized_width}")
|
| 174 |
+
# image = image.resize((resized_width, resized_height))
|
| 175 |
+
return image
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def smart_nframes(
|
| 179 |
+
ele: Dict[str, Any],
|
| 180 |
+
total_frames: int,
|
| 181 |
+
video_fps: Union[int, float],
|
| 182 |
+
) -> int:
|
| 183 |
+
"""calculate the number of frames for video used for model inputs.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
ele (dict): a dict contains the configuration of video.
|
| 187 |
+
support either `fps` or `nframes`:
|
| 188 |
+
- nframes: the number of frames to extract for model inputs.
|
| 189 |
+
- fps: the fps to extract frames for model inputs.
|
| 190 |
+
- min_frames: the minimum number of frames of the video, only used when fps is provided.
|
| 191 |
+
- max_frames: the maximum number of frames of the video, only used when fps is provided.
|
| 192 |
+
total_frames (int): the original total number of frames of the video.
|
| 193 |
+
video_fps (int | float): the original fps of the video.
|
| 194 |
+
|
| 195 |
+
Raises:
|
| 196 |
+
ValueError: nframes should in interval [FRAME_FACTOR, total_frames].
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
int: the number of frames for video used for model inputs.
|
| 200 |
+
"""
|
| 201 |
+
assert not ("fps" in ele and "nframes" in ele), "Only accept either `fps` or `nframes`"
|
| 202 |
+
if "nframes" in ele:
|
| 203 |
+
nframes = round_by_factor(ele["nframes"], FRAME_FACTOR)
|
| 204 |
+
else:
|
| 205 |
+
fps = ele.get("fps", FPS)
|
| 206 |
+
min_frames = ceil_by_factor(ele.get("min_frames", FPS_MIN_FRAMES), FRAME_FACTOR)
|
| 207 |
+
max_frames = floor_by_factor(ele.get("max_frames", min(FPS_MAX_FRAMES, total_frames)), FRAME_FACTOR)
|
| 208 |
+
nframes = total_frames / video_fps * fps
|
| 209 |
+
if nframes > total_frames:
|
| 210 |
+
logger.warning(f"smart_nframes: nframes[{nframes}] > total_frames[{total_frames}]")
|
| 211 |
+
nframes = min(min(max(nframes, min_frames), max_frames), total_frames)
|
| 212 |
+
nframes = floor_by_factor(nframes, FRAME_FACTOR)
|
| 213 |
+
if not (FRAME_FACTOR <= nframes and nframes <= total_frames):
|
| 214 |
+
raise ValueError(f"nframes should in interval [{FRAME_FACTOR}, {total_frames}], but got {nframes}.")
|
| 215 |
+
return nframes
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _read_video_torchvision(
|
| 219 |
+
ele: Dict[str, Any],
|
| 220 |
+
) -> Tuple[torch.Tensor, float]:
|
| 221 |
+
"""read video using torchvision.io.read_video
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
ele (dict): a dict contains the configuration of video.
|
| 225 |
+
support keys:
|
| 226 |
+
- video: the path of video. support "file://", "http://", "https://" and local path.
|
| 227 |
+
- video_start: the start time of video.
|
| 228 |
+
- video_end: the end time of video.
|
| 229 |
+
Returns:
|
| 230 |
+
torch.Tensor: the video tensor with shape (T, C, H, W).
|
| 231 |
+
"""
|
| 232 |
+
video_path = ele["video"]
|
| 233 |
+
if version.parse(torchvision.__version__) < version.parse("0.19.0"):
|
| 234 |
+
if "http://" in video_path or "https://" in video_path:
|
| 235 |
+
warnings.warn("torchvision < 0.19.0 does not support http/https video path, please upgrade to 0.19.0.")
|
| 236 |
+
if "file://" in video_path:
|
| 237 |
+
video_path = video_path[7:]
|
| 238 |
+
st = time.time()
|
| 239 |
+
video, audio, info = io.read_video(
|
| 240 |
+
video_path,
|
| 241 |
+
start_pts=ele.get("video_start", 0.0),
|
| 242 |
+
end_pts=ele.get("video_end", None),
|
| 243 |
+
pts_unit="sec",
|
| 244 |
+
output_format="TCHW",
|
| 245 |
+
)
|
| 246 |
+
total_frames, video_fps = video.size(0), info["video_fps"]
|
| 247 |
+
logger.info(f"torchvision: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
|
| 248 |
+
nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
|
| 249 |
+
idx = torch.linspace(0, total_frames - 1, nframes).round().long()
|
| 250 |
+
sample_fps = nframes / max(total_frames, 1e-6) * video_fps
|
| 251 |
+
video = video[idx]
|
| 252 |
+
|
| 253 |
+
video_metadata = dict(
|
| 254 |
+
fps=video_fps,
|
| 255 |
+
frames_indices=idx,
|
| 256 |
+
total_num_frames=total_frames,
|
| 257 |
+
video_backend="torchvision",
|
| 258 |
+
)
|
| 259 |
+
return video, video_metadata, sample_fps
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def is_decord_available() -> bool:
|
| 263 |
+
import importlib.util
|
| 264 |
+
|
| 265 |
+
return importlib.util.find_spec("decord") is not None
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def calculate_video_frame_range(
|
| 269 |
+
ele: Dict[str, Any],
|
| 270 |
+
total_frames: int,
|
| 271 |
+
video_fps: float,
|
| 272 |
+
) -> Tuple[int, int, int]:
|
| 273 |
+
"""
|
| 274 |
+
Calculate the start and end frame indices based on the given time range.
|
| 275 |
+
|
| 276 |
+
Args:
|
| 277 |
+
ele (dict): A dictionary containing optional 'video_start' and 'video_end' keys (in seconds).
|
| 278 |
+
total_frames (int): Total number of frames in the video.
|
| 279 |
+
video_fps (float): Frames per second of the video.
|
| 280 |
+
|
| 281 |
+
Returns:
|
| 282 |
+
tuple: A tuple containing (start_frame, end_frame, frame_count).
|
| 283 |
+
|
| 284 |
+
Raises:
|
| 285 |
+
ValueError: If input parameters are invalid or the time range is inconsistent.
|
| 286 |
+
"""
|
| 287 |
+
# Validate essential parameters
|
| 288 |
+
if video_fps <= 0:
|
| 289 |
+
raise ValueError("video_fps must be a positive number")
|
| 290 |
+
if total_frames <= 0:
|
| 291 |
+
raise ValueError("total_frames must be a positive integer")
|
| 292 |
+
|
| 293 |
+
# Get start and end time in seconds
|
| 294 |
+
video_start = ele.get("video_start", None)
|
| 295 |
+
video_end = ele.get("video_end", None)
|
| 296 |
+
if video_start is None and video_end is None:
|
| 297 |
+
return 0, total_frames - 1, total_frames
|
| 298 |
+
|
| 299 |
+
max_duration = total_frames / video_fps
|
| 300 |
+
# Process start frame
|
| 301 |
+
if video_start is not None:
|
| 302 |
+
video_start_clamped = max(0.0, min(video_start, max_duration))
|
| 303 |
+
start_frame = math.ceil(video_start_clamped * video_fps)
|
| 304 |
+
else:
|
| 305 |
+
start_frame = 0
|
| 306 |
+
# Process end frame
|
| 307 |
+
if video_end is not None:
|
| 308 |
+
video_end_clamped = max(0.0, min(video_end, max_duration))
|
| 309 |
+
end_frame = math.floor(video_end_clamped * video_fps)
|
| 310 |
+
end_frame = min(end_frame, total_frames - 1)
|
| 311 |
+
else:
|
| 312 |
+
end_frame = total_frames - 1
|
| 313 |
+
|
| 314 |
+
# Validate frame order
|
| 315 |
+
if start_frame >= end_frame:
|
| 316 |
+
raise ValueError(
|
| 317 |
+
f"Invalid time range: Start frame {start_frame} (at {video_start_clamped if video_start is not None else 0}s) "
|
| 318 |
+
f"exceeds end frame {end_frame} (at {video_end_clamped if video_end is not None else max_duration}s). "
|
| 319 |
+
f"Video duration: {max_duration:.2f}s ({total_frames} frames @ {video_fps}fps)"
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
logger.info(f"calculate video frame range: {start_frame=}, {end_frame=}, {total_frames=} from {video_start=}, {video_end=}, {video_fps=:.3f}")
|
| 323 |
+
return start_frame, end_frame, end_frame - start_frame + 1
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _read_video_decord(
|
| 327 |
+
ele: Dict[str, Any],
|
| 328 |
+
) -> Tuple[torch.Tensor, float]:
|
| 329 |
+
"""read video using decord.VideoReader
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
ele (dict): a dict contains the configuration of video.
|
| 333 |
+
support keys:
|
| 334 |
+
- video: the path of video. support "file://", "http://", "https://" and local path.
|
| 335 |
+
- video_start: the start time of video.
|
| 336 |
+
- video_end: the end time of video.
|
| 337 |
+
Returns:
|
| 338 |
+
torch.Tensor: the video tensor with shape (T, C, H, W).
|
| 339 |
+
"""
|
| 340 |
+
import decord
|
| 341 |
+
video_path = ele["video"]
|
| 342 |
+
st = time.time()
|
| 343 |
+
vr = decord.VideoReader(video_path)
|
| 344 |
+
total_frames, video_fps = len(vr), vr.get_avg_fps()
|
| 345 |
+
start_frame, end_frame, total_frames = calculate_video_frame_range(
|
| 346 |
+
ele,
|
| 347 |
+
total_frames,
|
| 348 |
+
video_fps,
|
| 349 |
+
)
|
| 350 |
+
nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
|
| 351 |
+
idx = torch.linspace(start_frame, end_frame, nframes).round().long().tolist()
|
| 352 |
+
video = vr.get_batch(idx).asnumpy()
|
| 353 |
+
video = torch.tensor(video).permute(0, 3, 1, 2) # Convert to TCHW format
|
| 354 |
+
logger.info(f"decord: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
|
| 355 |
+
sample_fps = nframes / max(total_frames, 1e-6) * video_fps
|
| 356 |
+
|
| 357 |
+
video_metadata = dict(
|
| 358 |
+
fps=video_fps,
|
| 359 |
+
frames_indices=idx,
|
| 360 |
+
total_num_frames=total_frames,
|
| 361 |
+
video_backend="decord",
|
| 362 |
+
)
|
| 363 |
+
return video, video_metadata, sample_fps
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def is_torchcodec_available() -> bool:
|
| 367 |
+
import importlib.util
|
| 368 |
+
|
| 369 |
+
return importlib.util.find_spec("torchcodec") is not None
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _read_video_torchcodec(
|
| 373 |
+
ele: Dict[str, Any],
|
| 374 |
+
) -> Tuple[torch.Tensor, float]:
|
| 375 |
+
"""read video using torchcodec.decoders.VideoDecoder
|
| 376 |
+
|
| 377 |
+
Args:
|
| 378 |
+
ele (dict): a dict contains the configuration of video.
|
| 379 |
+
support keys:
|
| 380 |
+
- video: the path of video. support "file://", "http://", "https://" and local path.
|
| 381 |
+
- video_start: the start time of video.
|
| 382 |
+
- video_end: the end time of video.
|
| 383 |
+
Returns:
|
| 384 |
+
torch.Tensor: the video tensor with shape (T, C, H, W).
|
| 385 |
+
"""
|
| 386 |
+
from torchcodec.decoders import VideoDecoder
|
| 387 |
+
TORCHCODEC_NUM_THREADS = int(os.environ.get('TORCHCODEC_NUM_THREADS', 8))
|
| 388 |
+
logger.info(f"set TORCHCODEC_NUM_THREADS: {TORCHCODEC_NUM_THREADS}")
|
| 389 |
+
video_path = ele["video"]
|
| 390 |
+
st = time.time()
|
| 391 |
+
decoder = VideoDecoder(video_path, num_ffmpeg_threads=TORCHCODEC_NUM_THREADS)
|
| 392 |
+
video_fps = decoder.metadata.average_fps
|
| 393 |
+
total_frames = decoder.metadata.num_frames
|
| 394 |
+
start_frame, end_frame, total_frames = calculate_video_frame_range(
|
| 395 |
+
ele,
|
| 396 |
+
total_frames,
|
| 397 |
+
video_fps,
|
| 398 |
+
)
|
| 399 |
+
nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
|
| 400 |
+
idx = torch.linspace(start_frame, end_frame, nframes).round().long().tolist()
|
| 401 |
+
sample_fps = nframes / max(total_frames, 1e-6) * video_fps
|
| 402 |
+
video = decoder.get_frames_at(indices=idx).data
|
| 403 |
+
logger.info(f"torchcodec: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
|
| 404 |
+
|
| 405 |
+
video_metadata = dict(
|
| 406 |
+
fps=video_fps,
|
| 407 |
+
frames_indices=idx,
|
| 408 |
+
total_num_frames=total_frames,
|
| 409 |
+
video_backend="torchcodec",
|
| 410 |
+
)
|
| 411 |
+
return video, video_metadata, sample_fps
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
VIDEO_READER_BACKENDS = {
|
| 415 |
+
"decord": _read_video_decord,
|
| 416 |
+
"torchvision": _read_video_torchvision,
|
| 417 |
+
"torchcodec": _read_video_torchcodec,
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
FORCE_QWENVL_VIDEO_READER = os.getenv("FORCE_QWENVL_VIDEO_READER", None)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
@lru_cache(maxsize=1)
|
| 424 |
+
def get_video_reader_backend() -> str:
|
| 425 |
+
if FORCE_QWENVL_VIDEO_READER is not None:
|
| 426 |
+
video_reader_backend = FORCE_QWENVL_VIDEO_READER
|
| 427 |
+
elif is_torchcodec_available():
|
| 428 |
+
video_reader_backend = "torchcodec"
|
| 429 |
+
elif is_decord_available():
|
| 430 |
+
video_reader_backend = "decord"
|
| 431 |
+
else:
|
| 432 |
+
video_reader_backend = "torchvision"
|
| 433 |
+
print(f"qwen-vl-utils using {video_reader_backend} to read video.", file=sys.stderr)
|
| 434 |
+
return video_reader_backend
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def fetch_video(ele: Dict[str, Any], image_patch_size: int = 14, return_video_sample_fps: bool = False,
|
| 438 |
+
return_video_metadata: bool = False) -> Union[torch.Tensor, List[Image.Image]]:
|
| 439 |
+
image_factor = image_patch_size * SPATIAL_MERGE_SIZE
|
| 440 |
+
VIDEO_FRAME_MIN_PIXELS = VIDEO_MIN_TOKEN_NUM * image_factor * image_factor
|
| 441 |
+
VIDEO_FRAME_MAX_PIXELS = VIDEO_MAX_TOKEN_NUM * image_factor * image_factor
|
| 442 |
+
if isinstance(ele["video"], str):
|
| 443 |
+
video_reader_backend = get_video_reader_backend()
|
| 444 |
+
try:
|
| 445 |
+
video, video_metadata, sample_fps = VIDEO_READER_BACKENDS[video_reader_backend](ele)
|
| 446 |
+
except Exception as e:
|
| 447 |
+
logger.warning(f"video_reader_backend {video_reader_backend} error, use torchvision as default, msg: {e}")
|
| 448 |
+
video, video_metadata, sample_fps = VIDEO_READER_BACKENDS["torchvision"](ele)
|
| 449 |
+
else:
|
| 450 |
+
# The input is a list of frames
|
| 451 |
+
assert isinstance(ele["video"], (list, tuple))
|
| 452 |
+
process_info = ele.copy()
|
| 453 |
+
process_info.pop("type", None)
|
| 454 |
+
process_info.pop("video", None)
|
| 455 |
+
# use ThreadPoolExecutor to parallel process frames
|
| 456 |
+
max_workers = min(MAX_NUM_WORKERS_FETCH_VIDEO, len(ele["video"]))
|
| 457 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 458 |
+
futures = [
|
| 459 |
+
executor.submit(fetch_image, {"image": video_element, **process_info}, image_factor)
|
| 460 |
+
for video_element in ele["video"]
|
| 461 |
+
]
|
| 462 |
+
image_list = [future.result() for future in futures]
|
| 463 |
+
|
| 464 |
+
nframes = ceil_by_factor(len(image_list), FRAME_FACTOR)
|
| 465 |
+
if len(image_list) < nframes:
|
| 466 |
+
image_list.extend([image_list[-1]] * (nframes - len(image_list)))
|
| 467 |
+
|
| 468 |
+
sample_fps = ele.get("sample_fps", 2.0)
|
| 469 |
+
video = torch.stack([
|
| 470 |
+
torch.from_numpy(np.array(image).transpose(2, 0, 1))
|
| 471 |
+
for image in image_list
|
| 472 |
+
])
|
| 473 |
+
|
| 474 |
+
# fake video metadata
|
| 475 |
+
raw_fps = process_info.pop("raw_fps", sample_fps)
|
| 476 |
+
video_metadata = dict(
|
| 477 |
+
fps=raw_fps,
|
| 478 |
+
frames_indices=[i for i in range(len(video))],
|
| 479 |
+
total_num_frames=(nframes / sample_fps) * raw_fps,
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
nframes, _, height, width = video.shape
|
| 483 |
+
min_pixels = ele.get("min_pixels", VIDEO_FRAME_MIN_PIXELS)
|
| 484 |
+
total_pixels = ele.get("total_pixels", MODEL_SEQ_LEN * image_factor * image_factor * 0.9)
|
| 485 |
+
max_pixels = max(min(VIDEO_FRAME_MAX_PIXELS, total_pixels / nframes * FRAME_FACTOR), int(min_pixels * 1.05))
|
| 486 |
+
max_pixels_supposed = ele.get("max_pixels", max_pixels)
|
| 487 |
+
if max_pixels_supposed > max_pixels:
|
| 488 |
+
logger.warning(f"The given max_pixels[{max_pixels_supposed}] exceeds limit[{max_pixels}].")
|
| 489 |
+
max_pixels = min(max_pixels_supposed, max_pixels)
|
| 490 |
+
if "resized_height" in ele and "resized_width" in ele:
|
| 491 |
+
resized_height, resized_width = smart_resize(
|
| 492 |
+
ele["resized_height"],
|
| 493 |
+
ele["resized_width"],
|
| 494 |
+
factor=image_factor,
|
| 495 |
+
)
|
| 496 |
+
else:
|
| 497 |
+
resized_height, resized_width = smart_resize(
|
| 498 |
+
height,
|
| 499 |
+
width,
|
| 500 |
+
factor=image_factor,
|
| 501 |
+
min_pixels=min_pixels,
|
| 502 |
+
max_pixels=max_pixels,
|
| 503 |
+
)
|
| 504 |
+
video = transforms.functional.resize(
|
| 505 |
+
video,
|
| 506 |
+
[resized_height, resized_width],
|
| 507 |
+
interpolation=InterpolationMode.BICUBIC,
|
| 508 |
+
antialias=True,
|
| 509 |
+
).float()
|
| 510 |
+
|
| 511 |
+
final_video = (video, video_metadata) if return_video_metadata else video
|
| 512 |
+
if return_video_sample_fps:
|
| 513 |
+
return final_video, sample_fps
|
| 514 |
+
return final_video
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def extract_vision_info(conversations: Union[List[Dict[str, Any]], List[List[Dict[str, Any]]]]) -> List[Dict[str, Any]]:
|
| 518 |
+
vision_infos = []
|
| 519 |
+
if isinstance(conversations[0], dict):
|
| 520 |
+
conversations = [conversations]
|
| 521 |
+
for conversation in conversations:
|
| 522 |
+
for message in conversation:
|
| 523 |
+
if isinstance(message["content"], list):
|
| 524 |
+
for ele in message["content"]:
|
| 525 |
+
if (
|
| 526 |
+
"image" in ele
|
| 527 |
+
or "image_url" in ele
|
| 528 |
+
or "video" in ele
|
| 529 |
+
or ele.get("type", "text") in ("image", "image_url", "video")
|
| 530 |
+
):
|
| 531 |
+
vision_infos.append(ele)
|
| 532 |
+
return vision_infos
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def process_vision_info(
|
| 536 |
+
conversations: Union[List[Dict[str, Any]], List[List[Dict[str, Any]]]],
|
| 537 |
+
return_video_kwargs: bool = False,
|
| 538 |
+
return_video_metadata: bool = False,
|
| 539 |
+
image_patch_size: int = 14,
|
| 540 |
+
) -> Tuple[Optional[List[Image.Image]], Optional[List[Union[torch.Tensor, List[Image.Image]]]], Optional[Dict[str, Any]]]:
|
| 541 |
+
|
| 542 |
+
vision_infos = extract_vision_info(conversations)
|
| 543 |
+
## Read images or videos
|
| 544 |
+
image_inputs = []
|
| 545 |
+
video_inputs = []
|
| 546 |
+
video_sample_fps_list = []
|
| 547 |
+
for vision_info in vision_infos:
|
| 548 |
+
if "image" in vision_info or "image_url" in vision_info:
|
| 549 |
+
image_inputs.append(fetch_image(vision_info, image_patch_size=image_patch_size))
|
| 550 |
+
elif "video" in vision_info:
|
| 551 |
+
video_input, video_sample_fps = fetch_video(vision_info, return_video_sample_fps=True,
|
| 552 |
+
image_patch_size=image_patch_size, return_video_metadata=return_video_metadata)
|
| 553 |
+
video_sample_fps_list.append(video_sample_fps)
|
| 554 |
+
video_inputs.append(video_input)
|
| 555 |
+
else:
|
| 556 |
+
raise ValueError("image, image_url or video should in content.")
|
| 557 |
+
if len(image_inputs) == 0:
|
| 558 |
+
image_inputs = None
|
| 559 |
+
if len(video_inputs) == 0:
|
| 560 |
+
video_inputs = None
|
| 561 |
+
|
| 562 |
+
video_kwargs = {'do_sample_frames': False}
|
| 563 |
+
if not return_video_metadata: # BC for qwen2.5vl
|
| 564 |
+
video_kwargs.update({'fps': video_sample_fps_list})
|
| 565 |
+
|
| 566 |
+
if return_video_k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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from dreamomni2.pipeline_dreamomni2 import DreamOmni2Pipeline
|
| 3 |
+
from diffusers.utils import load_image
|
| 4 |
+
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
|
| 5 |
+
# from qwen_vl_utils import process_vision_info
|
| 6 |
+
from utils.vprocess import process_vision_info, resizeinput
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import gradio as gr
|
| 11 |
+
import uuid
|
| 12 |
+
import argparse
|
| 13 |
+
|
| 14 |
+
def parse_args():
|
| 15 |
+
"""Parses command-line arguments for model paths and server configuration."""
|
| 16 |
+
parser = argparse.ArgumentParser(description="Launch DreamOmni2 Editing Gradio Demo.")
|
| 17 |
+
parser.add_argument(
|
| 18 |
+
"--vlm_path",
|
| 19 |
+
type=str,
|
| 20 |
+
default="vlm-model",
|
| 21 |
+
help="Path to the Qwen2_5_VL VLM model directory."
|
| 22 |
+
)
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"--edit_lora_path",
|
| 25 |
+
type=str,
|
| 26 |
+
default="edit_lora",
|
| 27 |
+
help="Path to the FLUX.1-Kontext editing LoRA weights directory."
|
| 28 |
+
)
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--server_name",
|
| 31 |
+
type=str,
|
| 32 |
+
default="0.0.0.0",
|
| 33 |
+
help="The server name (IP address) to host the Gradio demo."
|
| 34 |
+
)
|
| 35 |
+
parser.add_argument(
|
| 36 |
+
"--server_port",
|
| 37 |
+
type=int,
|
| 38 |
+
default=7860,
|
| 39 |
+
help="The port number to host the Gradio demo."
|
| 40 |
+
)
|
| 41 |
+
args = parser.parse_args()
|
| 42 |
+
return args
|
| 43 |
+
|
| 44 |
+
ARGS = parse_args()
|
| 45 |
+
vlm_path = ARGS.vlm_path
|
| 46 |
+
edit_lora_path = ARGS.edit_lora_path
|
| 47 |
+
server_name = ARGS.server_name
|
| 48 |
+
server_port = ARGS.server_port
|
| 49 |
+
device = "cuda"
|
| 50 |
+
|
| 51 |
+
def extract_gen_content(text):
|
| 52 |
+
text = text[6:-7]
|
| 53 |
+
return text
|
| 54 |
+
|
| 55 |
+
print(f"Loading models from vlm_path: {vlm_path}, edit_lora_path: {edit_lora_path}")
|
| 56 |
+
|
| 57 |
+
pipe = DreamOmni2Pipeline.from_pretrained(
|
| 58 |
+
"black-forest-labs/FLUX.1-Kontext-dev",
|
| 59 |
+
torch_dtype=torch.bfloat16
|
| 60 |
+
)
|
| 61 |
+
pipe.to(device)
|
| 62 |
+
pipe.load_lora_weights(edit_lora_path, adapter_name="edit")
|
| 63 |
+
pipe.set_adapters(["edit"], adapter_weights=[1])
|
| 64 |
+
|
| 65 |
+
vlm_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 66 |
+
vlm_path,
|
| 67 |
+
torch_dtype="bfloat16",
|
| 68 |
+
device_map="cuda"
|
| 69 |
+
)
|
| 70 |
+
processor = AutoProcessor.from_pretrained(vlm_path)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def infer_vlm(input_img_path, input_instruction, prefix):
|
| 74 |
+
if not vlm_model or not processor:
|
| 75 |
+
raise gr.Error("VLM Model not loaded. Cannot process prompt.")
|
| 76 |
+
tp = []
|
| 77 |
+
for path in input_img_path:
|
| 78 |
+
tp.append({"type": "image", "image": path})
|
| 79 |
+
tp.append({"type": "text", "text": input_instruction + prefix})
|
| 80 |
+
messages = [{"role": "user", "content": tp}]
|
| 81 |
+
|
| 82 |
+
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 83 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
| 84 |
+
inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt")
|
| 85 |
+
inputs = inputs.to("cuda")
|
| 86 |
+
|
| 87 |
+
generated_ids = vlm_model.generate(**inputs, do_sample=False, max_new_tokens=4096)
|
| 88 |
+
generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
|
| 89 |
+
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 90 |
+
return output_text[0]
|
| 91 |
+
|
| 92 |
+
PREFERRED_KONTEXT_RESOLUTIONS = [
|
| 93 |
+
(672, 1568),
|
| 94 |
+
(688, 1504),
|
| 95 |
+
(720, 1456),
|
| 96 |
+
(752, 1392),
|
| 97 |
+
(800, 1328),
|
| 98 |
+
(832, 1248),
|
| 99 |
+
(880, 1184),
|
| 100 |
+
(944, 1104),
|
| 101 |
+
(1024, 1024),
|
| 102 |
+
(1104, 944),
|
| 103 |
+
(1184, 880),
|
| 104 |
+
(1248, 832),
|
| 105 |
+
(1328, 800),
|
| 106 |
+
(1392, 752),
|
| 107 |
+
(1456, 720),
|
| 108 |
+
(1504, 688),
|
| 109 |
+
(1568, 672),
|
| 110 |
+
]
|
| 111 |
+
def find_closest_resolution(width, height, preferred_resolutions):
|
| 112 |
+
input_ratio = width / height
|
| 113 |
+
closest_resolution = min(
|
| 114 |
+
preferred_resolutions,
|
| 115 |
+
key=lambda res: abs((res[0] / res[1]) - input_ratio)
|
| 116 |
+
)
|
| 117 |
+
return closest_resolution
|
| 118 |
+
|
| 119 |
+
def perform_edit(input_img_paths, input_instruction, output_path):
|
| 120 |
+
prefix = " It is editing task."
|
| 121 |
+
source_imgs = []
|
| 122 |
+
for path in input_img_paths:
|
| 123 |
+
img = load_image(path)
|
| 124 |
+
# source_imgs.append(img)
|
| 125 |
+
source_imgs.append(resizeinput(img))
|
| 126 |
+
prompt = infer_vlm(input_img_paths, input_instruction, prefix)
|
| 127 |
+
prompt = extract_gen_content(prompt)
|
| 128 |
+
print(f"Generated Prompt for VLM: {prompt}")
|
| 129 |
+
|
| 130 |
+
image = pipe(
|
| 131 |
+
images=source_imgs,
|
| 132 |
+
height=source_imgs[0].height,
|
| 133 |
+
width=source_imgs[0].width,
|
| 134 |
+
prompt=prompt,
|
| 135 |
+
num_inference_steps=30,
|
| 136 |
+
guidance_scale=3.5,
|
| 137 |
+
).images[0]
|
| 138 |
+
image.save(output_path)
|
| 139 |
+
print(f"Edit result saved to {output_path}")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def process_request(image_file_1, image_file_2, instruction):
|
| 143 |
+
# debugpy.listen(5678)
|
| 144 |
+
# print("Waiting for debugger attach...")
|
| 145 |
+
# debugpy.wait_for_client()
|
| 146 |
+
if not image_file_1 or not image_file_2:
|
| 147 |
+
raise gr.Error("Please upload both images.")
|
| 148 |
+
if not instruction:
|
| 149 |
+
raise gr.Error("Please provide an instruction.")
|
| 150 |
+
if not pipe or not vlm_model:
|
| 151 |
+
raise gr.Error("Models not loaded. Check the console for errors.")
|
| 152 |
+
|
| 153 |
+
output_path = f"/tmp/{uuid.uuid4()}.png"
|
| 154 |
+
input_img_paths = [image_file_1, image_file_2] # List of file paths from the two gr.File inputs
|
| 155 |
+
|
| 156 |
+
perform_edit(input_img_paths, instruction, output_path)
|
| 157 |
+
return output_path
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
css = """
|
| 161 |
+
.text-center { text-align: center; }
|
| 162 |
+
.result-img img {
|
| 163 |
+
max-height: 60vh !important;
|
| 164 |
+
min-height: 30vh !important;
|
| 165 |
+
width: auto !important;
|
| 166 |
+
object-fit: contain;
|
| 167 |
+
}
|
| 168 |
+
.input-img img {
|
| 169 |
+
max-height: 30vh !important;
|
| 170 |
+
width: auto !important;
|
| 171 |
+
object-fit: contain;
|
| 172 |
+
}
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="DreamOmni2", css=css) as demo:
|
| 177 |
+
gr.HTML(
|
| 178 |
+
"""
|
| 179 |
+
<h1 style="text-align:center; font-size:48px; font-weight:bold; margin-bottom:20px;">
|
| 180 |
+
DreamOmni2: Omni-purpose Image Generation and Editing
|
| 181 |
+
</h1>
|
| 182 |
+
"""
|
| 183 |
+
)
|
| 184 |
+
gr.Markdown(
|
| 185 |
+
"Select a mode, upload two images, provide an instruction, and click 'Run'.",
|
| 186 |
+
elem_classes="text-center"
|
| 187 |
+
)
|
| 188 |
+
with gr.Row():
|
| 189 |
+
with gr.Column(scale=2):
|
| 190 |
+
gr.Markdown("⬆️ Upload images. Click or drag to upload.")
|
| 191 |
+
|
| 192 |
+
with gr.Row():
|
| 193 |
+
image_uploader_1 = gr.Image(
|
| 194 |
+
label="Img 1",
|
| 195 |
+
type="filepath",
|
| 196 |
+
interactive=True,
|
| 197 |
+
elem_classes="input-img",
|
| 198 |
+
)
|
| 199 |
+
image_uploader_2 = gr.Image(
|
| 200 |
+
label="Img 2",
|
| 201 |
+
type="filepath",
|
| 202 |
+
interactive=True,
|
| 203 |
+
elem_classes="input-img",
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
instruction_text = gr.Textbox(
|
| 207 |
+
label="Instruction",
|
| 208 |
+
lines=2,
|
| 209 |
+
placeholder="Input your instruction for generation or editing here...",
|
| 210 |
+
)
|
| 211 |
+
run_button = gr.Button("Run", variant="primary")
|
| 212 |
+
|
| 213 |
+
with gr.Column(scale=2):
|
| 214 |
+
gr.Markdown(
|
| 215 |
+
"✏️ **Editing Mode**: Modify an existing image using instructions and references.\n\n"
|
| 216 |
+
"Tip: If the result is not what you expect, try clicking **Run** again. "
|
| 217 |
+
)
|
| 218 |
+
output_image = gr.Image(
|
| 219 |
+
label="Result",
|
| 220 |
+
type="filepath",
|
| 221 |
+
elem_classes="result-img",
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
# --- Examples (不变) ---
|
| 225 |
+
gr.Markdown("## Examples")
|
| 226 |
+
|
| 227 |
+
gr.Examples(
|
| 228 |
+
label="Editing Examples",
|
| 229 |
+
examples=[
|
| 230 |
+
["example_input/edit_tests/4/ref_0.jpg", "example_input/edit_tests/4/ref_1.jpg", "Replace the first image have the same image style as the second image.","example_input/edit_tests/4/res.jpg"],
|
| 231 |
+
["example_input/edit_tests/5/ref_0.jpg", "example_input/edit_tests/5/ref_1.jpg", "Make the person in the first image have the same hairstyle as the person in the second image.","example_input/edit_tests/5/res.jpg"],
|
| 232 |
+
["example_input/edit_tests/src.jpg", "example_input/edit_tests/ref.jpg", "Make the woman from the second image stand on the road in the first image.","example_input/edit_tests/edi_res.png"],
|
| 233 |
+
["example_input/edit_tests/1/ref_0.jpg", "example_input/edit_tests/1/ref_1.jpg", "Replace the lantern in the first image with the dog in the second image.","example_input/edit_tests/1/res.jpg"],
|
| 234 |
+
["example_input/edit_tests/2/ref_0.jpg", "example_input/edit_tests/2/ref_1.jpg", "Replace the suit in the first image with the clothes in the second image.","example_input/edit_tests/2/res.jpg"],
|
| 235 |
+
["example_input/edit_tests/3/ref_0.jpg", "example_input/edit_tests/3/ref_1.jpg", "Make the first image has the same light condition as the second image.","example_input/edit_tests/3/res.jpg"],
|
| 236 |
+
["example_input/edit_tests/6/ref_0.jpg", "example_input/edit_tests/6/ref_1.jpg", "Make the words in the first image have the same font as the words in the second image.","example_input/edit_tests/6/res.jpg"],
|
| 237 |
+
["example_input/edit_tests/7/ref_0.jpg", "example_input/edit_tests/7/ref_1.jpg", "Make the car in the first image have the same pattern as the mouse in the second image.","example_input/edit_tests/7/res.jpg"],
|
| 238 |
+
["example_input/edit_tests/8/ref_0.jpg", "example_input/edit_tests/8/ref_1.jpg", "Make the dress in the first image have the same pattern in the second image.","example_input/edit_tests/8/res.jpg"],
|
| 239 |
+
],
|
| 240 |
+
inputs=[image_uploader_1, image_uploader_2, instruction_text, output_image],
|
| 241 |
+
cache_examples=False,
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
run_button.click(
|
| 245 |
+
fn=process_request,
|
| 246 |
+
inputs=[image_uploader_1, image_uploader_2, instruction_text],
|
| 247 |
+
outputs=output_image
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
if __name__ == "__main__":
|
| 251 |
+
print("Launching Gradio Demo...")
|
| 252 |
+
demo.launch(server_name=server_name, server_port=server_port)
|
web_generate.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from dreamomni2.pipeline_dreamomni2 import DreamOmni2Pipeline
|
| 3 |
+
from diffusers.utils import load_image
|
| 4 |
+
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
|
| 5 |
+
# from qwen_vl_utils import process_vision_info
|
| 6 |
+
from utils.vprocess import process_vision_info, resizeinput
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import gradio as gr
|
| 11 |
+
import uuid
|
| 12 |
+
import argparse
|
| 13 |
+
|
| 14 |
+
def parse_args():
|
| 15 |
+
"""Parses command-line arguments for model paths and server configuration."""
|
| 16 |
+
parser = argparse.ArgumentParser(description="Launch DreamOmni2 Editing Gradio Demo.")
|
| 17 |
+
parser.add_argument(
|
| 18 |
+
"--vlm_path",
|
| 19 |
+
type=str,
|
| 20 |
+
default="vlm-model",
|
| 21 |
+
help="Path to the Qwen2_5_VL VLM model directory."
|
| 22 |
+
)
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"--gen_lora_path",
|
| 25 |
+
type=str,
|
| 26 |
+
default="gen_lora",
|
| 27 |
+
help="Path to the FLUX.1-Kontext generation LoRA weights directory."
|
| 28 |
+
)
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--server_name",
|
| 31 |
+
type=str,
|
| 32 |
+
default="0.0.0.0",
|
| 33 |
+
help="The server name (IP address) to host the Gradio demo."
|
| 34 |
+
)
|
| 35 |
+
parser.add_argument(
|
| 36 |
+
"--server_port",
|
| 37 |
+
type=int,
|
| 38 |
+
default=7860,
|
| 39 |
+
help="The port number to host the Gradio demo."
|
| 40 |
+
)
|
| 41 |
+
args = parser.parse_args()
|
| 42 |
+
return args
|
| 43 |
+
|
| 44 |
+
ARGS = parse_args()
|
| 45 |
+
vlm_path = ARGS.vlm_path
|
| 46 |
+
gen_lora_path = ARGS.gen_lora_path
|
| 47 |
+
server_name = ARGS.server_name
|
| 48 |
+
server_port = ARGS.server_port
|
| 49 |
+
device = "cuda"
|
| 50 |
+
|
| 51 |
+
def extract_gen_content(text):
|
| 52 |
+
text = text[6:-7]
|
| 53 |
+
return text
|
| 54 |
+
|
| 55 |
+
print(f"Loading models from vlm_path: {vlm_path}, gen_lora_path: {gen_lora_path}")
|
| 56 |
+
|
| 57 |
+
pipe = DreamOmni2Pipeline.from_pretrained(
|
| 58 |
+
"black-forest-labs/FLUX.1-Kontext-dev",
|
| 59 |
+
torch_dtype=torch.bfloat16
|
| 60 |
+
)
|
| 61 |
+
pipe.to(device)
|
| 62 |
+
pipe.load_lora_weights(gen_lora_path, adapter_name="generation")
|
| 63 |
+
pipe.set_adapters(["generation"], adapter_weights=[1])
|
| 64 |
+
|
| 65 |
+
vlm_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 66 |
+
vlm_path,
|
| 67 |
+
torch_dtype="bfloat16",
|
| 68 |
+
device_map="cuda"
|
| 69 |
+
)
|
| 70 |
+
processor = AutoProcessor.from_pretrained(vlm_path)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def infer_vlm(input_img_path, input_instruction, prefix):
|
| 74 |
+
if not vlm_model or not processor:
|
| 75 |
+
raise gr.Error("VLM Model not loaded. Cannot process prompt.")
|
| 76 |
+
tp = []
|
| 77 |
+
for path in input_img_path:
|
| 78 |
+
tp.append({"type": "image", "image": path})
|
| 79 |
+
tp.append({"type": "text", "text": input_instruction + prefix})
|
| 80 |
+
messages = [{"role": "user", "content": tp}]
|
| 81 |
+
|
| 82 |
+
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 83 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
| 84 |
+
inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt")
|
| 85 |
+
inputs = inputs.to("cuda")
|
| 86 |
+
|
| 87 |
+
generated_ids = vlm_model.generate(**inputs, do_sample=False, max_new_tokens=4096)
|
| 88 |
+
generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
|
| 89 |
+
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 90 |
+
return output_text[0]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
PREFERRED_KONTEXT_RESOLUTIONS = [
|
| 94 |
+
(672, 1568),
|
| 95 |
+
(688, 1504),
|
| 96 |
+
(720, 1456),
|
| 97 |
+
(752, 1392),
|
| 98 |
+
(800, 1328),
|
| 99 |
+
(832, 1248),
|
| 100 |
+
(880, 1184),
|
| 101 |
+
(944, 1104),
|
| 102 |
+
(1024, 1024),
|
| 103 |
+
(1104, 944),
|
| 104 |
+
(1184, 880),
|
| 105 |
+
(1248, 832),
|
| 106 |
+
(1328, 800),
|
| 107 |
+
(1392, 752),
|
| 108 |
+
(1456, 720),
|
| 109 |
+
(1504, 688),
|
| 110 |
+
(1568, 672),
|
| 111 |
+
]
|
| 112 |
+
def find_closest_resolution(width, height, preferred_resolutions):
|
| 113 |
+
input_ratio = width / height
|
| 114 |
+
closest_resolution = min(
|
| 115 |
+
preferred_resolutions,
|
| 116 |
+
key=lambda res: abs((res[0] / res[1]) - input_ratio)
|
| 117 |
+
)
|
| 118 |
+
return closest_resolution
|
| 119 |
+
|
| 120 |
+
def perform_generation(input_img_paths, input_instruction, output_path, height=1024, width=1024):
|
| 121 |
+
prefix = " It is generation task."
|
| 122 |
+
source_imgs = []
|
| 123 |
+
for path in input_img_paths:
|
| 124 |
+
img = load_image(path)
|
| 125 |
+
# source_imgs.append(img)
|
| 126 |
+
source_imgs.append(resizeinput(img))
|
| 127 |
+
prompt = infer_vlm(input_img_paths, input_instruction, prefix)
|
| 128 |
+
prompt = extract_gen_content(prompt)
|
| 129 |
+
print(f"Generated Prompt for VLM: {prompt}")
|
| 130 |
+
|
| 131 |
+
image = pipe(
|
| 132 |
+
images=source_imgs,
|
| 133 |
+
height=height,
|
| 134 |
+
width=width,
|
| 135 |
+
prompt=prompt,
|
| 136 |
+
num_inference_steps=30,
|
| 137 |
+
guidance_scale=3.5,
|
| 138 |
+
).images[0]
|
| 139 |
+
|
| 140 |
+
image.save(output_path)
|
| 141 |
+
print(f"Generation result saved to {output_path}")
|
| 142 |
+
|
| 143 |
+
# --- Gradio Interface Logic ---
|
| 144 |
+
|
| 145 |
+
def process_request(image_file_1, image_file_2, instruction):
|
| 146 |
+
# debugpy.listen(5678)
|
| 147 |
+
# print("Waiting for debugger attach...")
|
| 148 |
+
# debugpy.wait_for_client()
|
| 149 |
+
if not image_file_1 or not image_file_2:
|
| 150 |
+
raise gr.Error("Please upload both images.")
|
| 151 |
+
if not instruction:
|
| 152 |
+
raise gr.Error("Please provide an instruction.")
|
| 153 |
+
if not pipe or not vlm_model:
|
| 154 |
+
raise gr.Error("Models not loaded. Check the console for errors.")
|
| 155 |
+
|
| 156 |
+
output_path = f"/tmp/{uuid.uuid4()}.png"
|
| 157 |
+
input_img_paths = [image_file_1, image_file_2] # List of file paths from the two gr.File inputs
|
| 158 |
+
|
| 159 |
+
perform_generation(input_img_paths, instruction, output_path)
|
| 160 |
+
|
| 161 |
+
return output_path
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
css = """
|
| 165 |
+
.text-center { text-align: center; }
|
| 166 |
+
.result-img img {
|
| 167 |
+
max-height: 60vh !important;
|
| 168 |
+
min-height: 30vh !important;
|
| 169 |
+
width: auto !important;
|
| 170 |
+
object-fit: contain;
|
| 171 |
+
}
|
| 172 |
+
.input-img img {
|
| 173 |
+
max-height: 30vh !important;
|
| 174 |
+
width: auto !important;
|
| 175 |
+
object-fit: contain;
|
| 176 |
+
}
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="DreamOmni2", css=css) as demo:
|
| 181 |
+
gr.HTML(
|
| 182 |
+
"""
|
| 183 |
+
<h1 style="text-align:center; font-size:48px; font-weight:bold; margin-bottom:20px;">
|
| 184 |
+
DreamOmni2: Omni-purpose Image Generation and Editing
|
| 185 |
+
</h1>
|
| 186 |
+
"""
|
| 187 |
+
)
|
| 188 |
+
gr.Markdown(
|
| 189 |
+
"Select a mode, upload two images, provide an instruction, and click 'Run'.",
|
| 190 |
+
elem_classes="text-center"
|
| 191 |
+
)
|
| 192 |
+
with gr.Row():
|
| 193 |
+
with gr.Column(scale=2):
|
| 194 |
+
gr.Markdown("⬆️ Upload images. Click or drag to upload.")
|
| 195 |
+
|
| 196 |
+
with gr.Row():
|
| 197 |
+
image_uploader_1 = gr.Image(
|
| 198 |
+
label="Img 1",
|
| 199 |
+
type="filepath",
|
| 200 |
+
interactive=True,
|
| 201 |
+
elem_classes="input-img",
|
| 202 |
+
)
|
| 203 |
+
image_uploader_2 = gr.Image(
|
| 204 |
+
label="Img 2",
|
| 205 |
+
type="filepath",
|
| 206 |
+
interactive=True,
|
| 207 |
+
elem_classes="input-img",
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
instruction_text = gr.Textbox(
|
| 211 |
+
label="Instruction",
|
| 212 |
+
lines=2,
|
| 213 |
+
placeholder="Input your instruction for generation or editing here...",
|
| 214 |
+
)
|
| 215 |
+
run_button = gr.Button("Run", variant="primary")
|
| 216 |
+
|
| 217 |
+
with gr.Column(scale=2):
|
| 218 |
+
gr.Markdown("🖼️ **Generation Mode**: Create new scenes from reference images."
|
| 219 |
+
"Tip: If the result is not what you expect, try clicking **Run** again. ")
|
| 220 |
+
output_image = gr.Image(
|
| 221 |
+
label="Result",
|
| 222 |
+
type="filepath",
|
| 223 |
+
elem_classes="result-img",
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# --- Examples ---
|
| 227 |
+
gr.Markdown("## Examples")
|
| 228 |
+
gr.Examples(
|
| 229 |
+
label="Generation Examples",
|
| 230 |
+
examples=[
|
| 231 |
+
[
|
| 232 |
+
"example_input/gen_tests/img1.jpg",
|
| 233 |
+
"example_input/gen_tests/img2.jpg",
|
| 234 |
+
"In the scene, the character from the first image stands on the left, and the character from the second image stands on the right. They are shaking hands against the backdrop of a spaceship interior.",
|
| 235 |
+
"example_input/gen_tests/gen_res.png"
|
| 236 |
+
]
|
| 237 |
+
],
|
| 238 |
+
inputs=[image_uploader_1, image_uploader_2, instruction_text, output_image],
|
| 239 |
+
cache_examples=False,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
run_button.click(
|
| 243 |
+
fn=process_request,
|
| 244 |
+
inputs=[image_uploader_1, image_uploader_2, instruction_text],
|
| 245 |
+
outputs=output_image
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
if __name__ == "__main__":
|
| 249 |
+
|
| 250 |
+
print("Launching Gradio Demo...")
|
| 251 |
+
demo.launch(server_name="0.0.0.0", server_port=7861, )
|